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 updateActionBarTitle();
806 cleanSecondFragment();
811 protected void onSaveInstanceState(Bundle outState
) {
812 // responsibility of restore is preferred in onCreate() before than in
813 // onRestoreInstanceState when there are Fragments involved
814 Log_OC
.v(TAG
, "onSaveInstanceState() start");
815 super.onSaveInstanceState(outState
);
816 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
817 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
818 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
819 // mRefreshSharesInProgress);
820 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
822 Log_OC
.v(TAG
, "onSaveInstanceState() end");
828 protected void onResume() {
829 Log_OC
.v(TAG
, "onResume() start");
832 // refresh Navigation Drawer account list
833 mNavigationDrawerAdapter
.updateAccountList();
835 // refresh list of files
836 refreshListOfFilesFragment();
838 // Listen for sync messages
839 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
840 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
841 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
842 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
843 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
844 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
845 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
846 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
847 // syncIntentFilter);
849 // Listen for upload messages
850 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
851 mUploadFinishReceiver
= new UploadFinishReceiver();
852 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
854 // Listen for download messages
855 IntentFilter downloadIntentFilter
= new IntentFilter(
856 FileDownloader
.getDownloadAddedMessage());
857 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
858 mDownloadFinishReceiver
= new DownloadFinishReceiver();
859 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
861 Log_OC
.v(TAG
, "onResume() end");
866 protected void onPause() {
867 Log_OC
.v(TAG
, "onPause() start");
868 if (mSyncBroadcastReceiver
!= null
) {
869 unregisterReceiver(mSyncBroadcastReceiver
);
870 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
871 mSyncBroadcastReceiver
= null
;
873 if (mUploadFinishReceiver
!= null
) {
874 unregisterReceiver(mUploadFinishReceiver
);
875 mUploadFinishReceiver
= null
;
877 if (mDownloadFinishReceiver
!= null
) {
878 unregisterReceiver(mDownloadFinishReceiver
);
879 mDownloadFinishReceiver
= null
;
883 Log_OC
.v(TAG
, "onPause() end");
887 * Pushes a directory to the drop down list
888 * @param directory to push
889 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
891 public void pushDirname(OCFile directory
) {
892 if(!directory
.isFolder()){
893 throw new IllegalArgumentException("Only directories may be pushed!");
895 mDirectories
.insert(directory
.getFileName(), 0);
900 * Pops a directory name from the drop down list
901 * @return True, unless the stack is empty
903 public boolean popDirname() {
904 mDirectories
.remove(mDirectories
.getItem(0));
905 return !mDirectories
.isEmpty();
908 // Custom array adapter to override text colors
909 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
911 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
915 public View
getView(int position
, View convertView
, ViewGroup parent
) {
916 View v
= super.getView(position
, convertView
, parent
);
918 ((TextView
) v
).setTextColor(getResources().getColorStateList(
919 android
.R
.color
.white
));
921 fixRoot((TextView
) v
);
925 public View
getDropDownView(int position
, View convertView
,
927 View v
= super.getDropDownView(position
, convertView
, parent
);
929 ((TextView
) v
).setTextColor(getResources().getColorStateList(
930 android
.R
.color
.white
));
932 fixRoot((TextView
) v
);
936 private void fixRoot(TextView v
) {
937 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
938 v
.setText(R
.string
.default_display_name_for_root_folder
);
944 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
947 * {@link BroadcastReceiver} to enable syncing feedback in UI
950 public void onReceive(Context context
, Intent intent
) {
952 String event
= intent
.getAction();
953 Log_OC
.d(TAG
, "Received broadcast " + event
);
954 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
955 String synchFolderRemotePath
=
956 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
957 RemoteOperationResult synchResult
=
958 (RemoteOperationResult
)intent
.getSerializableExtra(
959 FileSyncAdapter
.EXTRA_RESULT
);
960 boolean sameAccount
= (getAccount() != null
&&
961 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
965 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
966 mSyncInProgress
= true
;
969 OCFile currentFile
= (getFile() == null
) ? null
:
970 getStorageManager().getFileByPath(getFile().getRemotePath());
971 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
972 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
974 if (currentDir
== null
) {
975 // current folder was removed from the server
976 Toast
.makeText( FileDisplayActivity
.this,
979 sync_current_folder_was_removed
),
980 mDirectories
.getItem(0)),
986 if (currentFile
== null
&& !getFile().isFolder()) {
987 // currently selected file was removed in the server, and now we
989 cleanSecondFragment();
990 currentFile
= currentDir
;
993 if (synchFolderRemotePath
!= null
&&
994 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
995 OCFileListFragment fileListFragment
= getListOfFilesFragment();
996 if (fileListFragment
!= null
) {
997 fileListFragment
.listDirectory();
998 // TODO Enable when "On Device" is recovered ?
999 // fileListFragment.listDirectory(currentDir,
1000 // MainApp.getOnlyOnDevice());
1003 setFile(currentFile
);
1006 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
1007 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1010 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1012 /// TODO refactor and make common
1013 synchResult
!= null
&& !synchResult
.isSuccess() &&
1014 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1015 synchResult
.isIdPRedirection() ||
1016 (synchResult
.isException() && synchResult
.getException()
1017 instanceof AuthenticatorException
))) {
1021 OwnCloudClient client
;
1022 OwnCloudAccount ocAccount
=
1023 new OwnCloudAccount(getAccount(), context
);
1024 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1025 removeClientFor(ocAccount
));
1027 if (client
!= null
) {
1028 OwnCloudCredentials cred
= client
.getCredentials();
1030 AccountManager am
= AccountManager
.get(context
);
1031 if (cred
.authTokenExpires()) {
1032 am
.invalidateAuthToken(
1037 am
.clearPassword(getAccount());
1041 requestCredentialsUpdate();
1043 } catch (AccountNotFoundException e
) {
1044 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1049 removeStickyBroadcast(intent
);
1050 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1051 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1052 /*|| mRefreshSharesInProgress*/);
1054 setBackgroundText();
1058 if (synchResult
!= null
) {
1059 if (synchResult
.getCode().equals(
1060 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1061 mLastSslUntrustedServerResult
= synchResult
;
1064 } catch (RuntimeException e
) {
1065 // avoid app crashes after changing the serial id of RemoteOperationResult
1066 // in owncloud library with broadcast notifications pending to process
1067 removeStickyBroadcast(intent
);
1073 * Show a text message on screen view for notifying user if content is
1074 * loading or folder is empty
1076 private void setBackgroundText() {
1077 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1078 if (ocFileListFragment
!= null
) {
1079 int message
= R
.string
.file_list_loading
;
1080 if (!mSyncInProgress
) {
1081 // In case file list is empty
1082 message
= R
.string
.file_list_empty
;
1084 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1086 Log_OC
.e(TAG
, "OCFileListFragment is null");
1091 * Once the file upload has finished -> update view
1093 private class UploadFinishReceiver
extends BroadcastReceiver
{
1095 * Once the file upload has finished -> update view
1096 * @author David A. Velasco
1097 * {@link BroadcastReceiver} to enable upload feedback in UI
1100 public void onReceive(Context context
, Intent intent
) {
1102 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1103 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1104 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1105 OCFile currentDir
= getCurrentDir();
1106 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1107 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1109 if (sameAccount
&& isDescendant
) {
1110 refreshListOfFilesFragment();
1113 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1115 boolean renamedInUpload
= getFile().getRemotePath().
1116 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1117 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1119 FileFragment details
= getSecondFragment();
1120 boolean detailFragmentIsShown
= (details
!= null
&&
1121 details
instanceof FileDetailFragment
);
1123 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1124 if (uploadWasFine
) {
1125 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1127 if (renamedInUpload
) {
1128 String newName
= (new File(uploadedRemotePath
)).getName();
1129 Toast msg
= Toast
.makeText(
1132 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1137 if (uploadWasFine
|| getFile().fileExists()) {
1138 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1140 cleanSecondFragment();
1143 // Force the preview if the file is an image
1144 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1145 startImagePreview(getFile());
1146 } // TODO what about other kind of previews?
1150 if (intent
!= null
) {
1151 removeStickyBroadcast(intent
);
1161 * Class waiting for broadcast events from the {@link FileDownloader} service.
1163 * Updates the UI when a download is started or finished, provided that it is relevant for the
1166 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1168 //int refreshCounter = 0;
1170 public void onReceive(Context context
, Intent intent
) {
1172 boolean sameAccount
= isSameAccount(context
, intent
);
1173 String downloadedRemotePath
=
1174 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1175 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1177 if (sameAccount
&& isDescendant
) {
1178 String linkedToRemotePath
=
1179 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1180 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1181 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1182 refreshListOfFilesFragment();
1184 refreshSecondFragment(
1186 downloadedRemotePath
,
1187 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1191 if (mWaitingToSend
!= null
) {
1193 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1194 if (mWaitingToSend
.isDown()) {
1195 sendDownloadedFile();
1200 if (intent
!= null
) {
1201 removeStickyBroadcast(intent
);
1206 private boolean isDescendant(String downloadedRemotePath
) {
1207 OCFile currentDir
= getCurrentDir();
1209 currentDir
!= null
&&
1210 downloadedRemotePath
!= null
&&
1211 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1215 private boolean isAscendant(String linkedToRemotePath
) {
1216 OCFile currentDir
= getCurrentDir();
1218 currentDir
!= null
&&
1219 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1223 private boolean isSameAccount(Context context
, Intent intent
) {
1224 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1225 return (accountName
!= null
&& getAccount() != null
&&
1226 accountName
.equals(getAccount().name
));
1231 public void browseToRoot() {
1232 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1233 if (listOfFiles
!= null
) { // should never be null, indeed
1234 while (mDirectories
.getCount() > 1) {
1237 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1238 listOfFiles
.listDirectory(root
);
1239 // TODO Enable when "On Device" is recovered ?
1240 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1241 setFile(listOfFiles
.getCurrentFile());
1242 startSyncFolderOperation(root
, false
);
1243 updateActionBarTitle();
1245 cleanSecondFragment();
1250 public void browseTo(OCFile folder
) {
1251 if (folder
== null
|| !folder
.isFolder()) {
1252 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1254 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1255 if (listOfFiles
!= null
) {
1256 setNavigationListWithFolder(folder
);
1257 listOfFiles
.listDirectory(folder
);
1258 // TODO Enable when "On Device" is recovered ?
1259 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1260 setFile(listOfFiles
.getCurrentFile());
1261 startSyncFolderOperation(folder
, false
);
1263 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1265 cleanSecondFragment();
1273 * Updates action bar and second fragment, if in dual pane mode.
1276 public void onBrowsedDownTo(OCFile directory
) {
1277 pushDirname(directory
);
1278 cleanSecondFragment();
1279 updateActionBarTitle();
1281 startSyncFolderOperation(directory
, false
);
1286 * Shows the information of the {@link OCFile} received as a
1287 * parameter in the second fragment.
1289 * @param file {@link OCFile} whose details will be shown
1292 public void showDetails(OCFile file
) {
1293 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1294 setSecondFragment(detailFragment
);
1295 updateFragmentsVisibility(true
);
1296 updateNavigationElementsInActionBar(file
);
1304 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1305 ActionBar actionBar
= getSupportActionBar();
1307 // For adding content description tag to a title field in the action bar
1308 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1310 if (chosenFile
== null
|| mDualPane
) {
1311 // only list of files - set for browsing through folders
1312 OCFile currentDir
= getCurrentDir();
1313 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1314 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1315 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1316 actionBar
.setDisplayHomeAsUpEnabled(true
);
1317 actionBar
.setDisplayShowTitleEnabled(true
);
1319 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1320 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1321 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1322 actionBarTitleView
.setContentDescription(
1323 getString(R
.string
.default_display_name_for_root_folder
));
1326 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1327 // actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD :
1328 // ActionBar.NAVIGATION_MODE_LIST);
1329 actionBar
.setListNavigationCallbacks(mDirectories
, this);
1330 // assuming mDirectories is updated
1333 actionBar
.setDisplayHomeAsUpEnabled(true
);
1334 actionBar
.setDisplayShowTitleEnabled(true
);
1335 actionBar
.setTitle(chosenFile
.getFileName());
1336 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1337 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1338 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1339 getWindow().getDecorView().findViewById(actionBarTitleId
).
1340 setContentDescription(chosenFile
.getFileName());
1347 protected ServiceConnection
newTransferenceServiceConnection() {
1348 return new ListServiceConnection();
1351 /** Defines callbacks for service binding, passed to bindService() */
1352 private class ListServiceConnection
implements ServiceConnection
{
1355 public void onServiceConnected(ComponentName component
, IBinder service
) {
1356 if (component
.equals(new ComponentName(
1357 FileDisplayActivity
.this, FileDownloader
.class))) {
1358 Log_OC
.d(TAG
, "Download service connected");
1359 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1360 if (mWaitingToPreview
!= null
)
1361 if (getStorageManager() != null
) {
1364 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1365 if (!mWaitingToPreview
.isDown()) {
1366 requestForDownload();
1370 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1371 FileUploader
.class))) {
1372 Log_OC
.d(TAG
, "Upload service connected");
1373 mUploaderBinder
= (FileUploaderBinder
) service
;
1377 // a new chance to get the mDownloadBinder through
1378 // getFileDownloadBinder() - THIS IS A MESS
1379 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1380 if (listOfFiles
!= null
) {
1381 listOfFiles
.listDirectory();
1382 // TODO Enable when "On Device" is recovered ?
1383 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1385 FileFragment secondFragment
= getSecondFragment();
1386 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1387 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1388 detailFragment
.listenForTransferProgress();
1389 detailFragment
.updateFileDetails(false
, false
);
1394 public void onServiceDisconnected(ComponentName component
) {
1395 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1396 FileDownloader
.class))) {
1397 Log_OC
.d(TAG
, "Download service disconnected");
1398 mDownloaderBinder
= null
;
1399 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1400 FileUploader
.class))) {
1401 Log_OC
.d(TAG
, "Upload service disconnected");
1402 mUploaderBinder
= null
;
1408 public void onSavedCertificate() {
1409 startSyncFolderOperation(getCurrentDir(), false
);
1414 public void onFailedSavingCertificate() {
1415 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1416 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1418 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1422 public void onCancelCertificate() {
1427 * Updates the view associated to the activity after the finish of some operation over files
1428 * in the current account.
1430 * @param operation Removal operation performed.
1431 * @param result Result of the removal.
1434 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1435 super.onRemoteOperationFinish(operation
, result
);
1437 if (operation
instanceof RemoveFileOperation
) {
1438 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1440 } else if (operation
instanceof RenameFileOperation
) {
1441 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1443 } else if (operation
instanceof SynchronizeFileOperation
) {
1444 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1446 } else if (operation
instanceof CreateFolderOperation
) {
1447 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1449 } else if (operation
instanceof CreateShareOperation
) {
1450 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1452 } else if (operation
instanceof UnshareLinkOperation
) {
1453 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1455 } else if (operation
instanceof MoveFileOperation
) {
1456 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1462 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1463 RemoteOperationResult result
) {
1464 if (result
.isSuccess()) {
1465 refreshShowDetails();
1466 refreshListOfFilesFragment();
1471 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1472 RemoteOperationResult result
) {
1473 if (result
.isSuccess()) {
1474 refreshShowDetails();
1475 refreshListOfFilesFragment();
1477 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1478 cleanSecondFragment();
1479 refreshListOfFilesFragment();
1483 private void refreshShowDetails() {
1484 FileFragment details
= getSecondFragment();
1485 if (details
!= null
) {
1486 OCFile file
= details
.getFile();
1488 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1489 if (details
instanceof PreviewMediaFragment
) {
1490 // Refresh OCFile of the fragment
1491 ((PreviewMediaFragment
) details
).updateFile(file
);
1496 invalidateOptionsMenu();
1501 * Updates the view associated to the activity after the finish of an operation trying to
1504 * @param operation Removal operation performed.
1505 * @param result Result of the removal.
1507 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1508 RemoteOperationResult result
) {
1509 dismissLoadingDialog();
1511 Toast msg
= Toast
.makeText(this,
1512 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1516 if (result
.isSuccess()) {
1517 OCFile removedFile
= operation
.getFile();
1518 FileFragment second
= getSecondFragment();
1519 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1520 if (second
instanceof PreviewMediaFragment
) {
1521 ((PreviewMediaFragment
)second
).stopPreview(true
);
1523 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1524 cleanSecondFragment();
1526 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1527 refreshListOfFilesFragment();
1529 invalidateOptionsMenu();
1531 if (result
.isSslRecoverableException()) {
1532 mLastSslUntrustedServerResult
= result
;
1533 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1540 * Updates the view associated to the activity after the finish of an operation trying to move a
1543 * @param operation Move operation performed.
1544 * @param result Result of the move operation.
1546 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1547 RemoteOperationResult result
) {
1548 if (result
.isSuccess()) {
1549 dismissLoadingDialog();
1550 refreshListOfFilesFragment();
1552 dismissLoadingDialog();
1554 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1555 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1559 } catch (NotFoundException e
) {
1560 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1567 * Updates the view associated to the activity after the finish of an operation trying to rename
1570 * @param operation Renaming operation performed.
1571 * @param result Result of the renaming.
1573 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1574 RemoteOperationResult result
) {
1575 dismissLoadingDialog();
1576 OCFile renamedFile
= operation
.getFile();
1577 if (result
.isSuccess()) {
1578 FileFragment details
= getSecondFragment();
1579 if (details
!= null
) {
1580 if (details
instanceof FileDetailFragment
&&
1581 renamedFile
.equals(details
.getFile()) ) {
1582 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1583 showDetails(renamedFile
);
1585 } else if (details
instanceof PreviewMediaFragment
&&
1586 renamedFile
.equals(details
.getFile())) {
1587 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1588 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1589 int position
= ((PreviewMediaFragment
)details
).getPosition();
1590 startMediaPreview(renamedFile
, position
, true
);
1592 getFileOperationsHelper().openFile(renamedFile
);
1597 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1598 refreshListOfFilesFragment();
1602 Toast msg
= Toast
.makeText(this,
1603 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1607 if (result
.isSslRecoverableException()) {
1608 mLastSslUntrustedServerResult
= result
;
1609 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1614 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1615 RemoteOperationResult result
) {
1616 dismissLoadingDialog();
1617 OCFile syncedFile
= operation
.getLocalFile();
1618 if (!result
.isSuccess()) {
1619 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1620 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1621 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1622 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1628 if (operation
.transferWasRequested()) {
1629 onTransferStateChanged(syncedFile
, true
, true
);
1632 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1633 operation
, getResources()), Toast
.LENGTH_LONG
);
1640 * Updates the view associated to the activity after the finish of an operation trying create a
1643 * @param operation Creation operation performed.
1644 * @param result Result of the creation.
1646 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1647 RemoteOperationResult result
) {
1648 if (result
.isSuccess()) {
1649 dismissLoadingDialog();
1650 refreshListOfFilesFragment();
1652 dismissLoadingDialog();
1654 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1655 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1659 } catch (NotFoundException e
) {
1660 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1670 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1671 refreshListOfFilesFragment();
1672 FileFragment details
= getSecondFragment();
1673 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1674 file
.equals(details
.getFile()) ) {
1675 if (downloading
|| uploading
) {
1676 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1678 if (!file
.fileExists()) {
1679 cleanSecondFragment();
1681 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1689 private void requestForDownload() {
1690 Account account
= getAccount();
1691 //if (!mWaitingToPreview.isDownloading()) {
1692 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1693 Intent i
= new Intent(this, FileDownloader
.class);
1694 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1695 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1701 private OCFile
getCurrentDir() {
1702 OCFile file
= getFile();
1704 if (file
.isFolder()) {
1706 } else if (getStorageManager() != null
) {
1707 String parentPath
= file
.getRemotePath().substring(0,
1708 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1709 return getStorageManager().getFileByPath(parentPath
);
1715 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1716 long currentSyncTime
= System
.currentTimeMillis();
1718 mSyncInProgress
= true
;
1720 // perform folder synchronization
1721 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1724 getFileOperationsHelper().isSharedSupported(),
1726 getStorageManager(),
1728 getApplicationContext()
1730 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1732 setSupportProgressBarIndeterminateVisibility(true
);
1734 setBackgroundText();
1738 * Show untrusted cert dialog
1740 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1741 // Show a dialog with the certificate info
1742 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1743 (CertificateCombinedException
) result
.getException());
1744 FragmentManager fm
= getSupportFragmentManager();
1745 FragmentTransaction ft
= fm
.beginTransaction();
1746 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1749 private void requestForDownload(OCFile file
) {
1750 Account account
= getAccount();
1751 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1752 Intent i
= new Intent(this, FileDownloader
.class);
1753 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1754 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1759 private void sendDownloadedFile(){
1760 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1761 mWaitingToSend
= null
;
1766 * Requests the download of the received {@link OCFile} , updates the UI
1767 * to monitor the download progress and prepares the activity to send the file
1768 * when the download finishes.
1770 * @param file {@link OCFile} to download and preview.
1772 public void startDownloadForSending(OCFile file
) {
1773 mWaitingToSend
= file
;
1774 requestForDownload(mWaitingToSend
);
1775 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1776 updateFragmentsVisibility(hasSecondFragment
);
1780 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1782 * @param file Image {@link OCFile} to show.
1784 public void startImagePreview(OCFile file
) {
1785 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1786 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1787 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1788 startActivity(showDetailsIntent
);
1793 * Stars the preview of an already down media {@link OCFile}.
1795 * @param file Media {@link OCFile} to preview.
1796 * @param startPlaybackPosition Media position where the playback will be started,
1798 * @param autoplay When 'true', the playback will start without user
1801 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1802 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1804 setSecondFragment(mediaFragment
);
1805 updateFragmentsVisibility(true
);
1806 updateNavigationElementsInActionBar(file
);
1811 * Requests the download of the received {@link OCFile} , updates the UI
1812 * to monitor the download progress and prepares the activity to preview
1813 * or open the file when the download finishes.
1815 * @param file {@link OCFile} to download and preview.
1817 public void startDownloadForPreview(OCFile file
) {
1818 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1819 setSecondFragment(detailFragment
);
1820 mWaitingToPreview
= file
;
1821 requestForDownload();
1822 updateFragmentsVisibility(true
);
1823 updateNavigationElementsInActionBar(file
);
1828 public void cancelTransference(OCFile file
) {
1829 getFileOperationsHelper().cancelTransference(file
);
1830 if (mWaitingToPreview
!= null
&&
1831 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1832 mWaitingToPreview
= null
;
1834 if (mWaitingToSend
!= null
&&
1835 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1836 mWaitingToSend
= null
;
1838 onTransferStateChanged(file
, false
, false
);
1842 public void onRefresh(boolean ignoreETag
) {
1843 refreshList(ignoreETag
);
1847 public void onRefresh() {
1851 private void refreshList(boolean ignoreETag
) {
1852 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1853 if (listOfFiles
!= null
) {
1854 OCFile folder
= listOfFiles
.getCurrentFile();
1855 if (folder
!= null
) {
1856 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1857 listDirectory(mFile);*/
1858 startSyncFolderOperation(folder
, ignoreETag
);
1863 private void sortByDate(boolean ascending
){
1864 getListOfFilesFragment().sortByDate(ascending
);
1867 private void sortBySize(boolean ascending
){
1868 getListOfFilesFragment().sortBySize(ascending
);
1871 private void sortByName(boolean ascending
){
1872 getListOfFilesFragment().sortByName(ascending
);
1875 public void allFilesOption() {