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
.SuppressLint
;
29 import android
.annotation
.TargetApi
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.ContentUris
;
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
.Environment
;
50 import android
.os
.IBinder
;
51 import android
.preference
.PreferenceManager
;
52 import android
.provider
.DocumentsContract
;
53 import android
.provider
.MediaStore
;
54 import android
.provider
.OpenableColumns
;
55 import android
.support
.v4
.app
.Fragment
;
56 import android
.support
.v4
.app
.FragmentManager
;
57 import android
.support
.v4
.app
.FragmentTransaction
;
58 import android
.util
.Log
;
59 import android
.view
.View
;
60 import android
.view
.ViewGroup
;
61 import android
.widget
.ArrayAdapter
;
62 import android
.widget
.TextView
;
63 import android
.widget
.Toast
;
65 import com
.actionbarsherlock
.app
.ActionBar
;
66 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
67 import com
.actionbarsherlock
.view
.Menu
;
68 import com
.actionbarsherlock
.view
.MenuInflater
;
69 import com
.actionbarsherlock
.view
.MenuItem
;
70 import com
.actionbarsherlock
.view
.Window
;
71 import com
.owncloud
.android
.BuildConfig
;
72 import com
.owncloud
.android
.MainApp
;
73 import com
.owncloud
.android
.R
;
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
.RefreshFolderOperation
;
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
;
165 protected void onCreate(Bundle savedInstanceState
) {
166 Log_OC
.d(TAG
, "onCreate() start");
167 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
169 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
171 // PIN CODE request ; best location is to decide, let's try this first
172 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
174 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
178 /// grant that FileObserverService is watching favourite files
179 if (savedInstanceState
== null
) {
180 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
181 startService(initObserversIntent
);
184 /// Load of saved instance state
185 if(savedInstanceState
!= null
) {
186 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
187 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
188 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
191 mWaitingToPreview
= null
;
192 mSyncInProgress
= false
;
193 mWaitingToSend
= null
;
198 // Inflate and set the layout view
199 setContentView(R
.layout
.files
);
200 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
201 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
202 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
203 if (savedInstanceState
== null
) {
204 createMinFragments();
208 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
209 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
210 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
214 Log_OC
.d(TAG
, "onCreate() end");
218 protected void onStart() {
220 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
224 protected void onDestroy() {
229 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
232 protected void onAccountSet(boolean stateWasRecovered
) {
233 super.onAccountSet(stateWasRecovered
);
234 if (getAccount() != null
) {
235 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
236 OCFile file
= getFile();
237 // get parent from path
238 String parentPath
= "";
240 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
241 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
242 // get parent from path
243 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
244 if (getStorageManager().getFileByPath(parentPath
) == null
)
245 file
= null
; // not able to know the directory where the file is uploading
247 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
251 // fall back to root folder
252 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
255 setNavigationListWithFolder(file
);
257 if (!stateWasRecovered
) {
258 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
259 initFragmentsWithFile();
260 if (file
.isFolder()) {
261 startSyncFolderOperation(file
, false
);
265 updateFragmentsVisibility(!file
.isFolder());
266 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
272 private void setNavigationListWithFolder(OCFile file
) {
273 mDirectories
.clear();
274 OCFile fileIt
= file
;
276 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
277 if (fileIt
.isFolder()) {
278 mDirectories
.add(fileIt
.getFileName());
280 // get parent from path
281 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
282 fileIt
= getStorageManager().getFileByPath(parentPath
);
284 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
302 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
306 OCFile file
= getFile();
307 Fragment secondFragment
= chooseInitialSecondFragment(file
);
308 if (secondFragment
!= null
) {
309 setSecondFragment(secondFragment
);
310 updateFragmentsVisibility(true
);
311 updateNavigationElementsInActionBar(file
);
314 cleanSecondFragment();
318 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
319 if (getAccount() == null
) {
320 Log_OC
.wtf(TAG
, "\t account is NULL");
322 if (getFile() == null
) {
323 Log_OC
.wtf(TAG
, "\t file is NULL");
328 private Fragment
chooseInitialSecondFragment(OCFile file
) {
329 Fragment secondFragment
= null
;
330 if (file
!= null
&& !file
.isFolder()) {
331 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
332 && file
.getLastSyncDateForProperties() > 0 // temporal fix
334 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
335 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
336 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
339 secondFragment
= new FileDetailFragment(file
, getAccount());
342 return secondFragment
;
347 * Replaces the second fragment managed by the activity with the received as
350 * Assumes never will be more than two fragments managed at the same time.
352 * @param fragment New second Fragment to set.
354 private void setSecondFragment(Fragment fragment
) {
355 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
356 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
357 transaction
.commit();
361 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
363 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
366 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
367 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
370 } else if (existsSecondFragment
) {
371 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
372 mLeftFragmentContainer
.setVisibility(View
.GONE
);
374 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
382 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
383 mRightFragmentContainer
.setVisibility(View
.GONE
);
389 private OCFileListFragment
getListOfFilesFragment() {
390 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
391 if (listOfFiles
!= null
) {
392 return (OCFileListFragment
)listOfFiles
;
394 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
398 public FileFragment
getSecondFragment() {
399 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
400 if (second
!= null
) {
401 return (FileFragment
)second
;
406 protected void cleanSecondFragment() {
407 Fragment second
= getSecondFragment();
408 if (second
!= null
) {
409 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
413 updateFragmentsVisibility(false
);
414 updateNavigationElementsInActionBar(null
);
417 protected void refreshListOfFilesFragment() {
418 OCFileListFragment fileListFragment
= getListOfFilesFragment();
419 if (fileListFragment
!= null
) {
420 fileListFragment
.listDirectory();
424 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
425 FileFragment secondFragment
= getSecondFragment();
426 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
427 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
428 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
429 OCFile fileInFragment
= detailsFragment
.getFile();
430 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
431 // the user browsed to other file ; forget the automatic preview
432 mWaitingToPreview
= null
;
434 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
435 // grant that the right panel updates the progress bar
436 detailsFragment
.listenForTransferProgress();
437 detailsFragment
.updateFileDetails(true
, false
);
439 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
440 // update the right panel
441 boolean detailsFragmentChanged
= false
;
444 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
445 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
446 startMediaPreview(mWaitingToPreview
, 0, true
);
447 detailsFragmentChanged
= true
;
449 getFileOperationsHelper().openFile(mWaitingToPreview
);
452 mWaitingToPreview
= null
;
454 if (!detailsFragmentChanged
) {
455 detailsFragment
.updateFileDetails(false
, (success
));
462 public boolean onPrepareOptionsMenu(Menu menu
) {
463 if (BuildConfig
.DEBUG
) {
464 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
466 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
468 return super.onPrepareOptionsMenu(menu
);
472 public boolean onCreateOptionsMenu(Menu menu
) {
473 MenuInflater inflater
= getSherlock().getMenuInflater();
474 inflater
.inflate(R
.menu
.main_menu
, menu
);
479 public boolean onOptionsItemSelected(MenuItem item
) {
480 boolean retval
= true
;
481 switch (item
.getItemId()) {
482 case R
.id
.action_create_dir
: {
483 CreateFolderDialogFragment dialog
=
484 CreateFolderDialogFragment
.newInstance(getCurrentDir());
485 dialog
.show(getSupportFragmentManager(), "createdirdialog");
488 case R
.id
.action_sync_account
: {
489 startSynchronization();
492 case R
.id
.action_upload
: {
493 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
496 case R
.id
.action_settings
: {
497 Intent settingsIntent
= new Intent(this, Preferences
.class);
498 startActivity(settingsIntent
);
501 case R
.id
.action_logger
: {
502 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
503 startActivity(loggerIntent
);
506 case android
.R
.id
.home
: {
507 FileFragment second
= getSecondFragment();
508 OCFile currentDir
= getCurrentDir();
509 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
510 (second
!= null
&& second
.getFile() != null
)) {
516 case R
.id
.action_sort
: {
517 SharedPreferences appPreferences
= PreferenceManager
518 .getDefaultSharedPreferences(this);
520 // Read sorting order, default to sort by name ascending
521 Integer sortOrder
= appPreferences
522 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
524 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
525 builder
.setTitle(R
.string
.actionbar_sort_title
)
526 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
527 public void onClick(DialogInterface dialog
, int which
) {
537 // TODO re-enable when server-side folder size calculation is available
539 // sortBySize(false);
547 builder
.create().show();
551 retval
= super.onOptionsItemSelected(item
);
556 private void startSynchronization() {
557 Log_OC
.e(TAG
, "Got to start sync");
558 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
559 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
560 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
561 Bundle bundle
= new Bundle();
562 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
563 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
564 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
565 ContentResolver
.requestSync(
567 MainApp
.getAuthority(), bundle
);
569 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
570 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
571 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
572 builder
.setExpedited(true
);
573 builder
.setManual(true
);
576 // Fix bug in Android Lollipop when you click on refresh the whole account
577 Bundle extras
= new Bundle();
578 builder
.setExtras(extras
);
580 SyncRequest request
= builder
.build();
581 ContentResolver
.requestSync(request
);
587 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
588 if (itemPosition
!= 0) {
589 String targetPath
= "";
590 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
591 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
593 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
594 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
595 if (targetFolder
!= null
) {
596 browseTo(targetFolder
);
599 // the next operation triggers a new call to this method, but it's necessary to
600 // ensure that the name exposed in the action bar is the current directory when the
601 // user selected it in the navigation list
602 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
603 getSupportActionBar().setSelectedNavigationItem(0);
609 * Called, when the user selected something for uploading
612 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
613 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
614 super.onActivityResult(requestCode
, resultCode
, data
);
616 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
617 //getClipData is only supported on api level 16+, Jelly Bean
618 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
619 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
620 Intent intent
= new Intent();
621 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
622 requestSimpleUpload(intent
, resultCode
);
625 requestSimpleUpload(data
, resultCode
);
627 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
628 requestMultipleUpload(data
, resultCode
);
630 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
632 final Intent fData
= data
;
633 final int fResultCode
= resultCode
;
634 getHandler().postDelayed(
638 requestMoveOperation(fData
, fResultCode
);
641 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
646 private void requestMultipleUpload(Intent data
, int resultCode
) {
647 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
648 if (filePaths
!= null
) {
649 String
[] remotePaths
= new String
[filePaths
.length
];
650 String remotePathBase
= "";
651 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
652 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
654 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
655 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
656 for (int j
= 0; j
< remotePaths
.length
; j
++) {
657 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
660 Intent i
= new Intent(this, FileUploader
.class);
661 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
662 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
663 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
664 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
665 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
666 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
670 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
671 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
678 private void requestSimpleUpload(Intent data
, int resultCode
) {
679 String filepath
= null
;
680 String mimeType
= null
;
682 Uri selectedImageUri
= data
.getData();
685 mimeType
= getContentResolver().getType(selectedImageUri
);
687 String filemanagerstring
= selectedImageUri
.getPath();
688 String selectedImagePath
= getPath(selectedImageUri
);
690 if (selectedImagePath
!= null
)
691 filepath
= selectedImagePath
;
693 filepath
= filemanagerstring
;
695 } catch (Exception e
) {
696 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
700 if (filepath
== null
) {
701 Log_OC
.e(TAG
, "Couldnt resolve path to file");
702 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
708 Intent i
= new Intent(this, FileUploader
.class);
709 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
711 String remotepath
= new String();
712 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
713 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
715 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
716 remotepath
+= OCFile
.PATH_SEPARATOR
;
718 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
720 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
721 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
724 if (cursor
!= null
&& cursor
.moveToFirst()) {
725 String displayName
= cursor
.getString(
726 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
727 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
729 displayName
.replace(File
.separatorChar
, '_');
730 displayName
.replace(File
.pathSeparatorChar
, '_');
731 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
739 remotepath
+= new File(filepath
).getName();
742 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
743 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
744 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
745 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
746 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
747 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
752 * Request the operation for moving the file/folder from one path to another
754 * @param data Intent received
755 * @param resultCode Result code received
757 private void requestMoveOperation(Intent data
, int resultCode
) {
758 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
759 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
760 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
764 public void onBackPressed() {
765 OCFileListFragment listOfFiles
= getListOfFilesFragment();
766 if (mDualPane
|| getSecondFragment() == null
) {
767 if (listOfFiles
!= null
) { // should never be null, indeed
768 if (mDirectories
.getCount() <= 1) {
772 int levelsUp
= listOfFiles
.onBrowseUp();
773 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
778 if (listOfFiles
!= null
) { // should never be null, indeed
779 setFile(listOfFiles
.getCurrentFile());
781 cleanSecondFragment();
786 protected void onSaveInstanceState(Bundle outState
) {
787 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
788 Log_OC
.e(TAG
, "onSaveInstanceState() start");
789 super.onSaveInstanceState(outState
);
790 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
791 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
792 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
793 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
795 Log_OC
.d(TAG
, "onSaveInstanceState() end");
801 protected void onResume() {
803 Log_OC
.e(TAG
, "onResume() start");
805 // refresh list of files
806 refreshListOfFilesFragment();
808 // Listen for sync messages
809 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
810 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
811 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
812 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
813 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
814 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
815 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
816 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
818 // Listen for upload messages
819 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
820 mUploadFinishReceiver
= new UploadFinishReceiver();
821 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
823 // Listen for download messages
824 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
825 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
826 mDownloadFinishReceiver
= new DownloadFinishReceiver();
827 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
829 Log_OC
.d(TAG
, "onResume() end");
834 protected void onPause() {
835 Log_OC
.e(TAG
, "onPause() start");
836 if (mSyncBroadcastReceiver
!= null
) {
837 unregisterReceiver(mSyncBroadcastReceiver
);
838 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
839 mSyncBroadcastReceiver
= null
;
841 if (mUploadFinishReceiver
!= null
) {
842 unregisterReceiver(mUploadFinishReceiver
);
843 mUploadFinishReceiver
= null
;
845 if (mDownloadFinishReceiver
!= null
) {
846 unregisterReceiver(mDownloadFinishReceiver
);
847 mDownloadFinishReceiver
= null
;
851 Log_OC
.d(TAG
, "onPause() end");
857 protected Dialog
onCreateDialog(int id
) {
858 Dialog dialog
= null
;
859 AlertDialog
.Builder builder
;
861 case DIALOG_SHORT_WAIT
: {
862 ProgressDialog working_dialog
= new ProgressDialog(this);
863 working_dialog
.setMessage(getResources().getString(
864 R
.string
.wait_a_moment
));
865 working_dialog
.setIndeterminate(true
);
866 working_dialog
.setCancelable(false
);
867 dialog
= working_dialog
;
870 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
873 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
874 getString(R
.string
.actionbar_upload_from_apps
) };
876 builder
= new AlertDialog
.Builder(this);
877 builder
.setTitle(R
.string
.actionbar_upload
);
878 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
879 public void onClick(DialogInterface dialog
, int item
) {
882 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
883 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
884 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
886 // TODO create and handle new fragment
887 // LocalFileListFragment
889 } else if (item
== 1) {
890 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
891 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
892 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
893 if(Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
894 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
896 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
897 ACTION_SELECT_CONTENT_FROM_APPS
);
901 dialog
= builder
.create();
904 case DIALOG_CERT_NOT_SAVED
: {
905 builder
= new AlertDialog
.Builder(this);
906 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
907 builder
.setCancelable(false
);
908 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
910 public void onClick(DialogInterface dialog
, int which
) {
914 dialog
= builder
.create();
925 * Translates a content URI of an content to a physical path on the disk
927 * @param uri The URI to resolve
928 * @return The path to the content or null if it could not be found
930 public String
getPath(Uri uri
) {
931 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
934 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
935 // ExternalStorageProvider
936 if (UriUtils
.isExternalStorageDocument(uri
)) {
937 final String docId
= DocumentsContract
.getDocumentId(uri
);
938 final String
[] split
= docId
.split(":");
939 final String type
= split
[0];
941 if ("primary".equalsIgnoreCase(type
)) {
942 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
946 else if (UriUtils
.isDownloadsDocument(uri
)) {
948 final String id
= DocumentsContract
.getDocumentId(uri
);
949 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
952 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
955 else if (UriUtils
.isMediaDocument(uri
)) {
956 final String docId
= DocumentsContract
.getDocumentId(uri
);
957 final String
[] split
= docId
.split(":");
958 final String type
= split
[0];
960 Uri contentUri
= null
;
961 if ("image".equals(type
)) {
962 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
963 } else if ("video".equals(type
)) {
964 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
965 } else if ("audio".equals(type
)) {
966 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
969 final String selection
= "_id=?";
970 final String
[] selectionArgs
= new String
[] { split
[1] };
972 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
974 // Documents providers returned as content://...
975 else if (UriUtils
.isContentDocument(uri
)) {
976 return uri
.toString();
979 // MediaStore (and general)
980 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
982 // Return the remote address
983 if (UriUtils
.isGooglePhotosUri(uri
))
984 return uri
.getLastPathSegment();
986 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
989 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
990 return uri
.getPath();
996 * Pushes a directory to the drop down list
997 * @param directory to push
998 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1000 public void pushDirname(OCFile directory
) {
1001 if(!directory
.isFolder()){
1002 throw new IllegalArgumentException("Only directories may be pushed!");
1004 mDirectories
.insert(directory
.getFileName(), 0);
1009 * Pops a directory name from the drop down list
1010 * @return True, unless the stack is empty
1012 public boolean popDirname() {
1013 mDirectories
.remove(mDirectories
.getItem(0));
1014 return !mDirectories
.isEmpty();
1017 // Custom array adapter to override text colors
1018 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1020 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1024 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1025 View v
= super.getView(position
, convertView
, parent
);
1027 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1028 android
.R
.color
.white
));
1030 fixRoot((TextView
) v
);
1034 public View
getDropDownView(int position
, View convertView
,
1036 View v
= super.getDropDownView(position
, convertView
, parent
);
1038 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1039 android
.R
.color
.white
));
1041 fixRoot((TextView
) v
);
1045 private void fixRoot(TextView v
) {
1046 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1047 v
.setText(R
.string
.default_display_name_for_root_folder
);
1053 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1056 * {@link BroadcastReceiver} to enable syncing feedback in UI
1059 public void onReceive(Context context
, Intent intent
) {
1061 String event
= intent
.getAction();
1062 Log_OC
.d(TAG
, "Received broadcast " + event
);
1063 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1064 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1065 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1066 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1070 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1071 mSyncInProgress
= true
;
1074 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1075 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1077 if (currentDir
== null
) {
1078 // current folder was removed from the server
1079 Toast
.makeText( FileDisplayActivity
.this,
1080 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1086 if (currentFile
== null
&& !getFile().isFolder()) {
1087 // currently selected file was removed in the server, and now we know it
1088 cleanSecondFragment();
1089 currentFile
= currentDir
;
1092 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1093 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1094 if (fileListFragment
!= null
) {
1095 fileListFragment
.listDirectory(currentDir
);
1098 setFile(currentFile
);
1101 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1103 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1105 /// TODO refactor and make common
1106 synchResult
!= null
&& !synchResult
.isSuccess() &&
1107 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1108 synchResult
.isIdPRedirection() ||
1109 (synchResult
.isException() && synchResult
.getException()
1110 instanceof AuthenticatorException
))) {
1112 OwnCloudClient client
= null
;
1114 OwnCloudAccount ocAccount
=
1115 new OwnCloudAccount(getAccount(), context
);
1116 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1117 removeClientFor(ocAccount
));
1118 // TODO get rid of these exceptions
1119 } catch (AccountNotFoundException e
) {
1120 e
.printStackTrace();
1121 } catch (AuthenticatorException e
) {
1122 e
.printStackTrace();
1123 } catch (OperationCanceledException e
) {
1124 e
.printStackTrace();
1125 } catch (IOException e
) {
1126 e
.printStackTrace();
1129 if (client
!= null
) {
1130 OwnCloudCredentials cred
= client
.getCredentials();
1132 AccountManager am
= AccountManager
.get(context
);
1133 if (cred
.authTokenExpires()) {
1134 am
.invalidateAuthToken(
1139 am
.clearPassword(getAccount());
1144 requestCredentialsUpdate();
1148 removeStickyBroadcast(intent
);
1149 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1150 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1152 setBackgroundText();
1156 if (synchResult
!= null
) {
1157 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1158 mLastSslUntrustedServerResult
= synchResult
;
1161 } catch (RuntimeException e
) {
1162 // avoid app crashes after changing the serial id of RemoteOperationResult
1163 // in owncloud library with broadcast notifications pending to process
1164 removeStickyBroadcast(intent
);
1170 * Show a text message on screen view for notifying user if content is
1171 * loading or folder is empty
1173 private void setBackgroundText() {
1174 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1175 if (ocFileListFragment
!= null
) {
1176 int message
= R
.string
.file_list_loading
;
1177 if (!mSyncInProgress
) {
1178 // In case file list is empty
1179 message
= R
.string
.file_list_empty
;
1181 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1183 Log_OC
.e(TAG
, "OCFileListFragment is null");
1188 * Once the file upload has finished -> update view
1190 private class UploadFinishReceiver
extends BroadcastReceiver
{
1192 * Once the file upload has finished -> update view
1193 * @author David A. Velasco
1194 * {@link BroadcastReceiver} to enable upload feedback in UI
1197 public void onReceive(Context context
, Intent intent
) {
1199 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1200 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1201 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1202 OCFile currentDir
= getCurrentDir();
1203 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1204 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1206 if (sameAccount
&& isDescendant
) {
1207 refreshListOfFilesFragment();
1210 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1211 boolean renamedInUpload
= getFile().getRemotePath().
1212 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1213 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1215 FileFragment details
= getSecondFragment();
1216 boolean detailFragmentIsShown
= (details
!= null
&&
1217 details
instanceof FileDetailFragment
);
1219 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1220 if (uploadWasFine
) {
1221 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1223 if (renamedInUpload
) {
1224 String newName
= (new File(uploadedRemotePath
)).getName();
1225 Toast msg
= Toast
.makeText(
1228 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1233 if (uploadWasFine
|| getFile().fileExists()) {
1234 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1236 cleanSecondFragment();
1239 // Force the preview if the file is an image
1240 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1241 startImagePreview(getFile());
1242 } // TODO what about other kind of previews?
1246 if (intent
!= null
) {
1247 removeStickyBroadcast(intent
);
1257 * Class waiting for broadcast events from the {@link FielDownloader} service.
1259 * Updates the UI when a download is started or finished, provided that it is relevant for the
1262 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1264 public void onReceive(Context context
, Intent intent
) {
1266 boolean sameAccount
= isSameAccount(context
, intent
);
1267 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1268 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1270 if (sameAccount
&& isDescendant
) {
1271 refreshListOfFilesFragment();
1272 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1275 if (mWaitingToSend
!= null
) {
1276 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1277 if (mWaitingToSend
.isDown()) {
1278 sendDownloadedFile();
1283 if (intent
!= null
) {
1284 removeStickyBroadcast(intent
);
1289 private boolean isDescendant(String downloadedRemotePath
) {
1290 OCFile currentDir
= getCurrentDir();
1291 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1294 private boolean isSameAccount(Context context
, Intent intent
) {
1295 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1296 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1301 public void browseToRoot() {
1302 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1303 if (listOfFiles
!= null
) { // should never be null, indeed
1304 while (mDirectories
.getCount() > 1) {
1307 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1308 listOfFiles
.listDirectory(root
);
1309 setFile(listOfFiles
.getCurrentFile());
1310 startSyncFolderOperation(root
, false
);
1312 cleanSecondFragment();
1316 public void browseTo(OCFile folder
) {
1317 if (folder
== null
|| !folder
.isFolder()) {
1318 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1320 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1321 if (listOfFiles
!= null
) {
1322 setNavigationListWithFolder(folder
);
1323 listOfFiles
.listDirectory(folder
);
1324 setFile(listOfFiles
.getCurrentFile());
1325 startSyncFolderOperation(folder
, false
);
1327 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1329 cleanSecondFragment();
1336 * Updates action bar and second fragment, if in dual pane mode.
1339 public void onBrowsedDownTo(OCFile directory
) {
1340 pushDirname(directory
);
1341 cleanSecondFragment();
1344 startSyncFolderOperation(directory
, false
);
1349 * Shows the information of the {@link OCFile} received as a
1350 * parameter in the second fragment.
1352 * @param file {@link OCFile} whose details will be shown
1355 public void showDetails(OCFile file
) {
1356 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1357 setSecondFragment(detailFragment
);
1358 updateFragmentsVisibility(true
);
1359 updateNavigationElementsInActionBar(file
);
1367 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1368 ActionBar actionBar
= getSupportActionBar();
1369 if (chosenFile
== null
|| mDualPane
) {
1370 // only list of files - set for browsing through folders
1371 OCFile currentDir
= getCurrentDir();
1372 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1373 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1374 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1376 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1378 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1379 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1382 actionBar
.setDisplayHomeAsUpEnabled(true
);
1383 actionBar
.setDisplayShowTitleEnabled(true
);
1384 actionBar
.setTitle(chosenFile
.getFileName());
1385 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1391 protected ServiceConnection
newTransferenceServiceConnection() {
1392 return new ListServiceConnection();
1395 /** Defines callbacks for service binding, passed to bindService() */
1396 private class ListServiceConnection
implements ServiceConnection
{
1399 public void onServiceConnected(ComponentName component
, IBinder service
) {
1400 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1401 Log_OC
.d(TAG
, "Download service connected");
1402 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1403 if (mWaitingToPreview
!= null
)
1404 if (getStorageManager() != null
) {
1405 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1406 if (!mWaitingToPreview
.isDown()) {
1407 requestForDownload();
1411 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1412 Log_OC
.d(TAG
, "Upload service connected");
1413 mUploaderBinder
= (FileUploaderBinder
) service
;
1417 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1418 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1419 if (listOfFiles
!= null
) {
1420 listOfFiles
.listDirectory();
1422 FileFragment secondFragment
= getSecondFragment();
1423 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1424 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1425 detailFragment
.listenForTransferProgress();
1426 detailFragment
.updateFileDetails(false
, false
);
1431 public void onServiceDisconnected(ComponentName component
) {
1432 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1433 Log_OC
.d(TAG
, "Download service disconnected");
1434 mDownloaderBinder
= null
;
1435 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1436 Log_OC
.d(TAG
, "Upload service disconnected");
1437 mUploaderBinder
= null
;
1445 * Launch an intent to request the PIN code to the user before letting him use the app
1447 private void requestPinCode() {
1448 boolean pinStart
= false
;
1449 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1450 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1452 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1453 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1460 public void onSavedCertificate() {
1461 startSyncFolderOperation(getCurrentDir(), false
);
1466 public void onFailedSavingCertificate() {
1467 showDialog(DIALOG_CERT_NOT_SAVED
);
1471 public void onCancelCertificate() {
1476 * Updates the view associated to the activity after the finish of some operation over files
1477 * in the current account.
1479 * @param operation Removal operation performed.
1480 * @param result Result of the removal.
1483 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1484 super.onRemoteOperationFinish(operation
, result
);
1486 if (operation
instanceof RemoveFileOperation
) {
1487 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1489 } else if (operation
instanceof RenameFileOperation
) {
1490 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1492 } else if (operation
instanceof SynchronizeFileOperation
) {
1493 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1495 } else if (operation
instanceof CreateFolderOperation
) {
1496 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1498 } else if (operation
instanceof CreateShareOperation
) {
1499 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1501 } else if (operation
instanceof UnshareLinkOperation
) {
1502 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1504 } else if (operation
instanceof MoveFileOperation
) {
1505 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1511 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1512 if (result
.isSuccess()) {
1513 refreshShowDetails();
1514 refreshListOfFilesFragment();
1519 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1520 if (result
.isSuccess()) {
1521 refreshShowDetails();
1522 refreshListOfFilesFragment();
1524 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1525 cleanSecondFragment();
1526 refreshListOfFilesFragment();
1530 private void refreshShowDetails() {
1531 FileFragment details
= getSecondFragment();
1532 if (details
!= null
) {
1533 OCFile file
= details
.getFile();
1535 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1536 if (details
instanceof PreviewMediaFragment
) {
1537 // Refresh OCFile of the fragment
1538 ((PreviewMediaFragment
) details
).updateFile(file
);
1543 invalidateOptionsMenu();
1548 * Updates the view associated to the activity after the finish of an operation trying to remove a
1551 * @param operation Removal operation performed.
1552 * @param result Result of the removal.
1554 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1555 dismissLoadingDialog();
1557 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1561 if (result
.isSuccess()) {
1562 OCFile removedFile
= operation
.getFile();
1563 FileFragment second
= getSecondFragment();
1564 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1565 if (second
instanceof PreviewMediaFragment
) {
1566 ((PreviewMediaFragment
)second
).stopPreview(true
);
1568 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1569 cleanSecondFragment();
1571 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1572 refreshListOfFilesFragment();
1574 invalidateOptionsMenu();
1576 if (result
.isSslRecoverableException()) {
1577 mLastSslUntrustedServerResult
= result
;
1578 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1585 * Updates the view associated to the activity after the finish of an operation trying to move a
1588 * @param operation Move operation performed.
1589 * @param result Result of the move operation.
1591 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1592 if (result
.isSuccess()) {
1593 dismissLoadingDialog();
1594 refreshListOfFilesFragment();
1596 dismissLoadingDialog();
1598 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1599 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1603 } catch (NotFoundException e
) {
1604 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1611 * Updates the view associated to the activity after the finish of an operation trying to rename a
1614 * @param operation Renaming operation performed.
1615 * @param result Result of the renaming.
1617 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1618 dismissLoadingDialog();
1619 OCFile renamedFile
= operation
.getFile();
1620 if (result
.isSuccess()) {
1621 FileFragment details
= getSecondFragment();
1622 if (details
!= null
) {
1623 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1624 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1625 showDetails(renamedFile
);
1627 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1628 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1629 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1630 int position
= ((PreviewMediaFragment
)details
).getPosition();
1631 startMediaPreview(renamedFile
, position
, true
);
1633 getFileOperationsHelper().openFile(renamedFile
);
1638 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1639 refreshListOfFilesFragment();
1643 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1647 if (result
.isSslRecoverableException()) {
1648 mLastSslUntrustedServerResult
= result
;
1649 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1654 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1655 dismissLoadingDialog();
1656 OCFile syncedFile
= operation
.getLocalFile();
1657 if (!result
.isSuccess()) {
1658 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1659 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1660 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1661 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1667 if (operation
.transferWasRequested()) {
1668 onTransferStateChanged(syncedFile
, true
, true
);
1671 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1679 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1681 * @param operation Creation operation performed.
1682 * @param result Result of the creation.
1684 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1685 if (result
.isSuccess()) {
1686 dismissLoadingDialog();
1687 refreshListOfFilesFragment();
1689 dismissLoadingDialog();
1691 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1692 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1696 } catch (NotFoundException e
) {
1697 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1707 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1708 refreshListOfFilesFragment();
1709 FileFragment details
= getSecondFragment();
1710 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1711 if (downloading
|| uploading
) {
1712 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1714 if (!file
.fileExists()) {
1715 cleanSecondFragment();
1717 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1725 private void requestForDownload() {
1726 Account account
= getAccount();
1727 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1728 Intent i
= new Intent(this, FileDownloader
.class);
1729 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1730 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1736 private OCFile
getCurrentDir() {
1737 OCFile file
= getFile();
1739 if (file
.isFolder()) {
1741 } else if (getStorageManager() != null
) {
1742 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1743 return getStorageManager().getFileByPath(parentPath
);
1749 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1750 long currentSyncTime
= System
.currentTimeMillis();
1752 mSyncInProgress
= true
;
1754 // perform folder synchronization
1755 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1758 getFileOperationsHelper().isSharedSupported(),
1760 getStorageManager(),
1762 getApplicationContext()
1764 synchFolderOp
.execute(getAccount(), this, null
, null
);
1766 setSupportProgressBarIndeterminateVisibility(true
);
1768 setBackgroundText();
1772 * Show untrusted cert dialog
1774 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1775 // Show a dialog with the certificate info
1776 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1777 FragmentManager fm
= getSupportFragmentManager();
1778 FragmentTransaction ft
= fm
.beginTransaction();
1779 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1782 private void requestForDownload(OCFile file
) {
1783 Account account
= getAccount();
1784 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1785 Intent i
= new Intent(this, FileDownloader
.class);
1786 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1787 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1792 private void sendDownloadedFile(){
1793 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1794 mWaitingToSend
= null
;
1799 * Requests the download of the received {@link OCFile} , updates the UI
1800 * to monitor the download progress and prepares the activity to send the file
1801 * when the download finishes.
1803 * @param file {@link OCFile} to download and preview.
1805 public void startDownloadForSending(OCFile file
) {
1806 mWaitingToSend
= file
;
1807 requestForDownload(mWaitingToSend
);
1808 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1809 updateFragmentsVisibility(hasSecondFragment
);
1813 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1815 * @param file Image {@link OCFile} to show.
1817 public void startImagePreview(OCFile file
) {
1818 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1819 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1820 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1821 startActivity(showDetailsIntent
);
1826 * Stars the preview of an already down media {@link OCFile}.
1828 * @param file Media {@link OCFile} to preview.
1829 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1830 * @param autoplay When 'true', the playback will start without user interactions.
1832 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1833 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1834 setSecondFragment(mediaFragment
);
1835 updateFragmentsVisibility(true
);
1836 updateNavigationElementsInActionBar(file
);
1841 * Requests the download of the received {@link OCFile} , updates the UI
1842 * to monitor the download progress and prepares the activity to preview
1843 * or open the file when the download finishes.
1845 * @param file {@link OCFile} to download and preview.
1847 public void startDownloadForPreview(OCFile file
) {
1848 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1849 setSecondFragment(detailFragment
);
1850 mWaitingToPreview
= file
;
1851 requestForDownload();
1852 updateFragmentsVisibility(true
);
1853 updateNavigationElementsInActionBar(file
);
1858 public void cancelTransference(OCFile file
) {
1859 getFileOperationsHelper().cancelTransference(file
);
1860 if (mWaitingToPreview
!= null
&&
1861 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1862 mWaitingToPreview
= null
;
1864 if (mWaitingToSend
!= null
&&
1865 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1866 mWaitingToSend
= null
;
1868 onTransferStateChanged(file
, false
, false
);
1872 public void onRefresh(boolean ignoreETag
) {
1873 refreshList(ignoreETag
);
1877 public void onRefresh() {
1881 private void refreshList(boolean ignoreETag
) {
1882 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1883 if (listOfFiles
!= null
) {
1884 OCFile folder
= listOfFiles
.getCurrentFile();
1885 if (folder
!= null
) {
1886 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1887 listDirectory(mFile);*/
1888 startSyncFolderOperation(folder
, ignoreETag
);
1893 private void sortByDate(boolean ascending
){
1894 getListOfFilesFragment().sortByDate(ascending
);
1897 private void sortBySize(boolean ascending
){
1898 getListOfFilesFragment().sortBySize(ascending
);
1901 private void sortByName(boolean ascending
){
1902 getListOfFilesFragment().sortByName(ascending
);