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