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