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