2469dcf71488e632755bb39af45ce5a7f0f93385
[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 // Documents providers returned as content://...
953 else if (isAContentDocument(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 *
1046 * @param uri The Uri to check.
1047 * @return Whether the Uri is from a content provider as kind "content://..."
1048 */
1049 public static boolean isAContentDocument(Uri uri) {
1050 return uri.toString().startsWith("content://");
1051 }
1052
1053 /**
1054 * Pushes a directory to the drop down list
1055 * @param directory to push
1056 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1057 */
1058 public void pushDirname(OCFile directory) {
1059 if(!directory.isFolder()){
1060 throw new IllegalArgumentException("Only directories may be pushed!");
1061 }
1062 mDirectories.insert(directory.getFileName(), 0);
1063 setFile(directory);
1064 }
1065
1066 /**
1067 * Pops a directory name from the drop down list
1068 * @return True, unless the stack is empty
1069 */
1070 public boolean popDirname() {
1071 mDirectories.remove(mDirectories.getItem(0));
1072 return !mDirectories.isEmpty();
1073 }
1074
1075 // Custom array adapter to override text colors
1076 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
1077
1078 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
1079 super(ctx, view);
1080 }
1081
1082 public View getView(int position, View convertView, ViewGroup parent) {
1083 View v = super.getView(position, convertView, parent);
1084
1085 ((TextView) v).setTextColor(getResources().getColorStateList(
1086 android.R.color.white));
1087
1088 fixRoot((TextView) v );
1089 return v;
1090 }
1091
1092 public View getDropDownView(int position, View convertView,
1093 ViewGroup parent) {
1094 View v = super.getDropDownView(position, convertView, parent);
1095
1096 ((TextView) v).setTextColor(getResources().getColorStateList(
1097 android.R.color.white));
1098
1099 fixRoot((TextView) v );
1100 return v;
1101 }
1102
1103 private void fixRoot(TextView v) {
1104 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
1105 v.setText(R.string.default_display_name_for_root_folder);
1106 }
1107 }
1108
1109 }
1110
1111 private class SyncBroadcastReceiver extends BroadcastReceiver {
1112
1113 /**
1114 * {@link BroadcastReceiver} to enable syncing feedback in UI
1115 */
1116 @Override
1117 public void onReceive(Context context, Intent intent) {
1118 try {
1119 String event = intent.getAction();
1120 Log_OC.d(TAG, "Received broadcast " + event);
1121 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
1122 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
1123 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
1124 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
1125
1126 if (sameAccount) {
1127
1128 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
1129 mSyncInProgress = true;
1130
1131 } else {
1132 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
1133 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1134
1135 if (currentDir == null) {
1136 // current folder was removed from the server
1137 Toast.makeText( FileDisplayActivity.this,
1138 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
1139 Toast.LENGTH_LONG)
1140 .show();
1141 browseToRoot();
1142
1143 } else {
1144 if (currentFile == null && !getFile().isFolder()) {
1145 // currently selected file was removed in the server, and now we know it
1146 cleanSecondFragment();
1147 currentFile = currentDir;
1148 }
1149
1150 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
1151 OCFileListFragment fileListFragment = getListOfFilesFragment();
1152 if (fileListFragment != null) {
1153 fileListFragment.listDirectory(currentDir);
1154 }
1155 }
1156 setFile(currentFile);
1157 }
1158
1159 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
1160
1161 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
1162 equals(event) &&
1163 /// TODO refactor and make common
1164 synchResult != null && !synchResult.isSuccess() &&
1165 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
1166 synchResult.isIdPRedirection() ||
1167 (synchResult.isException() && synchResult.getException()
1168 instanceof AuthenticatorException))) {
1169
1170 OwnCloudClient client = null;
1171 try {
1172 OwnCloudAccount ocAccount =
1173 new OwnCloudAccount(getAccount(), context);
1174 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1175 removeClientFor(ocAccount));
1176 // TODO get rid of these exceptions
1177 } catch (AccountNotFoundException e) {
1178 e.printStackTrace();
1179 } catch (AuthenticatorException e) {
1180 e.printStackTrace();
1181 } catch (OperationCanceledException e) {
1182 e.printStackTrace();
1183 } catch (IOException e) {
1184 e.printStackTrace();
1185 }
1186
1187 if (client != null) {
1188 OwnCloudCredentials cred = client.getCredentials();
1189 if (cred != null) {
1190 AccountManager am = AccountManager.get(context);
1191 if (cred.authTokenExpires()) {
1192 am.invalidateAuthToken(
1193 getAccount().type,
1194 cred.getAuthToken()
1195 );
1196 } else {
1197 am.clearPassword(getAccount());
1198 }
1199 }
1200 }
1201
1202 requestCredentialsUpdate();
1203
1204 }
1205 }
1206 removeStickyBroadcast(intent);
1207 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1209
1210 setBackgroundText();
1211
1212 }
1213
1214 if (synchResult != null) {
1215 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1216 mLastSslUntrustedServerResult = synchResult;
1217 }
1218 }
1219 } catch (RuntimeException e) {
1220 // avoid app crashes after changing the serial id of RemoteOperationResult
1221 // in owncloud library with broadcast notifications pending to process
1222 removeStickyBroadcast(intent);
1223 }
1224 }
1225 }
1226
1227 /**
1228 * Show a text message on screen view for notifying user if content is
1229 * loading or folder is empty
1230 */
1231 private void setBackgroundText() {
1232 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1233 if (ocFileListFragment != null) {
1234 int message = R.string.file_list_loading;
1235 if (!mSyncInProgress) {
1236 // In case file list is empty
1237 message = R.string.file_list_empty;
1238 }
1239 ocFileListFragment.setMessageForEmptyList(getString(message));
1240 } else {
1241 Log_OC.e(TAG, "OCFileListFragment is null");
1242 }
1243 }
1244
1245 /**
1246 * Once the file upload has finished -> update view
1247 */
1248 private class UploadFinishReceiver extends BroadcastReceiver {
1249 /**
1250 * Once the file upload has finished -> update view
1251 * @author David A. Velasco
1252 * {@link BroadcastReceiver} to enable upload feedback in UI
1253 */
1254 @Override
1255 public void onReceive(Context context, Intent intent) {
1256 try {
1257 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1258 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1259 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1260 OCFile currentDir = getCurrentDir();
1261 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1262 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1263
1264 if (sameAccount && isDescendant) {
1265 refreshListOfFilesFragment();
1266 }
1267
1268 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1269 boolean renamedInUpload = getFile().getRemotePath().
1270 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1271 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1272 renamedInUpload;
1273 FileFragment details = getSecondFragment();
1274 boolean detailFragmentIsShown = (details != null &&
1275 details instanceof FileDetailFragment);
1276
1277 if (sameAccount && sameFile && detailFragmentIsShown) {
1278 if (uploadWasFine) {
1279 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1280 }
1281 if (renamedInUpload) {
1282 String newName = (new File(uploadedRemotePath)).getName();
1283 Toast msg = Toast.makeText(
1284 context,
1285 String.format(
1286 getString(R.string.filedetails_renamed_in_upload_msg),
1287 newName),
1288 Toast.LENGTH_LONG);
1289 msg.show();
1290 }
1291 if (uploadWasFine || getFile().fileExists()) {
1292 ((FileDetailFragment)details).updateFileDetails(false, true);
1293 } else {
1294 cleanSecondFragment();
1295 }
1296
1297 // Force the preview if the file is an image
1298 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1299 startImagePreview(getFile());
1300 } // TODO what about other kind of previews?
1301 }
1302
1303 } finally {
1304 if (intent != null) {
1305 removeStickyBroadcast(intent);
1306 }
1307 }
1308
1309 }
1310
1311 }
1312
1313
1314 /**
1315 * Class waiting for broadcast events from the {@link FielDownloader} service.
1316 *
1317 * Updates the UI when a download is started or finished, provided that it is relevant for the
1318 * current folder.
1319 */
1320 private class DownloadFinishReceiver extends BroadcastReceiver {
1321 @Override
1322 public void onReceive(Context context, Intent intent) {
1323 try {
1324 boolean sameAccount = isSameAccount(context, intent);
1325 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1326 boolean isDescendant = isDescendant(downloadedRemotePath);
1327
1328 if (sameAccount && isDescendant) {
1329 refreshListOfFilesFragment();
1330 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1331 }
1332
1333 if (mWaitingToSend != null) {
1334 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1335 if (mWaitingToSend.isDown()) {
1336 sendDownloadedFile();
1337 }
1338 }
1339
1340 } finally {
1341 if (intent != null) {
1342 removeStickyBroadcast(intent);
1343 }
1344 }
1345 }
1346
1347 private boolean isDescendant(String downloadedRemotePath) {
1348 OCFile currentDir = getCurrentDir();
1349 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1350 }
1351
1352 private boolean isSameAccount(Context context, Intent intent) {
1353 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1354 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1355 }
1356 }
1357
1358
1359 public void browseToRoot() {
1360 OCFileListFragment listOfFiles = getListOfFilesFragment();
1361 if (listOfFiles != null) { // should never be null, indeed
1362 while (mDirectories.getCount() > 1) {
1363 popDirname();
1364 }
1365 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1366 listOfFiles.listDirectory(root);
1367 setFile(listOfFiles.getCurrentFile());
1368 startSyncFolderOperation(root, false);
1369 }
1370 cleanSecondFragment();
1371 }
1372
1373
1374 public void browseTo(OCFile folder) {
1375 if (folder == null || !folder.isFolder()) {
1376 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1377 }
1378 OCFileListFragment listOfFiles = getListOfFilesFragment();
1379 if (listOfFiles != null) {
1380 setNavigationListWithFolder(folder);
1381 listOfFiles.listDirectory(folder);
1382 setFile(listOfFiles.getCurrentFile());
1383 startSyncFolderOperation(folder, false);
1384 } else {
1385 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1386 }
1387 cleanSecondFragment();
1388 }
1389
1390
1391 /**
1392 * {@inheritDoc}
1393 *
1394 * Updates action bar and second fragment, if in dual pane mode.
1395 */
1396 @Override
1397 public void onBrowsedDownTo(OCFile directory) {
1398 pushDirname(directory);
1399 cleanSecondFragment();
1400
1401 // Sync Folder
1402 startSyncFolderOperation(directory, false);
1403
1404 }
1405
1406 /**
1407 * Shows the information of the {@link OCFile} received as a
1408 * parameter in the second fragment.
1409 *
1410 * @param file {@link OCFile} whose details will be shown
1411 */
1412 @Override
1413 public void showDetails(OCFile file) {
1414 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1415 setSecondFragment(detailFragment);
1416 updateFragmentsVisibility(true);
1417 updateNavigationElementsInActionBar(file);
1418 setFile(file);
1419 }
1420
1421
1422 /**
1423 * TODO
1424 */
1425 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1426 ActionBar actionBar = getSupportActionBar();
1427 if (chosenFile == null || mDualPane) {
1428 // only list of files - set for browsing through folders
1429 OCFile currentDir = getCurrentDir();
1430 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1431 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1432 actionBar.setDisplayShowTitleEnabled(!noRoot);
1433 if (!noRoot) {
1434 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1435 }
1436 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1437 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1438
1439 } else {
1440 actionBar.setDisplayHomeAsUpEnabled(true);
1441 actionBar.setDisplayShowTitleEnabled(true);
1442 actionBar.setTitle(chosenFile.getFileName());
1443 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1444 }
1445 }
1446
1447
1448 @Override
1449 protected ServiceConnection newTransferenceServiceConnection() {
1450 return new ListServiceConnection();
1451 }
1452
1453 /** Defines callbacks for service binding, passed to bindService() */
1454 private class ListServiceConnection implements ServiceConnection {
1455
1456 @Override
1457 public void onServiceConnected(ComponentName component, IBinder service) {
1458 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1459 Log_OC.d(TAG, "Download service connected");
1460 mDownloaderBinder = (FileDownloaderBinder) service;
1461 if (mWaitingToPreview != null)
1462 if (getStorageManager() != null) {
1463 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1464 if (!mWaitingToPreview.isDown()) {
1465 requestForDownload();
1466 }
1467 }
1468
1469 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1470 Log_OC.d(TAG, "Upload service connected");
1471 mUploaderBinder = (FileUploaderBinder) service;
1472 } else {
1473 return;
1474 }
1475 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1476 OCFileListFragment listOfFiles = getListOfFilesFragment();
1477 if (listOfFiles != null) {
1478 listOfFiles.listDirectory();
1479 }
1480 FileFragment secondFragment = getSecondFragment();
1481 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1482 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1483 detailFragment.listenForTransferProgress();
1484 detailFragment.updateFileDetails(false, false);
1485 }
1486 }
1487
1488 @Override
1489 public void onServiceDisconnected(ComponentName component) {
1490 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1491 Log_OC.d(TAG, "Download service disconnected");
1492 mDownloaderBinder = null;
1493 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1494 Log_OC.d(TAG, "Upload service disconnected");
1495 mUploaderBinder = null;
1496 }
1497 }
1498 };
1499
1500
1501
1502 /**
1503 * Launch an intent to request the PIN code to the user before letting him use the app
1504 */
1505 private void requestPinCode() {
1506 boolean pinStart = false;
1507 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1508 pinStart = appPrefs.getBoolean("set_pincode", false);
1509 if (pinStart) {
1510 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1511 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1512 startActivity(i);
1513 }
1514 }
1515
1516
1517 @Override
1518 public void onSavedCertificate() {
1519 startSyncFolderOperation(getCurrentDir(), false);
1520 }
1521
1522
1523 @Override
1524 public void onFailedSavingCertificate() {
1525 showDialog(DIALOG_CERT_NOT_SAVED);
1526 }
1527
1528 @Override
1529 public void onCancelCertificate() {
1530 // nothing to do
1531 }
1532
1533 /**
1534 * Updates the view associated to the activity after the finish of some operation over files
1535 * in the current account.
1536 *
1537 * @param operation Removal operation performed.
1538 * @param result Result of the removal.
1539 */
1540 @Override
1541 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1542 super.onRemoteOperationFinish(operation, result);
1543
1544 if (operation instanceof RemoveFileOperation) {
1545 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1546
1547 } else if (operation instanceof RenameFileOperation) {
1548 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1549
1550 } else if (operation instanceof SynchronizeFileOperation) {
1551 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1552
1553 } else if (operation instanceof CreateFolderOperation) {
1554 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1555
1556 } else if (operation instanceof CreateShareOperation) {
1557 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1558
1559 } else if (operation instanceof UnshareLinkOperation) {
1560 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1561
1562 } else if (operation instanceof MoveFileOperation) {
1563 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1564 }
1565
1566 }
1567
1568
1569 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1570 if (result.isSuccess()) {
1571 refreshShowDetails();
1572 refreshListOfFilesFragment();
1573 }
1574 }
1575
1576
1577 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1578 if (result.isSuccess()) {
1579 refreshShowDetails();
1580 refreshListOfFilesFragment();
1581
1582 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1583 cleanSecondFragment();
1584 refreshListOfFilesFragment();
1585 }
1586 }
1587
1588 private void refreshShowDetails() {
1589 FileFragment details = getSecondFragment();
1590 if (details != null) {
1591 OCFile file = details.getFile();
1592 if (file != null) {
1593 file = getStorageManager().getFileByPath(file.getRemotePath());
1594 if (details instanceof PreviewMediaFragment) {
1595 // Refresh OCFile of the fragment
1596 ((PreviewMediaFragment) details).updateFile(file);
1597 } else {
1598 showDetails(file);
1599 }
1600 }
1601 invalidateOptionsMenu();
1602 }
1603 }
1604
1605 /**
1606 * Updates the view associated to the activity after the finish of an operation trying to remove a
1607 * file.
1608 *
1609 * @param operation Removal operation performed.
1610 * @param result Result of the removal.
1611 */
1612 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1613 dismissLoadingDialog();
1614
1615 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1616 Toast.LENGTH_LONG);
1617 msg.show();
1618
1619 if (result.isSuccess()) {
1620 OCFile removedFile = operation.getFile();
1621 FileFragment second = getSecondFragment();
1622 if (second != null && removedFile.equals(second.getFile())) {
1623 if (second instanceof PreviewMediaFragment) {
1624 ((PreviewMediaFragment)second).stopPreview(true);
1625 }
1626 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1627 cleanSecondFragment();
1628 }
1629 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1630 refreshListOfFilesFragment();
1631 }
1632 invalidateOptionsMenu();
1633 } else {
1634 if (result.isSslRecoverableException()) {
1635 mLastSslUntrustedServerResult = result;
1636 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1637 }
1638 }
1639 }
1640
1641
1642 /**
1643 * Updates the view associated to the activity after the finish of an operation trying to move a
1644 * file.
1645 *
1646 * @param operation Move operation performed.
1647 * @param result Result of the move operation.
1648 */
1649 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1650 if (result.isSuccess()) {
1651 dismissLoadingDialog();
1652 refreshListOfFilesFragment();
1653 } else {
1654 dismissLoadingDialog();
1655 try {
1656 Toast msg = Toast.makeText(FileDisplayActivity.this,
1657 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1658 Toast.LENGTH_LONG);
1659 msg.show();
1660
1661 } catch (NotFoundException e) {
1662 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1663 }
1664 }
1665 }
1666
1667
1668 /**
1669 * Updates the view associated to the activity after the finish of an operation trying to rename a
1670 * file.
1671 *
1672 * @param operation Renaming operation performed.
1673 * @param result Result of the renaming.
1674 */
1675 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1676 dismissLoadingDialog();
1677 OCFile renamedFile = operation.getFile();
1678 if (result.isSuccess()) {
1679 FileFragment details = getSecondFragment();
1680 if (details != null) {
1681 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1682 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1683 showDetails(renamedFile);
1684
1685 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1686 ((PreviewMediaFragment) details).updateFile(renamedFile);
1687 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1688 int position = ((PreviewMediaFragment)details).getPosition();
1689 startMediaPreview(renamedFile, position, true);
1690 } else {
1691 getFileOperationsHelper().openFile(renamedFile);
1692 }
1693 }
1694 }
1695
1696 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1697 refreshListOfFilesFragment();
1698 }
1699
1700 } else {
1701 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1702 Toast.LENGTH_LONG);
1703 msg.show();
1704
1705 if (result.isSslRecoverableException()) {
1706 mLastSslUntrustedServerResult = result;
1707 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1708 }
1709 }
1710 }
1711
1712 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1713 dismissLoadingDialog();
1714 OCFile syncedFile = operation.getLocalFile();
1715 if (!result.isSuccess()) {
1716 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1717 Intent i = new Intent(this, ConflictsResolveActivity.class);
1718 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1719 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1720 startActivity(i);
1721
1722 }
1723
1724 } else {
1725 if (operation.transferWasRequested()) {
1726 onTransferStateChanged(syncedFile, true, true);
1727
1728 } else {
1729 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1730 Toast.LENGTH_LONG);
1731 msg.show();
1732 }
1733 }
1734 }
1735
1736 /**
1737 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1738 *
1739 * @param operation Creation operation performed.
1740 * @param result Result of the creation.
1741 */
1742 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1743 if (result.isSuccess()) {
1744 dismissLoadingDialog();
1745 refreshListOfFilesFragment();
1746 } else {
1747 dismissLoadingDialog();
1748 try {
1749 Toast msg = Toast.makeText(FileDisplayActivity.this,
1750 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1751 Toast.LENGTH_LONG);
1752 msg.show();
1753
1754 } catch (NotFoundException e) {
1755 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1756 }
1757 }
1758 }
1759
1760
1761 /**
1762 * {@inheritDoc}
1763 */
1764 @Override
1765 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1766 refreshListOfFilesFragment();
1767 FileFragment details = getSecondFragment();
1768 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1769 if (downloading || uploading) {
1770 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1771 } else {
1772 if (!file.fileExists()) {
1773 cleanSecondFragment();
1774 } else {
1775 ((FileDetailFragment)details).updateFileDetails(false, true);
1776 }
1777 }
1778 }
1779
1780 }
1781
1782
1783 private void requestForDownload() {
1784 Account account = getAccount();
1785 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1786 Intent i = new Intent(this, FileDownloader.class);
1787 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1788 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1789 startService(i);
1790 }
1791 }
1792
1793
1794 private OCFile getCurrentDir() {
1795 OCFile file = getFile();
1796 if (file != null) {
1797 if (file.isFolder()) {
1798 return file;
1799 } else if (getStorageManager() != null) {
1800 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1801 return getStorageManager().getFileByPath(parentPath);
1802 }
1803 }
1804 return null;
1805 }
1806
1807 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1808 long currentSyncTime = System.currentTimeMillis();
1809
1810 mSyncInProgress = true;
1811
1812 // perform folder synchronization
1813 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1814 currentSyncTime,
1815 false,
1816 getFileOperationsHelper().isSharedSupported(),
1817 ignoreETag,
1818 getStorageManager(),
1819 getAccount(),
1820 getApplicationContext()
1821 );
1822 synchFolderOp.execute(getAccount(), this, null, null);
1823
1824 setSupportProgressBarIndeterminateVisibility(true);
1825
1826 setBackgroundText();
1827 }
1828
1829 /**
1830 * Show untrusted cert dialog
1831 */
1832 public void showUntrustedCertDialog(RemoteOperationResult result) {
1833 // Show a dialog with the certificate info
1834 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1835 FragmentManager fm = getSupportFragmentManager();
1836 FragmentTransaction ft = fm.beginTransaction();
1837 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1838 }
1839
1840 private void requestForDownload(OCFile file) {
1841 Account account = getAccount();
1842 if (!mDownloaderBinder.isDownloading(account, file)) {
1843 Intent i = new Intent(this, FileDownloader.class);
1844 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1845 i.putExtra(FileDownloader.EXTRA_FILE, file);
1846 startService(i);
1847 }
1848 }
1849
1850 private void sendDownloadedFile(){
1851 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1852 mWaitingToSend = null;
1853 }
1854
1855
1856 /**
1857 * Requests the download of the received {@link OCFile} , updates the UI
1858 * to monitor the download progress and prepares the activity to send the file
1859 * when the download finishes.
1860 *
1861 * @param file {@link OCFile} to download and preview.
1862 */
1863 public void startDownloadForSending(OCFile file) {
1864 mWaitingToSend = file;
1865 requestForDownload(mWaitingToSend);
1866 boolean hasSecondFragment = (getSecondFragment()!= null);
1867 updateFragmentsVisibility(hasSecondFragment);
1868 }
1869
1870 /**
1871 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1872 *
1873 * @param file Image {@link OCFile} to show.
1874 */
1875 public void startImagePreview(OCFile file) {
1876 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1877 showDetailsIntent.putExtra(EXTRA_FILE, file);
1878 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1879 startActivity(showDetailsIntent);
1880
1881 }
1882
1883 /**
1884 * Stars the preview of an already down media {@link OCFile}.
1885 *
1886 * @param file Media {@link OCFile} to preview.
1887 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1888 * @param autoplay When 'true', the playback will start without user interactions.
1889 */
1890 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1891 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1892 setSecondFragment(mediaFragment);
1893 updateFragmentsVisibility(true);
1894 updateNavigationElementsInActionBar(file);
1895 setFile(file);
1896 }
1897
1898 /**
1899 * Requests the download of the received {@link OCFile} , updates the UI
1900 * to monitor the download progress and prepares the activity to preview
1901 * or open the file when the download finishes.
1902 *
1903 * @param file {@link OCFile} to download and preview.
1904 */
1905 public void startDownloadForPreview(OCFile file) {
1906 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1907 setSecondFragment(detailFragment);
1908 mWaitingToPreview = file;
1909 requestForDownload();
1910 updateFragmentsVisibility(true);
1911 updateNavigationElementsInActionBar(file);
1912 setFile(file);
1913 }
1914
1915
1916 public void cancelTransference(OCFile file) {
1917 getFileOperationsHelper().cancelTransference(file);
1918 if (mWaitingToPreview != null &&
1919 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1920 mWaitingToPreview = null;
1921 }
1922 if (mWaitingToSend != null &&
1923 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1924 mWaitingToSend = null;
1925 }
1926 onTransferStateChanged(file, false, false);
1927 }
1928
1929 @Override
1930 public void onRefresh(boolean ignoreETag) {
1931 refreshList(ignoreETag);
1932 }
1933
1934 @Override
1935 public void onRefresh() {
1936 refreshList(true);
1937 }
1938
1939 private void refreshList(boolean ignoreETag) {
1940 OCFileListFragment listOfFiles = getListOfFilesFragment();
1941 if (listOfFiles != null) {
1942 OCFile folder = listOfFiles.getCurrentFile();
1943 if (folder != null) {
1944 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1945 listDirectory(mFile);*/
1946 startSyncFolderOperation(folder, ignoreETag);
1947 }
1948 }
1949 }
1950
1951 private void sortByDate(boolean ascending){
1952 getListOfFilesFragment().sortByDate(ascending);
1953 }
1954
1955 private void sortBySize(boolean ascending){
1956 getListOfFilesFragment().sortBySize(ascending);
1957 }
1958
1959 private void sortByName(boolean ascending){
1960 getListOfFilesFragment().sortByName(ascending);
1961 }
1962 }