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