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