2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
23 package com
.owncloud
.android
.ui
.activity
;
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
;
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
.CreateShareViaLinkOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareWithShareeOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.UnshareOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 import com
.owncloud
.android
.utils
.FileStorageUtils
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
117 implements FileFragment
.ContainerActivity
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
128 private ProgressBar mProgressBar
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 public static final int ACTION_MOVE_FILES
= 3;
139 public static final int ACTION_COPY_FILES
= 4;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
151 public static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
155 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.v(TAG
, "onCreate() start");
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
165 /// grant that FileObserverService is watching favorite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
177 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
192 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
193 mProgressBar
.setIndeterminateDrawable(
194 ContextCompat
.getDrawable(this,
195 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
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();
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
206 // according to the official
209 // enable ActionBar app icon to behave as action to toggle nav drawer
210 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
211 getSupportActionBar().setHomeButtonEnabled(true
);
213 mProgressBar
.setIndeterminate(mSyncInProgress
);
214 // always AFTER setContentView(...) ; to work around bug in its implementation
218 Log_OC
.v(TAG
, "onCreate() end");
222 protected void onStart() {
223 Log_OC
.v(TAG
, "onStart() start");
225 Log_OC
.v(TAG
, "onStart() end");
229 protected void onStop() {
230 Log_OC
.v(TAG
, "onStop() start");
232 Log_OC
.v(TAG
, "onStop() end");
236 protected void onDestroy() {
237 Log_OC
.v(TAG
, "onDestroy() start");
239 Log_OC
.v(TAG
, "onDestroy() end");
243 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
246 protected void onAccountSet(boolean stateWasRecovered
) {
247 super.onAccountSet(stateWasRecovered
);
248 if (getAccount() != null
) {
249 /// Check whether the 'main' OCFile handled by the Activity is contained in the
251 OCFile file
= getFile();
252 // get parent from path
253 String parentPath
= "";
255 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
256 // upload in progress - right now, files are not inserted in the local
257 // cache until the upload is successful get parent from path
258 parentPath
= file
.getRemotePath().substring(0,
259 file
.getRemotePath().lastIndexOf(file
.getFileName()));
260 if (getStorageManager().getFileByPath(parentPath
) == null
)
261 file
= null
; // not able to know the directory where the file is uploading
263 file
= getStorageManager().getFileByPath(file
.getRemotePath());
264 // currentDir = null if not in the current Account
268 // fall back to root folder
269 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
273 if (mAccountWasSet
) {
274 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
277 if (!stateWasRecovered
) {
278 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
279 initFragmentsWithFile();
280 if (file
.isFolder()) {
281 startSyncFolderOperation(file
, false
);
285 updateFragmentsVisibility(!file
.isFolder());
286 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
291 private void createMinFragments() {
292 OCFileListFragment listOfFiles
= new OCFileListFragment();
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
295 transaction
.commit();
298 private void initFragmentsWithFile() {
299 if (getAccount() != null
&& getFile() != null
) {
301 OCFileListFragment listOfFiles
= getListOfFilesFragment();
302 if (listOfFiles
!= null
) {
303 listOfFiles
.listDirectory(getCurrentDir());
304 // TODO Enable when "On Device" is recovered
305 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
308 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
312 OCFile file
= getFile();
313 Fragment secondFragment
= chooseInitialSecondFragment(file
);
314 if (secondFragment
!= null
) {
315 setSecondFragment(secondFragment
);
316 updateFragmentsVisibility(true
);
317 updateActionBarTitleAndHomeButton(file
);
320 cleanSecondFragment();
321 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
322 startTextPreview(file
);
326 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
327 if (getAccount() == null
) {
328 Log_OC
.wtf(TAG
, "\t account is NULL");
330 if (getFile() == null
) {
331 Log_OC
.wtf(TAG
, "\t file is NULL");
336 private Fragment
chooseInitialSecondFragment(OCFile file
) {
337 Fragment secondFragment
= null
;
338 if (file
!= null
&& !file
.isFolder()) {
339 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
340 && file
.getLastSyncDateForProperties() > 0 // temporal fix
342 int startPlaybackPosition
=
343 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
345 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
346 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
347 startPlaybackPosition
, autoplay
);
349 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
350 secondFragment
= null
;
352 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
355 return secondFragment
;
360 * Replaces the second fragment managed by the activity with the received as
363 * Assumes never will be more than two fragments managed at the same time.
365 * @param fragment New second Fragment to set.
367 private void setSecondFragment(Fragment fragment
) {
368 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
369 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
370 transaction
.commit();
374 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
376 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
383 } else if (existsSecondFragment
) {
384 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
385 mLeftFragmentContainer
.setVisibility(View
.GONE
);
387 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
388 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
392 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
393 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
395 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
396 mRightFragmentContainer
.setVisibility(View
.GONE
);
402 private OCFileListFragment
getListOfFilesFragment() {
403 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
404 FileDisplayActivity
.TAG_LIST_OF_FILES
);
405 if (listOfFiles
!= null
) {
406 return (OCFileListFragment
) listOfFiles
;
408 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
412 public FileFragment
getSecondFragment() {
413 Fragment second
= getSupportFragmentManager().findFragmentByTag(
414 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
415 if (second
!= null
) {
416 return (FileFragment
) second
;
421 protected void cleanSecondFragment() {
422 Fragment second
= getSecondFragment();
423 if (second
!= null
) {
424 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
428 updateFragmentsVisibility(false
);
429 updateActionBarTitleAndHomeButton(null
);
432 protected void refreshListOfFilesFragment() {
433 OCFileListFragment fileListFragment
= getListOfFilesFragment();
434 if (fileListFragment
!= null
) {
435 fileListFragment
.listDirectory();
436 // TODO Enable when "On Device" is recovered ?
437 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
441 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
443 FileFragment secondFragment
= getSecondFragment();
444 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
445 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
446 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
447 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
448 OCFile fileInFragment
= detailsFragment
.getFile();
449 if (fileInFragment
!= null
&&
450 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
451 // the user browsed to other file ; forget the automatic preview
452 mWaitingToPreview
= null
;
454 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
455 // grant that the right panel updates the progress bar
456 detailsFragment
.listenForTransferProgress();
457 detailsFragment
.updateFileDetails(true
, false
);
459 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
460 // update the right panel
461 boolean detailsFragmentChanged
= false
;
464 mWaitingToPreview
= getStorageManager().getFileById(
465 mWaitingToPreview
.getFileId()); // update the file from database,
466 // for the local storage path
467 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
468 startMediaPreview(mWaitingToPreview
, 0, true
);
469 detailsFragmentChanged
= true
;
470 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
471 startTextPreview(mWaitingToPreview
);
472 detailsFragmentChanged
= true
;
474 getFileOperationsHelper().openFile(mWaitingToPreview
);
477 mWaitingToPreview
= null
;
479 if (!detailsFragmentChanged
) {
480 detailsFragment
.updateFileDetails(false
, (success
));
487 public boolean onPrepareOptionsMenu(Menu menu
) {
488 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
489 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
492 return super.onPrepareOptionsMenu(menu
);
496 public boolean onCreateOptionsMenu(Menu menu
) {
497 MenuInflater inflater
= getMenuInflater();
498 inflater
.inflate(R
.menu
.main_menu
, menu
);
499 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
505 public boolean onOptionsItemSelected(MenuItem item
) {
506 boolean retval
= true
;
507 switch (item
.getItemId()) {
508 case R
.id
.action_sync_account
: {
509 startSynchronization();
512 case android
.R
.id
.home
: {
513 FileFragment second
= getSecondFragment();
514 OCFile currentDir
= getCurrentDir();
515 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
516 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
517 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
518 (second
!= null
&& second
.getFile() != null
)) {
522 mDrawerLayout
.openDrawer(GravityCompat
.START
);
526 case R
.id
.action_sort
: {
527 SharedPreferences appPreferences
= PreferenceManager
528 .getDefaultSharedPreferences(this);
530 // Read sorting order, default to sort by name ascending
531 Integer sortOrder
= appPreferences
532 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
534 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
535 builder
.setTitle(R
.string
.actionbar_sort_title
)
536 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
537 new DialogInterface
.OnClickListener() {
538 public void onClick(DialogInterface dialog
, int which
) {
551 builder
.create().show();
555 retval
= super.onOptionsItemSelected(item
);
560 public void createFolder() {
561 CreateFolderDialogFragment dialog
=
562 CreateFolderDialogFragment
.newInstance(getCurrentDir());
563 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
566 public void uploadLocalFilesSelected() {
567 Intent action
= new Intent(this, UploadFilesActivity
.class);
569 UploadFilesActivity
.EXTRA_ACCOUNT
,
572 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
575 public void uploadFromOtherAppsSelected() {
576 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
577 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
578 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
579 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
580 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
582 startActivityForResult(
583 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
584 ACTION_SELECT_CONTENT_FROM_APPS
588 private void startSynchronization() {
589 Log_OC
.d(TAG
, "Got to start sync");
590 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
591 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
592 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
593 // cancel the current synchronizations of any ownCloud account
594 Bundle bundle
= new Bundle();
595 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
596 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
597 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
598 MainApp
.getAuthority());
599 ContentResolver
.requestSync(
601 MainApp
.getAuthority(), bundle
);
603 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
604 MainApp
.getAuthority() + " with new API");
605 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
606 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
607 builder
.setExpedited(true
);
608 builder
.setManual(true
);
611 // Fix bug in Android Lollipop when you click on refresh the whole account
612 Bundle extras
= new Bundle();
613 builder
.setExtras(extras
);
615 SyncRequest request
= builder
.build();
616 ContentResolver
.requestSync(request
);
621 * Called, when the user selected something for uploading
624 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
626 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
628 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
629 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
630 //getClipData is only supported on api level 16+, Jelly Bean
631 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
632 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
633 Intent intent
= new Intent();
634 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
635 requestSimpleUpload(intent
, resultCode
);
638 requestSimpleUpload(data
, resultCode
);
640 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
641 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
642 requestMultipleUpload(data
, resultCode
);
644 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
645 final Intent fData
= data
;
646 final int fResultCode
= resultCode
;
647 getHandler().postDelayed(
651 requestMoveOperation(fData
, fResultCode
);
654 DELAY_TO_REQUEST_OPERATIONS_LATER
657 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
659 final Intent fData
= data
;
660 final int fResultCode
= resultCode
;
661 getHandler().postDelayed(
665 requestCopyOperation(fData
, fResultCode
);
668 DELAY_TO_REQUEST_OPERATIONS_LATER
672 super.onActivityResult(requestCode
, resultCode
, data
);
677 private void requestMultipleUpload(Intent data
, int resultCode
) {
678 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
679 if (filePaths
!= null
) {
680 String
[] remotePaths
= new String
[filePaths
.length
];
681 String remotePathBase
= getCurrentDir().getRemotePath();
682 for (int j
= 0; j
< remotePaths
.length
; j
++) {
683 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
686 Intent i
= new Intent(this, FileUploader
.class);
687 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
688 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
689 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
690 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
691 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
692 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
696 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
697 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
705 private void requestSimpleUpload(Intent data
, int resultCode
) {
706 String filePath
= null
;
707 String mimeType
= null
;
709 Uri selectedImageUri
= data
.getData();
712 mimeType
= getContentResolver().getType(selectedImageUri
);
714 String fileManagerString
= selectedImageUri
.getPath();
715 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
717 if (selectedImagePath
!= null
)
718 filePath
= selectedImagePath
;
720 filePath
= fileManagerString
;
722 } catch (Exception e
) {
723 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
724 "Intent.ACTION_GET_CONTENT", e
);
727 if (filePath
== null
) {
728 Log_OC
.e(TAG
, "Couldn't resolve path to file");
729 Toast t
= Toast
.makeText(
730 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
738 Intent i
= new Intent(this, FileUploader
.class);
739 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
740 OCFile currentDir
= getCurrentDir();
741 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
743 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
744 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
746 if (cursor
!= null
&& cursor
.moveToFirst()) {
747 String displayName
= cursor
.getString(cursor
.getColumnIndex(
748 OpenableColumns
.DISPLAY_NAME
));
749 Log_OC
.v(TAG
, "Display Name: " + displayName
);
751 displayName
.replace(File
.separatorChar
, '_');
752 displayName
.replace(File
.pathSeparatorChar
, '_');
753 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
756 // and what happens in case of error?; wrong target name for the upload
762 remotePath
+= new File(filePath
).getName();
765 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
766 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
767 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
768 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
769 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
770 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
775 * Request the operation for moving the file/folder from one path to another
777 * @param data Intent received
778 * @param resultCode Result code received
780 private void requestMoveOperation(Intent data
, int resultCode
) {
781 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
782 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
783 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
787 * Request the operation for copying the file/folder from one path to another
789 * @param data Intent received
790 * @param resultCode Result code received
792 private void requestCopyOperation(Intent data
, int resultCode
) {
793 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
794 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
795 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
799 public void onBackPressed() {
800 boolean isFabOpen
= isFabOpen();
801 boolean isDrawerOpen
= isDrawerOpen();
804 * BackPressed priority/hierarchy:
805 * 1. close drawer if opened
806 * 2. close FAB if open (only if drawer isn't open)
807 * 3. navigate up (only if drawer and FAB aren't open)
809 if(isDrawerOpen
&& isFabOpen
) {
810 // close drawer first
811 super.onBackPressed();
812 } else if(isDrawerOpen
&& !isFabOpen
) {
814 super.onBackPressed();
815 } else if (!isDrawerOpen
&& isFabOpen
) {
817 getListOfFilesFragment().getFabMain().collapse();
820 OCFileListFragment listOfFiles
= getListOfFilesFragment();
821 if (mDualPane
|| getSecondFragment() == null
) {
822 OCFile currentDir
= getCurrentDir();
823 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
827 if (listOfFiles
!= null
) { // should never be null, indeed
828 listOfFiles
.onBrowseUp();
831 if (listOfFiles
!= null
) { // should never be null, indeed
832 setFile(listOfFiles
.getCurrentFile());
834 cleanSecondFragment();
839 protected void onSaveInstanceState(Bundle outState
) {
840 // responsibility of restore is preferred in onCreate() before than in
841 // onRestoreInstanceState when there are Fragments involved
842 Log_OC
.v(TAG
, "onSaveInstanceState() start");
843 super.onSaveInstanceState(outState
);
844 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
845 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
846 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
847 // mRefreshSharesInProgress);
848 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
850 Log_OC
.v(TAG
, "onSaveInstanceState() end");
855 protected void onResume() {
856 Log_OC
.v(TAG
, "onResume() start");
858 // refresh Navigation Drawer account list
859 mNavigationDrawerAdapter
.updateAccountList();
861 // refresh list of files
862 refreshListOfFilesFragment();
864 // Listen for sync messages
865 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
866 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
867 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
868 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
869 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
870 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
871 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
872 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
873 // syncIntentFilter);
875 // Listen for upload messages
876 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
877 mUploadFinishReceiver
= new UploadFinishReceiver();
878 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
880 // Listen for download messages
881 IntentFilter downloadIntentFilter
= new IntentFilter(
882 FileDownloader
.getDownloadAddedMessage());
883 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
884 mDownloadFinishReceiver
= new DownloadFinishReceiver();
885 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
887 Log_OC
.v(TAG
, "onResume() end");
893 protected void onPause() {
894 Log_OC
.v(TAG
, "onPause() start");
895 if (mSyncBroadcastReceiver
!= null
) {
896 unregisterReceiver(mSyncBroadcastReceiver
);
897 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
898 mSyncBroadcastReceiver
= null
;
900 if (mUploadFinishReceiver
!= null
) {
901 unregisterReceiver(mUploadFinishReceiver
);
902 mUploadFinishReceiver
= null
;
904 if (mDownloadFinishReceiver
!= null
) {
905 unregisterReceiver(mDownloadFinishReceiver
);
906 mDownloadFinishReceiver
= null
;
910 Log_OC
.v(TAG
, "onPause() end");
913 public boolean isFabOpen() {
914 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
922 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
925 * {@link BroadcastReceiver} to enable syncing feedback in UI
928 public void onReceive(Context context
, Intent intent
) {
930 String event
= intent
.getAction();
931 Log_OC
.d(TAG
, "Received broadcast " + event
);
932 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
933 String synchFolderRemotePath
=
934 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
935 RemoteOperationResult synchResult
=
936 (RemoteOperationResult
)intent
.getSerializableExtra(
937 FileSyncAdapter
.EXTRA_RESULT
);
938 boolean sameAccount
= (getAccount() != null
&&
939 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
943 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
944 mSyncInProgress
= true
;
947 OCFile currentFile
= (getFile() == null
) ? null
:
948 getStorageManager().getFileByPath(getFile().getRemotePath());
949 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
950 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
952 if (currentDir
== null
) {
953 // current folder was removed from the server
954 Toast
.makeText( FileDisplayActivity
.this,
957 sync_current_folder_was_removed
),
958 synchFolderRemotePath
),
965 if (currentFile
== null
&& !getFile().isFolder()) {
966 // currently selected file was removed in the server, and now we
968 cleanSecondFragment();
969 currentFile
= currentDir
;
972 if (synchFolderRemotePath
!= null
&&
973 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
974 OCFileListFragment fileListFragment
= getListOfFilesFragment();
975 if (fileListFragment
!= null
) {
976 fileListFragment
.listDirectory();
977 // TODO Enable when "On Device" is recovered ?
978 // fileListFragment.listDirectory(currentDir,
979 // MainApp.getOnlyOnDevice());
982 setFile(currentFile
);
985 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
986 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
989 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
990 equals(event
) &&/// TODO refactor and make common
992 synchResult
!= null
&& !synchResult
.isSuccess() &&
993 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
994 synchResult
.isIdPRedirection() ||
995 (synchResult
.isException() && synchResult
.getException()
996 instanceof AuthenticatorException
))) {
1000 OwnCloudClient client
;
1001 OwnCloudAccount ocAccount
=
1002 new OwnCloudAccount(getAccount(), context
);
1003 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1004 removeClientFor(ocAccount
));
1005 if (client
!= null
) {
1006 OwnCloudCredentials cred
= client
.getCredentials();
1008 AccountManager am
= AccountManager
.get(context
);
1009 if (cred
.authTokenExpires()) {
1010 am
.invalidateAuthToken(
1015 am
.clearPassword(getAccount());
1019 requestCredentialsUpdate();
1021 } catch (AccountNotFoundException e
) {
1022 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1028 removeStickyBroadcast(intent
);
1029 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1030 mProgressBar
.setIndeterminate(mSyncInProgress
);
1031 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1032 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1033 /*|| mRefreshSharesInProgress*/ //);
1035 setBackgroundText();
1039 if (synchResult
!= null
) {
1040 if (synchResult
.getCode().equals(
1041 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1042 mLastSslUntrustedServerResult
= synchResult
;
1045 } catch (RuntimeException e
) {
1046 // avoid app crashes after changing the serial id of RemoteOperationResult
1047 // in owncloud library with broadcast notifications pending to process
1048 removeStickyBroadcast(intent
);
1054 * Show a text message on screen view for notifying user if content is
1055 * loading or folder is empty
1057 private void setBackgroundText() {
1058 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1059 if (ocFileListFragment
!= null
) {
1060 int message
= R
.string
.file_list_loading
;
1061 if (!mSyncInProgress
) {
1062 // In case file list is empty
1063 message
= R
.string
.file_list_empty
;
1065 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1067 Log_OC
.e(TAG
, "OCFileListFragment is null");
1072 * Once the file upload has finished -> update view
1074 private class UploadFinishReceiver
extends BroadcastReceiver
{
1076 * Once the file upload has finished -> update view
1078 * @author David A. Velasco
1079 * {@link BroadcastReceiver} to enable upload feedback in UI
1082 public void onReceive(Context context
, Intent intent
) {
1084 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1085 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1086 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1087 OCFile currentDir
= getCurrentDir();
1088 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1089 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1091 if (sameAccount
&& isDescendant
) {
1092 String linkedToRemotePath
=
1093 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1094 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1095 refreshListOfFilesFragment();
1099 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1101 boolean renamedInUpload
= getFile().getRemotePath().
1102 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1103 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1105 FileFragment details
= getSecondFragment();
1106 boolean detailFragmentIsShown
= (details
!= null
&&
1107 details
instanceof FileDetailFragment
);
1109 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1110 if (uploadWasFine
) {
1111 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1113 if (renamedInUpload
) {
1114 String newName
= (new File(uploadedRemotePath
)).getName();
1115 Toast msg
= Toast
.makeText(
1118 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1123 if (uploadWasFine
|| getFile().fileExists()) {
1124 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1126 cleanSecondFragment();
1129 // Force the preview if the file is an image or text file
1130 if (uploadWasFine
) {
1131 OCFile ocFile
= getFile();
1132 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1133 startImagePreview(getFile());
1134 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1135 startTextPreview(ocFile
);
1136 // TODO what about other kind of previews?
1140 mProgressBar
.setIndeterminate(false
);
1142 if (intent
!= null
) {
1143 removeStickyBroadcast(intent
);
1149 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1150 private boolean isAscendant(String linkedToRemotePath
) {
1151 OCFile currentDir
= getCurrentDir();
1153 currentDir
!= null
&&
1154 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1163 * Class waiting for broadcast events from the {@link FileDownloader} service.
1165 * Updates the UI when a download is started or finished, provided that it is relevant for the
1168 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1171 public void onReceive(Context context
, Intent intent
) {
1173 boolean sameAccount
= isSameAccount(intent
);
1174 String downloadedRemotePath
=
1175 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1176 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1178 if (sameAccount
&& isDescendant
) {
1179 String linkedToRemotePath
=
1180 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1181 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1182 refreshListOfFilesFragment();
1184 refreshSecondFragment(
1186 downloadedRemotePath
,
1187 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1191 if (mWaitingToSend
!= null
) {
1193 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1194 if (mWaitingToSend
.isDown()) {
1195 sendDownloadedFile();
1200 if (intent
!= null
) {
1201 removeStickyBroadcast(intent
);
1206 private boolean isDescendant(String downloadedRemotePath
) {
1207 OCFile currentDir
= getCurrentDir();
1209 currentDir
!= null
&&
1210 downloadedRemotePath
!= null
&&
1211 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1215 private boolean isAscendant(String linkedToRemotePath
) {
1216 OCFile currentDir
= getCurrentDir();
1218 currentDir
!= null
&&
1219 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1223 private boolean isSameAccount(Intent intent
) {
1224 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1225 return (accountName
!= null
&& getAccount() != null
&&
1226 accountName
.equals(getAccount().name
));
1231 public void browseToRoot() {
1232 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1233 if (listOfFiles
!= null
) { // should never be null, indeed
1234 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1235 listOfFiles
.listDirectory(root
);
1236 // TODO Enable when "On Device" is recovered ?
1237 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1238 setFile(listOfFiles
.getCurrentFile());
1239 startSyncFolderOperation(root
, false
);
1241 cleanSecondFragment();
1248 * Updates action bar and second fragment, if in dual pane mode.
1251 public void onBrowsedDownTo(OCFile directory
) {
1253 cleanSecondFragment();
1255 startSyncFolderOperation(directory
, false
);
1259 * Shows the information of the {@link OCFile} received as a
1260 * parameter in the second fragment.
1262 * @param file {@link OCFile} whose details will be shown
1265 public void showDetails(OCFile file
) {
1266 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1267 setSecondFragment(detailFragment
);
1268 updateFragmentsVisibility(true
);
1269 updateActionBarTitleAndHomeButton(file
);
1274 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1276 // in dual pane mode, keep the focus of title an action bar in the current folder
1277 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1280 super.updateActionBarTitleAndHomeButton(chosenFile
);
1286 protected ServiceConnection
newTransferenceServiceConnection() {
1287 return new ListServiceConnection();
1291 * Defines callbacks for service binding, passed to bindService()
1293 private class ListServiceConnection
implements ServiceConnection
{
1296 public void onServiceConnected(ComponentName component
, IBinder service
) {
1297 if (component
.equals(new ComponentName(
1298 FileDisplayActivity
.this, FileDownloader
.class))) {
1299 Log_OC
.d(TAG
, "Download service connected");
1300 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1301 if (mWaitingToPreview
!= null
)
1302 if (getStorageManager() != null
) {
1305 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1306 if (!mWaitingToPreview
.isDown()) {
1307 requestForDownload();
1311 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1312 FileUploader
.class))) {
1313 Log_OC
.d(TAG
, "Upload service connected");
1314 mUploaderBinder
= (FileUploaderBinder
) service
;
1318 // a new chance to get the mDownloadBinder through
1319 // getFileDownloadBinder() - THIS IS A MESS
1320 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1321 if (listOfFiles
!= null
) {
1322 listOfFiles
.listDirectory();
1323 // TODO Enable when "On Device" is recovered ?
1324 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1326 FileFragment secondFragment
= getSecondFragment();
1327 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1328 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1329 detailFragment
.listenForTransferProgress();
1330 detailFragment
.updateFileDetails(false
, false
);
1335 public void onServiceDisconnected(ComponentName component
) {
1336 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1337 FileDownloader
.class))) {
1338 Log_OC
.d(TAG
, "Download service disconnected");
1339 mDownloaderBinder
= null
;
1340 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1341 FileUploader
.class))) {
1342 Log_OC
.d(TAG
, "Upload service disconnected");
1343 mUploaderBinder
= null
;
1349 public void onSavedCertificate() {
1350 startSyncFolderOperation(getCurrentDir(), false
);
1355 public void onFailedSavingCertificate() {
1356 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1357 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1359 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1363 public void onCancelCertificate() {
1368 * Updates the view associated to the activity after the finish of some operation over files
1369 * in the current account.
1371 * @param operation Removal operation performed.
1372 * @param result Result of the removal.
1375 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1376 super.onRemoteOperationFinish(operation
, result
);
1378 if (operation
instanceof RemoveFileOperation
) {
1379 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1381 } else if (operation
instanceof RenameFileOperation
) {
1382 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1384 } else if (operation
instanceof SynchronizeFileOperation
) {
1385 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1387 } else if (operation
instanceof CreateFolderOperation
) {
1388 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1390 } else if (operation
instanceof CreateShareViaLinkOperation
||
1391 operation
instanceof CreateShareWithShareeOperation
) {
1393 refreshShowDetails();
1394 refreshListOfFilesFragment();
1396 } else if (operation
instanceof UnshareOperation
) {
1397 onUnshareLinkOperationFinish((UnshareOperation
) operation
, result
);
1399 } else if (operation
instanceof MoveFileOperation
) {
1400 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1402 } else if (operation
instanceof CopyFileOperation
) {
1403 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1408 private void onUnshareLinkOperationFinish(UnshareOperation operation
,
1409 RemoteOperationResult result
) {
1410 if (result
.isSuccess()) {
1411 refreshShowDetails();
1412 refreshListOfFilesFragment();
1414 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1415 cleanSecondFragment();
1416 refreshListOfFilesFragment();
1420 private void refreshShowDetails() {
1421 FileFragment details
= getSecondFragment();
1422 if (details
!= null
) {
1423 OCFile file
= details
.getFile();
1425 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1426 if (details
instanceof PreviewMediaFragment
) {
1427 // Refresh OCFile of the fragment
1428 ((PreviewMediaFragment
) details
).updateFile(file
);
1429 } else if (details
instanceof PreviewTextFragment
) {
1430 // Refresh OCFile of the fragment
1431 ((PreviewTextFragment
) details
).updateFile(file
);
1436 invalidateOptionsMenu();
1441 * Updates the view associated to the activity after the finish of an operation trying to
1444 * @param operation Removal operation performed.
1445 * @param result Result of the removal.
1447 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1448 RemoteOperationResult result
) {
1449 Toast msg
= Toast
.makeText(this,
1450 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1454 if (result
.isSuccess()) {
1455 OCFile removedFile
= operation
.getFile();
1456 FileFragment second
= getSecondFragment();
1457 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1458 if (second
instanceof PreviewMediaFragment
) {
1459 ((PreviewMediaFragment
) second
).stopPreview(true
);
1461 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1462 cleanSecondFragment();
1464 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1465 refreshListOfFilesFragment();
1467 invalidateOptionsMenu();
1469 if (result
.isSslRecoverableException()) {
1470 mLastSslUntrustedServerResult
= result
;
1471 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1478 * Updates the view associated to the activity after the finish of an operation trying to move a
1481 * @param operation Move operation performed.
1482 * @param result Result of the move operation.
1484 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1485 RemoteOperationResult result
) {
1486 if (result
.isSuccess()) {
1487 refreshListOfFilesFragment();
1490 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1491 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1495 } catch (NotFoundException e
) {
1496 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1502 * Updates the view associated to the activity after the finish of an operation trying to copy a
1505 * @param operation Copy operation performed.
1506 * @param result Result of the copy operation.
1508 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1509 if (result
.isSuccess()) {
1510 refreshListOfFilesFragment();
1513 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1514 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1518 } catch (NotFoundException e
) {
1519 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1525 * Updates the view associated to the activity after the finish of an operation trying to rename
1528 * @param operation Renaming operation performed.
1529 * @param result Result of the renaming.
1531 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1532 RemoteOperationResult result
) {
1533 OCFile renamedFile
= operation
.getFile();
1534 if (result
.isSuccess()) {
1535 FileFragment details
= getSecondFragment();
1536 if (details
!= null
) {
1537 if (details
instanceof FileDetailFragment
&&
1538 renamedFile
.equals(details
.getFile()) ) {
1539 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1540 showDetails(renamedFile
);
1542 } else if (details
instanceof PreviewMediaFragment
&&
1543 renamedFile
.equals(details
.getFile())) {
1544 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1545 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1546 int position
= ((PreviewMediaFragment
) details
).getPosition();
1547 startMediaPreview(renamedFile
, position
, true
);
1549 getFileOperationsHelper().openFile(renamedFile
);
1551 } else if (details
instanceof PreviewTextFragment
&&
1552 renamedFile
.equals(details
.getFile())) {
1553 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1554 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1555 startTextPreview(renamedFile
);
1557 getFileOperationsHelper().openFile(renamedFile
);
1562 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1563 refreshListOfFilesFragment();
1567 Toast msg
= Toast
.makeText(this,
1568 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1572 if (result
.isSslRecoverableException()) {
1573 mLastSslUntrustedServerResult
= result
;
1574 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1579 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1580 RemoteOperationResult result
) {
1581 if (result
.isSuccess()) {
1582 if (operation
.transferWasRequested()) {
1583 OCFile syncedFile
= operation
.getLocalFile();
1584 onTransferStateChanged(syncedFile
, true
, true
);
1585 invalidateOptionsMenu();
1586 refreshShowDetails();
1592 * Updates the view associated to the activity after the finish of an operation trying create a
1595 * @param operation Creation operation performed.
1596 * @param result Result of the creation.
1598 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1599 RemoteOperationResult result
) {
1600 if (result
.isSuccess()) {
1601 refreshListOfFilesFragment();
1604 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1605 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1609 } catch (NotFoundException e
) {
1610 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1620 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1621 refreshListOfFilesFragment();
1622 FileFragment details
= getSecondFragment();
1623 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1624 file
.equals(details
.getFile()) ) {
1625 if (downloading
|| uploading
) {
1626 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1628 if (!file
.fileExists()) {
1629 cleanSecondFragment();
1631 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1639 private void requestForDownload() {
1640 Account account
= getAccount();
1641 //if (!mWaitingToPreview.isDownloading()) {
1642 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1643 Intent i
= new Intent(this, FileDownloader
.class);
1644 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1645 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1651 private OCFile
getCurrentDir() {
1652 OCFile file
= getFile();
1654 if (file
.isFolder()) {
1656 } else if (getStorageManager() != null
) {
1657 String parentPath
= file
.getRemotePath().substring(0,
1658 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1659 return getStorageManager().getFileByPath(parentPath
);
1666 * Starts an operation to refresh the requested folder.
1668 * The operation is run in a new background thread created on the fly.
1670 * The refresh updates is a "light sync": properties of regular files in folder are updated (including
1671 * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
1674 * @param folder Folder to refresh.
1675 * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
1678 public void startSyncFolderOperation(final OCFile folder
, final boolean ignoreETag
) {
1680 // the execution is slightly delayed to allow the activity get the window focus if it's being started
1681 // or if the method is called from a dialog that is being dismissed
1682 getHandler().postDelayed(
1686 if (hasWindowFocus()) {
1687 long currentSyncTime
= System
.currentTimeMillis();
1688 mSyncInProgress
= true
;
1690 // perform folder synchronization
1691 RemoteOperation synchFolderOp
= new RefreshFolderOperation(folder
,
1694 getFileOperationsHelper().isSharedSupported(),
1696 getStorageManager(),
1698 getApplicationContext()
1700 synchFolderOp
.execute(
1702 MainApp
.getAppContext(),
1703 FileDisplayActivity
.this,
1708 mProgressBar
.setIndeterminate(true
);
1710 setBackgroundText();
1712 } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
1713 // another window floating over
1716 DELAY_TO_REQUEST_OPERATIONS_LATER
1722 * Show untrusted cert dialog
1724 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1725 // Show a dialog with the certificate info
1726 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1727 (CertificateCombinedException
) result
.getException());
1728 FragmentManager fm
= getSupportFragmentManager();
1729 FragmentTransaction ft
= fm
.beginTransaction();
1730 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1733 private void requestForDownload(OCFile file
) {
1734 Account account
= getAccount();
1735 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1736 Intent i
= new Intent(this, FileDownloader
.class);
1737 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1738 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1743 private void sendDownloadedFile() {
1744 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1745 mWaitingToSend
= null
;
1750 * Requests the download of the received {@link OCFile} , updates the UI
1751 * to monitor the download progress and prepares the activity to send the file
1752 * when the download finishes.
1754 * @param file {@link OCFile} to download and preview.
1756 public void startDownloadForSending(OCFile file
) {
1757 mWaitingToSend
= file
;
1758 requestForDownload(mWaitingToSend
);
1759 boolean hasSecondFragment
= (getSecondFragment() != null
);
1760 updateFragmentsVisibility(hasSecondFragment
);
1764 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1766 * @param file Image {@link OCFile} to show.
1768 public void startImagePreview(OCFile file
) {
1769 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1770 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1771 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1772 startActivity(showDetailsIntent
);
1776 * Stars the preview of an already down media {@link OCFile}.
1778 * @param file Media {@link OCFile} to preview.
1779 * @param startPlaybackPosition Media position where the playback will be started,
1781 * @param autoplay When 'true', the playback will start without user
1784 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1785 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1787 setSecondFragment(mediaFragment
);
1788 updateFragmentsVisibility(true
);
1789 updateActionBarTitleAndHomeButton(file
);
1794 * Stars the preview of a text file {@link OCFile}.
1796 * @param file Text {@link OCFile} to preview.
1798 public void startTextPreview(OCFile file
) {
1799 Bundle args
= new Bundle();
1800 args
.putParcelable(EXTRA_FILE
, file
);
1801 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1802 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1803 PreviewTextFragment
.class.getName(), args
);
1804 setSecondFragment(textPreviewFragment
);
1805 updateFragmentsVisibility(true
);
1806 //updateNavigationElementsInActionBar(file);
1811 * Requests the download of the received {@link OCFile} , updates the UI
1812 * to monitor the download progress and prepares the activity to preview
1813 * or open the file when the download finishes.
1815 * @param file {@link OCFile} to download and preview.
1817 public void startDownloadForPreview(OCFile file
) {
1818 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1819 setSecondFragment(detailFragment
);
1820 mWaitingToPreview
= file
;
1821 requestForDownload();
1822 updateFragmentsVisibility(true
);
1823 updateActionBarTitleAndHomeButton(file
);
1828 public void cancelTransference(OCFile file
) {
1829 getFileOperationsHelper().cancelTransference(file
);
1830 if (mWaitingToPreview
!= null
&&
1831 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1832 mWaitingToPreview
= null
;
1834 if (mWaitingToSend
!= null
&&
1835 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1836 mWaitingToSend
= null
;
1838 onTransferStateChanged(file
, false
, false
);
1842 public void onRefresh(boolean ignoreETag
) {
1843 refreshList(ignoreETag
);
1847 public void onRefresh() {
1851 private void refreshList(boolean ignoreETag
) {
1852 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1853 if (listOfFiles
!= null
) {
1854 OCFile folder
= listOfFiles
.getCurrentFile();
1855 if (folder
!= null
) {
1856 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1857 listDirectory(mFile);*/
1858 startSyncFolderOperation(folder
, ignoreETag
);
1863 private void sortByDate(boolean ascending
) {
1864 getListOfFilesFragment().sortByDate(ascending
);
1867 private void sortBySize(boolean ascending
) {
1868 getListOfFilesFragment().sortBySize(ascending
);
1871 private void sortByName(boolean ascending
) {
1872 getListOfFilesFragment().sortByName(ascending
);
1875 public void allFilesOption() {