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
.app
.Dialog
;
33 import android
.app
.ProgressDialog
;
34 import android
.content
.BroadcastReceiver
;
35 import android
.content
.ComponentName
;
36 import android
.content
.ContentResolver
;
37 import android
.content
.Context
;
38 import android
.content
.DialogInterface
;
39 import android
.content
.Intent
;
40 import android
.content
.IntentFilter
;
41 import android
.content
.ServiceConnection
;
42 import android
.content
.SharedPreferences
;
43 import android
.content
.SyncRequest
;
44 import android
.content
.res
.Resources
.NotFoundException
;
45 import android
.database
.Cursor
;
46 import android
.net
.Uri
;
47 import android
.os
.Build
;
48 import android
.os
.Bundle
;
49 import android
.os
.IBinder
;
50 import android
.preference
.PreferenceManager
;
51 import android
.provider
.OpenableColumns
;
52 import android
.support
.v4
.app
.Fragment
;
53 import android
.support
.v4
.app
.FragmentManager
;
54 import android
.support
.v4
.app
.FragmentTransaction
;
55 import android
.view
.View
;
56 import android
.view
.ViewGroup
;
57 import android
.widget
.ArrayAdapter
;
58 import android
.widget
.TextView
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.ActionBar
;
62 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
63 import com
.actionbarsherlock
.view
.Menu
;
64 import com
.actionbarsherlock
.view
.MenuInflater
;
65 import com
.actionbarsherlock
.view
.MenuItem
;
66 import com
.actionbarsherlock
.view
.Window
;
67 import com
.owncloud
.android
.BuildConfig
;
68 import com
.owncloud
.android
.MainApp
;
69 import com
.owncloud
.android
.R
;
70 import com
.owncloud
.android
.datamodel
.OCFile
;
71 import com
.owncloud
.android
.files
.services
.FileDownloader
;
72 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
75 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
76 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
79 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
80 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
85 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
86 import com
.owncloud
.android
.operations
.CreateShareOperation
;
87 import com
.owncloud
.android
.operations
.MoveFileOperation
;
88 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
89 import com
.owncloud
.android
.operations
.RenameFileOperation
;
90 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
91 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
92 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
93 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
94 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
95 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
96 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
97 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
98 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
100 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
101 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
106 import com
.owncloud
.android
.utils
.DisplayUtils
;
107 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
108 import com
.owncloud
.android
.utils
.FileStorageUtils
;
109 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
implements
117 FileFragment
.ContainerActivity
, OnNavigationListener
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private ArrayAdapter
<String
> mDirectories
;
122 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 private DownloadFinishReceiver mDownloadFinishReceiver
;
125 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
127 private boolean mDualPane
;
128 private View mLeftFragmentContainer
;
129 private View mRightFragmentContainer
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final int DIALOG_SHORT_WAIT
= 0;
136 private static final int DIALOG_CERT_NOT_SAVED
= 2;
138 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
140 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
141 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
142 public static final int ACTION_MOVE_FILES
= 3;
144 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
146 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
147 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
149 private OCFile mWaitingToPreview
;
151 private boolean mSyncInProgress
= false
;
153 private static String DIALOG_UNTRUSTED_CERT
= "untrustedCertDialog";
155 private OCFile mWaitingToSend
;
158 protected void onCreate(Bundle savedInstanceState
) {
159 Log_OC
.d(TAG
, "onCreate() start");
160 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
164 // PIN CODE request ; best location is to decide, let's try this first
165 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
167 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
171 /// grant that FileObserverService is watching favourite files
172 if (savedInstanceState
== null
) {
173 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
174 startService(initObserversIntent
);
177 /// Load of saved instance state
178 if(savedInstanceState
!= null
) {
179 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
180 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
181 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
184 mWaitingToPreview
= null
;
185 mSyncInProgress
= false
;
186 mWaitingToSend
= null
;
191 // Inflate and set the layout view
192 setContentView(R
.layout
.files
);
193 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
194 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
195 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
196 if (savedInstanceState
== null
) {
197 createMinFragments();
201 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
202 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
203 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
207 Log_OC
.d(TAG
, "onCreate() end");
211 protected void onStart() {
212 Log_OC
.d(TAG
, "onStart() start");
214 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
215 Log_OC
.d(TAG
, "onStart() end");
219 protected void onDestroy() {
224 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
227 protected void onAccountSet(boolean stateWasRecovered
) {
228 super.onAccountSet(stateWasRecovered
);
229 if (getAccount() != null
) {
230 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
231 OCFile file
= getFile();
232 // get parent from path
233 String parentPath
= "";
235 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
236 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
237 // get parent from path
238 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
239 if (getStorageManager().getFileByPath(parentPath
) == null
)
240 file
= null
; // not able to know the directory where the file is uploading
242 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
246 // fall back to root folder
247 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
250 setNavigationListWithFolder(file
);
252 if (!stateWasRecovered
) {
253 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
254 initFragmentsWithFile();
255 if (file
.isFolder()) {
256 startSyncFolderOperation(file
, false
);
260 updateFragmentsVisibility(!file
.isFolder());
261 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
267 private void setNavigationListWithFolder(OCFile file
) {
268 mDirectories
.clear();
269 OCFile fileIt
= file
;
271 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
272 if (fileIt
.isFolder()) {
273 mDirectories
.add(fileIt
.getFileName());
275 // get parent from path
276 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
277 fileIt
= getStorageManager().getFileByPath(parentPath
);
279 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
283 private void createMinFragments() {
284 OCFileListFragment listOfFiles
= new OCFileListFragment();
285 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
286 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
287 transaction
.commit();
290 private void initFragmentsWithFile() {
291 if (getAccount() != null
&& getFile() != null
) {
293 OCFileListFragment listOfFiles
= getListOfFilesFragment();
294 if (listOfFiles
!= null
) {
295 listOfFiles
.listDirectory(getCurrentDir());
297 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
301 OCFile file
= getFile();
302 Fragment secondFragment
= chooseInitialSecondFragment(file
);
303 if (secondFragment
!= null
) {
304 setSecondFragment(secondFragment
);
305 updateFragmentsVisibility(true
);
306 updateNavigationElementsInActionBar(file
);
309 cleanSecondFragment();
313 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
314 if (getAccount() == null
) {
315 Log_OC
.wtf(TAG
, "\t account is NULL");
317 if (getFile() == null
) {
318 Log_OC
.wtf(TAG
, "\t file is NULL");
323 private Fragment
chooseInitialSecondFragment(OCFile file
) {
324 Fragment secondFragment
= null
;
325 if (file
!= null
&& !file
.isFolder()) {
326 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
327 && file
.getLastSyncDateForProperties() > 0 // temporal fix
329 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
330 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
331 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
334 secondFragment
= new FileDetailFragment(file
, getAccount());
337 return secondFragment
;
342 * Replaces the second fragment managed by the activity with the received as
345 * Assumes never will be more than two fragments managed at the same time.
347 * @param fragment New second Fragment to set.
349 private void setSecondFragment(Fragment fragment
) {
350 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
351 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
352 transaction
.commit();
356 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
358 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
359 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
361 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
362 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
365 } else if (existsSecondFragment
) {
366 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
367 mLeftFragmentContainer
.setVisibility(View
.GONE
);
369 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
370 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
378 mRightFragmentContainer
.setVisibility(View
.GONE
);
384 private OCFileListFragment
getListOfFilesFragment() {
385 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
386 if (listOfFiles
!= null
) {
387 return (OCFileListFragment
)listOfFiles
;
389 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
393 public FileFragment
getSecondFragment() {
394 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
395 if (second
!= null
) {
396 return (FileFragment
)second
;
401 protected void cleanSecondFragment() {
402 Fragment second
= getSecondFragment();
403 if (second
!= null
) {
404 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
408 updateFragmentsVisibility(false
);
409 updateNavigationElementsInActionBar(null
);
412 protected void refreshListOfFilesFragment() {
413 OCFileListFragment fileListFragment
= getListOfFilesFragment();
414 if (fileListFragment
!= null
) {
415 fileListFragment
.listDirectory();
419 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
420 FileFragment secondFragment
= getSecondFragment();
421 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
422 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
423 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
424 OCFile fileInFragment
= detailsFragment
.getFile();
425 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
426 // the user browsed to other file ; forget the automatic preview
427 mWaitingToPreview
= null
;
429 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
430 // grant that the right panel updates the progress bar
431 detailsFragment
.listenForTransferProgress();
432 detailsFragment
.updateFileDetails(true
, false
);
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
435 // update the right panel
436 boolean detailsFragmentChanged
= false
;
439 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
440 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
441 startMediaPreview(mWaitingToPreview
, 0, true
);
442 detailsFragmentChanged
= true
;
444 getFileOperationsHelper().openFile(mWaitingToPreview
);
447 mWaitingToPreview
= null
;
449 if (!detailsFragmentChanged
) {
450 detailsFragment
.updateFileDetails(false
, (success
));
457 public boolean onPrepareOptionsMenu(Menu menu
) {
458 if (BuildConfig
.DEBUG
) {
459 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
461 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
463 return super.onPrepareOptionsMenu(menu
);
467 public boolean onCreateOptionsMenu(Menu menu
) {
468 MenuInflater inflater
= getSherlock().getMenuInflater();
469 inflater
.inflate(R
.menu
.main_menu
, menu
);
474 public boolean onOptionsItemSelected(MenuItem item
) {
475 boolean retval
= true
;
476 switch (item
.getItemId()) {
477 case R
.id
.action_create_dir
: {
478 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(getCurrentDir());
479 dialog
.show(getSupportFragmentManager(), "createDirDialog");
482 case R
.id
.action_sync_account
: {
483 startSynchronization();
486 case R
.id
.action_upload
: {
487 //showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
488 UploadSourceDialogFragment dialog
= UploadSourceDialogFragment
.newInstance(getAccount());
489 dialog
.show(getSupportFragmentManager(), "uploadSourceDialog");
493 case R
.id
.action_settings
: {
494 Intent settingsIntent
= new Intent(this, Preferences
.class);
495 startActivity(settingsIntent
);
498 case R
.id
.action_logger
: {
499 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
500 startActivity(loggerIntent
);
503 case android
.R
.id
.home
: {
504 FileFragment second
= getSecondFragment();
505 OCFile currentDir
= getCurrentDir();
506 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
507 (second
!= null
&& second
.getFile() != null
)) {
513 case R
.id
.action_sort
: {
514 SharedPreferences appPreferences
= PreferenceManager
515 .getDefaultSharedPreferences(this);
517 // Read sorting order, default to sort by name ascending
518 Integer sortOrder
= appPreferences
519 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
521 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
522 builder
.setTitle(R
.string
.actionbar_sort_title
)
523 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
524 public void onClick(DialogInterface dialog
, int which
) {
534 // TODO re-enable when server-side folder size calculation is available
536 // sortBySize(false);
544 builder
.create().show();
548 retval
= super.onOptionsItemSelected(item
);
553 private void startSynchronization() {
554 Log_OC
.d(TAG
, "Got to start sync");
555 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
556 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
557 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
558 Bundle bundle
= new Bundle();
559 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
560 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
561 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
562 ContentResolver
.requestSync(
564 MainApp
.getAuthority(), bundle
);
566 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
567 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
568 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
569 builder
.setExpedited(true
);
570 builder
.setManual(true
);
573 // Fix bug in Android Lollipop when you click on refresh the whole account
574 Bundle extras
= new Bundle();
575 builder
.setExtras(extras
);
577 SyncRequest request
= builder
.build();
578 ContentResolver
.requestSync(request
);
584 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
585 if (itemPosition
!= 0) {
586 String targetPath
= "";
587 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
588 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
590 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
591 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
592 if (targetFolder
!= null
) {
593 browseTo(targetFolder
);
596 // the next operation triggers a new call to this method, but it's necessary to
597 // ensure that the name exposed in the action bar is the current directory when the
598 // user selected it in the navigation list
599 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
600 getSupportActionBar().setSelectedNavigationItem(0);
606 * Called, when the user selected something for uploading
609 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
611 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
613 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
614 //getClipData is only supported on api level 16+, Jelly Bean
615 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
616 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
617 Intent intent
= new Intent();
618 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
619 requestSimpleUpload(intent
, resultCode
);
622 requestSimpleUpload(data
, resultCode
);
624 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
625 requestMultipleUpload(data
, resultCode
);
627 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
629 final Intent fData
= data
;
630 final int fResultCode
= resultCode
;
631 getHandler().postDelayed(
635 requestMoveOperation(fData
, fResultCode
);
638 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
642 super.onActivityResult(requestCode
, resultCode
, data
);
647 private void requestMultipleUpload(Intent data
, int resultCode
) {
648 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
649 if (filePaths
!= null
) {
650 String
[] remotePaths
= new String
[filePaths
.length
];
651 String remotePathBase
= "";
653 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
654 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
656 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
657 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
658 for (int j
= 0; j
< remotePaths
.length
; j
++) {
659 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
662 Intent i
= new Intent(this, FileUploader
.class);
663 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
664 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
665 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
666 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
667 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
668 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
672 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
673 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
680 private void requestSimpleUpload(Intent data
, int resultCode
) {
681 String filePath
= null
;
682 String mimeType
= null
;
684 Uri selectedImageUri
= data
.getData();
687 mimeType
= getContentResolver().getType(selectedImageUri
);
689 String fileManagerString
= selectedImageUri
.getPath();
690 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
692 if (selectedImagePath
!= null
)
693 filePath
= selectedImagePath
;
695 filePath
= fileManagerString
;
697 } catch (Exception e
) {
698 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
701 if (filePath
== null
) {
702 Log_OC
.e(TAG
, "Couldn't resolve path to file");
703 Toast t
= Toast
.makeText(
704 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
711 Intent i
= new Intent(this, FileUploader
.class);
712 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
713 OCFile currentDir
= getCurrentDir();
714 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
716 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
717 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
719 if (cursor
!= null
&& cursor
.moveToFirst()) {
720 String displayName
= cursor
.getString(cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
721 Log_OC
.v(TAG
, "Display Name: " + displayName
);
723 displayName
.replace(File
.separatorChar
, '_');
724 displayName
.replace(File
.pathSeparatorChar
, '_');
725 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
728 // and what happens in case of error?; wrong target name for the upload
734 remotePath
+= new File(filePath
).getName();
737 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
738 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
739 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
740 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
741 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
742 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
747 * Request the operation for moving the file/folder from one path to another
749 * @param data Intent received
750 * @param resultCode Result code received
752 private void requestMoveOperation(Intent data
, int resultCode
) {
753 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
754 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
755 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
759 public void onBackPressed() {
760 OCFileListFragment listOfFiles
= getListOfFilesFragment();
761 if (mDualPane
|| getSecondFragment() == null
) {
762 if (listOfFiles
!= null
) { // should never be null, indeed
763 if (mDirectories
.getCount() <= 1) {
767 int levelsUp
= listOfFiles
.onBrowseUp();
768 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
773 if (listOfFiles
!= null
) { // should never be null, indeed
774 setFile(listOfFiles
.getCurrentFile());
776 cleanSecondFragment();
781 protected void onSaveInstanceState(Bundle outState
) {
782 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
783 Log_OC
.d(TAG
, "onSaveInstanceState() start");
784 super.onSaveInstanceState(outState
);
785 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
786 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
787 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
788 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
790 Log_OC
.d(TAG
, "onSaveInstanceState() end");
796 protected void onResume() {
797 Log_OC
.d(TAG
, "onResume() start");
800 // refresh list of files
801 refreshListOfFilesFragment();
803 // Listen for sync messages
804 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
805 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
806 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
807 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
808 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
809 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
810 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
811 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
813 // Listen for upload messages
814 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
815 mUploadFinishReceiver
= new UploadFinishReceiver();
816 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
818 // Listen for download messages
819 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
820 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
821 mDownloadFinishReceiver
= new DownloadFinishReceiver();
822 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
824 Log_OC
.d(TAG
, "onResume() end");
829 protected void onPause() {
830 Log_OC
.d(TAG
, "onPause() start");
831 if (mSyncBroadcastReceiver
!= null
) {
832 unregisterReceiver(mSyncBroadcastReceiver
);
833 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
834 mSyncBroadcastReceiver
= null
;
836 if (mUploadFinishReceiver
!= null
) {
837 unregisterReceiver(mUploadFinishReceiver
);
838 mUploadFinishReceiver
= null
;
840 if (mDownloadFinishReceiver
!= null
) {
841 unregisterReceiver(mDownloadFinishReceiver
);
842 mDownloadFinishReceiver
= null
;
847 Log_OC
.d(TAG
, "onPause() end");
852 protected Dialog
onCreateDialog(int id
) {
853 Dialog dialog
= null
;
854 AlertDialog
.Builder builder
;
856 case DIALOG_SHORT_WAIT
: {
857 ProgressDialog working_dialog
= new ProgressDialog(this);
858 working_dialog
.setMessage(getResources().getString(
859 R
.string
.wait_a_moment
));
860 working_dialog
.setIndeterminate(true
);
861 working_dialog
.setCancelable(false
);
862 dialog
= working_dialog
;
866 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
869 String[] allTheItems = { getString(R.string.actionbar_upload_files),
870 getString(R.string.actionbar_upload_from_apps) };
872 builder = new AlertDialog.Builder(this);
873 builder.setTitle(R.string.actionbar_upload);
874 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
875 public void onClick(DialogInterface dialog, int item) {
878 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
879 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
880 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
882 // TODO create and handle new fragment
883 // LocalFileListFragment
885 } else if (item == 1) {
886 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
887 action = action.setType("*-/*").addCategory(Intent.CATEGORY_OPENABLE);
888 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
889 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
890 action.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
892 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
893 ACTION_SELECT_CONTENT_FROM_APPS);
897 dialog = builder.create();
900 case DIALOG_CERT_NOT_SAVED
: {
901 builder
= new AlertDialog
.Builder(this);
902 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
903 builder
.setCancelable(false
);
904 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
906 public void onClick(DialogInterface dialog
, int which
) {
910 dialog
= builder
.create();
921 * Pushes a directory to the drop down list
922 * @param directory to push
923 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
925 public void pushDirname(OCFile directory
) {
926 if(!directory
.isFolder()){
927 throw new IllegalArgumentException("Only directories may be pushed!");
929 mDirectories
.insert(directory
.getFileName(), 0);
934 * Pops a directory name from the drop down list
935 * @return True, unless the stack is empty
937 public boolean popDirname() {
938 mDirectories
.remove(mDirectories
.getItem(0));
939 return !mDirectories
.isEmpty();
942 // Custom array adapter to override text colors
943 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
945 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
949 public View
getView(int position
, View convertView
, ViewGroup parent
) {
950 View v
= super.getView(position
, convertView
, parent
);
952 ((TextView
) v
).setTextColor(getResources().getColorStateList(
953 android
.R
.color
.white
));
955 fixRoot((TextView
) v
);
959 public View
getDropDownView(int position
, View convertView
,
961 View v
= super.getDropDownView(position
, convertView
, parent
);
963 ((TextView
) v
).setTextColor(getResources().getColorStateList(
964 android
.R
.color
.white
));
966 fixRoot((TextView
) v
);
970 private void fixRoot(TextView v
) {
971 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
972 v
.setText(R
.string
.default_display_name_for_root_folder
);
978 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
981 * {@link BroadcastReceiver} to enable syncing feedback in UI
984 public void onReceive(Context context
, Intent intent
) {
986 String event
= intent
.getAction();
987 Log_OC
.d(TAG
, "Received broadcast " + event
);
988 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
989 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
990 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
991 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
995 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
996 mSyncInProgress
= true
;
999 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1000 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1002 if (currentDir
== null
) {
1003 // current folder was removed from the server
1004 Toast
.makeText( FileDisplayActivity
.this,
1005 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1011 if (currentFile
== null
&& !getFile().isFolder()) {
1012 // currently selected file was removed in the server, and now we know it
1013 cleanSecondFragment();
1014 currentFile
= currentDir
;
1017 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1018 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1019 if (fileListFragment
!= null
) {
1020 fileListFragment
.listDirectory(currentDir
);
1023 setFile(currentFile
);
1026 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1028 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1030 /// TODO refactor and make common
1031 synchResult
!= null
&& !synchResult
.isSuccess() &&
1032 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1033 synchResult
.isIdPRedirection() ||
1034 (synchResult
.isException() && synchResult
.getException()
1035 instanceof AuthenticatorException
))) {
1039 OwnCloudClient client
;
1040 OwnCloudAccount ocAccount
=
1041 new OwnCloudAccount(getAccount(), context
);
1042 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1043 removeClientFor(ocAccount
));
1045 if (client
!= null
) {
1046 OwnCloudCredentials cred
= client
.getCredentials();
1048 AccountManager am
= AccountManager
.get(context
);
1049 if (cred
.authTokenExpires()) {
1050 am
.invalidateAuthToken(
1055 am
.clearPassword(getAccount());
1059 requestCredentialsUpdate();
1061 } catch (AccountNotFoundException e
) {
1062 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1067 removeStickyBroadcast(intent
);
1068 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1069 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1071 setBackgroundText();
1075 if (synchResult
!= null
) {
1076 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1077 mLastSslUntrustedServerResult
= synchResult
;
1080 } catch (RuntimeException e
) {
1081 // avoid app crashes after changing the serial id of RemoteOperationResult
1082 // in owncloud library with broadcast notifications pending to process
1083 removeStickyBroadcast(intent
);
1089 * Show a text message on screen view for notifying user if content is
1090 * loading or folder is empty
1092 private void setBackgroundText() {
1093 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1094 if (ocFileListFragment
!= null
) {
1095 int message
= R
.string
.file_list_loading
;
1096 if (!mSyncInProgress
) {
1097 // In case file list is empty
1098 message
= R
.string
.file_list_empty
;
1100 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1102 Log_OC
.e(TAG
, "OCFileListFragment is null");
1107 * Once the file upload has finished -> update view
1109 private class UploadFinishReceiver
extends BroadcastReceiver
{
1111 * Once the file upload has finished -> update view
1112 * @author David A. Velasco
1113 * {@link BroadcastReceiver} to enable upload feedback in UI
1116 public void onReceive(Context context
, Intent intent
) {
1118 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1119 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1120 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1121 OCFile currentDir
= getCurrentDir();
1122 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1123 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1125 if (sameAccount
&& isDescendant
) {
1126 refreshListOfFilesFragment();
1129 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1130 boolean renamedInUpload
= getFile().getRemotePath().
1131 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1132 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1134 FileFragment details
= getSecondFragment();
1135 boolean detailFragmentIsShown
= (details
!= null
&&
1136 details
instanceof FileDetailFragment
);
1138 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1139 if (uploadWasFine
) {
1140 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1142 if (renamedInUpload
) {
1143 String newName
= (new File(uploadedRemotePath
)).getName();
1144 Toast msg
= Toast
.makeText(
1147 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1152 if (uploadWasFine
|| getFile().fileExists()) {
1153 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1155 cleanSecondFragment();
1158 // Force the preview if the file is an image
1159 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1160 startImagePreview(getFile());
1161 } // TODO what about other kind of previews?
1165 if (intent
!= null
) {
1166 removeStickyBroadcast(intent
);
1176 * Class waiting for broadcast events from the {@link FileDownloader} service.
1178 * Updates the UI when a download is started or finished, provided that it is relevant for the
1181 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1183 //int refreshCounter = 0;
1185 public void onReceive(Context context
, Intent intent
) {
1187 boolean sameAccount
= isSameAccount(context
, intent
);
1188 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1189 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1191 if (sameAccount
&& isDescendant
) {
1192 String linkedToRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1193 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1194 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1195 refreshListOfFilesFragment();
1197 refreshSecondFragment(
1199 downloadedRemotePath
,
1200 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1204 if (mWaitingToSend
!= null
) {
1205 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1206 if (mWaitingToSend
.isDown()) {
1207 sendDownloadedFile();
1212 if (intent
!= null
) {
1213 removeStickyBroadcast(intent
);
1218 private boolean isDescendant(String downloadedRemotePath
) {
1219 OCFile currentDir
= getCurrentDir();
1221 currentDir
!= null
&&
1222 downloadedRemotePath
!= null
&&
1223 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1227 private boolean isAscendant(String linkedToRemotePath
) {
1228 OCFile currentDir
= getCurrentDir();
1230 currentDir
!= null
&&
1231 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1235 private boolean isSameAccount(Context context
, Intent intent
) {
1236 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1237 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1242 public void browseToRoot() {
1243 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1244 if (listOfFiles
!= null
) { // should never be null, indeed
1245 while (mDirectories
.getCount() > 1) {
1248 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1249 listOfFiles
.listDirectory(root
);
1250 setFile(listOfFiles
.getCurrentFile());
1251 startSyncFolderOperation(root
, false
);
1253 cleanSecondFragment();
1257 public void browseTo(OCFile folder
) {
1258 if (folder
== null
|| !folder
.isFolder()) {
1259 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1261 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1262 if (listOfFiles
!= null
) {
1263 setNavigationListWithFolder(folder
);
1264 listOfFiles
.listDirectory(folder
);
1265 setFile(listOfFiles
.getCurrentFile());
1266 startSyncFolderOperation(folder
, false
);
1268 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1270 cleanSecondFragment();
1277 * Updates action bar and second fragment, if in dual pane mode.
1280 public void onBrowsedDownTo(OCFile directory
) {
1281 pushDirname(directory
);
1282 cleanSecondFragment();
1285 startSyncFolderOperation(directory
, false
);
1290 * Shows the information of the {@link OCFile} received as a
1291 * parameter in the second fragment.
1293 * @param file {@link OCFile} whose details will be shown
1296 public void showDetails(OCFile file
) {
1297 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1298 setSecondFragment(detailFragment
);
1299 updateFragmentsVisibility(true
);
1300 updateNavigationElementsInActionBar(file
);
1308 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1309 ActionBar actionBar
= getSupportActionBar();
1311 // For adding content description tag to a title field in the action bar
1312 int actionBarTitleId
= getResources().getIdentifier("action_bar_title", "id", "android");
1314 if (chosenFile
== null
|| mDualPane
) {
1315 // only list of files - set for browsing through folders
1316 OCFile currentDir
= getCurrentDir();
1317 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1318 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1319 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1321 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1322 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1323 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1324 actionBarTitleView
.setContentDescription(getString(R
.string
.default_display_name_for_root_folder
));
1327 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1328 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1331 actionBar
.setDisplayHomeAsUpEnabled(true
);
1332 actionBar
.setDisplayShowTitleEnabled(true
);
1333 actionBar
.setTitle(chosenFile
.getFileName());
1334 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1335 View actionBarTitleView
= getWindow().getDecorView().findViewById(actionBarTitleId
);
1336 if (actionBarTitleView
!= null
) { // it's null in Android 2.x
1337 getWindow().getDecorView().findViewById(actionBarTitleId
).
1338 setContentDescription(chosenFile
.getFileName());
1345 protected ServiceConnection
newTransferenceServiceConnection() {
1346 return new ListServiceConnection();
1349 /** Defines callbacks for service binding, passed to bindService() */
1350 private class ListServiceConnection
implements ServiceConnection
{
1353 public void onServiceConnected(ComponentName component
, IBinder service
) {
1354 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1355 Log_OC
.d(TAG
, "Download service connected");
1356 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1357 if (mWaitingToPreview
!= null
)
1358 if (getStorageManager() != null
) {
1359 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1360 if (!mWaitingToPreview
.isDown()) {
1361 requestForDownload();
1365 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1366 Log_OC
.d(TAG
, "Upload service connected");
1367 mUploaderBinder
= (FileUploaderBinder
) service
;
1371 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1372 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1373 if (listOfFiles
!= null
) {
1374 listOfFiles
.listDirectory();
1376 FileFragment secondFragment
= getSecondFragment();
1377 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1378 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1379 detailFragment
.listenForTransferProgress();
1380 detailFragment
.updateFileDetails(false
, false
);
1385 public void onServiceDisconnected(ComponentName component
) {
1386 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1387 Log_OC
.d(TAG
, "Download service disconnected");
1388 mDownloaderBinder
= null
;
1389 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1390 Log_OC
.d(TAG
, "Upload service disconnected");
1391 mUploaderBinder
= null
;
1399 * Launch an intent to request the PIN code to the user before letting him use the app
1401 private void requestPinCode() {
1402 boolean pinStart
= false
;
1403 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1404 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1406 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1407 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1414 public void onSavedCertificate() {
1415 startSyncFolderOperation(getCurrentDir(), false
);
1420 public void onFailedSavingCertificate() {
1421 showDialog(DIALOG_CERT_NOT_SAVED
);
1425 public void onCancelCertificate() {
1430 * Updates the view associated to the activity after the finish of some operation over files
1431 * in the current account.
1433 * @param operation Removal operation performed.
1434 * @param result Result of the removal.
1437 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1438 super.onRemoteOperationFinish(operation
, result
);
1440 if (operation
instanceof RemoveFileOperation
) {
1441 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1443 } else if (operation
instanceof RenameFileOperation
) {
1444 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1446 } else if (operation
instanceof SynchronizeFileOperation
) {
1447 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1449 } else if (operation
instanceof CreateFolderOperation
) {
1450 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1452 } else if (operation
instanceof CreateShareOperation
) {
1453 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1455 } else if (operation
instanceof UnshareLinkOperation
) {
1456 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1458 } else if (operation
instanceof MoveFileOperation
) {
1459 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1465 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1466 if (result
.isSuccess()) {
1467 refreshShowDetails();
1468 refreshListOfFilesFragment();
1473 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1474 if (result
.isSuccess()) {
1475 refreshShowDetails();
1476 refreshListOfFilesFragment();
1478 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1479 cleanSecondFragment();
1480 refreshListOfFilesFragment();
1484 private void refreshShowDetails() {
1485 FileFragment details
= getSecondFragment();
1486 if (details
!= null
) {
1487 OCFile file
= details
.getFile();
1489 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1490 if (details
instanceof PreviewMediaFragment
) {
1491 // Refresh OCFile of the fragment
1492 ((PreviewMediaFragment
) details
).updateFile(file
);
1497 invalidateOptionsMenu();
1502 * Updates the view associated to the activity after the finish of an operation trying to remove a
1505 * @param operation Removal operation performed.
1506 * @param result Result of the removal.
1508 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1509 dismissLoadingDialog();
1511 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1515 if (result
.isSuccess()) {
1516 OCFile removedFile
= operation
.getFile();
1517 FileFragment second
= getSecondFragment();
1518 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1519 if (second
instanceof PreviewMediaFragment
) {
1520 ((PreviewMediaFragment
)second
).stopPreview(true
);
1522 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1523 cleanSecondFragment();
1525 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1526 refreshListOfFilesFragment();
1528 invalidateOptionsMenu();
1530 if (result
.isSslRecoverableException()) {
1531 mLastSslUntrustedServerResult
= result
;
1532 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1539 * Updates the view associated to the activity after the finish of an operation trying to move a
1542 * @param operation Move operation performed.
1543 * @param result Result of the move operation.
1545 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1546 if (result
.isSuccess()) {
1547 dismissLoadingDialog();
1548 refreshListOfFilesFragment();
1550 dismissLoadingDialog();
1552 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1553 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1557 } catch (NotFoundException e
) {
1558 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1565 * Updates the view associated to the activity after the finish of an operation trying to rename a
1568 * @param operation Renaming operation performed.
1569 * @param result Result of the renaming.
1571 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1572 dismissLoadingDialog();
1573 OCFile renamedFile
= operation
.getFile();
1574 if (result
.isSuccess()) {
1575 FileFragment details
= getSecondFragment();
1576 if (details
!= null
) {
1577 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1578 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1579 showDetails(renamedFile
);
1581 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1582 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1583 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1584 int position
= ((PreviewMediaFragment
)details
).getPosition();
1585 startMediaPreview(renamedFile
, position
, true
);
1587 getFileOperationsHelper().openFile(renamedFile
);
1592 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1593 refreshListOfFilesFragment();
1597 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1601 if (result
.isSslRecoverableException()) {
1602 mLastSslUntrustedServerResult
= result
;
1603 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1608 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1609 dismissLoadingDialog();
1610 OCFile syncedFile
= operation
.getLocalFile();
1611 if (!result
.isSuccess()) {
1612 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1613 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1614 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1615 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1621 if (operation
.transferWasRequested()) {
1622 onTransferStateChanged(syncedFile
, true
, true
);
1625 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1633 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1635 * @param operation Creation operation performed.
1636 * @param result Result of the creation.
1638 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1639 if (result
.isSuccess()) {
1640 dismissLoadingDialog();
1641 refreshListOfFilesFragment();
1643 dismissLoadingDialog();
1645 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1646 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1650 } catch (NotFoundException e
) {
1651 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1661 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1662 refreshListOfFilesFragment();
1663 FileFragment details
= getSecondFragment();
1664 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1665 if (downloading
|| uploading
) {
1666 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1668 if (!file
.fileExists()) {
1669 cleanSecondFragment();
1671 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1679 private void requestForDownload() {
1680 Account account
= getAccount();
1681 //if (!mWaitingToPreview.isDownloading()) {
1682 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1683 Intent i
= new Intent(this, FileDownloader
.class);
1684 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1685 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1691 private OCFile
getCurrentDir() {
1692 OCFile file
= getFile();
1694 if (file
.isFolder()) {
1696 } else if (getStorageManager() != null
) {
1697 String parentPath
= file
.getRemotePath().substring(0,
1698 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1699 return getStorageManager().getFileByPath(parentPath
);
1705 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1706 long currentSyncTime
= System
.currentTimeMillis();
1708 mSyncInProgress
= true
;
1710 // perform folder synchronization
1711 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1714 getFileOperationsHelper().isSharedSupported(),
1716 getStorageManager(),
1718 getApplicationContext()
1720 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1722 setSupportProgressBarIndeterminateVisibility(true
);
1724 setBackgroundText();
1728 * Show untrusted cert dialog
1730 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1731 // Show a dialog with the certificate info
1732 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1733 (CertificateCombinedException
)result
.getException());
1734 FragmentManager fm
= getSupportFragmentManager();
1735 FragmentTransaction ft
= fm
.beginTransaction();
1736 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1739 private void requestForDownload(OCFile file
) {
1740 Account account
= getAccount();
1741 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1742 Intent i
= new Intent(this, FileDownloader
.class);
1743 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1744 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1749 private void sendDownloadedFile(){
1750 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1751 mWaitingToSend
= null
;
1756 * Requests the download of the received {@link OCFile} , updates the UI
1757 * to monitor the download progress and prepares the activity to send the file
1758 * when the download finishes.
1760 * @param file {@link OCFile} to download and preview.
1762 public void startDownloadForSending(OCFile file
) {
1763 mWaitingToSend
= file
;
1764 requestForDownload(mWaitingToSend
);
1765 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1766 updateFragmentsVisibility(hasSecondFragment
);
1770 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1772 * @param file Image {@link OCFile} to show.
1774 public void startImagePreview(OCFile file
) {
1775 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1776 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1777 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1778 startActivity(showDetailsIntent
);
1783 * Stars the preview of an already down media {@link OCFile}.
1785 * @param file Media {@link OCFile} to preview.
1786 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1787 * @param autoplay When 'true', the playback will start without user interactions.
1789 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1790 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
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
);