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