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