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