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
;
157 private Boolean mUnlocked
= false
;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.v(TAG
, "onCreate() start");
162 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
164 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
166 /// grant that FileObserverService is watching favorite files
167 if (savedInstanceState
== null
) {
168 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
169 startService(initObserversIntent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(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
);
188 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
189 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
190 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
191 if (savedInstanceState
== null
) {
192 createMinFragments();
196 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
197 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
198 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
202 Log_OC
.v(TAG
, "onCreate() end");
206 protected void onStart() {
207 Log_OC
.v(TAG
, "onStart() start");
209 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
210 Log_OC
.v(TAG
, "onStart() end");
214 protected void onDestroy() {
215 Log_OC
.v(TAG
, "onDestroy() start");
217 Log_OC
.v(TAG
, "onDestroy() end");
221 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
224 protected void onAccountSet(boolean stateWasRecovered
) {
225 super.onAccountSet(stateWasRecovered
);
226 if (getAccount() != null
) {
227 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
228 OCFile file
= getFile();
229 // get parent from path
230 String parentPath
= "";
232 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
233 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
234 // get parent from path
235 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
236 if (getStorageManager().getFileByPath(parentPath
) == null
)
237 file
= null
; // not able to know the directory where the file is uploading
239 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
243 // fall back to root folder
244 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
247 setNavigationListWithFolder(file
);
249 if (!stateWasRecovered
) {
250 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
251 initFragmentsWithFile();
252 if (file
.isFolder()) {
253 startSyncFolderOperation(file
, false
);
257 updateFragmentsVisibility(!file
.isFolder());
258 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
264 private void setNavigationListWithFolder(OCFile file
) {
265 mDirectories
.clear();
266 OCFile fileIt
= file
;
268 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
269 if (fileIt
.isFolder()) {
270 mDirectories
.add(fileIt
.getFileName());
272 // get parent from path
273 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
274 fileIt
= getStorageManager().getFileByPath(parentPath
);
276 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
280 private void createMinFragments() {
281 OCFileListFragment listOfFiles
= new OCFileListFragment();
282 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
283 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
284 transaction
.commit();
287 private void initFragmentsWithFile() {
288 if (getAccount() != null
&& getFile() != null
) {
290 OCFileListFragment listOfFiles
= getListOfFilesFragment();
291 if (listOfFiles
!= null
) {
292 listOfFiles
.listDirectory(getCurrentDir());
294 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
298 OCFile file
= getFile();
299 Fragment secondFragment
= chooseInitialSecondFragment(file
);
300 if (secondFragment
!= null
) {
301 setSecondFragment(secondFragment
);
302 updateFragmentsVisibility(true
);
303 updateNavigationElementsInActionBar(file
);
306 cleanSecondFragment();
310 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
311 if (getAccount() == null
) {
312 Log_OC
.wtf(TAG
, "\t account is NULL");
314 if (getFile() == null
) {
315 Log_OC
.wtf(TAG
, "\t file is NULL");
320 private Fragment
chooseInitialSecondFragment(OCFile file
) {
321 Fragment secondFragment
= null
;
322 if (file
!= null
&& !file
.isFolder()) {
323 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
324 && file
.getLastSyncDateForProperties() > 0 // temporal fix
326 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
327 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
328 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
331 secondFragment
= new FileDetailFragment(file
, getAccount());
334 return secondFragment
;
339 * Replaces the second fragment managed by the activity with the received as
342 * Assumes never will be more than two fragments managed at the same time.
344 * @param fragment New second Fragment to set.
346 private void setSecondFragment(Fragment fragment
) {
347 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
348 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
349 transaction
.commit();
353 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
355 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
356 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
358 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
362 } else if (existsSecondFragment
) {
363 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
364 mLeftFragmentContainer
.setVisibility(View
.GONE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
375 mRightFragmentContainer
.setVisibility(View
.GONE
);
381 private OCFileListFragment
getListOfFilesFragment() {
382 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
383 if (listOfFiles
!= null
) {
384 return (OCFileListFragment
)listOfFiles
;
386 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
390 public FileFragment
getSecondFragment() {
391 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
392 if (second
!= null
) {
393 return (FileFragment
)second
;
398 protected void cleanSecondFragment() {
399 Fragment second
= getSecondFragment();
400 if (second
!= null
) {
401 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
405 updateFragmentsVisibility(false
);
406 updateNavigationElementsInActionBar(null
);
409 protected void refreshListOfFilesFragment() {
410 OCFileListFragment fileListFragment
= getListOfFilesFragment();
411 if (fileListFragment
!= null
) {
412 fileListFragment
.listDirectory();
416 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
417 FileFragment secondFragment
= getSecondFragment();
418 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
419 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
420 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
421 OCFile fileInFragment
= detailsFragment
.getFile();
422 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
423 // the user browsed to other file ; forget the automatic preview
424 mWaitingToPreview
= null
;
426 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
427 // grant that the right panel updates the progress bar
428 detailsFragment
.listenForTransferProgress();
429 detailsFragment
.updateFileDetails(true
, false
);
431 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
432 // update the right panel
433 boolean detailsFragmentChanged
= false
;
436 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
437 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
438 startMediaPreview(mWaitingToPreview
, 0, true
);
439 detailsFragmentChanged
= true
;
441 getFileOperationsHelper().openFile(mWaitingToPreview
);
444 mWaitingToPreview
= null
;
446 if (!detailsFragmentChanged
) {
447 detailsFragment
.updateFileDetails(false
, (success
));
454 public boolean onPrepareOptionsMenu(Menu menu
) {
455 if (BuildConfig
.DEBUG
) {
456 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
458 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
460 return super.onPrepareOptionsMenu(menu
);
464 public boolean onCreateOptionsMenu(Menu menu
) {
465 MenuInflater inflater
= getSherlock().getMenuInflater();
466 inflater
.inflate(R
.menu
.main_menu
, menu
);
471 public boolean onOptionsItemSelected(MenuItem item
) {
472 boolean retval
= true
;
473 switch (item
.getItemId()) {
474 case R
.id
.action_create_dir
: {
475 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
476 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
479 case R
.id
.action_sync_account
: {
480 startSynchronization();
483 case R
.id
.action_upload
: {
484 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
485 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
489 case R
.id
.action_settings
: {
490 Intent settingsIntent
= new Intent(this, Preferences
.class);
491 startActivity(settingsIntent
);
494 case R
.id
.action_logger
: {
495 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
496 startActivity(loggerIntent
);
499 case android
.R
.id
.home
: {
500 FileFragment second
= getSecondFragment();
501 OCFile currentDir
= getCurrentDir();
502 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
503 (second
!= null
&& second
.getFile() != null
)) {
509 case R
.id
.action_sort
: {
510 SharedPreferences appPreferences
= PreferenceManager
511 .getDefaultSharedPreferences(this);
513 // Read sorting order, default to sort by name ascending
514 Integer sortOrder
= appPreferences
515 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
517 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
518 builder
.setTitle(R
.string
.actionbar_sort_title
)
519 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
520 public void onClick(DialogInterface dialog
, int which
) {
536 builder
.create().show();
540 retval
= super.onOptionsItemSelected(item
);
545 private void startSynchronization() {
546 Log_OC
.d(TAG
, "Got to start sync");
547 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
548 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
549 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
550 Bundle bundle
= new Bundle();
551 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
552 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
553 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
554 ContentResolver
.requestSync(
556 MainApp
.getAuthority(), bundle
);
558 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
559 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
560 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
561 builder
.setExpedited(true
);
562 builder
.setManual(true
);
565 // Fix bug in Android Lollipop when you click on refresh the whole account
566 Bundle extras
= new Bundle();
567 builder
.setExtras(extras
);
569 SyncRequest request
= builder
.build();
570 ContentResolver
.requestSync(request
);
576 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
577 if (itemPosition
!= 0) {
578 String targetPath
= "";
579 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
580 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
582 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
583 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
584 if (targetFolder
!= null
) {
585 browseTo(targetFolder
);
588 // the next operation triggers a new call to this method, but it's necessary to
589 // ensure that the name exposed in the action bar is the current directory when the
590 // user selected it in the navigation list
591 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
592 getSupportActionBar().setSelectedNavigationItem(0);
598 * Called, when the user selected something for uploading
601 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
603 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
605 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
606 //getClipData is only supported on api level 16+, Jelly Bean
607 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
608 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
609 Intent intent
= new Intent();
610 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
611 requestSimpleUpload(intent
, resultCode
);
614 requestSimpleUpload(data
, resultCode
);
616 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
617 requestMultipleUpload(data
, resultCode
);
619 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
621 final Intent fData
= data
;
622 final int fResultCode
= resultCode
;
623 getHandler().postDelayed(
627 requestMoveOperation(fData
, fResultCode
);
630 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
634 super.onActivityResult(requestCode
, resultCode
, data
);
639 private void requestMultipleUpload(Intent data
, int resultCode
) {
640 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
641 if (filePaths
!= null
) {
642 String
[] remotePaths
= new String
[filePaths
.length
];
643 String remotePathBase
= "";
645 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
646 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
648 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
649 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
650 for (int j
= 0; j
< remotePaths
.length
; j
++) {
651 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
654 Intent i
= new Intent(this, FileUploader
.class);
655 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
656 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
657 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
658 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
659 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
660 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
664 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
665 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
672 private void requestSimpleUpload(Intent data
, int resultCode
) {
673 String filePath
= null
;
674 String mimeType
= null
;
676 Uri selectedImageUri
= data
.getData();
679 mimeType
= getContentResolver().getType(selectedImageUri
);
681 String fileManagerString
= selectedImageUri
.getPath();
682 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
684 if (selectedImagePath
!= null
)
685 filePath
= selectedImagePath
;
687 filePath
= fileManagerString
;
689 } catch (Exception e
) {
690 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
693 if (filePath
== null
) {
694 Log_OC
.e(TAG
, "Couldn't resolve path to file");
695 Toast t
= Toast
.makeText(
696 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
703 Intent i
= new Intent(this, FileUploader
.class);
704 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
705 OCFile currentDir
= getCurrentDir();
706 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
708 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
709 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
711 if (cursor
!= null
&& cursor
.moveToFirst()) {
712 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
713 Log_OC
.v(TAG
, "Display Name: " + displayName
);
715 displayName
.replace(File
.separatorChar
, '_');
716 displayName
.replace(File
.pathSeparatorChar
, '_');
717 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
720 // and what happens in case of error?; wrong target name for the upload
726 remotePath
+= new File(filePath
).getName();
729 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
730 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
731 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
732 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
733 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
734 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
739 * Request the operation for moving the file/folder from one path to another
741 * @param data Intent received
742 * @param resultCode Result code received
744 private void requestMoveOperation(Intent data
, int resultCode
) {
745 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
746 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
747 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
751 public void onBackPressed() {
752 OCFileListFragment listOfFiles
= getListOfFilesFragment();
753 if (mDualPane
|| getSecondFragment() == null
) {
754 if (listOfFiles
!= null
) { // should never be null, indeed
755 if (mDirectories
.getCount() <= 1) {
759 int levelsUp
= listOfFiles
.onBrowseUp();
760 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
765 if (listOfFiles
!= null
) { // should never be null, indeed
766 setFile(listOfFiles
.getCurrentFile());
768 cleanSecondFragment();
773 protected void onSaveInstanceState(Bundle outState
) {
774 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
775 Log_OC
.v(TAG
, "onSaveInstanceState() start");
776 super.onSaveInstanceState(outState
);
777 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
778 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
779 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
780 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
782 Log_OC
.v(TAG
, "onSaveInstanceState() end");
788 protected void onResume() {
789 Log_OC
.v(TAG
, "onResume() start");
792 // refresh list of files
793 refreshListOfFilesFragment();
795 // Listen for sync messages
796 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
797 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
798 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
799 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
800 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
801 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
802 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
803 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
805 // Listen for upload messages
806 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
807 mUploadFinishReceiver
= new UploadFinishReceiver();
808 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
810 // Listen for download messages
811 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
812 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
813 mDownloadFinishReceiver
= new DownloadFinishReceiver();
814 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
816 Log_OC
.v(TAG
, "onResume() end");
821 protected void onPause() {
822 Log_OC
.v(TAG
, "onPause() start");
823 if (mSyncBroadcastReceiver
!= null
) {
824 unregisterReceiver(mSyncBroadcastReceiver
);
825 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
826 mSyncBroadcastReceiver
= null
;
828 if (mUploadFinishReceiver
!= null
) {
829 unregisterReceiver(mUploadFinishReceiver
);
830 mUploadFinishReceiver
= null
;
832 if (mDownloadFinishReceiver
!= null
) {
833 unregisterReceiver(mDownloadFinishReceiver
);
834 mDownloadFinishReceiver
= null
;
838 Log_OC
.v(TAG
, "onPause() end");
842 * Pushes a directory to the drop down list
843 * @param directory to push
844 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
846 public void pushDirname(OCFile directory
) {
847 if(!directory
.isFolder()){
848 throw new IllegalArgumentException("Only directories may be pushed!");
850 mDirectories
.insert(directory
.getFileName(), 0);
855 * Pops a directory name from the drop down list
856 * @return True, unless the stack is empty
858 public boolean popDirname() {
859 mDirectories
.remove(mDirectories
.getItem(0));
860 return !mDirectories
.isEmpty();
863 // Custom array adapter to override text colors
864 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
866 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
870 public View
getView(int position
, View convertView
, ViewGroup parent
) {
871 View v
= super.getView(position
, convertView
, parent
);
873 ((TextView
) v
).setTextColor(getResources().getColorStateList(
874 android
.R
.color
.white
));
876 fixRoot((TextView
) v
);
880 public View
getDropDownView(int position
, View convertView
,
882 View v
= super.getDropDownView(position
, convertView
, parent
);
884 ((TextView
) v
).setTextColor(getResources().getColorStateList(
885 android
.R
.color
.white
));
887 fixRoot((TextView
) v
);
891 private void fixRoot(TextView v
) {
892 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
893 v
.setText(R
.string
.default_display_name_for_root_folder
);
899 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
902 * {@link BroadcastReceiver} to enable syncing feedback in UI
905 public void onReceive(Context context
, Intent intent
) {
907 String event
= intent
.getAction();
908 Log_OC
.d(TAG
, "Received broadcast " + event
);
909 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
910 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
911 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
912 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
916 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
917 mSyncInProgress
= true
;
920 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
921 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
923 if (currentDir
== null
) {
924 // current folder was removed from the server
925 Toast
.makeText( FileDisplayActivity
.this,
926 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
932 if (currentFile
== null
&& !getFile().isFolder()) {
933 // currently selected file was removed in the server, and now we know it
934 cleanSecondFragment();
935 currentFile
= currentDir
;
938 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
939 OCFileListFragment fileListFragment
= getListOfFilesFragment();
940 if (fileListFragment
!= null
) {
941 fileListFragment
.listDirectory(currentDir
);
944 setFile(currentFile
);
947 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
949 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
951 /// TODO refactor and make common
952 synchResult
!= null
&& !synchResult
.isSuccess() &&
953 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
954 synchResult
.isIdPRedirection() ||
955 (synchResult
.isException() && synchResult
.getException()
956 instanceof AuthenticatorException
))) {
960 OwnCloudClient client
;
961 OwnCloudAccount ocAccount
=
962 new OwnCloudAccount(getAccount(), context
);
963 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
964 removeClientFor(ocAccount
));
966 if (client
!= null
) {
967 OwnCloudCredentials cred
= client
.getCredentials();
969 AccountManager am
= AccountManager
.get(context
);
970 if (cred
.authTokenExpires()) {
971 am
.invalidateAuthToken(
976 am
.clearPassword(getAccount());
980 requestCredentialsUpdate();
982 } catch (AccountNotFoundException e
) {
983 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
988 removeStickyBroadcast(intent
);
989 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
990 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
996 if (synchResult
!= null
) {
997 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
998 mLastSslUntrustedServerResult
= synchResult
;
1001 } catch (RuntimeException e
) {
1002 // avoid app crashes after changing the serial id of RemoteOperationResult
1003 // in owncloud library with broadcast notifications pending to process
1004 removeStickyBroadcast(intent
);
1010 * Show a text message on screen view for notifying user if content is
1011 * loading or folder is empty
1013 private void setBackgroundText() {
1014 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1015 if (ocFileListFragment
!= null
) {
1016 int message
= R
.string
.file_list_loading
;
1017 if (!mSyncInProgress
) {
1018 // In case file list is empty
1019 message
= R
.string
.file_list_empty
;
1021 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1023 Log_OC
.e(TAG
, "OCFileListFragment is null");
1028 * Once the file upload has finished -> update view
1030 private class UploadFinishReceiver
extends BroadcastReceiver
{
1032 * Once the file upload has finished -> update view
1033 * @author David A. Velasco
1034 * {@link BroadcastReceiver} to enable upload feedback in UI
1037 public void onReceive(Context context
, Intent intent
) {
1039 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1040 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1041 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1042 OCFile currentDir
= getCurrentDir();
1043 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1044 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1046 if (sameAccount
&& isDescendant
) {
1047 refreshListOfFilesFragment();
1050 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1051 boolean renamedInUpload
= getFile().getRemotePath().
1052 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1053 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1055 FileFragment details
= getSecondFragment();
1056 boolean detailFragmentIsShown
= (details
!= null
&&
1057 details
instanceof FileDetailFragment
);
1059 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1060 if (uploadWasFine
) {
1061 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1063 if (renamedInUpload
) {
1064 String newName
= (new File(uploadedRemotePath
)).getName();
1065 Toast msg
= Toast
.makeText(
1068 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1073 if (uploadWasFine
|| getFile().fileExists()) {
1074 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1076 cleanSecondFragment();
1079 // Force the preview if the file is an image
1080 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1081 startImagePreview(getFile());
1082 } // TODO what about other kind of previews?
1086 if (intent
!= null
) {
1087 removeStickyBroadcast(intent
);
1097 * Class waiting for broadcast events from the {@link FileDownloader} service.
1099 * Updates the UI when a download is started or finished, provided that it is relevant for the
1102 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1104 //int refreshCounter = 0;
1106 public void onReceive(Context context
, Intent intent
) {
1108 boolean sameAccount
= isSameAccount(context
, intent
);
1109 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1110 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1112 if (sameAccount
&& isDescendant
) {
1113 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1114 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1115 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1116 refreshListOfFilesFragment();
1118 refreshSecondFragment(
1120 downloadedRemotePath
,
1121 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1125 if (mWaitingToSend
!= null
) {
1126 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1127 if (mWaitingToSend
.isDown()) {
1128 sendDownloadedFile();
1133 if (intent
!= null
) {
1134 removeStickyBroadcast(intent
);
1139 private boolean isDescendant(String downloadedRemotePath
) {
1140 OCFile currentDir
= getCurrentDir();
1142 currentDir
!= null
&&
1143 downloadedRemotePath
!= null
&&
1144 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1148 private boolean isAscendant(String linkedToRemotePath
) {
1149 OCFile currentDir
= getCurrentDir();
1151 currentDir
!= null
&&
1152 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1156 private boolean isSameAccount(Context context
, Intent intent
) {
1157 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1158 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1163 public void browseToRoot() {
1164 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1165 if (listOfFiles
!= null
) { // should never be null, indeed
1166 while (mDirectories
.getCount() > 1) {
1169 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1170 listOfFiles
.listDirectory(root
);
1171 setFile(listOfFiles
.getCurrentFile());
1172 startSyncFolderOperation(root
, false
);
1174 cleanSecondFragment();
1178 public void browseTo(OCFile folder
) {
1179 if (folder
== null
|| !folder
.isFolder()) {
1180 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1182 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1183 if (listOfFiles
!= null
) {
1184 setNavigationListWithFolder(folder
);
1185 listOfFiles
.listDirectory(folder
);
1186 setFile(listOfFiles
.getCurrentFile());
1187 startSyncFolderOperation(folder
, false
);
1189 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1191 cleanSecondFragment();
1198 * Updates action bar and second fragment, if in dual pane mode.
1201 public void onBrowsedDownTo(OCFile directory
) {
1202 pushDirname(directory
);
1203 cleanSecondFragment();
1206 startSyncFolderOperation(directory
, false
);
1211 * Shows the information of the {@link OCFile} received as a
1212 * parameter in the second fragment.
1214 * @param file {@link OCFile} whose details will be shown
1217 public void showDetails(OCFile file
) {
1218 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1219 setSecondFragment(detailFragment
);
1220 updateFragmentsVisibility(true
);
1221 updateNavigationElementsInActionBar(file
);
1229 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1230 ActionBar actionBar
= getSupportActionBar();
1232 // For adding content description tag to a title field in the action bar
1233 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1235 if (chosenFile
== null
|| mDualPane
) {
1236 // only list of files - set for browsing through folders
1237 OCFile currentDir
= getCurrentDir();
1238 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1239 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1240 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1242 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1243 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1244 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1245 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1248 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1249 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1252 actionBar
.setDisplayHomeAsUpEnabled(true
);
1253 actionBar
.setDisplayShowTitleEnabled(true
);
1254 actionBar
.setTitle(chosenFile
.getFileName());
1255 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1256 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1257 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1258 getWindow().getDecorView().findViewById(actionBarTitleId
).
1259 setContentDescription(chosenFile
.getFileName());
1266 protected ServiceConnection
newTransferenceServiceConnection() {
1267 return new ListServiceConnection();
1270 /** Defines callbacks for service binding, passed to bindService() */
1271 private class ListServiceConnection
implements ServiceConnection
{
1274 public void onServiceConnected(ComponentName component
, IBinder service
) {
1275 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1276 Log_OC
.d(TAG
, "Download service connected");
1277 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1278 if (mWaitingToPreview
!= null
)
1279 if (getStorageManager() != null
) {
1280 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1281 if (!mWaitingToPreview
.isDown()) {
1282 requestForDownload();
1286 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1287 Log_OC
.d(TAG
, "Upload service connected");
1288 mUploaderBinder
= (FileUploaderBinder
) service
;
1292 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1293 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1294 if (listOfFiles
!= null
) {
1295 listOfFiles
.listDirectory();
1297 FileFragment secondFragment
= getSecondFragment();
1298 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1299 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1300 detailFragment
.listenForTransferProgress();
1301 detailFragment
.updateFileDetails(false
, false
);
1306 public void onServiceDisconnected(ComponentName component
) {
1307 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1308 Log_OC
.d(TAG
, "Download service disconnected");
1309 mDownloaderBinder
= null
;
1310 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1311 Log_OC
.d(TAG
, "Upload service disconnected");
1312 mUploaderBinder
= null
;
1318 public void onSavedCertificate() {
1319 startSyncFolderOperation(getCurrentDir(), false
);
1324 public void onFailedSavingCertificate() {
1325 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1326 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1328 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1332 public void onCancelCertificate() {
1337 * Updates the view associated to the activity after the finish of some operation over files
1338 * in the current account.
1340 * @param operation Removal operation performed.
1341 * @param result Result of the removal.
1344 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1345 super.onRemoteOperationFinish(operation
, result
);
1347 if (operation
instanceof RemoveFileOperation
) {
1348 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1350 } else if (operation
instanceof RenameFileOperation
) {
1351 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1353 } else if (operation
instanceof SynchronizeFileOperation
) {
1354 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1356 } else if (operation
instanceof CreateFolderOperation
) {
1357 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1359 } else if (operation
instanceof CreateShareOperation
) {
1360 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1362 } else if (operation
instanceof UnshareLinkOperation
) {
1363 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1365 } else if (operation
instanceof MoveFileOperation
) {
1366 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1372 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1373 if (result
.isSuccess()) {
1374 refreshShowDetails();
1375 refreshListOfFilesFragment();
1380 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1381 if (result
.isSuccess()) {
1382 refreshShowDetails();
1383 refreshListOfFilesFragment();
1385 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1386 cleanSecondFragment();
1387 refreshListOfFilesFragment();
1391 private void refreshShowDetails() {
1392 FileFragment details
= getSecondFragment();
1393 if (details
!= null
) {
1394 OCFile file
= details
.getFile();
1396 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1397 if (details
instanceof PreviewMediaFragment
) {
1398 // Refresh OCFile of the fragment
1399 ((PreviewMediaFragment
) details
).updateFile(file
);
1404 invalidateOptionsMenu();
1409 * Updates the view associated to the activity after the finish of an operation trying to remove a
1412 * @param operation Removal operation performed.
1413 * @param result Result of the removal.
1415 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1416 dismissLoadingDialog();
1418 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1422 if (result
.isSuccess()) {
1423 OCFile removedFile
= operation
.getFile();
1424 FileFragment second
= getSecondFragment();
1425 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1426 if (second
instanceof PreviewMediaFragment
) {
1427 ((PreviewMediaFragment
)second
).stopPreview(true
);
1429 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1430 cleanSecondFragment();
1432 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1433 refreshListOfFilesFragment();
1435 invalidateOptionsMenu();
1437 if (result
.isSslRecoverableException()) {
1438 mLastSslUntrustedServerResult
= result
;
1439 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1446 * Updates the view associated to the activity after the finish of an operation trying to move a
1449 * @param operation Move operation performed.
1450 * @param result Result of the move operation.
1452 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1453 if (result
.isSuccess()) {
1454 dismissLoadingDialog();
1455 refreshListOfFilesFragment();
1457 dismissLoadingDialog();
1459 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1460 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1464 } catch (NotFoundException e
) {
1465 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1472 * Updates the view associated to the activity after the finish of an operation trying to rename a
1475 * @param operation Renaming operation performed.
1476 * @param result Result of the renaming.
1478 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1479 dismissLoadingDialog();
1480 OCFile renamedFile
= operation
.getFile();
1481 if (result
.isSuccess()) {
1482 FileFragment details
= getSecondFragment();
1483 if (details
!= null
) {
1484 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1485 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1486 showDetails(renamedFile
);
1488 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1489 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1490 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1491 int position
= ((PreviewMediaFragment
)details
).getPosition();
1492 startMediaPreview(renamedFile
, position
, true
);
1494 getFileOperationsHelper().openFile(renamedFile
);
1499 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1500 refreshListOfFilesFragment();
1504 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1508 if (result
.isSslRecoverableException()) {
1509 mLastSslUntrustedServerResult
= result
;
1510 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1515 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1516 dismissLoadingDialog();
1517 OCFile syncedFile
= operation
.getLocalFile();
1518 if (!result
.isSuccess()) {
1519 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1520 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1521 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1522 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1528 if (operation
.transferWasRequested()) {
1529 onTransferStateChanged(syncedFile
, true
, true
);
1532 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1540 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1542 * @param operation Creation operation performed.
1543 * @param result Result of the creation.
1545 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1546 if (result
.isSuccess()) {
1547 dismissLoadingDialog();
1548 refreshListOfFilesFragment();
1550 dismissLoadingDialog();
1552 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1553 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1557 } catch (NotFoundException e
) {
1558 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1568 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1569 refreshListOfFilesFragment();
1570 FileFragment details
= getSecondFragment();
1571 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1572 if (downloading
|| uploading
) {
1573 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1575 if (!file
.fileExists()) {
1576 cleanSecondFragment();
1578 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1586 private void requestForDownload() {
1587 Account account
= getAccount();
1588 //if (!mWaitingToPreview.isDownloading()) {
1589 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1590 Intent i
= new Intent(this, FileDownloader
.class);
1591 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1592 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1598 private OCFile
getCurrentDir() {
1599 OCFile file
= getFile();
1601 if (file
.isFolder()) {
1603 } else if (getStorageManager() != null
) {
1604 String parentPath
= file
.getRemotePath().substring(0,
1605 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1606 return getStorageManager().getFileByPath(parentPath
);
1612 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1613 long currentSyncTime
= System
.currentTimeMillis();
1615 mSyncInProgress
= true
;
1617 // perform folder synchronization
1618 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1621 getFileOperationsHelper().isSharedSupported(),
1623 getStorageManager(),
1625 getApplicationContext()
1627 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1629 setSupportProgressBarIndeterminateVisibility(true
);
1631 setBackgroundText();
1635 * Show untrusted cert dialog
1637 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1638 // Show a dialog with the certificate info
1639 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1640 (CertificateCombinedException
)result
.getException());
1641 FragmentManager fm
= getSupportFragmentManager();
1642 FragmentTransaction ft
= fm
.beginTransaction();
1643 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1646 private void requestForDownload(OCFile file
) {
1647 Account account
= getAccount();
1648 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1649 Intent i
= new Intent(this, FileDownloader
.class);
1650 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1651 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1656 private void sendDownloadedFile(){
1657 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1658 mWaitingToSend
= null
;
1663 * Requests the download of the received {@link OCFile} , updates the UI
1664 * to monitor the download progress and prepares the activity to send the file
1665 * when the download finishes.
1667 * @param file {@link OCFile} to download and preview.
1669 public void startDownloadForSending(OCFile file
) {
1670 mWaitingToSend
= file
;
1671 requestForDownload(mWaitingToSend
);
1672 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1673 updateFragmentsVisibility(hasSecondFragment
);
1677 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1679 * @param file Image {@link OCFile} to show.
1681 public void startImagePreview(OCFile file
) {
1682 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1683 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1684 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1685 startActivity(showDetailsIntent
);
1690 * Stars the preview of an already down media {@link OCFile}.
1692 * @param file Media {@link OCFile} to preview.
1693 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1694 * @param autoplay When 'true', the playback will start without user interactions.
1696 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1697 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1698 setSecondFragment(mediaFragment
);
1699 updateFragmentsVisibility(true
);
1700 updateNavigationElementsInActionBar(file
);
1705 * Requests the download of the received {@link OCFile} , updates the UI
1706 * to monitor the download progress and prepares the activity to preview
1707 * or open the file when the download finishes.
1709 * @param file {@link OCFile} to download and preview.
1711 public void startDownloadForPreview(OCFile file
) {
1712 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1713 setSecondFragment(detailFragment
);
1714 mWaitingToPreview
= file
;
1715 requestForDownload();
1716 updateFragmentsVisibility(true
);
1717 updateNavigationElementsInActionBar(file
);
1722 public void cancelTransference(OCFile file
) {
1723 getFileOperationsHelper().cancelTransference(file
);
1724 if (mWaitingToPreview
!= null
&&
1725 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1726 mWaitingToPreview
= null
;
1728 if (mWaitingToSend
!= null
&&
1729 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1730 mWaitingToSend
= null
;
1732 onTransferStateChanged(file
, false
, false
);
1736 public void onRefresh(boolean ignoreETag
) {
1737 refreshList(ignoreETag
);
1741 public void onRefresh() {
1745 private void refreshList(boolean ignoreETag
) {
1746 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1747 if (listOfFiles
!= null
) {
1748 OCFile folder
= listOfFiles
.getCurrentFile();
1749 if (folder
!= null
) {
1750 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1751 listDirectory(mFile);*/
1752 startSyncFolderOperation(folder
, ignoreETag
);
1757 private void sortByDate(boolean ascending
){
1758 getListOfFilesFragment().sortByDate(ascending
);
1761 private void sortBySize(boolean ascending
){
1762 getListOfFilesFragment().sortBySize(ascending
);
1765 private void sortByName(boolean ascending
){
1766 getListOfFilesFragment().sortByName(ascending
);