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