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