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