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