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