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
.authentication
.PassCodeManager
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
84 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
85 import com
.owncloud
.android
.operations
.CreateShareOperation
;
86 import com
.owncloud
.android
.operations
.MoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RenameFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
90 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
91 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
92 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
93 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
94 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
101 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
106 import com
.owncloud
.android
.utils
.DisplayUtils
;
107 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
108 import com
.owncloud
.android
.utils
.FileStorageUtils
;
109 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
151 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
158 private Boolean mUnlocked
= false
;
161 protected void onCreate(Bundle savedInstanceState
) {
162 Log_OC
.d(TAG
, "onCreate() start");
163 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
165 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
167 /// grant that FileObserverService is watching favorite files
168 if (savedInstanceState
== null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
189 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
190 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
191 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
192 if (savedInstanceState
== null
) {
193 createMinFragments();
197 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
198 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203 Log_OC
.d(TAG
, "onCreate() end");
207 protected void onStart() {
208 Log_OC
.d(TAG
, "onStart() start");
210 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
211 Log_OC
.d(TAG
, "onStart() end");
215 protected void onDestroy() {
216 Log_OC
.d(TAG
, "onDestroy() start");
218 Log_OC
.d(TAG
, "onDestroy() end");
222 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
225 protected void onAccountSet(boolean stateWasRecovered
) {
226 super.onAccountSet(stateWasRecovered
);
227 if (getAccount() != null
) {
228 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
229 OCFile file
= getFile();
230 // get parent from path
231 String parentPath
= "";
233 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
234 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
235 // get parent from path
236 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
237 if (getStorageManager().getFileByPath(parentPath
) == null
)
238 file
= null
; // not able to know the directory where the file is uploading
240 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
244 // fall back to root folder
245 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
248 setNavigationListWithFolder(file
);
250 if (!stateWasRecovered
) {
251 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
252 initFragmentsWithFile();
253 if (file
.isFolder()) {
254 startSyncFolderOperation(file
, false
);
258 updateFragmentsVisibility(!file
.isFolder());
259 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
265 private void setNavigationListWithFolder(OCFile file
) {
266 mDirectories
.clear();
267 OCFile fileIt
= file
;
269 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
270 if (fileIt
.isFolder()) {
271 mDirectories
.add(fileIt
.getFileName());
273 // get parent from path
274 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
275 fileIt
= getStorageManager().getFileByPath(parentPath
);
277 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
281 private void createMinFragments() {
282 OCFileListFragment listOfFiles
= new OCFileListFragment();
283 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
284 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
285 transaction
.commit();
288 private void initFragmentsWithFile() {
289 if (getAccount() != null
&& getFile() != null
) {
291 OCFileListFragment listOfFiles
= getListOfFilesFragment();
292 if (listOfFiles
!= null
) {
293 listOfFiles
.listDirectory(getCurrentDir());
295 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
299 OCFile file
= getFile();
300 Fragment secondFragment
= chooseInitialSecondFragment(file
);
301 if (secondFragment
!= null
) {
302 setSecondFragment(secondFragment
);
303 updateFragmentsVisibility(true
);
304 updateNavigationElementsInActionBar(file
);
307 cleanSecondFragment();
311 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
312 if (getAccount() == null
) {
313 Log_OC
.wtf(TAG
, "\t account is NULL");
315 if (getFile() == null
) {
316 Log_OC
.wtf(TAG
, "\t file is NULL");
321 private Fragment
chooseInitialSecondFragment(OCFile file
) {
322 Fragment secondFragment
= null
;
323 if (file
!= null
&& !file
.isFolder()) {
324 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
325 && file
.getLastSyncDateForProperties() > 0 // temporal fix
327 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
328 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
329 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
332 secondFragment
= new FileDetailFragment(file
, getAccount());
335 return secondFragment
;
340 * Replaces the second fragment managed by the activity with the received as
343 * Assumes never will be more than two fragments managed at the same time.
345 * @param fragment New second Fragment to set.
347 private void setSecondFragment(Fragment fragment
) {
348 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
349 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
350 transaction
.commit();
354 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
356 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
357 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
359 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
360 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
363 } else if (existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
365 mLeftFragmentContainer
.setVisibility(View
.GONE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
372 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
376 mRightFragmentContainer
.setVisibility(View
.GONE
);
382 private OCFileListFragment
getListOfFilesFragment() {
383 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
384 if (listOfFiles
!= null
) {
385 return (OCFileListFragment
)listOfFiles
;
387 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
391 public FileFragment
getSecondFragment() {
392 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
393 if (second
!= null
) {
394 return (FileFragment
)second
;
399 protected void cleanSecondFragment() {
400 Fragment second
= getSecondFragment();
401 if (second
!= null
) {
402 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
406 updateFragmentsVisibility(false
);
407 updateNavigationElementsInActionBar(null
);
410 protected void refreshListOfFilesFragment() {
411 OCFileListFragment fileListFragment
= getListOfFilesFragment();
412 if (fileListFragment
!= null
) {
413 fileListFragment
.listDirectory();
417 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
418 FileFragment secondFragment
= getSecondFragment();
419 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
420 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
421 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
422 OCFile fileInFragment
= detailsFragment
.getFile();
423 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
424 // the user browsed to other file ; forget the automatic preview
425 mWaitingToPreview
= null
;
427 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
428 // grant that the right panel updates the progress bar
429 detailsFragment
.listenForTransferProgress();
430 detailsFragment
.updateFileDetails(true
, false
);
432 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
433 // update the right panel
434 boolean detailsFragmentChanged
= false
;
437 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
438 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
439 startMediaPreview(mWaitingToPreview
, 0, true
);
440 detailsFragmentChanged
= true
;
442 getFileOperationsHelper().openFile(mWaitingToPreview
);
445 mWaitingToPreview
= null
;
447 if (!detailsFragmentChanged
) {
448 detailsFragment
.updateFileDetails(false
, (success
));
455 public boolean onPrepareOptionsMenu(Menu menu
) {
456 if (BuildConfig
.DEBUG
) {
457 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
459 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
461 return super.onPrepareOptionsMenu(menu
);
465 public boolean onCreateOptionsMenu(Menu menu
) {
466 MenuInflater inflater
= getSherlock().getMenuInflater();
467 inflater
.inflate(R
.menu
.main_menu
, menu
);
472 public boolean onOptionsItemSelected(MenuItem item
) {
473 boolean retval
= true
;
474 switch (item
.getItemId()) {
475 case R
.id
.action_create_dir
: {
476 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
477 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
480 case R
.id
.action_sync_account
: {
481 startSynchronization();
484 case R
.id
.action_upload
: {
485 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
486 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
490 case R
.id
.action_settings
: {
491 Intent settingsIntent
= new Intent(this, Preferences
.class);
492 startActivity(settingsIntent
);
495 case R
.id
.action_logger
: {
496 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
497 startActivity(loggerIntent
);
500 case android
.R
.id
.home
: {
501 FileFragment second
= getSecondFragment();
502 OCFile currentDir
= getCurrentDir();
503 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
504 (second
!= null
&& second
.getFile() != null
)) {
510 case R
.id
.action_sort
: {
511 SharedPreferences appPreferences
= PreferenceManager
512 .getDefaultSharedPreferences(this);
514 // Read sorting order, default to sort by name ascending
515 Integer sortOrder
= appPreferences
516 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
518 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
519 builder
.setTitle(R
.string
.actionbar_sort_title
)
520 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
521 public void onClick(DialogInterface dialog
, int which
) {
537 builder
.create().show();
541 retval
= super.onOptionsItemSelected(item
);
546 private void startSynchronization() {
547 Log_OC
.d(TAG
, "Got to start sync");
548 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
549 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
550 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
551 Bundle bundle
= new Bundle();
552 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
553 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
554 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
555 ContentResolver
.requestSync(
557 MainApp
.getAuthority(), bundle
);
559 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
560 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
561 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
562 builder
.setExpedited(true
);
563 builder
.setManual(true
);
566 // Fix bug in Android Lollipop when you click on refresh the whole account
567 Bundle extras
= new Bundle();
568 builder
.setExtras(extras
);
570 SyncRequest request
= builder
.build();
571 ContentResolver
.requestSync(request
);
577 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
578 if (itemPosition
!= 0) {
579 String targetPath
= "";
580 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
581 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
583 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
584 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
585 if (targetFolder
!= null
) {
586 browseTo(targetFolder
);
589 // the next operation triggers a new call to this method, but it's necessary to
590 // ensure that the name exposed in the action bar is the current directory when the
591 // user selected it in the navigation list
592 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
593 getSupportActionBar().setSelectedNavigationItem(0);
599 * Called, when the user selected something for uploading
602 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
604 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
606 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
607 //getClipData is only supported on api level 16+, Jelly Bean
608 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
609 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
610 Intent intent
= new Intent();
611 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
612 requestSimpleUpload(intent
, resultCode
);
615 requestSimpleUpload(data
, resultCode
);
617 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
618 requestMultipleUpload(data
, resultCode
);
620 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
622 final Intent fData
= data
;
623 final int fResultCode
= resultCode
;
624 getHandler().postDelayed(
628 requestMoveOperation(fData
, fResultCode
);
631 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
635 super.onActivityResult(requestCode
, resultCode
, data
);
640 private void requestMultipleUpload(Intent data
, int resultCode
) {
641 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
642 if (filePaths
!= null
) {
643 String
[] remotePaths
= new String
[filePaths
.length
];
644 String remotePathBase
= "";
646 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
647 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
649 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
650 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
651 for (int j
= 0; j
< remotePaths
.length
; j
++) {
652 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
655 Intent i
= new Intent(this, FileUploader
.class);
656 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
657 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
658 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
659 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
660 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
661 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
665 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
666 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
673 private void requestSimpleUpload(Intent data
, int resultCode
) {
674 String filePath
= null
;
675 String mimeType
= null
;
677 Uri selectedImageUri
= data
.getData();
680 mimeType
= getContentResolver().getType(selectedImageUri
);
682 String fileManagerString
= selectedImageUri
.getPath();
683 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
685 if (selectedImagePath
!= null
)
686 filePath
= selectedImagePath
;
688 filePath
= fileManagerString
;
690 } catch (Exception e
) {
691 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
694 if (filePath
== null
) {
695 Log_OC
.e(TAG
, "Couldn't resolve path to file");
696 Toast t
= Toast
.makeText(
697 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
704 Intent i
= new Intent(this, FileUploader
.class);
705 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
706 OCFile currentDir
= getCurrentDir();
707 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
709 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
710 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
712 if (cursor
!= null
&& cursor
.moveToFirst()) {
713 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
714 Log_OC
.v(TAG
, "Display Name: " + displayName
);
716 displayName
.replace(File
.separatorChar
, '_');
717 displayName
.replace(File
.pathSeparatorChar
, '_');
718 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
721 // and what happens in case of error?; wrong target name for the upload
727 remotePath
+= new File(filePath
).getName();
730 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
731 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
732 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
733 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
734 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
735 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
740 * Request the operation for moving the file/folder from one path to another
742 * @param data Intent received
743 * @param resultCode Result code received
745 private void requestMoveOperation(Intent data
, int resultCode
) {
746 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
747 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
748 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
752 public void onBackPressed() {
753 OCFileListFragment listOfFiles
= getListOfFilesFragment();
754 if (mDualPane
|| getSecondFragment() == null
) {
755 if (listOfFiles
!= null
) { // should never be null, indeed
756 if (mDirectories
.getCount() <= 1) {
760 int levelsUp
= listOfFiles
.onBrowseUp();
761 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
766 if (listOfFiles
!= null
) { // should never be null, indeed
767 setFile(listOfFiles
.getCurrentFile());
769 cleanSecondFragment();
774 protected void onSaveInstanceState(Bundle outState
) {
775 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
776 Log_OC
.d(TAG
, "onSaveInstanceState() start");
777 super.onSaveInstanceState(outState
);
778 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
779 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
780 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
781 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
783 Log_OC
.d(TAG
, "onSaveInstanceState() end");
789 protected void onResume() {
790 Log_OC
.d(TAG
, "onResume() start");
793 // refresh list of files
794 refreshListOfFilesFragment();
796 // Listen for sync messages
797 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
798 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
799 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
800 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
801 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
802 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
803 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
804 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
806 // Listen for upload messages
807 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
808 mUploadFinishReceiver
= new UploadFinishReceiver();
809 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
811 // Listen for download messages
812 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
813 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
814 mDownloadFinishReceiver
= new DownloadFinishReceiver();
815 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
817 Log_OC
.d(TAG
, "onResume() end");
822 protected void onPause() {
823 Log_OC
.d(TAG
, "onPause() start");
824 if (mSyncBroadcastReceiver
!= null
) {
825 unregisterReceiver(mSyncBroadcastReceiver
);
826 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
827 mSyncBroadcastReceiver
= null
;
829 if (mUploadFinishReceiver
!= null
) {
830 unregisterReceiver(mUploadFinishReceiver
);
831 mUploadFinishReceiver
= null
;
833 if (mDownloadFinishReceiver
!= null
) {
834 unregisterReceiver(mDownloadFinishReceiver
);
835 mDownloadFinishReceiver
= null
;
839 Log_OC
.d(TAG
, "onPause() end");
843 * Pushes a directory to the drop down list
844 * @param directory to push
845 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
847 public void pushDirname(OCFile directory
) {
848 if(!directory
.isFolder()){
849 throw new IllegalArgumentException("Only directories may be pushed!");
851 mDirectories
.insert(directory
.getFileName(), 0);
856 * Pops a directory name from the drop down list
857 * @return True, unless the stack is empty
859 public boolean popDirname() {
860 mDirectories
.remove(mDirectories
.getItem(0));
861 return !mDirectories
.isEmpty();
864 // Custom array adapter to override text colors
865 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
867 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
871 public View
getView(int position
, View convertView
, ViewGroup parent
) {
872 View v
= super.getView(position
, convertView
, parent
);
874 ((TextView
) v
).setTextColor(getResources().getColorStateList(
875 android
.R
.color
.white
));
877 fixRoot((TextView
) v
);
881 public View
getDropDownView(int position
, View convertView
,
883 View v
= super.getDropDownView(position
, convertView
, parent
);
885 ((TextView
) v
).setTextColor(getResources().getColorStateList(
886 android
.R
.color
.white
));
888 fixRoot((TextView
) v
);
892 private void fixRoot(TextView v
) {
893 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
894 v
.setText(R
.string
.default_display_name_for_root_folder
);
900 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
903 * {@link BroadcastReceiver} to enable syncing feedback in UI
906 public void onReceive(Context context
, Intent intent
) {
908 String event
= intent
.getAction();
909 Log_OC
.d(TAG
, "Received broadcast " + event
);
910 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
911 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
912 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
913 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
917 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
918 mSyncInProgress
= true
;
921 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
922 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
924 if (currentDir
== null
) {
925 // current folder was removed from the server
926 Toast
.makeText( FileDisplayActivity
.this,
927 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
933 if (currentFile
== null
&& !getFile().isFolder()) {
934 // currently selected file was removed in the server, and now we know it
935 cleanSecondFragment();
936 currentFile
= currentDir
;
939 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
940 OCFileListFragment fileListFragment
= getListOfFilesFragment();
941 if (fileListFragment
!= null
) {
942 fileListFragment
.listDirectory(currentDir
);
945 setFile(currentFile
);
948 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
950 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
952 /// TODO refactor and make common
953 synchResult
!= null
&& !synchResult
.isSuccess() &&
954 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
955 synchResult
.isIdPRedirection() ||
956 (synchResult
.isException() && synchResult
.getException()
957 instanceof AuthenticatorException
))) {
961 OwnCloudClient client
;
962 OwnCloudAccount ocAccount
=
963 new OwnCloudAccount(getAccount(), context
);
964 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
965 removeClientFor(ocAccount
));
967 if (client
!= null
) {
968 OwnCloudCredentials cred
= client
.getCredentials();
970 AccountManager am
= AccountManager
.get(context
);
971 if (cred
.authTokenExpires()) {
972 am
.invalidateAuthToken(
977 am
.clearPassword(getAccount());
981 requestCredentialsUpdate();
983 } catch (AccountNotFoundException e
) {
984 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
989 removeStickyBroadcast(intent
);
990 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
991 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
997 if (synchResult
!= null
) {
998 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
999 mLastSslUntrustedServerResult
= synchResult
;
1002 } catch (RuntimeException e
) {
1003 // avoid app crashes after changing the serial id of RemoteOperationResult
1004 // in owncloud library with broadcast notifications pending to process
1005 removeStickyBroadcast(intent
);
1011 * Show a text message on screen view for notifying user if content is
1012 * loading or folder is empty
1014 private void setBackgroundText() {
1015 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1016 if (ocFileListFragment
!= null
) {
1017 int message
= R
.string
.file_list_loading
;
1018 if (!mSyncInProgress
) {
1019 // In case file list is empty
1020 message
= R
.string
.file_list_empty
;
1022 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1024 Log_OC
.e(TAG
, "OCFileListFragment is null");
1029 * Once the file upload has finished -> update view
1031 private class UploadFinishReceiver
extends BroadcastReceiver
{
1033 * Once the file upload has finished -> update view
1034 * @author David A. Velasco
1035 * {@link BroadcastReceiver} to enable upload feedback in UI
1038 public void onReceive(Context context
, Intent intent
) {
1040 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1041 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1042 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1043 OCFile currentDir
= getCurrentDir();
1044 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1045 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1047 if (sameAccount
&& isDescendant
) {
1048 refreshListOfFilesFragment();
1051 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1052 boolean renamedInUpload
= getFile().getRemotePath().
1053 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1054 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1056 FileFragment details
= getSecondFragment();
1057 boolean detailFragmentIsShown
= (details
!= null
&&
1058 details
instanceof FileDetailFragment
);
1060 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1061 if (uploadWasFine
) {
1062 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1064 if (renamedInUpload
) {
1065 String newName
= (new File(uploadedRemotePath
)).getName();
1066 Toast msg
= Toast
.makeText(
1069 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1074 if (uploadWasFine
|| getFile().fileExists()) {
1075 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1077 cleanSecondFragment();
1080 // Force the preview if the file is an image
1081 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1082 startImagePreview(getFile());
1083 } // TODO what about other kind of previews?
1087 if (intent
!= null
) {
1088 removeStickyBroadcast(intent
);
1098 * Class waiting for broadcast events from the {@link FileDownloader} service.
1100 * Updates the UI when a download is started or finished, provided that it is relevant for the
1103 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1105 //int refreshCounter = 0;
1107 public void onReceive(Context context
, Intent intent
) {
1109 boolean sameAccount
= isSameAccount(context
, intent
);
1110 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1111 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1113 if (sameAccount
&& isDescendant
) {
1114 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1115 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1116 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1117 refreshListOfFilesFragment();
1119 refreshSecondFragment(
1121 downloadedRemotePath
,
1122 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1126 if (mWaitingToSend
!= null
) {
1127 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1128 if (mWaitingToSend
.isDown()) {
1129 sendDownloadedFile();
1134 if (intent
!= null
) {
1135 removeStickyBroadcast(intent
);
1140 private boolean isDescendant(String downloadedRemotePath
) {
1141 OCFile currentDir
= getCurrentDir();
1143 currentDir
!= null
&&
1144 downloadedRemotePath
!= null
&&
1145 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1149 private boolean isAscendant(String linkedToRemotePath
) {
1150 OCFile currentDir
= getCurrentDir();
1152 currentDir
!= null
&&
1153 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1157 private boolean isSameAccount(Context context
, Intent intent
) {
1158 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1159 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1164 public void browseToRoot() {
1165 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1166 if (listOfFiles
!= null
) { // should never be null, indeed
1167 while (mDirectories
.getCount() > 1) {
1170 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1171 listOfFiles
.listDirectory(root
);
1172 setFile(listOfFiles
.getCurrentFile());
1173 startSyncFolderOperation(root
, false
);
1175 cleanSecondFragment();
1179 public void browseTo(OCFile folder
) {
1180 if (folder
== null
|| !folder
.isFolder()) {
1181 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1183 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1184 if (listOfFiles
!= null
) {
1185 setNavigationListWithFolder(folder
);
1186 listOfFiles
.listDirectory(folder
);
1187 setFile(listOfFiles
.getCurrentFile());
1188 startSyncFolderOperation(folder
, false
);
1190 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1192 cleanSecondFragment();
1199 * Updates action bar and second fragment, if in dual pane mode.
1202 public void onBrowsedDownTo(OCFile directory
) {
1203 pushDirname(directory
);
1204 cleanSecondFragment();
1207 startSyncFolderOperation(directory
, false
);
1212 * Shows the information of the {@link OCFile} received as a
1213 * parameter in the second fragment.
1215 * @param file {@link OCFile} whose details will be shown
1218 public void showDetails(OCFile file
) {
1219 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1220 setSecondFragment(detailFragment
);
1221 updateFragmentsVisibility(true
);
1222 updateNavigationElementsInActionBar(file
);
1230 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1231 ActionBar actionBar
= getSupportActionBar();
1233 // For adding content description tag to a title field in the action bar
1234 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1236 if (chosenFile
== null
|| mDualPane
) {
1237 // only list of files - set for browsing through folders
1238 OCFile currentDir
= getCurrentDir();
1239 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1240 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1241 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1243 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1244 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1245 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1246 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1249 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1250 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1253 actionBar
.setDisplayHomeAsUpEnabled(true
);
1254 actionBar
.setDisplayShowTitleEnabled(true
);
1255 actionBar
.setTitle(chosenFile
.getFileName());
1256 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1257 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1258 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1259 getWindow().getDecorView().findViewById(actionBarTitleId
).
1260 setContentDescription(chosenFile
.getFileName());
1267 protected ServiceConnection
newTransferenceServiceConnection() {
1268 return new ListServiceConnection();
1271 /** Defines callbacks for service binding, passed to bindService() */
1272 private class ListServiceConnection
implements ServiceConnection
{
1275 public void onServiceConnected(ComponentName component
, IBinder service
) {
1276 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1277 Log_OC
.d(TAG
, "Download service connected");
1278 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1279 if (mWaitingToPreview
!= null
)
1280 if (getStorageManager() != null
) {
1281 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1282 if (!mWaitingToPreview
.isDown()) {
1283 requestForDownload();
1287 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1288 Log_OC
.d(TAG
, "Upload service connected");
1289 mUploaderBinder
= (FileUploaderBinder
) service
;
1293 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1294 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1295 if (listOfFiles
!= null
) {
1296 listOfFiles
.listDirectory();
1298 FileFragment secondFragment
= getSecondFragment();
1299 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1300 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1301 detailFragment
.listenForTransferProgress();
1302 detailFragment
.updateFileDetails(false
, false
);
1307 public void onServiceDisconnected(ComponentName component
) {
1308 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1309 Log_OC
.d(TAG
, "Download service disconnected");
1310 mDownloaderBinder
= null
;
1311 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1312 Log_OC
.d(TAG
, "Upload service disconnected");
1313 mUploaderBinder
= null
;
1319 public void onSavedCertificate() {
1320 startSyncFolderOperation(getCurrentDir(), false
);
1325 public void onFailedSavingCertificate() {
1326 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1327 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1329 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1333 public void onCancelCertificate() {
1338 * Updates the view associated to the activity after the finish of some operation over files
1339 * in the current account.
1341 * @param operation Removal operation performed.
1342 * @param result Result of the removal.
1345 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1346 super.onRemoteOperationFinish(operation
, result
);
1348 if (operation
instanceof RemoveFileOperation
) {
1349 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1351 } else if (operation
instanceof RenameFileOperation
) {
1352 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1354 } else if (operation
instanceof SynchronizeFileOperation
) {
1355 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1357 } else if (operation
instanceof CreateFolderOperation
) {
1358 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1360 } else if (operation
instanceof CreateShareOperation
) {
1361 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1363 } else if (operation
instanceof UnshareLinkOperation
) {
1364 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1366 } else if (operation
instanceof MoveFileOperation
) {
1367 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1373 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1374 if (result
.isSuccess()) {
1375 refreshShowDetails();
1376 refreshListOfFilesFragment();
1381 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1382 if (result
.isSuccess()) {
1383 refreshShowDetails();
1384 refreshListOfFilesFragment();
1386 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1387 cleanSecondFragment();
1388 refreshListOfFilesFragment();
1392 private void refreshShowDetails() {
1393 FileFragment details
= getSecondFragment();
1394 if (details
!= null
) {
1395 OCFile file
= details
.getFile();
1397 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1398 if (details
instanceof PreviewMediaFragment
) {
1399 // Refresh OCFile of the fragment
1400 ((PreviewMediaFragment
) details
).updateFile(file
);
1405 invalidateOptionsMenu();
1410 * Updates the view associated to the activity after the finish of an operation trying to remove a
1413 * @param operation Removal operation performed.
1414 * @param result Result of the removal.
1416 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1417 dismissLoadingDialog();
1419 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1423 if (result
.isSuccess()) {
1424 OCFile removedFile
= operation
.getFile();
1425 FileFragment second
= getSecondFragment();
1426 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1427 if (second
instanceof PreviewMediaFragment
) {
1428 ((PreviewMediaFragment
)second
).stopPreview(true
);
1430 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1431 cleanSecondFragment();
1433 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1434 refreshListOfFilesFragment();
1436 invalidateOptionsMenu();
1438 if (result
.isSslRecoverableException()) {
1439 mLastSslUntrustedServerResult
= result
;
1440 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1447 * Updates the view associated to the activity after the finish of an operation trying to move a
1450 * @param operation Move operation performed.
1451 * @param result Result of the move operation.
1453 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1454 if (result
.isSuccess()) {
1455 dismissLoadingDialog();
1456 refreshListOfFilesFragment();
1458 dismissLoadingDialog();
1460 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1461 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1465 } catch (NotFoundException e
) {
1466 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1473 * Updates the view associated to the activity after the finish of an operation trying to rename a
1476 * @param operation Renaming operation performed.
1477 * @param result Result of the renaming.
1479 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1480 dismissLoadingDialog();
1481 OCFile renamedFile
= operation
.getFile();
1482 if (result
.isSuccess()) {
1483 FileFragment details
= getSecondFragment();
1484 if (details
!= null
) {
1485 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1486 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1487 showDetails(renamedFile
);
1489 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1490 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1491 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1492 int position
= ((PreviewMediaFragment
)details
).getPosition();
1493 startMediaPreview(renamedFile
, position
, true
);
1495 getFileOperationsHelper().openFile(renamedFile
);
1500 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1501 refreshListOfFilesFragment();
1505 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1509 if (result
.isSslRecoverableException()) {
1510 mLastSslUntrustedServerResult
= result
;
1511 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1516 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1517 dismissLoadingDialog();
1518 OCFile syncedFile
= operation
.getLocalFile();
1519 if (!result
.isSuccess()) {
1520 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1521 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1522 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1523 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1529 if (operation
.transferWasRequested()) {
1530 onTransferStateChanged(syncedFile
, true
, true
);
1533 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1541 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1543 * @param operation Creation operation performed.
1544 * @param result Result of the creation.
1546 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1547 if (result
.isSuccess()) {
1548 dismissLoadingDialog();
1549 refreshListOfFilesFragment();
1551 dismissLoadingDialog();
1553 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1554 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1558 } catch (NotFoundException e
) {
1559 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1569 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1570 refreshListOfFilesFragment();
1571 FileFragment details
= getSecondFragment();
1572 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1573 if (downloading
|| uploading
) {
1574 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1576 if (!file
.fileExists()) {
1577 cleanSecondFragment();
1579 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1587 private void requestForDownload() {
1588 Account account
= getAccount();
1589 //if (!mWaitingToPreview.isDownloading()) {
1590 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1591 Intent i
= new Intent(this, FileDownloader
.class);
1592 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1593 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1599 private OCFile
getCurrentDir() {
1600 OCFile file
= getFile();
1602 if (file
.isFolder()) {
1604 } else if (getStorageManager() != null
) {
1605 String parentPath
= file
.getRemotePath().substring(0,
1606 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1607 return getStorageManager().getFileByPath(parentPath
);
1613 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1614 long currentSyncTime
= System
.currentTimeMillis();
1616 mSyncInProgress
= true
;
1618 // perform folder synchronization
1619 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1622 getFileOperationsHelper().isSharedSupported(),
1624 getStorageManager(),
1626 getApplicationContext()
1628 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1630 setSupportProgressBarIndeterminateVisibility(true
);
1632 setBackgroundText();
1636 * Show untrusted cert dialog
1638 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1639 // Show a dialog with the certificate info
1640 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1641 (CertificateCombinedException
)result
.getException());
1642 FragmentManager fm
= getSupportFragmentManager();
1643 FragmentTransaction ft
= fm
.beginTransaction();
1644 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1647 private void requestForDownload(OCFile file
) {
1648 Account account
= getAccount();
1649 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1650 Intent i
= new Intent(this, FileDownloader
.class);
1651 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1652 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1657 private void sendDownloadedFile(){
1658 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1659 mWaitingToSend
= null
;
1664 * Requests the download of the received {@link OCFile} , updates the UI
1665 * to monitor the download progress and prepares the activity to send the file
1666 * when the download finishes.
1668 * @param file {@link OCFile} to download and preview.
1670 public void startDownloadForSending(OCFile file
) {
1671 mWaitingToSend
= file
;
1672 requestForDownload(mWaitingToSend
);
1673 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1674 updateFragmentsVisibility(hasSecondFragment
);
1678 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1680 * @param file Image {@link OCFile} to show.
1682 public void startImagePreview(OCFile file
) {
1683 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1684 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1685 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1686 startActivity(showDetailsIntent
);
1691 * Stars the preview of an already down media {@link OCFile}.
1693 * @param file Media {@link OCFile} to preview.
1694 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1695 * @param autoplay When 'true', the playback will start without user interactions.
1697 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1698 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1699 setSecondFragment(mediaFragment
);
1700 updateFragmentsVisibility(true
);
1701 updateNavigationElementsInActionBar(file
);
1706 * Requests the download of the received {@link OCFile} , updates the UI
1707 * to monitor the download progress and prepares the activity to preview
1708 * or open the file when the download finishes.
1710 * @param file {@link OCFile} to download and preview.
1712 public void startDownloadForPreview(OCFile file
) {
1713 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1714 setSecondFragment(detailFragment
);
1715 mWaitingToPreview
= file
;
1716 requestForDownload();
1717 updateFragmentsVisibility(true
);
1718 updateNavigationElementsInActionBar(file
);
1723 public void cancelTransference(OCFile file
) {
1724 getFileOperationsHelper().cancelTransference(file
);
1725 if (mWaitingToPreview
!= null
&&
1726 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1727 mWaitingToPreview
= null
;
1729 if (mWaitingToSend
!= null
&&
1730 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1731 mWaitingToSend
= null
;
1733 onTransferStateChanged(file
, false
, false
);
1737 public void onRefresh(boolean ignoreETag
) {
1738 refreshList(ignoreETag
);
1742 public void onRefresh() {
1746 private void refreshList(boolean ignoreETag
) {
1747 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1748 if (listOfFiles
!= null
) {
1749 OCFile folder
= listOfFiles
.getCurrentFile();
1750 if (folder
!= null
) {
1751 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1752 listDirectory(mFile);*/
1753 startSyncFolderOperation(folder
, ignoreETag
);
1758 private void sortByDate(boolean ascending
){
1759 getListOfFilesFragment().sortByDate(ascending
);
1762 private void sortBySize(boolean ascending
){
1763 getListOfFilesFragment().sortBySize(ascending
);
1766 private void sortByName(boolean ascending
){
1767 getListOfFilesFragment().sortByName(ascending
);