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