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