1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.io
.IOException
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.accounts
.AuthenticatorException
;
27 import android
.accounts
.OperationCanceledException
;
28 import android
.annotation
.SuppressLint
;
29 import android
.annotation
.TargetApi
;
30 import android
.app
.AlertDialog
;
31 import android
.app
.Dialog
;
32 import android
.app
.ProgressDialog
;
33 import android
.content
.BroadcastReceiver
;
34 import android
.content
.ComponentName
;
35 import android
.content
.ContentResolver
;
36 import android
.content
.ContentUris
;
37 import android
.content
.Context
;
38 import android
.content
.DialogInterface
;
39 import android
.content
.Intent
;
40 import android
.content
.IntentFilter
;
41 import android
.content
.ServiceConnection
;
42 import android
.content
.SharedPreferences
;
43 import android
.content
.SyncRequest
;
44 import android
.content
.res
.Resources
.NotFoundException
;
45 import android
.database
.Cursor
;
46 import android
.net
.Uri
;
47 import android
.os
.Build
;
48 import android
.os
.Bundle
;
49 import android
.os
.Environment
;
50 import android
.os
.IBinder
;
51 import android
.preference
.PreferenceManager
;
52 import android
.provider
.DocumentsContract
;
53 import android
.provider
.MediaStore
;
54 import android
.provider
.OpenableColumns
;
55 import android
.support
.v4
.app
.Fragment
;
56 import android
.support
.v4
.app
.FragmentManager
;
57 import android
.support
.v4
.app
.FragmentTransaction
;
58 import android
.util
.Log
;
59 import android
.view
.View
;
60 import android
.view
.ViewGroup
;
61 import android
.widget
.ArrayAdapter
;
62 import android
.widget
.TextView
;
63 import android
.widget
.Toast
;
65 import com
.actionbarsherlock
.app
.ActionBar
;
66 import com
.actionbarsherlock
.app
.ActionBar
.OnNavigationListener
;
67 import com
.actionbarsherlock
.view
.Menu
;
68 import com
.actionbarsherlock
.view
.MenuInflater
;
69 import com
.actionbarsherlock
.view
.MenuItem
;
70 import com
.actionbarsherlock
.view
.Window
;
71 import com
.owncloud
.android
.BuildConfig
;
72 import com
.owncloud
.android
.MainApp
;
73 import com
.owncloud
.android
.R
;
74 import com
.owncloud
.android
.datamodel
.OCFile
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
79 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
80 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
81 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
82 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
83 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
84 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
85 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
86 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
87 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
88 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
89 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
90 import com
.owncloud
.android
.operations
.CreateShareOperation
;
91 import com
.owncloud
.android
.operations
.MoveFileOperation
;
92 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
93 import com
.owncloud
.android
.operations
.RenameFileOperation
;
94 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
95 import com
.owncloud
.android
.operations
.SynchronizeFolderOperation
;
96 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
97 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
98 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
99 import com
.owncloud
.android
.ui
.adapter
.FileListListAdapter
;
100 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
101 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
102 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
103 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
104 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
105 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
106 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
107 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
108 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
109 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
110 import com
.owncloud
.android
.utils
.DisplayUtils
;
111 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
112 import com
.owncloud
.android
.utils
.FileStorageUtils
;
113 import com
.owncloud
.android
.utils
.UriUtils
;
117 * Displays, what files the user has available in his ownCloud.
119 * @author Bartek Przybylski
120 * @author David A. Velasco
123 public class FileDisplayActivity
extends HookActivity
implements
124 FileFragment
.ContainerActivity
, OnNavigationListener
,
125 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
127 private ArrayAdapter
<String
> mDirectories
;
129 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
130 private UploadFinishReceiver mUploadFinishReceiver
;
131 private DownloadFinishReceiver mDownloadFinishReceiver
;
132 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
134 private boolean mDualPane
;
135 private View mLeftFragmentContainer
;
136 private View mRightFragmentContainer
;
138 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
139 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
140 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
142 public static final int DIALOG_SHORT_WAIT
= 0;
143 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE
= 1;
144 private static final int DIALOG_CERT_NOT_SAVED
= 2;
146 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
148 private static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
149 private static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
150 public static final int ACTION_MOVE_FILES
= 3;
152 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
154 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
155 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
157 private OCFile mWaitingToPreview
;
159 private boolean mSyncInProgress
= false
;
161 private String DIALOG_UNTRUSTED_CERT
;
163 private OCFile mWaitingToSend
;
166 protected void onCreate(Bundle savedInstanceState
) {
167 Log_OC
.d(TAG
, "onCreate() start");
168 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
170 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
172 // PIN CODE request ; best location is to decide, let's try this first
173 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
175 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
179 /// grant that FileObserverService is watching favourite files
180 if (savedInstanceState
== null
) {
181 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
182 startService(initObserversIntent
);
185 /// Load of saved instance state
186 if(savedInstanceState
!= null
) {
187 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
188 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
189 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
192 mWaitingToPreview
= null
;
193 mSyncInProgress
= false
;
194 mWaitingToSend
= null
;
199 // Inflate and set the layout view
200 setContentView(R
.layout
.files
);
201 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
202 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
203 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
204 if (savedInstanceState
== null
) {
205 createMinFragments();
209 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
210 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
211 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
215 Log_OC
.d(TAG
, "onCreate() end");
219 protected void onStart() {
221 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
225 protected void onDestroy() {
230 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
233 protected void onAccountSet(boolean stateWasRecovered
) {
234 super.onAccountSet(stateWasRecovered
);
235 if (getAccount() != null
) {
236 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
237 OCFile file
= getFile();
238 // get parent from path
239 String parentPath
= "";
241 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
242 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
243 // get parent from path
244 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
245 if (getStorageManager().getFileByPath(parentPath
) == null
)
246 file
= null
; // not able to know the directory where the file is uploading
248 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
252 // fall back to root folder
253 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
256 setNavigationListWithFolder(file
);
258 if (!stateWasRecovered
) {
259 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
260 initFragmentsWithFile();
261 if (file
.isFolder()) {
262 startSyncFolderOperation(file
, false
);
266 updateFragmentsVisibility(!file
.isFolder());
267 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
273 private void setNavigationListWithFolder(OCFile file
) {
274 mDirectories
.clear();
275 OCFile fileIt
= file
;
277 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
278 if (fileIt
.isFolder()) {
279 mDirectories
.add(fileIt
.getFileName());
281 // get parent from path
282 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
283 fileIt
= getStorageManager().getFileByPath(parentPath
);
285 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
303 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
307 OCFile file
= getFile();
308 Fragment secondFragment
= chooseInitialSecondFragment(file
);
309 if (secondFragment
!= null
) {
310 setSecondFragment(secondFragment
);
311 updateFragmentsVisibility(true
);
312 updateNavigationElementsInActionBar(file
);
315 cleanSecondFragment();
319 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
320 if (getAccount() == null
) {
321 Log_OC
.wtf(TAG
, "\t account is NULL");
323 if (getFile() == null
) {
324 Log_OC
.wtf(TAG
, "\t file is NULL");
329 private Fragment
chooseInitialSecondFragment(OCFile file
) {
330 Fragment secondFragment
= null
;
331 if (file
!= null
&& !file
.isFolder()) {
332 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
333 && file
.getLastSyncDateForProperties() > 0 // temporal fix
335 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
336 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
337 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
340 secondFragment
= new FileDetailFragment(file
, getAccount());
343 return secondFragment
;
348 * Replaces the second fragment managed by the activity with the received as
351 * Assumes never will be more than two fragments managed at the same time.
353 * @param fragment New second Fragment to set.
355 private void setSecondFragment(Fragment fragment
) {
356 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
357 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
358 transaction
.commit();
362 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 } else if (existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
373 mLeftFragmentContainer
.setVisibility(View
.GONE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
384 mRightFragmentContainer
.setVisibility(View
.GONE
);
390 private OCFileListFragment
getListOfFilesFragment() {
391 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
392 if (listOfFiles
!= null
) {
393 return (OCFileListFragment
)listOfFiles
;
395 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
399 public FileFragment
getSecondFragment() {
400 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
401 if (second
!= null
) {
402 return (FileFragment
)second
;
407 protected void cleanSecondFragment() {
408 Fragment second
= getSecondFragment();
409 if (second
!= null
) {
410 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
414 updateFragmentsVisibility(false
);
415 updateNavigationElementsInActionBar(null
);
418 protected void refreshListOfFilesFragment() {
419 OCFileListFragment fileListFragment
= getListOfFilesFragment();
420 if (fileListFragment
!= null
) {
421 fileListFragment
.listDirectory();
425 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
426 FileFragment secondFragment
= getSecondFragment();
427 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
428 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
429 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
430 OCFile fileInFragment
= detailsFragment
.getFile();
431 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
432 // the user browsed to other file ; forget the automatic preview
433 mWaitingToPreview
= null
;
435 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
436 // grant that the right panel updates the progress bar
437 detailsFragment
.listenForTransferProgress();
438 detailsFragment
.updateFileDetails(true
, false
);
440 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
441 // update the right panel
442 boolean detailsFragmentChanged
= false
;
445 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
446 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
447 startMediaPreview(mWaitingToPreview
, 0, true
);
448 detailsFragmentChanged
= true
;
450 getFileOperationsHelper().openFile(mWaitingToPreview
);
453 mWaitingToPreview
= null
;
455 if (!detailsFragmentChanged
) {
456 detailsFragment
.updateFileDetails(false
, (success
));
463 public boolean onPrepareOptionsMenu(Menu menu
) {
464 if (BuildConfig
.DEBUG
) {
465 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
467 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
469 return super.onPrepareOptionsMenu(menu
);
473 public boolean onCreateOptionsMenu(Menu menu
) {
474 MenuInflater inflater
= getSherlock().getMenuInflater();
475 inflater
.inflate(R
.menu
.main_menu
, menu
);
480 public boolean onOptionsItemSelected(MenuItem item
) {
481 boolean retval
= true
;
482 switch (item
.getItemId()) {
483 case R
.id
.action_create_dir
: {
484 CreateFolderDialogFragment dialog
=
485 CreateFolderDialogFragment
.newInstance(getCurrentDir());
486 dialog
.show(getSupportFragmentManager(), "createdirdialog");
489 case R
.id
.action_sync_account
: {
490 startSynchronization();
493 case R
.id
.action_upload
: {
494 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
497 case R
.id
.action_settings
: {
498 Intent settingsIntent
= new Intent(this, Preferences
.class);
499 startActivity(settingsIntent
);
502 case R
.id
.action_logger
: {
503 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
504 startActivity(loggerIntent
);
507 case android
.R
.id
.home
: {
508 FileFragment second
= getSecondFragment();
509 OCFile currentDir
= getCurrentDir();
510 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
511 (second
!= null
&& second
.getFile() != null
)) {
517 case R
.id
.action_sort
: {
518 SharedPreferences appPreferences
= PreferenceManager
519 .getDefaultSharedPreferences(this);
521 // Read sorting order, default to sort by name ascending
522 Integer sortOrder
= appPreferences
523 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
525 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
526 builder
.setTitle(R
.string
.actionbar_sort_title
)
527 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
528 public void onClick(DialogInterface dialog
, int which
) {
538 // TODO re-enable when server-side folder size calculation is available
540 // sortBySize(false);
548 builder
.create().show();
552 retval
= super.onOptionsItemSelected(item
);
557 private void startSynchronization() {
558 Log_OC
.e(TAG
, "Got to start sync");
559 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
560 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
561 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
562 Bundle bundle
= new Bundle();
563 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
564 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
565 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
566 ContentResolver
.requestSync(
568 MainApp
.getAuthority(), bundle
);
570 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
571 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
572 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
573 builder
.setExpedited(true
);
574 builder
.setManual(true
);
577 // Fix bug in Android Lollipop when you click on refresh the whole account
578 Bundle extras
= new Bundle();
579 builder
.setExtras(extras
);
581 SyncRequest request
= builder
.build();
582 ContentResolver
.requestSync(request
);
588 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
589 if (itemPosition
!= 0) {
590 String targetPath
= "";
591 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
592 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
594 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
595 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
596 if (targetFolder
!= null
) {
597 browseTo(targetFolder
);
600 // the next operation triggers a new call to this method, but it's necessary to
601 // ensure that the name exposed in the action bar is the current directory when the
602 // user selected it in the navigation list
603 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
604 getSupportActionBar().setSelectedNavigationItem(0);
610 * Called, when the user selected something for uploading
613 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
614 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
615 super.onActivityResult(requestCode
, resultCode
, data
);
617 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
618 //getClipData is only supported on api level 16+, Jelly Bean
619 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
620 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
621 Intent intent
= new Intent();
622 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
623 requestSimpleUpload(intent
, resultCode
);
626 requestSimpleUpload(data
, resultCode
);
628 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
629 requestMultipleUpload(data
, resultCode
);
631 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
633 final Intent fData
= data
;
634 final int fResultCode
= resultCode
;
635 getHandler().postDelayed(
639 requestMoveOperation(fData
, fResultCode
);
642 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
647 private void requestMultipleUpload(Intent data
, int resultCode
) {
648 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
649 if (filePaths
!= null
) {
650 String
[] remotePaths
= new String
[filePaths
.length
];
651 String remotePathBase
= "";
652 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
653 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
655 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
656 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
657 for (int j
= 0; j
< remotePaths
.length
; j
++) {
658 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
661 Intent i
= new Intent(this, FileUploader
.class);
662 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
663 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
664 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
665 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
666 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
667 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
671 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
672 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
679 private void requestSimpleUpload(Intent data
, int resultCode
) {
680 String filepath
= null
;
681 String mimeType
= null
;
683 Uri selectedImageUri
= data
.getData();
686 mimeType
= getContentResolver().getType(selectedImageUri
);
688 String filemanagerstring
= selectedImageUri
.getPath();
689 String selectedImagePath
= getPath(selectedImageUri
);
691 if (selectedImagePath
!= null
)
692 filepath
= selectedImagePath
;
694 filepath
= filemanagerstring
;
696 } catch (Exception e
) {
697 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
701 if (filepath
== null
) {
702 Log_OC
.e(TAG
, "Couldnt resolve path to file");
703 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
709 Intent i
= new Intent(this, FileUploader
.class);
710 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
712 String remotepath
= new String();
713 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
714 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
716 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
717 remotepath
+= OCFile
.PATH_SEPARATOR
;
719 if (filepath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
721 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
722 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
725 if (cursor
!= null
&& cursor
.moveToFirst()) {
726 String displayName
= cursor
.getString(
727 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
728 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
730 displayName
.replace(File
.separatorChar
, '_');
731 displayName
.replace(File
.pathSeparatorChar
, '_');
732 remotepath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filepath
);
740 remotepath
+= new File(filepath
).getName();
743 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
744 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
745 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
746 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
747 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
748 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
753 * Request the operation for moving the file/folder from one path to another
755 * @param data Intent received
756 * @param resultCode Result code received
758 private void requestMoveOperation(Intent data
, int resultCode
) {
759 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
760 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
761 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
765 public void onBackPressed() {
766 OCFileListFragment listOfFiles
= getListOfFilesFragment();
767 if (mDualPane
|| getSecondFragment() == null
) {
768 if (listOfFiles
!= null
) { // should never be null, indeed
769 if (mDirectories
.getCount() <= 1) {
773 int levelsUp
= listOfFiles
.onBrowseUp();
774 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
779 if (listOfFiles
!= null
) { // should never be null, indeed
780 setFile(listOfFiles
.getCurrentFile());
782 cleanSecondFragment();
787 protected void onSaveInstanceState(Bundle outState
) {
788 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
789 Log_OC
.e(TAG
, "onSaveInstanceState() start");
790 super.onSaveInstanceState(outState
);
791 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
792 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
793 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
794 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
796 Log_OC
.d(TAG
, "onSaveInstanceState() end");
802 protected void onResume() {
804 Log_OC
.e(TAG
, "onResume() start");
806 // refresh list of files
807 refreshListOfFilesFragment();
809 // Listen for sync messages
810 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
811 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
812 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
813 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
814 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
815 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
816 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
817 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
819 // Listen for upload messages
820 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
821 mUploadFinishReceiver
= new UploadFinishReceiver();
822 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
824 // Listen for download messages
825 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
826 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
827 mDownloadFinishReceiver
= new DownloadFinishReceiver();
828 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
830 Log_OC
.d(TAG
, "onResume() end");
835 protected void onPause() {
836 Log_OC
.e(TAG
, "onPause() start");
837 if (mSyncBroadcastReceiver
!= null
) {
838 unregisterReceiver(mSyncBroadcastReceiver
);
839 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
840 mSyncBroadcastReceiver
= null
;
842 if (mUploadFinishReceiver
!= null
) {
843 unregisterReceiver(mUploadFinishReceiver
);
844 mUploadFinishReceiver
= null
;
846 if (mDownloadFinishReceiver
!= null
) {
847 unregisterReceiver(mDownloadFinishReceiver
);
848 mDownloadFinishReceiver
= null
;
852 Log_OC
.d(TAG
, "onPause() end");
858 protected Dialog
onCreateDialog(int id
) {
859 Dialog dialog
= null
;
860 AlertDialog
.Builder builder
;
862 case DIALOG_SHORT_WAIT
: {
863 ProgressDialog working_dialog
= new ProgressDialog(this);
864 working_dialog
.setMessage(getResources().getString(
865 R
.string
.wait_a_moment
));
866 working_dialog
.setIndeterminate(true
);
867 working_dialog
.setCancelable(false
);
868 dialog
= working_dialog
;
871 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
874 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
875 getString(R
.string
.actionbar_upload_from_apps
) };
877 builder
= new AlertDialog
.Builder(this);
878 builder
.setTitle(R
.string
.actionbar_upload
);
879 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
880 public void onClick(DialogInterface dialog
, int item
) {
883 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
884 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
885 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
887 // TODO create and handle new fragment
888 // LocalFileListFragment
890 } else if (item
== 1) {
891 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
892 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
893 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
894 if(Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
895 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
897 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
898 ACTION_SELECT_CONTENT_FROM_APPS
);
902 dialog
= builder
.create();
905 case DIALOG_CERT_NOT_SAVED
: {
906 builder
= new AlertDialog
.Builder(this);
907 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
908 builder
.setCancelable(false
);
909 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
911 public void onClick(DialogInterface dialog
, int which
) {
915 dialog
= builder
.create();
926 * Translates a content URI of an content to a physical path on the disk
928 * @param uri The URI to resolve
929 * @return The path to the content or null if it could not be found
931 public String
getPath(Uri uri
) {
932 final boolean isKitKatOrLater
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
935 if (isKitKatOrLater
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
936 // ExternalStorageProvider
937 if (UriUtils
.isExternalStorageDocument(uri
)) {
938 final String docId
= DocumentsContract
.getDocumentId(uri
);
939 final String
[] split
= docId
.split(":");
940 final String type
= split
[0];
942 if ("primary".equalsIgnoreCase(type
)) {
943 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
947 else if (UriUtils
.isDownloadsDocument(uri
)) {
949 final String id
= DocumentsContract
.getDocumentId(uri
);
950 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
953 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, null
, null
);
956 else if (UriUtils
.isMediaDocument(uri
)) {
957 final String docId
= DocumentsContract
.getDocumentId(uri
);
958 final String
[] split
= docId
.split(":");
959 final String type
= split
[0];
961 Uri contentUri
= null
;
962 if ("image".equals(type
)) {
963 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
964 } else if ("video".equals(type
)) {
965 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
966 } else if ("audio".equals(type
)) {
967 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
970 final String selection
= "_id=?";
971 final String
[] selectionArgs
= new String
[] { split
[1] };
973 return UriUtils
.getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
975 // Documents providers returned as content://...
976 else if (UriUtils
.isContentDocument(uri
)) {
977 return uri
.toString();
980 // MediaStore (and general)
981 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
983 // Return the remote address
984 if (UriUtils
.isGooglePhotosUri(uri
))
985 return uri
.getLastPathSegment();
987 return UriUtils
.getDataColumn(getApplicationContext(), uri
, null
, null
);
990 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
991 return uri
.getPath();
997 * Pushes a directory to the drop down list
998 * @param directory to push
999 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1001 public void pushDirname(OCFile directory
) {
1002 if(!directory
.isFolder()){
1003 throw new IllegalArgumentException("Only directories may be pushed!");
1005 mDirectories
.insert(directory
.getFileName(), 0);
1010 * Pops a directory name from the drop down list
1011 * @return True, unless the stack is empty
1013 public boolean popDirname() {
1014 mDirectories
.remove(mDirectories
.getItem(0));
1015 return !mDirectories
.isEmpty();
1018 // Custom array adapter to override text colors
1019 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1021 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1025 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1026 View v
= super.getView(position
, convertView
, parent
);
1028 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1029 android
.R
.color
.white
));
1031 fixRoot((TextView
) v
);
1035 public View
getDropDownView(int position
, View convertView
,
1037 View v
= super.getDropDownView(position
, convertView
, parent
);
1039 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1040 android
.R
.color
.white
));
1042 fixRoot((TextView
) v
);
1046 private void fixRoot(TextView v
) {
1047 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1048 v
.setText(R
.string
.default_display_name_for_root_folder
);
1054 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1057 * {@link BroadcastReceiver} to enable syncing feedback in UI
1060 public void onReceive(Context context
, Intent intent
) {
1062 String event
= intent
.getAction();
1063 Log_OC
.d(TAG
, "Received broadcast " + event
);
1064 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1065 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1066 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1067 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1071 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1072 mSyncInProgress
= true
;
1075 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1076 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1078 if (currentDir
== null
) {
1079 // current folder was removed from the server
1080 Toast
.makeText( FileDisplayActivity
.this,
1081 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1087 if (currentFile
== null
&& !getFile().isFolder()) {
1088 // currently selected file was removed in the server, and now we know it
1089 cleanSecondFragment();
1090 currentFile
= currentDir
;
1093 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1094 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1095 if (fileListFragment
!= null
) {
1096 fileListFragment
.listDirectory(currentDir
);
1099 setFile(currentFile
);
1102 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1104 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1106 /// TODO refactor and make common
1107 synchResult
!= null
&& !synchResult
.isSuccess() &&
1108 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1109 synchResult
.isIdPRedirection() ||
1110 (synchResult
.isException() && synchResult
.getException()
1111 instanceof AuthenticatorException
))) {
1113 OwnCloudClient client
= null
;
1115 OwnCloudAccount ocAccount
=
1116 new OwnCloudAccount(getAccount(), context
);
1117 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1118 removeClientFor(ocAccount
));
1119 // TODO get rid of these exceptions
1120 } catch (AccountNotFoundException e
) {
1121 e
.printStackTrace();
1122 } catch (AuthenticatorException e
) {
1123 e
.printStackTrace();
1124 } catch (OperationCanceledException e
) {
1125 e
.printStackTrace();
1126 } catch (IOException e
) {
1127 e
.printStackTrace();
1130 if (client
!= null
) {
1131 OwnCloudCredentials cred
= client
.getCredentials();
1133 AccountManager am
= AccountManager
.get(context
);
1134 if (cred
.authTokenExpires()) {
1135 am
.invalidateAuthToken(
1140 am
.clearPassword(getAccount());
1145 requestCredentialsUpdate();
1149 removeStickyBroadcast(intent
);
1150 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1151 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1153 setBackgroundText();
1157 if (synchResult
!= null
) {
1158 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1159 mLastSslUntrustedServerResult
= synchResult
;
1162 } catch (RuntimeException e
) {
1163 // avoid app crashes after changing the serial id of RemoteOperationResult
1164 // in owncloud library with broadcast notifications pending to process
1165 removeStickyBroadcast(intent
);
1171 * Show a text message on screen view for notifying user if content is
1172 * loading or folder is empty
1174 private void setBackgroundText() {
1175 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1176 if (ocFileListFragment
!= null
) {
1177 int message
= R
.string
.file_list_loading
;
1178 if (!mSyncInProgress
) {
1179 // In case file list is empty
1180 message
= R
.string
.file_list_empty
;
1182 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1184 Log_OC
.e(TAG
, "OCFileListFragment is null");
1189 * Once the file upload has finished -> update view
1191 private class UploadFinishReceiver
extends BroadcastReceiver
{
1193 * Once the file upload has finished -> update view
1194 * @author David A. Velasco
1195 * {@link BroadcastReceiver} to enable upload feedback in UI
1198 public void onReceive(Context context
, Intent intent
) {
1200 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1201 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1202 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1203 OCFile currentDir
= getCurrentDir();
1204 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1205 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1207 if (sameAccount
&& isDescendant
) {
1208 refreshListOfFilesFragment();
1211 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1212 boolean renamedInUpload
= getFile().getRemotePath().
1213 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1214 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1216 FileFragment details
= getSecondFragment();
1217 boolean detailFragmentIsShown
= (details
!= null
&&
1218 details
instanceof FileDetailFragment
);
1220 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1221 if (uploadWasFine
) {
1222 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1224 if (renamedInUpload
) {
1225 String newName
= (new File(uploadedRemotePath
)).getName();
1226 Toast msg
= Toast
.makeText(
1229 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1234 if (uploadWasFine
|| getFile().fileExists()) {
1235 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1237 cleanSecondFragment();
1240 // Force the preview if the file is an image
1241 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1242 startImagePreview(getFile());
1243 } // TODO what about other kind of previews?
1247 if (intent
!= null
) {
1248 removeStickyBroadcast(intent
);
1258 * Class waiting for broadcast events from the {@link FielDownloader} service.
1260 * Updates the UI when a download is started or finished, provided that it is relevant for the
1263 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1265 public void onReceive(Context context
, Intent intent
) {
1267 boolean sameAccount
= isSameAccount(context
, intent
);
1268 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1269 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1271 if (sameAccount
&& isDescendant
) {
1272 refreshListOfFilesFragment();
1273 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1276 if (mWaitingToSend
!= null
) {
1277 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1278 if (mWaitingToSend
.isDown()) {
1279 sendDownloadedFile();
1284 if (intent
!= null
) {
1285 removeStickyBroadcast(intent
);
1290 private boolean isDescendant(String downloadedRemotePath
) {
1291 OCFile currentDir
= getCurrentDir();
1292 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1295 private boolean isSameAccount(Context context
, Intent intent
) {
1296 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1297 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1302 public void browseToRoot() {
1303 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1304 if (listOfFiles
!= null
) { // should never be null, indeed
1305 while (mDirectories
.getCount() > 1) {
1308 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1309 listOfFiles
.listDirectory(root
);
1310 setFile(listOfFiles
.getCurrentFile());
1311 startSyncFolderOperation(root
, false
);
1313 cleanSecondFragment();
1317 public void browseTo(OCFile folder
) {
1318 if (folder
== null
|| !folder
.isFolder()) {
1319 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1321 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1322 if (listOfFiles
!= null
) {
1323 setNavigationListWithFolder(folder
);
1324 listOfFiles
.listDirectory(folder
);
1325 setFile(listOfFiles
.getCurrentFile());
1326 startSyncFolderOperation(folder
, false
);
1328 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1330 cleanSecondFragment();
1337 * Updates action bar and second fragment, if in dual pane mode.
1340 public void onBrowsedDownTo(OCFile directory
) {
1341 pushDirname(directory
);
1342 cleanSecondFragment();
1345 startSyncFolderOperation(directory
, false
);
1350 * Shows the information of the {@link OCFile} received as a
1351 * parameter in the second fragment.
1353 * @param file {@link OCFile} whose details will be shown
1356 public void showDetails(OCFile file
) {
1357 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1358 setSecondFragment(detailFragment
);
1359 updateFragmentsVisibility(true
);
1360 updateNavigationElementsInActionBar(file
);
1368 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1369 ActionBar actionBar
= getSupportActionBar();
1370 if (chosenFile
== null
|| mDualPane
) {
1371 // only list of files - set for browsing through folders
1372 OCFile currentDir
= getCurrentDir();
1373 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1374 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1375 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1377 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1379 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1380 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1383 actionBar
.setDisplayHomeAsUpEnabled(true
);
1384 actionBar
.setDisplayShowTitleEnabled(true
);
1385 actionBar
.setTitle(chosenFile
.getFileName());
1386 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1392 protected ServiceConnection
newTransferenceServiceConnection() {
1393 return new ListServiceConnection();
1396 /** Defines callbacks for service binding, passed to bindService() */
1397 private class ListServiceConnection
implements ServiceConnection
{
1400 public void onServiceConnected(ComponentName component
, IBinder service
) {
1401 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1402 Log_OC
.d(TAG
, "Download service connected");
1403 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1404 if (mWaitingToPreview
!= null
)
1405 if (getStorageManager() != null
) {
1406 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1407 if (!mWaitingToPreview
.isDown()) {
1408 requestForDownload();
1412 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1413 Log_OC
.d(TAG
, "Upload service connected");
1414 mUploaderBinder
= (FileUploaderBinder
) service
;
1418 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1419 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1420 if (listOfFiles
!= null
) {
1421 listOfFiles
.listDirectory();
1423 FileFragment secondFragment
= getSecondFragment();
1424 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1425 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1426 detailFragment
.listenForTransferProgress();
1427 detailFragment
.updateFileDetails(false
, false
);
1432 public void onServiceDisconnected(ComponentName component
) {
1433 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1434 Log_OC
.d(TAG
, "Download service disconnected");
1435 mDownloaderBinder
= null
;
1436 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1437 Log_OC
.d(TAG
, "Upload service disconnected");
1438 mUploaderBinder
= null
;
1446 * Launch an intent to request the PIN code to the user before letting him use the app
1448 private void requestPinCode() {
1449 boolean pinStart
= false
;
1450 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1451 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1453 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1454 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1461 public void onSavedCertificate() {
1462 startSyncFolderOperation(getCurrentDir(), false
);
1467 public void onFailedSavingCertificate() {
1468 showDialog(DIALOG_CERT_NOT_SAVED
);
1472 public void onCancelCertificate() {
1477 * Updates the view associated to the activity after the finish of some operation over files
1478 * in the current account.
1480 * @param operation Removal operation performed.
1481 * @param result Result of the removal.
1484 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1485 super.onRemoteOperationFinish(operation
, result
);
1487 if (operation
instanceof RemoveFileOperation
) {
1488 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1490 } else if (operation
instanceof RenameFileOperation
) {
1491 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1493 } else if (operation
instanceof SynchronizeFileOperation
) {
1494 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1496 } else if (operation
instanceof CreateFolderOperation
) {
1497 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1499 } else if (operation
instanceof CreateShareOperation
) {
1500 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1502 } else if (operation
instanceof UnshareLinkOperation
) {
1503 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1505 } else if (operation
instanceof MoveFileOperation
) {
1506 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1512 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1513 if (result
.isSuccess()) {
1514 refreshShowDetails();
1515 refreshListOfFilesFragment();
1520 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1521 if (result
.isSuccess()) {
1522 refreshShowDetails();
1523 refreshListOfFilesFragment();
1525 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1526 cleanSecondFragment();
1527 refreshListOfFilesFragment();
1531 private void refreshShowDetails() {
1532 FileFragment details
= getSecondFragment();
1533 if (details
!= null
) {
1534 OCFile file
= details
.getFile();
1536 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1537 if (details
instanceof PreviewMediaFragment
) {
1538 // Refresh OCFile of the fragment
1539 ((PreviewMediaFragment
) details
).updateFile(file
);
1544 invalidateOptionsMenu();
1549 * Updates the view associated to the activity after the finish of an operation trying to remove a
1552 * @param operation Removal operation performed.
1553 * @param result Result of the removal.
1555 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1556 dismissLoadingDialog();
1558 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1562 if (result
.isSuccess()) {
1563 OCFile removedFile
= operation
.getFile();
1564 FileFragment second
= getSecondFragment();
1565 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1566 if (second
instanceof PreviewMediaFragment
) {
1567 ((PreviewMediaFragment
)second
).stopPreview(true
);
1569 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1570 cleanSecondFragment();
1572 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1573 refreshListOfFilesFragment();
1575 invalidateOptionsMenu();
1577 if (result
.isSslRecoverableException()) {
1578 mLastSslUntrustedServerResult
= result
;
1579 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1586 * Updates the view associated to the activity after the finish of an operation trying to move a
1589 * @param operation Move operation performed.
1590 * @param result Result of the move operation.
1592 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1593 if (result
.isSuccess()) {
1594 dismissLoadingDialog();
1595 refreshListOfFilesFragment();
1597 dismissLoadingDialog();
1599 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1600 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1604 } catch (NotFoundException e
) {
1605 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1612 * Updates the view associated to the activity after the finish of an operation trying to rename a
1615 * @param operation Renaming operation performed.
1616 * @param result Result of the renaming.
1618 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1619 dismissLoadingDialog();
1620 OCFile renamedFile
= operation
.getFile();
1621 if (result
.isSuccess()) {
1622 FileFragment details
= getSecondFragment();
1623 if (details
!= null
) {
1624 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1625 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1626 showDetails(renamedFile
);
1628 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1629 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1630 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1631 int position
= ((PreviewMediaFragment
)details
).getPosition();
1632 startMediaPreview(renamedFile
, position
, true
);
1634 getFileOperationsHelper().openFile(renamedFile
);
1639 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1640 refreshListOfFilesFragment();
1644 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1648 if (result
.isSslRecoverableException()) {
1649 mLastSslUntrustedServerResult
= result
;
1650 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1655 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1656 dismissLoadingDialog();
1657 OCFile syncedFile
= operation
.getLocalFile();
1658 if (!result
.isSuccess()) {
1659 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1660 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1661 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1662 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1668 if (operation
.transferWasRequested()) {
1669 onTransferStateChanged(syncedFile
, true
, true
);
1672 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1680 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1682 * @param operation Creation operation performed.
1683 * @param result Result of the creation.
1685 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1686 if (result
.isSuccess()) {
1687 dismissLoadingDialog();
1688 refreshListOfFilesFragment();
1690 dismissLoadingDialog();
1692 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1693 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1697 } catch (NotFoundException e
) {
1698 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1708 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1709 refreshListOfFilesFragment();
1710 FileFragment details
= getSecondFragment();
1711 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1712 if (downloading
|| uploading
) {
1713 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1715 if (!file
.fileExists()) {
1716 cleanSecondFragment();
1718 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1726 private void requestForDownload() {
1727 Account account
= getAccount();
1728 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1729 Intent i
= new Intent(this, FileDownloader
.class);
1730 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1731 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1737 private OCFile
getCurrentDir() {
1738 OCFile file
= getFile();
1740 if (file
.isFolder()) {
1742 } else if (getStorageManager() != null
) {
1743 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1744 return getStorageManager().getFileByPath(parentPath
);
1750 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1751 long currentSyncTime
= System
.currentTimeMillis();
1753 mSyncInProgress
= true
;
1755 // perform folder synchronization
1756 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1759 getFileOperationsHelper().isSharedSupported(),
1761 getStorageManager(),
1763 getApplicationContext()
1765 synchFolderOp
.execute(getAccount(), this, null
, null
);
1767 setSupportProgressBarIndeterminateVisibility(true
);
1769 setBackgroundText();
1773 * Show untrusted cert dialog
1775 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1776 // Show a dialog with the certificate info
1777 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1778 FragmentManager fm
= getSupportFragmentManager();
1779 FragmentTransaction ft
= fm
.beginTransaction();
1780 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1783 private void requestForDownload(OCFile file
) {
1784 Account account
= getAccount();
1785 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1786 Intent i
= new Intent(this, FileDownloader
.class);
1787 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1788 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1793 private void sendDownloadedFile(){
1794 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1795 mWaitingToSend
= null
;
1800 * Requests the download of the received {@link OCFile} , updates the UI
1801 * to monitor the download progress and prepares the activity to send the file
1802 * when the download finishes.
1804 * @param file {@link OCFile} to download and preview.
1806 public void startDownloadForSending(OCFile file
) {
1807 mWaitingToSend
= file
;
1808 requestForDownload(mWaitingToSend
);
1809 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1810 updateFragmentsVisibility(hasSecondFragment
);
1814 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1816 * @param file Image {@link OCFile} to show.
1818 public void startImagePreview(OCFile file
) {
1819 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1820 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1821 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1822 startActivity(showDetailsIntent
);
1827 * Stars the preview of an already down media {@link OCFile}.
1829 * @param file Media {@link OCFile} to preview.
1830 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1831 * @param autoplay When 'true', the playback will start without user interactions.
1833 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1834 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1835 setSecondFragment(mediaFragment
);
1836 updateFragmentsVisibility(true
);
1837 updateNavigationElementsInActionBar(file
);
1842 * Requests the download of the received {@link OCFile} , updates the UI
1843 * to monitor the download progress and prepares the activity to preview
1844 * or open the file when the download finishes.
1846 * @param file {@link OCFile} to download and preview.
1848 public void startDownloadForPreview(OCFile file
) {
1849 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1850 setSecondFragment(detailFragment
);
1851 mWaitingToPreview
= file
;
1852 requestForDownload();
1853 updateFragmentsVisibility(true
);
1854 updateNavigationElementsInActionBar(file
);
1859 public void cancelTransference(OCFile file
) {
1860 getFileOperationsHelper().cancelTransference(file
);
1861 if (mWaitingToPreview
!= null
&&
1862 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1863 mWaitingToPreview
= null
;
1865 if (mWaitingToSend
!= null
&&
1866 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1867 mWaitingToSend
= null
;
1869 onTransferStateChanged(file
, false
, false
);
1873 public void onRefresh(boolean ignoreETag
) {
1874 refreshList(ignoreETag
);
1878 public void onRefresh() {
1882 private void refreshList(boolean ignoreETag
) {
1883 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1884 if (listOfFiles
!= null
) {
1885 OCFile folder
= listOfFiles
.getCurrentFile();
1886 if (folder
!= null
) {
1887 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1888 listDirectory(mFile);*/
1889 startSyncFolderOperation(folder
, ignoreETag
);
1894 private void sortByDate(boolean ascending
){
1895 getListOfFilesFragment().sortByDate(ascending
);
1898 private void sortBySize(boolean ascending
){
1899 getListOfFilesFragment().sortBySize(ascending
);
1902 private void sortByName(boolean ascending
){
1903 getListOfFilesFragment().sortByName(ascending
);