fixed according to review
[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 switchLayout(getFile());
326
327 } else {
328 Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
329 if (getAccount() == null) {
330 Log_OC.wtf(TAG, "\t account is NULL");
331 }
332 if (getFile() == null) {
333 Log_OC.wtf(TAG, "\t file is NULL");
334 }
335 }
336 }
337
338 private void switchLayout(OCFile file){
339 if (DisplayUtils.isGridView(file, getStorageManager())){
340 switchToGridView();
341 } else {
342 switchToListView();
343 }
344 }
345
346 private Fragment chooseInitialSecondFragment(OCFile file) {
347 Fragment secondFragment = null;
348 if (file != null && !file.isFolder()) {
349 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
350 && file.getLastSyncDateForProperties() > 0 // temporal fix
351 ) {
352 int startPlaybackPosition =
353 getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
354 boolean autoplay =
355 getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
356 secondFragment = new PreviewMediaFragment(file, getAccount(),
357 startPlaybackPosition, autoplay);
358
359 } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
360 secondFragment = null;
361 } else {
362 secondFragment = FileDetailFragment.newInstance(file, getAccount());
363 }
364 }
365 return secondFragment;
366 }
367
368
369 /**
370 * Replaces the second fragment managed by the activity with the received as
371 * a parameter.
372 * <p/>
373 * Assumes never will be more than two fragments managed at the same time.
374 *
375 * @param fragment New second Fragment to set.
376 */
377 private void setSecondFragment(Fragment fragment) {
378 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
379 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
380 transaction.commit();
381 }
382
383
384 private void updateFragmentsVisibility(boolean existsSecondFragment) {
385 if (mDualPane) {
386 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
387 mLeftFragmentContainer.setVisibility(View.VISIBLE);
388 }
389 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
390 mRightFragmentContainer.setVisibility(View.VISIBLE);
391 }
392
393 } else if (existsSecondFragment) {
394 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
395 mLeftFragmentContainer.setVisibility(View.GONE);
396 }
397 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
398 mRightFragmentContainer.setVisibility(View.VISIBLE);
399 }
400
401 } else {
402 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
403 mLeftFragmentContainer.setVisibility(View.VISIBLE);
404 }
405 if (mRightFragmentContainer.getVisibility() != View.GONE) {
406 mRightFragmentContainer.setVisibility(View.GONE);
407 }
408 }
409 }
410
411
412 private OCFileListFragment getListOfFilesFragment() {
413 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
414 FileDisplayActivity.TAG_LIST_OF_FILES);
415 if (listOfFiles != null) {
416 return (OCFileListFragment) listOfFiles;
417 }
418 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
419 return null;
420 }
421
422 public FileFragment getSecondFragment() {
423 Fragment second = getSupportFragmentManager().findFragmentByTag(
424 FileDisplayActivity.TAG_SECOND_FRAGMENT);
425 if (second != null) {
426 return (FileFragment) second;
427 }
428 return null;
429 }
430
431 protected void cleanSecondFragment() {
432 Fragment second = getSecondFragment();
433 if (second != null) {
434 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
435 tr.remove(second);
436 tr.commit();
437 }
438 updateFragmentsVisibility(false);
439 updateActionBarTitleAndHomeButton(null);
440 }
441
442 protected void refreshListOfFilesFragment() {
443 OCFileListFragment fileListFragment = getListOfFilesFragment();
444 if (fileListFragment != null) {
445 fileListFragment.listDirectory();
446 // TODO Enable when "On Device" is recovered ?
447 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
448 }
449 }
450
451 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath,
452 boolean success) {
453 FileFragment secondFragment = getSecondFragment();
454 boolean waitedPreview = (mWaitingToPreview != null &&
455 mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
456 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
457 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
458 OCFile fileInFragment = detailsFragment.getFile();
459 if (fileInFragment != null &&
460 !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
461 // the user browsed to other file ; forget the automatic preview
462 mWaitingToPreview = null;
463
464 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
465 // grant that the right panel updates the progress bar
466 detailsFragment.listenForTransferProgress();
467 detailsFragment.updateFileDetails(true, false);
468
469 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
470 // update the right panel
471 boolean detailsFragmentChanged = false;
472 if (waitedPreview) {
473 if (success) {
474 mWaitingToPreview = getStorageManager().getFileById(
475 mWaitingToPreview.getFileId()); // update the file from database,
476 // for the local storage path
477 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
478 startMediaPreview(mWaitingToPreview, 0, true);
479 detailsFragmentChanged = true;
480 } else if (PreviewTextFragment.canBePreviewed(mWaitingToPreview)) {
481 startTextPreview(mWaitingToPreview);
482 detailsFragmentChanged = true;
483 } else {
484 getFileOperationsHelper().openFile(mWaitingToPreview);
485 }
486 }
487 mWaitingToPreview = null;
488 }
489 if (!detailsFragmentChanged) {
490 detailsFragment.updateFileDetails(false, (success));
491 }
492 }
493 }
494 }
495
496 @Override
497 public boolean onPrepareOptionsMenu(Menu menu) {
498 boolean drawerOpen = mDrawerLayout.isDrawerOpen(GravityCompat.START);
499 menu.findItem(R.id.action_upload).setVisible(!drawerOpen);
500 menu.findItem(R.id.action_create_dir).setVisible(!drawerOpen);
501 menu.findItem(R.id.action_sort).setVisible(!drawerOpen);
502 menu.findItem(R.id.action_sync_account).setVisible(!drawerOpen);
503 menu.findItem(R.id.action_switch_view).setVisible(!drawerOpen);
504
505 return super.onPrepareOptionsMenu(menu);
506 }
507
508 @Override
509 public boolean onCreateOptionsMenu(Menu menu) {
510 MenuInflater inflater = getMenuInflater();
511 inflater.inflate(R.menu.main_menu, menu);
512 mOptionsMenu = menu;
513
514 MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view);
515
516 changeGridIcon();
517
518 return true;
519 }
520
521
522 @Override
523 public boolean onOptionsItemSelected(MenuItem item) {
524 boolean retval = true;
525 switch (item.getItemId()) {
526 case R.id.action_create_dir: {
527 CreateFolderDialogFragment dialog =
528 CreateFolderDialogFragment.newInstance(getCurrentDir());
529 dialog.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
530 break;
531 }
532
533 case R.id.action_sync_account: {
534 startSynchronization();
535 break;
536 }
537 case R.id.action_upload: {
538 UploadSourceDialogFragment dialog =
539 UploadSourceDialogFragment.newInstance(getAccount());
540 dialog.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE);
541 break;
542 }
543 case android.R.id.home: {
544 FileFragment second = getSecondFragment();
545 OCFile currentDir = getCurrentDir();
546 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
547 mDrawerLayout.closeDrawer(GravityCompat.START);
548 } else if((currentDir != null && currentDir.getParentId() != 0) ||
549 (second != null && second.getFile() != null)) {
550 onBackPressed();
551
552 } else {
553 mDrawerLayout.openDrawer(GravityCompat.START);
554 }
555 break;
556 }
557 case R.id.action_sort: {
558 SharedPreferences appPreferences = PreferenceManager
559 .getDefaultSharedPreferences(this);
560
561 // Read sorting order, default to sort by name ascending
562 Integer sortOrder = appPreferences
563 .getInt("sortOrder", FileStorageUtils.SORT_NAME);
564
565 AlertDialog.Builder builder = new AlertDialog.Builder(this);
566 builder.setTitle(R.string.actionbar_sort_title)
567 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder ,
568 new DialogInterface.OnClickListener() {
569 public void onClick(DialogInterface dialog, int which) {
570 switch (which){
571 case 0:
572 sortByName(true);
573 break;
574 case 1:
575 sortByDate(false);
576 break;
577 }
578
579 dialog.dismiss();
580 }
581 });
582 builder.create().show();
583 break;
584 }
585 case R.id.action_switch_view:{
586 if (isGridView()){
587 item.setTitle(getApplicationContext().getString(R.string.action_switch_grid_view));
588 item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
589 R.drawable.ic_view_module));
590 DisplayUtils.setViewMode(getFile(), false);
591 switchToListView();
592 } else {
593 item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
594 item.setIcon(ContextCompat.getDrawable(getApplicationContext(),
595 R.drawable.ic_view_list));
596 DisplayUtils.setViewMode(getFile(), true);
597 switchToGridView();
598 }
599
600 return true;
601 }
602 default:
603 retval = super.onOptionsItemSelected(item);
604 }
605 return retval;
606 }
607
608 private void startSynchronization() {
609 Log_OC.d(TAG, "Got to start sync");
610 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
611 Log_OC.d(TAG, "Canceling all syncs for " + MainApp.getAuthority());
612 ContentResolver.cancelSync(null, MainApp.getAuthority());
613 // cancel the current synchronizations of any ownCloud account
614 Bundle bundle = new Bundle();
615 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
616 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
617 Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
618 MainApp.getAuthority());
619 ContentResolver.requestSync(
620 getAccount(),
621 MainApp.getAuthority(), bundle);
622 } else {
623 Log_OC.d(TAG, "Requesting sync for " + getAccount().name + " at " +
624 MainApp.getAuthority() + " with new API");
625 SyncRequest.Builder builder = new SyncRequest.Builder();
626 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
627 builder.setExpedited(true);
628 builder.setManual(true);
629 builder.syncOnce();
630
631 // Fix bug in Android Lollipop when you click on refresh the whole account
632 Bundle extras = new Bundle();
633 builder.setExtras(extras);
634
635 SyncRequest request = builder.build();
636 ContentResolver.requestSync(request);
637 }
638 }
639
640 /**
641 * Called, when the user selected something for uploading
642 *
643 */
644 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
645 @Override
646 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
647
648 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK ||
649 resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
650 //getClipData is only supported on api level 16+, Jelly Bean
651 if (data.getData() == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
652 for( int i = 0; i < data.getClipData().getItemCount(); i++){
653 Intent intent = new Intent();
654 intent.setData(data.getClipData().getItemAt(i).getUri());
655 requestSimpleUpload(intent, resultCode);
656 }
657 }else {
658 requestSimpleUpload(data, resultCode);
659 }
660 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK ||
661 resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
662 requestMultipleUpload(data, resultCode);
663
664 } else if (requestCode == ACTION_MOVE_FILES && resultCode == RESULT_OK){
665 final Intent fData = data;
666 final int fResultCode = resultCode;
667 getHandler().postDelayed(
668 new Runnable() {
669 @Override
670 public void run() {
671 requestMoveOperation(fData, fResultCode);
672 }
673 },
674 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
675 );
676
677 } else if (requestCode == ACTION_COPY_FILES && resultCode == RESULT_OK) {
678
679 final Intent fData = data;
680 final int fResultCode = resultCode;
681 getHandler().postDelayed(
682 new Runnable() {
683 @Override
684 public void run() {
685 requestCopyOperation(fData, fResultCode);
686 }
687 },
688 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
689 );
690
691 } else {
692 super.onActivityResult(requestCode, resultCode, data);
693 }
694
695 }
696
697 private void requestMultipleUpload(Intent data, int resultCode) {
698 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
699 if (filePaths != null) {
700 String[] remotePaths = new String[filePaths.length];
701 String remotePathBase = getCurrentDir().getRemotePath();
702 for (int j = 0; j< remotePaths.length; j++) {
703 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
704 }
705
706 Intent i = new Intent(this, FileUploader.class);
707 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
708 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
709 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
710 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
711 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
712 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
713 startService(i);
714
715 } else {
716 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
717 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected),
718 Toast.LENGTH_LONG);
719 t.show();
720 return;
721 }
722 }
723
724
725 private void requestSimpleUpload(Intent data, int resultCode) {
726 String filePath = null;
727 String mimeType = null;
728
729 Uri selectedImageUri = data.getData();
730
731 try {
732 mimeType = getContentResolver().getType(selectedImageUri);
733
734 String fileManagerString = selectedImageUri.getPath();
735 String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);
736
737 if (selectedImagePath != null)
738 filePath = selectedImagePath;
739 else
740 filePath = fileManagerString;
741
742 } catch (Exception e) {
743 Log_OC.e(TAG, "Unexpected exception when trying to read the result of " +
744 "Intent.ACTION_GET_CONTENT", e);
745
746 } finally {
747 if (filePath == null) {
748 Log_OC.e(TAG, "Couldn't resolve path to file");
749 Toast t = Toast.makeText(
750 this, getString(R.string.filedisplay_unexpected_bad_get_content),
751 Toast.LENGTH_LONG
752 );
753 t.show();
754 return;
755 }
756 }
757
758 Intent i = new Intent(this, FileUploader.class);
759 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
760 OCFile currentDir = getCurrentDir();
761 String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;
762
763 if (filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
764 Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
765 try {
766 if (cursor != null && cursor.moveToFirst()) {
767 String displayName = cursor.getString(cursor.getColumnIndex(
768 OpenableColumns.DISPLAY_NAME));
769 Log_OC.v(TAG, "Display Name: " + displayName );
770
771 displayName.replace(File.separatorChar, '_');
772 displayName.replace(File.pathSeparatorChar, '_');
773 remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);
774
775 }
776 // and what happens in case of error?; wrong target name for the upload
777 } finally {
778 cursor.close();
779 }
780
781 } else {
782 remotePath += new File(filePath).getName();
783 }
784
785 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
786 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
787 i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
788 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
789 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
790 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
791 startService(i);
792 }
793
794 /**
795 * Request the operation for moving the file/folder from one path to another
796 *
797 * @param data Intent received
798 * @param resultCode Result code received
799 */
800 private void requestMoveOperation(Intent data, int resultCode) {
801 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
802 OCFile targetFile = (OCFile) data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
803 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
804 }
805
806 /**
807 * Request the operation for copying the file/folder from one path to another
808 *
809 * @param data Intent received
810 * @param resultCode Result code received
811 */
812 private void requestCopyOperation(Intent data, int resultCode) {
813 OCFile folderToMoveAt = data.getParcelableExtra(FolderPickerActivity.EXTRA_FOLDER);
814 OCFile targetFile = data.getParcelableExtra(FolderPickerActivity.EXTRA_FILE);
815 getFileOperationsHelper().copyFile(folderToMoveAt, targetFile);
816 }
817
818 @Override
819 public void onBackPressed() {
820 if (!isDrawerOpen()){
821 OCFileListFragment listOfFiles = getListOfFilesFragment();
822 if (mDualPane || getSecondFragment() == null) {
823 OCFile currentDir = getCurrentDir();
824 if (currentDir == null || currentDir.getParentId() == FileDataStorageManager.ROOT_PARENT_ID) {
825 finish();
826 return;
827 }
828 if (listOfFiles != null) { // should never be null, indeed
829 listOfFiles.onBrowseUp();
830 }
831 }
832 if (listOfFiles != null) { // should never be null, indeed
833 setFile(listOfFiles.getCurrentFile());
834 }
835 cleanSecondFragment();
836
837 changeGridIcon();
838 } else {
839 super.onBackPressed();
840 }
841 }
842
843 private void changeGridIcon(){
844 MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view);
845 if (DisplayUtils.isGridView(getFile(), getStorageManager())){
846 menuItem.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
847 menuItem.setIcon(ContextCompat.getDrawable(getApplicationContext(),
848 R.drawable.ic_view_list));
849 } else {
850 menuItem.setTitle(getApplicationContext().getString(R.string.action_switch_grid_view));
851 menuItem.setIcon(ContextCompat.getDrawable(getApplicationContext(),
852 R.drawable.ic_view_module));
853 }
854 }
855
856 @Override
857 protected void onSaveInstanceState(Bundle outState) {
858 // responsibility of restore is preferred in onCreate() before than in
859 // onRestoreInstanceState when there are Fragments involved
860 Log_OC.v(TAG, "onSaveInstanceState() start");
861 super.onSaveInstanceState(outState);
862 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
863 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
864 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
865 // mRefreshSharesInProgress);
866 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
867
868 Log_OC.v(TAG, "onSaveInstanceState() end");
869 }
870
871
872 @Override
873 protected void onResume() {
874 Log_OC.v(TAG, "onResume() start");
875 super.onResume();
876 // refresh Navigation Drawer account list
877 mNavigationDrawerAdapter.updateAccountList();
878
879 // refresh list of files
880 refreshListOfFilesFragment();
881
882 // Listen for sync messages
883 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
884 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
885 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
886 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
887 syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
888 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
889 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
890 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
891 // syncIntentFilter);
892
893 // Listen for upload messages
894 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
895 mUploadFinishReceiver = new UploadFinishReceiver();
896 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
897
898 // Listen for download messages
899 IntentFilter downloadIntentFilter = new IntentFilter(
900 FileDownloader.getDownloadAddedMessage());
901 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
902 mDownloadFinishReceiver = new DownloadFinishReceiver();
903 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
904
905 Log_OC.v(TAG, "onResume() end");
906
907 }
908
909
910 @Override
911 protected void onPause() {
912 Log_OC.v(TAG, "onPause() start");
913 if (mSyncBroadcastReceiver != null) {
914 unregisterReceiver(mSyncBroadcastReceiver);
915 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
916 mSyncBroadcastReceiver = null;
917 }
918 if (mUploadFinishReceiver != null) {
919 unregisterReceiver(mUploadFinishReceiver);
920 mUploadFinishReceiver = null;
921 }
922 if (mDownloadFinishReceiver != null) {
923 unregisterReceiver(mDownloadFinishReceiver);
924 mDownloadFinishReceiver = null;
925 }
926
927 super.onPause();
928 Log_OC.v(TAG, "onPause() end");
929 }
930
931
932 private class SyncBroadcastReceiver extends BroadcastReceiver {
933
934 /**
935 * {@link BroadcastReceiver} to enable syncing feedback in UI
936 */
937 @Override
938 public void onReceive(Context context, Intent intent) {
939 try {
940 String event = intent.getAction();
941 Log_OC.d(TAG, "Received broadcast " + event);
942 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
943 String synchFolderRemotePath =
944 intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
945 RemoteOperationResult synchResult =
946 (RemoteOperationResult)intent.getSerializableExtra(
947 FileSyncAdapter.EXTRA_RESULT);
948 boolean sameAccount = (getAccount() != null &&
949 accountName.equals(getAccount().name) && getStorageManager() != null);
950
951 if (sameAccount) {
952
953 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
954 mSyncInProgress = true;
955
956 } else {
957 OCFile currentFile = (getFile() == null) ? null :
958 getStorageManager().getFileByPath(getFile().getRemotePath());
959 OCFile currentDir = (getCurrentDir() == null) ? null :
960 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
961
962 if (currentDir == null) {
963 // current folder was removed from the server
964 Toast.makeText( FileDisplayActivity.this,
965 String.format(
966 getString(R.string.
967 sync_current_folder_was_removed),
968 synchFolderRemotePath),
969 Toast.LENGTH_LONG)
970 .show();
971
972 browseToRoot();
973
974 } else {
975 if (currentFile == null && !getFile().isFolder()) {
976 // currently selected file was removed in the server, and now we
977 // know it
978 cleanSecondFragment();
979 currentFile = currentDir;
980 }
981
982 if (synchFolderRemotePath != null &&
983 currentDir.getRemotePath().equals(synchFolderRemotePath)) {
984 OCFileListFragment fileListFragment = getListOfFilesFragment();
985 if (fileListFragment != null) {
986 fileListFragment.listDirectory();
987 // TODO Enable when "On Device" is recovered ?
988 // fileListFragment.listDirectory(currentDir,
989 // MainApp.getOnlyOnDevice());
990 }
991 }
992 setFile(currentFile);
993 }
994
995 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
996 !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED
997 .equals(event));
998
999 if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
1000 equals(event) &&/// TODO refactor and make common
1001
1002 synchResult != null && !synchResult.isSuccess() &&
1003 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
1004 synchResult.isIdPRedirection() ||
1005 (synchResult.isException() && synchResult.getException()
1006 instanceof AuthenticatorException))) {
1007
1008
1009 try {
1010 OwnCloudClient client;
1011 OwnCloudAccount ocAccount =
1012 new OwnCloudAccount(getAccount(), context);
1013 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1014 removeClientFor(ocAccount));
1015 if (client != null) {
1016 OwnCloudCredentials cred = client.getCredentials();
1017 if (cred != null) {
1018 AccountManager am = AccountManager.get(context);
1019 if (cred.authTokenExpires()) {
1020 am.invalidateAuthToken(
1021 getAccount().type,
1022 cred.getAuthToken()
1023 );
1024 } else {
1025 am.clearPassword(getAccount());
1026 }
1027 }
1028 }
1029 requestCredentialsUpdate();
1030
1031 } catch (AccountNotFoundException e) {
1032 Log_OC.e(TAG, "Account " + getAccount() + " was removed!", e);
1033 }
1034
1035 }
1036 }
1037 removeStickyBroadcast(intent);
1038 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1039 mProgressBar.setIndeterminate(mSyncInProgress);
1040 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1041 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1042 /*|| mRefreshSharesInProgress*/ //);
1043
1044 setBackgroundText();
1045
1046 }
1047
1048 if (synchResult != null) {
1049 if (synchResult.getCode().equals(
1050 RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1051 mLastSslUntrustedServerResult = synchResult;
1052 }
1053 }
1054 } catch (RuntimeException e) {
1055 // avoid app crashes after changing the serial id of RemoteOperationResult
1056 // in owncloud library with broadcast notifications pending to process
1057 removeStickyBroadcast(intent);
1058 }
1059 }
1060 }
1061
1062 /**
1063 * Show a text message on screen view for notifying user if content is
1064 * loading or folder is empty
1065 */
1066 private void setBackgroundText() {
1067 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1068 if (ocFileListFragment != null) {
1069 int message = R.string.file_list_loading;
1070 if (!mSyncInProgress) {
1071 // In case file list is empty
1072 message = R.string.file_list_empty;
1073 }
1074 ocFileListFragment.setMessageForEmptyList(getString(message));
1075 } else {
1076 Log_OC.e(TAG, "OCFileListFragment is null");
1077 }
1078 }
1079
1080 /**
1081 * Once the file upload has finished -> update view
1082 */
1083 private class UploadFinishReceiver extends BroadcastReceiver {
1084 /**
1085 * Once the file upload has finished -> update view
1086 *
1087 * @author David A. Velasco
1088 * {@link BroadcastReceiver} to enable upload feedback in UI
1089 */
1090 @Override
1091 public void onReceive(Context context, Intent intent) {
1092 try {
1093 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1094 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1095 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1096 OCFile currentDir = getCurrentDir();
1097 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1098 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1099
1100 if (sameAccount && isDescendant) {
1101 refreshListOfFilesFragment();
1102 }
1103
1104 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT,
1105 false);
1106 boolean renamedInUpload = getFile().getRemotePath().
1107 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1108 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1109 renamedInUpload;
1110 FileFragment details = getSecondFragment();
1111 boolean detailFragmentIsShown = (details != null &&
1112 details instanceof FileDetailFragment);
1113
1114 if (sameAccount && sameFile && detailFragmentIsShown) {
1115 if (uploadWasFine) {
1116 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1117 }
1118 if (renamedInUpload) {
1119 String newName = (new File(uploadedRemotePath)).getName();
1120 Toast msg = Toast.makeText(
1121 context,
1122 String.format(
1123 getString(R.string.filedetails_renamed_in_upload_msg),
1124 newName),
1125 Toast.LENGTH_LONG);
1126 msg.show();
1127 }
1128 if (uploadWasFine || getFile().fileExists()) {
1129 ((FileDetailFragment) details).updateFileDetails(false, true);
1130 } else {
1131 cleanSecondFragment();
1132 }
1133
1134 // Force the preview if the file is an image or text file
1135 if (uploadWasFine) {
1136 OCFile ocFile = getFile();
1137 if (PreviewImageFragment.canBePreviewed(ocFile))
1138 startImagePreview(getFile());
1139 else if (PreviewTextFragment.canBePreviewed(ocFile))
1140 startTextPreview(ocFile);
1141 // TODO what about other kind of previews?
1142 }
1143 }
1144
1145 mProgressBar.setIndeterminate(false);
1146 } finally {
1147 if (intent != null) {
1148 removeStickyBroadcast(intent);
1149 }
1150 }
1151
1152 }
1153
1154 }
1155
1156
1157 /**
1158 * Class waiting for broadcast events from the {@link FileDownloader} service.
1159 *
1160 * Updates the UI when a download is started or finished, provided that it is relevant for the
1161 * current folder.
1162 */
1163 private class DownloadFinishReceiver extends BroadcastReceiver {
1164
1165 //int refreshCounter = 0;
1166 @Override
1167 public void onReceive(Context context, Intent intent) {
1168 try {
1169 boolean sameAccount = isSameAccount(context, intent);
1170 String downloadedRemotePath =
1171 intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1172 boolean isDescendant = isDescendant(downloadedRemotePath);
1173
1174 if (sameAccount && isDescendant) {
1175 String linkedToRemotePath =
1176 intent.getStringExtra(FileDownloader.EXTRA_LINKED_TO_PATH);
1177 if (linkedToRemotePath == null || isAscendant(linkedToRemotePath)) {
1178 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1179 refreshListOfFilesFragment();
1180 }
1181 refreshSecondFragment(
1182 intent.getAction(),
1183 downloadedRemotePath,
1184 intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)
1185 );
1186 }
1187
1188 if (mWaitingToSend != null) {
1189 mWaitingToSend =
1190 getStorageManager().getFileByPath(mWaitingToSend.getRemotePath());
1191 if (mWaitingToSend.isDown()) {
1192 sendDownloadedFile();
1193 }
1194 }
1195
1196 } finally {
1197 if (intent != null) {
1198 removeStickyBroadcast(intent);
1199 }
1200 }
1201 }
1202
1203 private boolean isDescendant(String downloadedRemotePath) {
1204 OCFile currentDir = getCurrentDir();
1205 return (
1206 currentDir != null &&
1207 downloadedRemotePath != null &&
1208 downloadedRemotePath.startsWith(currentDir.getRemotePath())
1209 );
1210 }
1211
1212 private boolean isAscendant(String linkedToRemotePath) {
1213 OCFile currentDir = getCurrentDir();
1214 return (
1215 currentDir != null &&
1216 currentDir.getRemotePath().startsWith(linkedToRemotePath)
1217 );
1218 }
1219
1220 private boolean isSameAccount(Context context, Intent intent) {
1221 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1222 return (accountName != null && getAccount() != null &&
1223 accountName.equals(getAccount().name));
1224 }
1225 }
1226
1227
1228 public void browseToRoot() {
1229 OCFileListFragment listOfFiles = getListOfFilesFragment();
1230 if (listOfFiles != null) { // should never be null, indeed
1231 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1232 listOfFiles.listDirectory(root);
1233 // TODO Enable when "On Device" is recovered ?
1234 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1235 setFile(listOfFiles.getCurrentFile());
1236 startSyncFolderOperation(root, false);
1237 }
1238 cleanSecondFragment();
1239 }
1240
1241
1242 /**
1243 * {@inheritDoc}
1244 * <p/>
1245 * Updates action bar and second fragment, if in dual pane mode.
1246 */
1247 @Override
1248 public void onBrowsedDownTo(OCFile directory) {
1249 setFile(directory);
1250 cleanSecondFragment();
1251 // Sync Folder
1252 startSyncFolderOperation(directory, false);
1253
1254 MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view);
1255
1256 changeGridIcon();
1257 switchLayout(directory);
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 }