061f482951fae66133c601892f99319df02c3d66
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22 import java.io.IOException;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AuthenticatorException;
27 import android.accounts.OperationCanceledException;
28 import android.app.AlertDialog;
29 import android.app.Dialog;
30 import android.app.ProgressDialog;
31 import android.content.BroadcastReceiver;
32 import android.content.ComponentName;
33 import android.content.ContentResolver;
34 import android.content.Context;
35 import android.content.DialogInterface;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.ServiceConnection;
39 import android.content.SharedPreferences;
40 import android.content.SyncRequest;
41 import android.content.res.Resources.NotFoundException;
42 import android.database.Cursor;
43 import android.net.Uri;
44 import android.os.Bundle;
45 import android.os.IBinder;
46 import android.preference.PreferenceManager;
47 import android.provider.MediaStore;
48 import android.support.v4.app.Fragment;
49 import android.support.v4.app.FragmentManager;
50 import android.support.v4.app.FragmentTransaction;
51 //import android.support.v4.content.LocalBroadcastManager;
52 import android.util.Log;
53 import android.view.View;
54 import android.view.ViewGroup;
55 import android.widget.ArrayAdapter;
56 import android.widget.TextView;
57 import android.widget.Toast;
58
59 import com.actionbarsherlock.app.ActionBar;
60 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
61 import com.actionbarsherlock.view.Menu;
62 import com.actionbarsherlock.view.MenuInflater;
63 import com.actionbarsherlock.view.MenuItem;
64 import com.actionbarsherlock.view.Window;
65 import com.owncloud.android.MainApp;
66 import com.owncloud.android.R;
67 import com.owncloud.android.datamodel.OCFile;
68 import com.owncloud.android.files.services.FileDownloader;
69 import com.owncloud.android.files.services.FileObserverService;
70 import com.owncloud.android.files.services.FileUploader;
71 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
72 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
73 import com.owncloud.android.operations.CreateFolderOperation;
74
75 import com.owncloud.android.lib.common.OwnCloudClient;
76 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
77 import com.owncloud.android.lib.common.OwnCloudCredentials;
78 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
79 import com.owncloud.android.lib.common.network.CertificateCombinedException;
80 import com.owncloud.android.lib.common.operations.RemoteOperation;
81 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
82 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
83 import com.owncloud.android.operations.CreateShareOperation;
84 import com.owncloud.android.operations.RemoveFileOperation;
85 import com.owncloud.android.operations.RenameFileOperation;
86 import com.owncloud.android.operations.SynchronizeFileOperation;
87 import com.owncloud.android.operations.SynchronizeFolderOperation;
88 import com.owncloud.android.operations.UnshareLinkOperation;
89 import com.owncloud.android.syncadapter.FileSyncAdapter;
90 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
91 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
92 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
93 import com.owncloud.android.ui.fragment.FileDetailFragment;
94 import com.owncloud.android.ui.fragment.FileFragment;
95 import com.owncloud.android.ui.fragment.OCFileListFragment;
96 import com.owncloud.android.ui.preview.PreviewImageActivity;
97 import com.owncloud.android.ui.preview.PreviewImageFragment;
98 import com.owncloud.android.ui.preview.PreviewMediaFragment;
99 import com.owncloud.android.ui.preview.PreviewVideoActivity;
100 import com.owncloud.android.utils.DisplayUtils;
101 import com.owncloud.android.utils.ErrorMessageAdapter;
102 import com.owncloud.android.utils.Log_OC;
103
104
105 /**
106 * Displays, what files the user has available in his ownCloud.
107 *
108 * @author Bartek Przybylski
109 * @author David A. Velasco
110 */
111
112 public class FileDisplayActivity extends HookActivity implements
113 FileFragment.ContainerActivity, OnNavigationListener, OnSslUntrustedCertListener {
114
115 private ArrayAdapter<String> mDirectories;
116
117 private SyncBroadcastReceiver mSyncBroadcastReceiver;
118 private UploadFinishReceiver mUploadFinishReceiver;
119 private DownloadFinishReceiver mDownloadFinishReceiver;
120 private RemoteOperationResult mLastSslUntrustedServerResult = null;
121
122 private boolean mDualPane;
123 private View mLeftFragmentContainer;
124 private View mRightFragmentContainer;
125
126 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
127 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
128 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
129
130 public static final int DIALOG_SHORT_WAIT = 0;
131 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
132 private static final int DIALOG_CERT_NOT_SAVED = 2;
133
134 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
135
136 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
137 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
138
139 private static final String TAG = FileDisplayActivity.class.getSimpleName();
140
141 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
142 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
143
144 private OCFile mWaitingToPreview;
145
146 private boolean mSyncInProgress = false;
147
148 private String DIALOG_UNTRUSTED_CERT;
149
150 private OCFile mWaitingToSend;
151
152 @Override
153 protected void onCreate(Bundle savedInstanceState) {
154 Log_OC.d(TAG, "onCreate() start");
155 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
156
157 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
158
159 // PIN CODE request ; best location is to decide, let's try this first
160 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
161 requestPinCode();
162 } else if (getIntent().getAction() == null && savedInstanceState == null) {
163 requestPinCode();
164 }
165
166 /// file observer
167 Intent observer_intent = new Intent(this, FileObserverService.class);
168 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
169 startService(observer_intent);
170
171 /// Load of saved instance state
172 if(savedInstanceState != null) {
173 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
174 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
175 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
176
177 } else {
178 mWaitingToPreview = null;
179 mSyncInProgress = false;
180 mWaitingToSend = null;
181 }
182
183 /// USER INTERFACE
184
185 // Inflate and set the layout view
186 setContentView(R.layout.files);
187 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
188 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
189 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
190 if (savedInstanceState == null) {
191 createMinFragments();
192 }
193
194 // Action bar setup
195 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
196 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
197 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
198
199 Log_OC.d(TAG, "onCreate() end");
200 }
201
202 @Override
203 protected void onStart() {
204 super.onStart();
205 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
206 }
207
208 @Override
209 protected void onDestroy() {
210 super.onDestroy();
211 }
212
213 /**
214 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
215 */
216 @Override
217 protected void onAccountSet(boolean stateWasRecovered) {
218 super.onAccountSet(stateWasRecovered);
219 if (getAccount() != null) {
220 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
221 OCFile file = getFile();
222 // get parent from path
223 String parentPath = "";
224 if (file != null) {
225 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
226 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
227 // get parent from path
228 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
229 if (getStorageManager().getFileByPath(parentPath) == null)
230 file = null; // not able to know the directory where the file is uploading
231 } else {
232 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
233 }
234 }
235 if (file == null) {
236 // fall back to root folder
237 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
238 }
239 setFile(file);
240 setNavigationListWithFolder(file);
241
242 if (!stateWasRecovered) {
243 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
244 initFragmentsWithFile();
245 if (file.isFolder()) {
246 startSyncFolderOperation(file);
247 }
248
249 } else {
250 updateFragmentsVisibility(!file.isFolder());
251 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
252 }
253 }
254 }
255
256
257 private void setNavigationListWithFolder(OCFile file) {
258 mDirectories.clear();
259 OCFile fileIt = file;
260 String parentPath;
261 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
262 if (fileIt.isFolder()) {
263 mDirectories.add(fileIt.getFileName());
264 }
265 // get parent from path
266 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
267 fileIt = getStorageManager().getFileByPath(parentPath);
268 }
269 mDirectories.add(OCFile.PATH_SEPARATOR);
270 }
271
272
273 private void createMinFragments() {
274 OCFileListFragment listOfFiles = new OCFileListFragment();
275 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
276 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
277 transaction.commit();
278 }
279
280 private void initFragmentsWithFile() {
281 if (getAccount() != null && getFile() != null) {
282 /// First fragment
283 OCFileListFragment listOfFiles = getListOfFilesFragment();
284 if (listOfFiles != null) {
285 listOfFiles.listDirectory(getCurrentDir());
286 } else {
287 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
288 }
289
290 /// Second fragment
291 OCFile file = getFile();
292 Fragment secondFragment = chooseInitialSecondFragment(file);
293 if (secondFragment != null) {
294 setSecondFragment(secondFragment);
295 updateFragmentsVisibility(true);
296 updateNavigationElementsInActionBar(file);
297
298 } else {
299 cleanSecondFragment();
300 }
301
302 } else {
303 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
304 if (getAccount() == null) {
305 Log.wtf(TAG, "\t account is NULL");
306 }
307 if (getFile() == null) {
308 Log.wtf(TAG, "\t file is NULL");
309 }
310 }
311 }
312
313 private Fragment chooseInitialSecondFragment(OCFile file) {
314 Fragment secondFragment = null;
315 if (file != null && !file.isFolder()) {
316 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
317 && file.getLastSyncDateForProperties() > 0 // temporal fix
318 ) {
319 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
320 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
321 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
322
323 } else {
324 secondFragment = new FileDetailFragment(file, getAccount());
325 }
326 }
327 return secondFragment;
328 }
329
330
331 /**
332 * Replaces the second fragment managed by the activity with the received as
333 * a parameter.
334 *
335 * Assumes never will be more than two fragments managed at the same time.
336 *
337 * @param fragment New second Fragment to set.
338 */
339 private void setSecondFragment(Fragment fragment) {
340 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
341 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
342 transaction.commit();
343 }
344
345
346 private void updateFragmentsVisibility(boolean existsSecondFragment) {
347 if (mDualPane) {
348 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
349 mLeftFragmentContainer.setVisibility(View.VISIBLE);
350 }
351 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
352 mRightFragmentContainer.setVisibility(View.VISIBLE);
353 }
354
355 } else if (existsSecondFragment) {
356 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
357 mLeftFragmentContainer.setVisibility(View.GONE);
358 }
359 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
360 mRightFragmentContainer.setVisibility(View.VISIBLE);
361 }
362
363 } else {
364 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
365 mLeftFragmentContainer.setVisibility(View.VISIBLE);
366 }
367 if (mRightFragmentContainer.getVisibility() != View.GONE) {
368 mRightFragmentContainer.setVisibility(View.GONE);
369 }
370 }
371 }
372
373
374 private OCFileListFragment getListOfFilesFragment() {
375 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
376 if (listOfFiles != null) {
377 return (OCFileListFragment)listOfFiles;
378 }
379 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
380 return null;
381 }
382
383 public FileFragment getSecondFragment() {
384 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
385 if (second != null) {
386 return (FileFragment)second;
387 }
388 return null;
389 }
390
391 protected void cleanSecondFragment() {
392 Fragment second = getSecondFragment();
393 if (second != null) {
394 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
395 tr.remove(second);
396 tr.commit();
397 }
398 updateFragmentsVisibility(false);
399 updateNavigationElementsInActionBar(null);
400 }
401
402 protected void refreshListOfFilesFragment() {
403 OCFileListFragment fileListFragment = getListOfFilesFragment();
404 if (fileListFragment != null) {
405 fileListFragment.listDirectory();
406 }
407 }
408
409 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
410 FileFragment secondFragment = getSecondFragment();
411 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
412 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
413 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
414 OCFile fileInFragment = detailsFragment.getFile();
415 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
416 // the user browsed to other file ; forget the automatic preview
417 mWaitingToPreview = null;
418
419 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
420 // grant that the right panel updates the progress bar
421 detailsFragment.listenForTransferProgress();
422 detailsFragment.updateFileDetails(true, false);
423
424 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
425 // update the right panel
426 boolean detailsFragmentChanged = false;
427 if (waitedPreview) {
428 if (success) {
429 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
430 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
431 startMediaPreview(mWaitingToPreview, 0, true);
432 detailsFragmentChanged = true;
433 } else {
434 getFileOperationsHelper().openFile(mWaitingToPreview);
435 }
436 }
437 mWaitingToPreview = null;
438 }
439 if (!detailsFragmentChanged) {
440 detailsFragment.updateFileDetails(false, (success));
441 }
442 }
443 }
444 }
445
446 @Override
447 public boolean onCreateOptionsMenu(Menu menu) {
448 MenuInflater inflater = getSherlock().getMenuInflater();
449 inflater.inflate(R.menu.main_menu, menu);
450 return true;
451 }
452
453 @Override
454 public boolean onOptionsItemSelected(MenuItem item) {
455 boolean retval = true;
456 switch (item.getItemId()) {
457 case R.id.action_create_dir: {
458 CreateFolderDialogFragment dialog =
459 CreateFolderDialogFragment.newInstance(getCurrentDir());
460 dialog.show(getSupportFragmentManager(), "createdirdialog");
461 break;
462 }
463 case R.id.action_sync_account: {
464 startSynchronization();
465 break;
466 }
467 case R.id.action_upload: {
468 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
469 break;
470 }
471 case R.id.action_settings: {
472 Intent settingsIntent = new Intent(this, Preferences.class);
473 startActivity(settingsIntent);
474 break;
475 }
476 case android.R.id.home: {
477 FileFragment second = getSecondFragment();
478 OCFile currentDir = getCurrentDir();
479 if((currentDir != null && currentDir.getParentId() != 0) ||
480 (second != null && second.getFile() != null)) {
481 onBackPressed();
482
483 }
484 break;
485 }
486 default:
487 retval = super.onOptionsItemSelected(item);
488 }
489 return retval;
490 }
491
492 private void startSynchronization() {
493 Log_OC.e(TAG, "Got to start sync");
494 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
495 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
496 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
497 Bundle bundle = new Bundle();
498 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
499 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
500 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
501 ContentResolver.requestSync(
502 getAccount(),
503 MainApp.getAuthority(), bundle);
504 } else {
505 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
506 SyncRequest.Builder builder = new SyncRequest.Builder();
507 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
508 builder.setExpedited(true);
509 builder.setManual(true);
510 builder.syncOnce();
511 SyncRequest request = builder.build();
512 ContentResolver.requestSync(request);
513 }
514 }
515
516
517 @Override
518 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
519 if (itemPosition != 0) {
520 String targetPath = "";
521 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
522 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
523 }
524 targetPath = OCFile.PATH_SEPARATOR + targetPath;
525 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
526 if (targetFolder != null) {
527 browseTo(targetFolder);
528 }
529
530 // the next operation triggers a new call to this method, but it's necessary to
531 // ensure that the name exposed in the action bar is the current directory when the
532 // user selected it in the navigation list
533 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
534 getSupportActionBar().setSelectedNavigationItem(0);
535 }
536 return true;
537 }
538
539 /**
540 * Called, when the user selected something for uploading
541 */
542 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
543 super.onActivityResult(requestCode, resultCode, data);
544
545 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
546 requestSimpleUpload(data, resultCode);
547
548 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
549 requestMultipleUpload(data, resultCode);
550
551 }
552 }
553
554 private void requestMultipleUpload(Intent data, int resultCode) {
555 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
556 if (filePaths != null) {
557 String[] remotePaths = new String[filePaths.length];
558 String remotePathBase = "";
559 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
560 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
561 }
562 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
563 remotePathBase += OCFile.PATH_SEPARATOR;
564 for (int j = 0; j< remotePaths.length; j++) {
565 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
566 }
567
568 Intent i = new Intent(this, FileUploader.class);
569 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
570 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
571 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
572 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
573 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
574 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
575 startService(i);
576
577 } else {
578 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
579 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
580 t.show();
581 return;
582 }
583 }
584
585
586 private void requestSimpleUpload(Intent data, int resultCode) {
587 String filepath = null;
588 try {
589 Uri selectedImageUri = data.getData();
590
591 String filemanagerstring = selectedImageUri.getPath();
592 String selectedImagePath = getPath(selectedImageUri);
593
594 if (selectedImagePath != null)
595 filepath = selectedImagePath;
596 else
597 filepath = filemanagerstring;
598
599 } catch (Exception e) {
600 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
601 e.printStackTrace();
602
603 } finally {
604 if (filepath == null) {
605 Log_OC.e(TAG, "Couldnt resolve path to file");
606 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
607 t.show();
608 return;
609 }
610 }
611
612 Intent i = new Intent(this, FileUploader.class);
613 i.putExtra(FileUploader.KEY_ACCOUNT,
614 getAccount());
615 String remotepath = new String();
616 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
617 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
618 }
619 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
620 remotepath += OCFile.PATH_SEPARATOR;
621 remotepath += new File(filepath).getName();
622
623 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
624 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
625 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
626 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
627 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
628 startService(i);
629 }
630
631 @Override
632 public void onBackPressed() {
633 OCFileListFragment listOfFiles = getListOfFilesFragment();
634 if (mDualPane || getSecondFragment() == null) {
635 if (listOfFiles != null) { // should never be null, indeed
636 if (mDirectories.getCount() <= 1) {
637 finish();
638 return;
639 }
640 int levelsUp = listOfFiles.onBrowseUp();
641 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
642 popDirname();
643 }
644 }
645 }
646 if (listOfFiles != null) { // should never be null, indeed
647 setFile(listOfFiles.getCurrentFile());
648 }
649 cleanSecondFragment();
650
651 }
652
653 @Override
654 protected void onSaveInstanceState(Bundle outState) {
655 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
656 Log_OC.e(TAG, "onSaveInstanceState() start");
657 super.onSaveInstanceState(outState);
658 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
659 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
660 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
661 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
662
663 Log_OC.d(TAG, "onSaveInstanceState() end");
664 }
665
666
667
668 @Override
669 protected void onResume() {
670 super.onResume();
671 Log_OC.e(TAG, "onResume() start");
672
673 // refresh list of files
674 refreshListOfFilesFragment();
675
676 // Listen for sync messages
677 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
678 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
679 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
680 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
681 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
682 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
683 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
684 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
685
686 // Listen for upload messages
687 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
688 mUploadFinishReceiver = new UploadFinishReceiver();
689 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
690
691 // Listen for download messages
692 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
693 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
694 mDownloadFinishReceiver = new DownloadFinishReceiver();
695 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
696
697 Log_OC.d(TAG, "onResume() end");
698 }
699
700
701 @Override
702 protected void onPause() {
703 Log_OC.e(TAG, "onPause() start");
704 if (mSyncBroadcastReceiver != null) {
705 unregisterReceiver(mSyncBroadcastReceiver);
706 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
707 mSyncBroadcastReceiver = null;
708 }
709 if (mUploadFinishReceiver != null) {
710 unregisterReceiver(mUploadFinishReceiver);
711 mUploadFinishReceiver = null;
712 }
713 if (mDownloadFinishReceiver != null) {
714 unregisterReceiver(mDownloadFinishReceiver);
715 mDownloadFinishReceiver = null;
716 }
717
718
719 Log_OC.d(TAG, "onPause() end");
720 super.onPause();
721 }
722
723
724 @Override
725 protected Dialog onCreateDialog(int id) {
726 Dialog dialog = null;
727 AlertDialog.Builder builder;
728 switch (id) {
729 case DIALOG_SHORT_WAIT: {
730 ProgressDialog working_dialog = new ProgressDialog(this);
731 working_dialog.setMessage(getResources().getString(
732 R.string.wait_a_moment));
733 working_dialog.setIndeterminate(true);
734 working_dialog.setCancelable(false);
735 dialog = working_dialog;
736 break;
737 }
738 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
739
740 String[] items = null;
741
742 String[] allTheItems = { getString(R.string.actionbar_upload_files),
743 getString(R.string.actionbar_upload_from_apps),
744 getString(R.string.actionbar_failed_instant_upload) };
745
746 String[] commonItems = { getString(R.string.actionbar_upload_files),
747 getString(R.string.actionbar_upload_from_apps) };
748
749 if (InstantUploadActivity.IS_ENABLED)
750 items = allTheItems;
751 else
752 items = commonItems;
753
754 builder = new AlertDialog.Builder(this);
755 builder.setTitle(R.string.actionbar_upload);
756 builder.setItems(items, new DialogInterface.OnClickListener() {
757 public void onClick(DialogInterface dialog, int item) {
758 if (item == 0) {
759 // if (!mDualPane) {
760 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
761 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
762 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
763 // } else {
764 // TODO create and handle new fragment
765 // LocalFileListFragment
766 // }
767 } else if (item == 1) {
768 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
769 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
770 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
771 ACTION_SELECT_CONTENT_FROM_APPS);
772 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
773 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
774 action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
775 startActivity(action);
776 }
777 }
778 });
779 dialog = builder.create();
780 break;
781 }
782 case DIALOG_CERT_NOT_SAVED: {
783 builder = new AlertDialog.Builder(this);
784 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
785 builder.setCancelable(false);
786 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
787 @Override
788 public void onClick(DialogInterface dialog, int which) {
789 dialog.dismiss();
790 };
791 });
792 dialog = builder.create();
793 break;
794 }
795 default:
796 dialog = null;
797 }
798
799 return dialog;
800 }
801
802
803 /**
804 * Translates a content URI of an image to a physical path
805 * on the disk
806 * @param uri The URI to resolve
807 * @return The path to the image or null if it could not be found
808 */
809 public String getPath(Uri uri) {
810 String[] projection = { MediaStore.Images.Media.DATA };
811 Cursor cursor = managedQuery(uri, projection, null, null, null);
812 if (cursor != null) {
813 int column_index = cursor
814 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
815 cursor.moveToFirst();
816 return cursor.getString(column_index);
817 }
818 return null;
819 }
820
821 /**
822 * Pushes a directory to the drop down list
823 * @param directory to push
824 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
825 */
826 public void pushDirname(OCFile directory) {
827 if(!directory.isFolder()){
828 throw new IllegalArgumentException("Only directories may be pushed!");
829 }
830 mDirectories.insert(directory.getFileName(), 0);
831 setFile(directory);
832 }
833
834 /**
835 * Pops a directory name from the drop down list
836 * @return True, unless the stack is empty
837 */
838 public boolean popDirname() {
839 mDirectories.remove(mDirectories.getItem(0));
840 return !mDirectories.isEmpty();
841 }
842
843 // Custom array adapter to override text colors
844 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
845
846 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
847 super(ctx, view);
848 }
849
850 public View getView(int position, View convertView, ViewGroup parent) {
851 View v = super.getView(position, convertView, parent);
852
853 ((TextView) v).setTextColor(getResources().getColorStateList(
854 android.R.color.white));
855
856 fixRoot((TextView) v );
857 return v;
858 }
859
860 public View getDropDownView(int position, View convertView,
861 ViewGroup parent) {
862 View v = super.getDropDownView(position, convertView, parent);
863
864 ((TextView) v).setTextColor(getResources().getColorStateList(
865 android.R.color.white));
866
867 fixRoot((TextView) v );
868 return v;
869 }
870
871 private void fixRoot(TextView v) {
872 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
873 v.setText(R.string.default_display_name_for_root_folder);
874 }
875 }
876
877 }
878
879 private class SyncBroadcastReceiver extends BroadcastReceiver {
880
881 /**
882 * {@link BroadcastReceiver} to enable syncing feedback in UI
883 */
884 @Override
885 public void onReceive(Context context, Intent intent) {
886 try {
887 String event = intent.getAction();
888 Log_OC.d(TAG, "Received broadcast " + event);
889 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
890 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
891 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
892 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
893
894 if (sameAccount) {
895
896 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
897 mSyncInProgress = true;
898
899 } else {
900 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
901 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
902
903 if (currentDir == null) {
904 // current folder was removed from the server
905 Toast.makeText( FileDisplayActivity.this,
906 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
907 Toast.LENGTH_LONG)
908 .show();
909 browseToRoot();
910
911 } else {
912 if (currentFile == null && !getFile().isFolder()) {
913 // currently selected file was removed in the server, and now we know it
914 cleanSecondFragment();
915 currentFile = currentDir;
916 }
917
918 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
919 OCFileListFragment fileListFragment = getListOfFilesFragment();
920 if (fileListFragment != null) {
921 fileListFragment.listDirectory(currentDir);
922 }
923 }
924 setFile(currentFile);
925 }
926
927 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
928
929 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
930 equals(event) &&
931 /// TODO refactor and make common
932 synchResult != null && !synchResult.isSuccess() &&
933 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
934 synchResult.isIdPRedirection() ||
935 (synchResult.isException() && synchResult.getException()
936 instanceof AuthenticatorException))) {
937
938 OwnCloudClient client = null;
939 try {
940 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
941 removeClientFor(
942 getAccount(),
943 context));
944 // TODO get rid of these exceptions
945 } catch (AccountNotFoundException e) {
946 e.printStackTrace();
947 } catch (AuthenticatorException e) {
948 e.printStackTrace();
949 } catch (OperationCanceledException e) {
950 e.printStackTrace();
951 } catch (IOException e) {
952 e.printStackTrace();
953 }
954
955 if (client != null) {
956 OwnCloudCredentials cred = client.getCredentials();
957 if (cred != null) {
958 AccountManager am = AccountManager.get(context);
959 if (cred.authTokenExpires()) {
960 am.invalidateAuthToken(
961 getAccount().type,
962 cred.getAuthToken()
963 );
964 } else {
965 am.clearPassword(getAccount());
966 }
967 }
968 }
969
970 requestCredentialsUpdate();
971
972 }
973 }
974 removeStickyBroadcast(intent);
975 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
976 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
977
978 }
979
980 if (synchResult != null) {
981 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
982 mLastSslUntrustedServerResult = synchResult;
983 }
984 }
985 } catch (RuntimeException e) {
986 // avoid app crashes after changing the serial id of RemoteOperationResult
987 // in owncloud library with broadcast notifications pending to process
988 removeStickyBroadcast(intent);
989 }
990 }
991 }
992
993
994 /**
995 * Once the file upload has finished -> update view
996 */
997 private class UploadFinishReceiver extends BroadcastReceiver {
998 /**
999 * Once the file upload has finished -> update view
1000 * @author David A. Velasco
1001 * {@link BroadcastReceiver} to enable upload feedback in UI
1002 */
1003 @Override
1004 public void onReceive(Context context, Intent intent) {
1005 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1006 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1007 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1008 OCFile currentDir = getCurrentDir();
1009 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1010 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1011
1012 if (sameAccount && isDescendant) {
1013 refreshListOfFilesFragment();
1014 }
1015
1016 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1017 boolean renamedInUpload = getFile().getRemotePath().
1018 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1019 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1020 renamedInUpload;
1021 FileFragment details = getSecondFragment();
1022 boolean detailFragmentIsShown = (details != null &&
1023 details instanceof FileDetailFragment);
1024
1025 if (sameAccount && sameFile && detailFragmentIsShown) {
1026 if (uploadWasFine) {
1027 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1028 }
1029 if (renamedInUpload) {
1030 String newName = (new File(uploadedRemotePath)).getName();
1031 Toast msg = Toast.makeText(
1032 context,
1033 String.format(
1034 getString(R.string.filedetails_renamed_in_upload_msg),
1035 newName),
1036 Toast.LENGTH_LONG);
1037 msg.show();
1038 }
1039 if (uploadWasFine || getFile().fileExists()) {
1040 ((FileDetailFragment)details).updateFileDetails(false, true);
1041 } else {
1042 cleanSecondFragment();
1043 }
1044
1045 // Force the preview if the file is an image
1046 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1047 startImagePreview(getFile());
1048 } // TODO what about other kind of previews?
1049 }
1050
1051 removeStickyBroadcast(intent);
1052
1053 }
1054
1055 }
1056
1057
1058 /**
1059 * Class waiting for broadcast events from the {@link FielDownloader} service.
1060 *
1061 * Updates the UI when a download is started or finished, provided that it is relevant for the
1062 * current folder.
1063 */
1064 private class DownloadFinishReceiver extends BroadcastReceiver {
1065 @Override
1066 public void onReceive(Context context, Intent intent) {
1067 boolean sameAccount = isSameAccount(context, intent);
1068 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1069 boolean isDescendant = isDescendant(downloadedRemotePath);
1070
1071 if (sameAccount && isDescendant) {
1072 refreshListOfFilesFragment();
1073 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1074 }
1075
1076 if (mWaitingToSend != null) {
1077 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1078 if (mWaitingToSend.isDown()) {
1079 sendDownloadedFile();
1080 }
1081 }
1082
1083 removeStickyBroadcast(intent);
1084 }
1085
1086 private boolean isDescendant(String downloadedRemotePath) {
1087 OCFile currentDir = getCurrentDir();
1088 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1089 }
1090
1091 private boolean isSameAccount(Context context, Intent intent) {
1092 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1093 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1094 }
1095 }
1096
1097
1098 public void browseToRoot() {
1099 OCFileListFragment listOfFiles = getListOfFilesFragment();
1100 if (listOfFiles != null) { // should never be null, indeed
1101 while (mDirectories.getCount() > 1) {
1102 popDirname();
1103 }
1104 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1105 listOfFiles.listDirectory(root);
1106 setFile(listOfFiles.getCurrentFile());
1107 startSyncFolderOperation(root);
1108 }
1109 cleanSecondFragment();
1110 }
1111
1112
1113 public void browseTo(OCFile folder) {
1114 if (folder == null || !folder.isFolder()) {
1115 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1116 }
1117 OCFileListFragment listOfFiles = getListOfFilesFragment();
1118 if (listOfFiles != null) {
1119 setNavigationListWithFolder(folder);
1120 listOfFiles.listDirectory(folder);
1121 setFile(listOfFiles.getCurrentFile());
1122 startSyncFolderOperation(folder);
1123 } else {
1124 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1125 }
1126 cleanSecondFragment();
1127 }
1128
1129
1130 /**
1131 * {@inheritDoc}
1132 *
1133 * Updates action bar and second fragment, if in dual pane mode.
1134 */
1135 @Override
1136 public void onBrowsedDownTo(OCFile directory) {
1137 pushDirname(directory);
1138 cleanSecondFragment();
1139
1140 // Sync Folder
1141 startSyncFolderOperation(directory);
1142
1143 }
1144
1145 /**
1146 * Shows the information of the {@link OCFile} received as a
1147 * parameter in the second fragment.
1148 *
1149 * @param file {@link OCFile} whose details will be shown
1150 */
1151 @Override
1152 public void showDetails(OCFile file) {
1153 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1154 setSecondFragment(detailFragment);
1155 updateFragmentsVisibility(true);
1156 updateNavigationElementsInActionBar(file);
1157 setFile(file);
1158 }
1159
1160
1161 /**
1162 * TODO
1163 */
1164 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1165 ActionBar actionBar = getSupportActionBar();
1166 if (chosenFile == null || mDualPane) {
1167 // only list of files - set for browsing through folders
1168 OCFile currentDir = getCurrentDir();
1169 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1170 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1171 actionBar.setDisplayShowTitleEnabled(!noRoot);
1172 if (!noRoot) {
1173 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1174 }
1175 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1176 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1177
1178 } else {
1179 actionBar.setDisplayHomeAsUpEnabled(true);
1180 actionBar.setDisplayShowTitleEnabled(true);
1181 actionBar.setTitle(chosenFile.getFileName());
1182 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1183 }
1184 }
1185
1186
1187 @Override
1188 protected ServiceConnection newTransferenceServiceConnection() {
1189 return new ListServiceConnection();
1190 }
1191
1192 /** Defines callbacks for service binding, passed to bindService() */
1193 private class ListServiceConnection implements ServiceConnection {
1194
1195 @Override
1196 public void onServiceConnected(ComponentName component, IBinder service) {
1197 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1198 Log_OC.d(TAG, "Download service connected");
1199 mDownloaderBinder = (FileDownloaderBinder) service;
1200 if (mWaitingToPreview != null)
1201 if (getStorageManager() != null) {
1202 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1203 if (!mWaitingToPreview.isDown()) {
1204 requestForDownload();
1205 }
1206 }
1207
1208 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1209 Log_OC.d(TAG, "Upload service connected");
1210 mUploaderBinder = (FileUploaderBinder) service;
1211 } else {
1212 return;
1213 }
1214 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1215 OCFileListFragment listOfFiles = getListOfFilesFragment();
1216 if (listOfFiles != null) {
1217 listOfFiles.listDirectory();
1218 }
1219 FileFragment secondFragment = getSecondFragment();
1220 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1221 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1222 detailFragment.listenForTransferProgress();
1223 detailFragment.updateFileDetails(false, false);
1224 }
1225 }
1226
1227 @Override
1228 public void onServiceDisconnected(ComponentName component) {
1229 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1230 Log_OC.d(TAG, "Download service disconnected");
1231 mDownloaderBinder = null;
1232 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1233 Log_OC.d(TAG, "Upload service disconnected");
1234 mUploaderBinder = null;
1235 }
1236 }
1237 };
1238
1239
1240
1241 /**
1242 * Launch an intent to request the PIN code to the user before letting him use the app
1243 */
1244 private void requestPinCode() {
1245 boolean pinStart = false;
1246 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1247 pinStart = appPrefs.getBoolean("set_pincode", false);
1248 if (pinStart) {
1249 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1250 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1251 startActivity(i);
1252 }
1253 }
1254
1255
1256 @Override
1257 public void onSavedCertificate() {
1258 startSyncFolderOperation(getCurrentDir());
1259 }
1260
1261
1262 @Override
1263 public void onFailedSavingCertificate() {
1264 showDialog(DIALOG_CERT_NOT_SAVED);
1265 }
1266
1267 @Override
1268 public void onCancelCertificate() {
1269 // nothing to do
1270 }
1271
1272 /**
1273 * Updates the view associated to the activity after the finish of some operation over files
1274 * in the current account.
1275 *
1276 * @param operation Removal operation performed.
1277 * @param result Result of the removal.
1278 */
1279 @Override
1280 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1281 super.onRemoteOperationFinish(operation, result);
1282
1283 if (operation instanceof RemoveFileOperation) {
1284 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1285
1286 } else if (operation instanceof RenameFileOperation) {
1287 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1288
1289 } else if (operation instanceof SynchronizeFileOperation) {
1290 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1291
1292 } else if (operation instanceof CreateFolderOperation) {
1293 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1294
1295 } else if (operation instanceof CreateShareOperation) {
1296 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1297
1298 } else if (operation instanceof UnshareLinkOperation) {
1299 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1300
1301 }
1302
1303 }
1304
1305
1306 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1307 if (result.isSuccess()) {
1308 refreshShowDetails();
1309 refreshListOfFilesFragment();
1310 }
1311 }
1312
1313
1314 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1315 if (result.isSuccess()) {
1316 refreshShowDetails();
1317 refreshListOfFilesFragment();
1318
1319 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1320 cleanSecondFragment();
1321 refreshListOfFilesFragment();
1322 }
1323 }
1324
1325 private void refreshShowDetails() {
1326 FileFragment details = getSecondFragment();
1327 if (details != null) {
1328 OCFile file = details.getFile();
1329 if (file != null) {
1330 file = getStorageManager().getFileByPath(file.getRemotePath());
1331 if (details instanceof PreviewMediaFragment) {
1332 // Refresh OCFile of the fragment
1333 ((PreviewMediaFragment) details).updateFile(file);
1334 } else {
1335 showDetails(file);
1336 }
1337 }
1338 invalidateOptionsMenu();
1339 }
1340 }
1341
1342 /**
1343 * Updates the view associated to the activity after the finish of an operation trying to remove a
1344 * file.
1345 *
1346 * @param operation Removal operation performed.
1347 * @param result Result of the removal.
1348 */
1349 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1350 dismissLoadingDialog();
1351
1352 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1353 Toast.LENGTH_LONG);
1354 msg.show();
1355
1356 if (result.isSuccess()) {
1357 OCFile removedFile = operation.getFile();
1358 FileFragment second = getSecondFragment();
1359 if (second != null && removedFile.equals(second.getFile())) {
1360 if (second instanceof PreviewMediaFragment) {
1361 ((PreviewMediaFragment)second).stopPreview(true);
1362 }
1363 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1364 cleanSecondFragment();
1365 }
1366 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1367 refreshListOfFilesFragment();
1368 }
1369 invalidateOptionsMenu();
1370 } else {
1371 if (result.isSslRecoverableException()) {
1372 mLastSslUntrustedServerResult = result;
1373 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1374 }
1375 }
1376 }
1377
1378
1379 /**
1380 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1381 *
1382 * @param operation Creation operation performed.
1383 * @param result Result of the creation.
1384 */
1385 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1386 if (result.isSuccess()) {
1387 dismissLoadingDialog();
1388 refreshListOfFilesFragment();
1389 } else {
1390 dismissLoadingDialog();
1391 try {
1392 Toast msg = Toast.makeText(FileDisplayActivity.this,
1393 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1394 Toast.LENGTH_LONG);
1395 msg.show();
1396
1397 } catch (NotFoundException e) {
1398 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1399 }
1400 }
1401 }
1402
1403
1404 /**
1405 * Updates the view associated to the activity after the finish of an operation trying to rename a
1406 * file.
1407 *
1408 * @param operation Renaming operation performed.
1409 * @param result Result of the renaming.
1410 */
1411 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1412 dismissLoadingDialog();
1413 OCFile renamedFile = operation.getFile();
1414 if (result.isSuccess()) {
1415 FileFragment details = getSecondFragment();
1416 if (details != null) {
1417 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1418 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1419 showDetails(renamedFile);
1420
1421 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1422 ((PreviewMediaFragment) details).updateFile(renamedFile);
1423 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1424 int position = ((PreviewMediaFragment)details).getPosition();
1425 startMediaPreview(renamedFile, position, true);
1426 } else {
1427 getFileOperationsHelper().openFile(renamedFile);
1428 }
1429 }
1430 }
1431
1432 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1433 refreshListOfFilesFragment();
1434 }
1435
1436 } else {
1437 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1438 Toast.LENGTH_LONG);
1439 msg.show();
1440
1441 if (result.isSslRecoverableException()) {
1442 mLastSslUntrustedServerResult = result;
1443 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1444 }
1445 }
1446 }
1447
1448 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1449 dismissLoadingDialog();
1450 OCFile syncedFile = operation.getLocalFile();
1451 if (!result.isSuccess()) {
1452 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1453 Intent i = new Intent(this, ConflictsResolveActivity.class);
1454 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1455 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1456 startActivity(i);
1457
1458 }
1459
1460 } else {
1461 if (operation.transferWasRequested()) {
1462 onTransferStateChanged(syncedFile, true, true);
1463
1464 } else {
1465 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1466 Toast.LENGTH_LONG);
1467 msg.show();
1468 }
1469 }
1470 }
1471
1472
1473 /**
1474 * {@inheritDoc}
1475 */
1476 @Override
1477 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1478 refreshListOfFilesFragment();
1479 FileFragment details = getSecondFragment();
1480 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1481 if (downloading || uploading) {
1482 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1483 } else {
1484 if (!file.fileExists()) {
1485 cleanSecondFragment();
1486 } else {
1487 ((FileDetailFragment)details).updateFileDetails(false, true);
1488 }
1489 }
1490 }
1491
1492 }
1493
1494
1495 private void requestForDownload() {
1496 Account account = getAccount();
1497 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1498 Intent i = new Intent(this, FileDownloader.class);
1499 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1500 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1501 startService(i);
1502 }
1503 }
1504
1505
1506 private OCFile getCurrentDir() {
1507 OCFile file = getFile();
1508 if (file != null) {
1509 if (file.isFolder()) {
1510 return file;
1511 } else if (getStorageManager() != null) {
1512 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1513 return getStorageManager().getFileByPath(parentPath);
1514 }
1515 }
1516 return null;
1517 }
1518
1519 public void startSyncFolderOperation(OCFile folder) {
1520 long currentSyncTime = System.currentTimeMillis();
1521
1522 mSyncInProgress = true;
1523
1524 // perform folder synchronization
1525 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1526 currentSyncTime,
1527 false,
1528 getFileOperationsHelper().isSharedSupported(),
1529 getStorageManager(),
1530 getAccount(),
1531 getApplicationContext()
1532 );
1533 synchFolderOp.execute(getAccount(), this, null, null);
1534
1535 setSupportProgressBarIndeterminateVisibility(true);
1536 }
1537
1538 /**
1539 * Show untrusted cert dialog
1540 */
1541 public void showUntrustedCertDialog(RemoteOperationResult result) {
1542 // Show a dialog with the certificate info
1543 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1544 FragmentManager fm = getSupportFragmentManager();
1545 FragmentTransaction ft = fm.beginTransaction();
1546 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1547 }
1548
1549 private void requestForDownload(OCFile file) {
1550 Account account = getAccount();
1551 if (!mDownloaderBinder.isDownloading(account, file)) {
1552 Intent i = new Intent(this, FileDownloader.class);
1553 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1554 i.putExtra(FileDownloader.EXTRA_FILE, file);
1555 startService(i);
1556 }
1557 }
1558
1559 private void sendDownloadedFile(){
1560 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1561 mWaitingToSend = null;
1562 }
1563
1564
1565 /**
1566 * Requests the download of the received {@link OCFile} , updates the UI
1567 * to monitor the download progress and prepares the activity to send the file
1568 * when the download finishes.
1569 *
1570 * @param file {@link OCFile} to download and preview.
1571 */
1572 public void startDownloadForSending(OCFile file) {
1573 mWaitingToSend = file;
1574 requestForDownload(mWaitingToSend);
1575 boolean hasSecondFragment = (getSecondFragment()!= null);
1576 updateFragmentsVisibility(hasSecondFragment);
1577 }
1578
1579 /**
1580 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1581 *
1582 * @param file Image {@link OCFile} to show.
1583 */
1584 public void startImagePreview(OCFile file) {
1585 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1586 showDetailsIntent.putExtra(EXTRA_FILE, file);
1587 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1588 startActivity(showDetailsIntent);
1589
1590 }
1591
1592 /**
1593 * Stars the preview of an already down media {@link OCFile}.
1594 *
1595 * @param file Media {@link OCFile} to preview.
1596 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1597 * @param autoplay When 'true', the playback will start without user interactions.
1598 */
1599 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1600 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1601 setSecondFragment(mediaFragment);
1602 updateFragmentsVisibility(true);
1603 updateNavigationElementsInActionBar(file);
1604 setFile(file);
1605 }
1606
1607 /**
1608 * Requests the download of the received {@link OCFile} , updates the UI
1609 * to monitor the download progress and prepares the activity to preview
1610 * or open the file when the download finishes.
1611 *
1612 * @param file {@link OCFile} to download and preview.
1613 */
1614 public void startDownloadForPreview(OCFile file) {
1615 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1616 setSecondFragment(detailFragment);
1617 mWaitingToPreview = file;
1618 requestForDownload();
1619 updateFragmentsVisibility(true);
1620 updateNavigationElementsInActionBar(file);
1621 setFile(file);
1622 }
1623
1624
1625 public void cancelTransference(OCFile file) {
1626 getFileOperationsHelper().cancelTransference(file);
1627 if (mWaitingToPreview != null &&
1628 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1629 mWaitingToPreview = null;
1630 }
1631 if (mWaitingToSend != null &&
1632 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1633 mWaitingToSend = null;
1634 }
1635 onTransferStateChanged(file, false, false);
1636 }
1637
1638 }