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