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
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ProgressDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.ContentUris
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.Intent
;
38 import android
.content
.IntentFilter
;
39 import android
.content
.ServiceConnection
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.SyncRequest
;
42 import android
.content
.res
.Resources
.NotFoundException
;
43 import android
.database
.Cursor
;
44 import android
.net
.Uri
;
45 import android
.os
.Build
;
46 import android
.os
.Bundle
;
47 import android
.os
.Environment
;
48 import android
.os
.IBinder
;
49 import android
.preference
.PreferenceManager
;
50 import android
.provider
.DocumentsContract
;
51 import android
.provider
.MediaStore
;
52 import android
.provider
.OpenableColumns
;
53 import android
.support
.v4
.app
.Fragment
;
54 import android
.support
.v4
.app
.FragmentManager
;
55 import android
.support
.v4
.app
.FragmentTransaction
;
56 import android
.util
.Log
;
57 import android
.view
.View
;
58 import android
.view
.ViewGroup
;
59 import android
.widget
.ArrayAdapter
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import com
.actionbarsherlock
.app
.ActionBar
;
64 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
65 import com
.actionbarsherlock
.view
.Menu
;
66 import com
.actionbarsherlock
.view
.MenuInflater
;
67 import com
.actionbarsherlock
.view
.MenuItem
;
68 import com
.actionbarsherlock
.view
.Window
;
69 import com
.owncloud
.android
.BuildConfig
;
70 import com
.owncloud
.android
.MainApp
;
71 import com
.owncloud
.android
.R
;
72 import com
.owncloud
.android
.datamodel
.OCFile
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
;
74 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
77 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
78 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
79 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
81 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
82 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
83 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
84 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
86 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
87 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
88 import com
.owncloud
.android
.operations
.CreateShareOperation
;
89 import com
.owncloud
.android
.operations
.MoveFileOperation
;
90 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
91 import com
.owncloud
.android
.operations
.RenameFileOperation
;
92 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
93 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
94 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
95 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
96 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
97 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
98 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
99 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
100 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
101 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
102 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
103 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
105 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
106 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
108 import com
.owncloud
.android
.utils
.DisplayUtils
;
109 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
113 * Displays, what files the user has available in his ownCloud.
115 * @author Bartek Przybylski
116 * @author David A. Velasco
119 public class FileDisplayActivity
extends HookActivity
implements
120 FileFragment
.ContainerActivity
, OnNavigationListener
,
121 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
123 private ArrayAdapter
<String
> mDirectories
;
125 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
126 private UploadFinishReceiver mUploadFinishReceiver
;
127 private DownloadFinishReceiver mDownloadFinishReceiver
;
128 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
130 private boolean mDualPane
;
131 private View mLeftFragmentContainer
;
132 private View mRightFragmentContainer
;
134 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
135 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
136 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
138 public static final int DIALOG_SHORT_WAIT
= 0;
139 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
140 private static final int DIALOG_CERT_NOT_SAVED
= 2;
142 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
144 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
145 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
146 public static final int ACTION_MOVE_FILES
= 3;
148 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
150 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
151 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
153 private OCFile mWaitingToPreview
;
155 private boolean mSyncInProgress
= false
;
157 private String DIALOG_UNTRUSTED_CERT
;
159 private OCFile mWaitingToSend
;
162 protected void onCreate(Bundle savedInstanceState
) {
163 Log_OC
.d(TAG
, "onCreate() start");
164 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
166 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
168 // PIN CODE request ; best location is to decide, let's try this first
169 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
171 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
175 /// grant that FileObserverService is watching favourite files
176 if (savedInstanceState
== null
) {
177 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
178 startService(initObserversIntent
);
181 /// Load of saved instance state
182 if(savedInstanceState
!= null
) {
183 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
184 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
185 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
188 mWaitingToPreview
= null
;
189 mSyncInProgress
= false
;
190 mWaitingToSend
= null
;
195 // Inflate and set the layout view
196 setContentView(R
.layout
.files
);
197 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
198 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
199 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
200 if (savedInstanceState
== null
) {
201 createMinFragments();
205 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
206 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
207 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
211 Log_OC
.d(TAG
, "onCreate() end");
215 protected void onStart() {
217 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
221 protected void onDestroy() {
226 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
229 protected void onAccountSet(boolean stateWasRecovered
) {
230 super.onAccountSet(stateWasRecovered
);
231 if (getAccount() != null
) {
232 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
233 OCFile file
= getFile();
234 // get parent from path
235 String parentPath
= "";
237 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
238 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
239 // get parent from path
240 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
241 if (getStorageManager().getFileByPath(parentPath
) == null
)
242 file
= null
; // not able to know the directory where the file is uploading
244 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
248 // fall back to root folder
249 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
252 setNavigationListWithFolder(file
);
254 if (!stateWasRecovered
) {
255 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
256 initFragmentsWithFile();
257 if (file
.isFolder()) {
258 startSyncFolderOperation(file
, false
);
262 updateFragmentsVisibility(!file
.isFolder());
263 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
269 private void setNavigationListWithFolder(OCFile file
) {
270 mDirectories
.clear();
271 OCFile fileIt
= file
;
273 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
274 if (fileIt
.isFolder()) {
275 mDirectories
.add(fileIt
.getFileName());
277 // get parent from path
278 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
279 fileIt
= getStorageManager().getFileByPath(parentPath
);
281 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
285 private void createMinFragments() {
286 OCFileListFragment listOfFiles
= new OCFileListFragment();
287 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
288 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
289 transaction
.commit();
292 private void initFragmentsWithFile() {
293 if (getAccount() != null
&& getFile() != null
) {
295 OCFileListFragment listOfFiles
= getListOfFilesFragment();
296 if (listOfFiles
!= null
) {
297 listOfFiles
.listDirectory(getCurrentDir());
299 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
303 OCFile file
= getFile();
304 Fragment secondFragment
= chooseInitialSecondFragment(file
);
305 if (secondFragment
!= null
) {
306 setSecondFragment(secondFragment
);
307 updateFragmentsVisibility(true
);
308 updateNavigationElementsInActionBar(file
);
311 cleanSecondFragment();
315 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
316 if (getAccount() == null
) {
317 Log_OC
.wtf(TAG
, "\t account is NULL");
319 if (getFile() == null
) {
320 Log_OC
.wtf(TAG
, "\t file is NULL");
325 private Fragment
chooseInitialSecondFragment(OCFile file
) {
326 Fragment secondFragment
= null
;
327 if (file
!= null
&& !file
.isFolder()) {
328 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
329 && file
.getLastSyncDateForProperties() > 0 // temporal fix
331 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
332 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
333 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
336 secondFragment
= new FileDetailFragment(file
, getAccount());
339 return secondFragment
;
344 * Replaces the second fragment managed by the activity with the received as
347 * Assumes never will be more than two fragments managed at the same time.
349 * @param fragment New second Fragment to set.
351 private void setSecondFragment(Fragment fragment
) {
352 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
353 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
354 transaction
.commit();
358 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
360 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
361 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
363 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
364 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
367 } else if (existsSecondFragment
) {
368 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
369 mLeftFragmentContainer
.setVisibility(View
.GONE
);
371 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
372 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
380 mRightFragmentContainer
.setVisibility(View
.GONE
);
386 private OCFileListFragment
getListOfFilesFragment() {
387 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
388 if (listOfFiles
!= null
) {
389 return (OCFileListFragment
)listOfFiles
;
391 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
395 public FileFragment
getSecondFragment() {
396 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
397 if (second
!= null
) {
398 return (FileFragment
)second
;
403 protected void cleanSecondFragment() {
404 Fragment second
= getSecondFragment();
405 if (second
!= null
) {
406 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
410 updateFragmentsVisibility(false
);
411 updateNavigationElementsInActionBar(null
);
414 protected void refreshListOfFilesFragment() {
415 OCFileListFragment fileListFragment
= getListOfFilesFragment();
416 if (fileListFragment
!= null
) {
417 fileListFragment
.listDirectory();
421 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
422 FileFragment secondFragment
= getSecondFragment();
423 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
424 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
425 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
426 OCFile fileInFragment
= detailsFragment
.getFile();
427 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
428 // the user browsed to other file ; forget the automatic preview
429 mWaitingToPreview
= null
;
431 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
432 // grant that the right panel updates the progress bar
433 detailsFragment
.listenForTransferProgress();
434 detailsFragment
.updateFileDetails(true
, false
);
436 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
437 // update the right panel
438 boolean detailsFragmentChanged
= false
;
441 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
442 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
443 startMediaPreview(mWaitingToPreview
, 0, true
);
444 detailsFragmentChanged
= true
;
446 getFileOperationsHelper().openFile(mWaitingToPreview
);
449 mWaitingToPreview
= null
;
451 if (!detailsFragmentChanged
) {
452 detailsFragment
.updateFileDetails(false
, (success
));
459 public boolean onPrepareOptionsMenu(Menu menu
) {
460 if (BuildConfig
.DEBUG
) {
461 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
463 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
465 return super.onPrepareOptionsMenu(menu
);
469 public boolean onCreateOptionsMenu(Menu menu
) {
470 MenuInflater inflater
= getSherlock().getMenuInflater();
471 inflater
.inflate(R
.menu
.main_menu
, menu
);
476 public boolean onOptionsItemSelected(MenuItem item
) {
477 boolean retval
= true
;
478 switch (item
.getItemId()) {
479 case R
.id
.action_create_dir
: {
480 CreateFolderDialogFragment dialog
=
481 CreateFolderDialogFragment
.newInstance(getCurrentDir());
482 dialog
.show(getSupportFragmentManager(), "createdirdialog");
485 case R
.id
.action_sync_account
: {
486 startSynchronization();
489 case R
.id
.action_upload
: {
490 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
493 case R
.id
.action_settings
: {
494 Intent settingsIntent
= new Intent(this, Preferences
.class);
495 startActivity(settingsIntent
);
498 case R
.id
.action_logger
: {
499 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
500 startActivity(loggerIntent
);
503 case android
.R
.id
.home
: {
504 FileFragment second
= getSecondFragment();
505 OCFile currentDir
= getCurrentDir();
506 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
507 (second
!= null
&& second
.getFile() != null
)) {
513 case R
.id
.action_sort
: {
514 SharedPreferences appPreferences
= PreferenceManager
515 .getDefaultSharedPreferences(this);
517 // Read sorting order, default to sort by name ascending
518 Integer sortOrder
= appPreferences
519 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
521 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
522 builder
.setTitle(R
.string
.actionbar_sort_title
)
523 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
524 public void onClick(DialogInterface dialog
, int which
) {
534 // TODO re-enable when server-side folder size calculation is available
536 // sortBySize(false);
544 builder
.create().show();
548 retval
= super.onOptionsItemSelected(item
);
553 private void startSynchronization() {
554 Log_OC
.e(TAG
, "Got to start sync");
555 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
556 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
557 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
558 Bundle bundle
= new Bundle();
559 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
560 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
561 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
562 ContentResolver
.requestSync(
564 MainApp
.getAuthority(), bundle
);
566 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
567 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
568 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
569 builder
.setExpedited(true
);
570 builder
.setManual(true
);
572 SyncRequest request
= builder
.build();
573 ContentResolver
.requestSync(request
);
579 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
580 if (itemPosition
!= 0) {
581 String targetPath
= "";
582 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
583 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
585 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
586 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
587 if (targetFolder
!= null
) {
588 browseTo(targetFolder
);
591 // the next operation triggers a new call to this method, but it's necessary to
592 // ensure that the name exposed in the action bar is the current directory when the
593 // user selected it in the navigation list
594 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
595 getSupportActionBar().setSelectedNavigationItem(0);
601 * Called, when the user selected something for uploading
603 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
604 super.onActivityResult(requestCode
, resultCode
, data
);
606 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
607 requestSimpleUpload(data
, resultCode
);
609 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
610 requestMultipleUpload(data
, resultCode
);
612 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
613 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
615 final Intent fData
= data
;
616 final int fResultCode
= resultCode
;
617 getHandler().postDelayed(
621 requestMoveOperation(fData
, fResultCode
);
624 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
629 private void requestMultipleUpload(Intent data
, int resultCode
) {
630 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
631 if (filePaths
!= null
) {
632 String
[] remotePaths
= new String
[filePaths
.length
];
633 String remotePathBase
= "";
634 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
635 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
637 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
638 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
639 for (int j
= 0; j
< remotePaths
.length
; j
++) {
640 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
643 Intent i
= new Intent(this, FileUploader
.class);
644 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
645 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
646 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
647 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
648 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
649 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
653 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
654 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
661 private void requestSimpleUpload(Intent data
, int resultCode
) {
662 String filepath
= null
;
664 Uri selectedImageUri
= data
.getData();
666 String filemanagerstring
= selectedImageUri
.getPath();
667 String selectedImagePath
= getPath(selectedImageUri
);
669 if (selectedImagePath
!= null
)
670 filepath
= selectedImagePath
;
672 filepath
= filemanagerstring
;
674 } catch (Exception e
) {
675 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
679 if (filepath
== null
) {
680 Log_OC
.e(TAG
, "Couldnt resolve path to file");
681 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
687 Intent i
= new Intent(this, FileUploader
.class);
688 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
690 String remotepath
= new String();
691 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
692 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
694 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
695 remotepath
+= OCFile
.PATH_SEPARATOR
;
697 if (filepath
.startsWith("content://")) {
698 // The query, since it only applies to a single document, will only return
699 // one row. There's no need to filter, sort, or select fields, since we want
700 // all fields for one document.
701 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
702 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
705 // moveToFirst() returns false if the cursor has 0 rows. Very handy for
706 // "if there's anything to look at, look at it" conditionals.
707 if (cursor
!= null
&& cursor
.moveToFirst()) {
709 // Note it's called "Display Name". This is
710 // provider-specific, and might not necessarily be the file name.
711 String displayName
= cursor
.getString(
712 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
713 Log
.i(TAG
, "Display Name: " + displayName
);
715 remotepath
+= displayName
;
722 remotepath
+= new File(filepath
).getName();
725 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
726 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
727 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
728 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
729 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
734 * Request the operation for moving the file/folder from one path to another
736 * @param data Intent received
737 * @param resultCode Result code received
739 private void requestMoveOperation(Intent data
, int resultCode
) {
740 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
741 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
742 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
746 public void onBackPressed() {
747 OCFileListFragment listOfFiles
= getListOfFilesFragment();
748 if (mDualPane
|| getSecondFragment() == null
) {
749 if (listOfFiles
!= null
) { // should never be null, indeed
750 if (mDirectories
.getCount() <= 1) {
754 int levelsUp
= listOfFiles
.onBrowseUp();
755 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
760 if (listOfFiles
!= null
) { // should never be null, indeed
761 setFile(listOfFiles
.getCurrentFile());
763 cleanSecondFragment();
768 protected void onSaveInstanceState(Bundle outState
) {
769 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
770 Log_OC
.e(TAG
, "onSaveInstanceState() start");
771 super.onSaveInstanceState(outState
);
772 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
773 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
774 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
775 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
777 Log_OC
.d(TAG
, "onSaveInstanceState() end");
783 protected void onResume() {
785 Log_OC
.e(TAG
, "onResume() start");
787 // refresh list of files
788 refreshListOfFilesFragment();
790 // Listen for sync messages
791 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
792 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
793 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
794 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
795 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
796 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
797 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
798 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
800 // Listen for upload messages
801 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
802 mUploadFinishReceiver
= new UploadFinishReceiver();
803 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
805 // Listen for download messages
806 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
807 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
808 mDownloadFinishReceiver
= new DownloadFinishReceiver();
809 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
811 Log_OC
.d(TAG
, "onResume() end");
816 protected void onPause() {
817 Log_OC
.e(TAG
, "onPause() start");
818 if (mSyncBroadcastReceiver
!= null
) {
819 unregisterReceiver(mSyncBroadcastReceiver
);
820 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
821 mSyncBroadcastReceiver
= null
;
823 if (mUploadFinishReceiver
!= null
) {
824 unregisterReceiver(mUploadFinishReceiver
);
825 mUploadFinishReceiver
= null
;
827 if (mDownloadFinishReceiver
!= null
) {
828 unregisterReceiver(mDownloadFinishReceiver
);
829 mDownloadFinishReceiver
= null
;
833 Log_OC
.d(TAG
, "onPause() end");
839 protected Dialog
onCreateDialog(int id
) {
840 Dialog dialog
= null
;
841 AlertDialog
.Builder builder
;
843 case DIALOG_SHORT_WAIT
: {
844 ProgressDialog working_dialog
= new ProgressDialog(this);
845 working_dialog
.setMessage(getResources().getString(
846 R
.string
.wait_a_moment
));
847 working_dialog
.setIndeterminate(true
);
848 working_dialog
.setCancelable(false
);
849 dialog
= working_dialog
;
852 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
855 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
856 getString(R
.string
.actionbar_upload_from_apps
) };
858 builder
= new AlertDialog
.Builder(this);
859 builder
.setTitle(R
.string
.actionbar_upload
);
860 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
861 public void onClick(DialogInterface dialog
, int item
) {
864 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
865 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
866 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
868 // TODO create and handle new fragment
869 // LocalFileListFragment
871 } else if (item
== 1) {
872 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
873 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
874 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
875 ACTION_SELECT_CONTENT_FROM_APPS
);
879 dialog
= builder
.create();
882 case DIALOG_CERT_NOT_SAVED
: {
883 builder
= new AlertDialog
.Builder(this);
884 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
885 builder
.setCancelable(false
);
886 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
888 public void onClick(DialogInterface dialog
, int which
) {
892 dialog
= builder
.create();
903 * Translates a content URI of an content to a physical path on the disk
905 * @param uri The URI to resolve
906 * @return The path to the content or null if it could not be found
908 public String
getPath(Uri uri
) {
909 final boolean isKitKat
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
912 if (isKitKat
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
913 // ExternalStorageProvider
914 if (isExternalStorageDocument(uri
)) {
915 final String docId
= DocumentsContract
.getDocumentId(uri
);
916 final String
[] split
= docId
.split(":");
917 final String type
= split
[0];
919 if ("primary".equalsIgnoreCase(type
)) {
920 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
924 else if (isDownloadsDocument(uri
)) {
926 final String id
= DocumentsContract
.getDocumentId(uri
);
927 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
930 return getDataColumn(getApplicationContext(), contentUri
, null
, null
);
933 else if (isMediaDocument(uri
)) {
934 final String docId
= DocumentsContract
.getDocumentId(uri
);
935 final String
[] split
= docId
.split(":");
936 final String type
= split
[0];
938 Uri contentUri
= null
;
939 if ("image".equals(type
)) {
940 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
941 } else if ("video".equals(type
)) {
942 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
943 } else if ("audio".equals(type
)) {
944 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
947 final String selection
= "_id=?";
948 final String
[] selectionArgs
= new String
[] { split
[1] };
950 return getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
952 // Documents providers returned as content://...
953 else if (isAContentDocument(uri
)) {
954 return uri
.toString();
957 // MediaStore (and general)
958 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
960 // Return the remote address
961 if (isGooglePhotosUri(uri
))
962 return uri
.getLastPathSegment();
964 return getDataColumn(getApplicationContext(), uri
, null
, null
);
967 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
968 return uri
.getPath();
974 * Get the value of the data column for this Uri. This is useful for
975 * MediaStore Uris, and other file-based ContentProviders.
977 * @param context The context.
978 * @param uri The Uri to query.
979 * @param selection (Optional) Filter used in the query.
980 * @param selectionArgs (Optional) Selection arguments used in the query.
981 * @return The value of the _data column, which is typically a file path.
983 public static String
getDataColumn(Context context
, Uri uri
, String selection
, String
[] selectionArgs
) {
985 Cursor cursor
= null
;
986 final String column
= "_data";
987 final String
[] projection
= { column
};
990 cursor
= context
.getContentResolver().query(uri
, projection
, selection
, selectionArgs
, null
);
991 if (cursor
!= null
&& cursor
.moveToFirst()) {
993 final int column_index
= cursor
.getColumnIndexOrThrow(column
);
994 return cursor
.getString(column_index
);
1004 * @param uri The Uri to check.
1005 * @return Whether the Uri authority is ExternalStorageProvider.
1007 public static boolean isExternalStorageDocument(Uri uri
) {
1008 return "com.android.externalstorage.documents".equals(uri
.getAuthority());
1012 * @param uri The Uri to check.
1013 * @return Whether the Uri authority is DownloadsProvider.
1015 public static boolean isDownloadsDocument(Uri uri
) {
1016 return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
1020 * @param uri The Uri to check.
1021 * @return Whether the Uri authority is MediaProvider.
1023 public static boolean isMediaDocument(Uri uri
) {
1024 return "com.android.providers.media.documents".equals(uri
.getAuthority());
1028 * @param uri The Uri to check.
1029 * @return Whether the Uri authority is Google Photos.
1031 public static boolean isGooglePhotosUri(Uri uri
) {
1032 return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
1037 * @param uri The Uri to check.
1038 * @return Whether the Uri authority is Google Drive.
1040 public static boolean isGoogleDriveDocument(Uri uri
) {
1041 return "com.google.android.apps.docs.storage".equals(uri
.getAuthority());
1046 * @param uri The Uri to check.
1047 * @return Whether the Uri is from a content provider as kind "content://..."
1049 public static boolean isAContentDocument(Uri uri
) {
1050 return uri
.toString().startsWith("content://");
1054 * Pushes a directory to the drop down list
1055 * @param directory to push
1056 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1058 public void pushDirname(OCFile directory
) {
1059 if(!directory
.isFolder()){
1060 throw new IllegalArgumentException("Only directories may be pushed!");
1062 mDirectories
.insert(directory
.getFileName(), 0);
1067 * Pops a directory name from the drop down list
1068 * @return True, unless the stack is empty
1070 public boolean popDirname() {
1071 mDirectories
.remove(mDirectories
.getItem(0));
1072 return !mDirectories
.isEmpty();
1075 // Custom array adapter to override text colors
1076 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1078 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1082 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1083 View v
= super.getView(position
, convertView
, parent
);
1085 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1086 android
.R
.color
.white
));
1088 fixRoot((TextView
) v
);
1092 public View
getDropDownView(int position
, View convertView
,
1094 View v
= super.getDropDownView(position
, convertView
, parent
);
1096 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1097 android
.R
.color
.white
));
1099 fixRoot((TextView
) v
);
1103 private void fixRoot(TextView v
) {
1104 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1105 v
.setText(R
.string
.default_display_name_for_root_folder
);
1111 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1114 * {@link BroadcastReceiver} to enable syncing feedback in UI
1117 public void onReceive(Context context
, Intent intent
) {
1119 String event
= intent
.getAction();
1120 Log_OC
.d(TAG
, "Received broadcast " + event
);
1121 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1122 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1123 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1124 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1128 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1129 mSyncInProgress
= true
;
1132 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1133 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1135 if (currentDir
== null
) {
1136 // current folder was removed from the server
1137 Toast
.makeText( FileDisplayActivity
.this,
1138 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1144 if (currentFile
== null
&& !getFile().isFolder()) {
1145 // currently selected file was removed in the server, and now we know it
1146 cleanSecondFragment();
1147 currentFile
= currentDir
;
1150 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1151 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1152 if (fileListFragment
!= null
) {
1153 fileListFragment
.listDirectory(currentDir
);
1156 setFile(currentFile
);
1159 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1161 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1163 /// TODO refactor and make common
1164 synchResult
!= null
&& !synchResult
.isSuccess() &&
1165 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1166 synchResult
.isIdPRedirection() ||
1167 (synchResult
.isException() && synchResult
.getException()
1168 instanceof AuthenticatorException
))) {
1170 OwnCloudClient client
= null
;
1172 OwnCloudAccount ocAccount
=
1173 new OwnCloudAccount(getAccount(), context
);
1174 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1175 removeClientFor(ocAccount
));
1176 // TODO get rid of these exceptions
1177 } catch (AccountNotFoundException e
) {
1178 e
.printStackTrace();
1179 } catch (AuthenticatorException e
) {
1180 e
.printStackTrace();
1181 } catch (OperationCanceledException e
) {
1182 e
.printStackTrace();
1183 } catch (IOException e
) {
1184 e
.printStackTrace();
1187 if (client
!= null
) {
1188 OwnCloudCredentials cred
= client
.getCredentials();
1190 AccountManager am
= AccountManager
.get(context
);
1191 if (cred
.authTokenExpires()) {
1192 am
.invalidateAuthToken(
1197 am
.clearPassword(getAccount());
1202 requestCredentialsUpdate();
1206 removeStickyBroadcast(intent
);
1207 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1208 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1210 setBackgroundText();
1214 if (synchResult
!= null
) {
1215 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1216 mLastSslUntrustedServerResult
= synchResult
;
1219 } catch (RuntimeException e
) {
1220 // avoid app crashes after changing the serial id of RemoteOperationResult
1221 // in owncloud library with broadcast notifications pending to process
1222 removeStickyBroadcast(intent
);
1228 * Show a text message on screen view for notifying user if content is
1229 * loading or folder is empty
1231 private void setBackgroundText() {
1232 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1233 if (ocFileListFragment
!= null
) {
1234 int message
= R
.string
.file_list_loading
;
1235 if (!mSyncInProgress
) {
1236 // In case file list is empty
1237 message
= R
.string
.file_list_empty
;
1239 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1241 Log_OC
.e(TAG
, "OCFileListFragment is null");
1246 * Once the file upload has finished -> update view
1248 private class UploadFinishReceiver
extends BroadcastReceiver
{
1250 * Once the file upload has finished -> update view
1251 * @author David A. Velasco
1252 * {@link BroadcastReceiver} to enable upload feedback in UI
1255 public void onReceive(Context context
, Intent intent
) {
1257 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1258 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1259 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1260 OCFile currentDir
= getCurrentDir();
1261 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1262 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1264 if (sameAccount
&& isDescendant
) {
1265 refreshListOfFilesFragment();
1268 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1269 boolean renamedInUpload
= getFile().getRemotePath().
1270 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1271 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1273 FileFragment details
= getSecondFragment();
1274 boolean detailFragmentIsShown
= (details
!= null
&&
1275 details
instanceof FileDetailFragment
);
1277 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1278 if (uploadWasFine
) {
1279 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1281 if (renamedInUpload
) {
1282 String newName
= (new File(uploadedRemotePath
)).getName();
1283 Toast msg
= Toast
.makeText(
1286 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1291 if (uploadWasFine
|| getFile().fileExists()) {
1292 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1294 cleanSecondFragment();
1297 // Force the preview if the file is an image
1298 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1299 startImagePreview(getFile());
1300 } // TODO what about other kind of previews?
1304 if (intent
!= null
) {
1305 removeStickyBroadcast(intent
);
1315 * Class waiting for broadcast events from the {@link FielDownloader} service.
1317 * Updates the UI when a download is started or finished, provided that it is relevant for the
1320 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1322 public void onReceive(Context context
, Intent intent
) {
1324 boolean sameAccount
= isSameAccount(context
, intent
);
1325 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1326 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1328 if (sameAccount
&& isDescendant
) {
1329 refreshListOfFilesFragment();
1330 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1333 if (mWaitingToSend
!= null
) {
1334 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1335 if (mWaitingToSend
.isDown()) {
1336 sendDownloadedFile();
1341 if (intent
!= null
) {
1342 removeStickyBroadcast(intent
);
1347 private boolean isDescendant(String downloadedRemotePath
) {
1348 OCFile currentDir
= getCurrentDir();
1349 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1352 private boolean isSameAccount(Context context
, Intent intent
) {
1353 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1354 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1359 public void browseToRoot() {
1360 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1361 if (listOfFiles
!= null
) { // should never be null, indeed
1362 while (mDirectories
.getCount() > 1) {
1365 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1366 listOfFiles
.listDirectory(root
);
1367 setFile(listOfFiles
.getCurrentFile());
1368 startSyncFolderOperation(root
, false
);
1370 cleanSecondFragment();
1374 public void browseTo(OCFile folder
) {
1375 if (folder
== null
|| !folder
.isFolder()) {
1376 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1378 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1379 if (listOfFiles
!= null
) {
1380 setNavigationListWithFolder(folder
);
1381 listOfFiles
.listDirectory(folder
);
1382 setFile(listOfFiles
.getCurrentFile());
1383 startSyncFolderOperation(folder
, false
);
1385 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1387 cleanSecondFragment();
1394 * Updates action bar and second fragment, if in dual pane mode.
1397 public void onBrowsedDownTo(OCFile directory
) {
1398 pushDirname(directory
);
1399 cleanSecondFragment();
1402 startSyncFolderOperation(directory
, false
);
1407 * Shows the information of the {@link OCFile} received as a
1408 * parameter in the second fragment.
1410 * @param file {@link OCFile} whose details will be shown
1413 public void showDetails(OCFile file
) {
1414 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1415 setSecondFragment(detailFragment
);
1416 updateFragmentsVisibility(true
);
1417 updateNavigationElementsInActionBar(file
);
1425 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1426 ActionBar actionBar
= getSupportActionBar();
1427 if (chosenFile
== null
|| mDualPane
) {
1428 // only list of files - set for browsing through folders
1429 OCFile currentDir
= getCurrentDir();
1430 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1431 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1432 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1434 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1436 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1437 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1440 actionBar
.setDisplayHomeAsUpEnabled(true
);
1441 actionBar
.setDisplayShowTitleEnabled(true
);
1442 actionBar
.setTitle(chosenFile
.getFileName());
1443 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1449 protected ServiceConnection
newTransferenceServiceConnection() {
1450 return new ListServiceConnection();
1453 /** Defines callbacks for service binding, passed to bindService() */
1454 private class ListServiceConnection
implements ServiceConnection
{
1457 public void onServiceConnected(ComponentName component
, IBinder service
) {
1458 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1459 Log_OC
.d(TAG
, "Download service connected");
1460 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1461 if (mWaitingToPreview
!= null
)
1462 if (getStorageManager() != null
) {
1463 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1464 if (!mWaitingToPreview
.isDown()) {
1465 requestForDownload();
1469 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1470 Log_OC
.d(TAG
, "Upload service connected");
1471 mUploaderBinder
= (FileUploaderBinder
) service
;
1475 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1476 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1477 if (listOfFiles
!= null
) {
1478 listOfFiles
.listDirectory();
1480 FileFragment secondFragment
= getSecondFragment();
1481 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1482 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1483 detailFragment
.listenForTransferProgress();
1484 detailFragment
.updateFileDetails(false
, false
);
1489 public void onServiceDisconnected(ComponentName component
) {
1490 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1491 Log_OC
.d(TAG
, "Download service disconnected");
1492 mDownloaderBinder
= null
;
1493 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1494 Log_OC
.d(TAG
, "Upload service disconnected");
1495 mUploaderBinder
= null
;
1503 * Launch an intent to request the PIN code to the user before letting him use the app
1505 private void requestPinCode() {
1506 boolean pinStart
= false
;
1507 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1508 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1510 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1511 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1518 public void onSavedCertificate() {
1519 startSyncFolderOperation(getCurrentDir(), false
);
1524 public void onFailedSavingCertificate() {
1525 showDialog(DIALOG_CERT_NOT_SAVED
);
1529 public void onCancelCertificate() {
1534 * Updates the view associated to the activity after the finish of some operation over files
1535 * in the current account.
1537 * @param operation Removal operation performed.
1538 * @param result Result of the removal.
1541 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1542 super.onRemoteOperationFinish(operation
, result
);
1544 if (operation
instanceof RemoveFileOperation
) {
1545 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1547 } else if (operation
instanceof RenameFileOperation
) {
1548 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1550 } else if (operation
instanceof SynchronizeFileOperation
) {
1551 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1553 } else if (operation
instanceof CreateFolderOperation
) {
1554 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1556 } else if (operation
instanceof CreateShareOperation
) {
1557 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1559 } else if (operation
instanceof UnshareLinkOperation
) {
1560 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1562 } else if (operation
instanceof MoveFileOperation
) {
1563 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1569 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1570 if (result
.isSuccess()) {
1571 refreshShowDetails();
1572 refreshListOfFilesFragment();
1577 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1578 if (result
.isSuccess()) {
1579 refreshShowDetails();
1580 refreshListOfFilesFragment();
1582 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1583 cleanSecondFragment();
1584 refreshListOfFilesFragment();
1588 private void refreshShowDetails() {
1589 FileFragment details
= getSecondFragment();
1590 if (details
!= null
) {
1591 OCFile file
= details
.getFile();
1593 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1594 if (details
instanceof PreviewMediaFragment
) {
1595 // Refresh OCFile of the fragment
1596 ((PreviewMediaFragment
) details
).updateFile(file
);
1601 invalidateOptionsMenu();
1606 * Updates the view associated to the activity after the finish of an operation trying to remove a
1609 * @param operation Removal operation performed.
1610 * @param result Result of the removal.
1612 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1613 dismissLoadingDialog();
1615 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1619 if (result
.isSuccess()) {
1620 OCFile removedFile
= operation
.getFile();
1621 FileFragment second
= getSecondFragment();
1622 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1623 if (second
instanceof PreviewMediaFragment
) {
1624 ((PreviewMediaFragment
)second
).stopPreview(true
);
1626 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1627 cleanSecondFragment();
1629 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1630 refreshListOfFilesFragment();
1632 invalidateOptionsMenu();
1634 if (result
.isSslRecoverableException()) {
1635 mLastSslUntrustedServerResult
= result
;
1636 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1643 * Updates the view associated to the activity after the finish of an operation trying to move a
1646 * @param operation Move operation performed.
1647 * @param result Result of the move operation.
1649 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1650 if (result
.isSuccess()) {
1651 dismissLoadingDialog();
1652 refreshListOfFilesFragment();
1654 dismissLoadingDialog();
1656 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1657 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1661 } catch (NotFoundException e
) {
1662 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1669 * Updates the view associated to the activity after the finish of an operation trying to rename a
1672 * @param operation Renaming operation performed.
1673 * @param result Result of the renaming.
1675 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1676 dismissLoadingDialog();
1677 OCFile renamedFile
= operation
.getFile();
1678 if (result
.isSuccess()) {
1679 FileFragment details
= getSecondFragment();
1680 if (details
!= null
) {
1681 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1682 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1683 showDetails(renamedFile
);
1685 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1686 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1687 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1688 int position
= ((PreviewMediaFragment
)details
).getPosition();
1689 startMediaPreview(renamedFile
, position
, true
);
1691 getFileOperationsHelper().openFile(renamedFile
);
1696 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1697 refreshListOfFilesFragment();
1701 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1705 if (result
.isSslRecoverableException()) {
1706 mLastSslUntrustedServerResult
= result
;
1707 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1712 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1713 dismissLoadingDialog();
1714 OCFile syncedFile
= operation
.getLocalFile();
1715 if (!result
.isSuccess()) {
1716 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1717 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1718 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1719 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1725 if (operation
.transferWasRequested()) {
1726 onTransferStateChanged(syncedFile
, true
, true
);
1729 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1737 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1739 * @param operation Creation operation performed.
1740 * @param result Result of the creation.
1742 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1743 if (result
.isSuccess()) {
1744 dismissLoadingDialog();
1745 refreshListOfFilesFragment();
1747 dismissLoadingDialog();
1749 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1750 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1754 } catch (NotFoundException e
) {
1755 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1765 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1766 refreshListOfFilesFragment();
1767 FileFragment details
= getSecondFragment();
1768 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1769 if (downloading
|| uploading
) {
1770 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1772 if (!file
.fileExists()) {
1773 cleanSecondFragment();
1775 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1783 private void requestForDownload() {
1784 Account account
= getAccount();
1785 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1786 Intent i
= new Intent(this, FileDownloader
.class);
1787 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1788 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1794 private OCFile
getCurrentDir() {
1795 OCFile file
= getFile();
1797 if (file
.isFolder()) {
1799 } else if (getStorageManager() != null
) {
1800 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1801 return getStorageManager().getFileByPath(parentPath
);
1807 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1808 long currentSyncTime
= System
.currentTimeMillis();
1810 mSyncInProgress
= true
;
1812 // perform folder synchronization
1813 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1816 getFileOperationsHelper().isSharedSupported(),
1818 getStorageManager(),
1820 getApplicationContext()
1822 synchFolderOp
.execute(getAccount(), this, null
, null
);
1824 setSupportProgressBarIndeterminateVisibility(true
);
1826 setBackgroundText();
1830 * Show untrusted cert dialog
1832 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1833 // Show a dialog with the certificate info
1834 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1835 FragmentManager fm
= getSupportFragmentManager();
1836 FragmentTransaction ft
= fm
.beginTransaction();
1837 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1840 private void requestForDownload(OCFile file
) {
1841 Account account
= getAccount();
1842 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1843 Intent i
= new Intent(this, FileDownloader
.class);
1844 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1845 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1850 private void sendDownloadedFile(){
1851 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1852 mWaitingToSend
= null
;
1857 * Requests the download of the received {@link OCFile} , updates the UI
1858 * to monitor the download progress and prepares the activity to send the file
1859 * when the download finishes.
1861 * @param file {@link OCFile} to download and preview.
1863 public void startDownloadForSending(OCFile file
) {
1864 mWaitingToSend
= file
;
1865 requestForDownload(mWaitingToSend
);
1866 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1867 updateFragmentsVisibility(hasSecondFragment
);
1871 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1873 * @param file Image {@link OCFile} to show.
1875 public void startImagePreview(OCFile file
) {
1876 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1877 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1878 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1879 startActivity(showDetailsIntent
);
1884 * Stars the preview of an already down media {@link OCFile}.
1886 * @param file Media {@link OCFile} to preview.
1887 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1888 * @param autoplay When 'true', the playback will start without user interactions.
1890 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1891 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1892 setSecondFragment(mediaFragment
);
1893 updateFragmentsVisibility(true
);
1894 updateNavigationElementsInActionBar(file
);
1899 * Requests the download of the received {@link OCFile} , updates the UI
1900 * to monitor the download progress and prepares the activity to preview
1901 * or open the file when the download finishes.
1903 * @param file {@link OCFile} to download and preview.
1905 public void startDownloadForPreview(OCFile file
) {
1906 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1907 setSecondFragment(detailFragment
);
1908 mWaitingToPreview
= file
;
1909 requestForDownload();
1910 updateFragmentsVisibility(true
);
1911 updateNavigationElementsInActionBar(file
);
1916 public void cancelTransference(OCFile file
) {
1917 getFileOperationsHelper().cancelTransference(file
);
1918 if (mWaitingToPreview
!= null
&&
1919 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1920 mWaitingToPreview
= null
;
1922 if (mWaitingToSend
!= null
&&
1923 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1924 mWaitingToSend
= null
;
1926 onTransferStateChanged(file
, false
, false
);
1930 public void onRefresh(boolean ignoreETag
) {
1931 refreshList(ignoreETag
);
1935 public void onRefresh() {
1939 private void refreshList(boolean ignoreETag
) {
1940 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1941 if (listOfFiles
!= null
) {
1942 OCFile folder
= listOfFiles
.getCurrentFile();
1943 if (folder
!= null
) {
1944 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1945 listDirectory(mFile);*/
1946 startSyncFolderOperation(folder
, ignoreETag
);
1951 private void sortByDate(boolean ascending
){
1952 getListOfFilesFragment().sortByDate(ascending
);
1955 private void sortBySize(boolean ascending
){
1956 getListOfFilesFragment().sortBySize(ascending
);
1959 private void sortByName(boolean ascending
){
1960 getListOfFilesFragment().sortByName(ascending
);