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