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 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
524 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
526 mDrawerLayout
.openDrawer(GravityCompat
.START
);
530 case R
.id
.action_sort
: {
531 SharedPreferences appPreferences
= PreferenceManager
532 .getDefaultSharedPreferences(this);
534 // Read sorting order, default to sort by name ascending
535 Integer sortOrder
= appPreferences
536 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
538 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
539 builder
.setTitle(R
.string
.actionbar_sort_title
)
540 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
541 new DialogInterface
.OnClickListener() {
542 public void onClick(DialogInterface dialog
, int which
) {
555 builder
.create().show();
559 retval
= super.onOptionsItemSelected(item
);
564 private void startSynchronization() {
565 Log_OC
.d(TAG
, "Got to start sync");
566 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
567 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
568 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
569 // cancel the current synchronizations of any ownCloud account
570 Bundle bundle
= new Bundle();
571 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
572 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
573 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
574 MainApp
.getAuthority());
575 ContentResolver
.requestSync(
577 MainApp
.getAuthority(), bundle
);
579 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
580 MainApp
.getAuthority() + " with new API");
581 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
582 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
583 builder
.setExpedited(true
);
584 builder
.setManual(true
);
587 // Fix bug in Android Lollipop when you click on refresh the whole account
588 Bundle extras
= new Bundle();
589 builder
.setExtras(extras
);
591 SyncRequest request
= builder
.build();
592 ContentResolver
.requestSync(request
);
598 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
599 if (itemPosition
!= 0) {
600 String targetPath
= "";
601 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
602 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
604 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
605 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
606 if (targetFolder
!= null
) {
607 browseTo(targetFolder
);
610 // the next operation triggers a new call to this method, but it's necessary to
611 // ensure that the name exposed in the action bar is the current directory when the
612 // user selected it in the navigation list
613 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&&
615 getSupportActionBar().setSelectedNavigationItem(0);
621 * Called, when the user selected something for uploading
624 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
626 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
628 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
629 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
630 //getClipData is only supported on api level 16+, Jelly Bean
631 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
632 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
633 Intent intent
= new Intent();
634 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
635 requestSimpleUpload(intent
, resultCode
);
638 requestSimpleUpload(data
, resultCode
);
640 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
641 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
642 requestMultipleUpload(data
, resultCode
);
644 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
646 final Intent fData
= data
;
647 final int fResultCode
= resultCode
;
648 getHandler().postDelayed(
652 requestMoveOperation(fData
, fResultCode
);
655 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
659 super.onActivityResult(requestCode
, resultCode
, data
);
664 private void requestMultipleUpload(Intent data
, int resultCode
) {
665 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
666 if (filePaths
!= null
) {
667 String
[] remotePaths
= new String
[filePaths
.length
];
668 String remotePathBase
= "";
670 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
671 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
673 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
674 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
675 for (int j
= 0; j
< remotePaths
.length
; j
++) {
676 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
679 Intent i
= new Intent(this, FileUploader
.class);
680 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
681 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
682 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
683 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
684 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
685 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
689 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
690 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
698 private void requestSimpleUpload(Intent data
, int resultCode
) {
699 String filePath
= null
;
700 String mimeType
= null
;
702 Uri selectedImageUri
= data
.getData();
705 mimeType
= getContentResolver().getType(selectedImageUri
);
707 String fileManagerString
= selectedImageUri
.getPath();
708 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
710 if (selectedImagePath
!= null
)
711 filePath
= selectedImagePath
;
713 filePath
= fileManagerString
;
715 } catch (Exception e
) {
716 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
717 "Intent.ACTION_GET_CONTENT", e
);
720 if (filePath
== null
) {
721 Log_OC
.e(TAG
, "Couldn't resolve path to file");
722 Toast t
= Toast
.makeText(
723 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
731 Intent i
= new Intent(this, FileUploader
.class);
732 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
733 OCFile currentDir
= getCurrentDir();
734 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
736 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
737 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
739 if (cursor
!= null
&& cursor
.moveToFirst()) {
740 String displayName
= cursor
.getString(cursor
.getColumnIndex(
741 OpenableColumns
.DISPLAY_NAME
));
742 Log_OC
.v(TAG
, "Display Name: " + displayName
);
744 displayName
.replace(File
.separatorChar
, '_');
745 displayName
.replace(File
.pathSeparatorChar
, '_');
746 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
749 // and what happens in case of error?; wrong target name for the upload
755 remotePath
+= new File(filePath
).getName();
758 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
759 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
760 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
761 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
762 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
763 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
768 * Request the operation for moving the file/folder from one path to another
770 * @param data Intent received
771 * @param resultCode Result code received
773 private void requestMoveOperation(Intent data
, int resultCode
) {
774 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
775 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
776 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
780 public void onBackPressed() {
781 OCFileListFragment listOfFiles
= getListOfFilesFragment();
782 if (mDualPane
|| getSecondFragment() == null
) {
783 if (listOfFiles
!= null
) { // should never be null, indeed
784 if (mDirectories
.getCount() <= 1) {
788 int levelsUp
= listOfFiles
.onBrowseUp();
789 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
794 if (listOfFiles
!= null
) { // should never be null, indeed
795 setFile(listOfFiles
.getCurrentFile());
797 cleanSecondFragment();
802 protected void onSaveInstanceState(Bundle outState
) {
803 // responsibility of restore is preferred in onCreate() before than in
804 // onRestoreInstanceState when there are Fragments involved
805 Log_OC
.v(TAG
, "onSaveInstanceState() start");
806 super.onSaveInstanceState(outState
);
807 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
808 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
809 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
810 // mRefreshSharesInProgress);
811 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
813 Log_OC
.v(TAG
, "onSaveInstanceState() end");
819 protected void onResume() {
820 Log_OC
.v(TAG
, "onResume() start");
823 // refresh Navigation Drawer account list
824 mNavigationDrawerAdapter
.updateAccountList();
826 // refresh list of files
827 refreshListOfFilesFragment();
829 // Listen for sync messages
830 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
831 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
832 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
833 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
834 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
835 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
836 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
837 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
838 // syncIntentFilter);
840 // Listen for upload messages
841 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
842 mUploadFinishReceiver
= new UploadFinishReceiver();
843 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
845 // Listen for download messages
846 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
847 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
848 mDownloadFinishReceiver
= new DownloadFinishReceiver();
849 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
851 Log_OC
.v(TAG
, "onResume() end");
856 protected void onPause() {
857 Log_OC
.v(TAG
, "onPause() start");
858 if (mSyncBroadcastReceiver
!= null
) {
859 unregisterReceiver(mSyncBroadcastReceiver
);
860 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
861 mSyncBroadcastReceiver
= null
;
863 if (mUploadFinishReceiver
!= null
) {
864 unregisterReceiver(mUploadFinishReceiver
);
865 mUploadFinishReceiver
= null
;
867 if (mDownloadFinishReceiver
!= null
) {
868 unregisterReceiver(mDownloadFinishReceiver
);
869 mDownloadFinishReceiver
= null
;
873 Log_OC
.v(TAG
, "onPause() end");
877 * Pushes a directory to the drop down list
878 * @param directory to push
879 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
881 public void pushDirname(OCFile directory
) {
882 if(!directory
.isFolder()){
883 throw new IllegalArgumentException("Only directories may be pushed!");
885 mDirectories
.insert(directory
.getFileName(), 0);
890 * Pops a directory name from the drop down list
891 * @return True, unless the stack is empty
893 public boolean popDirname() {
894 mDirectories
.remove(mDirectories
.getItem(0));
895 return !mDirectories
.isEmpty();
898 // Custom array adapter to override text colors
899 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
901 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
905 public View
getView(int position
, View convertView
, ViewGroup parent
) {
906 View v
= super.getView(position
, convertView
, parent
);
908 ((TextView
) v
).setTextColor(getResources().getColorStateList(
909 android
.R
.color
.white
));
911 fixRoot((TextView
) v
);
915 public View
getDropDownView(int position
, View convertView
,
917 View v
= super.getDropDownView(position
, convertView
, parent
);
919 ((TextView
) v
).setTextColor(getResources().getColorStateList(
920 android
.R
.color
.white
));
922 fixRoot((TextView
) v
);
926 private void fixRoot(TextView v
) {
927 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
928 v
.setText(R
.string
.default_display_name_for_root_folder
);
934 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
937 * {@link BroadcastReceiver} to enable syncing feedback in UI
940 public void onReceive(Context context
, Intent intent
) {
942 String event
= intent
.getAction();
943 Log_OC
.d(TAG
, "Received broadcast " + event
);
944 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
945 String synchFolderRemotePath
=
946 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
947 RemoteOperationResult synchResult
=
948 (RemoteOperationResult
)intent
.getSerializableExtra(
949 FileSyncAdapter
.EXTRA_RESULT
);
950 boolean sameAccount
= (getAccount() != null
&&
951 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
955 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
956 mSyncInProgress
= true
;
959 OCFile currentFile
= (getFile() == null
) ? null
:
960 getStorageManager().getFileByPath(getFile().getRemotePath());
961 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
962 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
964 if (currentDir
== null
) {
965 // current folder was removed from the server
966 Toast
.makeText( FileDisplayActivity
.this,
968 getString(R
.string
.sync_current_folder_was_removed
),
969 mDirectories
.getItem(0)),
975 if (currentFile
== null
&& !getFile().isFolder()) {
976 // currently selected file was removed in the server, and now we
978 cleanSecondFragment();
979 currentFile
= currentDir
;
982 if (synchFolderRemotePath
!= null
&&
983 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
984 OCFileListFragment fileListFragment
= getListOfFilesFragment();
985 if (fileListFragment
!= null
) {
986 fileListFragment
.listDirectory();
987 // TODO Enable when "On Device" is recovered ?
988 // fileListFragment.listDirectory(currentDir,
989 // MainApp.getOnlyOnDevice());
992 setFile(currentFile
);
995 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
996 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
999 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1001 /// TODO refactor and make common
1002 synchResult
!= null
&& !synchResult
.isSuccess() &&
1003 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1004 synchResult
.isIdPRedirection() ||
1005 (synchResult
.isException() && synchResult
.getException()
1006 instanceof AuthenticatorException
))) {
1010 OwnCloudClient client
;
1011 OwnCloudAccount ocAccount
=
1012 new OwnCloudAccount(getAccount(), context
);
1013 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1014 removeClientFor(ocAccount
));
1016 if (client
!= null
) {
1017 OwnCloudCredentials cred
= client
.getCredentials();
1019 AccountManager am
= AccountManager
.get(context
);
1020 if (cred
.authTokenExpires()) {
1021 am
.invalidateAuthToken(
1026 am
.clearPassword(getAccount());
1030 requestCredentialsUpdate();
1032 } catch (AccountNotFoundException e
) {
1033 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1038 removeStickyBroadcast(intent
);
1039 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1040 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1041 /*|| mRefreshSharesInProgress*/);
1043 setBackgroundText();
1047 if (synchResult
!= null
) {
1048 if (synchResult
.getCode().equals(
1049 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1050 mLastSslUntrustedServerResult
= synchResult
;
1053 } catch (RuntimeException e
) {
1054 // avoid app crashes after changing the serial id of RemoteOperationResult
1055 // in owncloud library with broadcast notifications pending to process
1056 removeStickyBroadcast(intent
);
1062 * Show a text message on screen view for notifying user if content is
1063 * loading or folder is empty
1065 private void setBackgroundText() {
1066 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1067 if (ocFileListFragment
!= null
) {
1068 int message
= R
.string
.file_list_loading
;
1069 if (!mSyncInProgress
) {
1070 // In case file list is empty
1071 message
= R
.string
.file_list_empty
;
1073 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1075 Log_OC
.e(TAG
, "OCFileListFragment is null");
1080 * Once the file upload has finished -> update view
1082 private class UploadFinishReceiver
extends BroadcastReceiver
{
1084 * Once the file upload has finished -> update view
1085 * @author David A. Velasco
1086 * {@link BroadcastReceiver} to enable upload feedback in UI
1089 public void onReceive(Context context
, Intent intent
) {
1091 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1092 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1093 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1094 OCFile currentDir
= getCurrentDir();
1095 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1096 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1098 if (sameAccount
&& isDescendant
) {
1099 refreshListOfFilesFragment();
1102 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1104 boolean renamedInUpload
= getFile().getRemotePath().
1105 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1106 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1108 FileFragment details
= getSecondFragment();
1109 boolean detailFragmentIsShown
= (details
!= null
&&
1110 details
instanceof FileDetailFragment
);
1112 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1113 if (uploadWasFine
) {
1114 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1116 if (renamedInUpload
) {
1117 String newName
= (new File(uploadedRemotePath
)).getName();
1118 Toast msg
= Toast
.makeText(
1121 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1126 if (uploadWasFine
|| getFile().fileExists()) {
1127 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1129 cleanSecondFragment();
1132 // Force the preview if the file is an image
1133 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1134 startImagePreview(getFile());
1135 } // TODO what about other kind of previews?
1139 if (intent
!= null
) {
1140 removeStickyBroadcast(intent
);
1150 * Class waiting for broadcast events from the {@link FileDownloader} service.
1152 * Updates the UI when a download is started or finished, provided that it is relevant for the
1155 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1157 //int refreshCounter = 0;
1159 public void onReceive(Context context
, Intent intent
) {
1161 boolean sameAccount
= isSameAccount(context
, intent
);
1162 String downloadedRemotePath
=
1163 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1164 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1166 if (sameAccount
&& isDescendant
) {
1167 String linkedToRemotePath
=
1168 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1169 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1170 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1171 refreshListOfFilesFragment();
1173 refreshSecondFragment(
1175 downloadedRemotePath
,
1176 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1180 if (mWaitingToSend
!= null
) {
1182 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1183 if (mWaitingToSend
.isDown()) {
1184 sendDownloadedFile();
1189 if (intent
!= null
) {
1190 removeStickyBroadcast(intent
);
1195 private boolean isDescendant(String downloadedRemotePath
) {
1196 OCFile currentDir
= getCurrentDir();
1198 currentDir
!= null
&&
1199 downloadedRemotePath
!= null
&&
1200 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1204 private boolean isAscendant(String linkedToRemotePath
) {
1205 OCFile currentDir
= getCurrentDir();
1207 currentDir
!= null
&&
1208 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1212 private boolean isSameAccount(Context context
, Intent intent
) {
1213 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1214 return (accountName
!= null
&& getAccount() != null
&&
1215 accountName
.equals(getAccount().name
));
1220 public void browseToRoot() {
1221 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1222 if (listOfFiles
!= null
) { // should never be null, indeed
1223 while (mDirectories
.getCount() > 1) {
1226 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1227 listOfFiles
.listDirectory(root
);
1228 // TODO Enable when "On Device" is recovered ?
1229 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1230 setFile(listOfFiles
.getCurrentFile());
1231 startSyncFolderOperation(root
, false
);
1233 cleanSecondFragment();
1237 public void browseTo(OCFile folder
) {
1238 if (folder
== null
|| !folder
.isFolder()) {
1239 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1241 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1242 if (listOfFiles
!= null
) {
1243 setNavigationListWithFolder(folder
);
1244 listOfFiles
.listDirectory(folder
);
1245 // TODO Enable when "On Device" is recovered ?
1246 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1247 setFile(listOfFiles
.getCurrentFile());
1248 startSyncFolderOperation(folder
, false
);
1250 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1252 cleanSecondFragment();
1259 * Updates action bar and second fragment, if in dual pane mode.
1262 public void onBrowsedDownTo(OCFile directory
) {
1263 pushDirname(directory
);
1264 cleanSecondFragment();
1267 startSyncFolderOperation(directory
, false
);
1272 * Shows the information of the {@link OCFile} received as a
1273 * parameter in the second fragment.
1275 * @param file {@link OCFile} whose details will be shown
1278 public void showDetails(OCFile file
) {
1279 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1280 setSecondFragment(detailFragment
);
1281 updateFragmentsVisibility(true
);
1282 updateNavigationElementsInActionBar(file
);
1290 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1291 ActionBar actionBar
= getSupportActionBar();
1293 // For adding content description tag to a title field in the action bar
1294 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1296 if (chosenFile
== null
|| mDualPane
) {
1297 // only list of files - set for browsing through folders
1298 OCFile currentDir
= getCurrentDir();
1299 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1300 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1301 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1302 actionBar
.setDisplayHomeAsUpEnabled(true
);
1303 actionBar
.setDisplayShowTitleEnabled(true
);
1305 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1306 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1307 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1308 actionBarTitleView
.setContentDescription(
1309 getString(R
.string
.default_display_name_for_root_folder
));
1312 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
:
1313 ActionBar
.NAVIGATION_MODE_LIST
);
1314 actionBar
.setListNavigationCallbacks(mDirectories
, this);
1315 // assuming mDirectories is updated
1318 actionBar
.setDisplayHomeAsUpEnabled(true
);
1319 actionBar
.setDisplayShowTitleEnabled(true
);
1320 actionBar
.setTitle(chosenFile
.getFileName());
1321 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1322 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1323 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1324 getWindow().getDecorView().findViewById(actionBarTitleId
).
1325 setContentDescription(chosenFile
.getFileName());
1332 protected ServiceConnection
newTransferenceServiceConnection() {
1333 return new ListServiceConnection();
1336 /** Defines callbacks for service binding, passed to bindService() */
1337 private class ListServiceConnection
implements ServiceConnection
{
1340 public void onServiceConnected(ComponentName component
, IBinder service
) {
1341 if (component
.equals(new ComponentName(
1342 FileDisplayActivity
.this, FileDownloader
.class))) {
1343 Log_OC
.d(TAG
, "Download service connected");
1344 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1345 if (mWaitingToPreview
!= null
)
1346 if (getStorageManager() != null
) {
1349 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1350 if (!mWaitingToPreview
.isDown()) {
1351 requestForDownload();
1355 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1356 FileUploader
.class))) {
1357 Log_OC
.d(TAG
, "Upload service connected");
1358 mUploaderBinder
= (FileUploaderBinder
) service
;
1362 // a new chance to get the mDownloadBinder through
1363 // getFileDownloadBinder() - THIS IS A MESS
1364 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1365 if (listOfFiles
!= null
) {
1366 listOfFiles
.listDirectory();
1367 // TODO Enable when "On Device" is recovered ?
1368 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1370 FileFragment secondFragment
= getSecondFragment();
1371 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1372 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1373 detailFragment
.listenForTransferProgress();
1374 detailFragment
.updateFileDetails(false
, false
);
1379 public void onServiceDisconnected(ComponentName component
) {
1380 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1381 FileDownloader
.class))) {
1382 Log_OC
.d(TAG
, "Download service disconnected");
1383 mDownloaderBinder
= null
;
1384 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1385 FileUploader
.class))) {
1386 Log_OC
.d(TAG
, "Upload service disconnected");
1387 mUploaderBinder
= null
;
1393 public void onSavedCertificate() {
1394 startSyncFolderOperation(getCurrentDir(), false
);
1399 public void onFailedSavingCertificate() {
1400 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1401 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1403 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1407 public void onCancelCertificate() {
1412 * Updates the view associated to the activity after the finish of some operation over files
1413 * in the current account.
1415 * @param operation Removal operation performed.
1416 * @param result Result of the removal.
1419 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1420 super.onRemoteOperationFinish(operation
, result
);
1422 if (operation
instanceof RemoveFileOperation
) {
1423 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1425 } else if (operation
instanceof RenameFileOperation
) {
1426 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1428 } else if (operation
instanceof SynchronizeFileOperation
) {
1429 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1431 } else if (operation
instanceof CreateFolderOperation
) {
1432 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1434 } else if (operation
instanceof CreateShareOperation
) {
1435 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1437 } else if (operation
instanceof UnshareLinkOperation
) {
1438 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1440 } else if (operation
instanceof MoveFileOperation
) {
1441 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1447 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1448 RemoteOperationResult result
) {
1449 if (result
.isSuccess()) {
1450 refreshShowDetails();
1451 refreshListOfFilesFragment();
1456 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1457 RemoteOperationResult result
) {
1458 if (result
.isSuccess()) {
1459 refreshShowDetails();
1460 refreshListOfFilesFragment();
1462 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1463 cleanSecondFragment();
1464 refreshListOfFilesFragment();
1468 private void refreshShowDetails() {
1469 FileFragment details
= getSecondFragment();
1470 if (details
!= null
) {
1471 OCFile file
= details
.getFile();
1473 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1474 if (details
instanceof PreviewMediaFragment
) {
1475 // Refresh OCFile of the fragment
1476 ((PreviewMediaFragment
) details
).updateFile(file
);
1481 invalidateOptionsMenu();
1486 * Updates the view associated to the activity after the finish of an operation trying to
1489 * @param operation Removal operation performed.
1490 * @param result Result of the removal.
1492 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1493 RemoteOperationResult result
) {
1494 dismissLoadingDialog();
1496 Toast msg
= Toast
.makeText(this,
1497 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1501 if (result
.isSuccess()) {
1502 OCFile removedFile
= operation
.getFile();
1503 FileFragment second
= getSecondFragment();
1504 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1505 if (second
instanceof PreviewMediaFragment
) {
1506 ((PreviewMediaFragment
)second
).stopPreview(true
);
1508 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1509 cleanSecondFragment();
1511 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1512 refreshListOfFilesFragment();
1514 invalidateOptionsMenu();
1516 if (result
.isSslRecoverableException()) {
1517 mLastSslUntrustedServerResult
= result
;
1518 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1525 * Updates the view associated to the activity after the finish of an operation trying to move a
1528 * @param operation Move operation performed.
1529 * @param result Result of the move operation.
1531 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1532 RemoteOperationResult result
) {
1533 if (result
.isSuccess()) {
1534 dismissLoadingDialog();
1535 refreshListOfFilesFragment();
1537 dismissLoadingDialog();
1539 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1540 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1544 } catch (NotFoundException e
) {
1545 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1552 * Updates the view associated to the activity after the finish of an operation trying to rename
1555 * @param operation Renaming operation performed.
1556 * @param result Result of the renaming.
1558 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1559 RemoteOperationResult result
) {
1560 dismissLoadingDialog();
1561 OCFile renamedFile
= operation
.getFile();
1562 if (result
.isSuccess()) {
1563 FileFragment details
= getSecondFragment();
1564 if (details
!= null
) {
1565 if (details
instanceof FileDetailFragment
&&
1566 renamedFile
.equals(details
.getFile()) ) {
1567 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1568 showDetails(renamedFile
);
1570 } else if (details
instanceof PreviewMediaFragment
&&
1571 renamedFile
.equals(details
.getFile())) {
1572 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1573 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1574 int position
= ((PreviewMediaFragment
)details
).getPosition();
1575 startMediaPreview(renamedFile
, position
, true
);
1577 getFileOperationsHelper().openFile(renamedFile
);
1582 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1583 refreshListOfFilesFragment();
1587 Toast msg
= Toast
.makeText(this,
1588 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1592 if (result
.isSslRecoverableException()) {
1593 mLastSslUntrustedServerResult
= result
;
1594 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1599 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1600 RemoteOperationResult result
) {
1601 dismissLoadingDialog();
1602 OCFile syncedFile
= operation
.getLocalFile();
1603 if (!result
.isSuccess()) {
1604 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1605 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1606 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1607 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1613 if (operation
.transferWasRequested()) {
1614 onTransferStateChanged(syncedFile
, true
, true
);
1617 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1618 operation
, getResources()), Toast
.LENGTH_LONG
);
1625 * Updates the view associated to the activity after the finish of an operation trying create a
1628 * @param operation Creation operation performed.
1629 * @param result Result of the creation.
1631 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1632 RemoteOperationResult result
) {
1633 if (result
.isSuccess()) {
1634 dismissLoadingDialog();
1635 refreshListOfFilesFragment();
1637 dismissLoadingDialog();
1639 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1640 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1644 } catch (NotFoundException e
) {
1645 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1655 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1656 refreshListOfFilesFragment();
1657 FileFragment details
= getSecondFragment();
1658 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1659 file
.equals(details
.getFile()) ) {
1660 if (downloading
|| uploading
) {
1661 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1663 if (!file
.fileExists()) {
1664 cleanSecondFragment();
1666 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1674 private void requestForDownload() {
1675 Account account
= getAccount();
1676 //if (!mWaitingToPreview.isDownloading()) {
1677 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1678 Intent i
= new Intent(this, FileDownloader
.class);
1679 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1680 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1686 private OCFile
getCurrentDir() {
1687 OCFile file
= getFile();
1689 if (file
.isFolder()) {
1691 } else if (getStorageManager() != null
) {
1692 String parentPath
= file
.getRemotePath().substring(0,
1693 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1694 return getStorageManager().getFileByPath(parentPath
);
1700 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1701 long currentSyncTime
= System
.currentTimeMillis();
1703 mSyncInProgress
= true
;
1705 // perform folder synchronization
1706 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1709 getFileOperationsHelper().isSharedSupported(),
1711 getStorageManager(),
1713 getApplicationContext()
1715 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1717 setSupportProgressBarIndeterminateVisibility(true
);
1719 setBackgroundText();
1723 * Show untrusted cert dialog
1725 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1726 // Show a dialog with the certificate info
1727 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1728 (CertificateCombinedException
) result
.getException());
1729 FragmentManager fm
= getSupportFragmentManager();
1730 FragmentTransaction ft
= fm
.beginTransaction();
1731 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1734 private void requestForDownload(OCFile file
) {
1735 Account account
= getAccount();
1736 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1737 Intent i
= new Intent(this, FileDownloader
.class);
1738 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1739 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1744 private void sendDownloadedFile(){
1745 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1746 mWaitingToSend
= null
;
1751 * Requests the download of the received {@link OCFile} , updates the UI
1752 * to monitor the download progress and prepares the activity to send the file
1753 * when the download finishes.
1755 * @param file {@link OCFile} to download and preview.
1757 public void startDownloadForSending(OCFile file
) {
1758 mWaitingToSend
= file
;
1759 requestForDownload(mWaitingToSend
);
1760 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1761 updateFragmentsVisibility(hasSecondFragment
);
1765 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1767 * @param file Image {@link OCFile} to show.
1769 public void startImagePreview(OCFile file
) {
1770 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1771 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1772 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1773 startActivity(showDetailsIntent
);
1778 * Stars the preview of an already down media {@link OCFile}.
1780 * @param file Media {@link OCFile} to preview.
1781 * @param startPlaybackPosition Media position where the playback will be started,
1783 * @param autoplay When 'true', the playback will start without user
1786 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1787 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1789 setSecondFragment(mediaFragment
);
1790 updateFragmentsVisibility(true
);
1791 updateNavigationElementsInActionBar(file
);
1796 * Requests the download of the received {@link OCFile} , updates the UI
1797 * to monitor the download progress and prepares the activity to preview
1798 * or open the file when the download finishes.
1800 * @param file {@link OCFile} to download and preview.
1802 public void startDownloadForPreview(OCFile file
) {
1803 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1804 setSecondFragment(detailFragment
);
1805 mWaitingToPreview
= file
;
1806 requestForDownload();
1807 updateFragmentsVisibility(true
);
1808 updateNavigationElementsInActionBar(file
);
1813 public void cancelTransference(OCFile file
) {
1814 getFileOperationsHelper().cancelTransference(file
);
1815 if (mWaitingToPreview
!= null
&&
1816 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1817 mWaitingToPreview
= null
;
1819 if (mWaitingToSend
!= null
&&
1820 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1821 mWaitingToSend
= null
;
1823 onTransferStateChanged(file
, false
, false
);
1827 public void onRefresh(boolean ignoreETag
) {
1828 refreshList(ignoreETag
);
1832 public void onRefresh() {
1836 private void refreshList(boolean ignoreETag
) {
1837 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1838 if (listOfFiles
!= null
) {
1839 OCFile folder
= listOfFiles
.getCurrentFile();
1840 if (folder
!= null
) {
1841 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1842 listDirectory(mFile);*/
1843 startSyncFolderOperation(folder
, ignoreETag
);
1848 private void sortByDate(boolean ascending
){
1849 getListOfFilesFragment().sortByDate(ascending
);
1852 private void sortBySize(boolean ascending
){
1853 getListOfFilesFragment().sortBySize(ascending
);
1856 private void sortByName(boolean ascending
){
1857 getListOfFilesFragment().sortByName(ascending
);
1860 public void allFilesOption() {