2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
27 import android
.accounts
.Account
;
28 import android
.accounts
.AccountManager
;
29 import android
.accounts
.AuthenticatorException
;
30 import android
.annotation
.TargetApi
;
31 import android
.app
.AlertDialog
;
32 import android
.content
.BroadcastReceiver
;
33 import android
.content
.ComponentName
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Build
;
46 import android
.os
.Bundle
;
47 import android
.os
.IBinder
;
48 import android
.preference
.PreferenceManager
;
49 import android
.provider
.OpenableColumns
;
50 import android
.support
.v4
.app
.Fragment
;
51 import android
.support
.v4
.app
.FragmentManager
;
52 import android
.support
.v4
.app
.FragmentTransaction
;
53 import android
.support
.v7
.app
.ActionBar
;
54 import android
.view
.Menu
;
55 import android
.view
.MenuInflater
;
56 import android
.view
.MenuItem
;
57 import android
.view
.View
;
58 import android
.view
.ViewGroup
;
59 import android
.view
.Window
;
60 import android
.widget
.ArrayAdapter
;
61 import android
.widget
.TextView
;
62 import android
.widget
.Toast
;
64 import com
.owncloud
.android
.BuildConfig
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
;
69 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
82 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
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
.RefreshFolderOperation
;
89 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.FileStorageUtils
;
107 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";
154 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
);
188 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
189 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
190 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
191 if (savedInstanceState
== null
) {
192 createMinFragments();
196 mDirectories
= new CustomArrayAdapter
<String
>(this,
197 R
.layout
.support_simple_spinner_dropdown_item
);
198 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
199 // according to the official
201 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
202 /*|| mRefreshSharesInProgress*/);
203 // always AFTER setContentView(...) ; to work around bug in its implementation
207 Log_OC
.v(TAG
, "onCreate() end");
211 protected void onStart() {
212 Log_OC
.v(TAG
, "onStart() start");
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 Log_OC
.v(TAG
, "onStart() end");
219 protected void onDestroy() {
220 Log_OC
.v(TAG
, "onDestroy() start");
222 Log_OC
.v(TAG
, "onDestroy() end");
226 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
229 protected void onAccountSet(boolean stateWasRecovered
) {
230 super.onAccountSet(stateWasRecovered
);
231 if (getAccount() != null
) {
232 /// Check whether the 'main' OCFile handled by the Activity is contained in the
234 OCFile file
= getFile();
235 // get parent from path
236 String parentPath
= "";
238 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
239 // upload in progress - right now, files are not inserted in the local
240 // cache until the upload is successful get parent from path
241 parentPath
= file
.getRemotePath().substring(0,
242 file
.getRemotePath().lastIndexOf(file
.getFileName()));
243 if (getStorageManager().getFileByPath(parentPath
) == null
)
244 file
= null
; // not able to know the directory where the file is uploading
246 file
= getStorageManager().getFileByPath(file
.getRemotePath());
247 // currentDir = null if not in the current Account
251 // fall back to root folder
252 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
255 setNavigationListWithFolder(file
);
257 if (!stateWasRecovered
) {
258 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
259 initFragmentsWithFile();
260 if (file
.isFolder()) {
261 startSyncFolderOperation(file
, false
);
265 updateFragmentsVisibility(!file
.isFolder());
266 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
272 private void setNavigationListWithFolder(OCFile file
) {
273 mDirectories
.clear();
274 OCFile fileIt
= file
;
276 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
277 if (fileIt
.isFolder()) {
278 mDirectories
.add(fileIt
.getFileName());
280 // get parent from path
281 parentPath
= fileIt
.getRemotePath().substring(0,
282 fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
283 fileIt
= getStorageManager().getFileByPath(parentPath
);
285 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
303 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
307 OCFile file
= getFile();
308 Fragment secondFragment
= chooseInitialSecondFragment(file
);
309 if (secondFragment
!= null
) {
310 setSecondFragment(secondFragment
);
311 updateFragmentsVisibility(true
);
312 updateNavigationElementsInActionBar(file
);
315 cleanSecondFragment();
319 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null
) {
321 Log_OC
.wtf(TAG
, "\t account is NULL");
323 if (getFile() == null
) {
324 Log_OC
.wtf(TAG
, "\t file is NULL");
329 private Fragment
chooseInitialSecondFragment(OCFile file
) {
330 Fragment secondFragment
= null
;
331 if (file
!= null
&& !file
.isFolder()) {
332 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
333 && file
.getLastSyncDateForProperties() > 0 // temporal fix
335 int startPlaybackPosition
=
336 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
338 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
339 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
340 startPlaybackPosition
, autoplay
);
343 secondFragment
= new FileDetailFragment(file
, getAccount());
346 return secondFragment
;
351 * Replaces the second fragment managed by the activity with the received as
354 * Assumes never will be more than two fragments managed at the same time.
356 * @param fragment New second Fragment to set.
358 private void setSecondFragment(Fragment fragment
) {
359 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
360 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
361 transaction
.commit();
365 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
367 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 } else if (existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
376 mLeftFragmentContainer
.setVisibility(View
.GONE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
384 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
387 mRightFragmentContainer
.setVisibility(View
.GONE
);
393 private OCFileListFragment
getListOfFilesFragment() {
394 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
395 FileDisplayActivity
.TAG_LIST_OF_FILES
);
396 if (listOfFiles
!= null
) {
397 return (OCFileListFragment
)listOfFiles
;
399 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
403 public FileFragment
getSecondFragment() {
404 Fragment second
= getSupportFragmentManager().findFragmentByTag(
405 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
406 if (second
!= null
) {
407 return (FileFragment
)second
;
412 protected void cleanSecondFragment() {
413 Fragment second
= getSecondFragment();
414 if (second
!= null
) {
415 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
419 updateFragmentsVisibility(false
);
420 updateNavigationElementsInActionBar(null
);
423 protected void refreshListOfFilesFragment() {
424 OCFileListFragment fileListFragment
= getListOfFilesFragment();
425 if (fileListFragment
!= null
) {
426 fileListFragment
.listDirectory();
430 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
432 FileFragment secondFragment
= getSecondFragment();
433 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
434 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
435 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
436 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
437 OCFile fileInFragment
= detailsFragment
.getFile();
438 if (fileInFragment
!= null
&&
439 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
440 // the user browsed to other file ; forget the automatic preview
441 mWaitingToPreview
= null
;
443 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
444 // grant that the right panel updates the progress bar
445 detailsFragment
.listenForTransferProgress();
446 detailsFragment
.updateFileDetails(true
, false
);
448 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
449 // update the right panel
450 boolean detailsFragmentChanged
= false
;
453 mWaitingToPreview
= getStorageManager().getFileById(
454 mWaitingToPreview
.getFileId()); // update the file from database,
455 // for the local storage path
456 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
457 startMediaPreview(mWaitingToPreview
, 0, true
);
458 detailsFragmentChanged
= true
;
460 getFileOperationsHelper().openFile(mWaitingToPreview
);
463 mWaitingToPreview
= null
;
465 if (!detailsFragmentChanged
) {
466 detailsFragment
.updateFileDetails(false
, (success
));
473 public boolean onPrepareOptionsMenu(Menu menu
) {
474 if (BuildConfig
.DEBUG
) {
475 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
477 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
479 return super.onPrepareOptionsMenu(menu
);
483 public boolean onCreateOptionsMenu(Menu menu
) {
484 MenuInflater inflater
= getMenuInflater();
485 inflater
.inflate(R
.menu
.main_menu
, menu
);
490 public boolean onOptionsItemSelected(MenuItem item
) {
491 boolean retval
= true
;
492 switch (item
.getItemId()) {
493 case R
.id
.action_create_dir
: {
494 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
495 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
498 case R
.id
.action_sync_account
: {
499 startSynchronization();
502 case R
.id
.action_upload
: {
503 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
504 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
508 case R
.id
.action_settings
: {
509 Intent settingsIntent
= new Intent(this, Preferences
.class);
510 startActivity(settingsIntent
);
513 case R
.id
.action_logger
: {
514 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
515 startActivity(loggerIntent
);
518 case android
.R
.id
.home
: {
519 FileFragment second
= getSecondFragment();
520 OCFile currentDir
= getCurrentDir();
521 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
522 (second
!= null
&& second
.getFile() != null
)) {
528 case R
.id
.action_sort
: {
529 SharedPreferences appPreferences
= PreferenceManager
530 .getDefaultSharedPreferences(this);
532 // Read sorting order, default to sort by name ascending
533 Integer sortOrder
= appPreferences
534 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
536 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
537 builder
.setTitle(R
.string
.actionbar_sort_title
)
538 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
539 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
), Toast
.LENGTH_LONG
);
697 private void requestSimpleUpload(Intent data
, int resultCode
) {
698 String filePath
= null
;
699 String mimeType
= null
;
701 Uri selectedImageUri
= data
.getData();
704 mimeType
= getContentResolver().getType(selectedImageUri
);
706 String fileManagerString
= selectedImageUri
.getPath();
707 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
709 if (selectedImagePath
!= null
)
710 filePath
= selectedImagePath
;
712 filePath
= fileManagerString
;
714 } catch (Exception e
) {
715 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
716 "Intent.ACTION_GET_CONTENT", e
);
719 if (filePath
== null
) {
720 Log_OC
.e(TAG
, "Couldn't resolve path to file");
721 Toast t
= Toast
.makeText(
722 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
730 Intent i
= new Intent(this, FileUploader
.class);
731 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
732 OCFile currentDir
= getCurrentDir();
733 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
735 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
736 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
738 if (cursor
!= null
&& cursor
.moveToFirst()) {
739 String displayName
= cursor
.getString(cursor
.getColumnIndex(
740 OpenableColumns
.DISPLAY_NAME
));
741 Log_OC
.v(TAG
, "Display Name: " + displayName
);
743 displayName
.replace(File
.separatorChar
, '_');
744 displayName
.replace(File
.pathSeparatorChar
, '_');
745 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
748 // and what happens in case of error?; wrong target name for the upload
754 remotePath
+= new File(filePath
).getName();
757 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
758 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
759 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
760 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
761 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
762 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
767 * Request the operation for moving the file/folder from one path to another
769 * @param data Intent received
770 * @param resultCode Result code received
772 private void requestMoveOperation(Intent data
, int resultCode
) {
773 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
774 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
775 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
779 public void onBackPressed() {
780 OCFileListFragment listOfFiles
= getListOfFilesFragment();
781 if (mDualPane
|| getSecondFragment() == null
) {
782 if (listOfFiles
!= null
) { // should never be null, indeed
783 if (mDirectories
.getCount() <= 1) {
787 int levelsUp
= listOfFiles
.onBrowseUp();
788 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
793 if (listOfFiles
!= null
) { // should never be null, indeed
794 setFile(listOfFiles
.getCurrentFile());
796 cleanSecondFragment();
801 protected void onSaveInstanceState(Bundle outState
) {
802 // responsibility of restore is preferred in onCreate() before than in
803 // onRestoreInstanceState when there are Fragments involved
804 Log_OC
.v(TAG
, "onSaveInstanceState() start");
805 super.onSaveInstanceState(outState
);
806 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
807 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
808 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
809 // mRefreshSharesInProgress);
810 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
812 Log_OC
.v(TAG
, "onSaveInstanceState() end");
818 protected void onResume() {
819 Log_OC
.v(TAG
, "onResume() start");
822 // refresh list of files
823 refreshListOfFilesFragment();
825 // Listen for sync messages
826 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
827 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
828 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
829 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
830 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
831 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
832 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
833 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
834 // syncIntentFilter);
836 // Listen for upload messages
837 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
838 mUploadFinishReceiver
= new UploadFinishReceiver();
839 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
841 // Listen for download messages
842 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
843 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
844 mDownloadFinishReceiver
= new DownloadFinishReceiver();
845 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
847 Log_OC
.v(TAG
, "onResume() end");
852 protected void onPause() {
853 Log_OC
.v(TAG
, "onPause() start");
854 if (mSyncBroadcastReceiver
!= null
) {
855 unregisterReceiver(mSyncBroadcastReceiver
);
856 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
857 mSyncBroadcastReceiver
= null
;
859 if (mUploadFinishReceiver
!= null
) {
860 unregisterReceiver(mUploadFinishReceiver
);
861 mUploadFinishReceiver
= null
;
863 if (mDownloadFinishReceiver
!= null
) {
864 unregisterReceiver(mDownloadFinishReceiver
);
865 mDownloadFinishReceiver
= null
;
869 Log_OC
.v(TAG
, "onPause() end");
873 * Pushes a directory to the drop down list
874 * @param directory to push
875 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
877 public void pushDirname(OCFile directory
) {
878 if(!directory
.isFolder()){
879 throw new IllegalArgumentException("Only directories may be pushed!");
881 mDirectories
.insert(directory
.getFileName(), 0);
886 * Pops a directory name from the drop down list
887 * @return True, unless the stack is empty
889 public boolean popDirname() {
890 mDirectories
.remove(mDirectories
.getItem(0));
891 return !mDirectories
.isEmpty();
894 // Custom array adapter to override text colors
895 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
897 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
901 public View
getView(int position
, View convertView
, ViewGroup parent
) {
902 View v
= super.getView(position
, convertView
, parent
);
904 ((TextView
) v
).setTextColor(getResources().getColorStateList(
905 android
.R
.color
.white
));
907 fixRoot((TextView
) v
);
911 public View
getDropDownView(int position
, View convertView
,
913 View v
= super.getDropDownView(position
, convertView
, parent
);
915 ((TextView
) v
).setTextColor(getResources().getColorStateList(
916 android
.R
.color
.white
));
918 fixRoot((TextView
) v
);
922 private void fixRoot(TextView v
) {
923 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
924 v
.setText(R
.string
.default_display_name_for_root_folder
);
930 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
933 * {@link BroadcastReceiver} to enable syncing feedback in UI
936 public void onReceive(Context context
, Intent intent
) {
938 String event
= intent
.getAction();
939 Log_OC
.d(TAG
, "Received broadcast " + event
);
940 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
941 String synchFolderRemotePath
=
942 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
943 RemoteOperationResult synchResult
=
944 (RemoteOperationResult
)intent
.getSerializableExtra(
945 FileSyncAdapter
.EXTRA_RESULT
);
946 boolean sameAccount
= (getAccount() != null
&&
947 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
951 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
952 mSyncInProgress
= true
;
955 OCFile currentFile
= (getFile() == null
) ? null
:
956 getStorageManager().getFileByPath(getFile().getRemotePath());
957 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
958 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
960 if (currentDir
== null
) {
961 // current folder was removed from the server
962 Toast
.makeText( FileDisplayActivity
.this,
963 String
.format(getString(R
.string
.sync_current_folder_was_removed
),
964 mDirectories
.getItem(0)),
970 if (currentFile
== null
&& !getFile().isFolder()) {
971 // currently selected file was removed in the server, and now we know it
972 cleanSecondFragment();
973 currentFile
= currentDir
;
976 if (synchFolderRemotePath
!= null
&&
977 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
978 OCFileListFragment fileListFragment
= getListOfFilesFragment();
979 if (fileListFragment
!= null
) {
980 fileListFragment
.listDirectory(currentDir
);
983 setFile(currentFile
);
986 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
987 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
989 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
991 /// TODO refactor and make common
992 synchResult
!= null
&& !synchResult
.isSuccess() &&
993 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
994 synchResult
.isIdPRedirection() ||
995 (synchResult
.isException() && synchResult
.getException()
996 instanceof AuthenticatorException
))) {
1000 OwnCloudClient client
;
1001 OwnCloudAccount ocAccount
=
1002 new OwnCloudAccount(getAccount(), context
);
1003 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1004 removeClientFor(ocAccount
));
1006 if (client
!= null
) {
1007 OwnCloudCredentials cred
= client
.getCredentials();
1009 AccountManager am
= AccountManager
.get(context
);
1010 if (cred
.authTokenExpires()) {
1011 am
.invalidateAuthToken(
1016 am
.clearPassword(getAccount());
1020 requestCredentialsUpdate();
1022 } catch (AccountNotFoundException e
) {
1023 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1028 removeStickyBroadcast(intent
);
1029 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1030 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1031 /*|| mRefreshSharesInProgress*/);
1033 setBackgroundText();
1037 if (synchResult
!= null
) {
1038 if (synchResult
.getCode().equals(
1039 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1040 mLastSslUntrustedServerResult
= synchResult
;
1043 } catch (RuntimeException e
) {
1044 // avoid app crashes after changing the serial id of RemoteOperationResult
1045 // in owncloud library with broadcast notifications pending to process
1046 removeStickyBroadcast(intent
);
1052 * Show a text message on screen view for notifying user if content is
1053 * loading or folder is empty
1055 private void setBackgroundText() {
1056 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1057 if (ocFileListFragment
!= null
) {
1058 int message
= R
.string
.file_list_loading
;
1059 if (!mSyncInProgress
) {
1060 // In case file list is empty
1061 message
= R
.string
.file_list_empty
;
1063 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1065 Log_OC
.e(TAG
, "OCFileListFragment is null");
1070 * Once the file upload has finished -> update view
1072 private class UploadFinishReceiver
extends BroadcastReceiver
{
1074 * Once the file upload has finished -> update view
1075 * @author David A. Velasco
1076 * {@link BroadcastReceiver} to enable upload feedback in UI
1079 public void onReceive(Context context
, Intent intent
) {
1081 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1082 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1083 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1084 OCFile currentDir
= getCurrentDir();
1085 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1086 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1088 if (sameAccount
&& isDescendant
) {
1089 refreshListOfFilesFragment();
1092 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1094 boolean renamedInUpload
= getFile().getRemotePath().
1095 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1096 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1098 FileFragment details
= getSecondFragment();
1099 boolean detailFragmentIsShown
= (details
!= null
&&
1100 details
instanceof FileDetailFragment
);
1102 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1103 if (uploadWasFine
) {
1104 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1106 if (renamedInUpload
) {
1107 String newName
= (new File(uploadedRemotePath
)).getName();
1108 Toast msg
= Toast
.makeText(
1111 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1116 if (uploadWasFine
|| getFile().fileExists()) {
1117 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1119 cleanSecondFragment();
1122 // Force the preview if the file is an image
1123 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1124 startImagePreview(getFile());
1125 } // TODO what about other kind of previews?
1129 if (intent
!= null
) {
1130 removeStickyBroadcast(intent
);
1140 * Class waiting for broadcast events from the {@link FileDownloader} service.
1142 * Updates the UI when a download is started or finished, provided that it is relevant for the
1145 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1147 //int refreshCounter = 0;
1149 public void onReceive(Context context
, Intent intent
) {
1151 boolean sameAccount
= isSameAccount(context
, intent
);
1152 String downloadedRemotePath
=
1153 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1154 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1156 if (sameAccount
&& isDescendant
) {
1157 String linkedToRemotePath
=
1158 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1159 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1160 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1161 refreshListOfFilesFragment();
1163 refreshSecondFragment(
1165 downloadedRemotePath
,
1166 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1170 if (mWaitingToSend
!= null
) {
1172 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1173 if (mWaitingToSend
.isDown()) {
1174 sendDownloadedFile();
1179 if (intent
!= null
) {
1180 removeStickyBroadcast(intent
);
1185 private boolean isDescendant(String downloadedRemotePath
) {
1186 OCFile currentDir
= getCurrentDir();
1188 currentDir
!= null
&&
1189 downloadedRemotePath
!= null
&&
1190 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1194 private boolean isAscendant(String linkedToRemotePath
) {
1195 OCFile currentDir
= getCurrentDir();
1197 currentDir
!= null
&&
1198 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1202 private boolean isSameAccount(Context context
, Intent intent
) {
1203 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1204 return (accountName
!= null
&& getAccount() != null
&&
1205 accountName
.equals(getAccount().name
));
1210 public void browseToRoot() {
1211 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1212 if (listOfFiles
!= null
) { // should never be null, indeed
1213 while (mDirectories
.getCount() > 1) {
1216 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1217 listOfFiles
.listDirectory(root
);
1218 setFile(listOfFiles
.getCurrentFile());
1219 startSyncFolderOperation(root
, false
);
1221 cleanSecondFragment();
1225 public void browseTo(OCFile folder
) {
1226 if (folder
== null
|| !folder
.isFolder()) {
1227 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1229 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1230 if (listOfFiles
!= null
) {
1231 setNavigationListWithFolder(folder
);
1232 listOfFiles
.listDirectory(folder
);
1233 setFile(listOfFiles
.getCurrentFile());
1234 startSyncFolderOperation(folder
, false
);
1236 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1238 cleanSecondFragment();
1245 * Updates action bar and second fragment, if in dual pane mode.
1248 public void onBrowsedDownTo(OCFile directory
) {
1249 pushDirname(directory
);
1250 cleanSecondFragment();
1253 startSyncFolderOperation(directory
, false
);
1258 * Shows the information of the {@link OCFile} received as a
1259 * parameter in the second fragment.
1261 * @param file {@link OCFile} whose details will be shown
1264 public void showDetails(OCFile file
) {
1265 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1266 setSecondFragment(detailFragment
);
1267 updateFragmentsVisibility(true
);
1268 updateNavigationElementsInActionBar(file
);
1276 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1277 ActionBar actionBar
= getSupportActionBar();
1279 // For adding content description tag to a title field in the action bar
1280 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1282 if (chosenFile
== null
|| mDualPane
) {
1283 // only list of files - set for browsing through folders
1284 OCFile currentDir
= getCurrentDir();
1285 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1286 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1287 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1289 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1290 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1291 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1292 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1295 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
:
1296 ActionBar
.NAVIGATION_MODE_LIST
);
1297 actionBar
.setListNavigationCallbacks(mDirectories
, this);
1298 // assuming mDirectories is updated
1301 actionBar
.setDisplayHomeAsUpEnabled(true
);
1302 actionBar
.setDisplayShowTitleEnabled(true
);
1303 actionBar
.setTitle(chosenFile
.getFileName());
1304 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1305 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1306 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1307 getWindow().getDecorView().findViewById(actionBarTitleId
).
1308 setContentDescription(chosenFile
.getFileName());
1315 protected ServiceConnection
newTransferenceServiceConnection() {
1316 return new ListServiceConnection();
1319 /** Defines callbacks for service binding, passed to bindService() */
1320 private class ListServiceConnection
implements ServiceConnection
{
1323 public void onServiceConnected(ComponentName component
, IBinder service
) {
1324 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1325 Log_OC
.d(TAG
, "Download service connected");
1326 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1327 if (mWaitingToPreview
!= null
)
1328 if (getStorageManager() != null
) {
1331 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1332 if (!mWaitingToPreview
.isDown()) {
1333 requestForDownload();
1337 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1338 FileUploader
.class))) {
1339 Log_OC
.d(TAG
, "Upload service connected");
1340 mUploaderBinder
= (FileUploaderBinder
) service
;
1344 // a new chance to get the mDownloadBinder through
1345 // getFileDownloadBinder() - THIS IS A MESS
1346 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1347 if (listOfFiles
!= null
) {
1348 listOfFiles
.listDirectory();
1350 FileFragment secondFragment
= getSecondFragment();
1351 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1352 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1353 detailFragment
.listenForTransferProgress();
1354 detailFragment
.updateFileDetails(false
, false
);
1359 public void onServiceDisconnected(ComponentName component
) {
1360 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1361 FileDownloader
.class))) {
1362 Log_OC
.d(TAG
, "Download service disconnected");
1363 mDownloaderBinder
= null
;
1364 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1365 FileUploader
.class))) {
1366 Log_OC
.d(TAG
, "Upload service disconnected");
1367 mUploaderBinder
= null
;
1373 public void onSavedCertificate() {
1374 startSyncFolderOperation(getCurrentDir(), false
);
1379 public void onFailedSavingCertificate() {
1380 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1381 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1383 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1387 public void onCancelCertificate() {
1392 * Updates the view associated to the activity after the finish of some operation over files
1393 * in the current account.
1395 * @param operation Removal operation performed.
1396 * @param result Result of the removal.
1399 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1400 super.onRemoteOperationFinish(operation
, result
);
1402 if (operation
instanceof RemoveFileOperation
) {
1403 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1405 } else if (operation
instanceof RenameFileOperation
) {
1406 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1408 } else if (operation
instanceof SynchronizeFileOperation
) {
1409 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1411 } else if (operation
instanceof CreateFolderOperation
) {
1412 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1414 } else if (operation
instanceof CreateShareOperation
) {
1415 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1417 } else if (operation
instanceof UnshareLinkOperation
) {
1418 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1420 } else if (operation
instanceof MoveFileOperation
) {
1421 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1427 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1428 RemoteOperationResult result
) {
1429 if (result
.isSuccess()) {
1430 refreshShowDetails();
1431 refreshListOfFilesFragment();
1436 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1437 RemoteOperationResult result
) {
1438 if (result
.isSuccess()) {
1439 refreshShowDetails();
1440 refreshListOfFilesFragment();
1442 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1443 cleanSecondFragment();
1444 refreshListOfFilesFragment();
1448 private void refreshShowDetails() {
1449 FileFragment details
= getSecondFragment();
1450 if (details
!= null
) {
1451 OCFile file
= details
.getFile();
1453 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1454 if (details
instanceof PreviewMediaFragment
) {
1455 // Refresh OCFile of the fragment
1456 ((PreviewMediaFragment
) details
).updateFile(file
);
1461 invalidateOptionsMenu();
1466 * Updates the view associated to the activity after the finish of an operation trying to
1469 * @param operation Removal operation performed.
1470 * @param result Result of the removal.
1472 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1473 RemoteOperationResult result
) {
1474 dismissLoadingDialog();
1476 Toast msg
= Toast
.makeText(this,
1477 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1481 if (result
.isSuccess()) {
1482 OCFile removedFile
= operation
.getFile();
1483 FileFragment second
= getSecondFragment();
1484 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1485 if (second
instanceof PreviewMediaFragment
) {
1486 ((PreviewMediaFragment
)second
).stopPreview(true
);
1488 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1489 cleanSecondFragment();
1491 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1492 refreshListOfFilesFragment();
1494 invalidateOptionsMenu();
1496 if (result
.isSslRecoverableException()) {
1497 mLastSslUntrustedServerResult
= result
;
1498 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1505 * Updates the view associated to the activity after the finish of an operation trying to move a
1508 * @param operation Move operation performed.
1509 * @param result Result of the move operation.
1511 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1512 RemoteOperationResult result
) {
1513 if (result
.isSuccess()) {
1514 dismissLoadingDialog();
1515 refreshListOfFilesFragment();
1517 dismissLoadingDialog();
1519 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1520 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1524 } catch (NotFoundException e
) {
1525 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1532 * Updates the view associated to the activity after the finish of an operation trying to rename
1535 * @param operation Renaming operation performed.
1536 * @param result Result of the renaming.
1538 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1539 RemoteOperationResult result
) {
1540 dismissLoadingDialog();
1541 OCFile renamedFile
= operation
.getFile();
1542 if (result
.isSuccess()) {
1543 FileFragment details
= getSecondFragment();
1544 if (details
!= null
) {
1545 if (details
instanceof FileDetailFragment
&&
1546 renamedFile
.equals(details
.getFile()) ) {
1547 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1548 showDetails(renamedFile
);
1550 } else if (details
instanceof PreviewMediaFragment
&&
1551 renamedFile
.equals(details
.getFile())) {
1552 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1553 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1554 int position
= ((PreviewMediaFragment
)details
).getPosition();
1555 startMediaPreview(renamedFile
, position
, true
);
1557 getFileOperationsHelper().openFile(renamedFile
);
1562 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1563 refreshListOfFilesFragment();
1567 Toast msg
= Toast
.makeText(this,
1568 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1572 if (result
.isSslRecoverableException()) {
1573 mLastSslUntrustedServerResult
= result
;
1574 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1579 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1580 RemoteOperationResult result
) {
1581 dismissLoadingDialog();
1582 OCFile syncedFile
= operation
.getLocalFile();
1583 if (!result
.isSuccess()) {
1584 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1585 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1586 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1587 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1593 if (operation
.transferWasRequested()) {
1594 onTransferStateChanged(syncedFile
, true
, true
);
1597 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
,
1598 operation
, getResources()), Toast
.LENGTH_LONG
);
1605 * Updates the view associated to the activity after the finish of an operation trying create a
1608 * @param operation Creation operation performed.
1609 * @param result Result of the creation.
1611 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1612 RemoteOperationResult result
) {
1613 if (result
.isSuccess()) {
1614 dismissLoadingDialog();
1615 refreshListOfFilesFragment();
1617 dismissLoadingDialog();
1619 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1620 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1624 } catch (NotFoundException e
) {
1625 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1635 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1636 refreshListOfFilesFragment();
1637 FileFragment details
= getSecondFragment();
1638 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1639 file
.equals(details
.getFile()) ) {
1640 if (downloading
|| uploading
) {
1641 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1643 if (!file
.fileExists()) {
1644 cleanSecondFragment();
1646 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1654 private void requestForDownload() {
1655 Account account
= getAccount();
1656 //if (!mWaitingToPreview.isDownloading()) {
1657 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1658 Intent i
= new Intent(this, FileDownloader
.class);
1659 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1660 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1666 private OCFile
getCurrentDir() {
1667 OCFile file
= getFile();
1669 if (file
.isFolder()) {
1671 } else if (getStorageManager() != null
) {
1672 String parentPath
= file
.getRemotePath().substring(0,
1673 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1674 return getStorageManager().getFileByPath(parentPath
);
1680 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1681 long currentSyncTime
= System
.currentTimeMillis();
1683 mSyncInProgress
= true
;
1685 // perform folder synchronization
1686 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1689 getFileOperationsHelper().isSharedSupported(),
1691 getStorageManager(),
1693 getApplicationContext()
1695 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1697 setSupportProgressBarIndeterminateVisibility(true
);
1699 setBackgroundText();
1703 * Show untrusted cert dialog
1705 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1706 // Show a dialog with the certificate info
1707 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1708 (CertificateCombinedException
)result
.getException());
1709 FragmentManager fm
= getSupportFragmentManager();
1710 FragmentTransaction ft
= fm
.beginTransaction();
1711 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1714 private void requestForDownload(OCFile file
) {
1715 Account account
= getAccount();
1716 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1717 Intent i
= new Intent(this, FileDownloader
.class);
1718 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1719 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1724 private void sendDownloadedFile(){
1725 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1726 mWaitingToSend
= null
;
1731 * Requests the download of the received {@link OCFile} , updates the UI
1732 * to monitor the download progress and prepares the activity to send the file
1733 * when the download finishes.
1735 * @param file {@link OCFile} to download and preview.
1737 public void startDownloadForSending(OCFile file
) {
1738 mWaitingToSend
= file
;
1739 requestForDownload(mWaitingToSend
);
1740 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1741 updateFragmentsVisibility(hasSecondFragment
);
1745 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1747 * @param file Image {@link OCFile} to show.
1749 public void startImagePreview(OCFile file
) {
1750 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1751 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1752 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1753 startActivity(showDetailsIntent
);
1758 * Stars the preview of an already down media {@link OCFile}.
1760 * @param file Media {@link OCFile} to preview.
1761 * @param startPlaybackPosition Media position where the playback will be started,
1763 * @param autoplay When 'true', the playback will start without user
1766 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1767 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1769 setSecondFragment(mediaFragment
);
1770 updateFragmentsVisibility(true
);
1771 updateNavigationElementsInActionBar(file
);
1776 * Requests the download of the received {@link OCFile} , updates the UI
1777 * to monitor the download progress and prepares the activity to preview
1778 * or open the file when the download finishes.
1780 * @param file {@link OCFile} to download and preview.
1782 public void startDownloadForPreview(OCFile file
) {
1783 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1784 setSecondFragment(detailFragment
);
1785 mWaitingToPreview
= file
;
1786 requestForDownload();
1787 updateFragmentsVisibility(true
);
1788 updateNavigationElementsInActionBar(file
);
1793 public void cancelTransference(OCFile file
) {
1794 getFileOperationsHelper().cancelTransference(file
);
1795 if (mWaitingToPreview
!= null
&&
1796 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1797 mWaitingToPreview
= null
;
1799 if (mWaitingToSend
!= null
&&
1800 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1801 mWaitingToSend
= null
;
1803 onTransferStateChanged(file
, false
, false
);
1807 public void onRefresh(boolean ignoreETag
) {
1808 refreshList(ignoreETag
);
1812 public void onRefresh() {
1816 private void refreshList(boolean ignoreETag
) {
1817 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1818 if (listOfFiles
!= null
) {
1819 OCFile folder
= listOfFiles
.getCurrentFile();
1820 if (folder
!= null
) {
1821 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1822 listDirectory(mFile);*/
1823 startSyncFolderOperation(folder
, ignoreETag
);
1828 private void sortByDate(boolean ascending
){
1829 getListOfFilesFragment().sortByDate(ascending
);
1832 private void sortBySize(boolean ascending
){
1833 getListOfFilesFragment().sortBySize(ascending
);
1836 private void sortByName(boolean ascending
){
1837 getListOfFilesFragment().sortByName(ascending
);