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
;
27 import android
.accounts
.Account
;
28 import android
.accounts
.AccountManager
;
29 import android
.accounts
.AuthenticatorException
;
30 import android
.annotation
.TargetApi
;
31 import android
.app
.AlertDialog
;
32 import android
.content
.BroadcastReceiver
;
33 import android
.content
.ComponentName
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Build
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.OpenableColumns
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.view
.View
;
54 import android
.view
.ViewGroup
;
55 import android
.widget
.ArrayAdapter
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.view
.Menu
;
62 import com
.actionbarsherlock
.view
.MenuInflater
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.actionbarsherlock
.view
.Window
;
65 import com
.owncloud
.android
.BuildConfig
;
66 import com
.owncloud
.android
.MainApp
;
67 import com
.owncloud
.android
.R
;
68 import com
.owncloud
.android
.datamodel
.OCFile
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
77 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
78 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
82 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
83 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
84 import com
.owncloud
.android
.operations
.CreateShareOperation
;
85 import com
.owncloud
.android
.operations
.MoveFileOperation
;
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
.RefreshFolderOperation
;
90 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
91 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
92 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
93 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
97 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
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
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
implements
116 FileFragment
.ContainerActivity
, OnNavigationListener
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
119 private ArrayAdapter
<String
> mDirectories
;
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
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;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
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";
155 private OCFile mWaitingToSend
;
158 protected void onCreate(Bundle savedInstanceState
) {
159 Log_OC
.v(TAG
, "onCreate() start");
160 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
164 /// grant that FileObserverService is watching favorite files
165 if (savedInstanceState
== null
) {
166 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
167 startService(initObserversIntent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
177 mWaitingToPreview
= null
;
178 mSyncInProgress
= false
;
179 mWaitingToSend
= null
;
184 // Inflate and set the layout view
185 setContentView(R
.layout
.files
);
186 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
187 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
188 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
189 if (savedInstanceState
== null
) {
190 createMinFragments();
194 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
195 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
196 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
200 Log_OC
.v(TAG
, "onCreate() end");
204 protected void onStart() {
205 Log_OC
.v(TAG
, "onStart() start");
207 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
208 Log_OC
.v(TAG
, "onStart() end");
212 protected void onDestroy() {
213 Log_OC
.v(TAG
, "onDestroy() start");
215 Log_OC
.v(TAG
, "onDestroy() end");
219 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
222 protected void onAccountSet(boolean stateWasRecovered
) {
223 super.onAccountSet(stateWasRecovered
);
224 if (getAccount() != null
) {
225 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
226 OCFile file
= getFile();
227 // get parent from path
228 String parentPath
= "";
230 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
231 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
232 // get parent from path
233 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
234 if (getStorageManager().getFileByPath(parentPath
) == null
)
235 file
= null
; // not able to know the directory where the file is uploading
237 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
241 // fall back to root folder
242 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
245 setNavigationListWithFolder(file
);
247 if (!stateWasRecovered
) {
248 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
249 initFragmentsWithFile();
250 if (file
.isFolder()) {
251 startSyncFolderOperation(file
, false
);
255 updateFragmentsVisibility(!file
.isFolder());
256 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
262 private void setNavigationListWithFolder(OCFile file
) {
263 mDirectories
.clear();
264 OCFile fileIt
= file
;
266 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
267 if (fileIt
.isFolder()) {
268 mDirectories
.add(fileIt
.getFileName());
270 // get parent from path
271 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
272 fileIt
= getStorageManager().getFileByPath(parentPath
);
274 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
278 private void createMinFragments() {
279 OCFileListFragment listOfFiles
= new OCFileListFragment();
280 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
281 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
282 transaction
.commit();
285 private void initFragmentsWithFile() {
286 if (getAccount() != null
&& getFile() != null
) {
288 OCFileListFragment listOfFiles
= getListOfFilesFragment();
289 if (listOfFiles
!= null
) {
290 listOfFiles
.listDirectory(getCurrentDir());
292 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
296 OCFile file
= getFile();
297 Fragment secondFragment
= chooseInitialSecondFragment(file
);
298 if (secondFragment
!= null
) {
299 setSecondFragment(secondFragment
);
300 updateFragmentsVisibility(true
);
301 updateNavigationElementsInActionBar(file
);
304 cleanSecondFragment();
308 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
309 if (getAccount() == null
) {
310 Log_OC
.wtf(TAG
, "\t account is NULL");
312 if (getFile() == null
) {
313 Log_OC
.wtf(TAG
, "\t file is NULL");
318 private Fragment
chooseInitialSecondFragment(OCFile file
) {
319 Fragment secondFragment
= null
;
320 if (file
!= null
&& !file
.isFolder()) {
321 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
322 && file
.getLastSyncDateForProperties() > 0 // temporal fix
324 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
325 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
326 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
329 secondFragment
= new FileDetailFragment(file
, getAccount());
332 return secondFragment
;
337 * Replaces the second fragment managed by the activity with the received as
340 * Assumes never will be more than two fragments managed at the same time.
342 * @param fragment New second Fragment to set.
344 private void setSecondFragment(Fragment fragment
) {
345 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
346 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
347 transaction
.commit();
351 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
353 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
354 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
356 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
360 } else if (existsSecondFragment
) {
361 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
362 mLeftFragmentContainer
.setVisibility(View
.GONE
);
364 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
369 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
373 mRightFragmentContainer
.setVisibility(View
.GONE
);
379 private OCFileListFragment
getListOfFilesFragment() {
380 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
381 if (listOfFiles
!= null
) {
382 return (OCFileListFragment
)listOfFiles
;
384 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
388 public FileFragment
getSecondFragment() {
389 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
390 if (second
!= null
) {
391 return (FileFragment
)second
;
396 protected void cleanSecondFragment() {
397 Fragment second
= getSecondFragment();
398 if (second
!= null
) {
399 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
403 updateFragmentsVisibility(false
);
404 updateNavigationElementsInActionBar(null
);
407 protected void refreshListOfFilesFragment() {
408 OCFileListFragment fileListFragment
= getListOfFilesFragment();
409 if (fileListFragment
!= null
) {
410 fileListFragment
.listDirectory();
414 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
415 FileFragment secondFragment
= getSecondFragment();
416 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
417 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
418 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
419 OCFile fileInFragment
= detailsFragment
.getFile();
420 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
421 // the user browsed to other file ; forget the automatic preview
422 mWaitingToPreview
= null
;
424 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
425 // grant that the right panel updates the progress bar
426 detailsFragment
.listenForTransferProgress();
427 detailsFragment
.updateFileDetails(true
, false
);
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
430 // update the right panel
431 boolean detailsFragmentChanged
= false
;
434 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
435 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
436 startMediaPreview(mWaitingToPreview
, 0, true
);
437 detailsFragmentChanged
= true
;
439 getFileOperationsHelper().openFile(mWaitingToPreview
);
442 mWaitingToPreview
= null
;
444 if (!detailsFragmentChanged
) {
445 detailsFragment
.updateFileDetails(false
, (success
));
452 public boolean onPrepareOptionsMenu(Menu menu
) {
453 if (BuildConfig
.DEBUG
) {
454 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
456 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
458 return super.onPrepareOptionsMenu(menu
);
462 public boolean onCreateOptionsMenu(Menu menu
) {
463 MenuInflater inflater
= getSherlock().getMenuInflater();
464 inflater
.inflate(R
.menu
.main_menu
, menu
);
469 public boolean onOptionsItemSelected(MenuItem item
) {
470 boolean retval
= true
;
471 switch (item
.getItemId()) {
472 case R
.id
.action_create_dir
: {
473 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
474 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
477 case R
.id
.action_sync_account
: {
478 startSynchronization();
481 case R
.id
.action_upload
: {
482 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
483 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
487 case R
.id
.action_settings
: {
488 Intent settingsIntent
= new Intent(this, Preferences
.class);
489 startActivity(settingsIntent
);
492 case R
.id
.action_logger
: {
493 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
494 startActivity(loggerIntent
);
497 case android
.R
.id
.home
: {
498 FileFragment second
= getSecondFragment();
499 OCFile currentDir
= getCurrentDir();
500 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
501 (second
!= null
&& second
.getFile() != null
)) {
507 case R
.id
.action_sort
: {
508 SharedPreferences appPreferences
= PreferenceManager
509 .getDefaultSharedPreferences(this);
511 // Read sorting order, default to sort by name ascending
512 Integer sortOrder
= appPreferences
513 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
515 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
516 builder
.setTitle(R
.string
.actionbar_sort_title
)
517 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
518 public void onClick(DialogInterface dialog
, int which
) {
534 builder
.create().show();
538 retval
= super.onOptionsItemSelected(item
);
543 private void startSynchronization() {
544 Log_OC
.d(TAG
, "Got to start sync");
545 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
546 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
547 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
548 Bundle bundle
= new Bundle();
549 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
550 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
551 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
552 ContentResolver
.requestSync(
554 MainApp
.getAuthority(), bundle
);
556 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
557 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
558 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
559 builder
.setExpedited(true
);
560 builder
.setManual(true
);
563 // Fix bug in Android Lollipop when you click on refresh the whole account
564 Bundle extras
= new Bundle();
565 builder
.setExtras(extras
);
567 SyncRequest request
= builder
.build();
568 ContentResolver
.requestSync(request
);
574 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
575 if (itemPosition
!= 0) {
576 String targetPath
= "";
577 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
578 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
580 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
581 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
582 if (targetFolder
!= null
) {
583 browseTo(targetFolder
);
586 // the next operation triggers a new call to this method, but it's necessary to
587 // ensure that the name exposed in the action bar is the current directory when the
588 // user selected it in the navigation list
589 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
590 getSupportActionBar().setSelectedNavigationItem(0);
596 * Called, when the user selected something for uploading
599 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
601 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
603 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
604 //getClipData is only supported on api level 16+, Jelly Bean
605 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
606 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
607 Intent intent
= new Intent();
608 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
609 requestSimpleUpload(intent
, resultCode
);
612 requestSimpleUpload(data
, resultCode
);
614 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
615 requestMultipleUpload(data
, resultCode
);
617 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
619 final Intent fData
= data
;
620 final int fResultCode
= resultCode
;
621 getHandler().postDelayed(
625 requestMoveOperation(fData
, fResultCode
);
628 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
632 super.onActivityResult(requestCode
, resultCode
, data
);
637 private void requestMultipleUpload(Intent data
, int resultCode
) {
638 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
639 if (filePaths
!= null
) {
640 String
[] remotePaths
= new String
[filePaths
.length
];
641 String remotePathBase
= "";
643 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
644 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
646 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
647 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
648 for (int j
= 0; j
< remotePaths
.length
; j
++) {
649 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
652 Intent i
= new Intent(this, FileUploader
.class);
653 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
654 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
655 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
656 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
657 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
658 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
662 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
663 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
670 private void requestSimpleUpload(Intent data
, int resultCode
) {
671 String filePath
= null
;
672 String mimeType
= null
;
674 Uri selectedImageUri
= data
.getData();
677 mimeType
= getContentResolver().getType(selectedImageUri
);
679 String fileManagerString
= selectedImageUri
.getPath();
680 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
682 if (selectedImagePath
!= null
)
683 filePath
= selectedImagePath
;
685 filePath
= fileManagerString
;
687 } catch (Exception e
) {
688 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
691 if (filePath
== null
) {
692 Log_OC
.e(TAG
, "Couldn't resolve path to file");
693 Toast t
= Toast
.makeText(
694 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
701 Intent i
= new Intent(this, FileUploader
.class);
702 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
703 OCFile currentDir
= getCurrentDir();
704 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
706 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
707 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
709 if (cursor
!= null
&& cursor
.moveToFirst()) {
710 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
711 Log_OC
.v(TAG
, "Display Name: " + displayName
);
713 displayName
.replace(File
.separatorChar
, '_');
714 displayName
.replace(File
.pathSeparatorChar
, '_');
715 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
718 // and what happens in case of error?; wrong target name for the upload
724 remotePath
+= new File(filePath
).getName();
727 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
728 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
729 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
730 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
731 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
732 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
737 * Request the operation for moving the file/folder from one path to another
739 * @param data Intent received
740 * @param resultCode Result code received
742 private void requestMoveOperation(Intent data
, int resultCode
) {
743 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
744 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
745 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
749 public void onBackPressed() {
750 OCFileListFragment listOfFiles
= getListOfFilesFragment();
751 if (mDualPane
|| getSecondFragment() == null
) {
752 if (listOfFiles
!= null
) { // should never be null, indeed
753 if (mDirectories
.getCount() <= 1) {
757 int levelsUp
= listOfFiles
.onBrowseUp();
758 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
763 if (listOfFiles
!= null
) { // should never be null, indeed
764 setFile(listOfFiles
.getCurrentFile());
766 cleanSecondFragment();
771 protected void onSaveInstanceState(Bundle outState
) {
772 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
773 Log_OC
.v(TAG
, "onSaveInstanceState() start");
774 super.onSaveInstanceState(outState
);
775 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
776 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
777 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
778 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
780 Log_OC
.v(TAG
, "onSaveInstanceState() end");
786 protected void onResume() {
787 Log_OC
.v(TAG
, "onResume() start");
790 // refresh list of files
791 refreshListOfFilesFragment();
793 // Listen for sync messages
794 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
795 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
796 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
797 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
798 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
799 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
800 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
801 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
803 // Listen for upload messages
804 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
805 mUploadFinishReceiver
= new UploadFinishReceiver();
806 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
808 // Listen for download messages
809 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
810 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
811 mDownloadFinishReceiver
= new DownloadFinishReceiver();
812 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
814 Log_OC
.v(TAG
, "onResume() end");
819 protected void onPause() {
820 Log_OC
.v(TAG
, "onPause() start");
821 if (mSyncBroadcastReceiver
!= null
) {
822 unregisterReceiver(mSyncBroadcastReceiver
);
823 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
824 mSyncBroadcastReceiver
= null
;
826 if (mUploadFinishReceiver
!= null
) {
827 unregisterReceiver(mUploadFinishReceiver
);
828 mUploadFinishReceiver
= null
;
830 if (mDownloadFinishReceiver
!= null
) {
831 unregisterReceiver(mDownloadFinishReceiver
);
832 mDownloadFinishReceiver
= null
;
836 Log_OC
.v(TAG
, "onPause() end");
840 * Pushes a directory to the drop down list
841 * @param directory to push
842 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
844 public void pushDirname(OCFile directory
) {
845 if(!directory
.isFolder()){
846 throw new IllegalArgumentException("Only directories may be pushed!");
848 mDirectories
.insert(directory
.getFileName(), 0);
853 * Pops a directory name from the drop down list
854 * @return True, unless the stack is empty
856 public boolean popDirname() {
857 mDirectories
.remove(mDirectories
.getItem(0));
858 return !mDirectories
.isEmpty();
861 // Custom array adapter to override text colors
862 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
864 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
868 public View
getView(int position
, View convertView
, ViewGroup parent
) {
869 View v
= super.getView(position
, convertView
, parent
);
871 ((TextView
) v
).setTextColor(getResources().getColorStateList(
872 android
.R
.color
.white
));
874 fixRoot((TextView
) v
);
878 public View
getDropDownView(int position
, View convertView
,
880 View v
= super.getDropDownView(position
, convertView
, parent
);
882 ((TextView
) v
).setTextColor(getResources().getColorStateList(
883 android
.R
.color
.white
));
885 fixRoot((TextView
) v
);
889 private void fixRoot(TextView v
) {
890 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
891 v
.setText(R
.string
.default_display_name_for_root_folder
);
897 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
900 * {@link BroadcastReceiver} to enable syncing feedback in UI
903 public void onReceive(Context context
, Intent intent
) {
905 String event
= intent
.getAction();
906 Log_OC
.d(TAG
, "Received broadcast " + event
);
907 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
908 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
909 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
910 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
914 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
915 mSyncInProgress
= true
;
918 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
919 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
921 if (currentDir
== null
) {
922 // current folder was removed from the server
923 Toast
.makeText( FileDisplayActivity
.this,
924 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
930 if (currentFile
== null
&& !getFile().isFolder()) {
931 // currently selected file was removed in the server, and now we know it
932 cleanSecondFragment();
933 currentFile
= currentDir
;
936 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
937 OCFileListFragment fileListFragment
= getListOfFilesFragment();
938 if (fileListFragment
!= null
) {
939 fileListFragment
.listDirectory(currentDir
);
942 setFile(currentFile
);
945 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
947 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
949 /// TODO refactor and make common
950 synchResult
!= null
&& !synchResult
.isSuccess() &&
951 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
952 synchResult
.isIdPRedirection() ||
953 (synchResult
.isException() && synchResult
.getException()
954 instanceof AuthenticatorException
))) {
958 OwnCloudClient client
;
959 OwnCloudAccount ocAccount
=
960 new OwnCloudAccount(getAccount(), context
);
961 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
962 removeClientFor(ocAccount
));
964 if (client
!= null
) {
965 OwnCloudCredentials cred
= client
.getCredentials();
967 AccountManager am
= AccountManager
.get(context
);
968 if (cred
.authTokenExpires()) {
969 am
.invalidateAuthToken(
974 am
.clearPassword(getAccount());
978 requestCredentialsUpdate();
980 } catch (AccountNotFoundException e
) {
981 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
986 removeStickyBroadcast(intent
);
987 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
988 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
994 if (synchResult
!= null
) {
995 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
996 mLastSslUntrustedServerResult
= synchResult
;
999 } catch (RuntimeException e
) {
1000 // avoid app crashes after changing the serial id of RemoteOperationResult
1001 // in owncloud library with broadcast notifications pending to process
1002 removeStickyBroadcast(intent
);
1008 * Show a text message on screen view for notifying user if content is
1009 * loading or folder is empty
1011 private void setBackgroundText() {
1012 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1013 if (ocFileListFragment
!= null
) {
1014 int message
= R
.string
.file_list_loading
;
1015 if (!mSyncInProgress
) {
1016 // In case file list is empty
1017 message
= R
.string
.file_list_empty
;
1019 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1021 Log_OC
.e(TAG
, "OCFileListFragment is null");
1026 * Once the file upload has finished -> update view
1028 private class UploadFinishReceiver
extends BroadcastReceiver
{
1030 * Once the file upload has finished -> update view
1031 * @author David A. Velasco
1032 * {@link BroadcastReceiver} to enable upload feedback in UI
1035 public void onReceive(Context context
, Intent intent
) {
1037 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1038 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1039 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1040 OCFile currentDir
= getCurrentDir();
1041 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1042 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1044 if (sameAccount
&& isDescendant
) {
1045 refreshListOfFilesFragment();
1048 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1049 boolean renamedInUpload
= getFile().getRemotePath().
1050 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1051 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1053 FileFragment details
= getSecondFragment();
1054 boolean detailFragmentIsShown
= (details
!= null
&&
1055 details
instanceof FileDetailFragment
);
1057 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1058 if (uploadWasFine
) {
1059 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1061 if (renamedInUpload
) {
1062 String newName
= (new File(uploadedRemotePath
)).getName();
1063 Toast msg
= Toast
.makeText(
1066 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1071 if (uploadWasFine
|| getFile().fileExists()) {
1072 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1074 cleanSecondFragment();
1077 // Force the preview if the file is an image
1078 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1079 startImagePreview(getFile());
1080 } // TODO what about other kind of previews?
1084 if (intent
!= null
) {
1085 removeStickyBroadcast(intent
);
1095 * Class waiting for broadcast events from the {@link FileDownloader} service.
1097 * Updates the UI when a download is started or finished, provided that it is relevant for the
1100 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1102 //int refreshCounter = 0;
1104 public void onReceive(Context context
, Intent intent
) {
1106 boolean sameAccount
= isSameAccount(context
, intent
);
1107 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1108 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1110 if (sameAccount
&& isDescendant
) {
1111 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1112 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1113 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1114 refreshListOfFilesFragment();
1116 refreshSecondFragment(
1118 downloadedRemotePath
,
1119 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1123 if (mWaitingToSend
!= null
) {
1124 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1125 if (mWaitingToSend
.isDown()) {
1126 sendDownloadedFile();
1131 if (intent
!= null
) {
1132 removeStickyBroadcast(intent
);
1137 private boolean isDescendant(String downloadedRemotePath
) {
1138 OCFile currentDir
= getCurrentDir();
1140 currentDir
!= null
&&
1141 downloadedRemotePath
!= null
&&
1142 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1146 private boolean isAscendant(String linkedToRemotePath
) {
1147 OCFile currentDir
= getCurrentDir();
1149 currentDir
!= null
&&
1150 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1154 private boolean isSameAccount(Context context
, Intent intent
) {
1155 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1156 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1161 public void browseToRoot() {
1162 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1163 if (listOfFiles
!= null
) { // should never be null, indeed
1164 while (mDirectories
.getCount() > 1) {
1167 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1168 listOfFiles
.listDirectory(root
);
1169 setFile(listOfFiles
.getCurrentFile());
1170 startSyncFolderOperation(root
, false
);
1172 cleanSecondFragment();
1176 public void browseTo(OCFile folder
) {
1177 if (folder
== null
|| !folder
.isFolder()) {
1178 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1180 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1181 if (listOfFiles
!= null
) {
1182 setNavigationListWithFolder(folder
);
1183 listOfFiles
.listDirectory(folder
);
1184 setFile(listOfFiles
.getCurrentFile());
1185 startSyncFolderOperation(folder
, false
);
1187 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1189 cleanSecondFragment();
1196 * Updates action bar and second fragment, if in dual pane mode.
1199 public void onBrowsedDownTo(OCFile directory
) {
1200 pushDirname(directory
);
1201 cleanSecondFragment();
1204 startSyncFolderOperation(directory
, false
);
1209 * Shows the information of the {@link OCFile} received as a
1210 * parameter in the second fragment.
1212 * @param file {@link OCFile} whose details will be shown
1215 public void showDetails(OCFile file
) {
1216 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1217 setSecondFragment(detailFragment
);
1218 updateFragmentsVisibility(true
);
1219 updateNavigationElementsInActionBar(file
);
1227 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1228 ActionBar actionBar
= getSupportActionBar();
1230 // For adding content description tag to a title field in the action bar
1231 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1233 if (chosenFile
== null
|| mDualPane
) {
1234 // only list of files - set for browsing through folders
1235 OCFile currentDir
= getCurrentDir();
1236 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1237 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1238 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1240 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1241 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1242 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1243 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1246 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1247 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1250 actionBar
.setDisplayHomeAsUpEnabled(true
);
1251 actionBar
.setDisplayShowTitleEnabled(true
);
1252 actionBar
.setTitle(chosenFile
.getFileName());
1253 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1254 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1255 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1256 getWindow().getDecorView().findViewById(actionBarTitleId
).
1257 setContentDescription(chosenFile
.getFileName());
1264 protected ServiceConnection
newTransferenceServiceConnection() {
1265 return new ListServiceConnection();
1268 /** Defines callbacks for service binding, passed to bindService() */
1269 private class ListServiceConnection
implements ServiceConnection
{
1272 public void onServiceConnected(ComponentName component
, IBinder service
) {
1273 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1274 Log_OC
.d(TAG
, "Download service connected");
1275 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1276 if (mWaitingToPreview
!= null
)
1277 if (getStorageManager() != null
) {
1278 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1279 if (!mWaitingToPreview
.isDown()) {
1280 requestForDownload();
1284 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1285 Log_OC
.d(TAG
, "Upload service connected");
1286 mUploaderBinder
= (FileUploaderBinder
) service
;
1290 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1291 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1292 if (listOfFiles
!= null
) {
1293 listOfFiles
.listDirectory();
1295 FileFragment secondFragment
= getSecondFragment();
1296 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1297 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1298 detailFragment
.listenForTransferProgress();
1299 detailFragment
.updateFileDetails(false
, false
);
1304 public void onServiceDisconnected(ComponentName component
) {
1305 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1306 Log_OC
.d(TAG
, "Download service disconnected");
1307 mDownloaderBinder
= null
;
1308 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1309 Log_OC
.d(TAG
, "Upload service disconnected");
1310 mUploaderBinder
= null
;
1316 public void onSavedCertificate() {
1317 startSyncFolderOperation(getCurrentDir(), false
);
1322 public void onFailedSavingCertificate() {
1323 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1324 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1326 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1330 public void onCancelCertificate() {
1335 * Updates the view associated to the activity after the finish of some operation over files
1336 * in the current account.
1338 * @param operation Removal operation performed.
1339 * @param result Result of the removal.
1342 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1343 super.onRemoteOperationFinish(operation
, result
);
1345 if (operation
instanceof RemoveFileOperation
) {
1346 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1348 } else if (operation
instanceof RenameFileOperation
) {
1349 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1351 } else if (operation
instanceof SynchronizeFileOperation
) {
1352 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1354 } else if (operation
instanceof CreateFolderOperation
) {
1355 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1357 } else if (operation
instanceof CreateShareOperation
) {
1358 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1360 } else if (operation
instanceof UnshareLinkOperation
) {
1361 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1363 } else if (operation
instanceof MoveFileOperation
) {
1364 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1370 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1371 if (result
.isSuccess()) {
1372 refreshShowDetails();
1373 refreshListOfFilesFragment();
1378 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1379 if (result
.isSuccess()) {
1380 refreshShowDetails();
1381 refreshListOfFilesFragment();
1383 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1384 cleanSecondFragment();
1385 refreshListOfFilesFragment();
1389 private void refreshShowDetails() {
1390 FileFragment details
= getSecondFragment();
1391 if (details
!= null
) {
1392 OCFile file
= details
.getFile();
1394 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1395 if (details
instanceof PreviewMediaFragment
) {
1396 // Refresh OCFile of the fragment
1397 ((PreviewMediaFragment
) details
).updateFile(file
);
1402 invalidateOptionsMenu();
1407 * Updates the view associated to the activity after the finish of an operation trying to remove a
1410 * @param operation Removal operation performed.
1411 * @param result Result of the removal.
1413 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1414 dismissLoadingDialog();
1416 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1420 if (result
.isSuccess()) {
1421 OCFile removedFile
= operation
.getFile();
1422 FileFragment second
= getSecondFragment();
1423 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1424 if (second
instanceof PreviewMediaFragment
) {
1425 ((PreviewMediaFragment
)second
).stopPreview(true
);
1427 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1428 cleanSecondFragment();
1430 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1431 refreshListOfFilesFragment();
1433 invalidateOptionsMenu();
1435 if (result
.isSslRecoverableException()) {
1436 mLastSslUntrustedServerResult
= result
;
1437 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1444 * Updates the view associated to the activity after the finish of an operation trying to move a
1447 * @param operation Move operation performed.
1448 * @param result Result of the move operation.
1450 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 dismissLoadingDialog();
1453 refreshListOfFilesFragment();
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 } catch (NotFoundException e
) {
1463 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1470 * Updates the view associated to the activity after the finish of an operation trying to rename a
1473 * @param operation Renaming operation performed.
1474 * @param result Result of the renaming.
1476 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1477 dismissLoadingDialog();
1478 OCFile renamedFile
= operation
.getFile();
1479 if (result
.isSuccess()) {
1480 FileFragment details
= getSecondFragment();
1481 if (details
!= null
) {
1482 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1483 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1484 showDetails(renamedFile
);
1486 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1487 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1488 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1489 int position
= ((PreviewMediaFragment
)details
).getPosition();
1490 startMediaPreview(renamedFile
, position
, true
);
1492 getFileOperationsHelper().openFile(renamedFile
);
1497 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1498 refreshListOfFilesFragment();
1502 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1506 if (result
.isSslRecoverableException()) {
1507 mLastSslUntrustedServerResult
= result
;
1508 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1513 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1514 dismissLoadingDialog();
1515 OCFile syncedFile
= operation
.getLocalFile();
1516 if (!result
.isSuccess()) {
1517 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1518 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1519 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1520 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1526 if (operation
.transferWasRequested()) {
1527 onTransferStateChanged(syncedFile
, true
, true
);
1530 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1538 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1540 * @param operation Creation operation performed.
1541 * @param result Result of the creation.
1543 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1544 if (result
.isSuccess()) {
1545 dismissLoadingDialog();
1546 refreshListOfFilesFragment();
1548 dismissLoadingDialog();
1550 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1551 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1555 } catch (NotFoundException e
) {
1556 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1566 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1567 refreshListOfFilesFragment();
1568 FileFragment details
= getSecondFragment();
1569 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1570 if (downloading
|| uploading
) {
1571 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1573 if (!file
.fileExists()) {
1574 cleanSecondFragment();
1576 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1584 private void requestForDownload() {
1585 Account account
= getAccount();
1586 //if (!mWaitingToPreview.isDownloading()) {
1587 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1588 Intent i
= new Intent(this, FileDownloader
.class);
1589 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1590 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1596 private OCFile
getCurrentDir() {
1597 OCFile file
= getFile();
1599 if (file
.isFolder()) {
1601 } else if (getStorageManager() != null
) {
1602 String parentPath
= file
.getRemotePath().substring(0,
1603 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1604 return getStorageManager().getFileByPath(parentPath
);
1610 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1611 long currentSyncTime
= System
.currentTimeMillis();
1613 mSyncInProgress
= true
;
1615 // perform folder synchronization
1616 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1619 getFileOperationsHelper().isSharedSupported(),
1621 getStorageManager(),
1623 getApplicationContext()
1625 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1627 setSupportProgressBarIndeterminateVisibility(true
);
1629 setBackgroundText();
1633 * Show untrusted cert dialog
1635 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1636 // Show a dialog with the certificate info
1637 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1638 (CertificateCombinedException
)result
.getException());
1639 FragmentManager fm
= getSupportFragmentManager();
1640 FragmentTransaction ft
= fm
.beginTransaction();
1641 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1644 private void requestForDownload(OCFile file
) {
1645 Account account
= getAccount();
1646 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1647 Intent i
= new Intent(this, FileDownloader
.class);
1648 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1649 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1654 private void sendDownloadedFile(){
1655 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1656 mWaitingToSend
= null
;
1661 * Requests the download of the received {@link OCFile} , updates the UI
1662 * to monitor the download progress and prepares the activity to send the file
1663 * when the download finishes.
1665 * @param file {@link OCFile} to download and preview.
1667 public void startDownloadForSending(OCFile file
) {
1668 mWaitingToSend
= file
;
1669 requestForDownload(mWaitingToSend
);
1670 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1671 updateFragmentsVisibility(hasSecondFragment
);
1675 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1677 * @param file Image {@link OCFile} to show.
1679 public void startImagePreview(OCFile file
) {
1680 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1681 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1682 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1683 startActivity(showDetailsIntent
);
1688 * Stars the preview of an already down media {@link OCFile}.
1690 * @param file Media {@link OCFile} to preview.
1691 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1692 * @param autoplay When 'true', the playback will start without user interactions.
1694 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1695 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1696 setSecondFragment(mediaFragment
);
1697 updateFragmentsVisibility(true
);
1698 updateNavigationElementsInActionBar(file
);
1703 * Requests the download of the received {@link OCFile} , updates the UI
1704 * to monitor the download progress and prepares the activity to preview
1705 * or open the file when the download finishes.
1707 * @param file {@link OCFile} to download and preview.
1709 public void startDownloadForPreview(OCFile file
) {
1710 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1711 setSecondFragment(detailFragment
);
1712 mWaitingToPreview
= file
;
1713 requestForDownload();
1714 updateFragmentsVisibility(true
);
1715 updateNavigationElementsInActionBar(file
);
1720 public void cancelTransference(OCFile file
) {
1721 getFileOperationsHelper().cancelTransference(file
);
1722 if (mWaitingToPreview
!= null
&&
1723 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1724 mWaitingToPreview
= null
;
1726 if (mWaitingToSend
!= null
&&
1727 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1728 mWaitingToSend
= null
;
1730 onTransferStateChanged(file
, false
, false
);
1734 public void onRefresh(boolean ignoreETag
) {
1735 refreshList(ignoreETag
);
1739 public void onRefresh() {
1743 private void refreshList(boolean ignoreETag
) {
1744 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1745 if (listOfFiles
!= null
) {
1746 OCFile folder
= listOfFiles
.getCurrentFile();
1747 if (folder
!= null
) {
1748 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1749 listDirectory(mFile);*/
1750 startSyncFolderOperation(folder
, ignoreETag
);
1755 private void sortByDate(boolean ascending
){
1756 getListOfFilesFragment().sortByDate(ascending
);
1759 private void sortBySize(boolean ascending
){
1760 getListOfFilesFragment().sortBySize(ascending
);
1763 private void sortByName(boolean ascending
){
1764 getListOfFilesFragment().sortByName(ascending
);