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
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.view
.GravityCompat
;
52 import android
.support
.v7
.app
.ActionBar
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.view
.ViewGroup
;
58 import android
.view
.Window
;
59 import android
.widget
.ArrayAdapter
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import com
.owncloud
.android
.MainApp
;
64 import com
.owncloud
.android
.R
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
103 import com
.owncloud
.android
.utils
.DisplayUtils
;
104 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
105 import com
.owncloud
.android
.utils
.FileStorageUtils
;
106 import com
.owncloud
.android
.utils
.UriUtils
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
implements
116 FileFragment
.ContainerActivity
, ActionBar
.OnNavigationListener
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
119 private ArrayAdapter
<String
> mDirectories
;
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 public static final int ACTION_MOVE_FILES
= 3;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
150 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
151 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
152 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
154 private OCFile mWaitingToSend
;
158 protected void onCreate(Bundle savedInstanceState
) {
159 Log_OC
.v(TAG
, "onCreate() start");
160 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
165 /// grant that FileObserverService is watching favorite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
177 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
193 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
194 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
195 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
196 if (savedInstanceState
== null
) {
197 createMinFragments();
201 mDirectories
= new CustomArrayAdapter
<String
>(this,
202 R
.layout
.support_simple_spinner_dropdown_item
);
203 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
204 // according to the official
207 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
208 /*|| mRefreshSharesInProgress*/);
209 // always AFTER setContentView(...) ; to work around bug in its implementation
213 Log_OC
.v(TAG
, "onCreate() end");
217 protected void onStart() {
218 Log_OC
.v(TAG
, "onStart() start");
220 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
221 Log_OC
.v(TAG
, "onStart() end");
225 protected void onDestroy() {
226 Log_OC
.v(TAG
, "onDestroy() start");
228 Log_OC
.v(TAG
, "onDestroy() end");
232 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
235 protected void onAccountSet(boolean stateWasRecovered
) {
236 super.onAccountSet(stateWasRecovered
);
237 if (getAccount() != null
) {
238 /// Check whether the 'main' OCFile handled by the Activity is contained in the
240 OCFile file
= getFile();
241 // get parent from path
242 String parentPath
= "";
244 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
245 // upload in progress - right now, files are not inserted in the local
246 // cache until the upload is successful get parent from path
247 parentPath
= file
.getRemotePath().substring(0,
248 file
.getRemotePath().lastIndexOf(file
.getFileName()));
249 if (getStorageManager().getFileByPath(parentPath
) == null
)
250 file
= null
; // not able to know the directory where the file is uploading
252 file
= getStorageManager().getFileByPath(file
.getRemotePath());
253 // currentDir = null if not in the current Account
257 // fall back to root folder
258 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
261 setNavigationListWithFolder(file
);
263 if (!stateWasRecovered
) {
264 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
265 initFragmentsWithFile();
266 if (file
.isFolder()) {
267 startSyncFolderOperation(file
, false
);
271 updateFragmentsVisibility(!file
.isFolder());
272 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
278 private void setNavigationListWithFolder(OCFile file
) {
279 mDirectories
.clear();
280 OCFile fileIt
= file
;
282 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
283 if (fileIt
.isFolder()) {
284 mDirectories
.add(fileIt
.getFileName());
286 // get parent from path
287 parentPath
= fileIt
.getRemotePath().substring(0,
288 fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
289 fileIt
= getStorageManager().getFileByPath(parentPath
);
291 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
295 private void createMinFragments() {
296 OCFileListFragment listOfFiles
= new OCFileListFragment();
297 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
298 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
299 transaction
.commit();
302 private void initFragmentsWithFile() {
303 if (getAccount() != null
&& getFile() != null
) {
305 OCFileListFragment listOfFiles
= getListOfFilesFragment();
306 if (listOfFiles
!= null
) {
307 listOfFiles
.listDirectory(getCurrentDir());
308 // TODO Enable when "On Device" is recovered
309 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
311 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
315 OCFile file
= getFile();
316 Fragment secondFragment
= chooseInitialSecondFragment(file
);
317 if (secondFragment
!= null
) {
318 setSecondFragment(secondFragment
);
319 updateFragmentsVisibility(true
);
320 updateNavigationElementsInActionBar(file
);
323 cleanSecondFragment();
327 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
328 if (getAccount() == null
) {
329 Log_OC
.wtf(TAG
, "\t account is NULL");
331 if (getFile() == null
) {
332 Log_OC
.wtf(TAG
, "\t file is NULL");
337 private Fragment
chooseInitialSecondFragment(OCFile file
) {
338 Fragment secondFragment
= null
;
339 if (file
!= null
&& !file
.isFolder()) {
340 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
341 && file
.getLastSyncDateForProperties() > 0 // temporal fix
343 int startPlaybackPosition
=
344 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
346 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
347 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
348 startPlaybackPosition
, autoplay
);
351 secondFragment
= new FileDetailFragment(file
, getAccount());
354 return secondFragment
;
359 * Replaces the second fragment managed by the activity with the received as
362 * Assumes never will be more than two fragments managed at the same time.
364 * @param fragment New second Fragment to set.
366 private void setSecondFragment(Fragment fragment
) {
367 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
368 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
369 transaction
.commit();
373 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
382 } else if (existsSecondFragment
) {
383 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
384 mLeftFragmentContainer
.setVisibility(View
.GONE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
391 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
392 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
394 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
395 mRightFragmentContainer
.setVisibility(View
.GONE
);
401 private OCFileListFragment
getListOfFilesFragment() {
402 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
403 FileDisplayActivity
.TAG_LIST_OF_FILES
);
404 if (listOfFiles
!= null
) {
405 return (OCFileListFragment
)listOfFiles
;
407 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
411 public FileFragment
getSecondFragment() {
412 Fragment second
= getSupportFragmentManager().findFragmentByTag(
413 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
414 if (second
!= null
) {
415 return (FileFragment
)second
;
420 protected void cleanSecondFragment() {
421 Fragment second
= getSecondFragment();
422 if (second
!= null
) {
423 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
427 updateFragmentsVisibility(false
);
428 updateNavigationElementsInActionBar(null
);
431 protected void refreshListOfFilesFragment() {
432 OCFileListFragment fileListFragment
= getListOfFilesFragment();
433 if (fileListFragment
!= null
) {
434 fileListFragment
.listDirectory();
435 // TODO Enable when "On Device" is recovered ?
436 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
440 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
442 FileFragment secondFragment
= getSecondFragment();
443 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
444 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
445 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
446 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
447 OCFile fileInFragment
= detailsFragment
.getFile();
448 if (fileInFragment
!= null
&&
449 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
450 // the user browsed to other file ; forget the automatic preview
451 mWaitingToPreview
= null
;
453 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
454 // grant that the right panel updates the progress bar
455 detailsFragment
.listenForTransferProgress();
456 detailsFragment
.updateFileDetails(true
, false
);
458 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
459 // update the right panel
460 boolean detailsFragmentChanged
= false
;
463 mWaitingToPreview
= getStorageManager().getFileById(
464 mWaitingToPreview
.getFileId()); // update the file from database,
465 // for the local storage path
466 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
467 startMediaPreview(mWaitingToPreview
, 0, true
);
468 detailsFragmentChanged
= true
;
470 getFileOperationsHelper().openFile(mWaitingToPreview
);
473 mWaitingToPreview
= null
;
475 if (!detailsFragmentChanged
) {
476 detailsFragment
.updateFileDetails(false
, (success
));
483 public boolean onPrepareOptionsMenu(Menu menu
) {
484 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
485 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
486 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
487 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
488 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
490 return super.onPrepareOptionsMenu(menu
);
494 public boolean onCreateOptionsMenu(Menu menu
) {
495 MenuInflater inflater
= getMenuInflater();
496 inflater
.inflate(R
.menu
.main_menu
, menu
);
502 public boolean onOptionsItemSelected(MenuItem item
) {
503 boolean retval
= true
;
504 switch (item
.getItemId()) {
505 case R
.id
.action_create_dir
: {
506 CreateFolderDialogFragment dialog
=
507 CreateFolderDialogFragment
.newInstance(getCurrentDir());
508 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
511 case R
.id
.action_sync_account
: {
512 startSynchronization();
515 case R
.id
.action_upload
: {
516 UploadSourceDialogFragment dialog
=
517 UploadSourceDialogFragment
.newInstance(getAccount());
518 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
522 case android
.R
.id
.home
: {
523 FileFragment second
= getSecondFragment();
524 OCFile currentDir
= getCurrentDir();
525 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
526 (second
!= null
&& second
.getFile() != null
)) {
530 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
531 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
533 mDrawerLayout
.openDrawer(GravityCompat
.START
);
538 case R
.id
.action_sort
: {
539 SharedPreferences appPreferences
= PreferenceManager
540 .getDefaultSharedPreferences(this);
542 // Read sorting order, default to sort by name ascending
543 Integer sortOrder
= appPreferences
544 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
546 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
547 builder
.setTitle(R
.string
.actionbar_sort_title
)
548 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
549 new DialogInterface
.OnClickListener() {
550 public void onClick(DialogInterface dialog
, int which
) {
563 builder
.create().show();
567 retval
= super.onOptionsItemSelected(item
);
572 private void startSynchronization() {
573 Log_OC
.d(TAG
, "Got to start sync");
574 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
575 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
576 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
577 // cancel the current synchronizations of any ownCloud account
578 Bundle bundle
= new Bundle();
579 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
580 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
581 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
582 MainApp
.getAuthority());
583 ContentResolver
.requestSync(
585 MainApp
.getAuthority(), bundle
);
587 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
588 MainApp
.getAuthority() + " with new API");
589 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
590 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
591 builder
.setExpedited(true
);
592 builder
.setManual(true
);
595 // Fix bug in Android Lollipop when you click on refresh the whole account
596 Bundle extras
= new Bundle();
597 builder
.setExtras(extras
);
599 SyncRequest request
= builder
.build();
600 ContentResolver
.requestSync(request
);
606 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
607 if (itemPosition
!= 0) {
608 String targetPath
= "";
609 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
610 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
612 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
613 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
614 if (targetFolder
!= null
) {
615 browseTo(targetFolder
);
618 // the next operation triggers a new call to this method, but it's necessary to
619 // ensure that the name exposed in the action bar is the current directory when the
620 // user selected it in the navigation list
621 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&&
623 getSupportActionBar().setSelectedNavigationItem(0);
629 * Called, when the user selected something for uploading
632 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
634 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
636 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
637 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
638 //getClipData is only supported on api level 16+, Jelly Bean
639 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
640 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
641 Intent intent
= new Intent();
642 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
643 requestSimpleUpload(intent
, resultCode
);
646 requestSimpleUpload(data
, resultCode
);
648 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
649 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
650 requestMultipleUpload(data
, resultCode
);
652 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
654 final Intent fData
= data
;
655 final int fResultCode
= resultCode
;
656 getHandler().postDelayed(
660 requestMoveOperation(fData
, fResultCode
);
663 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
667 super.onActivityResult(requestCode
, resultCode
, data
);
672 private void requestMultipleUpload(Intent data
, int resultCode
) {
673 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
674 if (filePaths
!= null
) {
675 String
[] remotePaths
= new String
[filePaths
.length
];
676 String remotePathBase
= "";
678 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
679 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
681 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
682 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
683 for (int j
= 0; j
< remotePaths
.length
; j
++) {
684 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
687 Intent i
= new Intent(this, FileUploader
.class);
688 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
689 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
690 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
691 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
692 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
693 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
697 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
698 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
706 private void requestSimpleUpload(Intent data
, int resultCode
) {
707 String filePath
= null
;
708 String mimeType
= null
;
710 Uri selectedImageUri
= data
.getData();
713 mimeType
= getContentResolver().getType(selectedImageUri
);
715 String fileManagerString
= selectedImageUri
.getPath();
716 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
718 if (selectedImagePath
!= null
)
719 filePath
= selectedImagePath
;
721 filePath
= fileManagerString
;
723 } catch (Exception e
) {
724 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
725 "Intent.ACTION_GET_CONTENT", e
);
728 if (filePath
== null
) {
729 Log_OC
.e(TAG
, "Couldn't resolve path to file");
730 Toast t
= Toast
.makeText(
731 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
739 Intent i
= new Intent(this, FileUploader
.class);
740 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
741 OCFile currentDir
= getCurrentDir();
742 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
744 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
745 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
747 if (cursor
!= null
&& cursor
.moveToFirst()) {
748 String displayName
= cursor
.getString(cursor
.getColumnIndex(
749 OpenableColumns
.DISPLAY_NAME
));
750 Log_OC
.v(TAG
, "Display Name: " + displayName
);
752 displayName
.replace(File
.separatorChar
, '_');
753 displayName
.replace(File
.pathSeparatorChar
, '_');
754 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
757 // and what happens in case of error?; wrong target name for the upload
763 remotePath
+= new File(filePath
).getName();
766 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
767 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
768 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
769 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
770 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
771 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
776 * Request the operation for moving the file/folder from one path to another
778 * @param data Intent received
779 * @param resultCode Result code received
781 private void requestMoveOperation(Intent data
, int resultCode
) {
782 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
783 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
784 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
788 public void onBackPressed() {
789 OCFileListFragment listOfFiles
= getListOfFilesFragment();
790 if (mDualPane
|| getSecondFragment() == null
) {
791 if (listOfFiles
!= null
) { // should never be null, indeed
792 if (mDirectories
.getCount() <= 1) {
796 int levelsUp
= listOfFiles
.onBrowseUp();
797 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
802 if (listOfFiles
!= null
) { // should never be null, indeed
803 setFile(listOfFiles
.getCurrentFile());
805 cleanSecondFragment();
810 protected void onSaveInstanceState(Bundle outState
) {
811 // responsibility of restore is preferred in onCreate() before than in
812 // onRestoreInstanceState when there are Fragments involved
813 Log_OC
.v(TAG
, "onSaveInstanceState() start");
814 super.onSaveInstanceState(outState
);
815 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
816 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
817 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
818 // mRefreshSharesInProgress);
819 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
821 Log_OC
.v(TAG
, "onSaveInstanceState() end");
827 protected void onResume() {
828 Log_OC
.v(TAG
, "onResume() start");
831 // refresh Navigation Drawer account list
832 mNavigationDrawerAdapter
.updateAccountList();
834 // refresh list of files
835 refreshListOfFilesFragment();
837 // Listen for sync messages
838 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
839 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
840 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
841 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
842 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
843 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
844 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
845 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
846 // syncIntentFilter);
848 // Listen for upload messages
849 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
850 mUploadFinishReceiver
= new UploadFinishReceiver();
851 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
853 // Listen for download messages
854 IntentFilter downloadIntentFilter
= new IntentFilter(
855 FileDownloader
.getDownloadAddedMessage());
856 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
857 mDownloadFinishReceiver
= new DownloadFinishReceiver();
858 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
860 Log_OC
.v(TAG
, "onResume() end");
865 protected void onPause() {
866 Log_OC
.v(TAG
, "onPause() start");
867 if (mSyncBroadcastReceiver
!= null
) {
868 unregisterReceiver(mSyncBroadcastReceiver
);
869 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
870 mSyncBroadcastReceiver
= null
;
872 if (mUploadFinishReceiver
!= null
) {
873 unregisterReceiver(mUploadFinishReceiver
);
874 mUploadFinishReceiver
= null
;
876 if (mDownloadFinishReceiver
!= null
) {
877 unregisterReceiver(mDownloadFinishReceiver
);
878 mDownloadFinishReceiver
= null
;
882 Log_OC
.v(TAG
, "onPause() end");
886 * Pushes a directory to the drop down list
887 * @param directory to push
888 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
890 public void pushDirname(OCFile directory
) {
891 if(!directory
.isFolder()){
892 throw new IllegalArgumentException("Only directories may be pushed!");
894 mDirectories
.insert(directory
.getFileName(), 0);
899 * Pops a directory name from the drop down list
900 * @return True, unless the stack is empty
902 public boolean popDirname() {
903 mDirectories
.remove(mDirectories
.getItem(0));
904 return !mDirectories
.isEmpty();
907 // Custom array adapter to override text colors
908 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
910 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
914 public View
getView(int position
, View convertView
, ViewGroup parent
) {
915 View v
= super.getView(position
, convertView
, parent
);
917 ((TextView
) v
).setTextColor(getResources().getColorStateList(
918 android
.R
.color
.white
));
920 fixRoot((TextView
) v
);
924 public View
getDropDownView(int position
, View convertView
,
926 View v
= super.getDropDownView(position
, convertView
, parent
);
928 ((TextView
) v
).setTextColor(getResources().getColorStateList(
929 android
.R
.color
.white
));
931 fixRoot((TextView
) v
);
935 private void fixRoot(TextView v
) {
936 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
937 v
.setText(R
.string
.default_display_name_for_root_folder
);
943 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
946 * {@link BroadcastReceiver} to enable syncing feedback in UI
949 public void onReceive(Context context
, Intent intent
) {
951 String event
= intent
.getAction();
952 Log_OC
.d(TAG
, "Received broadcast " + event
);
953 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
954 String synchFolderRemotePath
=
955 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
956 RemoteOperationResult synchResult
=
957 (RemoteOperationResult
)intent
.getSerializableExtra(
958 FileSyncAdapter
.EXTRA_RESULT
);
959 boolean sameAccount
= (getAccount() != null
&&
960 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
964 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
965 mSyncInProgress
= true
;
968 OCFile currentFile
= (getFile() == null
) ? null
:
969 getStorageManager().getFileByPath(getFile().getRemotePath());
970 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
971 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
973 if (currentDir
== null
) {
974 // current folder was removed from the server
975 Toast
.makeText( FileDisplayActivity
.this,
978 sync_current_folder_was_removed
),
979 mDirectories
.getItem(0)),
985 if (currentFile
== null
&& !getFile().isFolder()) {
986 // currently selected file was removed in the server, and now we
988 cleanSecondFragment();
989 currentFile
= currentDir
;
992 if (synchFolderRemotePath
!= null
&&
993 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
994 OCFileListFragment fileListFragment
= getListOfFilesFragment();
995 if (fileListFragment
!= null
) {
996 fileListFragment
.listDirectory();
997 // TODO Enable when "On Device" is recovered ?
998 // fileListFragment.listDirectory(currentDir,
999 // MainApp.getOnlyOnDevice());
1002 setFile(currentFile
);
1005 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
1006 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1009 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1011 /// TODO refactor and make common
1012 synchResult
!= null
&& !synchResult
.isSuccess() &&
1013 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1014 synchResult
.isIdPRedirection() ||
1015 (synchResult
.isException() && synchResult
.getException()
1016 instanceof AuthenticatorException
))) {
1020 OwnCloudClient client
;
1021 OwnCloudAccount ocAccount
=
1022 new OwnCloudAccount(getAccount(), context
);
1023 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1024 removeClientFor(ocAccount
));
1026 if (client
!= null
) {
1027 OwnCloudCredentials cred
= client
.getCredentials();
1029 AccountManager am
= AccountManager
.get(context
);
1030 if (cred
.authTokenExpires()) {
1031 am
.invalidateAuthToken(
1036 am
.clearPassword(getAccount());
1040 requestCredentialsUpdate();
1042 } catch (AccountNotFoundException e
) {
1043 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1048 removeStickyBroadcast(intent
);
1049 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1050 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1051 /*|| mRefreshSharesInProgress*/);
1053 setBackgroundText();
1057 if (synchResult
!= null
) {
1058 if (synchResult
.getCode().equals(
1059 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1060 mLastSslUntrustedServerResult
= synchResult
;
1063 } catch (RuntimeException e
) {
1064 // avoid app crashes after changing the serial id of RemoteOperationResult
1065 // in owncloud library with broadcast notifications pending to process
1066 removeStickyBroadcast(intent
);
1072 * Show a text message on screen view for notifying user if content is
1073 * loading or folder is empty
1075 private void setBackgroundText() {
1076 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1077 if (ocFileListFragment
!= null
) {
1078 int message
= R
.string
.file_list_loading
;
1079 if (!mSyncInProgress
) {
1080 // In case file list is empty
1081 message
= R
.string
.file_list_empty
;
1083 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1085 Log_OC
.e(TAG
, "OCFileListFragment is null");
1090 * Once the file upload has finished -> update view
1092 private class UploadFinishReceiver
extends BroadcastReceiver
{
1094 * Once the file upload has finished -> update view
1095 * @author David A. Velasco
1096 * {@link BroadcastReceiver} to enable upload feedback in UI
1099 public void onReceive(Context context
, Intent intent
) {
1101 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1102 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1103 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1104 OCFile currentDir
= getCurrentDir();
1105 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1106 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1108 if (sameAccount
&& isDescendant
) {
1109 refreshListOfFilesFragment();
1112 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1114 boolean renamedInUpload
= getFile().getRemotePath().
1115 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1116 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1118 FileFragment details
= getSecondFragment();
1119 boolean detailFragmentIsShown
= (details
!= null
&&
1120 details
instanceof FileDetailFragment
);
1122 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1123 if (uploadWasFine
) {
1124 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1126 if (renamedInUpload
) {
1127 String newName
= (new File(uploadedRemotePath
)).getName();
1128 Toast msg
= Toast
.makeText(
1131 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1136 if (uploadWasFine
|| getFile().fileExists()) {
1137 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1139 cleanSecondFragment();
1142 // Force the preview if the file is an image
1143 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1144 startImagePreview(getFile());
1145 } // TODO what about other kind of previews?
1149 if (intent
!= null
) {
1150 removeStickyBroadcast(intent
);
1160 * Class waiting for broadcast events from the {@link FileDownloader} service.
1162 * Updates the UI when a download is started or finished, provided that it is relevant for the
1165 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1167 //int refreshCounter = 0;
1169 public void onReceive(Context context
, Intent intent
) {
1171 boolean sameAccount
= isSameAccount(context
, intent
);
1172 String downloadedRemotePath
=
1173 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1174 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1176 if (sameAccount
&& isDescendant
) {
1177 String linkedToRemotePath
=
1178 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1179 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1180 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1181 refreshListOfFilesFragment();
1183 refreshSecondFragment(
1185 downloadedRemotePath
,
1186 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1190 if (mWaitingToSend
!= null
) {
1192 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1193 if (mWaitingToSend
.isDown()) {
1194 sendDownloadedFile();
1199 if (intent
!= null
) {
1200 removeStickyBroadcast(intent
);
1205 private boolean isDescendant(String downloadedRemotePath
) {
1206 OCFile currentDir
= getCurrentDir();
1208 currentDir
!= null
&&
1209 downloadedRemotePath
!= null
&&
1210 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1214 private boolean isAscendant(String linkedToRemotePath
) {
1215 OCFile currentDir
= getCurrentDir();
1217 currentDir
!= null
&&
1218 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1222 private boolean isSameAccount(Context context
, Intent intent
) {
1223 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1224 return (accountName
!= null
&& getAccount() != null
&&
1225 accountName
.equals(getAccount().name
));
1230 public void browseToRoot() {
1231 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1232 if (listOfFiles
!= null
) { // should never be null, indeed
1233 while (mDirectories
.getCount() > 1) {
1236 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1237 listOfFiles
.listDirectory(root
);
1238 // TODO Enable when "On Device" is recovered ?
1239 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1240 setFile(listOfFiles
.getCurrentFile());
1241 startSyncFolderOperation(root
, false
);
1243 cleanSecondFragment();
1247 public void browseTo(OCFile folder
) {
1248 if (folder
== null
|| !folder
.isFolder()) {
1249 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1251 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1252 if (listOfFiles
!= null
) {
1253 setNavigationListWithFolder(folder
);
1254 listOfFiles
.listDirectory(folder
);
1255 // TODO Enable when "On Device" is recovered ?
1256 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1257 setFile(listOfFiles
.getCurrentFile());
1258 startSyncFolderOperation(folder
, false
);
1260 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1262 cleanSecondFragment();
1269 * Updates action bar and second fragment, if in dual pane mode.
1272 public void onBrowsedDownTo(OCFile directory
) {
1273 pushDirname(directory
);
1274 cleanSecondFragment();
1277 startSyncFolderOperation(directory
, false
);
1282 * Shows the information of the {@link OCFile} received as a
1283 * parameter in the second fragment.
1285 * @param file {@link OCFile} whose details will be shown
1288 public void showDetails(OCFile file
) {
1289 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1290 setSecondFragment(detailFragment
);
1291 updateFragmentsVisibility(true
);
1292 updateNavigationElementsInActionBar(file
);
1300 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1301 ActionBar actionBar
= getSupportActionBar();
1303 // For adding content description tag to a title field in the action bar
1304 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1306 if (chosenFile
== null
|| mDualPane
) {
1307 // only list of files - set for browsing through folders
1308 OCFile currentDir
= getCurrentDir();
1309 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1310 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1311 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1312 actionBar
.setDisplayHomeAsUpEnabled(true
);
1313 actionBar
.setDisplayShowTitleEnabled(true
);
1315 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1316 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1317 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1318 actionBarTitleView
.setContentDescription(
1319 getString(R
.string
.default_display_name_for_root_folder
));
1322 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
:
1323 ActionBar
.NAVIGATION_MODE_LIST
);
1324 actionBar
.setListNavigationCallbacks(mDirectories
, this);
1325 // assuming mDirectories is updated
1328 actionBar
.setDisplayHomeAsUpEnabled(true
);
1329 actionBar
.setDisplayShowTitleEnabled(true
);
1330 actionBar
.setTitle(chosenFile
.getFileName());
1331 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1332 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1333 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1334 getWindow().getDecorView().findViewById(actionBarTitleId
).
1335 setContentDescription(chosenFile
.getFileName());
1342 protected ServiceConnection
newTransferenceServiceConnection() {
1343 return new ListServiceConnection();
1346 /** Defines callbacks for service binding, passed to bindService() */
1347 private class ListServiceConnection
implements ServiceConnection
{
1350 public void onServiceConnected(ComponentName component
, IBinder service
) {
1351 if (component
.equals(new ComponentName(
1352 FileDisplayActivity
.this, FileDownloader
.class))) {
1353 Log_OC
.d(TAG
, "Download service connected");
1354 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1355 if (mWaitingToPreview
!= null
)
1356 if (getStorageManager() != null
) {
1359 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1360 if (!mWaitingToPreview
.isDown()) {
1361 requestForDownload();
1365 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1366 FileUploader
.class))) {
1367 Log_OC
.d(TAG
, "Upload service connected");
1368 mUploaderBinder
= (FileUploaderBinder
) service
;
1372 // a new chance to get the mDownloadBinder through
1373 // getFileDownloadBinder() - THIS IS A MESS
1374 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1375 if (listOfFiles
!= null
) {
1376 listOfFiles
.listDirectory();
1377 // TODO Enable when "On Device" is recovered ?
1378 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1380 FileFragment secondFragment
= getSecondFragment();
1381 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1382 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1383 detailFragment
.listenForTransferProgress();
1384 detailFragment
.updateFileDetails(false
, false
);
1389 public void onServiceDisconnected(ComponentName component
) {
1390 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1391 FileDownloader
.class))) {
1392 Log_OC
.d(TAG
, "Download service disconnected");
1393 mDownloaderBinder
= null
;
1394 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1395 FileUploader
.class))) {
1396 Log_OC
.d(TAG
, "Upload service disconnected");
1397 mUploaderBinder
= null
;
1403 public void onSavedCertificate() {
1404 startSyncFolderOperation(getCurrentDir(), false
);
1409 public void onFailedSavingCertificate() {
1410 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1411 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1413 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1417 public void onCancelCertificate() {
1422 * Updates the view associated to the activity after the finish of some operation over files
1423 * in the current account.
1425 * @param operation Removal operation performed.
1426 * @param result Result of the removal.
1429 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1430 super.onRemoteOperationFinish(operation
, result
);
1432 if (operation
instanceof RemoveFileOperation
) {
1433 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1435 } else if (operation
instanceof RenameFileOperation
) {
1436 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1438 } else if (operation
instanceof SynchronizeFileOperation
) {
1439 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1441 } else if (operation
instanceof CreateFolderOperation
) {
1442 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1444 } else if (operation
instanceof CreateShareOperation
) {
1445 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1447 } else if (operation
instanceof UnshareLinkOperation
) {
1448 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1450 } else if (operation
instanceof MoveFileOperation
) {
1451 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1457 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1458 RemoteOperationResult result
) {
1459 if (result
.isSuccess()) {
1460 refreshShowDetails();
1461 refreshListOfFilesFragment();
1466 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1467 RemoteOperationResult result
) {
1468 if (result
.isSuccess()) {
1469 refreshShowDetails();
1470 refreshListOfFilesFragment();
1472 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1473 cleanSecondFragment();
1474 refreshListOfFilesFragment();
1478 private void refreshShowDetails() {
1479 FileFragment details
= getSecondFragment();
1480 if (details
!= null
) {
1481 OCFile file
= details
.getFile();
1483 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1484 if (details
instanceof PreviewMediaFragment
) {
1485 // Refresh OCFile of the fragment
1486 ((PreviewMediaFragment
) details
).updateFile(file
);
1491 invalidateOptionsMenu();
1496 * Updates the view associated to the activity after the finish of an operation trying to
1499 * @param operation Removal operation performed.
1500 * @param result Result of the removal.
1502 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1503 RemoteOperationResult result
) {
1504 dismissLoadingDialog();
1506 Toast msg
= Toast
.makeText(this,
1507 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1511 if (result
.isSuccess()) {
1512 OCFile removedFile
= operation
.getFile();
1513 FileFragment second
= getSecondFragment();
1514 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1515 if (second
instanceof PreviewMediaFragment
) {
1516 ((PreviewMediaFragment
)second
).stopPreview(true
);
1518 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1519 cleanSecondFragment();
1521 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1522 refreshListOfFilesFragment();
1524 invalidateOptionsMenu();
1526 if (result
.isSslRecoverableException()) {
1527 mLastSslUntrustedServerResult
= result
;
1528 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1535 * Updates the view associated to the activity after the finish of an operation trying to move a
1538 * @param operation Move operation performed.
1539 * @param result Result of the move operation.
1541 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1542 RemoteOperationResult result
) {
1543 if (result
.isSuccess()) {
1544 dismissLoadingDialog();
1545 refreshListOfFilesFragment();
1547 dismissLoadingDialog();
1549 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1550 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1554 } catch (NotFoundException e
) {
1555 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1562 * Updates the view associated to the activity after the finish of an operation trying to rename
1565 * @param operation Renaming operation performed.
1566 * @param result Result of the renaming.
1568 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1569 RemoteOperationResult result
) {
1570 dismissLoadingDialog();
1571 OCFile renamedFile
= operation
.getFile();
1572 if (result
.isSuccess()) {
1573 FileFragment details
= getSecondFragment();
1574 if (details
!= null
) {
1575 if (details
instanceof FileDetailFragment
&&
1576 renamedFile
.equals(details
.getFile()) ) {
1577 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1578 showDetails(renamedFile
);
1580 } else if (details
instanceof PreviewMediaFragment
&&
1581 renamedFile
.equals(details
.getFile())) {
1582 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1583 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1584 int position
= ((PreviewMediaFragment
)details
).getPosition();
1585 startMediaPreview(renamedFile
, position
, true
);
1587 getFileOperationsHelper().openFile(renamedFile
);
1592 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1593 refreshListOfFilesFragment();
1597 Toast msg
= Toast
.makeText(this,
1598 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1602 if (result
.isSslRecoverableException()) {
1603 mLastSslUntrustedServerResult
= result
;
1604 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1609 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1610 RemoteOperationResult result
) {
1611 dismissLoadingDialog();
1612 OCFile syncedFile
= operation
.getLocalFile();
1613 if (!result
.isSuccess()) {
1614 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1615 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1616 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1617 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1623 if (operation
.transferWasRequested()) {
1624 onTransferStateChanged(syncedFile
, true
, true
);
1627 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1628 operation
, getResources()), Toast
.LENGTH_LONG
);
1635 * Updates the view associated to the activity after the finish of an operation trying create a
1638 * @param operation Creation operation performed.
1639 * @param result Result of the creation.
1641 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1642 RemoteOperationResult result
) {
1643 if (result
.isSuccess()) {
1644 dismissLoadingDialog();
1645 refreshListOfFilesFragment();
1647 dismissLoadingDialog();
1649 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1650 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1654 } catch (NotFoundException e
) {
1655 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1665 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1666 refreshListOfFilesFragment();
1667 FileFragment details
= getSecondFragment();
1668 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1669 file
.equals(details
.getFile()) ) {
1670 if (downloading
|| uploading
) {
1671 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1673 if (!file
.fileExists()) {
1674 cleanSecondFragment();
1676 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1684 private void requestForDownload() {
1685 Account account
= getAccount();
1686 //if (!mWaitingToPreview.isDownloading()) {
1687 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1688 Intent i
= new Intent(this, FileDownloader
.class);
1689 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1690 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1696 private OCFile
getCurrentDir() {
1697 OCFile file
= getFile();
1699 if (file
.isFolder()) {
1701 } else if (getStorageManager() != null
) {
1702 String parentPath
= file
.getRemotePath().substring(0,
1703 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1704 return getStorageManager().getFileByPath(parentPath
);
1710 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1711 long currentSyncTime
= System
.currentTimeMillis();
1713 mSyncInProgress
= true
;
1715 // perform folder synchronization
1716 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1719 getFileOperationsHelper().isSharedSupported(),
1721 getStorageManager(),
1723 getApplicationContext()
1725 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1727 setSupportProgressBarIndeterminateVisibility(true
);
1729 setBackgroundText();
1733 * Show untrusted cert dialog
1735 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1736 // Show a dialog with the certificate info
1737 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1738 (CertificateCombinedException
) result
.getException());
1739 FragmentManager fm
= getSupportFragmentManager();
1740 FragmentTransaction ft
= fm
.beginTransaction();
1741 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1744 private void requestForDownload(OCFile file
) {
1745 Account account
= getAccount();
1746 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1747 Intent i
= new Intent(this, FileDownloader
.class);
1748 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1749 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1754 private void sendDownloadedFile(){
1755 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1756 mWaitingToSend
= null
;
1761 * Requests the download of the received {@link OCFile} , updates the UI
1762 * to monitor the download progress and prepares the activity to send the file
1763 * when the download finishes.
1765 * @param file {@link OCFile} to download and preview.
1767 public void startDownloadForSending(OCFile file
) {
1768 mWaitingToSend
= file
;
1769 requestForDownload(mWaitingToSend
);
1770 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1771 updateFragmentsVisibility(hasSecondFragment
);
1775 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1777 * @param file Image {@link OCFile} to show.
1779 public void startImagePreview(OCFile file
) {
1780 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1781 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1782 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1783 startActivity(showDetailsIntent
);
1788 * Stars the preview of an already down media {@link OCFile}.
1790 * @param file Media {@link OCFile} to preview.
1791 * @param startPlaybackPosition Media position where the playback will be started,
1793 * @param autoplay When 'true', the playback will start without user
1796 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1797 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1799 setSecondFragment(mediaFragment
);
1800 updateFragmentsVisibility(true
);
1801 updateNavigationElementsInActionBar(file
);
1806 * Requests the download of the received {@link OCFile} , updates the UI
1807 * to monitor the download progress and prepares the activity to preview
1808 * or open the file when the download finishes.
1810 * @param file {@link OCFile} to download and preview.
1812 public void startDownloadForPreview(OCFile file
) {
1813 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1814 setSecondFragment(detailFragment
);
1815 mWaitingToPreview
= file
;
1816 requestForDownload();
1817 updateFragmentsVisibility(true
);
1818 updateNavigationElementsInActionBar(file
);
1823 public void cancelTransference(OCFile file
) {
1824 getFileOperationsHelper().cancelTransference(file
);
1825 if (mWaitingToPreview
!= null
&&
1826 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1827 mWaitingToPreview
= null
;
1829 if (mWaitingToSend
!= null
&&
1830 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1831 mWaitingToSend
= null
;
1833 onTransferStateChanged(file
, false
, false
);
1837 public void onRefresh(boolean ignoreETag
) {
1838 refreshList(ignoreETag
);
1842 public void onRefresh() {
1846 private void refreshList(boolean ignoreETag
) {
1847 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1848 if (listOfFiles
!= null
) {
1849 OCFile folder
= listOfFiles
.getCurrentFile();
1850 if (folder
!= null
) {
1851 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1852 listDirectory(mFile);*/
1853 startSyncFolderOperation(folder
, ignoreETag
);
1858 private void sortByDate(boolean ascending
){
1859 getListOfFilesFragment().sortByDate(ascending
);
1862 private void sortBySize(boolean ascending
){
1863 getListOfFilesFragment().sortBySize(ascending
);
1866 private void sortByName(boolean ascending
){
1867 getListOfFilesFragment().sortByName(ascending
);
1870 public void allFilesOption() {