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
.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
;
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 checkIfRequestPin(savedInstanceState
);
173 /// grant that FileObserverService is watching favourite files
174 if (savedInstanceState
== null
) {
175 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
176 startService(initObserversIntent
);
179 /// Load of saved instance state
180 if(savedInstanceState
!= null
) {
181 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
182 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
183 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
186 mWaitingToPreview
= null
;
187 mSyncInProgress
= false
;
188 mWaitingToSend
= null
;
193 // Inflate and set the layout view
194 setContentView(R
.layout
.files
);
195 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
196 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
197 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
198 if (savedInstanceState
== null
) {
199 createMinFragments();
203 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
204 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
205 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
209 Log_OC
.d(TAG
, "onCreate() end");
212 private void checkIfRequestPin(Bundle savedInstanceState
){
213 // PIN CODE request ; best location is to decide, let's try this first
214 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
216 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
222 protected void onStart() {
224 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
228 protected void onDestroy() {
233 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
236 protected void onAccountSet(boolean stateWasRecovered
) {
237 super.onAccountSet(stateWasRecovered
);
238 if (getAccount() != null
) {
239 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
240 OCFile file
= getFile();
241 // get parent from path
242 String parentPath
= "";
244 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
245 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
246 // get parent from path
247 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
248 if (getStorageManager().getFileByPath(parentPath
) == null
)
249 file
= null
; // not able to know the directory where the file is uploading
251 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
255 // fall back to root folder
256 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
259 setNavigationListWithFolder(file
);
261 if (!stateWasRecovered
) {
262 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
263 initFragmentsWithFile();
264 if (file
.isFolder()) {
265 startSyncFolderOperation(file
, false
);
269 updateFragmentsVisibility(!file
.isFolder());
270 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
276 private void setNavigationListWithFolder(OCFile file
) {
277 mDirectories
.clear();
278 OCFile fileIt
= file
;
280 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
281 if (fileIt
.isFolder()) {
282 mDirectories
.add(fileIt
.getFileName());
284 // get parent from path
285 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
286 fileIt
= getStorageManager().getFileByPath(parentPath
);
288 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
292 private void createMinFragments() {
293 OCFileListFragment listOfFiles
= new OCFileListFragment();
294 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
295 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
296 transaction
.commit();
299 private void initFragmentsWithFile() {
300 if (getAccount() != null
&& getFile() != null
) {
302 OCFileListFragment listOfFiles
= getListOfFilesFragment();
303 if (listOfFiles
!= null
) {
304 listOfFiles
.listDirectory(getCurrentDir());
306 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
310 OCFile file
= getFile();
311 Fragment secondFragment
= chooseInitialSecondFragment(file
);
312 if (secondFragment
!= null
) {
313 setSecondFragment(secondFragment
);
314 updateFragmentsVisibility(true
);
315 updateNavigationElementsInActionBar(file
);
318 cleanSecondFragment();
322 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
323 if (getAccount() == null
) {
324 Log_OC
.wtf(TAG
, "\t account is NULL");
326 if (getFile() == null
) {
327 Log_OC
.wtf(TAG
, "\t file is NULL");
332 private Fragment
chooseInitialSecondFragment(OCFile file
) {
333 Fragment secondFragment
= null
;
334 if (file
!= null
&& !file
.isFolder()) {
335 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
336 && file
.getLastSyncDateForProperties() > 0 // temporal fix
338 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
339 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
340 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
343 secondFragment
= new FileDetailFragment(file
, getAccount());
346 return secondFragment
;
351 * Replaces the second fragment managed by the activity with the received as
354 * Assumes never will be more than two fragments managed at the same time.
356 * @param fragment New second Fragment to set.
358 private void setSecondFragment(Fragment fragment
) {
359 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
360 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
361 transaction
.commit();
365 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
367 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
370 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
374 } else if (existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
376 mLeftFragmentContainer
.setVisibility(View
.GONE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
384 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
387 mRightFragmentContainer
.setVisibility(View
.GONE
);
393 private OCFileListFragment
getListOfFilesFragment() {
394 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
395 if (listOfFiles
!= null
) {
396 return (OCFileListFragment
)listOfFiles
;
398 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
402 public FileFragment
getSecondFragment() {
403 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
404 if (second
!= null
) {
405 return (FileFragment
)second
;
410 protected void cleanSecondFragment() {
411 Fragment second
= getSecondFragment();
412 if (second
!= null
) {
413 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
417 updateFragmentsVisibility(false
);
418 updateNavigationElementsInActionBar(null
);
421 protected void refreshListOfFilesFragment() {
422 OCFileListFragment fileListFragment
= getListOfFilesFragment();
423 if (fileListFragment
!= null
) {
424 fileListFragment
.listDirectory();
428 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
429 FileFragment secondFragment
= getSecondFragment();
430 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
431 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
432 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
433 OCFile fileInFragment
= detailsFragment
.getFile();
434 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
435 // the user browsed to other file ; forget the automatic preview
436 mWaitingToPreview
= null
;
438 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
439 // grant that the right panel updates the progress bar
440 detailsFragment
.listenForTransferProgress();
441 detailsFragment
.updateFileDetails(true
, false
);
443 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
444 // update the right panel
445 boolean detailsFragmentChanged
= false
;
448 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
449 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
450 startMediaPreview(mWaitingToPreview
, 0, true
);
451 detailsFragmentChanged
= true
;
453 getFileOperationsHelper().openFile(mWaitingToPreview
);
456 mWaitingToPreview
= null
;
458 if (!detailsFragmentChanged
) {
459 detailsFragment
.updateFileDetails(false
, (success
));
466 public boolean onPrepareOptionsMenu(Menu menu
) {
467 if (BuildConfig
.DEBUG
) {
468 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
470 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
472 return super.onPrepareOptionsMenu(menu
);
476 public boolean onCreateOptionsMenu(Menu menu
) {
477 MenuInflater inflater
= getSherlock().getMenuInflater();
478 inflater
.inflate(R
.menu
.main_menu
, menu
);
483 public boolean onOptionsItemSelected(MenuItem item
) {
484 boolean retval
= true
;
485 switch (item
.getItemId()) {
486 case R
.id
.action_create_dir
: {
487 CreateFolderDialogFragment dialog
=
488 CreateFolderDialogFragment
.newInstance(getCurrentDir());
489 dialog
.show(getSupportFragmentManager(), "createdirdialog");
492 case R
.id
.action_sync_account
: {
493 startSynchronization();
496 case R
.id
.action_upload
: {
497 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
500 case R
.id
.action_settings
: {
501 Intent settingsIntent
= new Intent(this, Preferences
.class);
502 startActivity(settingsIntent
);
505 case R
.id
.action_logger
: {
506 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
507 startActivity(loggerIntent
);
510 case android
.R
.id
.home
: {
511 FileFragment second
= getSecondFragment();
512 OCFile currentDir
= getCurrentDir();
513 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
514 (second
!= null
&& second
.getFile() != null
)) {
520 case R
.id
.action_sort
: {
521 SharedPreferences appPreferences
= PreferenceManager
522 .getDefaultSharedPreferences(this);
524 // Read sorting order, default to sort by name ascending
525 Integer sortOrder
= appPreferences
526 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
528 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
529 builder
.setTitle(R
.string
.actionbar_sort_title
)
530 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
531 public void onClick(DialogInterface dialog
, int which
) {
541 // TODO re-enable when server-side folder size calculation is available
543 // sortBySize(false);
551 builder
.create().show();
555 retval
= super.onOptionsItemSelected(item
);
560 private void startSynchronization() {
561 Log_OC
.e(TAG
, "Got to start sync");
562 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
563 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
564 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
565 Bundle bundle
= new Bundle();
566 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
567 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
568 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
569 ContentResolver
.requestSync(
571 MainApp
.getAuthority(), bundle
);
573 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
574 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
575 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
576 builder
.setExpedited(true
);
577 builder
.setManual(true
);
580 // Fix bug in Android Lollipop when you click on refresh the whole account
581 Bundle extras
= new Bundle();
582 builder
.setExtras(extras
);
584 SyncRequest request
= builder
.build();
585 ContentResolver
.requestSync(request
);
591 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
592 if (itemPosition
!= 0) {
593 String targetPath
= "";
594 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
595 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
597 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
598 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
599 if (targetFolder
!= null
) {
600 browseTo(targetFolder
);
603 // the next operation triggers a new call to this method, but it's necessary to
604 // ensure that the name exposed in the action bar is the current directory when the
605 // user selected it in the navigation list
606 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
607 getSupportActionBar().setSelectedNavigationItem(0);
613 * Called, when the user selected something for uploading
616 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
617 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
618 super.onActivityResult(requestCode
, resultCode
, data
);
620 Log_OC
.d(TAG
, "requestCode: " + requestCode
);
621 if (requestCode
== PinCodeActivity
.EXTRA_PIN_CORRECT
){
622 Log_OC
.d(TAG
, "Extra pin: " + resultCode
);
623 if (resultCode
== RESULT_OK
) {
628 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
629 //getClipData is only supported on api level 16+, Jelly Bean
630 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
631 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
632 Intent intent
= new Intent();
633 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
634 requestSimpleUpload(intent
, resultCode
);
637 requestSimpleUpload(data
, resultCode
);
639 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
640 requestMultipleUpload(data
, resultCode
);
642 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
644 final Intent fData
= data
;
645 final int fResultCode
= resultCode
;
646 getHandler().postDelayed(
650 requestMoveOperation(fData
, fResultCode
);
653 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
658 private void requestMultipleUpload(Intent data
, int resultCode
) {
659 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
660 if (filePaths
!= null
) {
661 String
[] remotePaths
= new String
[filePaths
.length
];
662 String remotePathBase
= "";
663 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
664 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
666 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
667 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
668 for (int j
= 0; j
< remotePaths
.length
; j
++) {
669 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
672 Intent i
= new Intent(this, FileUploader
.class);
673 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
674 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
675 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
676 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
677 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
678 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
682 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
683 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
690 private void requestSimpleUpload(Intent data
, int resultCode
) {
691 String filepath
= null
;
692 String mimeType
= null
;
694 Uri selectedImageUri
= data
.getData();
697 mimeType
= getContentResolver().getType(selectedImageUri
);
699 String filemanagerstring
= selectedImageUri
.getPath();
700 String selectedImagePath
= getPath(selectedImageUri
);
702 if (selectedImagePath
!= null
)
703 filepath
= selectedImagePath
;
705 filepath
= filemanagerstring
;
707 } catch (Exception e
) {
708 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
712 if (filepath
== null
) {
713 Log_OC
.e(TAG
, "Couldnt resolve path to file");
714 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
720 Intent i
= new Intent(this, FileUploader
.class);
721 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
723 String remotepath
= new String();
724 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
725 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
727 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
728 remotepath
+= OCFile
.PATH_SEPARATOR
;
730 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
732 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
733 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
736 if (cursor
!= null
&& cursor
.moveToFirst()) {
737 String displayName
= cursor
.getString(
738 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
739 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
741 displayName
.replace(File
.separatorChar
, '_');
742 displayName
.replace(File
.pathSeparatorChar
, '_');
743 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
751 remotepath
+= new File(filepath
).getName();
754 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
755 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
756 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
757 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
758 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
759 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
764 * Request the operation for moving the file/folder from one path to another
766 * @param data Intent received
767 * @param resultCode Result code received
769 private void requestMoveOperation(Intent data
, int resultCode
) {
770 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
771 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
772 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
776 public void onBackPressed() {
777 OCFileListFragment listOfFiles
= getListOfFilesFragment();
778 if (mDualPane
|| getSecondFragment() == null
) {
779 if (listOfFiles
!= null
) { // should never be null, indeed
780 if (mDirectories
.getCount() <= 1) {
784 int levelsUp
= listOfFiles
.onBrowseUp();
785 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
790 if (listOfFiles
!= null
) { // should never be null, indeed
791 setFile(listOfFiles
.getCurrentFile());
793 cleanSecondFragment();
798 protected void onSaveInstanceState(Bundle outState
) {
799 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
800 Log_OC
.e(TAG
, "onSaveInstanceState() start");
801 super.onSaveInstanceState(outState
);
802 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
803 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
804 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
805 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
807 Log_OC
.d(TAG
, "onSaveInstanceState() end");
813 protected void onResume() {
815 Log_OC
.e(TAG
, "onResume() start");
817 checkIfRequestPin(null
);
820 private void resume(){
821 // refresh list of files
822 refreshListOfFilesFragment();
824 // Listen for sync messages
825 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
826 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
827 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
828 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
829 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
830 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
831 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
832 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
834 // Listen for upload messages
835 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
836 mUploadFinishReceiver
= new UploadFinishReceiver();
837 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
839 // Listen for download messages
840 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
841 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
842 mDownloadFinishReceiver
= new DownloadFinishReceiver();
843 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
845 Log_OC
.d(TAG
, "onResume() end");
850 protected void onPause() {
851 Log_OC
.e(TAG
, "onPause() start");
852 if (mSyncBroadcastReceiver
!= null
) {
853 unregisterReceiver(mSyncBroadcastReceiver
);
854 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
855 mSyncBroadcastReceiver
= null
;
857 if (mUploadFinishReceiver
!= null
) {
858 unregisterReceiver(mUploadFinishReceiver
);
859 mUploadFinishReceiver
= null
;
861 if (mDownloadFinishReceiver
!= null
) {
862 unregisterReceiver(mDownloadFinishReceiver
);
863 mDownloadFinishReceiver
= null
;
867 Log_OC
.d(TAG
, "onPause() end");
873 protected Dialog
onCreateDialog(int id
) {
874 Dialog dialog
= null
;
875 AlertDialog
.Builder builder
;
877 case DIALOG_SHORT_WAIT
: {
878 ProgressDialog working_dialog
= new ProgressDialog(this);
879 working_dialog
.setMessage(getResources().getString(
880 R
.string
.wait_a_moment
));
881 working_dialog
.setIndeterminate(true
);
882 working_dialog
.setCancelable(false
);
883 dialog
= working_dialog
;
886 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
889 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
890 getString(R
.string
.actionbar_upload_from_apps
) };
892 builder
= new AlertDialog
.Builder(this);
893 builder
.setTitle(R
.string
.actionbar_upload
);
894 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
895 public void onClick(DialogInterface dialog
, int item
) {
898 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
899 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
900 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
902 // TODO create and handle new fragment
903 // LocalFileListFragment
905 } else if (item
== 1) {
906 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
907 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
908 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
909 if(Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
910 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
912 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
913 ACTION_SELECT_CONTENT_FROM_APPS
);
917 dialog
= builder
.create();
920 case DIALOG_CERT_NOT_SAVED
: {
921 builder
= new AlertDialog
.Builder(this);
922 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
923 builder
.setCancelable(false
);
924 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
926 public void onClick(DialogInterface dialog
, int which
) {
930 dialog
= builder
.create();
941 * Translates a content URI of an content to a physical path on the disk
943 * @param uri The URI to resolve
944 * @return The path to the content or null if it could not be found
946 public String
getPath(Uri uri
) {
947 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
950 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
951 // ExternalStorageProvider
952 if (UriUtils
.isExternalStorageDocument(uri
)) {
953 final String docId
= DocumentsContract
.getDocumentId(uri
);
954 final String
[] split
= docId
.split(":");
955 final String type
= split
[0];
957 if ("primary".equalsIgnoreCase(type
)) {
958 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
962 else if (UriUtils
.isDownloadsDocument(uri
)) {
964 final String id
= DocumentsContract
.getDocumentId(uri
);
965 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
968 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
971 else if (UriUtils
.isMediaDocument(uri
)) {
972 final String docId
= DocumentsContract
.getDocumentId(uri
);
973 final String
[] split
= docId
.split(":");
974 final String type
= split
[0];
976 Uri contentUri
= null
;
977 if ("image".equals(type
)) {
978 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
979 } else if ("video".equals(type
)) {
980 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
981 } else if ("audio".equals(type
)) {
982 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
985 final String selection
= "_id=?";
986 final String
[] selectionArgs
= new String
[] { split
[1] };
988 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
990 // Documents providers returned as content://...
991 else if (UriUtils
.isContentDocument(uri
)) {
992 return uri
.toString();
995 // MediaStore (and general)
996 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
998 // Return the remote address
999 if (UriUtils
.isGooglePhotosUri(uri
))
1000 return uri
.getLastPathSegment();
1002 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
1005 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
1006 return uri
.getPath();
1012 * Pushes a directory to the drop down list
1013 * @param directory to push
1014 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1016 public void pushDirname(OCFile directory
) {
1017 if(!directory
.isFolder()){
1018 throw new IllegalArgumentException("Only directories may be pushed!");
1020 mDirectories
.insert(directory
.getFileName(), 0);
1025 * Pops a directory name from the drop down list
1026 * @return True, unless the stack is empty
1028 public boolean popDirname() {
1029 mDirectories
.remove(mDirectories
.getItem(0));
1030 return !mDirectories
.isEmpty();
1033 // Custom array adapter to override text colors
1034 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1036 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1040 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1041 View v
= super.getView(position
, convertView
, parent
);
1043 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1044 android
.R
.color
.white
));
1046 fixRoot((TextView
) v
);
1050 public View
getDropDownView(int position
, View convertView
,
1052 View v
= super.getDropDownView(position
, convertView
, parent
);
1054 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1055 android
.R
.color
.white
));
1057 fixRoot((TextView
) v
);
1061 private void fixRoot(TextView v
) {
1062 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1063 v
.setText(R
.string
.default_display_name_for_root_folder
);
1069 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1072 * {@link BroadcastReceiver} to enable syncing feedback in UI
1075 public void onReceive(Context context
, Intent intent
) {
1077 String event
= intent
.getAction();
1078 Log_OC
.d(TAG
, "Received broadcast " + event
);
1079 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1080 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1081 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1082 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1086 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1087 mSyncInProgress
= true
;
1090 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1091 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1093 if (currentDir
== null
) {
1094 // current folder was removed from the server
1095 Toast
.makeText( FileDisplayActivity
.this,
1096 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1102 if (currentFile
== null
&& !getFile().isFolder()) {
1103 // currently selected file was removed in the server, and now we know it
1104 cleanSecondFragment();
1105 currentFile
= currentDir
;
1108 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1109 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1110 if (fileListFragment
!= null
) {
1111 fileListFragment
.listDirectory(currentDir
);
1114 setFile(currentFile
);
1117 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1119 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1121 /// TODO refactor and make common
1122 synchResult
!= null
&& !synchResult
.isSuccess() &&
1123 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1124 synchResult
.isIdPRedirection() ||
1125 (synchResult
.isException() && synchResult
.getException()
1126 instanceof AuthenticatorException
))) {
1128 OwnCloudClient client
= null
;
1130 OwnCloudAccount ocAccount
=
1131 new OwnCloudAccount(getAccount(), context
);
1132 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1133 removeClientFor(ocAccount
));
1134 // TODO get rid of these exceptions
1135 } catch (AccountNotFoundException e
) {
1136 e
.printStackTrace();
1137 } catch (AuthenticatorException e
) {
1138 e
.printStackTrace();
1139 } catch (OperationCanceledException e
) {
1140 e
.printStackTrace();
1141 } catch (IOException e
) {
1142 e
.printStackTrace();
1145 if (client
!= null
) {
1146 OwnCloudCredentials cred
= client
.getCredentials();
1148 AccountManager am
= AccountManager
.get(context
);
1149 if (cred
.authTokenExpires()) {
1150 am
.invalidateAuthToken(
1155 am
.clearPassword(getAccount());
1160 requestCredentialsUpdate();
1164 removeStickyBroadcast(intent
);
1165 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1166 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1168 setBackgroundText();
1172 if (synchResult
!= null
) {
1173 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1174 mLastSslUntrustedServerResult
= synchResult
;
1177 } catch (RuntimeException e
) {
1178 // avoid app crashes after changing the serial id of RemoteOperationResult
1179 // in owncloud library with broadcast notifications pending to process
1180 removeStickyBroadcast(intent
);
1186 * Show a text message on screen view for notifying user if content is
1187 * loading or folder is empty
1189 private void setBackgroundText() {
1190 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1191 if (ocFileListFragment
!= null
) {
1192 int message
= R
.string
.file_list_loading
;
1193 if (!mSyncInProgress
) {
1194 // In case file list is empty
1195 message
= R
.string
.file_list_empty
;
1197 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1199 Log_OC
.e(TAG
, "OCFileListFragment is null");
1204 * Once the file upload has finished -> update view
1206 private class UploadFinishReceiver
extends BroadcastReceiver
{
1208 * Once the file upload has finished -> update view
1209 * @author David A. Velasco
1210 * {@link BroadcastReceiver} to enable upload feedback in UI
1213 public void onReceive(Context context
, Intent intent
) {
1215 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1216 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1217 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1218 OCFile currentDir
= getCurrentDir();
1219 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1220 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1222 if (sameAccount
&& isDescendant
) {
1223 refreshListOfFilesFragment();
1226 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1227 boolean renamedInUpload
= getFile().getRemotePath().
1228 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1229 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1231 FileFragment details
= getSecondFragment();
1232 boolean detailFragmentIsShown
= (details
!= null
&&
1233 details
instanceof FileDetailFragment
);
1235 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1236 if (uploadWasFine
) {
1237 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1239 if (renamedInUpload
) {
1240 String newName
= (new File(uploadedRemotePath
)).getName();
1241 Toast msg
= Toast
.makeText(
1244 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1249 if (uploadWasFine
|| getFile().fileExists()) {
1250 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1252 cleanSecondFragment();
1255 // Force the preview if the file is an image
1256 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1257 startImagePreview(getFile());
1258 } // TODO what about other kind of previews?
1262 if (intent
!= null
) {
1263 removeStickyBroadcast(intent
);
1273 * Class waiting for broadcast events from the {@link FielDownloader} service.
1275 * Updates the UI when a download is started or finished, provided that it is relevant for the
1278 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1280 public void onReceive(Context context
, Intent intent
) {
1282 boolean sameAccount
= isSameAccount(context
, intent
);
1283 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1284 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1286 if (sameAccount
&& isDescendant
) {
1287 refreshListOfFilesFragment();
1288 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1291 if (mWaitingToSend
!= null
) {
1292 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1293 if (mWaitingToSend
.isDown()) {
1294 sendDownloadedFile();
1299 if (intent
!= null
) {
1300 removeStickyBroadcast(intent
);
1305 private boolean isDescendant(String downloadedRemotePath
) {
1306 OCFile currentDir
= getCurrentDir();
1307 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1310 private boolean isSameAccount(Context context
, Intent intent
) {
1311 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1312 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1317 public void browseToRoot() {
1318 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1319 if (listOfFiles
!= null
) { // should never be null, indeed
1320 while (mDirectories
.getCount() > 1) {
1323 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1324 listOfFiles
.listDirectory(root
);
1325 setFile(listOfFiles
.getCurrentFile());
1326 startSyncFolderOperation(root
, false
);
1328 cleanSecondFragment();
1332 public void browseTo(OCFile folder
) {
1333 if (folder
== null
|| !folder
.isFolder()) {
1334 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1336 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1337 if (listOfFiles
!= null
) {
1338 setNavigationListWithFolder(folder
);
1339 listOfFiles
.listDirectory(folder
);
1340 setFile(listOfFiles
.getCurrentFile());
1341 startSyncFolderOperation(folder
, false
);
1343 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1345 cleanSecondFragment();
1352 * Updates action bar and second fragment, if in dual pane mode.
1355 public void onBrowsedDownTo(OCFile directory
) {
1356 pushDirname(directory
);
1357 cleanSecondFragment();
1360 startSyncFolderOperation(directory
, false
);
1365 * Shows the information of the {@link OCFile} received as a
1366 * parameter in the second fragment.
1368 * @param file {@link OCFile} whose details will be shown
1371 public void showDetails(OCFile file
) {
1372 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1373 setSecondFragment(detailFragment
);
1374 updateFragmentsVisibility(true
);
1375 updateNavigationElementsInActionBar(file
);
1383 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1384 ActionBar actionBar
= getSupportActionBar();
1385 if (chosenFile
== null
|| mDualPane
) {
1386 // only list of files - set for browsing through folders
1387 OCFile currentDir
= getCurrentDir();
1388 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1389 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1390 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1392 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1394 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1395 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1398 actionBar
.setDisplayHomeAsUpEnabled(true
);
1399 actionBar
.setDisplayShowTitleEnabled(true
);
1400 actionBar
.setTitle(chosenFile
.getFileName());
1401 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1407 protected ServiceConnection
newTransferenceServiceConnection() {
1408 return new ListServiceConnection();
1411 /** Defines callbacks for service binding, passed to bindService() */
1412 private class ListServiceConnection
implements ServiceConnection
{
1415 public void onServiceConnected(ComponentName component
, IBinder service
) {
1416 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1417 Log_OC
.d(TAG
, "Download service connected");
1418 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1419 if (mWaitingToPreview
!= null
)
1420 if (getStorageManager() != null
) {
1421 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1422 if (!mWaitingToPreview
.isDown()) {
1423 requestForDownload();
1427 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1428 Log_OC
.d(TAG
, "Upload service connected");
1429 mUploaderBinder
= (FileUploaderBinder
) service
;
1433 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1434 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1435 if (listOfFiles
!= null
) {
1436 listOfFiles
.listDirectory();
1438 FileFragment secondFragment
= getSecondFragment();
1439 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1440 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1441 detailFragment
.listenForTransferProgress();
1442 detailFragment
.updateFileDetails(false
, false
);
1447 public void onServiceDisconnected(ComponentName component
) {
1448 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1449 Log_OC
.d(TAG
, "Download service disconnected");
1450 mDownloaderBinder
= null
;
1451 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1452 Log_OC
.d(TAG
, "Upload service disconnected");
1453 mUploaderBinder
= null
;
1461 * Launch an intent to request the PIN code to the user before letting him use the app
1463 private void requestPinCode() {
1464 boolean pinStart
= false
;
1465 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1466 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1468 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1469 // i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1470 startActivityForResult(i
, PinCodeActivity
.EXTRA_PIN_CORRECT
);
1476 public void onSavedCertificate() {
1477 startSyncFolderOperation(getCurrentDir(), false
);
1482 public void onFailedSavingCertificate() {
1483 showDialog(DIALOG_CERT_NOT_SAVED
);
1487 public void onCancelCertificate() {
1492 * Updates the view associated to the activity after the finish of some operation over files
1493 * in the current account.
1495 * @param operation Removal operation performed.
1496 * @param result Result of the removal.
1499 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1500 super.onRemoteOperationFinish(operation
, result
);
1502 if (operation
instanceof RemoveFileOperation
) {
1503 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1505 } else if (operation
instanceof RenameFileOperation
) {
1506 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1508 } else if (operation
instanceof SynchronizeFileOperation
) {
1509 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1511 } else if (operation
instanceof CreateFolderOperation
) {
1512 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1514 } else if (operation
instanceof CreateShareOperation
) {
1515 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1517 } else if (operation
instanceof UnshareLinkOperation
) {
1518 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1520 } else if (operation
instanceof MoveFileOperation
) {
1521 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1527 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1528 if (result
.isSuccess()) {
1529 refreshShowDetails();
1530 refreshListOfFilesFragment();
1535 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1536 if (result
.isSuccess()) {
1537 refreshShowDetails();
1538 refreshListOfFilesFragment();
1540 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1541 cleanSecondFragment();
1542 refreshListOfFilesFragment();
1546 private void refreshShowDetails() {
1547 FileFragment details
= getSecondFragment();
1548 if (details
!= null
) {
1549 OCFile file
= details
.getFile();
1551 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1552 if (details
instanceof PreviewMediaFragment
) {
1553 // Refresh OCFile of the fragment
1554 ((PreviewMediaFragment
) details
).updateFile(file
);
1559 invalidateOptionsMenu();
1564 * Updates the view associated to the activity after the finish of an operation trying to remove a
1567 * @param operation Removal operation performed.
1568 * @param result Result of the removal.
1570 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1571 dismissLoadingDialog();
1573 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1577 if (result
.isSuccess()) {
1578 OCFile removedFile
= operation
.getFile();
1579 FileFragment second
= getSecondFragment();
1580 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1581 if (second
instanceof PreviewMediaFragment
) {
1582 ((PreviewMediaFragment
)second
).stopPreview(true
);
1584 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1585 cleanSecondFragment();
1587 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1588 refreshListOfFilesFragment();
1590 invalidateOptionsMenu();
1592 if (result
.isSslRecoverableException()) {
1593 mLastSslUntrustedServerResult
= result
;
1594 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1601 * Updates the view associated to the activity after the finish of an operation trying to move a
1604 * @param operation Move operation performed.
1605 * @param result Result of the move operation.
1607 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1608 if (result
.isSuccess()) {
1609 dismissLoadingDialog();
1610 refreshListOfFilesFragment();
1612 dismissLoadingDialog();
1614 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1615 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1619 } catch (NotFoundException e
) {
1620 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1627 * Updates the view associated to the activity after the finish of an operation trying to rename a
1630 * @param operation Renaming operation performed.
1631 * @param result Result of the renaming.
1633 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1634 dismissLoadingDialog();
1635 OCFile renamedFile
= operation
.getFile();
1636 if (result
.isSuccess()) {
1637 FileFragment details
= getSecondFragment();
1638 if (details
!= null
) {
1639 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1640 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1641 showDetails(renamedFile
);
1643 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1644 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1645 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1646 int position
= ((PreviewMediaFragment
)details
).getPosition();
1647 startMediaPreview(renamedFile
, position
, true
);
1649 getFileOperationsHelper().openFile(renamedFile
);
1654 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1655 refreshListOfFilesFragment();
1659 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1663 if (result
.isSslRecoverableException()) {
1664 mLastSslUntrustedServerResult
= result
;
1665 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1670 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1671 dismissLoadingDialog();
1672 OCFile syncedFile
= operation
.getLocalFile();
1673 if (!result
.isSuccess()) {
1674 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1675 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1676 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1677 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1683 if (operation
.transferWasRequested()) {
1684 onTransferStateChanged(syncedFile
, true
, true
);
1687 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1695 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1697 * @param operation Creation operation performed.
1698 * @param result Result of the creation.
1700 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1701 if (result
.isSuccess()) {
1702 dismissLoadingDialog();
1703 refreshListOfFilesFragment();
1705 dismissLoadingDialog();
1707 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1708 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1712 } catch (NotFoundException e
) {
1713 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1723 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1724 refreshListOfFilesFragment();
1725 FileFragment details
= getSecondFragment();
1726 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1727 if (downloading
|| uploading
) {
1728 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1730 if (!file
.fileExists()) {
1731 cleanSecondFragment();
1733 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1741 private void requestForDownload() {
1742 Account account
= getAccount();
1743 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1744 Intent i
= new Intent(this, FileDownloader
.class);
1745 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1746 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1752 private OCFile
getCurrentDir() {
1753 OCFile file
= getFile();
1755 if (file
.isFolder()) {
1757 } else if (getStorageManager() != null
) {
1758 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1759 return getStorageManager().getFileByPath(parentPath
);
1765 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1766 long currentSyncTime
= System
.currentTimeMillis();
1768 mSyncInProgress
= true
;
1770 // perform folder synchronization
1771 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1774 getFileOperationsHelper().isSharedSupported(),
1776 getStorageManager(),
1778 getApplicationContext()
1780 synchFolderOp
.execute(getAccount(), this, null
, null
);
1782 setSupportProgressBarIndeterminateVisibility(true
);
1784 setBackgroundText();
1788 * Show untrusted cert dialog
1790 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1791 // Show a dialog with the certificate info
1792 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1793 FragmentManager fm
= getSupportFragmentManager();
1794 FragmentTransaction ft
= fm
.beginTransaction();
1795 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1798 private void requestForDownload(OCFile file
) {
1799 Account account
= getAccount();
1800 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1801 Intent i
= new Intent(this, FileDownloader
.class);
1802 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1803 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1808 private void sendDownloadedFile(){
1809 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1810 mWaitingToSend
= null
;
1815 * Requests the download of the received {@link OCFile} , updates the UI
1816 * to monitor the download progress and prepares the activity to send the file
1817 * when the download finishes.
1819 * @param file {@link OCFile} to download and preview.
1821 public void startDownloadForSending(OCFile file
) {
1822 mWaitingToSend
= file
;
1823 requestForDownload(mWaitingToSend
);
1824 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1825 updateFragmentsVisibility(hasSecondFragment
);
1829 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1831 * @param file Image {@link OCFile} to show.
1833 public void startImagePreview(OCFile file
) {
1834 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1835 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1836 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1837 startActivity(showDetailsIntent
);
1842 * Stars the preview of an already down media {@link OCFile}.
1844 * @param file Media {@link OCFile} to preview.
1845 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1846 * @param autoplay When 'true', the playback will start without user interactions.
1848 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1849 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1850 setSecondFragment(mediaFragment
);
1851 updateFragmentsVisibility(true
);
1852 updateNavigationElementsInActionBar(file
);
1857 * Requests the download of the received {@link OCFile} , updates the UI
1858 * to monitor the download progress and prepares the activity to preview
1859 * or open the file when the download finishes.
1861 * @param file {@link OCFile} to download and preview.
1863 public void startDownloadForPreview(OCFile file
) {
1864 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1865 setSecondFragment(detailFragment
);
1866 mWaitingToPreview
= file
;
1867 requestForDownload();
1868 updateFragmentsVisibility(true
);
1869 updateNavigationElementsInActionBar(file
);
1874 public void cancelTransference(OCFile file
) {
1875 getFileOperationsHelper().cancelTransference(file
);
1876 if (mWaitingToPreview
!= null
&&
1877 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1878 mWaitingToPreview
= null
;
1880 if (mWaitingToSend
!= null
&&
1881 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1882 mWaitingToSend
= null
;
1884 onTransferStateChanged(file
, false
, false
);
1888 public void onRefresh(boolean ignoreETag
) {
1889 refreshList(ignoreETag
);
1893 public void onRefresh() {
1897 private void refreshList(boolean ignoreETag
) {
1898 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1899 if (listOfFiles
!= null
) {
1900 OCFile folder
= listOfFiles
.getCurrentFile();
1901 if (folder
!= null
) {
1902 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1903 listDirectory(mFile);*/
1904 startSyncFolderOperation(folder
, ignoreETag
);
1909 private void sortByDate(boolean ascending
){
1910 getListOfFilesFragment().sortByDate(ascending
);
1913 private void sortBySize(boolean ascending
){
1914 getListOfFilesFragment().sortBySize(ascending
);
1917 private void sortByName(boolean ascending
){
1918 getListOfFilesFragment().sortByName(ascending
);