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