Moved text load call to onStart
[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
626 final Intent fData = data;
627 final int fResultCode = resultCode;
628 getHandler().postDelayed(
629 new Runnable() {
630 @Override
631 public void run() {
632 requestMoveOperation(fData, fResultCode);
633 }
634 },
635 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
636 );
637 }
638 }
639
640 private void requestMultipleUpload(Intent data, int resultCode) {
641 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
642 if (filePaths != null) {
643 String[] remotePaths = new String[filePaths.length];
644 String remotePathBase = "";
645 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
646 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
647 }
648 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
649 remotePathBase += OCFile.PATH_SEPARATOR;
650 for (int j = 0; j < remotePaths.length; j++) {
651 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
652 }
653
654 Intent i = new Intent(this, FileUploader.class);
655 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
656 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
657 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
658 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
659 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
660 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
661 startService(i);
662
663 } else {
664 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
665 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
666 t.show();
667 return;
668 }
669 }
670
671
672 private void requestSimpleUpload(Intent data, int resultCode) {
673 String filepath = null;
674 String mimeType = null;
675
676 Uri selectedImageUri = data.getData();
677
678 try {
679 mimeType = getContentResolver().getType(selectedImageUri);
680
681 String filemanagerstring = selectedImageUri.getPath();
682 String selectedImagePath = getPath(selectedImageUri);
683
684 if (selectedImagePath != null)
685 filepath = selectedImagePath;
686 else
687 filepath = filemanagerstring;
688
689 } catch (Exception e) {
690 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
691 e.printStackTrace();
692
693 } finally {
694 if (filepath == null) {
695 Log_OC.e(TAG, "Couldnt resolve path to file");
696 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
697 t.show();
698 return;
699 }
700 }
701
702 Intent i = new Intent(this, FileUploader.class);
703 i.putExtra(FileUploader.KEY_ACCOUNT,
704 getAccount());
705 String remotepath = new String();
706 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
707 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
708 }
709 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
710 remotepath += OCFile.PATH_SEPARATOR;
711
712 if (filepath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
713
714 Cursor cursor = MainApp.getAppContext().getContentResolver()
715 .query(Uri.parse(filepath), null, null, null, null, null);
716
717 try {
718 if (cursor != null && cursor.moveToFirst()) {
719 String displayName = cursor.getString(
720 cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
721 Log.i(TAG, "Display Name: " + displayName + "; mimeType: " + mimeType);
722
723 displayName.replace(File.separatorChar, '_');
724 displayName.replace(File.pathSeparatorChar, '_');
725 remotepath += displayName + DisplayUtils.getComposedFileExtension(filepath);
726
727 }
728 } finally {
729 cursor.close();
730 }
731
732 } else {
733 remotepath += new File(filepath).getName();
734 }
735
736 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
737 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
738 i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
739 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
740 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
741 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
742 startService(i);
743 }
744
745 /**
746 * Request the operation for moving the file/folder from one path to another
747 *
748 * @param data Intent received
749 * @param resultCode Result code received
750 */
751 private void requestMoveOperation(Intent data, int resultCode) {
752 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
753 OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
754 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
755 }
756
757 @Override
758 public void onBackPressed() {
759 OCFileListFragment listOfFiles = getListOfFilesFragment();
760 if (mDualPane || getSecondFragment() == null) {
761 if (listOfFiles != null) { // should never be null, indeed
762 if (mDirectories.getCount() <= 1) {
763 finish();
764 return;
765 }
766 int levelsUp = listOfFiles.onBrowseUp();
767 for (int i = 0; i < levelsUp && mDirectories.getCount() > 1; i++) {
768 popDirname();
769 }
770 }
771 }
772 if (listOfFiles != null) { // should never be null, indeed
773 setFile(listOfFiles.getCurrentFile());
774 }
775 cleanSecondFragment();
776
777 }
778
779 @Override
780 protected void onSaveInstanceState(Bundle outState) {
781 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
782 Log_OC.e(TAG, "onSaveInstanceState() start");
783 super.onSaveInstanceState(outState);
784 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
785 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
786 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
787 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
788
789 Log_OC.d(TAG, "onSaveInstanceState() end");
790 }
791
792
793 @Override
794 protected void onResume() {
795 super.onResume();
796 Log_OC.e(TAG, "onResume() start");
797
798 // refresh list of files
799 refreshListOfFilesFragment();
800
801 // Listen for sync messages
802 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
803 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
804 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
805 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
806 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
807 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
808 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
809 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
810
811 // Listen for upload messages
812 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
813 mUploadFinishReceiver = new UploadFinishReceiver();
814 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
815
816 // Listen for download messages
817 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
818 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
819 mDownloadFinishReceiver = new DownloadFinishReceiver();
820 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
821
822 Log_OC.d(TAG, "onResume() end");
823 }
824
825
826 @Override
827 protected void onPause() {
828 Log_OC.e(TAG, "onPause() start");
829 if (mSyncBroadcastReceiver != null) {
830 unregisterReceiver(mSyncBroadcastReceiver);
831 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
832 mSyncBroadcastReceiver = null;
833 }
834 if (mUploadFinishReceiver != null) {
835 unregisterReceiver(mUploadFinishReceiver);
836 mUploadFinishReceiver = null;
837 }
838 if (mDownloadFinishReceiver != null) {
839 unregisterReceiver(mDownloadFinishReceiver);
840 mDownloadFinishReceiver = null;
841 }
842
843
844 Log_OC.d(TAG, "onPause() end");
845 super.onPause();
846 }
847
848
849 @Override
850 protected Dialog onCreateDialog(int id) {
851 Dialog dialog = null;
852 AlertDialog.Builder builder;
853 switch (id) {
854 case DIALOG_SHORT_WAIT: {
855 ProgressDialog working_dialog = new ProgressDialog(this);
856 working_dialog.setMessage(getResources().getString(
857 R.string.wait_a_moment));
858 working_dialog.setIndeterminate(true);
859 working_dialog.setCancelable(false);
860 dialog = working_dialog;
861 break;
862 }
863 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
864
865
866 String[] allTheItems = {getString(R.string.actionbar_upload_files),
867 getString(R.string.actionbar_upload_from_apps)};
868
869 builder = new AlertDialog.Builder(this);
870 builder.setTitle(R.string.actionbar_upload);
871 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
872 public void onClick(DialogInterface dialog, int item) {
873 if (item == 0) {
874 // if (!mDualPane) {
875 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
876 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
877 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
878 // } else {
879 // TODO create and handle new fragment
880 // LocalFileListFragment
881 // }
882 } else if (item == 1) {
883 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
884 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
885 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
886 ACTION_SELECT_CONTENT_FROM_APPS);
887 }
888 }
889 });
890 dialog = builder.create();
891 break;
892 }
893 case DIALOG_CERT_NOT_SAVED: {
894 builder = new AlertDialog.Builder(this);
895 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
896 builder.setCancelable(false);
897 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
898 @Override
899 public void onClick(DialogInterface dialog, int which) {
900 dialog.dismiss();
901 }
902
903 ;
904 });
905 dialog = builder.create();
906 break;
907 }
908 default:
909 dialog = null;
910 }
911
912 return dialog;
913 }
914
915 /**
916 * Translates a content URI of an image to a physical path
917 * on the disk
918 *
919 * @param uri The URI to resolve
920 * @return The path to the content or null if it could not be found
921 */
922 public String getPath(Uri uri) {
923 final boolean isKitKatOrLater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
924
925 // DocumentProvider
926 if (isKitKatOrLater && DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
927 // ExternalStorageProvider
928 if (UriUtils.isExternalStorageDocument(uri)) {
929 final String docId = DocumentsContract.getDocumentId(uri);
930 final String[] split = docId.split(":");
931 final String type = split[0];
932
933 if ("primary".equalsIgnoreCase(type)) {
934 return Environment.getExternalStorageDirectory() + "/" + split[1];
935 }
936 }
937 // DownloadsProvider
938 else if (UriUtils.isDownloadsDocument(uri)) {
939
940 final String id = DocumentsContract.getDocumentId(uri);
941 final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
942 Long.valueOf(id));
943
944 return UriUtils.getDataColumn(getApplicationContext(), contentUri, null, null);
945 }
946 // MediaProvider
947 else if (UriUtils.isMediaDocument(uri)) {
948 final String docId = DocumentsContract.getDocumentId(uri);
949 final String[] split = docId.split(":");
950 final String type = split[0];
951
952 Uri contentUri = null;
953 if ("image".equals(type)) {
954 contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
955 } else if ("video".equals(type)) {
956 contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
957 } else if ("audio".equals(type)) {
958 contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
959 }
960
961 final String selection = "_id=?";
962 final String[] selectionArgs = new String[]{split[1]};
963
964 return UriUtils.getDataColumn(getApplicationContext(), contentUri, selection, selectionArgs);
965 }
966 // Documents providers returned as content://...
967 else if (UriUtils.isContentDocument(uri)) {
968 return uri.toString();
969 }
970 }
971 // MediaStore (and general)
972 else if ("content".equalsIgnoreCase(uri.getScheme())) {
973
974 // Return the remote address
975 if (UriUtils.isGooglePhotosUri(uri))
976 return uri.getLastPathSegment();
977
978 return UriUtils.getDataColumn(getApplicationContext(), uri, null, null);
979 }
980 // File
981 else if ("file".equalsIgnoreCase(uri.getScheme())) {
982 return uri.getPath();
983 }
984 return null;
985 }
986
987 /**
988 * Pushes a directory to the drop down list
989 *
990 * @param directory to push
991 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
992 */
993 public void pushDirname(OCFile directory) {
994 if (!directory.isFolder()) {
995 throw new IllegalArgumentException("Only directories may be pushed!");
996 }
997 mDirectories.insert(directory.getFileName(), 0);
998 setFile(directory);
999 }
1000
1001 /**
1002 * Pops a directory name from the drop down list
1003 *
1004 * @return True, unless the stack is empty
1005 */
1006 public boolean popDirname() {
1007 mDirectories.remove(mDirectories.getItem(0));
1008 return !mDirectories.isEmpty();
1009 }
1010
1011 // Custom array adapter to override text colors
1012 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
1013
1014 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
1015 super(ctx, view);
1016 }
1017
1018 public View getView(int position, View convertView, ViewGroup parent) {
1019 View v = super.getView(position, convertView, parent);
1020
1021 ((TextView) v).setTextColor(getResources().getColorStateList(
1022 android.R.color.white));
1023
1024 fixRoot((TextView) v);
1025 return v;
1026 }
1027
1028 public View getDropDownView(int position, View convertView,
1029 ViewGroup parent) {
1030 View v = super.getDropDownView(position, convertView, parent);
1031
1032 ((TextView) v).setTextColor(getResources().getColorStateList(
1033 android.R.color.white));
1034
1035 fixRoot((TextView) v);
1036 return v;
1037 }
1038
1039 private void fixRoot(TextView v) {
1040 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
1041 v.setText(R.string.default_display_name_for_root_folder);
1042 }
1043 }
1044
1045 }
1046
1047 private class SyncBroadcastReceiver extends BroadcastReceiver {
1048
1049 /**
1050 * {@link BroadcastReceiver} to enable syncing feedback in UI
1051 */
1052 @Override
1053 public void onReceive(Context context, Intent intent) {
1054 try {
1055 String event = intent.getAction();
1056 Log_OC.d(TAG, "Received broadcast " + event);
1057 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
1058 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
1059 RemoteOperationResult synchResult = (RemoteOperationResult) intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
1060 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
1061
1062 if (sameAccount) {
1063
1064 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
1065 mSyncInProgress = true;
1066
1067 } else {
1068 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
1069 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1070
1071 if (currentDir == null) {
1072 // current folder was removed from the server
1073 Toast.makeText(FileDisplayActivity.this,
1074 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
1075 Toast.LENGTH_LONG)
1076 .show();
1077 browseToRoot();
1078
1079 } else {
1080 if (currentFile == null && !getFile().isFolder()) {
1081 // currently selected file was removed in the server, and now we know it
1082 cleanSecondFragment();
1083 currentFile = currentDir;
1084 }
1085
1086 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
1087 OCFileListFragment fileListFragment = getListOfFilesFragment();
1088 if (fileListFragment != null) {
1089 fileListFragment.listDirectory(currentDir);
1090 }
1091 }
1092 setFile(currentFile);
1093 }
1094
1095 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
1096
1097 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
1098 equals(event) &&
1099 /// TODO refactor and make common
1100 synchResult != null && !synchResult.isSuccess() &&
1101 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
1102 synchResult.isIdPRedirection() ||
1103 (synchResult.isException() && synchResult.getException()
1104 instanceof AuthenticatorException))) {
1105
1106 OwnCloudClient client = null;
1107 try {
1108 OwnCloudAccount ocAccount =
1109 new OwnCloudAccount(getAccount(), context);
1110 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1111 removeClientFor(ocAccount));
1112 // TODO get rid of these exceptions
1113 } catch (AccountNotFoundException e) {
1114 e.printStackTrace();
1115 } catch (AuthenticatorException e) {
1116 e.printStackTrace();
1117 } catch (OperationCanceledException e) {
1118 e.printStackTrace();
1119 } catch (IOException e) {
1120 e.printStackTrace();
1121 }
1122
1123 if (client != null) {
1124 OwnCloudCredentials cred = client.getCredentials();
1125 if (cred != null) {
1126 AccountManager am = AccountManager.get(context);
1127 if (cred.authTokenExpires()) {
1128 am.invalidateAuthToken(
1129 getAccount().type,
1130 cred.getAuthToken()
1131 );
1132 } else {
1133 am.clearPassword(getAccount());
1134 }
1135 }
1136 }
1137
1138 requestCredentialsUpdate();
1139
1140 }
1141 }
1142 removeStickyBroadcast(intent);
1143 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1144 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1145
1146 setBackgroundText();
1147
1148 }
1149
1150 if (synchResult != null) {
1151 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1152 mLastSslUntrustedServerResult = synchResult;
1153 }
1154 }
1155 } catch (RuntimeException e) {
1156 // avoid app crashes after changing the serial id of RemoteOperationResult
1157 // in owncloud library with broadcast notifications pending to process
1158 removeStickyBroadcast(intent);
1159 }
1160 }
1161 }
1162
1163 /**
1164 * Show a text message on screen view for notifying user if content is
1165 * loading or folder is empty
1166 */
1167 private void setBackgroundText() {
1168 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1169 if (ocFileListFragment != null) {
1170 int message = R.string.file_list_loading;
1171 if (!mSyncInProgress) {
1172 // In case file list is empty
1173 message = R.string.file_list_empty;
1174 }
1175 ocFileListFragment.setMessageForEmptyList(getString(message));
1176 } else {
1177 Log_OC.e(TAG, "OCFileListFragment is null");
1178 }
1179 }
1180
1181 /**
1182 * Once the file upload has finished -> update view
1183 */
1184 private class UploadFinishReceiver extends BroadcastReceiver {
1185 /**
1186 * Once the file upload has finished -> update view
1187 *
1188 * @author David A. Velasco
1189 * {@link BroadcastReceiver} to enable upload feedback in UI
1190 */
1191 @Override
1192 public void onReceive(Context context, Intent intent) {
1193 try {
1194 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1195 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1196 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1197 OCFile currentDir = getCurrentDir();
1198 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1199 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1200
1201 if (sameAccount && isDescendant) {
1202 refreshListOfFilesFragment();
1203 }
1204
1205 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1206 boolean renamedInUpload = getFile().getRemotePath().
1207 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1208 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1209 renamedInUpload;
1210 FileFragment details = getSecondFragment();
1211 boolean detailFragmentIsShown = (details != null &&
1212 details instanceof FileDetailFragment);
1213
1214 if (sameAccount && sameFile && detailFragmentIsShown) {
1215 if (uploadWasFine) {
1216 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1217 }
1218 if (renamedInUpload) {
1219 String newName = (new File(uploadedRemotePath)).getName();
1220 Toast msg = Toast.makeText(
1221 context,
1222 String.format(
1223 getString(R.string.filedetails_renamed_in_upload_msg),
1224 newName),
1225 Toast.LENGTH_LONG);
1226 msg.show();
1227 }
1228 if (uploadWasFine || getFile().fileExists()) {
1229 ((FileDetailFragment) details).updateFileDetails(false, true);
1230 } else {
1231 cleanSecondFragment();
1232 }
1233
1234 // Force the preview if the file is an image or text file
1235 if (uploadWasFine) {
1236 OCFile ocFile = getFile();
1237 if (PreviewImageFragment.canBePreviewed(ocFile))
1238 startImagePreview(getFile());
1239 else if (PreviewTextFragment.canBePreviewed(ocFile))
1240 startTextPreview(ocFile);
1241 // TODO what about other kind of previews?
1242 }
1243 }
1244
1245 } finally {
1246 if (intent != null) {
1247 removeStickyBroadcast(intent);
1248 }
1249 }
1250
1251 }
1252
1253 }
1254
1255
1256 /**
1257 * Class waiting for broadcast events from the {@link FileDownloader} service.
1258 * <p/>
1259 * Updates the UI when a download is started or finished, provided that it is relevant for the
1260 * current folder.
1261 */
1262 private class DownloadFinishReceiver extends BroadcastReceiver {
1263 @Override
1264 public void onReceive(Context context, Intent intent) {
1265 try {
1266 boolean sameAccount = isSameAccount(context, intent);
1267 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1268 boolean isDescendant = isDescendant(downloadedRemotePath);
1269
1270 if (sameAccount && isDescendant) {
1271 refreshListOfFilesFragment();
1272 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1273 }
1274
1275 if (mWaitingToSend != null) {
1276 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1277 if (mWaitingToSend.isDown()) {
1278 sendDownloadedFile();
1279 }
1280 }
1281
1282 } finally {
1283 if (intent != null) {
1284 removeStickyBroadcast(intent);
1285 }
1286 }
1287 }
1288
1289 private boolean isDescendant(String downloadedRemotePath) {
1290 OCFile currentDir = getCurrentDir();
1291 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1292 }
1293
1294 private boolean isSameAccount(Context context, Intent intent) {
1295 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1296 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1297 }
1298 }
1299
1300
1301 public void browseToRoot() {
1302 OCFileListFragment listOfFiles = getListOfFilesFragment();
1303 if (listOfFiles != null) { // should never be null, indeed
1304 while (mDirectories.getCount() > 1) {
1305 popDirname();
1306 }
1307 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1308 listOfFiles.listDirectory(root);
1309 setFile(listOfFiles.getCurrentFile());
1310 startSyncFolderOperation(root, false);
1311 }
1312 cleanSecondFragment();
1313 }
1314
1315
1316 public void browseTo(OCFile folder) {
1317 if (folder == null || !folder.isFolder()) {
1318 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1319 }
1320 OCFileListFragment listOfFiles = getListOfFilesFragment();
1321 if (listOfFiles != null) {
1322 setNavigationListWithFolder(folder);
1323 listOfFiles.listDirectory(folder);
1324 setFile(listOfFiles.getCurrentFile());
1325 startSyncFolderOperation(folder, false);
1326 } else {
1327 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1328 }
1329 cleanSecondFragment();
1330 }
1331
1332
1333 /**
1334 * {@inheritDoc}
1335 * <p/>
1336 * Updates action bar and second fragment, if in dual pane mode.
1337 */
1338 @Override
1339 public void onBrowsedDownTo(OCFile directory) {
1340 pushDirname(directory);
1341 cleanSecondFragment();
1342
1343 // Sync Folder
1344 startSyncFolderOperation(directory, false);
1345
1346 }
1347
1348 /**
1349 * Shows the information of the {@link OCFile} received as a
1350 * parameter in the second fragment.
1351 *
1352 * @param file {@link OCFile} whose details will be shown
1353 */
1354 @Override
1355 public void showDetails(OCFile file) {
1356 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1357 setSecondFragment(detailFragment);
1358 updateFragmentsVisibility(true);
1359 updateNavigationElementsInActionBar(file);
1360 setFile(file);
1361 }
1362
1363
1364 /**
1365 * TODO
1366 */
1367 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1368 ActionBar actionBar = getSupportActionBar();
1369 if (chosenFile == null || mDualPane) {
1370 // only list of files - set for browsing through folders
1371 OCFile currentDir = getCurrentDir();
1372 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1373 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1374 actionBar.setDisplayShowTitleEnabled(!noRoot);
1375 if (!noRoot) {
1376 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1377 }
1378 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1379 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1380
1381 } else {
1382 actionBar.setDisplayHomeAsUpEnabled(true);
1383 actionBar.setDisplayShowTitleEnabled(true);
1384 actionBar.setTitle(chosenFile.getFileName());
1385 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1386 }
1387 }
1388
1389
1390 @Override
1391 protected ServiceConnection newTransferenceServiceConnection() {
1392 return new ListServiceConnection();
1393 }
1394
1395 /**
1396 * Defines callbacks for service binding, passed to bindService()
1397 */
1398 private class ListServiceConnection implements ServiceConnection {
1399
1400 @Override
1401 public void onServiceConnected(ComponentName component, IBinder service) {
1402 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1403 Log_OC.d(TAG, "Download service connected");
1404 mDownloaderBinder = (FileDownloaderBinder) service;
1405 if (mWaitingToPreview != null)
1406 if (getStorageManager() != null) {
1407 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1408 if (!mWaitingToPreview.isDown()) {
1409 requestForDownload();
1410 }
1411 }
1412
1413 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1414 Log_OC.d(TAG, "Upload service connected");
1415 mUploaderBinder = (FileUploaderBinder) service;
1416 } else {
1417 return;
1418 }
1419 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1420 OCFileListFragment listOfFiles = getListOfFilesFragment();
1421 if (listOfFiles != null) {
1422 listOfFiles.listDirectory();
1423 }
1424 FileFragment secondFragment = getSecondFragment();
1425 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1426 FileDetailFragment detailFragment = (FileDetailFragment) secondFragment;
1427 detailFragment.listenForTransferProgress();
1428 detailFragment.updateFileDetails(false, false);
1429 }
1430 }
1431
1432 @Override
1433 public void onServiceDisconnected(ComponentName component) {
1434 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1435 Log_OC.d(TAG, "Download service disconnected");
1436 mDownloaderBinder = null;
1437 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1438 Log_OC.d(TAG, "Upload service disconnected");
1439 mUploaderBinder = null;
1440 }
1441 }
1442 }
1443
1444 ;
1445
1446
1447 /**
1448 * Launch an intent to request the PIN code to the user before letting him use the app
1449 */
1450 private void requestPinCode() {
1451 boolean pinStart = false;
1452 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1453 pinStart = appPrefs.getBoolean("set_pincode", false);
1454 if (pinStart) {
1455 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1456 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1457 startActivity(i);
1458 }
1459 }
1460
1461
1462 @Override
1463 public void onSavedCertificate() {
1464 startSyncFolderOperation(getCurrentDir(), false);
1465 }
1466
1467
1468 @Override
1469 public void onFailedSavingCertificate() {
1470 showDialog(DIALOG_CERT_NOT_SAVED);
1471 }
1472
1473 @Override
1474 public void onCancelCertificate() {
1475 // nothing to do
1476 }
1477
1478 /**
1479 * Updates the view associated to the activity after the finish of some operation over files
1480 * in the current account.
1481 *
1482 * @param operation Removal operation performed.
1483 * @param result Result of the removal.
1484 */
1485 @Override
1486 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1487 super.onRemoteOperationFinish(operation, result);
1488
1489 if (operation instanceof RemoveFileOperation) {
1490 onRemoveFileOperationFinish((RemoveFileOperation) operation, result);
1491
1492 } else if (operation instanceof RenameFileOperation) {
1493 onRenameFileOperationFinish((RenameFileOperation) operation, result);
1494
1495 } else if (operation instanceof SynchronizeFileOperation) {
1496 onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);
1497
1498 } else if (operation instanceof CreateFolderOperation) {
1499 onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
1500
1501 } else if (operation instanceof CreateShareOperation) {
1502 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1503
1504 } else if (operation instanceof UnshareLinkOperation) {
1505 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
1506
1507 } else if (operation instanceof MoveFileOperation) {
1508 onMoveFileOperationFinish((MoveFileOperation) operation, result);
1509 }
1510
1511 }
1512
1513
1514 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1515 if (result.isSuccess()) {
1516 refreshShowDetails();
1517 refreshListOfFilesFragment();
1518 }
1519 }
1520
1521
1522 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1523 if (result.isSuccess()) {
1524 refreshShowDetails();
1525 refreshListOfFilesFragment();
1526
1527 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1528 cleanSecondFragment();
1529 refreshListOfFilesFragment();
1530 }
1531 }
1532
1533 private void refreshShowDetails() {
1534 FileFragment details = getSecondFragment();
1535 if (details != null) {
1536 OCFile file = details.getFile();
1537 if (file != null) {
1538 file = getStorageManager().getFileByPath(file.getRemotePath());
1539 if (details instanceof PreviewMediaFragment) {
1540 // Refresh OCFile of the fragment
1541 ((PreviewMediaFragment) details).updateFile(file);
1542 } else if (details instanceof PreviewTextFragment) {
1543 // Refresh OCFile of the fragment
1544 ((PreviewTextFragment) details).updateFile(file);
1545 } else
1546 showDetails(file);
1547 }
1548 invalidateOptionsMenu();
1549 }
1550 }
1551
1552 /**
1553 * Updates the view associated to the activity after the finish of an operation trying to remove a
1554 * file.
1555 *
1556 * @param operation Removal operation performed.
1557 * @param result Result of the removal.
1558 */
1559 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1560 dismissLoadingDialog();
1561
1562 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1563 Toast.LENGTH_LONG);
1564 msg.show();
1565
1566 if (result.isSuccess()) {
1567 OCFile removedFile = operation.getFile();
1568 FileFragment second = getSecondFragment();
1569 if (second != null && removedFile.equals(second.getFile())) {
1570 if (second instanceof PreviewMediaFragment) {
1571 ((PreviewMediaFragment) second).stopPreview(true);
1572 }
1573 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1574 cleanSecondFragment();
1575 }
1576 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1577 refreshListOfFilesFragment();
1578 }
1579 invalidateOptionsMenu();
1580 } else {
1581 if (result.isSslRecoverableException()) {
1582 mLastSslUntrustedServerResult = result;
1583 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1584 }
1585 }
1586 }
1587
1588
1589 /**
1590 * Updates the view associated to the activity after the finish of an operation trying to move a
1591 * file.
1592 *
1593 * @param operation Move operation performed.
1594 * @param result Result of the move operation.
1595 */
1596 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1597 if (result.isSuccess()) {
1598 dismissLoadingDialog();
1599 refreshListOfFilesFragment();
1600 } else {
1601 dismissLoadingDialog();
1602 try {
1603 Toast msg = Toast.makeText(FileDisplayActivity.this,
1604 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1605 Toast.LENGTH_LONG);
1606 msg.show();
1607
1608 } catch (NotFoundException e) {
1609 Log_OC.e(TAG, "Error while trying to show fail message ", e);
1610 }
1611 }
1612 }
1613
1614
1615 /**
1616 * Updates the view associated to the activity after the finish of an operation trying to rename a
1617 * file.
1618 *
1619 * @param operation Renaming operation performed.
1620 * @param result Result of the renaming.
1621 */
1622 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1623 dismissLoadingDialog();
1624 OCFile renamedFile = operation.getFile();
1625 if (result.isSuccess()) {
1626 FileFragment details = getSecondFragment();
1627 if (details != null) {
1628 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile())) {
1629 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1630 showDetails(renamedFile);
1631
1632 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1633 ((PreviewMediaFragment) details).updateFile(renamedFile);
1634 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1635 int position = ((PreviewMediaFragment) details).getPosition();
1636 startMediaPreview(renamedFile, position, true);
1637 } else {
1638 getFileOperationsHelper().openFile(renamedFile);
1639 }
1640 } else if (details instanceof PreviewTextFragment && renamedFile.equals(details.getFile())) {
1641 ((PreviewTextFragment) details).updateFile(renamedFile);
1642 if (PreviewTextFragment.canBePreviewed(renamedFile)) {
1643 startTextPreview(renamedFile);
1644 } else {
1645 getFileOperationsHelper().openFile(renamedFile);
1646 }
1647 }
1648 }
1649
1650 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1651 refreshListOfFilesFragment();
1652 }
1653
1654 } else {
1655 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1656 Toast.LENGTH_LONG);
1657 msg.show();
1658
1659 if (result.isSslRecoverableException()) {
1660 mLastSslUntrustedServerResult = result;
1661 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1662 }
1663 }
1664 }
1665
1666 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1667 dismissLoadingDialog();
1668 OCFile syncedFile = operation.getLocalFile();
1669 if (!result.isSuccess()) {
1670 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1671 Intent i = new Intent(this, ConflictsResolveActivity.class);
1672 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1673 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1674 startActivity(i);
1675
1676 }
1677
1678 } else {
1679 if (operation.transferWasRequested()) {
1680 onTransferStateChanged(syncedFile, true, true);
1681
1682 } else {
1683 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1684 Toast.LENGTH_LONG);
1685 msg.show();
1686 }
1687 }
1688 }
1689
1690 /**
1691 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1692 *
1693 * @param operation Creation operation performed.
1694 * @param result Result of the creation.
1695 */
1696 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1697 if (result.isSuccess()) {
1698 dismissLoadingDialog();
1699 refreshListOfFilesFragment();
1700 } else {
1701 dismissLoadingDialog();
1702 try {
1703 Toast msg = Toast.makeText(FileDisplayActivity.this,
1704 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1705 Toast.LENGTH_LONG);
1706 msg.show();
1707
1708 } catch (NotFoundException e) {
1709 Log_OC.e(TAG, "Error while trying to show fail message ", e);
1710 }
1711 }
1712 }
1713
1714
1715 /**
1716 * {@inheritDoc}
1717 */
1718 @Override
1719 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1720 refreshListOfFilesFragment();
1721 FileFragment details = getSecondFragment();
1722 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile())) {
1723 if (downloading || uploading) {
1724 ((FileDetailFragment) details).updateFileDetails(file, getAccount());
1725 } else {
1726 if (!file.fileExists()) {
1727 cleanSecondFragment();
1728 } else {
1729 ((FileDetailFragment) details).updateFileDetails(false, true);
1730 }
1731 }
1732 }
1733
1734 }
1735
1736
1737 private void requestForDownload() {
1738 Account account = getAccount();
1739 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1740 Intent i = new Intent(this, FileDownloader.class);
1741 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1742 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1743 startService(i);
1744 }
1745 }
1746
1747
1748 private OCFile getCurrentDir() {
1749 OCFile file = getFile();
1750 if (file != null) {
1751 if (file.isFolder()) {
1752 return file;
1753 } else if (getStorageManager() != null) {
1754 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1755 return getStorageManager().getFileByPath(parentPath);
1756 }
1757 }
1758 return null;
1759 }
1760
1761 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1762 long currentSyncTime = System.currentTimeMillis();
1763
1764 mSyncInProgress = true;
1765
1766 // perform folder synchronization
1767 RemoteOperation synchFolderOp = new SynchronizeFolderOperation(folder,
1768 currentSyncTime,
1769 false,
1770 getFileOperationsHelper().isSharedSupported(),
1771 ignoreETag,
1772 getStorageManager(),
1773 getAccount(),
1774 getApplicationContext()
1775 );
1776 synchFolderOp.execute(getAccount(), this, null, null);
1777
1778 setSupportProgressBarIndeterminateVisibility(true);
1779
1780 setBackgroundText();
1781 }
1782
1783 /**
1784 * Show untrusted cert dialog
1785 */
1786 public void showUntrustedCertDialog(RemoteOperationResult result) {
1787 // Show a dialog with the certificate info
1788 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException) result.getException());
1789 FragmentManager fm = getSupportFragmentManager();
1790 FragmentTransaction ft = fm.beginTransaction();
1791 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1792 }
1793
1794 private void requestForDownload(OCFile file) {
1795 Account account = getAccount();
1796 if (!mDownloaderBinder.isDownloading(account, file)) {
1797 Intent i = new Intent(this, FileDownloader.class);
1798 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1799 i.putExtra(FileDownloader.EXTRA_FILE, file);
1800 startService(i);
1801 }
1802 }
1803
1804 private void sendDownloadedFile() {
1805 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1806 mWaitingToSend = null;
1807 }
1808
1809
1810 /**
1811 * Requests the download of the received {@link OCFile} , updates the UI
1812 * to monitor the download progress and prepares the activity to send the file
1813 * when the download finishes.
1814 *
1815 * @param file {@link OCFile} to download and preview.
1816 */
1817 public void startDownloadForSending(OCFile file) {
1818 mWaitingToSend = file;
1819 requestForDownload(mWaitingToSend);
1820 boolean hasSecondFragment = (getSecondFragment() != null);
1821 updateFragmentsVisibility(hasSecondFragment);
1822 }
1823
1824 /**
1825 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1826 *
1827 * @param file Image {@link OCFile} to show.
1828 */
1829 public void startImagePreview(OCFile file) {
1830 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1831 showDetailsIntent.putExtra(EXTRA_FILE, file);
1832 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1833 startActivity(showDetailsIntent);
1834 }
1835
1836 /**
1837 * Stars the preview of an already down media {@link OCFile}.
1838 *
1839 * @param file Media {@link OCFile} to preview.
1840 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1841 * @param autoplay When 'true', the playback will start without user interactions.
1842 */
1843 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1844 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1845 setSecondFragment(mediaFragment);
1846 updateFragmentsVisibility(true);
1847 updateNavigationElementsInActionBar(file);
1848 setFile(file);
1849 }
1850
1851 /**
1852 * Stars the preview of a text file {@link OCFile}.
1853 *
1854 * @param file Text {@link OCFile} to preview.
1855 */
1856 public void startTextPreview(OCFile file) {
1857 Bundle args = new Bundle();
1858 args.putParcelable(EXTRA_FILE, file);
1859 args.putParcelable(EXTRA_ACCOUNT, getAccount());
1860 Fragment textPreviewFragment = Fragment.instantiate(getApplicationContext(), PreviewTextFragment.class.getName(), args);
1861 setSecondFragment(textPreviewFragment);
1862 updateFragmentsVisibility(true);
1863 updateNavigationElementsInActionBar(file);
1864 setFile(file);
1865 }
1866
1867 /**
1868 * Requests the download of the received {@link OCFile} , updates the UI
1869 * to monitor the download progress and prepares the activity to preview
1870 * or open the file when the download finishes.
1871 *
1872 * @param file {@link OCFile} to download and preview.
1873 */
1874 public void startDownloadForPreview(OCFile file) {
1875 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1876 setSecondFragment(detailFragment);
1877 mWaitingToPreview = file;
1878 requestForDownload();
1879 updateFragmentsVisibility(true);
1880 updateNavigationElementsInActionBar(file);
1881 setFile(file);
1882 }
1883
1884
1885 public void cancelTransference(OCFile file) {
1886 getFileOperationsHelper().cancelTransference(file);
1887 if (mWaitingToPreview != null &&
1888 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1889 mWaitingToPreview = null;
1890 }
1891 if (mWaitingToSend != null &&
1892 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1893 mWaitingToSend = null;
1894 }
1895 onTransferStateChanged(file, false, false);
1896 }
1897
1898 @Override
1899 public void onRefresh(boolean ignoreETag) {
1900 refreshList(ignoreETag);
1901 }
1902
1903 @Override
1904 public void onRefresh() {
1905 refreshList(true);
1906 }
1907
1908 private void refreshList(boolean ignoreETag) {
1909 OCFileListFragment listOfFiles = getListOfFilesFragment();
1910 if (listOfFiles != null) {
1911 OCFile folder = listOfFiles.getCurrentFile();
1912 if (folder != null) {
1913 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1914 listDirectory(mFile);*/
1915 startSyncFolderOperation(folder, ignoreETag);
1916 }
1917 }
1918 }
1919
1920 private void sortByDate(boolean ascending) {
1921 getListOfFilesFragment().sortByDate(ascending);
1922 }
1923
1924 private void sortBySize(boolean ascending) {
1925 getListOfFilesFragment().sortBySize(ascending);
1926 }
1927
1928 private void sortByName(boolean ascending) {
1929 getListOfFilesFragment().sortByName(ascending);
1930 }
1931 }