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
.operations
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.MoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
88 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import com
.owncloud
.android
.utils
.FileStorageUtils
;
105 import com
.owncloud
.android
.utils
.UriUtils
;
111 * Displays, what files the user has available in his ownCloud.
114 public class FileDisplayActivity
extends HookActivity
implements
115 FileFragment
.ContainerActivity
, ActionBar
.OnNavigationListener
,
116 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
118 private ArrayAdapter
<String
> mDirectories
;
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
129 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
131 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
133 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
135 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
136 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 public static final int ACTION_MOVE_FILES
= 3;
139 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
141 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
142 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
144 private OCFile mWaitingToPreview
;
146 private boolean mSyncInProgress
= false
;
148 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
149 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
150 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
151 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
153 private OCFile mWaitingToSend
;
157 protected void onCreate(Bundle savedInstanceState
) {
158 Log_OC
.v(TAG
, "onCreate() start");
159 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
161 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
164 /// grant that FileObserverService is watching favorite files
165 if (savedInstanceState
== null
) {
166 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
167 startService(initObserversIntent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
173 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
176 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
192 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
193 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
194 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
195 if (savedInstanceState
== null
) {
196 createMinFragments();
200 mDirectories
= new CustomArrayAdapter
<String
>(this,
201 R
.layout
.support_simple_spinner_dropdown_item
);
202 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
203 // according to the official
206 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
207 /*|| mRefreshSharesInProgress*/);
208 // always AFTER setContentView(...) ; to work around bug in its implementation
210 // TODO Remove??, it is done in onPostCreate
211 // mDrawerToggle.syncState();
215 Log_OC
.v(TAG
, "onCreate() end");
219 protected void onStart() {
220 Log_OC
.v(TAG
, "onStart() start");
222 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
223 Log_OC
.v(TAG
, "onStart() end");
227 protected void onDestroy() {
228 Log_OC
.v(TAG
, "onDestroy() start");
230 Log_OC
.v(TAG
, "onDestroy() end");
234 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
237 protected void onAccountSet(boolean stateWasRecovered
) {
238 super.onAccountSet(stateWasRecovered
);
239 if (getAccount() != null
) {
240 /// Check whether the 'main' OCFile handled by the Activity is contained in the
242 OCFile file
= getFile();
243 // get parent from path
244 String parentPath
= "";
246 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
247 // upload in progress - right now, files are not inserted in the local
248 // cache until the upload is successful get parent from path
249 parentPath
= file
.getRemotePath().substring(0,
250 file
.getRemotePath().lastIndexOf(file
.getFileName()));
251 if (getStorageManager().getFileByPath(parentPath
) == null
)
252 file
= null
; // not able to know the directory where the file is uploading
254 file
= getStorageManager().getFileByPath(file
.getRemotePath());
255 // currentDir = null if not in the current Account
259 // fall back to root folder
260 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
263 setNavigationListWithFolder(file
);
265 if (!stateWasRecovered
) {
266 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
267 initFragmentsWithFile();
268 if (file
.isFolder()) {
269 startSyncFolderOperation(file
, false
);
273 updateFragmentsVisibility(!file
.isFolder());
274 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
280 private void setNavigationListWithFolder(OCFile file
) {
281 mDirectories
.clear();
282 OCFile fileIt
= file
;
284 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
285 if (fileIt
.isFolder()) {
286 mDirectories
.add(fileIt
.getFileName());
288 // get parent from path
289 parentPath
= fileIt
.getRemotePath().substring(0,
290 fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
291 fileIt
= getStorageManager().getFileByPath(parentPath
);
293 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
297 private void createMinFragments() {
298 OCFileListFragment listOfFiles
= new OCFileListFragment();
299 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
300 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
301 transaction
.commit();
304 private void initFragmentsWithFile() {
305 if (getAccount() != null
&& getFile() != null
) {
307 OCFileListFragment listOfFiles
= getListOfFilesFragment();
308 if (listOfFiles
!= null
) {
309 listOfFiles
.listDirectory(getCurrentDir());
310 // TODO Enable when "On Device" is recovered
311 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
313 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
317 OCFile file
= getFile();
318 Fragment secondFragment
= chooseInitialSecondFragment(file
);
319 if (secondFragment
!= null
) {
320 setSecondFragment(secondFragment
);
321 updateFragmentsVisibility(true
);
322 updateNavigationElementsInActionBar(file
);
325 cleanSecondFragment();
329 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
330 if (getAccount() == null
) {
331 Log_OC
.wtf(TAG
, "\t account is NULL");
333 if (getFile() == null
) {
334 Log_OC
.wtf(TAG
, "\t file is NULL");
339 private Fragment
chooseInitialSecondFragment(OCFile file
) {
340 Fragment secondFragment
= null
;
341 if (file
!= null
&& !file
.isFolder()) {
342 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
343 && file
.getLastSyncDateForProperties() > 0 // temporal fix
345 int startPlaybackPosition
=
346 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
348 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
349 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
350 startPlaybackPosition
, autoplay
);
353 secondFragment
= new FileDetailFragment(file
, getAccount());
356 return secondFragment
;
361 * Replaces the second fragment managed by the activity with the received as
364 * Assumes never will be more than two fragments managed at the same time.
366 * @param fragment New second Fragment to set.
368 private void setSecondFragment(Fragment fragment
) {
369 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
370 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
371 transaction
.commit();
375 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
377 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
384 } else if (existsSecondFragment
) {
385 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
386 mLeftFragmentContainer
.setVisibility(View
.GONE
);
388 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
389 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
393 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
394 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
396 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
397 mRightFragmentContainer
.setVisibility(View
.GONE
);
403 private OCFileListFragment
getListOfFilesFragment() {
404 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
405 FileDisplayActivity
.TAG_LIST_OF_FILES
);
406 if (listOfFiles
!= null
) {
407 return (OCFileListFragment
)listOfFiles
;
409 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
413 public FileFragment
getSecondFragment() {
414 Fragment second
= getSupportFragmentManager().findFragmentByTag(
415 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
416 if (second
!= null
) {
417 return (FileFragment
)second
;
422 protected void cleanSecondFragment() {
423 Fragment second
= getSecondFragment();
424 if (second
!= null
) {
425 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
429 updateFragmentsVisibility(false
);
430 updateNavigationElementsInActionBar(null
);
433 protected void refreshListOfFilesFragment() {
434 OCFileListFragment fileListFragment
= getListOfFilesFragment();
435 if (fileListFragment
!= null
) {
436 fileListFragment
.listDirectory();
437 // TODO Enable when "On Device" is recovered ?
438 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
442 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
444 FileFragment secondFragment
= getSecondFragment();
445 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
446 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
447 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
448 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
449 OCFile fileInFragment
= detailsFragment
.getFile();
450 if (fileInFragment
!= null
&&
451 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
452 // the user browsed to other file ; forget the automatic preview
453 mWaitingToPreview
= null
;
455 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
456 // grant that the right panel updates the progress bar
457 detailsFragment
.listenForTransferProgress();
458 detailsFragment
.updateFileDetails(true
, false
);
460 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
461 // update the right panel
462 boolean detailsFragmentChanged
= false
;
465 mWaitingToPreview
= getStorageManager().getFileById(
466 mWaitingToPreview
.getFileId()); // update the file from database,
467 // for the local storage path
468 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
469 startMediaPreview(mWaitingToPreview
, 0, true
);
470 detailsFragmentChanged
= true
;
472 getFileOperationsHelper().openFile(mWaitingToPreview
);
475 mWaitingToPreview
= null
;
477 if (!detailsFragmentChanged
) {
478 detailsFragment
.updateFileDetails(false
, (success
));
485 public boolean onPrepareOptionsMenu(Menu menu
) {
486 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
487 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
488 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
492 return super.onPrepareOptionsMenu(menu
);
496 public boolean onCreateOptionsMenu(Menu menu
) {
497 MenuInflater inflater
= getMenuInflater();
498 inflater
.inflate(R
.menu
.main_menu
, menu
);
504 public boolean onOptionsItemSelected(MenuItem item
) {
505 boolean retval
= true
;
506 switch (item
.getItemId()) {
507 case R
.id
.action_create_dir
: {
508 CreateFolderDialogFragment dialog
=
509 CreateFolderDialogFragment
.newInstance(getCurrentDir());
510 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
513 case R
.id
.action_sync_account
: {
514 startSynchronization();
517 case R
.id
.action_upload
: {
518 UploadSourceDialogFragment dialog
=
519 UploadSourceDialogFragment
.newInstance(getAccount());
520 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
524 case android
.R
.id
.home
: {
525 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
526 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
528 mDrawerLayout
.openDrawer(GravityCompat
.START
);
532 case R
.id
.action_sort
: {
533 SharedPreferences appPreferences
= PreferenceManager
534 .getDefaultSharedPreferences(this);
536 // Read sorting order, default to sort by name ascending
537 Integer sortOrder
= appPreferences
538 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
540 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
541 builder
.setTitle(R
.string
.actionbar_sort_title
)
542 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
543 new DialogInterface
.OnClickListener() {
544 public void onClick(DialogInterface dialog
, int which
) {
557 builder
.create().show();
561 retval
= super.onOptionsItemSelected(item
);
566 private void startSynchronization() {
567 Log_OC
.d(TAG
, "Got to start sync");
568 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
569 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
570 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
571 // cancel the current synchronizations of any ownCloud account
572 Bundle bundle
= new Bundle();
573 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
574 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
575 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
576 MainApp
.getAuthority());
577 ContentResolver
.requestSync(
579 MainApp
.getAuthority(), bundle
);
581 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
582 MainApp
.getAuthority() + " with new API");
583 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
584 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
585 builder
.setExpedited(true
);
586 builder
.setManual(true
);
589 // Fix bug in Android Lollipop when you click on refresh the whole account
590 Bundle extras
= new Bundle();
591 builder
.setExtras(extras
);
593 SyncRequest request
= builder
.build();
594 ContentResolver
.requestSync(request
);
600 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
601 if (itemPosition
!= 0) {
602 String targetPath
= "";
603 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
604 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
606 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
607 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
608 if (targetFolder
!= null
) {
609 browseTo(targetFolder
);
612 // the next operation triggers a new call to this method, but it's necessary to
613 // ensure that the name exposed in the action bar is the current directory when the
614 // user selected it in the navigation list
615 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&&
617 getSupportActionBar().setSelectedNavigationItem(0);
623 * Called, when the user selected something for uploading
626 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
628 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
630 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
631 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
632 //getClipData is only supported on api level 16+, Jelly Bean
633 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
634 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
635 Intent intent
= new Intent();
636 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
637 requestSimpleUpload(intent
, resultCode
);
640 requestSimpleUpload(data
, resultCode
);
642 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
643 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
644 requestMultipleUpload(data
, resultCode
);
646 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
648 final Intent fData
= data
;
649 final int fResultCode
= resultCode
;
650 getHandler().postDelayed(
654 requestMoveOperation(fData
, fResultCode
);
657 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
661 super.onActivityResult(requestCode
, resultCode
, data
);
666 private void requestMultipleUpload(Intent data
, int resultCode
) {
667 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
668 if (filePaths
!= null
) {
669 String
[] remotePaths
= new String
[filePaths
.length
];
670 String remotePathBase
= "";
672 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
673 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
675 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
676 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
677 for (int j
= 0; j
< remotePaths
.length
; j
++) {
678 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
681 Intent i
= new Intent(this, FileUploader
.class);
682 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
683 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
684 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
685 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
686 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
687 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
691 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
692 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
700 private void requestSimpleUpload(Intent data
, int resultCode
) {
701 String filePath
= null
;
702 String mimeType
= null
;
704 Uri selectedImageUri
= data
.getData();
707 mimeType
= getContentResolver().getType(selectedImageUri
);
709 String fileManagerString
= selectedImageUri
.getPath();
710 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
712 if (selectedImagePath
!= null
)
713 filePath
= selectedImagePath
;
715 filePath
= fileManagerString
;
717 } catch (Exception e
) {
718 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
719 "Intent.ACTION_GET_CONTENT", e
);
722 if (filePath
== null
) {
723 Log_OC
.e(TAG
, "Couldn't resolve path to file");
724 Toast t
= Toast
.makeText(
725 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
733 Intent i
= new Intent(this, FileUploader
.class);
734 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
735 OCFile currentDir
= getCurrentDir();
736 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
738 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
739 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
741 if (cursor
!= null
&& cursor
.moveToFirst()) {
742 String displayName
= cursor
.getString(cursor
.getColumnIndex(
743 OpenableColumns
.DISPLAY_NAME
));
744 Log_OC
.v(TAG
, "Display Name: " + displayName
);
746 displayName
.replace(File
.separatorChar
, '_');
747 displayName
.replace(File
.pathSeparatorChar
, '_');
748 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
751 // and what happens in case of error?; wrong target name for the upload
757 remotePath
+= new File(filePath
).getName();
760 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
761 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
762 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
763 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
764 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
765 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
770 * Request the operation for moving the file/folder from one path to another
772 * @param data Intent received
773 * @param resultCode Result code received
775 private void requestMoveOperation(Intent data
, int resultCode
) {
776 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
777 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
778 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
782 public void onBackPressed() {
783 OCFileListFragment listOfFiles
= getListOfFilesFragment();
784 if (mDualPane
|| getSecondFragment() == null
) {
785 if (listOfFiles
!= null
) { // should never be null, indeed
786 if (mDirectories
.getCount() <= 1) {
790 int levelsUp
= listOfFiles
.onBrowseUp();
791 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
796 if (listOfFiles
!= null
) { // should never be null, indeed
797 setFile(listOfFiles
.getCurrentFile());
799 cleanSecondFragment();
804 protected void onSaveInstanceState(Bundle outState
) {
805 // responsibility of restore is preferred in onCreate() before than in
806 // onRestoreInstanceState when there are Fragments involved
807 Log_OC
.v(TAG
, "onSaveInstanceState() start");
808 super.onSaveInstanceState(outState
);
809 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
810 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
811 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
812 // mRefreshSharesInProgress);
813 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
815 Log_OC
.v(TAG
, "onSaveInstanceState() end");
821 protected void onResume() {
822 Log_OC
.v(TAG
, "onResume() start");
825 // refresh Navigation Drawer account list
826 mNavigationDrawerAdapter
.updateAccountList();
828 // refresh list of files
829 refreshListOfFilesFragment();
831 // Listen for sync messages
832 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
833 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
834 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
835 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
836 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
837 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
838 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
839 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
840 // syncIntentFilter);
842 // Listen for upload messages
843 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
844 mUploadFinishReceiver
= new UploadFinishReceiver();
845 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
847 // Listen for download messages
848 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
849 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
850 mDownloadFinishReceiver
= new DownloadFinishReceiver();
851 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
853 Log_OC
.v(TAG
, "onResume() end");
858 protected void onPause() {
859 Log_OC
.v(TAG
, "onPause() start");
860 if (mSyncBroadcastReceiver
!= null
) {
861 unregisterReceiver(mSyncBroadcastReceiver
);
862 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
863 mSyncBroadcastReceiver
= null
;
865 if (mUploadFinishReceiver
!= null
) {
866 unregisterReceiver(mUploadFinishReceiver
);
867 mUploadFinishReceiver
= null
;
869 if (mDownloadFinishReceiver
!= null
) {
870 unregisterReceiver(mDownloadFinishReceiver
);
871 mDownloadFinishReceiver
= null
;
875 Log_OC
.v(TAG
, "onPause() end");
879 * Pushes a directory to the drop down list
880 * @param directory to push
881 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
883 public void pushDirname(OCFile directory
) {
884 if(!directory
.isFolder()){
885 throw new IllegalArgumentException("Only directories may be pushed!");
887 mDirectories
.insert(directory
.getFileName(), 0);
892 * Pops a directory name from the drop down list
893 * @return True, unless the stack is empty
895 public boolean popDirname() {
896 mDirectories
.remove(mDirectories
.getItem(0));
897 return !mDirectories
.isEmpty();
900 // Custom array adapter to override text colors
901 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
903 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
907 public View
getView(int position
, View convertView
, ViewGroup parent
) {
908 View v
= super.getView(position
, convertView
, parent
);
910 ((TextView
) v
).setTextColor(getResources().getColorStateList(
911 android
.R
.color
.white
));
913 fixRoot((TextView
) v
);
917 public View
getDropDownView(int position
, View convertView
,
919 View v
= super.getDropDownView(position
, convertView
, parent
);
921 ((TextView
) v
).setTextColor(getResources().getColorStateList(
922 android
.R
.color
.white
));
924 fixRoot((TextView
) v
);
928 private void fixRoot(TextView v
) {
929 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
930 v
.setText(R
.string
.default_display_name_for_root_folder
);
936 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
939 * {@link BroadcastReceiver} to enable syncing feedback in UI
942 public void onReceive(Context context
, Intent intent
) {
944 String event
= intent
.getAction();
945 Log_OC
.d(TAG
, "Received broadcast " + event
);
946 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
947 String synchFolderRemotePath
=
948 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
949 RemoteOperationResult synchResult
=
950 (RemoteOperationResult
)intent
.getSerializableExtra(
951 FileSyncAdapter
.EXTRA_RESULT
);
952 boolean sameAccount
= (getAccount() != null
&&
953 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
957 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
958 mSyncInProgress
= true
;
961 OCFile currentFile
= (getFile() == null
) ? null
:
962 getStorageManager().getFileByPath(getFile().getRemotePath());
963 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
964 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
966 if (currentDir
== null
) {
967 // current folder was removed from the server
968 Toast
.makeText( FileDisplayActivity
.this,
970 getString(R
.string
.sync_current_folder_was_removed
),
971 mDirectories
.getItem(0)),
977 if (currentFile
== null
&& !getFile().isFolder()) {
978 // currently selected file was removed in the server, and now we
980 cleanSecondFragment();
981 currentFile
= currentDir
;
984 if (synchFolderRemotePath
!= null
&&
985 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
986 OCFileListFragment fileListFragment
= getListOfFilesFragment();
987 if (fileListFragment
!= null
) {
988 fileListFragment
.listDirectory();
989 // TODO Enable when "On Device" is recovered ?
990 // fileListFragment.listDirectory(currentDir,
991 // MainApp.getOnlyOnDevice());
994 setFile(currentFile
);
997 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
998 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1001 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1003 /// TODO refactor and make common
1004 synchResult
!= null
&& !synchResult
.isSuccess() &&
1005 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1006 synchResult
.isIdPRedirection() ||
1007 (synchResult
.isException() && synchResult
.getException()
1008 instanceof AuthenticatorException
))) {
1012 OwnCloudClient client
;
1013 OwnCloudAccount ocAccount
=
1014 new OwnCloudAccount(getAccount(), context
);
1015 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1016 removeClientFor(ocAccount
));
1018 if (client
!= null
) {
1019 OwnCloudCredentials cred
= client
.getCredentials();
1021 AccountManager am
= AccountManager
.get(context
);
1022 if (cred
.authTokenExpires()) {
1023 am
.invalidateAuthToken(
1028 am
.clearPassword(getAccount());
1032 requestCredentialsUpdate();
1034 } catch (AccountNotFoundException e
) {
1035 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1040 removeStickyBroadcast(intent
);
1041 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1042 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1043 /*|| mRefreshSharesInProgress*/);
1045 setBackgroundText();
1049 if (synchResult
!= null
) {
1050 if (synchResult
.getCode().equals(
1051 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1052 mLastSslUntrustedServerResult
= synchResult
;
1055 } catch (RuntimeException e
) {
1056 // avoid app crashes after changing the serial id of RemoteOperationResult
1057 // in owncloud library with broadcast notifications pending to process
1058 removeStickyBroadcast(intent
);
1064 * Show a text message on screen view for notifying user if content is
1065 * loading or folder is empty
1067 private void setBackgroundText() {
1068 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1069 if (ocFileListFragment
!= null
) {
1070 int message
= R
.string
.file_list_loading
;
1071 if (!mSyncInProgress
) {
1072 // In case file list is empty
1073 message
= R
.string
.file_list_empty
;
1075 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1077 Log_OC
.e(TAG
, "OCFileListFragment is null");
1082 * Once the file upload has finished -> update view
1084 private class UploadFinishReceiver
extends BroadcastReceiver
{
1086 * Once the file upload has finished -> update view
1087 * @author David A. Velasco
1088 * {@link BroadcastReceiver} to enable upload feedback in UI
1091 public void onReceive(Context context
, Intent intent
) {
1093 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1094 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1095 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1096 OCFile currentDir
= getCurrentDir();
1097 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1098 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1100 if (sameAccount
&& isDescendant
) {
1101 refreshListOfFilesFragment();
1104 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1106 boolean renamedInUpload
= getFile().getRemotePath().
1107 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1108 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1110 FileFragment details
= getSecondFragment();
1111 boolean detailFragmentIsShown
= (details
!= null
&&
1112 details
instanceof FileDetailFragment
);
1114 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1115 if (uploadWasFine
) {
1116 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1118 if (renamedInUpload
) {
1119 String newName
= (new File(uploadedRemotePath
)).getName();
1120 Toast msg
= Toast
.makeText(
1123 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1128 if (uploadWasFine
|| getFile().fileExists()) {
1129 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1131 cleanSecondFragment();
1134 // Force the preview if the file is an image
1135 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1136 startImagePreview(getFile());
1137 } // TODO what about other kind of previews?
1141 if (intent
!= null
) {
1142 removeStickyBroadcast(intent
);
1152 * Class waiting for broadcast events from the {@link FileDownloader} service.
1154 * Updates the UI when a download is started or finished, provided that it is relevant for the
1157 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1159 //int refreshCounter = 0;
1161 public void onReceive(Context context
, Intent intent
) {
1163 boolean sameAccount
= isSameAccount(context
, intent
);
1164 String downloadedRemotePath
=
1165 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1166 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1168 if (sameAccount
&& isDescendant
) {
1169 String linkedToRemotePath
=
1170 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1171 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1172 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1173 refreshListOfFilesFragment();
1175 refreshSecondFragment(
1177 downloadedRemotePath
,
1178 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1182 if (mWaitingToSend
!= null
) {
1184 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1185 if (mWaitingToSend
.isDown()) {
1186 sendDownloadedFile();
1191 if (intent
!= null
) {
1192 removeStickyBroadcast(intent
);
1197 private boolean isDescendant(String downloadedRemotePath
) {
1198 OCFile currentDir
= getCurrentDir();
1200 currentDir
!= null
&&
1201 downloadedRemotePath
!= null
&&
1202 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1206 private boolean isAscendant(String linkedToRemotePath
) {
1207 OCFile currentDir
= getCurrentDir();
1209 currentDir
!= null
&&
1210 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1214 private boolean isSameAccount(Context context
, Intent intent
) {
1215 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1216 return (accountName
!= null
&& getAccount() != null
&&
1217 accountName
.equals(getAccount().name
));
1222 public void browseToRoot() {
1223 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1224 if (listOfFiles
!= null
) { // should never be null, indeed
1225 while (mDirectories
.getCount() > 1) {
1228 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1229 listOfFiles
.listDirectory(root
);
1230 // TODO Enable when "On Device" is recovered ?
1231 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1232 setFile(listOfFiles
.getCurrentFile());
1233 startSyncFolderOperation(root
, false
);
1235 cleanSecondFragment();
1239 public void browseTo(OCFile folder
) {
1240 if (folder
== null
|| !folder
.isFolder()) {
1241 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1243 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1244 if (listOfFiles
!= null
) {
1245 setNavigationListWithFolder(folder
);
1246 listOfFiles
.listDirectory(folder
);
1247 // TODO Enable when "On Device" is recovered ?
1248 // listOfFiles.listDirectory(folder, MainApp.getOnlyOnDevice());
1249 setFile(listOfFiles
.getCurrentFile());
1250 startSyncFolderOperation(folder
, false
);
1252 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1254 cleanSecondFragment();
1261 * Updates action bar and second fragment, if in dual pane mode.
1264 public void onBrowsedDownTo(OCFile directory
) {
1265 pushDirname(directory
);
1266 cleanSecondFragment();
1269 startSyncFolderOperation(directory
, false
);
1274 * Shows the information of the {@link OCFile} received as a
1275 * parameter in the second fragment.
1277 * @param file {@link OCFile} whose details will be shown
1280 public void showDetails(OCFile file
) {
1281 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1282 setSecondFragment(detailFragment
);
1283 updateFragmentsVisibility(true
);
1284 updateNavigationElementsInActionBar(file
);
1292 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1293 ActionBar actionBar
= getSupportActionBar();
1295 // For adding content description tag to a title field in the action bar
1296 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1298 if (chosenFile
== null
|| mDualPane
) {
1299 // only list of files - set for browsing through folders
1300 OCFile currentDir
= getCurrentDir();
1301 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1302 // actionBar.setDisplayHomeAsUpEnabled(noRoot);
1303 // actionBar.setDisplayShowTitleEnabled(!noRoot);
1304 actionBar
.setDisplayHomeAsUpEnabled(true
);
1305 actionBar
.setDisplayShowTitleEnabled(true
);
1307 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1308 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1309 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1310 actionBarTitleView
.setContentDescription(
1311 getString(R
.string
.default_display_name_for_root_folder
));
1314 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
:
1315 ActionBar
.NAVIGATION_MODE_LIST
);
1316 actionBar
.setListNavigationCallbacks(mDirectories
, this);
1317 // assuming mDirectories is updated
1320 actionBar
.setDisplayHomeAsUpEnabled(true
);
1321 actionBar
.setDisplayShowTitleEnabled(true
);
1322 actionBar
.setTitle(chosenFile
.getFileName());
1323 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1324 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1325 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1326 getWindow().getDecorView().findViewById(actionBarTitleId
).
1327 setContentDescription(chosenFile
.getFileName());
1334 protected ServiceConnection
newTransferenceServiceConnection() {
1335 return new ListServiceConnection();
1338 /** Defines callbacks for service binding, passed to bindService() */
1339 private class ListServiceConnection
implements ServiceConnection
{
1342 public void onServiceConnected(ComponentName component
, IBinder service
) {
1343 if (component
.equals(new ComponentName(
1344 FileDisplayActivity
.this, FileDownloader
.class))) {
1345 Log_OC
.d(TAG
, "Download service connected");
1346 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1347 if (mWaitingToPreview
!= null
)
1348 if (getStorageManager() != null
) {
1351 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1352 if (!mWaitingToPreview
.isDown()) {
1353 requestForDownload();
1357 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1358 FileUploader
.class))) {
1359 Log_OC
.d(TAG
, "Upload service connected");
1360 mUploaderBinder
= (FileUploaderBinder
) service
;
1364 // a new chance to get the mDownloadBinder through
1365 // getFileDownloadBinder() - THIS IS A MESS
1366 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1367 if (listOfFiles
!= null
) {
1368 listOfFiles
.listDirectory();
1369 // TODO Enable when "On Device" is recovered ?
1370 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1372 FileFragment secondFragment
= getSecondFragment();
1373 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1374 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1375 detailFragment
.listenForTransferProgress();
1376 detailFragment
.updateFileDetails(false
, false
);
1381 public void onServiceDisconnected(ComponentName component
) {
1382 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1383 FileDownloader
.class))) {
1384 Log_OC
.d(TAG
, "Download service disconnected");
1385 mDownloaderBinder
= null
;
1386 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1387 FileUploader
.class))) {
1388 Log_OC
.d(TAG
, "Upload service disconnected");
1389 mUploaderBinder
= null
;
1395 public void onSavedCertificate() {
1396 startSyncFolderOperation(getCurrentDir(), false
);
1401 public void onFailedSavingCertificate() {
1402 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1403 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1405 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1409 public void onCancelCertificate() {
1414 * Updates the view associated to the activity after the finish of some operation over files
1415 * in the current account.
1417 * @param operation Removal operation performed.
1418 * @param result Result of the removal.
1421 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1422 super.onRemoteOperationFinish(operation
, result
);
1424 if (operation
instanceof RemoveFileOperation
) {
1425 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1427 } else if (operation
instanceof RenameFileOperation
) {
1428 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1430 } else if (operation
instanceof SynchronizeFileOperation
) {
1431 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1433 } else if (operation
instanceof CreateFolderOperation
) {
1434 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1436 } else if (operation
instanceof CreateShareOperation
) {
1437 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1439 } else if (operation
instanceof UnshareLinkOperation
) {
1440 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1442 } else if (operation
instanceof MoveFileOperation
) {
1443 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1449 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1450 RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 refreshShowDetails();
1453 refreshListOfFilesFragment();
1458 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1459 RemoteOperationResult result
) {
1460 if (result
.isSuccess()) {
1461 refreshShowDetails();
1462 refreshListOfFilesFragment();
1464 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1465 cleanSecondFragment();
1466 refreshListOfFilesFragment();
1470 private void refreshShowDetails() {
1471 FileFragment details
= getSecondFragment();
1472 if (details
!= null
) {
1473 OCFile file
= details
.getFile();
1475 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1476 if (details
instanceof PreviewMediaFragment
) {
1477 // Refresh OCFile of the fragment
1478 ((PreviewMediaFragment
) details
).updateFile(file
);
1483 invalidateOptionsMenu();
1488 * Updates the view associated to the activity after the finish of an operation trying to
1491 * @param operation Removal operation performed.
1492 * @param result Result of the removal.
1494 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1495 RemoteOperationResult result
) {
1496 dismissLoadingDialog();
1498 Toast msg
= Toast
.makeText(this,
1499 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1503 if (result
.isSuccess()) {
1504 OCFile removedFile
= operation
.getFile();
1505 FileFragment second
= getSecondFragment();
1506 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1507 if (second
instanceof PreviewMediaFragment
) {
1508 ((PreviewMediaFragment
)second
).stopPreview(true
);
1510 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1511 cleanSecondFragment();
1513 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1514 refreshListOfFilesFragment();
1516 invalidateOptionsMenu();
1518 if (result
.isSslRecoverableException()) {
1519 mLastSslUntrustedServerResult
= result
;
1520 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1527 * Updates the view associated to the activity after the finish of an operation trying to move a
1530 * @param operation Move operation performed.
1531 * @param result Result of the move operation.
1533 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1534 RemoteOperationResult result
) {
1535 if (result
.isSuccess()) {
1536 dismissLoadingDialog();
1537 refreshListOfFilesFragment();
1539 dismissLoadingDialog();
1541 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1542 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1546 } catch (NotFoundException e
) {
1547 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1554 * Updates the view associated to the activity after the finish of an operation trying to rename
1557 * @param operation Renaming operation performed.
1558 * @param result Result of the renaming.
1560 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1561 RemoteOperationResult result
) {
1562 dismissLoadingDialog();
1563 OCFile renamedFile
= operation
.getFile();
1564 if (result
.isSuccess()) {
1565 FileFragment details
= getSecondFragment();
1566 if (details
!= null
) {
1567 if (details
instanceof FileDetailFragment
&&
1568 renamedFile
.equals(details
.getFile()) ) {
1569 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1570 showDetails(renamedFile
);
1572 } else if (details
instanceof PreviewMediaFragment
&&
1573 renamedFile
.equals(details
.getFile())) {
1574 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1575 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1576 int position
= ((PreviewMediaFragment
)details
).getPosition();
1577 startMediaPreview(renamedFile
, position
, true
);
1579 getFileOperationsHelper().openFile(renamedFile
);
1584 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1585 refreshListOfFilesFragment();
1589 Toast msg
= Toast
.makeText(this,
1590 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1594 if (result
.isSslRecoverableException()) {
1595 mLastSslUntrustedServerResult
= result
;
1596 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1601 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1602 RemoteOperationResult result
) {
1603 dismissLoadingDialog();
1604 OCFile syncedFile
= operation
.getLocalFile();
1605 if (!result
.isSuccess()) {
1606 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1607 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1608 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1609 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1615 if (operation
.transferWasRequested()) {
1616 onTransferStateChanged(syncedFile
, true
, true
);
1619 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1620 operation
, getResources()), Toast
.LENGTH_LONG
);
1627 * Updates the view associated to the activity after the finish of an operation trying create a
1630 * @param operation Creation operation performed.
1631 * @param result Result of the creation.
1633 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1634 RemoteOperationResult result
) {
1635 if (result
.isSuccess()) {
1636 dismissLoadingDialog();
1637 refreshListOfFilesFragment();
1639 dismissLoadingDialog();
1641 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1642 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1646 } catch (NotFoundException e
) {
1647 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1657 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1658 refreshListOfFilesFragment();
1659 FileFragment details
= getSecondFragment();
1660 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1661 file
.equals(details
.getFile()) ) {
1662 if (downloading
|| uploading
) {
1663 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1665 if (!file
.fileExists()) {
1666 cleanSecondFragment();
1668 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1676 private void requestForDownload() {
1677 Account account
= getAccount();
1678 //if (!mWaitingToPreview.isDownloading()) {
1679 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1680 Intent i
= new Intent(this, FileDownloader
.class);
1681 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1682 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1688 private OCFile
getCurrentDir() {
1689 OCFile file
= getFile();
1691 if (file
.isFolder()) {
1693 } else if (getStorageManager() != null
) {
1694 String parentPath
= file
.getRemotePath().substring(0,
1695 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1696 return getStorageManager().getFileByPath(parentPath
);
1702 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1703 long currentSyncTime
= System
.currentTimeMillis();
1705 mSyncInProgress
= true
;
1707 // perform folder synchronization
1708 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1711 getFileOperationsHelper().isSharedSupported(),
1713 getStorageManager(),
1715 getApplicationContext()
1717 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1719 setSupportProgressBarIndeterminateVisibility(true
);
1721 setBackgroundText();
1725 * Show untrusted cert dialog
1727 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1728 // Show a dialog with the certificate info
1729 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1730 (CertificateCombinedException
) result
.getException());
1731 FragmentManager fm
= getSupportFragmentManager();
1732 FragmentTransaction ft
= fm
.beginTransaction();
1733 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1736 private void requestForDownload(OCFile file
) {
1737 Account account
= getAccount();
1738 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1739 Intent i
= new Intent(this, FileDownloader
.class);
1740 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1741 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1746 private void sendDownloadedFile(){
1747 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1748 mWaitingToSend
= null
;
1753 * Requests the download of the received {@link OCFile} , updates the UI
1754 * to monitor the download progress and prepares the activity to send the file
1755 * when the download finishes.
1757 * @param file {@link OCFile} to download and preview.
1759 public void startDownloadForSending(OCFile file
) {
1760 mWaitingToSend
= file
;
1761 requestForDownload(mWaitingToSend
);
1762 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1763 updateFragmentsVisibility(hasSecondFragment
);
1767 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1769 * @param file Image {@link OCFile} to show.
1771 public void startImagePreview(OCFile file
) {
1772 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1773 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1774 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1775 startActivity(showDetailsIntent
);
1780 * Stars the preview of an already down media {@link OCFile}.
1782 * @param file Media {@link OCFile} to preview.
1783 * @param startPlaybackPosition Media position where the playback will be started,
1785 * @param autoplay When 'true', the playback will start without user
1788 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1789 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1791 setSecondFragment(mediaFragment
);
1792 updateFragmentsVisibility(true
);
1793 updateNavigationElementsInActionBar(file
);
1798 * Requests the download of the received {@link OCFile} , updates the UI
1799 * to monitor the download progress and prepares the activity to preview
1800 * or open the file when the download finishes.
1802 * @param file {@link OCFile} to download and preview.
1804 public void startDownloadForPreview(OCFile file
) {
1805 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1806 setSecondFragment(detailFragment
);
1807 mWaitingToPreview
= file
;
1808 requestForDownload();
1809 updateFragmentsVisibility(true
);
1810 updateNavigationElementsInActionBar(file
);
1815 public void cancelTransference(OCFile file
) {
1816 getFileOperationsHelper().cancelTransference(file
);
1817 if (mWaitingToPreview
!= null
&&
1818 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1819 mWaitingToPreview
= null
;
1821 if (mWaitingToSend
!= null
&&
1822 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1823 mWaitingToSend
= null
;
1825 onTransferStateChanged(file
, false
, false
);
1829 public void onRefresh(boolean ignoreETag
) {
1830 refreshList(ignoreETag
);
1834 public void onRefresh() {
1838 private void refreshList(boolean ignoreETag
) {
1839 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1840 if (listOfFiles
!= null
) {
1841 OCFile folder
= listOfFiles
.getCurrentFile();
1842 if (folder
!= null
) {
1843 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1844 listDirectory(mFile);*/
1845 startSyncFolderOperation(folder
, ignoreETag
);
1850 private void sortByDate(boolean ascending
){
1851 getListOfFilesFragment().sortByDate(ascending
);
1854 private void sortBySize(boolean ascending
){
1855 getListOfFilesFragment().sortBySize(ascending
);
1858 private void sortByName(boolean ascending
){
1859 getListOfFilesFragment().sortByName(ascending
);
1862 // public void restart(){
1863 // Intent i = new Intent(this, FileDisplayActivity.class);
1864 // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1865 // startActivity(i);
1868 // public void closeDrawer() {
1869 // mDrawerLayout.closeDrawers();
1872 // private class DrawerItemClickListener implements ListView.OnItemClickListener {
1874 // public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1875 // if (mShowAccounts && position > 0){
1876 // position = position - 1;
1878 // switch (position){
1879 // case 0: // Accounts
1880 // mShowAccounts = !mShowAccounts;
1881 // mNavigationDrawerAdapter.setShowAccounts(mShowAccounts);
1882 // mNavigationDrawerAdapter.notifyDataSetChanged();
1885 // case 1: // All Files
1886 // // TODO Enable when "On Device" is recovered ?
1887 // //MainApp.showOnlyFilesOnDevice(false);
1888 // mDrawerLayout.closeDrawers();
1891 // // TODO Enable when "On Device" is recovered ?
1893 //// MainApp.showOnlyFilesOnDevice(true);
1894 //// mDrawerLayout.closeDrawers();
1897 // case 2: // Settings
1898 // Intent settingsIntent = new Intent(getApplicationContext(),
1899 // Preferences.class);
1900 // startActivity(settingsIntent);
1904 // Intent loggerIntent = new Intent(getApplicationContext(),
1905 // LogHistoryActivity.class);
1906 // startActivity(loggerIntent);