1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.annotation
.TargetApi
;
29 import android
.app
.AlertDialog
;
30 import android
.app
.Dialog
;
31 import android
.app
.ProgressDialog
;
32 import android
.content
.BroadcastReceiver
;
33 import android
.content
.ComponentName
;
34 import android
.content
.ContentResolver
;
35 import android
.content
.ContentUris
;
36 import android
.content
.Context
;
37 import android
.content
.DialogInterface
;
38 import android
.content
.Intent
;
39 import android
.content
.IntentFilter
;
40 import android
.content
.ServiceConnection
;
41 import android
.content
.SharedPreferences
;
42 import android
.content
.SyncRequest
;
43 import android
.content
.res
.Resources
.NotFoundException
;
44 import android
.database
.Cursor
;
45 import android
.net
.Uri
;
46 import android
.os
.Build
;
47 import android
.os
.Bundle
;
48 import android
.os
.Environment
;
49 import android
.os
.IBinder
;
50 import android
.preference
.PreferenceManager
;
51 import android
.provider
.DocumentsContract
;
52 import android
.provider
.MediaStore
;
53 import android
.provider
.OpenableColumns
;
54 import android
.support
.v4
.app
.Fragment
;
55 import android
.support
.v4
.app
.FragmentManager
;
56 import android
.support
.v4
.app
.FragmentTransaction
;
57 import android
.util
.Log
;
58 import android
.view
.View
;
59 import android
.view
.ViewGroup
;
60 import android
.widget
.ArrayAdapter
;
61 import android
.widget
.TextView
;
62 import android
.widget
.Toast
;
64 import com
.actionbarsherlock
.app
.ActionBar
;
65 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
66 import com
.actionbarsherlock
.view
.Menu
;
67 import com
.actionbarsherlock
.view
.MenuInflater
;
68 import com
.actionbarsherlock
.view
.MenuItem
;
69 import com
.actionbarsherlock
.view
.Window
;
70 import com
.owncloud
.android
.BuildConfig
;
71 import com
.owncloud
.android
.MainApp
;
72 import com
.owncloud
.android
.R
;
73 import com
.owncloud
.android
.authentication
.PinCheck
;
74 import com
.owncloud
.android
.datamodel
.OCFile
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
79 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
81 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
82 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
83 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
84 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
86 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
87 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
88 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
89 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
90 import com
.owncloud
.android
.operations
.CreateShareOperation
;
91 import com
.owncloud
.android
.operations
.MoveFileOperation
;
92 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
93 import com
.owncloud
.android
.operations
.RenameFileOperation
;
94 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
95 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
96 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
97 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
98 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
99 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
100 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
101 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
102 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
103 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
104 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
105 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
106 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
108 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
109 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
110 import com
.owncloud
.android
.utils
.DisplayUtils
;
111 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
112 import com
.owncloud
.android
.utils
.UriUtils
;
116 * Displays, what files the user has available in his ownCloud.
118 * @author Bartek Przybylski
119 * @author David A. Velasco
122 public class FileDisplayActivity
extends HookActivity
implements
123 FileFragment
.ContainerActivity
, OnNavigationListener
,
124 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
126 private ArrayAdapter
<String
> mDirectories
;
128 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
129 private UploadFinishReceiver mUploadFinishReceiver
;
130 private DownloadFinishReceiver mDownloadFinishReceiver
;
131 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
133 private boolean mDualPane
;
134 private View mLeftFragmentContainer
;
135 private View mRightFragmentContainer
;
137 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
138 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
139 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
141 public static final int DIALOG_SHORT_WAIT
= 0;
142 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
143 private static final int DIALOG_CERT_NOT_SAVED
= 2;
145 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
147 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
148 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
149 public static final int ACTION_MOVE_FILES
= 3;
151 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
153 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
154 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
156 private OCFile mWaitingToPreview
;
158 private boolean mSyncInProgress
= false
;
160 private String DIALOG_UNTRUSTED_CERT
;
162 private OCFile mWaitingToSend
;
164 private Boolean mUnlocked
= false
;
167 protected void onCreate(Bundle savedInstanceState
) {
168 Log_OC
.d(TAG
, "onCreate() start");
169 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
171 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
174 if (PinCheck
.checkIfPinEntry()){
175 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
176 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
180 /// grant that FileObserverService is watching favorite files
181 if (savedInstanceState
== null
) {
182 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
183 startService(initObserversIntent
);
186 /// Load of saved instance state
187 if(savedInstanceState
!= null
) {
188 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
189 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
190 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
193 mWaitingToPreview
= null
;
194 mSyncInProgress
= false
;
195 mWaitingToSend
= null
;
200 // Inflate and set the layout view
201 setContentView(R
.layout
.files
);
202 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
203 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
204 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
205 if (savedInstanceState
== null
) {
206 createMinFragments();
210 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
211 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
212 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
216 Log_OC
.d(TAG
, "onCreate() end");
220 protected void onStart() {
222 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
226 protected void onDestroy() {
231 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
234 protected void onAccountSet(boolean stateWasRecovered
) {
235 super.onAccountSet(stateWasRecovered
);
236 if (getAccount() != null
) {
237 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
238 OCFile file
= getFile();
239 // get parent from path
240 String parentPath
= "";
242 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
243 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
244 // get parent from path
245 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
246 if (getStorageManager().getFileByPath(parentPath
) == null
)
247 file
= null
; // not able to know the directory where the file is uploading
249 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
253 // fall back to root folder
254 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
257 setNavigationListWithFolder(file
);
259 if (!stateWasRecovered
) {
260 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
261 initFragmentsWithFile();
262 if (file
.isFolder()) {
263 startSyncFolderOperation(file
, false
);
267 updateFragmentsVisibility(!file
.isFolder());
268 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
274 private void setNavigationListWithFolder(OCFile file
) {
275 mDirectories
.clear();
276 OCFile fileIt
= file
;
278 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
279 if (fileIt
.isFolder()) {
280 mDirectories
.add(fileIt
.getFileName());
282 // get parent from path
283 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
284 fileIt
= getStorageManager().getFileByPath(parentPath
);
286 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
290 private void createMinFragments() {
291 OCFileListFragment listOfFiles
= new OCFileListFragment();
292 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
293 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
294 transaction
.commit();
297 private void initFragmentsWithFile() {
298 if (getAccount() != null
&& getFile() != null
) {
300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
301 if (listOfFiles
!= null
) {
302 listOfFiles
.listDirectory(getCurrentDir());
304 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
308 OCFile file
= getFile();
309 Fragment secondFragment
= chooseInitialSecondFragment(file
);
310 if (secondFragment
!= null
) {
311 setSecondFragment(secondFragment
);
312 updateFragmentsVisibility(true
);
313 updateNavigationElementsInActionBar(file
);
316 cleanSecondFragment();
320 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
321 if (getAccount() == null
) {
322 Log_OC
.wtf(TAG
, "\t account is NULL");
324 if (getFile() == null
) {
325 Log_OC
.wtf(TAG
, "\t file is NULL");
330 private Fragment
chooseInitialSecondFragment(OCFile file
) {
331 Fragment secondFragment
= null
;
332 if (file
!= null
&& !file
.isFolder()) {
333 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
334 && file
.getLastSyncDateForProperties() > 0 // temporal fix
336 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
337 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
338 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
341 secondFragment
= new FileDetailFragment(file
, getAccount());
344 return secondFragment
;
349 * Replaces the second fragment managed by the activity with the received as
352 * Assumes never will be more than two fragments managed at the same time.
354 * @param fragment New second Fragment to set.
356 private void setSecondFragment(Fragment fragment
) {
357 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
358 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
359 transaction
.commit();
363 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
365 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
368 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
369 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
372 } else if (existsSecondFragment
) {
373 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
374 mLeftFragmentContainer
.setVisibility(View
.GONE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
381 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
384 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
385 mRightFragmentContainer
.setVisibility(View
.GONE
);
391 private OCFileListFragment
getListOfFilesFragment() {
392 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
393 if (listOfFiles
!= null
) {
394 return (OCFileListFragment
)listOfFiles
;
396 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
400 public FileFragment
getSecondFragment() {
401 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
402 if (second
!= null
) {
403 return (FileFragment
)second
;
408 protected void cleanSecondFragment() {
409 Fragment second
= getSecondFragment();
410 if (second
!= null
) {
411 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
415 updateFragmentsVisibility(false
);
416 updateNavigationElementsInActionBar(null
);
419 protected void refreshListOfFilesFragment() {
420 OCFileListFragment fileListFragment
= getListOfFilesFragment();
421 if (fileListFragment
!= null
) {
422 fileListFragment
.listDirectory();
426 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
427 FileFragment secondFragment
= getSecondFragment();
428 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
429 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
430 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
431 OCFile fileInFragment
= detailsFragment
.getFile();
432 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
433 // the user browsed to other file ; forget the automatic preview
434 mWaitingToPreview
= null
;
436 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
437 // grant that the right panel updates the progress bar
438 detailsFragment
.listenForTransferProgress();
439 detailsFragment
.updateFileDetails(true
, false
);
441 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
442 // update the right panel
443 boolean detailsFragmentChanged
= false
;
446 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
447 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
448 startMediaPreview(mWaitingToPreview
, 0, true
);
449 detailsFragmentChanged
= true
;
451 getFileOperationsHelper().openFile(mWaitingToPreview
);
454 mWaitingToPreview
= null
;
456 if (!detailsFragmentChanged
) {
457 detailsFragment
.updateFileDetails(false
, (success
));
464 public boolean onPrepareOptionsMenu(Menu menu
) {
465 if (BuildConfig
.DEBUG
) {
466 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
468 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
470 return super.onPrepareOptionsMenu(menu
);
474 public boolean onCreateOptionsMenu(Menu menu
) {
475 MenuInflater inflater
= getSherlock().getMenuInflater();
476 inflater
.inflate(R
.menu
.main_menu
, menu
);
481 public boolean onOptionsItemSelected(MenuItem item
) {
482 boolean retval
= true
;
483 switch (item
.getItemId()) {
484 case R
.id
.action_create_dir
: {
485 CreateFolderDialogFragment dialog
=
486 CreateFolderDialogFragment
.newInstance(getCurrentDir());
487 dialog
.show(getSupportFragmentManager(), "createdirdialog");
490 case R
.id
.action_sync_account
: {
491 startSynchronization();
494 case R
.id
.action_upload
: {
495 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
498 case R
.id
.action_settings
: {
499 Intent settingsIntent
= new Intent(this, Preferences
.class);
500 startActivity(settingsIntent
);
503 case R
.id
.action_logger
: {
504 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
505 startActivity(loggerIntent
);
508 case android
.R
.id
.home
: {
509 FileFragment second
= getSecondFragment();
510 OCFile currentDir
= getCurrentDir();
511 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
512 (second
!= null
&& second
.getFile() != null
)) {
518 case R
.id
.action_sort
: {
519 SharedPreferences appPreferences
= PreferenceManager
520 .getDefaultSharedPreferences(this);
522 // Read sorting order, default to sort by name ascending
523 Integer sortOrder
= appPreferences
524 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
526 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
527 builder
.setTitle(R
.string
.actionbar_sort_title
)
528 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
529 public void onClick(DialogInterface dialog
, int which
) {
539 // TODO re-enable when server-side folder size calculation is available
541 // sortBySize(false);
549 builder
.create().show();
553 retval
= super.onOptionsItemSelected(item
);
558 private void startSynchronization() {
559 Log_OC
.e(TAG
, "Got to start sync");
560 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
561 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
562 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
563 Bundle bundle
= new Bundle();
564 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
565 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
566 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
567 ContentResolver
.requestSync(
569 MainApp
.getAuthority(), bundle
);
571 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
572 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
573 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
574 builder
.setExpedited(true
);
575 builder
.setManual(true
);
578 // Fix bug in Android Lollipop when you click on refresh the whole account
579 Bundle extras
= new Bundle();
580 builder
.setExtras(extras
);
582 SyncRequest request
= builder
.build();
583 ContentResolver
.requestSync(request
);
589 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
590 if (itemPosition
!= 0) {
591 String targetPath
= "";
592 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
593 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
595 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
596 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
597 if (targetFolder
!= null
) {
598 browseTo(targetFolder
);
601 // the next operation triggers a new call to this method, but it's necessary to
602 // ensure that the name exposed in the action bar is the current directory when the
603 // user selected it in the navigation list
604 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
605 getSupportActionBar().setSelectedNavigationItem(0);
611 * Called, when the user selected something for uploading
614 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
615 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
616 super.onActivityResult(requestCode
, resultCode
, data
);
618 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
619 //getClipData is only supported on api level 16+, Jelly Bean
620 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
621 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
622 Intent intent
= new Intent();
623 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
624 requestSimpleUpload(intent
, resultCode
);
627 requestSimpleUpload(data
, resultCode
);
629 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
630 requestMultipleUpload(data
, resultCode
);
632 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
634 final Intent fData
= data
;
635 final int fResultCode
= resultCode
;
636 getHandler().postDelayed(
640 requestMoveOperation(fData
, fResultCode
);
643 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
648 private void requestMultipleUpload(Intent data
, int resultCode
) {
649 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
650 if (filePaths
!= null
) {
651 String
[] remotePaths
= new String
[filePaths
.length
];
652 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
= getPath(selectedImageUri
);
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
);
702 if (filepath
== null
) {
703 Log_OC
.e(TAG
, "Couldnt resolve path to file");
704 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
710 Intent i
= new Intent(this, FileUploader
.class);
711 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
713 String remotepath
= new String();
714 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
715 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
717 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
718 remotepath
+= OCFile
.PATH_SEPARATOR
;
720 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
722 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
723 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
726 if (cursor
!= null
&& cursor
.moveToFirst()) {
727 String displayName
= cursor
.getString(
728 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
729 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
731 displayName
.replace(File
.separatorChar
, '_');
732 displayName
.replace(File
.pathSeparatorChar
, '_');
733 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
741 remotepath
+= new File(filepath
).getName();
744 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
745 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
746 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
747 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
748 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
749 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
754 * Request the operation for moving the file/folder from one path to another
756 * @param data Intent received
757 * @param resultCode Result code received
759 private void requestMoveOperation(Intent data
, int resultCode
) {
760 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
761 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
762 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
766 public void onBackPressed() {
767 OCFileListFragment listOfFiles
= getListOfFilesFragment();
768 if (mDualPane
|| getSecondFragment() == null
) {
769 if (listOfFiles
!= null
) { // should never be null, indeed
770 if (mDirectories
.getCount() <= 1) {
774 int levelsUp
= listOfFiles
.onBrowseUp();
775 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
780 if (listOfFiles
!= null
) { // should never be null, indeed
781 setFile(listOfFiles
.getCurrentFile());
783 cleanSecondFragment();
788 protected void onSaveInstanceState(Bundle outState
) {
789 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
790 Log_OC
.e(TAG
, "onSaveInstanceState() start");
791 super.onSaveInstanceState(outState
);
792 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
793 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
794 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
795 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
797 Log_OC
.d(TAG
, "onSaveInstanceState() end");
803 protected void onResume() {
805 Log_OC
.e(TAG
, "onResume() start");
807 if (PinCheck
.checkIfPinEntry()){
808 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
809 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
813 // refresh list of files
814 refreshListOfFilesFragment();
816 // Listen for sync messages
817 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
818 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
819 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
820 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
821 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
822 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
823 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
824 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
826 // Listen for upload messages
827 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
828 mUploadFinishReceiver
= new UploadFinishReceiver();
829 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
831 // Listen for download messages
832 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
833 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
834 mDownloadFinishReceiver
= new DownloadFinishReceiver();
835 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
837 Log_OC
.d(TAG
, "onResume() end");
842 protected void onPause() {
843 Log_OC
.e(TAG
, "onPause() start");
844 if (mSyncBroadcastReceiver
!= null
) {
845 unregisterReceiver(mSyncBroadcastReceiver
);
846 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
847 mSyncBroadcastReceiver
= null
;
849 if (mUploadFinishReceiver
!= null
) {
850 unregisterReceiver(mUploadFinishReceiver
);
851 mUploadFinishReceiver
= null
;
853 if (mDownloadFinishReceiver
!= null
) {
854 unregisterReceiver(mDownloadFinishReceiver
);
855 mDownloadFinishReceiver
= null
;
858 PinCheck
.setUnlockTimestamp();
859 Log_OC
.d(TAG
, "onPause() end");
865 protected Dialog
onCreateDialog(int id
) {
866 Dialog dialog
= null
;
867 AlertDialog
.Builder builder
;
869 case DIALOG_SHORT_WAIT
: {
870 ProgressDialog working_dialog
= new ProgressDialog(this);
871 working_dialog
.setMessage(getResources().getString(
872 R
.string
.wait_a_moment
));
873 working_dialog
.setIndeterminate(true
);
874 working_dialog
.setCancelable(false
);
875 dialog
= working_dialog
;
878 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
881 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
882 getString(R
.string
.actionbar_upload_from_apps
) };
884 builder
= new AlertDialog
.Builder(this);
885 builder
.setTitle(R
.string
.actionbar_upload
);
886 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
887 public void onClick(DialogInterface dialog
, int item
) {
890 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
891 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
892 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
894 // TODO create and handle new fragment
895 // LocalFileListFragment
897 } else if (item
== 1) {
898 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
899 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
900 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
901 if(Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
902 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
904 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
905 ACTION_SELECT_CONTENT_FROM_APPS
);
909 dialog
= builder
.create();
912 case DIALOG_CERT_NOT_SAVED
: {
913 builder
= new AlertDialog
.Builder(this);
914 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
915 builder
.setCancelable(false
);
916 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
918 public void onClick(DialogInterface dialog
, int which
) {
922 dialog
= builder
.create();
933 * Translates a content URI of an content to a physical path on the disk
935 * @param uri The URI to resolve
936 * @return The path to the content or null if it could not be found
938 public String
getPath(Uri uri
) {
939 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
942 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
943 // ExternalStorageProvider
944 if (UriUtils
.isExternalStorageDocument(uri
)) {
945 final String docId
= DocumentsContract
.getDocumentId(uri
);
946 final String
[] split
= docId
.split(":");
947 final String type
= split
[0];
949 if ("primary".equalsIgnoreCase(type
)) {
950 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
954 else if (UriUtils
.isDownloadsDocument(uri
)) {
956 final String id
= DocumentsContract
.getDocumentId(uri
);
957 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
960 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
963 else if (UriUtils
.isMediaDocument(uri
)) {
964 final String docId
= DocumentsContract
.getDocumentId(uri
);
965 final String
[] split
= docId
.split(":");
966 final String type
= split
[0];
968 Uri contentUri
= null
;
969 if ("image".equals(type
)) {
970 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
971 } else if ("video".equals(type
)) {
972 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
973 } else if ("audio".equals(type
)) {
974 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
977 final String selection
= "_id=?";
978 final String
[] selectionArgs
= new String
[] { split
[1] };
980 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
982 // Documents providers returned as content://...
983 else if (UriUtils
.isContentDocument(uri
)) {
984 return uri
.toString();
987 // MediaStore (and general)
988 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
990 // Return the remote address
991 if (UriUtils
.isGooglePhotosUri(uri
))
992 return uri
.getLastPathSegment();
994 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
997 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
998 return uri
.getPath();
1004 * Pushes a directory to the drop down list
1005 * @param directory to push
1006 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1008 public void pushDirname(OCFile directory
) {
1009 if(!directory
.isFolder()){
1010 throw new IllegalArgumentException("Only directories may be pushed!");
1012 mDirectories
.insert(directory
.getFileName(), 0);
1017 * Pops a directory name from the drop down list
1018 * @return True, unless the stack is empty
1020 public boolean popDirname() {
1021 mDirectories
.remove(mDirectories
.getItem(0));
1022 return !mDirectories
.isEmpty();
1025 // Custom array adapter to override text colors
1026 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1028 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1032 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1033 View v
= super.getView(position
, convertView
, parent
);
1035 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1036 android
.R
.color
.white
));
1038 fixRoot((TextView
) v
);
1042 public View
getDropDownView(int position
, View convertView
,
1044 View v
= super.getDropDownView(position
, convertView
, parent
);
1046 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1047 android
.R
.color
.white
));
1049 fixRoot((TextView
) v
);
1053 private void fixRoot(TextView v
) {
1054 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1055 v
.setText(R
.string
.default_display_name_for_root_folder
);
1061 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1064 * {@link BroadcastReceiver} to enable syncing feedback in UI
1067 public void onReceive(Context context
, Intent intent
) {
1069 String event
= intent
.getAction();
1070 Log_OC
.d(TAG
, "Received broadcast " + event
);
1071 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1072 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1073 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1074 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1078 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1079 mSyncInProgress
= true
;
1082 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1083 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1085 if (currentDir
== null
) {
1086 // current folder was removed from the server
1087 Toast
.makeText( FileDisplayActivity
.this,
1088 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1094 if (currentFile
== null
&& !getFile().isFolder()) {
1095 // currently selected file was removed in the server, and now we know it
1096 cleanSecondFragment();
1097 currentFile
= currentDir
;
1100 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1101 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1102 if (fileListFragment
!= null
) {
1103 fileListFragment
.listDirectory(currentDir
);
1106 setFile(currentFile
);
1109 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1111 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1113 /// TODO refactor and make common
1114 synchResult
!= null
&& !synchResult
.isSuccess() &&
1115 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1116 synchResult
.isIdPRedirection() ||
1117 (synchResult
.isException() && synchResult
.getException()
1118 instanceof AuthenticatorException
))) {
1120 OwnCloudClient client
= null
;
1122 OwnCloudAccount ocAccount
=
1123 new OwnCloudAccount(getAccount(), context
);
1124 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1125 removeClientFor(ocAccount
));
1126 // TODO get rid of these exceptions
1127 } catch (AccountNotFoundException e
) {
1128 e
.printStackTrace();
1129 } catch (AuthenticatorException e
) {
1130 e
.printStackTrace();
1131 } catch (OperationCanceledException e
) {
1132 e
.printStackTrace();
1133 } catch (IOException e
) {
1134 e
.printStackTrace();
1137 if (client
!= null
) {
1138 OwnCloudCredentials cred
= client
.getCredentials();
1140 AccountManager am
= AccountManager
.get(context
);
1141 if (cred
.authTokenExpires()) {
1142 am
.invalidateAuthToken(
1147 am
.clearPassword(getAccount());
1152 requestCredentialsUpdate();
1156 removeStickyBroadcast(intent
);
1157 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1158 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1160 setBackgroundText();
1164 if (synchResult
!= null
) {
1165 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1166 mLastSslUntrustedServerResult
= synchResult
;
1169 } catch (RuntimeException e
) {
1170 // avoid app crashes after changing the serial id of RemoteOperationResult
1171 // in owncloud library with broadcast notifications pending to process
1172 removeStickyBroadcast(intent
);
1178 * Show a text message on screen view for notifying user if content is
1179 * loading or folder is empty
1181 private void setBackgroundText() {
1182 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1183 if (ocFileListFragment
!= null
) {
1184 int message
= R
.string
.file_list_loading
;
1185 if (!mSyncInProgress
) {
1186 // In case file list is empty
1187 message
= R
.string
.file_list_empty
;
1189 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1191 Log_OC
.e(TAG
, "OCFileListFragment is null");
1196 * Once the file upload has finished -> update view
1198 private class UploadFinishReceiver
extends BroadcastReceiver
{
1200 * Once the file upload has finished -> update view
1201 * @author David A. Velasco
1202 * {@link BroadcastReceiver} to enable upload feedback in UI
1205 public void onReceive(Context context
, Intent intent
) {
1207 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1208 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1209 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1210 OCFile currentDir
= getCurrentDir();
1211 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1212 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1214 if (sameAccount
&& isDescendant
) {
1215 refreshListOfFilesFragment();
1218 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1219 boolean renamedInUpload
= getFile().getRemotePath().
1220 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1221 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1223 FileFragment details
= getSecondFragment();
1224 boolean detailFragmentIsShown
= (details
!= null
&&
1225 details
instanceof FileDetailFragment
);
1227 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1228 if (uploadWasFine
) {
1229 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1231 if (renamedInUpload
) {
1232 String newName
= (new File(uploadedRemotePath
)).getName();
1233 Toast msg
= Toast
.makeText(
1236 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1241 if (uploadWasFine
|| getFile().fileExists()) {
1242 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1244 cleanSecondFragment();
1247 // Force the preview if the file is an image
1248 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1249 startImagePreview(getFile());
1250 } // TODO what about other kind of previews?
1254 if (intent
!= null
) {
1255 removeStickyBroadcast(intent
);
1265 * Class waiting for broadcast events from the {@link FielDownloader} service.
1267 * Updates the UI when a download is started or finished, provided that it is relevant for the
1270 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1272 public void onReceive(Context context
, Intent intent
) {
1274 boolean sameAccount
= isSameAccount(context
, intent
);
1275 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1276 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1278 if (sameAccount
&& isDescendant
) {
1279 refreshListOfFilesFragment();
1280 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1283 if (mWaitingToSend
!= null
) {
1284 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1285 if (mWaitingToSend
.isDown()) {
1286 sendDownloadedFile();
1291 if (intent
!= null
) {
1292 removeStickyBroadcast(intent
);
1297 private boolean isDescendant(String downloadedRemotePath
) {
1298 OCFile currentDir
= getCurrentDir();
1299 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1302 private boolean isSameAccount(Context context
, Intent intent
) {
1303 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1304 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1309 public void browseToRoot() {
1310 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1311 if (listOfFiles
!= null
) { // should never be null, indeed
1312 while (mDirectories
.getCount() > 1) {
1315 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1316 listOfFiles
.listDirectory(root
);
1317 setFile(listOfFiles
.getCurrentFile());
1318 startSyncFolderOperation(root
, false
);
1320 cleanSecondFragment();
1324 public void browseTo(OCFile folder
) {
1325 if (folder
== null
|| !folder
.isFolder()) {
1326 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1328 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1329 if (listOfFiles
!= null
) {
1330 setNavigationListWithFolder(folder
);
1331 listOfFiles
.listDirectory(folder
);
1332 setFile(listOfFiles
.getCurrentFile());
1333 startSyncFolderOperation(folder
, false
);
1335 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1337 cleanSecondFragment();
1344 * Updates action bar and second fragment, if in dual pane mode.
1347 public void onBrowsedDownTo(OCFile directory
) {
1348 pushDirname(directory
);
1349 cleanSecondFragment();
1352 startSyncFolderOperation(directory
, false
);
1357 * Shows the information of the {@link OCFile} received as a
1358 * parameter in the second fragment.
1360 * @param file {@link OCFile} whose details will be shown
1363 public void showDetails(OCFile file
) {
1364 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1365 setSecondFragment(detailFragment
);
1366 updateFragmentsVisibility(true
);
1367 updateNavigationElementsInActionBar(file
);
1375 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1376 ActionBar actionBar
= getSupportActionBar();
1377 if (chosenFile
== null
|| mDualPane
) {
1378 // only list of files - set for browsing through folders
1379 OCFile currentDir
= getCurrentDir();
1380 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1381 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1382 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1384 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1386 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1387 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1390 actionBar
.setDisplayHomeAsUpEnabled(true
);
1391 actionBar
.setDisplayShowTitleEnabled(true
);
1392 actionBar
.setTitle(chosenFile
.getFileName());
1393 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1399 protected ServiceConnection
newTransferenceServiceConnection() {
1400 return new ListServiceConnection();
1403 /** Defines callbacks for service binding, passed to bindService() */
1404 private class ListServiceConnection
implements ServiceConnection
{
1407 public void onServiceConnected(ComponentName component
, IBinder service
) {
1408 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1409 Log_OC
.d(TAG
, "Download service connected");
1410 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1411 if (mWaitingToPreview
!= null
)
1412 if (getStorageManager() != null
) {
1413 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1414 if (!mWaitingToPreview
.isDown()) {
1415 requestForDownload();
1419 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1420 Log_OC
.d(TAG
, "Upload service connected");
1421 mUploaderBinder
= (FileUploaderBinder
) service
;
1425 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1426 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1427 if (listOfFiles
!= null
) {
1428 listOfFiles
.listDirectory();
1430 FileFragment secondFragment
= getSecondFragment();
1431 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1432 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1433 detailFragment
.listenForTransferProgress();
1434 detailFragment
.updateFileDetails(false
, false
);
1439 public void onServiceDisconnected(ComponentName component
) {
1440 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1441 Log_OC
.d(TAG
, "Download service disconnected");
1442 mDownloaderBinder
= null
;
1443 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1444 Log_OC
.d(TAG
, "Upload service disconnected");
1445 mUploaderBinder
= null
;
1451 public void onSavedCertificate() {
1452 startSyncFolderOperation(getCurrentDir(), false
);
1457 public void onFailedSavingCertificate() {
1458 showDialog(DIALOG_CERT_NOT_SAVED
);
1462 public void onCancelCertificate() {
1467 * Updates the view associated to the activity after the finish of some operation over files
1468 * in the current account.
1470 * @param operation Removal operation performed.
1471 * @param result Result of the removal.
1474 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1475 super.onRemoteOperationFinish(operation
, result
);
1477 if (operation
instanceof RemoveFileOperation
) {
1478 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1480 } else if (operation
instanceof RenameFileOperation
) {
1481 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1483 } else if (operation
instanceof SynchronizeFileOperation
) {
1484 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1486 } else if (operation
instanceof CreateFolderOperation
) {
1487 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1489 } else if (operation
instanceof CreateShareOperation
) {
1490 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1492 } else if (operation
instanceof UnshareLinkOperation
) {
1493 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1495 } else if (operation
instanceof MoveFileOperation
) {
1496 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1502 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1503 if (result
.isSuccess()) {
1504 refreshShowDetails();
1505 refreshListOfFilesFragment();
1510 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1511 if (result
.isSuccess()) {
1512 refreshShowDetails();
1513 refreshListOfFilesFragment();
1515 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1516 cleanSecondFragment();
1517 refreshListOfFilesFragment();
1521 private void refreshShowDetails() {
1522 FileFragment details
= getSecondFragment();
1523 if (details
!= null
) {
1524 OCFile file
= details
.getFile();
1526 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1527 if (details
instanceof PreviewMediaFragment
) {
1528 // Refresh OCFile of the fragment
1529 ((PreviewMediaFragment
) details
).updateFile(file
);
1534 invalidateOptionsMenu();
1539 * Updates the view associated to the activity after the finish of an operation trying to remove a
1542 * @param operation Removal operation performed.
1543 * @param result Result of the removal.
1545 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1546 dismissLoadingDialog();
1548 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1552 if (result
.isSuccess()) {
1553 OCFile removedFile
= operation
.getFile();
1554 FileFragment second
= getSecondFragment();
1555 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1556 if (second
instanceof PreviewMediaFragment
) {
1557 ((PreviewMediaFragment
)second
).stopPreview(true
);
1559 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1560 cleanSecondFragment();
1562 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1563 refreshListOfFilesFragment();
1565 invalidateOptionsMenu();
1567 if (result
.isSslRecoverableException()) {
1568 mLastSslUntrustedServerResult
= result
;
1569 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1576 * Updates the view associated to the activity after the finish of an operation trying to move a
1579 * @param operation Move operation performed.
1580 * @param result Result of the move operation.
1582 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1583 if (result
.isSuccess()) {
1584 dismissLoadingDialog();
1585 refreshListOfFilesFragment();
1587 dismissLoadingDialog();
1589 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1590 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1594 } catch (NotFoundException e
) {
1595 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1602 * Updates the view associated to the activity after the finish of an operation trying to rename a
1605 * @param operation Renaming operation performed.
1606 * @param result Result of the renaming.
1608 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1609 dismissLoadingDialog();
1610 OCFile renamedFile
= operation
.getFile();
1611 if (result
.isSuccess()) {
1612 FileFragment details
= getSecondFragment();
1613 if (details
!= null
) {
1614 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1615 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1616 showDetails(renamedFile
);
1618 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1619 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1620 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1621 int position
= ((PreviewMediaFragment
)details
).getPosition();
1622 startMediaPreview(renamedFile
, position
, true
);
1624 getFileOperationsHelper().openFile(renamedFile
);
1629 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1630 refreshListOfFilesFragment();
1634 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1638 if (result
.isSslRecoverableException()) {
1639 mLastSslUntrustedServerResult
= result
;
1640 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1645 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1646 dismissLoadingDialog();
1647 OCFile syncedFile
= operation
.getLocalFile();
1648 if (!result
.isSuccess()) {
1649 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1650 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1651 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1652 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1658 if (operation
.transferWasRequested()) {
1659 onTransferStateChanged(syncedFile
, true
, true
);
1662 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1670 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1672 * @param operation Creation operation performed.
1673 * @param result Result of the creation.
1675 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1676 if (result
.isSuccess()) {
1677 dismissLoadingDialog();
1678 refreshListOfFilesFragment();
1680 dismissLoadingDialog();
1682 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1683 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1687 } catch (NotFoundException e
) {
1688 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1698 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1699 refreshListOfFilesFragment();
1700 FileFragment details
= getSecondFragment();
1701 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1702 if (downloading
|| uploading
) {
1703 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1705 if (!file
.fileExists()) {
1706 cleanSecondFragment();
1708 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1716 private void requestForDownload() {
1717 Account account
= getAccount();
1718 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1719 Intent i
= new Intent(this, FileDownloader
.class);
1720 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1721 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1727 private OCFile
getCurrentDir() {
1728 OCFile file
= getFile();
1730 if (file
.isFolder()) {
1732 } else if (getStorageManager() != null
) {
1733 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1734 return getStorageManager().getFileByPath(parentPath
);
1740 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1741 long currentSyncTime
= System
.currentTimeMillis();
1743 mSyncInProgress
= true
;
1745 // perform folder synchronization
1746 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1749 getFileOperationsHelper().isSharedSupported(),
1751 getStorageManager(),
1753 getApplicationContext()
1755 synchFolderOp
.execute(getAccount(), this, null
, null
);
1757 setSupportProgressBarIndeterminateVisibility(true
);
1759 setBackgroundText();
1763 * Show untrusted cert dialog
1765 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1766 // Show a dialog with the certificate info
1767 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1768 FragmentManager fm
= getSupportFragmentManager();
1769 FragmentTransaction ft
= fm
.beginTransaction();
1770 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1773 private void requestForDownload(OCFile file
) {
1774 Account account
= getAccount();
1775 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1776 Intent i
= new Intent(this, FileDownloader
.class);
1777 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1778 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1783 private void sendDownloadedFile(){
1784 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1785 mWaitingToSend
= null
;
1790 * Requests the download of the received {@link OCFile} , updates the UI
1791 * to monitor the download progress and prepares the activity to send the file
1792 * when the download finishes.
1794 * @param file {@link OCFile} to download and preview.
1796 public void startDownloadForSending(OCFile file
) {
1797 mWaitingToSend
= file
;
1798 requestForDownload(mWaitingToSend
);
1799 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1800 updateFragmentsVisibility(hasSecondFragment
);
1804 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1806 * @param file Image {@link OCFile} to show.
1808 public void startImagePreview(OCFile file
) {
1809 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1810 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1811 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1812 startActivity(showDetailsIntent
);
1817 * Stars the preview of an already down media {@link OCFile}.
1819 * @param file Media {@link OCFile} to preview.
1820 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1821 * @param autoplay When 'true', the playback will start without user interactions.
1823 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1824 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1825 setSecondFragment(mediaFragment
);
1826 updateFragmentsVisibility(true
);
1827 updateNavigationElementsInActionBar(file
);
1832 * Requests the download of the received {@link OCFile} , updates the UI
1833 * to monitor the download progress and prepares the activity to preview
1834 * or open the file when the download finishes.
1836 * @param file {@link OCFile} to download and preview.
1838 public void startDownloadForPreview(OCFile file
) {
1839 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1840 setSecondFragment(detailFragment
);
1841 mWaitingToPreview
= file
;
1842 requestForDownload();
1843 updateFragmentsVisibility(true
);
1844 updateNavigationElementsInActionBar(file
);
1849 public void cancelTransference(OCFile file
) {
1850 getFileOperationsHelper().cancelTransference(file
);
1851 if (mWaitingToPreview
!= null
&&
1852 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1853 mWaitingToPreview
= null
;
1855 if (mWaitingToSend
!= null
&&
1856 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1857 mWaitingToSend
= null
;
1859 onTransferStateChanged(file
, false
, false
);
1863 public void onRefresh(boolean ignoreETag
) {
1864 refreshList(ignoreETag
);
1868 public void onRefresh() {
1872 private void refreshList(boolean ignoreETag
) {
1873 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1874 if (listOfFiles
!= null
) {
1875 OCFile folder
= listOfFiles
.getCurrentFile();
1876 if (folder
!= null
) {
1877 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1878 listDirectory(mFile);*/
1879 startSyncFolderOperation(folder
, ignoreETag
);
1884 private void sortByDate(boolean ascending
){
1885 getListOfFilesFragment().sortByDate(ascending
);
1888 private void sortBySize(boolean ascending
){
1889 getListOfFilesFragment().sortBySize(ascending
);
1892 private void sortByName(boolean ascending
){
1893 getListOfFilesFragment().sortByName(ascending
);