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
);
953 else if (isGoogleDriveDocument(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());
1045 * Pushes a directory to the drop down list
1046 * @param directory to push
1047 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1049 public void pushDirname(OCFile directory
) {
1050 if(!directory
.isFolder()){
1051 throw new IllegalArgumentException("Only directories may be pushed!");
1053 mDirectories
.insert(directory
.getFileName(), 0);
1058 * Pops a directory name from the drop down list
1059 * @return True, unless the stack is empty
1061 public boolean popDirname() {
1062 mDirectories
.remove(mDirectories
.getItem(0));
1063 return !mDirectories
.isEmpty();
1066 // Custom array adapter to override text colors
1067 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1069 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1073 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1074 View v
= super.getView(position
, convertView
, parent
);
1076 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1077 android
.R
.color
.white
));
1079 fixRoot((TextView
) v
);
1083 public View
getDropDownView(int position
, View convertView
,
1085 View v
= super.getDropDownView(position
, convertView
, parent
);
1087 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1088 android
.R
.color
.white
));
1090 fixRoot((TextView
) v
);
1094 private void fixRoot(TextView v
) {
1095 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1096 v
.setText(R
.string
.default_display_name_for_root_folder
);
1102 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1105 * {@link BroadcastReceiver} to enable syncing feedback in UI
1108 public void onReceive(Context context
, Intent intent
) {
1110 String event
= intent
.getAction();
1111 Log_OC
.d(TAG
, "Received broadcast " + event
);
1112 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1113 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1114 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1115 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1119 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1120 mSyncInProgress
= true
;
1123 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1124 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1126 if (currentDir
== null
) {
1127 // current folder was removed from the server
1128 Toast
.makeText( FileDisplayActivity
.this,
1129 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1135 if (currentFile
== null
&& !getFile().isFolder()) {
1136 // currently selected file was removed in the server, and now we know it
1137 cleanSecondFragment();
1138 currentFile
= currentDir
;
1141 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1142 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1143 if (fileListFragment
!= null
) {
1144 fileListFragment
.listDirectory(currentDir
);
1147 setFile(currentFile
);
1150 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1152 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1154 /// TODO refactor and make common
1155 synchResult
!= null
&& !synchResult
.isSuccess() &&
1156 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1157 synchResult
.isIdPRedirection() ||
1158 (synchResult
.isException() && synchResult
.getException()
1159 instanceof AuthenticatorException
))) {
1161 OwnCloudClient client
= null
;
1163 OwnCloudAccount ocAccount
=
1164 new OwnCloudAccount(getAccount(), context
);
1165 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1166 removeClientFor(ocAccount
));
1167 // TODO get rid of these exceptions
1168 } catch (AccountNotFoundException e
) {
1169 e
.printStackTrace();
1170 } catch (AuthenticatorException e
) {
1171 e
.printStackTrace();
1172 } catch (OperationCanceledException e
) {
1173 e
.printStackTrace();
1174 } catch (IOException e
) {
1175 e
.printStackTrace();
1178 if (client
!= null
) {
1179 OwnCloudCredentials cred
= client
.getCredentials();
1181 AccountManager am
= AccountManager
.get(context
);
1182 if (cred
.authTokenExpires()) {
1183 am
.invalidateAuthToken(
1188 am
.clearPassword(getAccount());
1193 requestCredentialsUpdate();
1197 removeStickyBroadcast(intent
);
1198 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1199 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1201 setBackgroundText();
1205 if (synchResult
!= null
) {
1206 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1207 mLastSslUntrustedServerResult
= synchResult
;
1210 } catch (RuntimeException e
) {
1211 // avoid app crashes after changing the serial id of RemoteOperationResult
1212 // in owncloud library with broadcast notifications pending to process
1213 removeStickyBroadcast(intent
);
1219 * Show a text message on screen view for notifying user if content is
1220 * loading or folder is empty
1222 private void setBackgroundText() {
1223 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1224 if (ocFileListFragment
!= null
) {
1225 int message
= R
.string
.file_list_loading
;
1226 if (!mSyncInProgress
) {
1227 // In case file list is empty
1228 message
= R
.string
.file_list_empty
;
1230 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1232 Log_OC
.e(TAG
, "OCFileListFragment is null");
1237 * Once the file upload has finished -> update view
1239 private class UploadFinishReceiver
extends BroadcastReceiver
{
1241 * Once the file upload has finished -> update view
1242 * @author David A. Velasco
1243 * {@link BroadcastReceiver} to enable upload feedback in UI
1246 public void onReceive(Context context
, Intent intent
) {
1248 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1249 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1250 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1251 OCFile currentDir
= getCurrentDir();
1252 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1253 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1255 if (sameAccount
&& isDescendant
) {
1256 refreshListOfFilesFragment();
1259 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1260 boolean renamedInUpload
= getFile().getRemotePath().
1261 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1262 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1264 FileFragment details
= getSecondFragment();
1265 boolean detailFragmentIsShown
= (details
!= null
&&
1266 details
instanceof FileDetailFragment
);
1268 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1269 if (uploadWasFine
) {
1270 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1272 if (renamedInUpload
) {
1273 String newName
= (new File(uploadedRemotePath
)).getName();
1274 Toast msg
= Toast
.makeText(
1277 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1282 if (uploadWasFine
|| getFile().fileExists()) {
1283 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1285 cleanSecondFragment();
1288 // Force the preview if the file is an image
1289 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1290 startImagePreview(getFile());
1291 } // TODO what about other kind of previews?
1295 if (intent
!= null
) {
1296 removeStickyBroadcast(intent
);
1306 * Class waiting for broadcast events from the {@link FielDownloader} service.
1308 * Updates the UI when a download is started or finished, provided that it is relevant for the
1311 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1313 public void onReceive(Context context
, Intent intent
) {
1315 boolean sameAccount
= isSameAccount(context
, intent
);
1316 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1317 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1319 if (sameAccount
&& isDescendant
) {
1320 refreshListOfFilesFragment();
1321 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1324 if (mWaitingToSend
!= null
) {
1325 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1326 if (mWaitingToSend
.isDown()) {
1327 sendDownloadedFile();
1332 if (intent
!= null
) {
1333 removeStickyBroadcast(intent
);
1338 private boolean isDescendant(String downloadedRemotePath
) {
1339 OCFile currentDir
= getCurrentDir();
1340 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1343 private boolean isSameAccount(Context context
, Intent intent
) {
1344 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1345 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1350 public void browseToRoot() {
1351 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1352 if (listOfFiles
!= null
) { // should never be null, indeed
1353 while (mDirectories
.getCount() > 1) {
1356 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1357 listOfFiles
.listDirectory(root
);
1358 setFile(listOfFiles
.getCurrentFile());
1359 startSyncFolderOperation(root
, false
);
1361 cleanSecondFragment();
1365 public void browseTo(OCFile folder
) {
1366 if (folder
== null
|| !folder
.isFolder()) {
1367 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1369 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1370 if (listOfFiles
!= null
) {
1371 setNavigationListWithFolder(folder
);
1372 listOfFiles
.listDirectory(folder
);
1373 setFile(listOfFiles
.getCurrentFile());
1374 startSyncFolderOperation(folder
, false
);
1376 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1378 cleanSecondFragment();
1385 * Updates action bar and second fragment, if in dual pane mode.
1388 public void onBrowsedDownTo(OCFile directory
) {
1389 pushDirname(directory
);
1390 cleanSecondFragment();
1393 startSyncFolderOperation(directory
, false
);
1398 * Shows the information of the {@link OCFile} received as a
1399 * parameter in the second fragment.
1401 * @param file {@link OCFile} whose details will be shown
1404 public void showDetails(OCFile file
) {
1405 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1406 setSecondFragment(detailFragment
);
1407 updateFragmentsVisibility(true
);
1408 updateNavigationElementsInActionBar(file
);
1416 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1417 ActionBar actionBar
= getSupportActionBar();
1418 if (chosenFile
== null
|| mDualPane
) {
1419 // only list of files - set for browsing through folders
1420 OCFile currentDir
= getCurrentDir();
1421 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1422 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1423 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1425 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1427 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1428 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1431 actionBar
.setDisplayHomeAsUpEnabled(true
);
1432 actionBar
.setDisplayShowTitleEnabled(true
);
1433 actionBar
.setTitle(chosenFile
.getFileName());
1434 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1440 protected ServiceConnection
newTransferenceServiceConnection() {
1441 return new ListServiceConnection();
1444 /** Defines callbacks for service binding, passed to bindService() */
1445 private class ListServiceConnection
implements ServiceConnection
{
1448 public void onServiceConnected(ComponentName component
, IBinder service
) {
1449 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1450 Log_OC
.d(TAG
, "Download service connected");
1451 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1452 if (mWaitingToPreview
!= null
)
1453 if (getStorageManager() != null
) {
1454 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1455 if (!mWaitingToPreview
.isDown()) {
1456 requestForDownload();
1460 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1461 Log_OC
.d(TAG
, "Upload service connected");
1462 mUploaderBinder
= (FileUploaderBinder
) service
;
1466 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1467 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1468 if (listOfFiles
!= null
) {
1469 listOfFiles
.listDirectory();
1471 FileFragment secondFragment
= getSecondFragment();
1472 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1473 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1474 detailFragment
.listenForTransferProgress();
1475 detailFragment
.updateFileDetails(false
, false
);
1480 public void onServiceDisconnected(ComponentName component
) {
1481 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1482 Log_OC
.d(TAG
, "Download service disconnected");
1483 mDownloaderBinder
= null
;
1484 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1485 Log_OC
.d(TAG
, "Upload service disconnected");
1486 mUploaderBinder
= null
;
1494 * Launch an intent to request the PIN code to the user before letting him use the app
1496 private void requestPinCode() {
1497 boolean pinStart
= false
;
1498 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1499 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1501 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1502 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1509 public void onSavedCertificate() {
1510 startSyncFolderOperation(getCurrentDir(), false
);
1515 public void onFailedSavingCertificate() {
1516 showDialog(DIALOG_CERT_NOT_SAVED
);
1520 public void onCancelCertificate() {
1525 * Updates the view associated to the activity after the finish of some operation over files
1526 * in the current account.
1528 * @param operation Removal operation performed.
1529 * @param result Result of the removal.
1532 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1533 super.onRemoteOperationFinish(operation
, result
);
1535 if (operation
instanceof RemoveFileOperation
) {
1536 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1538 } else if (operation
instanceof RenameFileOperation
) {
1539 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1541 } else if (operation
instanceof SynchronizeFileOperation
) {
1542 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1544 } else if (operation
instanceof CreateFolderOperation
) {
1545 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1547 } else if (operation
instanceof CreateShareOperation
) {
1548 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1550 } else if (operation
instanceof UnshareLinkOperation
) {
1551 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1553 } else if (operation
instanceof MoveFileOperation
) {
1554 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1560 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1561 if (result
.isSuccess()) {
1562 refreshShowDetails();
1563 refreshListOfFilesFragment();
1568 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1569 if (result
.isSuccess()) {
1570 refreshShowDetails();
1571 refreshListOfFilesFragment();
1573 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1574 cleanSecondFragment();
1575 refreshListOfFilesFragment();
1579 private void refreshShowDetails() {
1580 FileFragment details
= getSecondFragment();
1581 if (details
!= null
) {
1582 OCFile file
= details
.getFile();
1584 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1585 if (details
instanceof PreviewMediaFragment
) {
1586 // Refresh OCFile of the fragment
1587 ((PreviewMediaFragment
) details
).updateFile(file
);
1592 invalidateOptionsMenu();
1597 * Updates the view associated to the activity after the finish of an operation trying to remove a
1600 * @param operation Removal operation performed.
1601 * @param result Result of the removal.
1603 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1604 dismissLoadingDialog();
1606 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1610 if (result
.isSuccess()) {
1611 OCFile removedFile
= operation
.getFile();
1612 FileFragment second
= getSecondFragment();
1613 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1614 if (second
instanceof PreviewMediaFragment
) {
1615 ((PreviewMediaFragment
)second
).stopPreview(true
);
1617 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1618 cleanSecondFragment();
1620 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1621 refreshListOfFilesFragment();
1623 invalidateOptionsMenu();
1625 if (result
.isSslRecoverableException()) {
1626 mLastSslUntrustedServerResult
= result
;
1627 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1634 * Updates the view associated to the activity after the finish of an operation trying to move a
1637 * @param operation Move operation performed.
1638 * @param result Result of the move operation.
1640 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1641 if (result
.isSuccess()) {
1642 dismissLoadingDialog();
1643 refreshListOfFilesFragment();
1645 dismissLoadingDialog();
1647 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1648 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1652 } catch (NotFoundException e
) {
1653 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1660 * Updates the view associated to the activity after the finish of an operation trying to rename a
1663 * @param operation Renaming operation performed.
1664 * @param result Result of the renaming.
1666 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1667 dismissLoadingDialog();
1668 OCFile renamedFile
= operation
.getFile();
1669 if (result
.isSuccess()) {
1670 FileFragment details
= getSecondFragment();
1671 if (details
!= null
) {
1672 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1673 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1674 showDetails(renamedFile
);
1676 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1677 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1678 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1679 int position
= ((PreviewMediaFragment
)details
).getPosition();
1680 startMediaPreview(renamedFile
, position
, true
);
1682 getFileOperationsHelper().openFile(renamedFile
);
1687 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1688 refreshListOfFilesFragment();
1692 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1696 if (result
.isSslRecoverableException()) {
1697 mLastSslUntrustedServerResult
= result
;
1698 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1703 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1704 dismissLoadingDialog();
1705 OCFile syncedFile
= operation
.getLocalFile();
1706 if (!result
.isSuccess()) {
1707 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1708 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1709 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1710 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1716 if (operation
.transferWasRequested()) {
1717 onTransferStateChanged(syncedFile
, true
, true
);
1720 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1728 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1730 * @param operation Creation operation performed.
1731 * @param result Result of the creation.
1733 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1734 if (result
.isSuccess()) {
1735 dismissLoadingDialog();
1736 refreshListOfFilesFragment();
1738 dismissLoadingDialog();
1740 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1741 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1745 } catch (NotFoundException e
) {
1746 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1756 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1757 refreshListOfFilesFragment();
1758 FileFragment details
= getSecondFragment();
1759 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1760 if (downloading
|| uploading
) {
1761 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1763 if (!file
.fileExists()) {
1764 cleanSecondFragment();
1766 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1774 private void requestForDownload() {
1775 Account account
= getAccount();
1776 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1777 Intent i
= new Intent(this, FileDownloader
.class);
1778 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1779 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1785 private OCFile
getCurrentDir() {
1786 OCFile file
= getFile();
1788 if (file
.isFolder()) {
1790 } else if (getStorageManager() != null
) {
1791 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1792 return getStorageManager().getFileByPath(parentPath
);
1798 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1799 long currentSyncTime
= System
.currentTimeMillis();
1801 mSyncInProgress
= true
;
1803 // perform folder synchronization
1804 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1807 getFileOperationsHelper().isSharedSupported(),
1809 getStorageManager(),
1811 getApplicationContext()
1813 synchFolderOp
.execute(getAccount(), this, null
, null
);
1815 setSupportProgressBarIndeterminateVisibility(true
);
1817 setBackgroundText();
1821 * Show untrusted cert dialog
1823 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1824 // Show a dialog with the certificate info
1825 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1826 FragmentManager fm
= getSupportFragmentManager();
1827 FragmentTransaction ft
= fm
.beginTransaction();
1828 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1831 private void requestForDownload(OCFile file
) {
1832 Account account
= getAccount();
1833 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1834 Intent i
= new Intent(this, FileDownloader
.class);
1835 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1836 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1841 private void sendDownloadedFile(){
1842 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1843 mWaitingToSend
= null
;
1848 * Requests the download of the received {@link OCFile} , updates the UI
1849 * to monitor the download progress and prepares the activity to send the file
1850 * when the download finishes.
1852 * @param file {@link OCFile} to download and preview.
1854 public void startDownloadForSending(OCFile file
) {
1855 mWaitingToSend
= file
;
1856 requestForDownload(mWaitingToSend
);
1857 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1858 updateFragmentsVisibility(hasSecondFragment
);
1862 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1864 * @param file Image {@link OCFile} to show.
1866 public void startImagePreview(OCFile file
) {
1867 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1868 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1869 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1870 startActivity(showDetailsIntent
);
1875 * Stars the preview of an already down media {@link OCFile}.
1877 * @param file Media {@link OCFile} to preview.
1878 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1879 * @param autoplay When 'true', the playback will start without user interactions.
1881 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1882 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1883 setSecondFragment(mediaFragment
);
1884 updateFragmentsVisibility(true
);
1885 updateNavigationElementsInActionBar(file
);
1890 * Requests the download of the received {@link OCFile} , updates the UI
1891 * to monitor the download progress and prepares the activity to preview
1892 * or open the file when the download finishes.
1894 * @param file {@link OCFile} to download and preview.
1896 public void startDownloadForPreview(OCFile file
) {
1897 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1898 setSecondFragment(detailFragment
);
1899 mWaitingToPreview
= file
;
1900 requestForDownload();
1901 updateFragmentsVisibility(true
);
1902 updateNavigationElementsInActionBar(file
);
1907 public void cancelTransference(OCFile file
) {
1908 getFileOperationsHelper().cancelTransference(file
);
1909 if (mWaitingToPreview
!= null
&&
1910 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1911 mWaitingToPreview
= null
;
1913 if (mWaitingToSend
!= null
&&
1914 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1915 mWaitingToSend
= null
;
1917 onTransferStateChanged(file
, false
, false
);
1921 public void onRefresh(boolean ignoreETag
) {
1922 refreshList(ignoreETag
);
1926 public void onRefresh() {
1930 private void refreshList(boolean ignoreETag
) {
1931 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1932 if (listOfFiles
!= null
) {
1933 OCFile folder
= listOfFiles
.getCurrentFile();
1934 if (folder
!= null
) {
1935 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1936 listDirectory(mFile);*/
1937 startSyncFolderOperation(folder
, ignoreETag
);
1942 private void sortByDate(boolean ascending
){
1943 getListOfFilesFragment().sortByDate(ascending
);
1946 private void sortBySize(boolean ascending
){
1947 getListOfFilesFragment().sortBySize(ascending
);
1950 private void sortByName(boolean ascending
){
1951 getListOfFilesFragment().sortByName(ascending
);