2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
27 import android
.accounts
.Account
;
28 import android
.accounts
.AccountManager
;
29 import android
.accounts
.AuthenticatorException
;
30 import android
.annotation
.TargetApi
;
31 import android
.app
.AlertDialog
;
32 import android
.content
.BroadcastReceiver
;
33 import android
.content
.ComponentName
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Build
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.OpenableColumns
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.view
.View
;
54 import android
.view
.ViewGroup
;
55 import android
.widget
.ArrayAdapter
;
56 import android
.widget
.TextView
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
61 import com
.actionbarsherlock
.view
.Menu
;
62 import com
.actionbarsherlock
.view
.MenuInflater
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.actionbarsherlock
.view
.Window
;
65 import com
.owncloud
.android
.BuildConfig
;
66 import com
.owncloud
.android
.MainApp
;
67 import com
.owncloud
.android
.R
;
68 import com
.owncloud
.android
.authentication
.PinCheck
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
72 import com
.owncloud
.android
.files
.services
.FileUploader
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
78 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
79 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
84 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
85 import com
.owncloud
.android
.operations
.CreateShareOperation
;
86 import com
.owncloud
.android
.operations
.MoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RenameFileOperation
;
89 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
90 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
91 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
92 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
93 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
94 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
101 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
106 import com
.owncloud
.android
.utils
.DisplayUtils
;
107 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
108 import com
.owncloud
.android
.utils
.FileStorageUtils
;
109 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
151 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
158 private Boolean mUnlocked
= false
;
161 protected void onCreate(Bundle savedInstanceState
) {
162 Log_OC
.d(TAG
, "onCreate() start");
163 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
165 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
168 if (PinCheck
.checkIfPinEntry()){
169 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
170 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
174 /// grant that FileObserverService is watching favorite files
175 if (savedInstanceState
== null
) {
176 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
177 startService(initObserversIntent
);
180 /// Load of saved instance state
181 if(savedInstanceState
!= null
) {
182 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
183 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
184 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
187 mWaitingToPreview
= null
;
188 mSyncInProgress
= false
;
189 mWaitingToSend
= null
;
194 // Inflate and set the layout view
195 setContentView(R
.layout
.files
);
196 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
197 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
198 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
199 if (savedInstanceState
== null
) {
200 createMinFragments();
204 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
206 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
210 Log_OC
.d(TAG
, "onCreate() end");
214 protected void onStart() {
215 Log_OC
.d(TAG
, "onStart() start");
217 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
218 Log_OC
.d(TAG
, "onStart() end");
222 protected void onDestroy() {
223 Log_OC
.d(TAG
, "onDestroy() start");
225 Log_OC
.d(TAG
, "onDestroy() end");
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(), DIALOG_CREATE_FOLDER
);
487 case R
.id
.action_sync_account
: {
488 startSynchronization();
491 case R
.id
.action_upload
: {
492 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
493 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
497 case R
.id
.action_settings
: {
498 Intent settingsIntent
= new Intent(this, Preferences
.class);
499 startActivity(settingsIntent
);
502 case R
.id
.action_logger
: {
503 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
504 startActivity(loggerIntent
);
507 case android
.R
.id
.home
: {
508 FileFragment second
= getSecondFragment();
509 OCFile currentDir
= getCurrentDir();
510 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
511 (second
!= null
&& second
.getFile() != null
)) {
517 case R
.id
.action_sort
: {
518 SharedPreferences appPreferences
= PreferenceManager
519 .getDefaultSharedPreferences(this);
521 // Read sorting order, default to sort by name ascending
522 Integer sortOrder
= appPreferences
523 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
525 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
526 builder
.setTitle(R
.string
.actionbar_sort_title
)
527 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
528 public void onClick(DialogInterface dialog
, int which
) {
538 // TODO re-enable when server-side folder size calculation is available
540 // sortBySize(false);
548 builder
.create().show();
552 retval
= super.onOptionsItemSelected(item
);
557 private void startSynchronization() {
558 Log_OC
.d(TAG
, "Got to start sync");
559 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
560 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
561 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
562 Bundle bundle
= new Bundle();
563 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
564 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
565 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
566 ContentResolver
.requestSync(
568 MainApp
.getAuthority(), bundle
);
570 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
571 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
572 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
573 builder
.setExpedited(true
);
574 builder
.setManual(true
);
577 // Fix bug in Android Lollipop when you click on refresh the whole account
578 Bundle extras
= new Bundle();
579 builder
.setExtras(extras
);
581 SyncRequest request
= builder
.build();
582 ContentResolver
.requestSync(request
);
588 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
589 if (itemPosition
!= 0) {
590 String targetPath
= "";
591 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
592 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
594 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
595 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
596 if (targetFolder
!= null
) {
597 browseTo(targetFolder
);
600 // the next operation triggers a new call to this method, but it's necessary to
601 // ensure that the name exposed in the action bar is the current directory when the
602 // user selected it in the navigation list
603 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
604 getSupportActionBar().setSelectedNavigationItem(0);
610 * Called, when the user selected something for uploading
613 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
615 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
617 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
618 //getClipData is only supported on api level 16+, Jelly Bean
619 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
620 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
621 Intent intent
= new Intent();
622 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
623 requestSimpleUpload(intent
, resultCode
);
626 requestSimpleUpload(data
, resultCode
);
628 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
629 requestMultipleUpload(data
, resultCode
);
631 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
633 final Intent fData
= data
;
634 final int fResultCode
= resultCode
;
635 getHandler().postDelayed(
639 requestMoveOperation(fData
, fResultCode
);
642 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
646 super.onActivityResult(requestCode
, resultCode
, data
);
651 private void requestMultipleUpload(Intent data
, int resultCode
) {
652 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
653 if (filePaths
!= null
) {
654 String
[] remotePaths
= new String
[filePaths
.length
];
655 String remotePathBase
= "";
657 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
658 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
660 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
661 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
662 for (int j
= 0; j
< remotePaths
.length
; j
++) {
663 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
666 Intent i
= new Intent(this, FileUploader
.class);
667 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
668 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
669 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
670 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
671 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
672 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
676 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
677 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
684 private void requestSimpleUpload(Intent data
, int resultCode
) {
685 String filePath
= null
;
686 String mimeType
= null
;
688 Uri selectedImageUri
= data
.getData();
691 mimeType
= getContentResolver().getType(selectedImageUri
);
693 String fileManagerString
= selectedImageUri
.getPath();
694 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
696 if (selectedImagePath
!= null
)
697 filePath
= selectedImagePath
;
699 filePath
= fileManagerString
;
701 } catch (Exception e
) {
702 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
705 if (filePath
== null
) {
706 Log_OC
.e(TAG
, "Couldn't resolve path to file");
707 Toast t
= Toast
.makeText(
708 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
715 Intent i
= new Intent(this, FileUploader
.class);
716 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
717 OCFile currentDir
= getCurrentDir();
718 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
720 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
721 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
723 if (cursor
!= null
&& cursor
.moveToFirst()) {
724 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
725 Log_OC
.v(TAG
, "Display Name: " + displayName
);
727 displayName
.replace(File
.separatorChar
, '_');
728 displayName
.replace(File
.pathSeparatorChar
, '_');
729 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
732 // and what happens in case of error?; wrong target name for the upload
738 remotePath
+= new File(filePath
).getName();
741 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
742 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
743 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
744 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
745 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
746 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
751 * Request the operation for moving the file/folder from one path to another
753 * @param data Intent received
754 * @param resultCode Result code received
756 private void requestMoveOperation(Intent data
, int resultCode
) {
757 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
758 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
759 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
763 public void onBackPressed() {
764 OCFileListFragment listOfFiles
= getListOfFilesFragment();
765 if (mDualPane
|| getSecondFragment() == null
) {
766 if (listOfFiles
!= null
) { // should never be null, indeed
767 if (mDirectories
.getCount() <= 1) {
771 int levelsUp
= listOfFiles
.onBrowseUp();
772 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
777 if (listOfFiles
!= null
) { // should never be null, indeed
778 setFile(listOfFiles
.getCurrentFile());
780 cleanSecondFragment();
785 protected void onSaveInstanceState(Bundle outState
) {
786 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
787 Log_OC
.d(TAG
, "onSaveInstanceState() start");
788 super.onSaveInstanceState(outState
);
789 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
790 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
791 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
792 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
794 Log_OC
.d(TAG
, "onSaveInstanceState() end");
800 protected void onResume() {
801 Log_OC
.d(TAG
, "onResume() start");
804 if (PinCheck
.checkIfPinEntry()){
805 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
806 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
810 // refresh list of files
811 refreshListOfFilesFragment();
813 // Listen for sync messages
814 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
815 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
816 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
817 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
818 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
819 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
820 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
821 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
823 // Listen for upload messages
824 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
825 mUploadFinishReceiver
= new UploadFinishReceiver();
826 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
828 // Listen for download messages
829 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
830 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
831 mDownloadFinishReceiver
= new DownloadFinishReceiver();
832 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
834 Log_OC
.d(TAG
, "onResume() end");
839 protected void onPause() {
840 Log_OC
.d(TAG
, "onPause() start");
841 if (mSyncBroadcastReceiver
!= null
) {
842 unregisterReceiver(mSyncBroadcastReceiver
);
843 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
844 mSyncBroadcastReceiver
= null
;
846 if (mUploadFinishReceiver
!= null
) {
847 unregisterReceiver(mUploadFinishReceiver
);
848 mUploadFinishReceiver
= null
;
850 if (mDownloadFinishReceiver
!= null
) {
851 unregisterReceiver(mDownloadFinishReceiver
);
852 mDownloadFinishReceiver
= null
;
855 PinCheck
.setUnlockTimestamp();
858 Log_OC
.d(TAG
, "onPause() end");
862 * Pushes a directory to the drop down list
863 * @param directory to push
864 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
866 public void pushDirname(OCFile directory
) {
867 if(!directory
.isFolder()){
868 throw new IllegalArgumentException("Only directories may be pushed!");
870 mDirectories
.insert(directory
.getFileName(), 0);
875 * Pops a directory name from the drop down list
876 * @return True, unless the stack is empty
878 public boolean popDirname() {
879 mDirectories
.remove(mDirectories
.getItem(0));
880 return !mDirectories
.isEmpty();
883 // Custom array adapter to override text colors
884 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
886 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
890 public View
getView(int position
, View convertView
, ViewGroup parent
) {
891 View v
= super.getView(position
, convertView
, parent
);
893 ((TextView
) v
).setTextColor(getResources().getColorStateList(
894 android
.R
.color
.white
));
896 fixRoot((TextView
) v
);
900 public View
getDropDownView(int position
, View convertView
,
902 View v
= super.getDropDownView(position
, convertView
, parent
);
904 ((TextView
) v
).setTextColor(getResources().getColorStateList(
905 android
.R
.color
.white
));
907 fixRoot((TextView
) v
);
911 private void fixRoot(TextView v
) {
912 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
913 v
.setText(R
.string
.default_display_name_for_root_folder
);
919 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
922 * {@link BroadcastReceiver} to enable syncing feedback in UI
925 public void onReceive(Context context
, Intent intent
) {
927 String event
= intent
.getAction();
928 Log_OC
.d(TAG
, "Received broadcast " + event
);
929 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
930 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
931 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
932 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
936 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
937 mSyncInProgress
= true
;
940 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
941 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
943 if (currentDir
== null
) {
944 // current folder was removed from the server
945 Toast
.makeText( FileDisplayActivity
.this,
946 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
952 if (currentFile
== null
&& !getFile().isFolder()) {
953 // currently selected file was removed in the server, and now we know it
954 cleanSecondFragment();
955 currentFile
= currentDir
;
958 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
959 OCFileListFragment fileListFragment
= getListOfFilesFragment();
960 if (fileListFragment
!= null
) {
961 fileListFragment
.listDirectory(currentDir
);
964 setFile(currentFile
);
967 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
969 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
971 /// TODO refactor and make common
972 synchResult
!= null
&& !synchResult
.isSuccess() &&
973 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
974 synchResult
.isIdPRedirection() ||
975 (synchResult
.isException() && synchResult
.getException()
976 instanceof AuthenticatorException
))) {
980 OwnCloudClient client
;
981 OwnCloudAccount ocAccount
=
982 new OwnCloudAccount(getAccount(), context
);
983 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
984 removeClientFor(ocAccount
));
986 if (client
!= null
) {
987 OwnCloudCredentials cred
= client
.getCredentials();
989 AccountManager am
= AccountManager
.get(context
);
990 if (cred
.authTokenExpires()) {
991 am
.invalidateAuthToken(
996 am
.clearPassword(getAccount());
1000 requestCredentialsUpdate();
1002 } catch (AccountNotFoundException e
) {
1003 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1008 removeStickyBroadcast(intent
);
1009 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1010 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1012 setBackgroundText();
1016 if (synchResult
!= null
) {
1017 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1018 mLastSslUntrustedServerResult
= synchResult
;
1021 } catch (RuntimeException e
) {
1022 // avoid app crashes after changing the serial id of RemoteOperationResult
1023 // in owncloud library with broadcast notifications pending to process
1024 removeStickyBroadcast(intent
);
1030 * Show a text message on screen view for notifying user if content is
1031 * loading or folder is empty
1033 private void setBackgroundText() {
1034 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1035 if (ocFileListFragment
!= null
) {
1036 int message
= R
.string
.file_list_loading
;
1037 if (!mSyncInProgress
) {
1038 // In case file list is empty
1039 message
= R
.string
.file_list_empty
;
1041 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1043 Log_OC
.e(TAG
, "OCFileListFragment is null");
1048 * Once the file upload has finished -> update view
1050 private class UploadFinishReceiver
extends BroadcastReceiver
{
1052 * Once the file upload has finished -> update view
1053 * @author David A. Velasco
1054 * {@link BroadcastReceiver} to enable upload feedback in UI
1057 public void onReceive(Context context
, Intent intent
) {
1059 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1060 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1061 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1062 OCFile currentDir
= getCurrentDir();
1063 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1064 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1066 if (sameAccount
&& isDescendant
) {
1067 refreshListOfFilesFragment();
1070 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1071 boolean renamedInUpload
= getFile().getRemotePath().
1072 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1073 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1075 FileFragment details
= getSecondFragment();
1076 boolean detailFragmentIsShown
= (details
!= null
&&
1077 details
instanceof FileDetailFragment
);
1079 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1080 if (uploadWasFine
) {
1081 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1083 if (renamedInUpload
) {
1084 String newName
= (new File(uploadedRemotePath
)).getName();
1085 Toast msg
= Toast
.makeText(
1088 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1093 if (uploadWasFine
|| getFile().fileExists()) {
1094 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1096 cleanSecondFragment();
1099 // Force the preview if the file is an image
1100 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1101 startImagePreview(getFile());
1102 } // TODO what about other kind of previews?
1106 if (intent
!= null
) {
1107 removeStickyBroadcast(intent
);
1117 * Class waiting for broadcast events from the {@link FileDownloader} service.
1119 * Updates the UI when a download is started or finished, provided that it is relevant for the
1122 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1124 //int refreshCounter = 0;
1126 public void onReceive(Context context
, Intent intent
) {
1128 boolean sameAccount
= isSameAccount(context
, intent
);
1129 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1130 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1132 if (sameAccount
&& isDescendant
) {
1133 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1134 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1135 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1136 refreshListOfFilesFragment();
1138 refreshSecondFragment(
1140 downloadedRemotePath
,
1141 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1145 if (mWaitingToSend
!= null
) {
1146 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1147 if (mWaitingToSend
.isDown()) {
1148 sendDownloadedFile();
1153 if (intent
!= null
) {
1154 removeStickyBroadcast(intent
);
1159 private boolean isDescendant(String downloadedRemotePath
) {
1160 OCFile currentDir
= getCurrentDir();
1162 currentDir
!= null
&&
1163 downloadedRemotePath
!= null
&&
1164 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1168 private boolean isAscendant(String linkedToRemotePath
) {
1169 OCFile currentDir
= getCurrentDir();
1171 currentDir
!= null
&&
1172 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1176 private boolean isSameAccount(Context context
, Intent intent
) {
1177 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1178 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1183 public void browseToRoot() {
1184 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1185 if (listOfFiles
!= null
) { // should never be null, indeed
1186 while (mDirectories
.getCount() > 1) {
1189 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1190 listOfFiles
.listDirectory(root
);
1191 setFile(listOfFiles
.getCurrentFile());
1192 startSyncFolderOperation(root
, false
);
1194 cleanSecondFragment();
1198 public void browseTo(OCFile folder
) {
1199 if (folder
== null
|| !folder
.isFolder()) {
1200 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1202 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1203 if (listOfFiles
!= null
) {
1204 setNavigationListWithFolder(folder
);
1205 listOfFiles
.listDirectory(folder
);
1206 setFile(listOfFiles
.getCurrentFile());
1207 startSyncFolderOperation(folder
, false
);
1209 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1211 cleanSecondFragment();
1218 * Updates action bar and second fragment, if in dual pane mode.
1221 public void onBrowsedDownTo(OCFile directory
) {
1222 pushDirname(directory
);
1223 cleanSecondFragment();
1226 startSyncFolderOperation(directory
, false
);
1231 * Shows the information of the {@link OCFile} received as a
1232 * parameter in the second fragment.
1234 * @param file {@link OCFile} whose details will be shown
1237 public void showDetails(OCFile file
) {
1238 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1239 setSecondFragment(detailFragment
);
1240 updateFragmentsVisibility(true
);
1241 updateNavigationElementsInActionBar(file
);
1249 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1250 ActionBar actionBar
= getSupportActionBar();
1252 // For adding content description tag to a title field in the action bar
1253 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1255 if (chosenFile
== null
|| mDualPane
) {
1256 // only list of files - set for browsing through folders
1257 OCFile currentDir
= getCurrentDir();
1258 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1259 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1260 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1262 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1263 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1264 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1265 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1268 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1269 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1272 actionBar
.setDisplayHomeAsUpEnabled(true
);
1273 actionBar
.setDisplayShowTitleEnabled(true
);
1274 actionBar
.setTitle(chosenFile
.getFileName());
1275 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1276 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1277 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1278 getWindow().getDecorView().findViewById(actionBarTitleId
).
1279 setContentDescription(chosenFile
.getFileName());
1286 protected ServiceConnection
newTransferenceServiceConnection() {
1287 return new ListServiceConnection();
1290 /** Defines callbacks for service binding, passed to bindService() */
1291 private class ListServiceConnection
implements ServiceConnection
{
1294 public void onServiceConnected(ComponentName component
, IBinder service
) {
1295 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1296 Log_OC
.d(TAG
, "Download service connected");
1297 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1298 if (mWaitingToPreview
!= null
)
1299 if (getStorageManager() != null
) {
1300 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1301 if (!mWaitingToPreview
.isDown()) {
1302 requestForDownload();
1306 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1307 Log_OC
.d(TAG
, "Upload service connected");
1308 mUploaderBinder
= (FileUploaderBinder
) service
;
1312 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1313 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1314 if (listOfFiles
!= null
) {
1315 listOfFiles
.listDirectory();
1317 FileFragment secondFragment
= getSecondFragment();
1318 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1319 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1320 detailFragment
.listenForTransferProgress();
1321 detailFragment
.updateFileDetails(false
, false
);
1326 public void onServiceDisconnected(ComponentName component
) {
1327 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1328 Log_OC
.d(TAG
, "Download service disconnected");
1329 mDownloaderBinder
= null
;
1330 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1331 Log_OC
.d(TAG
, "Upload service disconnected");
1332 mUploaderBinder
= null
;
1338 public void onSavedCertificate() {
1339 startSyncFolderOperation(getCurrentDir(), false
);
1344 public void onFailedSavingCertificate() {
1345 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1346 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1348 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1352 public void onCancelCertificate() {
1357 * Updates the view associated to the activity after the finish of some operation over files
1358 * in the current account.
1360 * @param operation Removal operation performed.
1361 * @param result Result of the removal.
1364 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1365 super.onRemoteOperationFinish(operation
, result
);
1367 if (operation
instanceof RemoveFileOperation
) {
1368 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1370 } else if (operation
instanceof RenameFileOperation
) {
1371 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1373 } else if (operation
instanceof SynchronizeFileOperation
) {
1374 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1376 } else if (operation
instanceof CreateFolderOperation
) {
1377 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1379 } else if (operation
instanceof CreateShareOperation
) {
1380 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1382 } else if (operation
instanceof UnshareLinkOperation
) {
1383 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1385 } else if (operation
instanceof MoveFileOperation
) {
1386 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1392 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1393 if (result
.isSuccess()) {
1394 refreshShowDetails();
1395 refreshListOfFilesFragment();
1400 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1401 if (result
.isSuccess()) {
1402 refreshShowDetails();
1403 refreshListOfFilesFragment();
1405 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1406 cleanSecondFragment();
1407 refreshListOfFilesFragment();
1411 private void refreshShowDetails() {
1412 FileFragment details
= getSecondFragment();
1413 if (details
!= null
) {
1414 OCFile file
= details
.getFile();
1416 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1417 if (details
instanceof PreviewMediaFragment
) {
1418 // Refresh OCFile of the fragment
1419 ((PreviewMediaFragment
) details
).updateFile(file
);
1424 invalidateOptionsMenu();
1429 * Updates the view associated to the activity after the finish of an operation trying to remove a
1432 * @param operation Removal operation performed.
1433 * @param result Result of the removal.
1435 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1436 dismissLoadingDialog();
1438 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1442 if (result
.isSuccess()) {
1443 OCFile removedFile
= operation
.getFile();
1444 FileFragment second
= getSecondFragment();
1445 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1446 if (second
instanceof PreviewMediaFragment
) {
1447 ((PreviewMediaFragment
)second
).stopPreview(true
);
1449 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1450 cleanSecondFragment();
1452 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1453 refreshListOfFilesFragment();
1455 invalidateOptionsMenu();
1457 if (result
.isSslRecoverableException()) {
1458 mLastSslUntrustedServerResult
= result
;
1459 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1466 * Updates the view associated to the activity after the finish of an operation trying to move a
1469 * @param operation Move operation performed.
1470 * @param result Result of the move operation.
1472 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1473 if (result
.isSuccess()) {
1474 dismissLoadingDialog();
1475 refreshListOfFilesFragment();
1477 dismissLoadingDialog();
1479 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1480 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1484 } catch (NotFoundException e
) {
1485 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1492 * Updates the view associated to the activity after the finish of an operation trying to rename a
1495 * @param operation Renaming operation performed.
1496 * @param result Result of the renaming.
1498 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1499 dismissLoadingDialog();
1500 OCFile renamedFile
= operation
.getFile();
1501 if (result
.isSuccess()) {
1502 FileFragment details
= getSecondFragment();
1503 if (details
!= null
) {
1504 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1505 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1506 showDetails(renamedFile
);
1508 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1509 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1510 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1511 int position
= ((PreviewMediaFragment
)details
).getPosition();
1512 startMediaPreview(renamedFile
, position
, true
);
1514 getFileOperationsHelper().openFile(renamedFile
);
1519 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1520 refreshListOfFilesFragment();
1524 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1528 if (result
.isSslRecoverableException()) {
1529 mLastSslUntrustedServerResult
= result
;
1530 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1535 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1536 dismissLoadingDialog();
1537 OCFile syncedFile
= operation
.getLocalFile();
1538 if (!result
.isSuccess()) {
1539 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1540 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1541 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1542 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1548 if (operation
.transferWasRequested()) {
1549 onTransferStateChanged(syncedFile
, true
, true
);
1552 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1560 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1562 * @param operation Creation operation performed.
1563 * @param result Result of the creation.
1565 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1566 if (result
.isSuccess()) {
1567 dismissLoadingDialog();
1568 refreshListOfFilesFragment();
1570 dismissLoadingDialog();
1572 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1573 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1577 } catch (NotFoundException e
) {
1578 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1588 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1589 refreshListOfFilesFragment();
1590 FileFragment details
= getSecondFragment();
1591 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1592 if (downloading
|| uploading
) {
1593 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1595 if (!file
.fileExists()) {
1596 cleanSecondFragment();
1598 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1606 private void requestForDownload() {
1607 Account account
= getAccount();
1608 //if (!mWaitingToPreview.isDownloading()) {
1609 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1610 Intent i
= new Intent(this, FileDownloader
.class);
1611 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1612 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1618 private OCFile
getCurrentDir() {
1619 OCFile file
= getFile();
1621 if (file
.isFolder()) {
1623 } else if (getStorageManager() != null
) {
1624 String parentPath
= file
.getRemotePath().substring(0,
1625 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1626 return getStorageManager().getFileByPath(parentPath
);
1632 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1633 long currentSyncTime
= System
.currentTimeMillis();
1635 mSyncInProgress
= true
;
1637 // perform folder synchronization
1638 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1641 getFileOperationsHelper().isSharedSupported(),
1643 getStorageManager(),
1645 getApplicationContext()
1647 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1649 setSupportProgressBarIndeterminateVisibility(true
);
1651 setBackgroundText();
1655 * Show untrusted cert dialog
1657 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1658 // Show a dialog with the certificate info
1659 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1660 (CertificateCombinedException
)result
.getException());
1661 FragmentManager fm
= getSupportFragmentManager();
1662 FragmentTransaction ft
= fm
.beginTransaction();
1663 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1666 private void requestForDownload(OCFile file
) {
1667 Account account
= getAccount();
1668 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1669 Intent i
= new Intent(this, FileDownloader
.class);
1670 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1671 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1676 private void sendDownloadedFile(){
1677 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1678 mWaitingToSend
= null
;
1683 * Requests the download of the received {@link OCFile} , updates the UI
1684 * to monitor the download progress and prepares the activity to send the file
1685 * when the download finishes.
1687 * @param file {@link OCFile} to download and preview.
1689 public void startDownloadForSending(OCFile file
) {
1690 mWaitingToSend
= file
;
1691 requestForDownload(mWaitingToSend
);
1692 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1693 updateFragmentsVisibility(hasSecondFragment
);
1697 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1699 * @param file Image {@link OCFile} to show.
1701 public void startImagePreview(OCFile file
) {
1702 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1703 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1704 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1705 startActivity(showDetailsIntent
);
1710 * Stars the preview of an already down media {@link OCFile}.
1712 * @param file Media {@link OCFile} to preview.
1713 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1714 * @param autoplay When 'true', the playback will start without user interactions.
1716 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1717 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1718 setSecondFragment(mediaFragment
);
1719 updateFragmentsVisibility(true
);
1720 updateNavigationElementsInActionBar(file
);
1725 * Requests the download of the received {@link OCFile} , updates the UI
1726 * to monitor the download progress and prepares the activity to preview
1727 * or open the file when the download finishes.
1729 * @param file {@link OCFile} to download and preview.
1731 public void startDownloadForPreview(OCFile file
) {
1732 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1733 setSecondFragment(detailFragment
);
1734 mWaitingToPreview
= file
;
1735 requestForDownload();
1736 updateFragmentsVisibility(true
);
1737 updateNavigationElementsInActionBar(file
);
1742 public void cancelTransference(OCFile file
) {
1743 getFileOperationsHelper().cancelTransference(file
);
1744 if (mWaitingToPreview
!= null
&&
1745 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1746 mWaitingToPreview
= null
;
1748 if (mWaitingToSend
!= null
&&
1749 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1750 mWaitingToSend
= null
;
1752 onTransferStateChanged(file
, false
, false
);
1756 public void onRefresh(boolean ignoreETag
) {
1757 refreshList(ignoreETag
);
1761 public void onRefresh() {
1765 private void refreshList(boolean ignoreETag
) {
1766 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1767 if (listOfFiles
!= null
) {
1768 OCFile folder
= listOfFiles
.getCurrentFile();
1769 if (folder
!= null
) {
1770 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1771 listDirectory(mFile);*/
1772 startSyncFolderOperation(folder
, ignoreETag
);
1777 private void sortByDate(boolean ascending
){
1778 getListOfFilesFragment().sortByDate(ascending
);
1781 private void sortBySize(boolean ascending
){
1782 getListOfFilesFragment().sortBySize(ascending
);
1785 private void sortByName(boolean ascending
){
1786 getListOfFilesFragment().sortByName(ascending
);