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