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
.d(TAG
, "onCreate() start");
160 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
164 // PIN CODE request ; best location is to decide, let's try this first
165 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
167 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
171 /// grant that FileObserverService is watching favourite files
172 if (savedInstanceState
== null
) {
173 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
174 startService(initObserversIntent
);
177 /// Load of saved instance state
178 if(savedInstanceState
!= null
) {
179 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
180 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
181 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
184 mWaitingToPreview
= null
;
185 mSyncInProgress
= false
;
186 mWaitingToSend
= null
;
191 // Inflate and set the layout view
192 setContentView(R
.layout
.files
);
193 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
194 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
195 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
196 if (savedInstanceState
== null
) {
197 createMinFragments();
201 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
202 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
203 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
207 Log_OC
.d(TAG
, "onCreate() end");
211 protected void onStart() {
212 Log_OC
.d(TAG
, "onStart() start");
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 Log_OC
.d(TAG
, "onStart() end");
219 protected void onDestroy() {
220 Log_OC
.d(TAG
, "onDestroy() start");
222 Log_OC
.d(TAG
, "onDestroy() end");
226 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
229 protected void onAccountSet(boolean stateWasRecovered
) {
230 super.onAccountSet(stateWasRecovered
);
231 if (getAccount() != null
) {
232 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
233 OCFile file
= getFile();
234 // get parent from path
235 String parentPath
= "";
237 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
238 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
239 // get parent from path
240 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
241 if (getStorageManager().getFileByPath(parentPath
) == null
)
242 file
= null
; // not able to know the directory where the file is uploading
244 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
248 // fall back to root folder
249 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
252 setNavigationListWithFolder(file
);
254 if (!stateWasRecovered
) {
255 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
256 initFragmentsWithFile();
257 if (file
.isFolder()) {
258 startSyncFolderOperation(file
, false
);
262 updateFragmentsVisibility(!file
.isFolder());
263 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
269 private void setNavigationListWithFolder(OCFile file
) {
270 mDirectories
.clear();
271 OCFile fileIt
= file
;
273 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
274 if (fileIt
.isFolder()) {
275 mDirectories
.add(fileIt
.getFileName());
277 // get parent from path
278 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
279 fileIt
= getStorageManager().getFileByPath(parentPath
);
281 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
285 private void createMinFragments() {
286 OCFileListFragment listOfFiles
= new OCFileListFragment();
287 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
288 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
289 transaction
.commit();
292 private void initFragmentsWithFile() {
293 if (getAccount() != null
&& getFile() != null
) {
295 OCFileListFragment listOfFiles
= getListOfFilesFragment();
296 if (listOfFiles
!= null
) {
297 listOfFiles
.listDirectory(getCurrentDir());
299 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
303 OCFile file
= getFile();
304 Fragment secondFragment
= chooseInitialSecondFragment(file
);
305 if (secondFragment
!= null
) {
306 setSecondFragment(secondFragment
);
307 updateFragmentsVisibility(true
);
308 updateNavigationElementsInActionBar(file
);
311 cleanSecondFragment();
315 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
316 if (getAccount() == null
) {
317 Log_OC
.wtf(TAG
, "\t account is NULL");
319 if (getFile() == null
) {
320 Log_OC
.wtf(TAG
, "\t file is NULL");
325 private Fragment
chooseInitialSecondFragment(OCFile file
) {
326 Fragment secondFragment
= null
;
327 if (file
!= null
&& !file
.isFolder()) {
328 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
329 && file
.getLastSyncDateForProperties() > 0 // temporal fix
331 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
332 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
333 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
336 secondFragment
= new FileDetailFragment(file
, getAccount());
339 return secondFragment
;
344 * Replaces the second fragment managed by the activity with the received as
347 * Assumes never will be more than two fragments managed at the same time.
349 * @param fragment New second Fragment to set.
351 private void setSecondFragment(Fragment fragment
) {
352 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
353 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
354 transaction
.commit();
358 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
360 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
367 } else if (existsSecondFragment
) {
368 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
369 mLeftFragmentContainer
.setVisibility(View
.GONE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
380 mRightFragmentContainer
.setVisibility(View
.GONE
);
386 private OCFileListFragment
getListOfFilesFragment() {
387 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
388 if (listOfFiles
!= null
) {
389 return (OCFileListFragment
)listOfFiles
;
391 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
395 public FileFragment
getSecondFragment() {
396 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
397 if (second
!= null
) {
398 return (FileFragment
)second
;
403 protected void cleanSecondFragment() {
404 Fragment second
= getSecondFragment();
405 if (second
!= null
) {
406 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
410 updateFragmentsVisibility(false
);
411 updateNavigationElementsInActionBar(null
);
414 protected void refreshListOfFilesFragment() {
415 OCFileListFragment fileListFragment
= getListOfFilesFragment();
416 if (fileListFragment
!= null
) {
417 fileListFragment
.listDirectory();
421 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
422 FileFragment secondFragment
= getSecondFragment();
423 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
424 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
425 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
426 OCFile fileInFragment
= detailsFragment
.getFile();
427 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
428 // the user browsed to other file ; forget the automatic preview
429 mWaitingToPreview
= null
;
431 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
432 // grant that the right panel updates the progress bar
433 detailsFragment
.listenForTransferProgress();
434 detailsFragment
.updateFileDetails(true
, false
);
436 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
437 // update the right panel
438 boolean detailsFragmentChanged
= false
;
441 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
442 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
443 startMediaPreview(mWaitingToPreview
, 0, true
);
444 detailsFragmentChanged
= true
;
446 getFileOperationsHelper().openFile(mWaitingToPreview
);
449 mWaitingToPreview
= null
;
451 if (!detailsFragmentChanged
) {
452 detailsFragment
.updateFileDetails(false
, (success
));
459 public boolean onPrepareOptionsMenu(Menu menu
) {
460 if (BuildConfig
.DEBUG
) {
461 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
463 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
465 return super.onPrepareOptionsMenu(menu
);
469 public boolean onCreateOptionsMenu(Menu menu
) {
470 MenuInflater inflater
= getSherlock().getMenuInflater();
471 inflater
.inflate(R
.menu
.main_menu
, menu
);
476 public boolean onOptionsItemSelected(MenuItem item
) {
477 boolean retval
= true
;
478 switch (item
.getItemId()) {
479 case R
.id
.action_create_dir
: {
480 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
481 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
484 case R
.id
.action_sync_account
: {
485 startSynchronization();
488 case R
.id
.action_upload
: {
489 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
490 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
494 case R
.id
.action_settings
: {
495 Intent settingsIntent
= new Intent(this, Preferences
.class);
496 startActivity(settingsIntent
);
499 case R
.id
.action_logger
: {
500 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
501 startActivity(loggerIntent
);
504 case android
.R
.id
.home
: {
505 FileFragment second
= getSecondFragment();
506 OCFile currentDir
= getCurrentDir();
507 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
508 (second
!= null
&& second
.getFile() != null
)) {
514 case R
.id
.action_sort
: {
515 SharedPreferences appPreferences
= PreferenceManager
516 .getDefaultSharedPreferences(this);
518 // Read sorting order, default to sort by name ascending
519 Integer sortOrder
= appPreferences
520 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
522 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
523 builder
.setTitle(R
.string
.actionbar_sort_title
)
524 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
525 public void onClick(DialogInterface dialog
, int which
) {
535 // TODO re-enable when server-side folder size calculation is available
537 // sortBySize(false);
545 builder
.create().show();
549 retval
= super.onOptionsItemSelected(item
);
554 private void startSynchronization() {
555 Log_OC
.d(TAG
, "Got to start sync");
556 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
557 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
558 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
559 Bundle bundle
= new Bundle();
560 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
561 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
562 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
563 ContentResolver
.requestSync(
565 MainApp
.getAuthority(), bundle
);
567 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
568 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
569 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
570 builder
.setExpedited(true
);
571 builder
.setManual(true
);
574 // Fix bug in Android Lollipop when you click on refresh the whole account
575 Bundle extras
= new Bundle();
576 builder
.setExtras(extras
);
578 SyncRequest request
= builder
.build();
579 ContentResolver
.requestSync(request
);
585 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
586 if (itemPosition
!= 0) {
587 String targetPath
= "";
588 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
589 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
591 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
592 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
593 if (targetFolder
!= null
) {
594 browseTo(targetFolder
);
597 // the next operation triggers a new call to this method, but it's necessary to
598 // ensure that the name exposed in the action bar is the current directory when the
599 // user selected it in the navigation list
600 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
601 getSupportActionBar().setSelectedNavigationItem(0);
607 * Called, when the user selected something for uploading
610 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
612 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
614 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
615 //getClipData is only supported on api level 16+, Jelly Bean
616 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
617 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
618 Intent intent
= new Intent();
619 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
620 requestSimpleUpload(intent
, resultCode
);
623 requestSimpleUpload(data
, resultCode
);
625 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
626 requestMultipleUpload(data
, resultCode
);
628 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
630 final Intent fData
= data
;
631 final int fResultCode
= resultCode
;
632 getHandler().postDelayed(
636 requestMoveOperation(fData
, fResultCode
);
639 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
643 super.onActivityResult(requestCode
, resultCode
, data
);
648 private void requestMultipleUpload(Intent data
, int resultCode
) {
649 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
650 if (filePaths
!= null
) {
651 String
[] remotePaths
= new String
[filePaths
.length
];
652 String remotePathBase
= "";
654 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
655 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
657 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
658 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
659 for (int j
= 0; j
< remotePaths
.length
; j
++) {
660 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
663 Intent i
= new Intent(this, FileUploader
.class);
664 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
665 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
666 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
667 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
668 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
669 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
673 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
674 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
681 private void requestSimpleUpload(Intent data
, int resultCode
) {
682 String filePath
= null
;
683 String mimeType
= null
;
685 Uri selectedImageUri
= data
.getData();
688 mimeType
= getContentResolver().getType(selectedImageUri
);
690 String fileManagerString
= selectedImageUri
.getPath();
691 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
693 if (selectedImagePath
!= null
)
694 filePath
= selectedImagePath
;
696 filePath
= fileManagerString
;
698 } catch (Exception e
) {
699 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
702 if (filePath
== null
) {
703 Log_OC
.e(TAG
, "Couldn't resolve path to file");
704 Toast t
= Toast
.makeText(
705 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
712 Intent i
= new Intent(this, FileUploader
.class);
713 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
714 OCFile currentDir
= getCurrentDir();
715 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
717 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
718 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
720 if (cursor
!= null
&& cursor
.moveToFirst()) {
721 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
722 Log_OC
.v(TAG
, "Display Name: " + displayName
);
724 displayName
.replace(File
.separatorChar
, '_');
725 displayName
.replace(File
.pathSeparatorChar
, '_');
726 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
729 // and what happens in case of error?; wrong target name for the upload
735 remotePath
+= new File(filePath
).getName();
738 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
739 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
740 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
741 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
742 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
743 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
748 * Request the operation for moving the file/folder from one path to another
750 * @param data Intent received
751 * @param resultCode Result code received
753 private void requestMoveOperation(Intent data
, int resultCode
) {
754 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
755 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
756 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
760 public void onBackPressed() {
761 OCFileListFragment listOfFiles
= getListOfFilesFragment();
762 if (mDualPane
|| getSecondFragment() == null
) {
763 if (listOfFiles
!= null
) { // should never be null, indeed
764 if (mDirectories
.getCount() <= 1) {
768 int levelsUp
= listOfFiles
.onBrowseUp();
769 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
774 if (listOfFiles
!= null
) { // should never be null, indeed
775 setFile(listOfFiles
.getCurrentFile());
777 cleanSecondFragment();
782 protected void onSaveInstanceState(Bundle outState
) {
783 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
784 Log_OC
.d(TAG
, "onSaveInstanceState() start");
785 super.onSaveInstanceState(outState
);
786 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
787 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
788 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
789 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
791 Log_OC
.d(TAG
, "onSaveInstanceState() end");
797 protected void onResume() {
798 Log_OC
.d(TAG
, "onResume() start");
801 // refresh list of files
802 refreshListOfFilesFragment();
804 // Listen for sync messages
805 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
806 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
807 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
808 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
809 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
810 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
811 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
812 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
814 // Listen for upload messages
815 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
816 mUploadFinishReceiver
= new UploadFinishReceiver();
817 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
819 // Listen for download messages
820 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
821 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
822 mDownloadFinishReceiver
= new DownloadFinishReceiver();
823 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
825 Log_OC
.d(TAG
, "onResume() end");
830 protected void onPause() {
831 Log_OC
.d(TAG
, "onPause() start");
832 if (mSyncBroadcastReceiver
!= null
) {
833 unregisterReceiver(mSyncBroadcastReceiver
);
834 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
835 mSyncBroadcastReceiver
= null
;
837 if (mUploadFinishReceiver
!= null
) {
838 unregisterReceiver(mUploadFinishReceiver
);
839 mUploadFinishReceiver
= null
;
841 if (mDownloadFinishReceiver
!= null
) {
842 unregisterReceiver(mDownloadFinishReceiver
);
843 mDownloadFinishReceiver
= null
;
848 Log_OC
.d(TAG
, "onPause() end");
852 * Pushes a directory to the drop down list
853 * @param directory to push
854 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
856 public void pushDirname(OCFile directory
) {
857 if(!directory
.isFolder()){
858 throw new IllegalArgumentException("Only directories may be pushed!");
860 mDirectories
.insert(directory
.getFileName(), 0);
865 * Pops a directory name from the drop down list
866 * @return True, unless the stack is empty
868 public boolean popDirname() {
869 mDirectories
.remove(mDirectories
.getItem(0));
870 return !mDirectories
.isEmpty();
873 // Custom array adapter to override text colors
874 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
876 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
880 public View
getView(int position
, View convertView
, ViewGroup parent
) {
881 View v
= super.getView(position
, convertView
, parent
);
883 ((TextView
) v
).setTextColor(getResources().getColorStateList(
884 android
.R
.color
.white
));
886 fixRoot((TextView
) v
);
890 public View
getDropDownView(int position
, View convertView
,
892 View v
= super.getDropDownView(position
, convertView
, parent
);
894 ((TextView
) v
).setTextColor(getResources().getColorStateList(
895 android
.R
.color
.white
));
897 fixRoot((TextView
) v
);
901 private void fixRoot(TextView v
) {
902 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
903 v
.setText(R
.string
.default_display_name_for_root_folder
);
909 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
912 * {@link BroadcastReceiver} to enable syncing feedback in UI
915 public void onReceive(Context context
, Intent intent
) {
917 String event
= intent
.getAction();
918 Log_OC
.d(TAG
, "Received broadcast " + event
);
919 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
920 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
921 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
922 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
926 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
927 mSyncInProgress
= true
;
930 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
931 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
933 if (currentDir
== null
) {
934 // current folder was removed from the server
935 Toast
.makeText( FileDisplayActivity
.this,
936 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
942 if (currentFile
== null
&& !getFile().isFolder()) {
943 // currently selected file was removed in the server, and now we know it
944 cleanSecondFragment();
945 currentFile
= currentDir
;
948 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
949 OCFileListFragment fileListFragment
= getListOfFilesFragment();
950 if (fileListFragment
!= null
) {
951 fileListFragment
.listDirectory(currentDir
);
954 setFile(currentFile
);
957 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
959 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
961 /// TODO refactor and make common
962 synchResult
!= null
&& !synchResult
.isSuccess() &&
963 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
964 synchResult
.isIdPRedirection() ||
965 (synchResult
.isException() && synchResult
.getException()
966 instanceof AuthenticatorException
))) {
970 OwnCloudClient client
;
971 OwnCloudAccount ocAccount
=
972 new OwnCloudAccount(getAccount(), context
);
973 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
974 removeClientFor(ocAccount
));
976 if (client
!= null
) {
977 OwnCloudCredentials cred
= client
.getCredentials();
979 AccountManager am
= AccountManager
.get(context
);
980 if (cred
.authTokenExpires()) {
981 am
.invalidateAuthToken(
986 am
.clearPassword(getAccount());
990 requestCredentialsUpdate();
992 } catch (AccountNotFoundException e
) {
993 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
998 removeStickyBroadcast(intent
);
999 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1000 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1002 setBackgroundText();
1006 if (synchResult
!= null
) {
1007 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1008 mLastSslUntrustedServerResult
= synchResult
;
1011 } catch (RuntimeException e
) {
1012 // avoid app crashes after changing the serial id of RemoteOperationResult
1013 // in owncloud library with broadcast notifications pending to process
1014 removeStickyBroadcast(intent
);
1020 * Show a text message on screen view for notifying user if content is
1021 * loading or folder is empty
1023 private void setBackgroundText() {
1024 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1025 if (ocFileListFragment
!= null
) {
1026 int message
= R
.string
.file_list_loading
;
1027 if (!mSyncInProgress
) {
1028 // In case file list is empty
1029 message
= R
.string
.file_list_empty
;
1031 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1033 Log_OC
.e(TAG
, "OCFileListFragment is null");
1038 * Once the file upload has finished -> update view
1040 private class UploadFinishReceiver
extends BroadcastReceiver
{
1042 * Once the file upload has finished -> update view
1043 * @author David A. Velasco
1044 * {@link BroadcastReceiver} to enable upload feedback in UI
1047 public void onReceive(Context context
, Intent intent
) {
1049 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1050 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1051 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1052 OCFile currentDir
= getCurrentDir();
1053 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1054 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1056 if (sameAccount
&& isDescendant
) {
1057 refreshListOfFilesFragment();
1060 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1061 boolean renamedInUpload
= getFile().getRemotePath().
1062 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1063 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1065 FileFragment details
= getSecondFragment();
1066 boolean detailFragmentIsShown
= (details
!= null
&&
1067 details
instanceof FileDetailFragment
);
1069 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1070 if (uploadWasFine
) {
1071 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1073 if (renamedInUpload
) {
1074 String newName
= (new File(uploadedRemotePath
)).getName();
1075 Toast msg
= Toast
.makeText(
1078 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1083 if (uploadWasFine
|| getFile().fileExists()) {
1084 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1086 cleanSecondFragment();
1089 // Force the preview if the file is an image
1090 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1091 startImagePreview(getFile());
1092 } // TODO what about other kind of previews?
1096 if (intent
!= null
) {
1097 removeStickyBroadcast(intent
);
1107 * Class waiting for broadcast events from the {@link FileDownloader} service.
1109 * Updates the UI when a download is started or finished, provided that it is relevant for the
1112 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1114 //int refreshCounter = 0;
1116 public void onReceive(Context context
, Intent intent
) {
1118 boolean sameAccount
= isSameAccount(context
, intent
);
1119 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1120 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1122 if (sameAccount
&& isDescendant
) {
1123 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1124 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1125 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1126 refreshListOfFilesFragment();
1128 refreshSecondFragment(
1130 downloadedRemotePath
,
1131 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1135 if (mWaitingToSend
!= null
) {
1136 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1137 if (mWaitingToSend
.isDown()) {
1138 sendDownloadedFile();
1143 if (intent
!= null
) {
1144 removeStickyBroadcast(intent
);
1149 private boolean isDescendant(String downloadedRemotePath
) {
1150 OCFile currentDir
= getCurrentDir();
1152 currentDir
!= null
&&
1153 downloadedRemotePath
!= null
&&
1154 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1158 private boolean isAscendant(String linkedToRemotePath
) {
1159 OCFile currentDir
= getCurrentDir();
1161 currentDir
!= null
&&
1162 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1166 private boolean isSameAccount(Context context
, Intent intent
) {
1167 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1168 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1173 public void browseToRoot() {
1174 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1175 if (listOfFiles
!= null
) { // should never be null, indeed
1176 while (mDirectories
.getCount() > 1) {
1179 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1180 listOfFiles
.listDirectory(root
);
1181 setFile(listOfFiles
.getCurrentFile());
1182 startSyncFolderOperation(root
, false
);
1184 cleanSecondFragment();
1188 public void browseTo(OCFile folder
) {
1189 if (folder
== null
|| !folder
.isFolder()) {
1190 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1192 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1193 if (listOfFiles
!= null
) {
1194 setNavigationListWithFolder(folder
);
1195 listOfFiles
.listDirectory(folder
);
1196 setFile(listOfFiles
.getCurrentFile());
1197 startSyncFolderOperation(folder
, false
);
1199 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1201 cleanSecondFragment();
1208 * Updates action bar and second fragment, if in dual pane mode.
1211 public void onBrowsedDownTo(OCFile directory
) {
1212 pushDirname(directory
);
1213 cleanSecondFragment();
1216 startSyncFolderOperation(directory
, false
);
1221 * Shows the information of the {@link OCFile} received as a
1222 * parameter in the second fragment.
1224 * @param file {@link OCFile} whose details will be shown
1227 public void showDetails(OCFile file
) {
1228 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1229 setSecondFragment(detailFragment
);
1230 updateFragmentsVisibility(true
);
1231 updateNavigationElementsInActionBar(file
);
1239 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1240 ActionBar actionBar
= getSupportActionBar();
1242 // For adding content description tag to a title field in the action bar
1243 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1245 if (chosenFile
== null
|| mDualPane
) {
1246 // only list of files - set for browsing through folders
1247 OCFile currentDir
= getCurrentDir();
1248 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1249 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1250 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1252 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1253 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1254 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1255 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1258 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1259 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1262 actionBar
.setDisplayHomeAsUpEnabled(true
);
1263 actionBar
.setDisplayShowTitleEnabled(true
);
1264 actionBar
.setTitle(chosenFile
.getFileName());
1265 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1266 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1267 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1268 getWindow().getDecorView().findViewById(actionBarTitleId
).
1269 setContentDescription(chosenFile
.getFileName());
1276 protected ServiceConnection
newTransferenceServiceConnection() {
1277 return new ListServiceConnection();
1280 /** Defines callbacks for service binding, passed to bindService() */
1281 private class ListServiceConnection
implements ServiceConnection
{
1284 public void onServiceConnected(ComponentName component
, IBinder service
) {
1285 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1286 Log_OC
.d(TAG
, "Download service connected");
1287 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1288 if (mWaitingToPreview
!= null
)
1289 if (getStorageManager() != null
) {
1290 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1291 if (!mWaitingToPreview
.isDown()) {
1292 requestForDownload();
1296 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1297 Log_OC
.d(TAG
, "Upload service connected");
1298 mUploaderBinder
= (FileUploaderBinder
) service
;
1302 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1303 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1304 if (listOfFiles
!= null
) {
1305 listOfFiles
.listDirectory();
1307 FileFragment secondFragment
= getSecondFragment();
1308 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1309 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1310 detailFragment
.listenForTransferProgress();
1311 detailFragment
.updateFileDetails(false
, false
);
1316 public void onServiceDisconnected(ComponentName component
) {
1317 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1318 Log_OC
.d(TAG
, "Download service disconnected");
1319 mDownloaderBinder
= null
;
1320 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1321 Log_OC
.d(TAG
, "Upload service disconnected");
1322 mUploaderBinder
= null
;
1330 * Launch an intent to request the PIN code to the user before letting him use the app
1332 private void requestPinCode() {
1333 boolean pinStart
= false
;
1334 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1335 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1337 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1338 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1345 public void onSavedCertificate() {
1346 startSyncFolderOperation(getCurrentDir(), false
);
1351 public void onFailedSavingCertificate() {
1352 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1353 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1355 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1359 public void onCancelCertificate() {
1364 * Updates the view associated to the activity after the finish of some operation over files
1365 * in the current account.
1367 * @param operation Removal operation performed.
1368 * @param result Result of the removal.
1371 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1372 super.onRemoteOperationFinish(operation
, result
);
1374 if (operation
instanceof RemoveFileOperation
) {
1375 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1377 } else if (operation
instanceof RenameFileOperation
) {
1378 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1380 } else if (operation
instanceof SynchronizeFileOperation
) {
1381 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1383 } else if (operation
instanceof CreateFolderOperation
) {
1384 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1386 } else if (operation
instanceof CreateShareOperation
) {
1387 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1389 } else if (operation
instanceof UnshareLinkOperation
) {
1390 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1392 } else if (operation
instanceof MoveFileOperation
) {
1393 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1399 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1400 if (result
.isSuccess()) {
1401 refreshShowDetails();
1402 refreshListOfFilesFragment();
1407 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1408 if (result
.isSuccess()) {
1409 refreshShowDetails();
1410 refreshListOfFilesFragment();
1412 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1413 cleanSecondFragment();
1414 refreshListOfFilesFragment();
1418 private void refreshShowDetails() {
1419 FileFragment details
= getSecondFragment();
1420 if (details
!= null
) {
1421 OCFile file
= details
.getFile();
1423 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1424 if (details
instanceof PreviewMediaFragment
) {
1425 // Refresh OCFile of the fragment
1426 ((PreviewMediaFragment
) details
).updateFile(file
);
1431 invalidateOptionsMenu();
1436 * Updates the view associated to the activity after the finish of an operation trying to remove a
1439 * @param operation Removal operation performed.
1440 * @param result Result of the removal.
1442 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1443 dismissLoadingDialog();
1445 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1449 if (result
.isSuccess()) {
1450 OCFile removedFile
= operation
.getFile();
1451 FileFragment second
= getSecondFragment();
1452 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1453 if (second
instanceof PreviewMediaFragment
) {
1454 ((PreviewMediaFragment
)second
).stopPreview(true
);
1456 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1457 cleanSecondFragment();
1459 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1460 refreshListOfFilesFragment();
1462 invalidateOptionsMenu();
1464 if (result
.isSslRecoverableException()) {
1465 mLastSslUntrustedServerResult
= result
;
1466 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1473 * Updates the view associated to the activity after the finish of an operation trying to move a
1476 * @param operation Move operation performed.
1477 * @param result Result of the move operation.
1479 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1480 if (result
.isSuccess()) {
1481 dismissLoadingDialog();
1482 refreshListOfFilesFragment();
1484 dismissLoadingDialog();
1486 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1487 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1491 } catch (NotFoundException e
) {
1492 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1499 * Updates the view associated to the activity after the finish of an operation trying to rename a
1502 * @param operation Renaming operation performed.
1503 * @param result Result of the renaming.
1505 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1506 dismissLoadingDialog();
1507 OCFile renamedFile
= operation
.getFile();
1508 if (result
.isSuccess()) {
1509 FileFragment details
= getSecondFragment();
1510 if (details
!= null
) {
1511 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1512 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1513 showDetails(renamedFile
);
1515 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1516 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1517 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1518 int position
= ((PreviewMediaFragment
)details
).getPosition();
1519 startMediaPreview(renamedFile
, position
, true
);
1521 getFileOperationsHelper().openFile(renamedFile
);
1526 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1527 refreshListOfFilesFragment();
1531 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1535 if (result
.isSslRecoverableException()) {
1536 mLastSslUntrustedServerResult
= result
;
1537 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1542 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1543 dismissLoadingDialog();
1544 OCFile syncedFile
= operation
.getLocalFile();
1545 if (!result
.isSuccess()) {
1546 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1547 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1548 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1549 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1555 if (operation
.transferWasRequested()) {
1556 onTransferStateChanged(syncedFile
, true
, true
);
1559 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1567 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1569 * @param operation Creation operation performed.
1570 * @param result Result of the creation.
1572 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1573 if (result
.isSuccess()) {
1574 dismissLoadingDialog();
1575 refreshListOfFilesFragment();
1577 dismissLoadingDialog();
1579 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1580 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1584 } catch (NotFoundException e
) {
1585 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1595 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1596 refreshListOfFilesFragment();
1597 FileFragment details
= getSecondFragment();
1598 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1599 if (downloading
|| uploading
) {
1600 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1602 if (!file
.fileExists()) {
1603 cleanSecondFragment();
1605 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1613 private void requestForDownload() {
1614 Account account
= getAccount();
1615 //if (!mWaitingToPreview.isDownloading()) {
1616 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1617 Intent i
= new Intent(this, FileDownloader
.class);
1618 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1619 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1625 private OCFile
getCurrentDir() {
1626 OCFile file
= getFile();
1628 if (file
.isFolder()) {
1630 } else if (getStorageManager() != null
) {
1631 String parentPath
= file
.getRemotePath().substring(0,
1632 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1633 return getStorageManager().getFileByPath(parentPath
);
1639 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1640 long currentSyncTime
= System
.currentTimeMillis();
1642 mSyncInProgress
= true
;
1644 // perform folder synchronization
1645 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1648 getFileOperationsHelper().isSharedSupported(),
1650 getStorageManager(),
1652 getApplicationContext()
1654 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1656 setSupportProgressBarIndeterminateVisibility(true
);
1658 setBackgroundText();
1662 * Show untrusted cert dialog
1664 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1665 // Show a dialog with the certificate info
1666 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1667 (CertificateCombinedException
)result
.getException());
1668 FragmentManager fm
= getSupportFragmentManager();
1669 FragmentTransaction ft
= fm
.beginTransaction();
1670 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1673 private void requestForDownload(OCFile file
) {
1674 Account account
= getAccount();
1675 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1676 Intent i
= new Intent(this, FileDownloader
.class);
1677 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1678 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1683 private void sendDownloadedFile(){
1684 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1685 mWaitingToSend
= null
;
1690 * Requests the download of the received {@link OCFile} , updates the UI
1691 * to monitor the download progress and prepares the activity to send the file
1692 * when the download finishes.
1694 * @param file {@link OCFile} to download and preview.
1696 public void startDownloadForSending(OCFile file
) {
1697 mWaitingToSend
= file
;
1698 requestForDownload(mWaitingToSend
);
1699 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1700 updateFragmentsVisibility(hasSecondFragment
);
1704 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1706 * @param file Image {@link OCFile} to show.
1708 public void startImagePreview(OCFile file
) {
1709 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1710 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1711 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1712 startActivity(showDetailsIntent
);
1717 * Stars the preview of an already down media {@link OCFile}.
1719 * @param file Media {@link OCFile} to preview.
1720 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1721 * @param autoplay When 'true', the playback will start without user interactions.
1723 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1724 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1725 setSecondFragment(mediaFragment
);
1726 updateFragmentsVisibility(true
);
1727 updateNavigationElementsInActionBar(file
);
1732 * Requests the download of the received {@link OCFile} , updates the UI
1733 * to monitor the download progress and prepares the activity to preview
1734 * or open the file when the download finishes.
1736 * @param file {@link OCFile} to download and preview.
1738 public void startDownloadForPreview(OCFile file
) {
1739 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1740 setSecondFragment(detailFragment
);
1741 mWaitingToPreview
= file
;
1742 requestForDownload();
1743 updateFragmentsVisibility(true
);
1744 updateNavigationElementsInActionBar(file
);
1749 public void cancelTransference(OCFile file
) {
1750 getFileOperationsHelper().cancelTransference(file
);
1751 if (mWaitingToPreview
!= null
&&
1752 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1753 mWaitingToPreview
= null
;
1755 if (mWaitingToSend
!= null
&&
1756 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1757 mWaitingToSend
= null
;
1759 onTransferStateChanged(file
, false
, false
);
1763 public void onRefresh(boolean ignoreETag
) {
1764 refreshList(ignoreETag
);
1768 public void onRefresh() {
1772 private void refreshList(boolean ignoreETag
) {
1773 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1774 if (listOfFiles
!= null
) {
1775 OCFile folder
= listOfFiles
.getCurrentFile();
1776 if (folder
!= null
) {
1777 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1778 listDirectory(mFile);*/
1779 startSyncFolderOperation(folder
, ignoreETag
);
1784 private void sortByDate(boolean ascending
){
1785 getListOfFilesFragment().sortByDate(ascending
);
1788 private void sortBySize(boolean ascending
){
1789 getListOfFilesFragment().sortBySize(ascending
);
1792 private void sortByName(boolean ascending
){
1793 getListOfFilesFragment().sortByName(ascending
);