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