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
.app
.Dialog
;
33 import android
.app
.ProgressDialog
;
34 import android
.content
.BroadcastReceiver
;
35 import android
.content
.ComponentName
;
36 import android
.content
.ContentResolver
;
37 import android
.content
.ContentUris
;
38 import android
.content
.Context
;
39 import android
.content
.DialogInterface
;
40 import android
.content
.Intent
;
41 import android
.content
.IntentFilter
;
42 import android
.content
.ServiceConnection
;
43 import android
.content
.SharedPreferences
;
44 import android
.content
.SyncRequest
;
45 import android
.content
.res
.Resources
.NotFoundException
;
46 import android
.database
.Cursor
;
47 import android
.net
.Uri
;
48 import android
.os
.Build
;
49 import android
.os
.Bundle
;
50 import android
.os
.Environment
;
51 import android
.os
.IBinder
;
52 import android
.preference
.PreferenceManager
;
53 import android
.provider
.DocumentsContract
;
54 import android
.provider
.MediaStore
;
55 import android
.provider
.OpenableColumns
;
56 import android
.support
.v4
.app
.Fragment
;
57 import android
.support
.v4
.app
.FragmentManager
;
58 import android
.support
.v4
.app
.FragmentTransaction
;
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
.datamodel
.OCFile
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
79 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
81 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
82 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
83 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
84 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
86 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
87 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
88 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
89 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
90 import com
.owncloud
.android
.operations
.CreateShareOperation
;
91 import com
.owncloud
.android
.operations
.MoveFileOperation
;
92 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
93 import com
.owncloud
.android
.operations
.RenameFileOperation
;
94 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
95 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
96 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
97 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
98 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
99 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
100 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
101 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
102 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
103 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
104 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
105 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
106 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
108 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
109 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
110 import com
.owncloud
.android
.utils
.DisplayUtils
;
111 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
112 import com
.owncloud
.android
.utils
.FileStorageUtils
;
113 import com
.owncloud
.android
.utils
.UriUtils
;
117 * Displays, what files the user has available in his ownCloud.
120 public class FileDisplayActivity
extends HookActivity
implements
121 FileFragment
.ContainerActivity
, OnNavigationListener
,
122 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
124 private ArrayAdapter
<String
> mDirectories
;
126 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
127 private UploadFinishReceiver mUploadFinishReceiver
;
128 private DownloadFinishReceiver mDownloadFinishReceiver
;
129 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
131 private boolean mDualPane
;
132 private View mLeftFragmentContainer
;
133 private View mRightFragmentContainer
;
135 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
136 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
137 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
139 public static final int DIALOG_SHORT_WAIT
= 0;
140 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
141 private static final int DIALOG_CERT_NOT_SAVED
= 2;
143 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
145 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
146 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
147 public static final int ACTION_MOVE_FILES
= 3;
149 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
151 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
152 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
154 private OCFile mWaitingToPreview
;
156 private boolean mSyncInProgress
= false
;
158 private String DIALOG_UNTRUSTED_CERT
;
160 private OCFile mWaitingToSend
;
163 protected void onCreate(Bundle savedInstanceState
) {
164 Log_OC
.d(TAG
, "onCreate() start");
165 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
167 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
169 // PIN CODE request ; best location is to decide, let's try this first
170 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
172 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
176 /// grant that FileObserverService is watching favourite files
177 if (savedInstanceState
== null
) {
178 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
179 startService(initObserversIntent
);
182 /// Load of saved instance state
183 if(savedInstanceState
!= null
) {
184 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
185 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
186 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
189 mWaitingToPreview
= null
;
190 mSyncInProgress
= false
;
191 mWaitingToSend
= null
;
196 // Inflate and set the layout view
197 setContentView(R
.layout
.files
);
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
212 Log_OC
.d(TAG
, "onCreate() end");
216 protected void onStart() {
217 Log_OC
.d(TAG
, "onStart() start");
219 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
220 Log_OC
.d(TAG
, "onStart() end");
224 protected void onDestroy() {
229 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
232 protected void onAccountSet(boolean stateWasRecovered
) {
233 super.onAccountSet(stateWasRecovered
);
234 if (getAccount() != null
) {
235 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
236 OCFile file
= getFile();
237 // get parent from path
238 String parentPath
= "";
240 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
241 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
242 // get parent from path
243 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
244 if (getStorageManager().getFileByPath(parentPath
) == null
)
245 file
= null
; // not able to know the directory where the file is uploading
247 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
251 // fall back to root folder
252 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
255 setNavigationListWithFolder(file
);
257 if (!stateWasRecovered
) {
258 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
259 initFragmentsWithFile();
260 if (file
.isFolder()) {
261 startSyncFolderOperation(file
, false
);
265 updateFragmentsVisibility(!file
.isFolder());
266 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
272 private void setNavigationListWithFolder(OCFile file
) {
273 mDirectories
.clear();
274 OCFile fileIt
= file
;
276 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
277 if (fileIt
.isFolder()) {
278 mDirectories
.add(fileIt
.getFileName());
280 // get parent from path
281 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
282 fileIt
= getStorageManager().getFileByPath(parentPath
);
284 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
302 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
306 OCFile file
= getFile();
307 Fragment secondFragment
= chooseInitialSecondFragment(file
);
308 if (secondFragment
!= null
) {
309 setSecondFragment(secondFragment
);
310 updateFragmentsVisibility(true
);
311 updateNavigationElementsInActionBar(file
);
314 cleanSecondFragment();
318 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
319 if (getAccount() == null
) {
320 Log_OC
.wtf(TAG
, "\t account is NULL");
322 if (getFile() == null
) {
323 Log_OC
.wtf(TAG
, "\t file is NULL");
328 private Fragment
chooseInitialSecondFragment(OCFile file
) {
329 Fragment secondFragment
= null
;
330 if (file
!= null
&& !file
.isFolder()) {
331 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
332 && file
.getLastSyncDateForProperties() > 0 // temporal fix
334 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
335 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
336 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
339 secondFragment
= new FileDetailFragment(file
, getAccount());
342 return secondFragment
;
347 * Replaces the second fragment managed by the activity with the received as
350 * Assumes never will be more than two fragments managed at the same time.
352 * @param fragment New second Fragment to set.
354 private void setSecondFragment(Fragment fragment
) {
355 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
356 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
357 transaction
.commit();
361 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
363 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 } else if (existsSecondFragment
) {
371 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
372 mLeftFragmentContainer
.setVisibility(View
.GONE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
382 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
383 mRightFragmentContainer
.setVisibility(View
.GONE
);
389 private OCFileListFragment
getListOfFilesFragment() {
390 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
391 if (listOfFiles
!= null
) {
392 return (OCFileListFragment
)listOfFiles
;
394 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
398 public FileFragment
getSecondFragment() {
399 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
400 if (second
!= null
) {
401 return (FileFragment
)second
;
406 protected void cleanSecondFragment() {
407 Fragment second
= getSecondFragment();
408 if (second
!= null
) {
409 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
413 updateFragmentsVisibility(false
);
414 updateNavigationElementsInActionBar(null
);
417 protected void refreshListOfFilesFragment() {
418 OCFileListFragment fileListFragment
= getListOfFilesFragment();
419 if (fileListFragment
!= null
) {
420 fileListFragment
.listDirectory();
424 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
425 FileFragment secondFragment
= getSecondFragment();
426 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
427 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
428 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
429 OCFile fileInFragment
= detailsFragment
.getFile();
430 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
431 // the user browsed to other file ; forget the automatic preview
432 mWaitingToPreview
= null
;
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
435 // grant that the right panel updates the progress bar
436 detailsFragment
.listenForTransferProgress();
437 detailsFragment
.updateFileDetails(true
, false
);
439 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
440 // update the right panel
441 boolean detailsFragmentChanged
= false
;
444 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
445 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
446 startMediaPreview(mWaitingToPreview
, 0, true
);
447 detailsFragmentChanged
= true
;
449 getFileOperationsHelper().openFile(mWaitingToPreview
);
452 mWaitingToPreview
= null
;
454 if (!detailsFragmentChanged
) {
455 detailsFragment
.updateFileDetails(false
, (success
));
462 public boolean onPrepareOptionsMenu(Menu menu
) {
463 if (BuildConfig
.DEBUG
) {
464 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
466 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
468 return super.onPrepareOptionsMenu(menu
);
472 public boolean onCreateOptionsMenu(Menu menu
) {
473 MenuInflater inflater
= getSherlock().getMenuInflater();
474 inflater
.inflate(R
.menu
.main_menu
, menu
);
479 public boolean onOptionsItemSelected(MenuItem item
) {
480 boolean retval
= true
;
481 switch (item
.getItemId()) {
482 case R
.id
.action_create_dir
: {
483 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
484 dialog
.show(getSupportFragmentManager(), "createDirDialog");
487 case R
.id
.action_sync_account
: {
488 startSynchronization();
491 case R
.id
.action_upload
: {
492 //showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
493 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
494 dialog
.show(getSupportFragmentManager(), "uploadSourceDialog");
498 case R
.id
.action_settings
: {
499 Intent settingsIntent
= new Intent(this, Preferences
.class);
500 startActivity(settingsIntent
);
503 case R
.id
.action_logger
: {
504 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
505 startActivity(loggerIntent
);
508 case android
.R
.id
.home
: {
509 FileFragment second
= getSecondFragment();
510 OCFile currentDir
= getCurrentDir();
511 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
512 (second
!= null
&& second
.getFile() != null
)) {
518 case R
.id
.action_sort
: {
519 SharedPreferences appPreferences
= PreferenceManager
520 .getDefaultSharedPreferences(this);
522 // Read sorting order, default to sort by name ascending
523 Integer sortOrder
= appPreferences
524 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
526 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
527 builder
.setTitle(R
.string
.actionbar_sort_title
)
528 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
529 public void onClick(DialogInterface dialog
, int which
) {
539 // TODO re-enable when server-side folder size calculation is available
541 // sortBySize(false);
549 builder
.create().show();
553 retval
= super.onOptionsItemSelected(item
);
558 private void startSynchronization() {
559 Log_OC
.d(TAG
, "Got to start sync");
560 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
561 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
562 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
563 Bundle bundle
= new Bundle();
564 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
565 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
566 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
567 ContentResolver
.requestSync(
569 MainApp
.getAuthority(), bundle
);
571 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
572 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
573 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
574 builder
.setExpedited(true
);
575 builder
.setManual(true
);
578 // Fix bug in Android Lollipop when you click on refresh the whole account
579 Bundle extras
= new Bundle();
580 builder
.setExtras(extras
);
582 SyncRequest request
= builder
.build();
583 ContentResolver
.requestSync(request
);
589 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
590 if (itemPosition
!= 0) {
591 String targetPath
= "";
592 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
593 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
595 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
596 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
597 if (targetFolder
!= null
) {
598 browseTo(targetFolder
);
601 // the next operation triggers a new call to this method, but it's necessary to
602 // ensure that the name exposed in the action bar is the current directory when the
603 // user selected it in the navigation list
604 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
605 getSupportActionBar().setSelectedNavigationItem(0);
611 * Called, when the user selected something for uploading
614 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
616 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
617 Log_OC
.e(TAG
, "ON ACTIVITIRESULT IN FILE_DISPLAY_ACTIVITY");
619 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
620 //getClipData is only supported on api level 16+, Jelly Bean
621 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
622 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
623 Intent intent
= new Intent();
624 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
625 requestSimpleUpload(intent
, resultCode
);
628 requestSimpleUpload(data
, resultCode
);
630 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
631 requestMultipleUpload(data
, resultCode
);
633 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
635 final Intent fData
= data
;
636 final int fResultCode
= resultCode
;
637 getHandler().postDelayed(
641 requestMoveOperation(fData
, fResultCode
);
644 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
648 super.onActivityResult(requestCode
, resultCode
, data
);
653 private void requestMultipleUpload(Intent data
, int resultCode
) {
654 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
655 if (filePaths
!= null
) {
656 String
[] remotePaths
= new String
[filePaths
.length
];
657 String remotePathBase
= "";
659 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
660 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
662 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
663 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
664 for (int j
= 0; j
< remotePaths
.length
; j
++) {
665 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
668 Intent i
= new Intent(this, FileUploader
.class);
669 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
670 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
671 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
672 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
673 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
674 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
678 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
679 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
686 private void requestSimpleUpload(Intent data
, int resultCode
) {
687 String filepath
= null
;
688 String mimeType
= null
;
690 Uri selectedImageUri
= data
.getData();
693 mimeType
= getContentResolver().getType(selectedImageUri
);
695 String filemanagerstring
= selectedImageUri
.getPath();
696 String selectedImagePath
= getPath(selectedImageUri
);
698 if (selectedImagePath
!= null
)
699 filepath
= selectedImagePath
;
701 filepath
= filemanagerstring
;
703 } catch (Exception e
) {
704 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
708 if (filepath
== null
) {
709 Log_OC
.e(TAG
, "Couldn't resolve path to file");
710 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
716 Intent i
= new Intent(this, FileUploader
.class);
717 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
719 String remotepath
= new String();
720 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
721 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
723 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
724 remotepath
+= OCFile
.PATH_SEPARATOR
;
726 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
728 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
729 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
732 if (cursor
!= null
&& cursor
.moveToFirst()) {
733 String displayName
= cursor
.getString(
734 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
735 Log_OC
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
737 displayName
.replace(File
.separatorChar
, '_');
738 displayName
.replace(File
.pathSeparatorChar
, '_');
739 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
747 remotepath
+= new File(filepath
).getName();
750 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
751 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
752 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
753 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
754 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
755 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
760 * Request the operation for moving the file/folder from one path to another
762 * @param data Intent received
763 * @param resultCode Result code received
765 private void requestMoveOperation(Intent data
, int resultCode
) {
766 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
767 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
768 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
772 public void onBackPressed() {
773 OCFileListFragment listOfFiles
= getListOfFilesFragment();
774 if (mDualPane
|| getSecondFragment() == null
) {
775 if (listOfFiles
!= null
) { // should never be null, indeed
776 if (mDirectories
.getCount() <= 1) {
780 int levelsUp
= listOfFiles
.onBrowseUp();
781 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
786 if (listOfFiles
!= null
) { // should never be null, indeed
787 setFile(listOfFiles
.getCurrentFile());
789 cleanSecondFragment();
794 protected void onSaveInstanceState(Bundle outState
) {
795 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
796 Log_OC
.d(TAG
, "onSaveInstanceState() start");
797 super.onSaveInstanceState(outState
);
798 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
799 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
800 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
801 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
803 Log_OC
.d(TAG
, "onSaveInstanceState() end");
809 protected void onResume() {
810 Log_OC
.d(TAG
, "onResume() start");
813 // refresh list of files
814 refreshListOfFilesFragment();
816 // Listen for sync messages
817 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
818 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
819 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
820 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
821 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
822 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
823 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
824 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
826 // Listen for upload messages
827 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
828 mUploadFinishReceiver
= new UploadFinishReceiver();
829 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
831 // Listen for download messages
832 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
833 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
834 mDownloadFinishReceiver
= new DownloadFinishReceiver();
835 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
837 Log_OC
.d(TAG
, "onResume() end");
842 protected void onPause() {
843 Log_OC
.d(TAG
, "onPause() start");
844 if (mSyncBroadcastReceiver
!= null
) {
845 unregisterReceiver(mSyncBroadcastReceiver
);
846 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
847 mSyncBroadcastReceiver
= null
;
849 if (mUploadFinishReceiver
!= null
) {
850 unregisterReceiver(mUploadFinishReceiver
);
851 mUploadFinishReceiver
= null
;
853 if (mDownloadFinishReceiver
!= null
) {
854 unregisterReceiver(mDownloadFinishReceiver
);
855 mDownloadFinishReceiver
= null
;
860 Log_OC
.d(TAG
, "onPause() end");
865 protected Dialog
onCreateDialog(int id
) {
866 Dialog dialog
= null
;
867 AlertDialog
.Builder builder
;
869 case DIALOG_SHORT_WAIT
: {
870 ProgressDialog working_dialog
= new ProgressDialog(this);
871 working_dialog
.setMessage(getResources().getString(
872 R
.string
.wait_a_moment
));
873 working_dialog
.setIndeterminate(true
);
874 working_dialog
.setCancelable(false
);
875 dialog
= working_dialog
;
879 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
882 String[] allTheItems = { getString(R.string.actionbar_upload_files),
883 getString(R.string.actionbar_upload_from_apps) };
885 builder = new AlertDialog.Builder(this);
886 builder.setTitle(R.string.actionbar_upload);
887 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
888 public void onClick(DialogInterface dialog, int item) {
891 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
892 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
893 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
895 // TODO create and handle new fragment
896 // LocalFileListFragment
898 } else if (item == 1) {
899 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
900 action = action.setType("*-/*").addCategory(Intent.CATEGORY_OPENABLE);
901 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
902 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
903 action.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
905 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
906 ACTION_SELECT_CONTENT_FROM_APPS);
910 dialog = builder.create();
913 case DIALOG_CERT_NOT_SAVED
: {
914 builder
= new AlertDialog
.Builder(this);
915 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
916 builder
.setCancelable(false
);
917 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
919 public void onClick(DialogInterface dialog
, int which
) {
923 dialog
= builder
.create();
934 * Pushes a directory to the drop down list
935 * @param directory to push
936 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
938 public void pushDirname(OCFile directory
) {
939 if(!directory
.isFolder()){
940 throw new IllegalArgumentException("Only directories may be pushed!");
942 mDirectories
.insert(directory
.getFileName(), 0);
947 * Pops a directory name from the drop down list
948 * @return True, unless the stack is empty
950 public boolean popDirname() {
951 mDirectories
.remove(mDirectories
.getItem(0));
952 return !mDirectories
.isEmpty();
955 // Custom array adapter to override text colors
956 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
958 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
962 public View
getView(int position
, View convertView
, ViewGroup parent
) {
963 View v
= super.getView(position
, convertView
, parent
);
965 ((TextView
) v
).setTextColor(getResources().getColorStateList(
966 android
.R
.color
.white
));
968 fixRoot((TextView
) v
);
972 public View
getDropDownView(int position
, View convertView
,
974 View v
= super.getDropDownView(position
, convertView
, parent
);
976 ((TextView
) v
).setTextColor(getResources().getColorStateList(
977 android
.R
.color
.white
));
979 fixRoot((TextView
) v
);
983 private void fixRoot(TextView v
) {
984 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
985 v
.setText(R
.string
.default_display_name_for_root_folder
);
991 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
994 * {@link BroadcastReceiver} to enable syncing feedback in UI
997 public void onReceive(Context context
, Intent intent
) {
999 String event
= intent
.getAction();
1000 Log_OC
.d(TAG
, "Received broadcast " + event
);
1001 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1002 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1003 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1004 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1008 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1009 mSyncInProgress
= true
;
1012 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1013 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1015 if (currentDir
== null
) {
1016 // current folder was removed from the server
1017 Toast
.makeText( FileDisplayActivity
.this,
1018 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1024 if (currentFile
== null
&& !getFile().isFolder()) {
1025 // currently selected file was removed in the server, and now we know it
1026 cleanSecondFragment();
1027 currentFile
= currentDir
;
1030 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1031 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1032 if (fileListFragment
!= null
) {
1033 fileListFragment
.listDirectory(currentDir
);
1036 setFile(currentFile
);
1039 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1041 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1043 /// TODO refactor and make common
1044 synchResult
!= null
&& !synchResult
.isSuccess() &&
1045 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1046 synchResult
.isIdPRedirection() ||
1047 (synchResult
.isException() && synchResult
.getException()
1048 instanceof AuthenticatorException
))) {
1052 OwnCloudClient client
;
1053 OwnCloudAccount ocAccount
=
1054 new OwnCloudAccount(getAccount(), context
);
1055 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1056 removeClientFor(ocAccount
));
1058 if (client
!= null
) {
1059 OwnCloudCredentials cred
= client
.getCredentials();
1061 AccountManager am
= AccountManager
.get(context
);
1062 if (cred
.authTokenExpires()) {
1063 am
.invalidateAuthToken(
1068 am
.clearPassword(getAccount());
1072 requestCredentialsUpdate();
1074 } catch (AccountNotFoundException e
) {
1075 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1080 removeStickyBroadcast(intent
);
1081 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1082 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1084 setBackgroundText();
1088 if (synchResult
!= null
) {
1089 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1090 mLastSslUntrustedServerResult
= synchResult
;
1093 } catch (RuntimeException e
) {
1094 // avoid app crashes after changing the serial id of RemoteOperationResult
1095 // in owncloud library with broadcast notifications pending to process
1096 removeStickyBroadcast(intent
);
1102 * Show a text message on screen view for notifying user if content is
1103 * loading or folder is empty
1105 private void setBackgroundText() {
1106 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1107 if (ocFileListFragment
!= null
) {
1108 int message
= R
.string
.file_list_loading
;
1109 if (!mSyncInProgress
) {
1110 // In case file list is empty
1111 message
= R
.string
.file_list_empty
;
1113 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1115 Log_OC
.e(TAG
, "OCFileListFragment is null");
1120 * Once the file upload has finished -> update view
1122 private class UploadFinishReceiver
extends BroadcastReceiver
{
1124 * Once the file upload has finished -> update view
1125 * @author David A. Velasco
1126 * {@link BroadcastReceiver} to enable upload feedback in UI
1129 public void onReceive(Context context
, Intent intent
) {
1131 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1132 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1133 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1134 OCFile currentDir
= getCurrentDir();
1135 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1136 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1138 if (sameAccount
&& isDescendant
) {
1139 refreshListOfFilesFragment();
1142 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1143 boolean renamedInUpload
= getFile().getRemotePath().
1144 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1145 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1147 FileFragment details
= getSecondFragment();
1148 boolean detailFragmentIsShown
= (details
!= null
&&
1149 details
instanceof FileDetailFragment
);
1151 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1152 if (uploadWasFine
) {
1153 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1155 if (renamedInUpload
) {
1156 String newName
= (new File(uploadedRemotePath
)).getName();
1157 Toast msg
= Toast
.makeText(
1160 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1165 if (uploadWasFine
|| getFile().fileExists()) {
1166 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1168 cleanSecondFragment();
1171 // Force the preview if the file is an image
1172 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1173 startImagePreview(getFile());
1174 } // TODO what about other kind of previews?
1178 if (intent
!= null
) {
1179 removeStickyBroadcast(intent
);
1189 * Class waiting for broadcast events from the {@link FileDownloader} service.
1191 * Updates the UI when a download is started or finished, provided that it is relevant for the
1194 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1196 //int refreshCounter = 0;
1198 public void onReceive(Context context
, Intent intent
) {
1200 boolean sameAccount
= isSameAccount(context
, intent
);
1201 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1202 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1204 if (sameAccount
&& isDescendant
) {
1205 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1206 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1207 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1208 refreshListOfFilesFragment();
1210 refreshSecondFragment(
1212 downloadedRemotePath
,
1213 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1217 if (mWaitingToSend
!= null
) {
1218 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1219 if (mWaitingToSend
.isDown()) {
1220 sendDownloadedFile();
1225 if (intent
!= null
) {
1226 removeStickyBroadcast(intent
);
1231 private boolean isDescendant(String downloadedRemotePath
) {
1232 OCFile currentDir
= getCurrentDir();
1234 currentDir
!= null
&&
1235 downloadedRemotePath
!= null
&&
1236 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1240 private boolean isAscendant(String linkedToRemotePath
) {
1241 OCFile currentDir
= getCurrentDir();
1243 currentDir
!= null
&&
1244 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1248 private boolean isSameAccount(Context context
, Intent intent
) {
1249 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1250 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1255 public void browseToRoot() {
1256 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1257 if (listOfFiles
!= null
) { // should never be null, indeed
1258 while (mDirectories
.getCount() > 1) {
1261 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1262 listOfFiles
.listDirectory(root
);
1263 setFile(listOfFiles
.getCurrentFile());
1264 startSyncFolderOperation(root
, false
);
1266 cleanSecondFragment();
1270 public void browseTo(OCFile folder
) {
1271 if (folder
== null
|| !folder
.isFolder()) {
1272 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1274 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1275 if (listOfFiles
!= null
) {
1276 setNavigationListWithFolder(folder
);
1277 listOfFiles
.listDirectory(folder
);
1278 setFile(listOfFiles
.getCurrentFile());
1279 startSyncFolderOperation(folder
, false
);
1281 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1283 cleanSecondFragment();
1290 * Updates action bar and second fragment, if in dual pane mode.
1293 public void onBrowsedDownTo(OCFile directory
) {
1294 pushDirname(directory
);
1295 cleanSecondFragment();
1298 startSyncFolderOperation(directory
, false
);
1303 * Shows the information of the {@link OCFile} received as a
1304 * parameter in the second fragment.
1306 * @param file {@link OCFile} whose details will be shown
1309 public void showDetails(OCFile file
) {
1310 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1311 setSecondFragment(detailFragment
);
1312 updateFragmentsVisibility(true
);
1313 updateNavigationElementsInActionBar(file
);
1321 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1322 ActionBar actionBar
= getSupportActionBar();
1324 // For adding content description tag to a title field in the action bar
1325 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1327 if (chosenFile
== null
|| mDualPane
) {
1328 // only list of files - set for browsing through folders
1329 OCFile currentDir
= getCurrentDir();
1330 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1331 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1332 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1334 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1335 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1336 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1337 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1340 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1341 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1344 actionBar
.setDisplayHomeAsUpEnabled(true
);
1345 actionBar
.setDisplayShowTitleEnabled(true
);
1346 actionBar
.setTitle(chosenFile
.getFileName());
1347 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1348 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1349 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1350 getWindow().getDecorView().findViewById(actionBarTitleId
).
1351 setContentDescription(chosenFile
.getFileName());
1358 protected ServiceConnection
newTransferenceServiceConnection() {
1359 return new ListServiceConnection();
1362 /** Defines callbacks for service binding, passed to bindService() */
1363 private class ListServiceConnection
implements ServiceConnection
{
1366 public void onServiceConnected(ComponentName component
, IBinder service
) {
1367 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1368 Log_OC
.d(TAG
, "Download service connected");
1369 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1370 if (mWaitingToPreview
!= null
)
1371 if (getStorageManager() != null
) {
1372 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1373 if (!mWaitingToPreview
.isDown()) {
1374 requestForDownload();
1378 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1379 Log_OC
.d(TAG
, "Upload service connected");
1380 mUploaderBinder
= (FileUploaderBinder
) service
;
1384 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1385 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1386 if (listOfFiles
!= null
) {
1387 listOfFiles
.listDirectory();
1389 FileFragment secondFragment
= getSecondFragment();
1390 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1391 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1392 detailFragment
.listenForTransferProgress();
1393 detailFragment
.updateFileDetails(false
, false
);
1398 public void onServiceDisconnected(ComponentName component
) {
1399 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1400 Log_OC
.d(TAG
, "Download service disconnected");
1401 mDownloaderBinder
= null
;
1402 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1403 Log_OC
.d(TAG
, "Upload service disconnected");
1404 mUploaderBinder
= null
;
1412 * Launch an intent to request the PIN code to the user before letting him use the app
1414 private void requestPinCode() {
1415 boolean pinStart
= false
;
1416 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1417 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1419 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1420 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1427 public void onSavedCertificate() {
1428 startSyncFolderOperation(getCurrentDir(), false
);
1433 public void onFailedSavingCertificate() {
1434 showDialog(DIALOG_CERT_NOT_SAVED
);
1438 public void onCancelCertificate() {
1443 * Updates the view associated to the activity after the finish of some operation over files
1444 * in the current account.
1446 * @param operation Removal operation performed.
1447 * @param result Result of the removal.
1450 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1451 super.onRemoteOperationFinish(operation
, result
);
1453 if (operation
instanceof RemoveFileOperation
) {
1454 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1456 } else if (operation
instanceof RenameFileOperation
) {
1457 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1459 } else if (operation
instanceof SynchronizeFileOperation
) {
1460 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1462 } else if (operation
instanceof CreateFolderOperation
) {
1463 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1465 } else if (operation
instanceof CreateShareOperation
) {
1466 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1468 } else if (operation
instanceof UnshareLinkOperation
) {
1469 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1471 } else if (operation
instanceof MoveFileOperation
) {
1472 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1478 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1479 if (result
.isSuccess()) {
1480 refreshShowDetails();
1481 refreshListOfFilesFragment();
1486 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1487 if (result
.isSuccess()) {
1488 refreshShowDetails();
1489 refreshListOfFilesFragment();
1491 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1492 cleanSecondFragment();
1493 refreshListOfFilesFragment();
1497 private void refreshShowDetails() {
1498 FileFragment details
= getSecondFragment();
1499 if (details
!= null
) {
1500 OCFile file
= details
.getFile();
1502 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1503 if (details
instanceof PreviewMediaFragment
) {
1504 // Refresh OCFile of the fragment
1505 ((PreviewMediaFragment
) details
).updateFile(file
);
1510 invalidateOptionsMenu();
1515 * Updates the view associated to the activity after the finish of an operation trying to remove a
1518 * @param operation Removal operation performed.
1519 * @param result Result of the removal.
1521 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1522 dismissLoadingDialog();
1524 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1528 if (result
.isSuccess()) {
1529 OCFile removedFile
= operation
.getFile();
1530 FileFragment second
= getSecondFragment();
1531 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1532 if (second
instanceof PreviewMediaFragment
) {
1533 ((PreviewMediaFragment
)second
).stopPreview(true
);
1535 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1536 cleanSecondFragment();
1538 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1539 refreshListOfFilesFragment();
1541 invalidateOptionsMenu();
1543 if (result
.isSslRecoverableException()) {
1544 mLastSslUntrustedServerResult
= result
;
1545 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1552 * Updates the view associated to the activity after the finish of an operation trying to move a
1555 * @param operation Move operation performed.
1556 * @param result Result of the move operation.
1558 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1559 if (result
.isSuccess()) {
1560 dismissLoadingDialog();
1561 refreshListOfFilesFragment();
1563 dismissLoadingDialog();
1565 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1566 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1570 } catch (NotFoundException e
) {
1571 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1578 * Updates the view associated to the activity after the finish of an operation trying to rename a
1581 * @param operation Renaming operation performed.
1582 * @param result Result of the renaming.
1584 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1585 dismissLoadingDialog();
1586 OCFile renamedFile
= operation
.getFile();
1587 if (result
.isSuccess()) {
1588 FileFragment details
= getSecondFragment();
1589 if (details
!= null
) {
1590 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1591 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1592 showDetails(renamedFile
);
1594 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1595 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1596 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1597 int position
= ((PreviewMediaFragment
)details
).getPosition();
1598 startMediaPreview(renamedFile
, position
, true
);
1600 getFileOperationsHelper().openFile(renamedFile
);
1605 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1606 refreshListOfFilesFragment();
1610 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1614 if (result
.isSslRecoverableException()) {
1615 mLastSslUntrustedServerResult
= result
;
1616 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1621 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1622 dismissLoadingDialog();
1623 OCFile syncedFile
= operation
.getLocalFile();
1624 if (!result
.isSuccess()) {
1625 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1626 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1627 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1628 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1634 if (operation
.transferWasRequested()) {
1635 onTransferStateChanged(syncedFile
, true
, true
);
1638 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1646 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1648 * @param operation Creation operation performed.
1649 * @param result Result of the creation.
1651 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1652 if (result
.isSuccess()) {
1653 dismissLoadingDialog();
1654 refreshListOfFilesFragment();
1656 dismissLoadingDialog();
1658 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1659 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1663 } catch (NotFoundException e
) {
1664 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1674 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1675 refreshListOfFilesFragment();
1676 FileFragment details
= getSecondFragment();
1677 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1678 if (downloading
|| uploading
) {
1679 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1681 if (!file
.fileExists()) {
1682 cleanSecondFragment();
1684 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1692 private void requestForDownload() {
1693 Account account
= getAccount();
1694 //if (!mWaitingToPreview.isDownloading()) {
1695 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1696 Intent i
= new Intent(this, FileDownloader
.class);
1697 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1698 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1704 private OCFile
getCurrentDir() {
1705 OCFile file
= getFile();
1707 if (file
.isFolder()) {
1709 } else if (getStorageManager() != null
) {
1710 String parentPath
= file
.getRemotePath().substring(0,
1711 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1712 return getStorageManager().getFileByPath(parentPath
);
1718 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1719 long currentSyncTime
= System
.currentTimeMillis();
1721 mSyncInProgress
= true
;
1723 // perform folder synchronization
1724 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1727 getFileOperationsHelper().isSharedSupported(),
1729 getStorageManager(),
1731 getApplicationContext()
1733 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1735 setSupportProgressBarIndeterminateVisibility(true
);
1737 setBackgroundText();
1741 * Show untrusted cert dialog
1743 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1744 // Show a dialog with the certificate info
1745 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1746 (CertificateCombinedException
)result
.getException());
1747 FragmentManager fm
= getSupportFragmentManager();
1748 FragmentTransaction ft
= fm
.beginTransaction();
1749 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1752 private void requestForDownload(OCFile file
) {
1753 Account account
= getAccount();
1754 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1755 Intent i
= new Intent(this, FileDownloader
.class);
1756 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1757 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1762 private void sendDownloadedFile(){
1763 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1764 mWaitingToSend
= null
;
1769 * Requests the download of the received {@link OCFile} , updates the UI
1770 * to monitor the download progress and prepares the activity to send the file
1771 * when the download finishes.
1773 * @param file {@link OCFile} to download and preview.
1775 public void startDownloadForSending(OCFile file
) {
1776 mWaitingToSend
= file
;
1777 requestForDownload(mWaitingToSend
);
1778 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1779 updateFragmentsVisibility(hasSecondFragment
);
1783 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1785 * @param file Image {@link OCFile} to show.
1787 public void startImagePreview(OCFile file
) {
1788 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1789 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1790 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1791 startActivity(showDetailsIntent
);
1796 * Stars the preview of an already down media {@link OCFile}.
1798 * @param file Media {@link OCFile} to preview.
1799 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1800 * @param autoplay When 'true', the playback will start without user interactions.
1802 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1803 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1804 setSecondFragment(mediaFragment
);
1805 updateFragmentsVisibility(true
);
1806 updateNavigationElementsInActionBar(file
);
1811 * Requests the download of the received {@link OCFile} , updates the UI
1812 * to monitor the download progress and prepares the activity to preview
1813 * or open the file when the download finishes.
1815 * @param file {@link OCFile} to download and preview.
1817 public void startDownloadForPreview(OCFile file
) {
1818 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1819 setSecondFragment(detailFragment
);
1820 mWaitingToPreview
= file
;
1821 requestForDownload();
1822 updateFragmentsVisibility(true
);
1823 updateNavigationElementsInActionBar(file
);
1828 public void cancelTransference(OCFile file
) {
1829 getFileOperationsHelper().cancelTransference(file
);
1830 if (mWaitingToPreview
!= null
&&
1831 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1832 mWaitingToPreview
= null
;
1834 if (mWaitingToSend
!= null
&&
1835 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1836 mWaitingToSend
= null
;
1838 onTransferStateChanged(file
, false
, false
);
1842 public void onRefresh(boolean ignoreETag
) {
1843 refreshList(ignoreETag
);
1847 public void onRefresh() {
1851 private void refreshList(boolean ignoreETag
) {
1852 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1853 if (listOfFiles
!= null
) {
1854 OCFile folder
= listOfFiles
.getCurrentFile();
1855 if (folder
!= null
) {
1856 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1857 listDirectory(mFile);*/
1858 startSyncFolderOperation(folder
, ignoreETag
);
1863 private void sortByDate(boolean ascending
){
1864 getListOfFilesFragment().sortByDate(ascending
);
1867 private void sortBySize(boolean ascending
){
1868 getListOfFilesFragment().sortBySize(ascending
);
1871 private void sortByName(boolean ascending
){
1872 getListOfFilesFragment().sortByName(ascending
);
1878 * Translates a content URI of a content to a physical path on the disk
1880 * @param uri The URI to resolve
1881 * @return The path to the content or null if it could not be found
1883 @TargetApi(Build
.VERSION_CODES
.KITKAT
)
1884 public String
getPath(Uri uri
) {
1885 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
1888 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(this, uri
)) {
1889 // ExternalStorageProvider
1890 if (UriUtils
.isExternalStorageDocument(uri
)) {
1891 final String docId
= DocumentsContract
.getDocumentId(uri
);
1892 final String
[] split
= docId
.split(":");
1893 final String type
= split
[0];
1895 if ("primary".equalsIgnoreCase(type
)) {
1896 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
1899 // DownloadsProvider
1900 else if (UriUtils
.isDownloadsDocument(uri
)) {
1902 final String id
= DocumentsContract
.getDocumentId(uri
);
1903 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
1906 return UriUtils
.getDataColumn(this, contentUri
, null
, null
);
1909 else if (UriUtils
.isMediaDocument(uri
)) {
1910 final String docId
= DocumentsContract
.getDocumentId(uri
);
1911 final String
[] split
= docId
.split(":");
1912 final String type
= split
[0];
1914 Uri contentUri
= null
;
1915 if ("image".equals(type
)) {
1916 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
1917 } else if ("video".equals(type
)) {
1918 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
1919 } else if ("audio".equals(type
)) {
1920 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
1923 final String selection
= "_id=?";
1924 final String
[] selectionArgs
= new String
[] { split
[1] };
1926 return UriUtils
.getDataColumn(this, contentUri
, selection
, selectionArgs
);
1928 // Documents providers returned as content://...
1929 else if (UriUtils
.isContentDocument(uri
)) {
1930 return uri
.toString();
1933 // MediaStore (and general)
1934 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
1936 // Return the remote address
1937 if (UriUtils
.isGooglePhotosUri(uri
))
1938 return uri
.getLastPathSegment();
1940 return UriUtils
.getDataColumn(this, uri
, null
, null
);
1943 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
1944 return uri
.getPath();