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