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