1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.annotation
.SuppressLint
;
29 import android
.annotation
.TargetApi
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.ContentUris
;
37 import android
.content
.Context
;
38 import android
.content
.DialogInterface
;
39 import android
.content
.Intent
;
40 import android
.content
.IntentFilter
;
41 import android
.content
.ServiceConnection
;
42 import android
.content
.SharedPreferences
;
43 import android
.content
.SyncRequest
;
44 import android
.content
.res
.Resources
.NotFoundException
;
45 import android
.database
.Cursor
;
46 import android
.net
.Uri
;
47 import android
.os
.Build
;
48 import android
.os
.Bundle
;
49 import android
.os
.Environment
;
50 import android
.os
.IBinder
;
51 import android
.preference
.PreferenceManager
;
52 import android
.provider
.DocumentsContract
;
53 import android
.provider
.MediaStore
;
54 import android
.provider
.OpenableColumns
;
55 import android
.support
.v4
.app
.Fragment
;
56 import android
.support
.v4
.app
.FragmentManager
;
57 import android
.support
.v4
.app
.FragmentTransaction
;
58 import android
.util
.Log
;
59 import android
.view
.View
;
60 import android
.view
.ViewGroup
;
61 import android
.widget
.ArrayAdapter
;
62 import android
.widget
.TextView
;
63 import android
.widget
.Toast
;
65 import com
.actionbarsherlock
.app
.ActionBar
;
66 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
67 import com
.actionbarsherlock
.view
.Menu
;
68 import com
.actionbarsherlock
.view
.MenuInflater
;
69 import com
.actionbarsherlock
.view
.MenuItem
;
70 import com
.actionbarsherlock
.view
.Window
;
71 import com
.owncloud
.android
.BuildConfig
;
72 import com
.owncloud
.android
.MainApp
;
73 import com
.owncloud
.android
.R
;
74 import com
.owncloud
.android
.authentication
.PinCheck
;
75 import com
.owncloud
.android
.datamodel
.OCFile
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
;
77 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
;
79 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
81 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
82 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
83 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
84 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
85 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
86 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
87 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
88 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
89 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
90 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
91 import com
.owncloud
.android
.operations
.CreateShareOperation
;
92 import com
.owncloud
.android
.operations
.MoveFileOperation
;
93 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
94 import com
.owncloud
.android
.operations
.RenameFileOperation
;
95 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
96 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
97 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
98 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
99 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
100 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
101 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
102 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
103 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
104 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
105 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
106 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
108 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
109 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
110 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
111 import com
.owncloud
.android
.utils
.DisplayUtils
;
112 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
113 import com
.owncloud
.android
.utils
.UriUtils
;
117 * Displays, what files the user has available in his ownCloud.
119 * @author Bartek Przybylski
120 * @author David A. Velasco
123 public class FileDisplayActivity
extends HookActivity
implements
124 FileFragment
.ContainerActivity
, OnNavigationListener
,
125 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
127 private ArrayAdapter
<String
> mDirectories
;
129 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
130 private UploadFinishReceiver mUploadFinishReceiver
;
131 private DownloadFinishReceiver mDownloadFinishReceiver
;
132 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
134 private boolean mDualPane
;
135 private View mLeftFragmentContainer
;
136 private View mRightFragmentContainer
;
138 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
139 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
140 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
142 public static final int DIALOG_SHORT_WAIT
= 0;
143 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
144 private static final int DIALOG_CERT_NOT_SAVED
= 2;
146 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
148 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
149 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
150 public static final int ACTION_MOVE_FILES
= 3;
152 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
154 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
155 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
157 private OCFile mWaitingToPreview
;
159 private boolean mSyncInProgress
= false
;
161 private String DIALOG_UNTRUSTED_CERT
;
163 private OCFile mWaitingToSend
;
165 private Boolean mUnlocked
= false
;
168 protected void onCreate(Bundle savedInstanceState
) {
169 Log_OC
.d(TAG
, "onCreate() start");
170 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
172 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
175 if (PinCheck
.checkIfPinEntry()){
176 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
177 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
181 // if (mUnlocked == false){
182 // checkIfRequestPin(savedInstanceState);
184 // mUnlocked = false;
187 /// grant that FileObserverService is watching favorite files
188 if (savedInstanceState
== null
) {
189 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
190 startService(initObserversIntent
);
193 /// Load of saved instance state
194 if(savedInstanceState
!= null
) {
195 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
196 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
197 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
200 mWaitingToPreview
= null
;
201 mSyncInProgress
= false
;
202 mWaitingToSend
= null
;
207 // Inflate and set the layout view
208 setContentView(R
.layout
.files
);
209 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
210 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
211 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
212 if (savedInstanceState
== null
) {
213 createMinFragments();
217 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
218 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
219 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
223 Log_OC
.d(TAG
, "onCreate() end");
227 protected void onStart() {
229 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
233 protected void onDestroy() {
238 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
241 protected void onAccountSet(boolean stateWasRecovered
) {
242 super.onAccountSet(stateWasRecovered
);
243 if (getAccount() != null
) {
244 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
245 OCFile file
= getFile();
246 // get parent from path
247 String parentPath
= "";
249 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
250 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
251 // get parent from path
252 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
253 if (getStorageManager().getFileByPath(parentPath
) == null
)
254 file
= null
; // not able to know the directory where the file is uploading
256 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
260 // fall back to root folder
261 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
264 setNavigationListWithFolder(file
);
266 if (!stateWasRecovered
) {
267 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
268 initFragmentsWithFile();
269 if (file
.isFolder()) {
270 startSyncFolderOperation(file
, false
);
274 updateFragmentsVisibility(!file
.isFolder());
275 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
281 private void setNavigationListWithFolder(OCFile file
) {
282 mDirectories
.clear();
283 OCFile fileIt
= file
;
285 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
286 if (fileIt
.isFolder()) {
287 mDirectories
.add(fileIt
.getFileName());
289 // get parent from path
290 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
291 fileIt
= getStorageManager().getFileByPath(parentPath
);
293 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
297 private void createMinFragments() {
298 OCFileListFragment listOfFiles
= new OCFileListFragment();
299 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
300 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
301 transaction
.commit();
304 private void initFragmentsWithFile() {
305 if (getAccount() != null
&& getFile() != null
) {
307 OCFileListFragment listOfFiles
= getListOfFilesFragment();
308 if (listOfFiles
!= null
) {
309 listOfFiles
.listDirectory(getCurrentDir());
311 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
315 OCFile file
= getFile();
316 Fragment secondFragment
= chooseInitialSecondFragment(file
);
317 if (secondFragment
!= null
) {
318 setSecondFragment(secondFragment
);
319 updateFragmentsVisibility(true
);
320 updateNavigationElementsInActionBar(file
);
323 cleanSecondFragment();
327 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
328 if (getAccount() == null
) {
329 Log_OC
.wtf(TAG
, "\t account is NULL");
331 if (getFile() == null
) {
332 Log_OC
.wtf(TAG
, "\t file is NULL");
337 private Fragment
chooseInitialSecondFragment(OCFile file
) {
338 Fragment secondFragment
= null
;
339 if (file
!= null
&& !file
.isFolder()) {
340 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
341 && file
.getLastSyncDateForProperties() > 0 // temporal fix
343 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
344 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
345 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
348 secondFragment
= new FileDetailFragment(file
, getAccount());
351 return secondFragment
;
356 * Replaces the second fragment managed by the activity with the received as
359 * Assumes never will be more than two fragments managed at the same time.
361 * @param fragment New second Fragment to set.
363 private void setSecondFragment(Fragment fragment
) {
364 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
365 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
366 transaction
.commit();
370 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
373 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
379 } else if (existsSecondFragment
) {
380 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
381 mLeftFragmentContainer
.setVisibility(View
.GONE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
384 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
388 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
389 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
391 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
392 mRightFragmentContainer
.setVisibility(View
.GONE
);
398 private OCFileListFragment
getListOfFilesFragment() {
399 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
400 if (listOfFiles
!= null
) {
401 return (OCFileListFragment
)listOfFiles
;
403 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
407 public FileFragment
getSecondFragment() {
408 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
409 if (second
!= null
) {
410 return (FileFragment
)second
;
415 protected void cleanSecondFragment() {
416 Fragment second
= getSecondFragment();
417 if (second
!= null
) {
418 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
422 updateFragmentsVisibility(false
);
423 updateNavigationElementsInActionBar(null
);
426 protected void refreshListOfFilesFragment() {
427 OCFileListFragment fileListFragment
= getListOfFilesFragment();
428 if (fileListFragment
!= null
) {
429 fileListFragment
.listDirectory();
433 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
434 FileFragment secondFragment
= getSecondFragment();
435 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
436 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
437 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
438 OCFile fileInFragment
= detailsFragment
.getFile();
439 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
440 // the user browsed to other file ; forget the automatic preview
441 mWaitingToPreview
= null
;
443 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
444 // grant that the right panel updates the progress bar
445 detailsFragment
.listenForTransferProgress();
446 detailsFragment
.updateFileDetails(true
, false
);
448 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
449 // update the right panel
450 boolean detailsFragmentChanged
= false
;
453 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
454 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
455 startMediaPreview(mWaitingToPreview
, 0, true
);
456 detailsFragmentChanged
= true
;
458 getFileOperationsHelper().openFile(mWaitingToPreview
);
461 mWaitingToPreview
= null
;
463 if (!detailsFragmentChanged
) {
464 detailsFragment
.updateFileDetails(false
, (success
));
471 public boolean onPrepareOptionsMenu(Menu menu
) {
472 if (BuildConfig
.DEBUG
) {
473 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
475 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
477 return super.onPrepareOptionsMenu(menu
);
481 public boolean onCreateOptionsMenu(Menu menu
) {
482 MenuInflater inflater
= getSherlock().getMenuInflater();
483 inflater
.inflate(R
.menu
.main_menu
, menu
);
488 public boolean onOptionsItemSelected(MenuItem item
) {
489 boolean retval
= true
;
490 switch (item
.getItemId()) {
491 case R
.id
.action_create_dir
: {
492 CreateFolderDialogFragment dialog
=
493 CreateFolderDialogFragment
.newInstance(getCurrentDir());
494 dialog
.show(getSupportFragmentManager(), "createdirdialog");
497 case R
.id
.action_sync_account
: {
498 startSynchronization();
501 case R
.id
.action_upload
: {
502 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
505 case R
.id
.action_settings
: {
506 Intent settingsIntent
= new Intent(this, Preferences
.class);
507 startActivity(settingsIntent
);
510 case R
.id
.action_logger
: {
511 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
512 startActivity(loggerIntent
);
515 case android
.R
.id
.home
: {
516 FileFragment second
= getSecondFragment();
517 OCFile currentDir
= getCurrentDir();
518 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
519 (second
!= null
&& second
.getFile() != null
)) {
525 case R
.id
.action_sort
: {
526 SharedPreferences appPreferences
= PreferenceManager
527 .getDefaultSharedPreferences(this);
529 // Read sorting order, default to sort by name ascending
530 Integer sortOrder
= appPreferences
531 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
533 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
534 builder
.setTitle(R
.string
.actionbar_sort_title
)
535 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
536 public void onClick(DialogInterface dialog
, int which
) {
546 // TODO re-enable when server-side folder size calculation is available
548 // sortBySize(false);
556 builder
.create().show();
560 retval
= super.onOptionsItemSelected(item
);
565 private void startSynchronization() {
566 Log_OC
.e(TAG
, "Got to start sync");
567 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
568 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
569 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
570 Bundle bundle
= new Bundle();
571 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
572 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
573 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
574 ContentResolver
.requestSync(
576 MainApp
.getAuthority(), bundle
);
578 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
579 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
580 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
581 builder
.setExpedited(true
);
582 builder
.setManual(true
);
585 // Fix bug in Android Lollipop when you click on refresh the whole account
586 Bundle extras
= new Bundle();
587 builder
.setExtras(extras
);
589 SyncRequest request
= builder
.build();
590 ContentResolver
.requestSync(request
);
596 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
597 if (itemPosition
!= 0) {
598 String targetPath
= "";
599 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
600 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
602 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
603 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
604 if (targetFolder
!= null
) {
605 browseTo(targetFolder
);
608 // the next operation triggers a new call to this method, but it's necessary to
609 // ensure that the name exposed in the action bar is the current directory when the
610 // user selected it in the navigation list
611 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
612 getSupportActionBar().setSelectedNavigationItem(0);
618 * Called, when the user selected something for uploading
621 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
622 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
623 super.onActivityResult(requestCode
, resultCode
, data
);
625 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
626 //getClipData is only supported on api level 16+, Jelly Bean
627 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
628 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
629 Intent intent
= new Intent();
630 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
631 requestSimpleUpload(intent
, resultCode
);
634 requestSimpleUpload(data
, resultCode
);
636 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
637 requestMultipleUpload(data
, resultCode
);
639 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
641 final Intent fData
= data
;
642 final int fResultCode
= resultCode
;
643 getHandler().postDelayed(
647 requestMoveOperation(fData
, fResultCode
);
650 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
655 private void requestMultipleUpload(Intent data
, int resultCode
) {
656 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
657 if (filePaths
!= null
) {
658 String
[] remotePaths
= new String
[filePaths
.length
];
659 String remotePathBase
= "";
660 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
661 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
663 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
664 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
665 for (int j
= 0; j
< remotePaths
.length
; j
++) {
666 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
669 Intent i
= new Intent(this, FileUploader
.class);
670 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
671 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
672 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
673 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
674 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
675 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
679 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
680 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
687 private void requestSimpleUpload(Intent data
, int resultCode
) {
688 String filepath
= null
;
689 String mimeType
= null
;
691 Uri selectedImageUri
= data
.getData();
694 mimeType
= getContentResolver().getType(selectedImageUri
);
696 String filemanagerstring
= selectedImageUri
.getPath();
697 String selectedImagePath
= getPath(selectedImageUri
);
699 if (selectedImagePath
!= null
)
700 filepath
= selectedImagePath
;
702 filepath
= filemanagerstring
;
704 } catch (Exception e
) {
705 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
709 if (filepath
== null
) {
710 Log_OC
.e(TAG
, "Couldnt resolve path to file");
711 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
717 Intent i
= new Intent(this, FileUploader
.class);
718 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
720 String remotepath
= new String();
721 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
722 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
724 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
725 remotepath
+= OCFile
.PATH_SEPARATOR
;
727 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
729 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
730 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
733 if (cursor
!= null
&& cursor
.moveToFirst()) {
734 String displayName
= cursor
.getString(
735 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
736 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
738 displayName
.replace(File
.separatorChar
, '_');
739 displayName
.replace(File
.pathSeparatorChar
, '_');
740 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
748 remotepath
+= new File(filepath
).getName();
751 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
752 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
753 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
754 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
755 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
756 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
761 * Request the operation for moving the file/folder from one path to another
763 * @param data Intent received
764 * @param resultCode Result code received
766 private void requestMoveOperation(Intent data
, int resultCode
) {
767 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
768 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
769 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
773 public void onBackPressed() {
774 OCFileListFragment listOfFiles
= getListOfFilesFragment();
775 if (mDualPane
|| getSecondFragment() == null
) {
776 if (listOfFiles
!= null
) { // should never be null, indeed
777 if (mDirectories
.getCount() <= 1) {
781 int levelsUp
= listOfFiles
.onBrowseUp();
782 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
787 if (listOfFiles
!= null
) { // should never be null, indeed
788 setFile(listOfFiles
.getCurrentFile());
790 cleanSecondFragment();
795 protected void onSaveInstanceState(Bundle outState
) {
796 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
797 Log_OC
.e(TAG
, "onSaveInstanceState() start");
798 super.onSaveInstanceState(outState
);
799 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
800 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
801 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
802 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
804 Log_OC
.d(TAG
, "onSaveInstanceState() end");
810 protected void onResume() {
812 Log_OC
.e(TAG
, "onResume() start");
814 if (PinCheck
.checkIfPinEntry()){
815 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
816 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
821 private void resume(){
822 // refresh list of files
823 refreshListOfFilesFragment();
825 // Listen for sync messages
826 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
827 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
828 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
829 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
830 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
831 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
832 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
833 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
835 // Listen for upload messages
836 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
837 mUploadFinishReceiver
= new UploadFinishReceiver();
838 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
840 // Listen for download messages
841 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
842 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
843 mDownloadFinishReceiver
= new DownloadFinishReceiver();
844 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
846 Log_OC
.d(TAG
, "onResume() end");
851 protected void onPause() {
852 Log_OC
.e(TAG
, "onPause() start");
853 if (mSyncBroadcastReceiver
!= null
) {
854 unregisterReceiver(mSyncBroadcastReceiver
);
855 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
856 mSyncBroadcastReceiver
= null
;
858 if (mUploadFinishReceiver
!= null
) {
859 unregisterReceiver(mUploadFinishReceiver
);
860 mUploadFinishReceiver
= null
;
862 if (mDownloadFinishReceiver
!= null
) {
863 unregisterReceiver(mDownloadFinishReceiver
);
864 mDownloadFinishReceiver
= null
;
867 PinCheck
.setUnlockTimestamp();
868 Log_OC
.d(TAG
, "onPause() end");
874 protected Dialog
onCreateDialog(int id
) {
875 Dialog dialog
= null
;
876 AlertDialog
.Builder builder
;
878 case DIALOG_SHORT_WAIT
: {
879 ProgressDialog working_dialog
= new ProgressDialog(this);
880 working_dialog
.setMessage(getResources().getString(
881 R
.string
.wait_a_moment
));
882 working_dialog
.setIndeterminate(true
);
883 working_dialog
.setCancelable(false
);
884 dialog
= working_dialog
;
887 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
890 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
891 getString(R
.string
.actionbar_upload_from_apps
) };
893 builder
= new AlertDialog
.Builder(this);
894 builder
.setTitle(R
.string
.actionbar_upload
);
895 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
896 public void onClick(DialogInterface dialog
, int item
) {
899 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
900 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
901 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
903 // TODO create and handle new fragment
904 // LocalFileListFragment
906 } else if (item
== 1) {
907 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
908 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
909 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
910 if(Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
911 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
913 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
914 ACTION_SELECT_CONTENT_FROM_APPS
);
918 dialog
= builder
.create();
921 case DIALOG_CERT_NOT_SAVED
: {
922 builder
= new AlertDialog
.Builder(this);
923 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
924 builder
.setCancelable(false
);
925 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
927 public void onClick(DialogInterface dialog
, int which
) {
931 dialog
= builder
.create();
942 * Translates a content URI of an content to a physical path on the disk
944 * @param uri The URI to resolve
945 * @return The path to the content or null if it could not be found
947 public String
getPath(Uri uri
) {
948 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
951 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
952 // ExternalStorageProvider
953 if (UriUtils
.isExternalStorageDocument(uri
)) {
954 final String docId
= DocumentsContract
.getDocumentId(uri
);
955 final String
[] split
= docId
.split(":");
956 final String type
= split
[0];
958 if ("primary".equalsIgnoreCase(type
)) {
959 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
963 else if (UriUtils
.isDownloadsDocument(uri
)) {
965 final String id
= DocumentsContract
.getDocumentId(uri
);
966 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
969 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
972 else if (UriUtils
.isMediaDocument(uri
)) {
973 final String docId
= DocumentsContract
.getDocumentId(uri
);
974 final String
[] split
= docId
.split(":");
975 final String type
= split
[0];
977 Uri contentUri
= null
;
978 if ("image".equals(type
)) {
979 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
980 } else if ("video".equals(type
)) {
981 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
982 } else if ("audio".equals(type
)) {
983 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
986 final String selection
= "_id=?";
987 final String
[] selectionArgs
= new String
[] { split
[1] };
989 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
991 // Documents providers returned as content://...
992 else if (UriUtils
.isContentDocument(uri
)) {
993 return uri
.toString();
996 // MediaStore (and general)
997 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
999 // Return the remote address
1000 if (UriUtils
.isGooglePhotosUri(uri
))
1001 return uri
.getLastPathSegment();
1003 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
1006 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
1007 return uri
.getPath();
1013 * Pushes a directory to the drop down list
1014 * @param directory to push
1015 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1017 public void pushDirname(OCFile directory
) {
1018 if(!directory
.isFolder()){
1019 throw new IllegalArgumentException("Only directories may be pushed!");
1021 mDirectories
.insert(directory
.getFileName(), 0);
1026 * Pops a directory name from the drop down list
1027 * @return True, unless the stack is empty
1029 public boolean popDirname() {
1030 mDirectories
.remove(mDirectories
.getItem(0));
1031 return !mDirectories
.isEmpty();
1034 // Custom array adapter to override text colors
1035 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1037 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1041 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1042 View v
= super.getView(position
, convertView
, parent
);
1044 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1045 android
.R
.color
.white
));
1047 fixRoot((TextView
) v
);
1051 public View
getDropDownView(int position
, View convertView
,
1053 View v
= super.getDropDownView(position
, convertView
, parent
);
1055 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1056 android
.R
.color
.white
));
1058 fixRoot((TextView
) v
);
1062 private void fixRoot(TextView v
) {
1063 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1064 v
.setText(R
.string
.default_display_name_for_root_folder
);
1070 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1073 * {@link BroadcastReceiver} to enable syncing feedback in UI
1076 public void onReceive(Context context
, Intent intent
) {
1078 String event
= intent
.getAction();
1079 Log_OC
.d(TAG
, "Received broadcast " + event
);
1080 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1081 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1082 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1083 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1087 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1088 mSyncInProgress
= true
;
1091 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1092 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1094 if (currentDir
== null
) {
1095 // current folder was removed from the server
1096 Toast
.makeText( FileDisplayActivity
.this,
1097 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1103 if (currentFile
== null
&& !getFile().isFolder()) {
1104 // currently selected file was removed in the server, and now we know it
1105 cleanSecondFragment();
1106 currentFile
= currentDir
;
1109 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1110 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1111 if (fileListFragment
!= null
) {
1112 fileListFragment
.listDirectory(currentDir
);
1115 setFile(currentFile
);
1118 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1120 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1122 /// TODO refactor and make common
1123 synchResult
!= null
&& !synchResult
.isSuccess() &&
1124 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1125 synchResult
.isIdPRedirection() ||
1126 (synchResult
.isException() && synchResult
.getException()
1127 instanceof AuthenticatorException
))) {
1129 OwnCloudClient client
= null
;
1131 OwnCloudAccount ocAccount
=
1132 new OwnCloudAccount(getAccount(), context
);
1133 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1134 removeClientFor(ocAccount
));
1135 // TODO get rid of these exceptions
1136 } catch (AccountNotFoundException e
) {
1137 e
.printStackTrace();
1138 } catch (AuthenticatorException e
) {
1139 e
.printStackTrace();
1140 } catch (OperationCanceledException e
) {
1141 e
.printStackTrace();
1142 } catch (IOException e
) {
1143 e
.printStackTrace();
1146 if (client
!= null
) {
1147 OwnCloudCredentials cred
= client
.getCredentials();
1149 AccountManager am
= AccountManager
.get(context
);
1150 if (cred
.authTokenExpires()) {
1151 am
.invalidateAuthToken(
1156 am
.clearPassword(getAccount());
1161 requestCredentialsUpdate();
1165 removeStickyBroadcast(intent
);
1166 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1167 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1169 setBackgroundText();
1173 if (synchResult
!= null
) {
1174 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1175 mLastSslUntrustedServerResult
= synchResult
;
1178 } catch (RuntimeException e
) {
1179 // avoid app crashes after changing the serial id of RemoteOperationResult
1180 // in owncloud library with broadcast notifications pending to process
1181 removeStickyBroadcast(intent
);
1187 * Show a text message on screen view for notifying user if content is
1188 * loading or folder is empty
1190 private void setBackgroundText() {
1191 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1192 if (ocFileListFragment
!= null
) {
1193 int message
= R
.string
.file_list_loading
;
1194 if (!mSyncInProgress
) {
1195 // In case file list is empty
1196 message
= R
.string
.file_list_empty
;
1198 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1200 Log_OC
.e(TAG
, "OCFileListFragment is null");
1205 * Once the file upload has finished -> update view
1207 private class UploadFinishReceiver
extends BroadcastReceiver
{
1209 * Once the file upload has finished -> update view
1210 * @author David A. Velasco
1211 * {@link BroadcastReceiver} to enable upload feedback in UI
1214 public void onReceive(Context context
, Intent intent
) {
1216 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1217 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1218 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1219 OCFile currentDir
= getCurrentDir();
1220 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1221 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1223 if (sameAccount
&& isDescendant
) {
1224 refreshListOfFilesFragment();
1227 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1228 boolean renamedInUpload
= getFile().getRemotePath().
1229 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1230 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1232 FileFragment details
= getSecondFragment();
1233 boolean detailFragmentIsShown
= (details
!= null
&&
1234 details
instanceof FileDetailFragment
);
1236 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1237 if (uploadWasFine
) {
1238 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1240 if (renamedInUpload
) {
1241 String newName
= (new File(uploadedRemotePath
)).getName();
1242 Toast msg
= Toast
.makeText(
1245 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1250 if (uploadWasFine
|| getFile().fileExists()) {
1251 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1253 cleanSecondFragment();
1256 // Force the preview if the file is an image
1257 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1258 startImagePreview(getFile());
1259 } // TODO what about other kind of previews?
1263 if (intent
!= null
) {
1264 removeStickyBroadcast(intent
);
1274 * Class waiting for broadcast events from the {@link FielDownloader} service.
1276 * Updates the UI when a download is started or finished, provided that it is relevant for the
1279 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1281 public void onReceive(Context context
, Intent intent
) {
1283 boolean sameAccount
= isSameAccount(context
, intent
);
1284 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1285 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1287 if (sameAccount
&& isDescendant
) {
1288 refreshListOfFilesFragment();
1289 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1292 if (mWaitingToSend
!= null
) {
1293 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1294 if (mWaitingToSend
.isDown()) {
1295 sendDownloadedFile();
1300 if (intent
!= null
) {
1301 removeStickyBroadcast(intent
);
1306 private boolean isDescendant(String downloadedRemotePath
) {
1307 OCFile currentDir
= getCurrentDir();
1308 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1311 private boolean isSameAccount(Context context
, Intent intent
) {
1312 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1313 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1318 public void browseToRoot() {
1319 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1320 if (listOfFiles
!= null
) { // should never be null, indeed
1321 while (mDirectories
.getCount() > 1) {
1324 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1325 listOfFiles
.listDirectory(root
);
1326 setFile(listOfFiles
.getCurrentFile());
1327 startSyncFolderOperation(root
, false
);
1329 cleanSecondFragment();
1333 public void browseTo(OCFile folder
) {
1334 if (folder
== null
|| !folder
.isFolder()) {
1335 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1337 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1338 if (listOfFiles
!= null
) {
1339 setNavigationListWithFolder(folder
);
1340 listOfFiles
.listDirectory(folder
);
1341 setFile(listOfFiles
.getCurrentFile());
1342 startSyncFolderOperation(folder
, false
);
1344 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1346 cleanSecondFragment();
1353 * Updates action bar and second fragment, if in dual pane mode.
1356 public void onBrowsedDownTo(OCFile directory
) {
1357 pushDirname(directory
);
1358 cleanSecondFragment();
1361 startSyncFolderOperation(directory
, false
);
1366 * Shows the information of the {@link OCFile} received as a
1367 * parameter in the second fragment.
1369 * @param file {@link OCFile} whose details will be shown
1372 public void showDetails(OCFile file
) {
1373 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1374 setSecondFragment(detailFragment
);
1375 updateFragmentsVisibility(true
);
1376 updateNavigationElementsInActionBar(file
);
1384 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1385 ActionBar actionBar
= getSupportActionBar();
1386 if (chosenFile
== null
|| mDualPane
) {
1387 // only list of files - set for browsing through folders
1388 OCFile currentDir
= getCurrentDir();
1389 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1390 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1391 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1393 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1395 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1396 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1399 actionBar
.setDisplayHomeAsUpEnabled(true
);
1400 actionBar
.setDisplayShowTitleEnabled(true
);
1401 actionBar
.setTitle(chosenFile
.getFileName());
1402 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1408 protected ServiceConnection
newTransferenceServiceConnection() {
1409 return new ListServiceConnection();
1412 /** Defines callbacks for service binding, passed to bindService() */
1413 private class ListServiceConnection
implements ServiceConnection
{
1416 public void onServiceConnected(ComponentName component
, IBinder service
) {
1417 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1418 Log_OC
.d(TAG
, "Download service connected");
1419 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1420 if (mWaitingToPreview
!= null
)
1421 if (getStorageManager() != null
) {
1422 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1423 if (!mWaitingToPreview
.isDown()) {
1424 requestForDownload();
1428 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1429 Log_OC
.d(TAG
, "Upload service connected");
1430 mUploaderBinder
= (FileUploaderBinder
) service
;
1434 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1435 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1436 if (listOfFiles
!= null
) {
1437 listOfFiles
.listDirectory();
1439 FileFragment secondFragment
= getSecondFragment();
1440 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1441 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1442 detailFragment
.listenForTransferProgress();
1443 detailFragment
.updateFileDetails(false
, false
);
1448 public void onServiceDisconnected(ComponentName component
) {
1449 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1450 Log_OC
.d(TAG
, "Download service disconnected");
1451 mDownloaderBinder
= null
;
1452 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1453 Log_OC
.d(TAG
, "Upload service disconnected");
1454 mUploaderBinder
= null
;
1460 public void onSavedCertificate() {
1461 startSyncFolderOperation(getCurrentDir(), false
);
1466 public void onFailedSavingCertificate() {
1467 showDialog(DIALOG_CERT_NOT_SAVED
);
1471 public void onCancelCertificate() {
1476 * Updates the view associated to the activity after the finish of some operation over files
1477 * in the current account.
1479 * @param operation Removal operation performed.
1480 * @param result Result of the removal.
1483 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1484 super.onRemoteOperationFinish(operation
, result
);
1486 if (operation
instanceof RemoveFileOperation
) {
1487 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1489 } else if (operation
instanceof RenameFileOperation
) {
1490 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1492 } else if (operation
instanceof SynchronizeFileOperation
) {
1493 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1495 } else if (operation
instanceof CreateFolderOperation
) {
1496 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1498 } else if (operation
instanceof CreateShareOperation
) {
1499 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1501 } else if (operation
instanceof UnshareLinkOperation
) {
1502 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1504 } else if (operation
instanceof MoveFileOperation
) {
1505 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1511 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1512 if (result
.isSuccess()) {
1513 refreshShowDetails();
1514 refreshListOfFilesFragment();
1519 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1520 if (result
.isSuccess()) {
1521 refreshShowDetails();
1522 refreshListOfFilesFragment();
1524 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1525 cleanSecondFragment();
1526 refreshListOfFilesFragment();
1530 private void refreshShowDetails() {
1531 FileFragment details
= getSecondFragment();
1532 if (details
!= null
) {
1533 OCFile file
= details
.getFile();
1535 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1536 if (details
instanceof PreviewMediaFragment
) {
1537 // Refresh OCFile of the fragment
1538 ((PreviewMediaFragment
) details
).updateFile(file
);
1543 invalidateOptionsMenu();
1548 * Updates the view associated to the activity after the finish of an operation trying to remove a
1551 * @param operation Removal operation performed.
1552 * @param result Result of the removal.
1554 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1555 dismissLoadingDialog();
1557 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1561 if (result
.isSuccess()) {
1562 OCFile removedFile
= operation
.getFile();
1563 FileFragment second
= getSecondFragment();
1564 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1565 if (second
instanceof PreviewMediaFragment
) {
1566 ((PreviewMediaFragment
)second
).stopPreview(true
);
1568 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1569 cleanSecondFragment();
1571 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1572 refreshListOfFilesFragment();
1574 invalidateOptionsMenu();
1576 if (result
.isSslRecoverableException()) {
1577 mLastSslUntrustedServerResult
= result
;
1578 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1585 * Updates the view associated to the activity after the finish of an operation trying to move a
1588 * @param operation Move operation performed.
1589 * @param result Result of the move operation.
1591 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1592 if (result
.isSuccess()) {
1593 dismissLoadingDialog();
1594 refreshListOfFilesFragment();
1596 dismissLoadingDialog();
1598 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1599 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1603 } catch (NotFoundException e
) {
1604 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1611 * Updates the view associated to the activity after the finish of an operation trying to rename a
1614 * @param operation Renaming operation performed.
1615 * @param result Result of the renaming.
1617 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1618 dismissLoadingDialog();
1619 OCFile renamedFile
= operation
.getFile();
1620 if (result
.isSuccess()) {
1621 FileFragment details
= getSecondFragment();
1622 if (details
!= null
) {
1623 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1624 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1625 showDetails(renamedFile
);
1627 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1628 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1629 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1630 int position
= ((PreviewMediaFragment
)details
).getPosition();
1631 startMediaPreview(renamedFile
, position
, true
);
1633 getFileOperationsHelper().openFile(renamedFile
);
1638 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1639 refreshListOfFilesFragment();
1643 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1647 if (result
.isSslRecoverableException()) {
1648 mLastSslUntrustedServerResult
= result
;
1649 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1654 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1655 dismissLoadingDialog();
1656 OCFile syncedFile
= operation
.getLocalFile();
1657 if (!result
.isSuccess()) {
1658 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1659 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1660 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1661 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1667 if (operation
.transferWasRequested()) {
1668 onTransferStateChanged(syncedFile
, true
, true
);
1671 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1679 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1681 * @param operation Creation operation performed.
1682 * @param result Result of the creation.
1684 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1685 if (result
.isSuccess()) {
1686 dismissLoadingDialog();
1687 refreshListOfFilesFragment();
1689 dismissLoadingDialog();
1691 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1692 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1696 } catch (NotFoundException e
) {
1697 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1707 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1708 refreshListOfFilesFragment();
1709 FileFragment details
= getSecondFragment();
1710 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1711 if (downloading
|| uploading
) {
1712 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1714 if (!file
.fileExists()) {
1715 cleanSecondFragment();
1717 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1725 private void requestForDownload() {
1726 Account account
= getAccount();
1727 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1728 Intent i
= new Intent(this, FileDownloader
.class);
1729 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1730 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1736 private OCFile
getCurrentDir() {
1737 OCFile file
= getFile();
1739 if (file
.isFolder()) {
1741 } else if (getStorageManager() != null
) {
1742 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1743 return getStorageManager().getFileByPath(parentPath
);
1749 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1750 long currentSyncTime
= System
.currentTimeMillis();
1752 mSyncInProgress
= true
;
1754 // perform folder synchronization
1755 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1758 getFileOperationsHelper().isSharedSupported(),
1760 getStorageManager(),
1762 getApplicationContext()
1764 synchFolderOp
.execute(getAccount(), this, null
, null
);
1766 setSupportProgressBarIndeterminateVisibility(true
);
1768 setBackgroundText();
1772 * Show untrusted cert dialog
1774 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1775 // Show a dialog with the certificate info
1776 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1777 FragmentManager fm
= getSupportFragmentManager();
1778 FragmentTransaction ft
= fm
.beginTransaction();
1779 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1782 private void requestForDownload(OCFile file
) {
1783 Account account
= getAccount();
1784 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1785 Intent i
= new Intent(this, FileDownloader
.class);
1786 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1787 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1792 private void sendDownloadedFile(){
1793 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1794 mWaitingToSend
= null
;
1799 * Requests the download of the received {@link OCFile} , updates the UI
1800 * to monitor the download progress and prepares the activity to send the file
1801 * when the download finishes.
1803 * @param file {@link OCFile} to download and preview.
1805 public void startDownloadForSending(OCFile file
) {
1806 mWaitingToSend
= file
;
1807 requestForDownload(mWaitingToSend
);
1808 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1809 updateFragmentsVisibility(hasSecondFragment
);
1813 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1815 * @param file Image {@link OCFile} to show.
1817 public void startImagePreview(OCFile file
) {
1818 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1819 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1820 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1821 startActivity(showDetailsIntent
);
1826 * Stars the preview of an already down media {@link OCFile}.
1828 * @param file Media {@link OCFile} to preview.
1829 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1830 * @param autoplay When 'true', the playback will start without user interactions.
1832 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1833 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1834 setSecondFragment(mediaFragment
);
1835 updateFragmentsVisibility(true
);
1836 updateNavigationElementsInActionBar(file
);
1841 * Requests the download of the received {@link OCFile} , updates the UI
1842 * to monitor the download progress and prepares the activity to preview
1843 * or open the file when the download finishes.
1845 * @param file {@link OCFile} to download and preview.
1847 public void startDownloadForPreview(OCFile file
) {
1848 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1849 setSecondFragment(detailFragment
);
1850 mWaitingToPreview
= file
;
1851 requestForDownload();
1852 updateFragmentsVisibility(true
);
1853 updateNavigationElementsInActionBar(file
);
1858 public void cancelTransference(OCFile file
) {
1859 getFileOperationsHelper().cancelTransference(file
);
1860 if (mWaitingToPreview
!= null
&&
1861 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1862 mWaitingToPreview
= null
;
1864 if (mWaitingToSend
!= null
&&
1865 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1866 mWaitingToSend
= null
;
1868 onTransferStateChanged(file
, false
, false
);
1872 public void onRefresh(boolean ignoreETag
) {
1873 refreshList(ignoreETag
);
1877 public void onRefresh() {
1881 private void refreshList(boolean ignoreETag
) {
1882 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1883 if (listOfFiles
!= null
) {
1884 OCFile folder
= listOfFiles
.getCurrentFile();
1885 if (folder
!= null
) {
1886 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1887 listDirectory(mFile);*/
1888 startSyncFolderOperation(folder
, ignoreETag
);
1893 private void sortByDate(boolean ascending
){
1894 getListOfFilesFragment().sortByDate(ascending
);
1897 private void sortBySize(boolean ascending
){
1898 getListOfFilesFragment().sortBySize(ascending
);
1901 private void sortByName(boolean ascending
){
1902 getListOfFilesFragment().sortByName(ascending
);