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
;
161 private static final String URI_CONTENT_SCHEME
= "content://";
164 protected void onCreate(Bundle savedInstanceState
) {
165 Log_OC
.d(TAG
, "onCreate() start");
166 requestWindowFeature(Window
.FEATURE_INDETERMINATE_PROGRESS
);
168 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account is valid
170 // PIN CODE request ; best location is to decide, let's try this first
171 if (getIntent().getAction() != null
&& getIntent().getAction().equals(Intent
.ACTION_MAIN
) && savedInstanceState
== null
) {
173 } else if (getIntent().getAction() == null
&& savedInstanceState
== null
) {
177 /// grant that FileObserverService is watching favourite files
178 if (savedInstanceState
== null
) {
179 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
180 startService(initObserversIntent
);
183 /// Load of saved instance state
184 if(savedInstanceState
!= null
) {
185 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
186 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
187 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
);
190 mWaitingToPreview
= null
;
191 mSyncInProgress
= false
;
192 mWaitingToSend
= null
;
197 // Inflate and set the layout view
198 setContentView(R
.layout
.files
);
199 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
200 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
201 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
202 if (savedInstanceState
== null
) {
203 createMinFragments();
207 mDirectories
= new CustomArrayAdapter
<String
>(this, R
.layout
.sherlock_spinner_dropdown_item
);
208 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS, according to the official documentation
209 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
213 Log_OC
.d(TAG
, "onCreate() end");
217 protected void onStart() {
219 getSupportActionBar().setIcon(DisplayUtils
.getSeasonalIconId());
223 protected void onDestroy() {
228 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
231 protected void onAccountSet(boolean stateWasRecovered
) {
232 super.onAccountSet(stateWasRecovered
);
233 if (getAccount() != null
) {
234 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
235 OCFile file
= getFile();
236 // get parent from path
237 String parentPath
= "";
239 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
240 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
241 // get parent from path
242 parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
243 if (getStorageManager().getFileByPath(parentPath
) == null
)
244 file
= null
; // not able to know the directory where the file is uploading
246 file
= getStorageManager().getFileByPath(file
.getRemotePath()); // currentDir = null if not in the current Account
250 // fall back to root folder
251 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
254 setNavigationListWithFolder(file
);
256 if (!stateWasRecovered
) {
257 Log_OC
.e(TAG
, "Initializing Fragments in onAccountChanged..");
258 initFragmentsWithFile();
259 if (file
.isFolder()) {
260 startSyncFolderOperation(file
, false
);
264 updateFragmentsVisibility(!file
.isFolder());
265 updateNavigationElementsInActionBar(file
.isFolder() ? null
: file
);
271 private void setNavigationListWithFolder(OCFile file
) {
272 mDirectories
.clear();
273 OCFile fileIt
= file
;
275 while(fileIt
!= null
&& fileIt
.getFileName() != OCFile
.ROOT_PATH
) {
276 if (fileIt
.isFolder()) {
277 mDirectories
.add(fileIt
.getFileName());
279 // get parent from path
280 parentPath
= fileIt
.getRemotePath().substring(0, fileIt
.getRemotePath().lastIndexOf(fileIt
.getFileName()));
281 fileIt
= getStorageManager().getFileByPath(parentPath
);
283 mDirectories
.add(OCFile
.PATH_SEPARATOR
);
287 private void createMinFragments() {
288 OCFileListFragment listOfFiles
= new OCFileListFragment();
289 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
290 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
291 transaction
.commit();
294 private void initFragmentsWithFile() {
295 if (getAccount() != null
&& getFile() != null
) {
297 OCFileListFragment listOfFiles
= getListOfFilesFragment();
298 if (listOfFiles
!= null
) {
299 listOfFiles
.listDirectory(getCurrentDir());
301 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
305 OCFile file
= getFile();
306 Fragment secondFragment
= chooseInitialSecondFragment(file
);
307 if (secondFragment
!= null
) {
308 setSecondFragment(secondFragment
);
309 updateFragmentsVisibility(true
);
310 updateNavigationElementsInActionBar(file
);
313 cleanSecondFragment();
317 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
318 if (getAccount() == null
) {
319 Log_OC
.wtf(TAG
, "\t account is NULL");
321 if (getFile() == null
) {
322 Log_OC
.wtf(TAG
, "\t file is NULL");
327 private Fragment
chooseInitialSecondFragment(OCFile file
) {
328 Fragment secondFragment
= null
;
329 if (file
!= null
&& !file
.isFolder()) {
330 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
331 && file
.getLastSyncDateForProperties() > 0 // temporal fix
333 int startPlaybackPosition
= getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
334 boolean autoplay
= getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
335 secondFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
338 secondFragment
= new FileDetailFragment(file
, getAccount());
341 return secondFragment
;
346 * Replaces the second fragment managed by the activity with the received as
349 * Assumes never will be more than two fragments managed at the same time.
351 * @param fragment New second Fragment to set.
353 private void setSecondFragment(Fragment fragment
) {
354 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
355 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
356 transaction
.commit();
360 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
362 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
363 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
365 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
366 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
369 } else if (existsSecondFragment
) {
370 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
371 mLeftFragmentContainer
.setVisibility(View
.GONE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
381 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
382 mRightFragmentContainer
.setVisibility(View
.GONE
);
388 private OCFileListFragment
getListOfFilesFragment() {
389 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_LIST_OF_FILES
);
390 if (listOfFiles
!= null
) {
391 return (OCFileListFragment
)listOfFiles
;
393 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
397 public FileFragment
getSecondFragment() {
398 Fragment second
= getSupportFragmentManager().findFragmentByTag(FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
399 if (second
!= null
) {
400 return (FileFragment
)second
;
405 protected void cleanSecondFragment() {
406 Fragment second
= getSecondFragment();
407 if (second
!= null
) {
408 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
412 updateFragmentsVisibility(false
);
413 updateNavigationElementsInActionBar(null
);
416 protected void refreshListOfFilesFragment() {
417 OCFileListFragment fileListFragment
= getListOfFilesFragment();
418 if (fileListFragment
!= null
) {
419 fileListFragment
.listDirectory();
423 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
, boolean success
) {
424 FileFragment secondFragment
= getSecondFragment();
425 boolean waitedPreview
= (mWaitingToPreview
!= null
&& mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
426 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
427 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
428 OCFile fileInFragment
= detailsFragment
.getFile();
429 if (fileInFragment
!= null
&& !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
430 // the user browsed to other file ; forget the automatic preview
431 mWaitingToPreview
= null
;
433 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
434 // grant that the right panel updates the progress bar
435 detailsFragment
.listenForTransferProgress();
436 detailsFragment
.updateFileDetails(true
, false
);
438 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
439 // update the right panel
440 boolean detailsFragmentChanged
= false
;
443 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file from database, for the local storage path
444 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
445 startMediaPreview(mWaitingToPreview
, 0, true
);
446 detailsFragmentChanged
= true
;
448 getFileOperationsHelper().openFile(mWaitingToPreview
);
451 mWaitingToPreview
= null
;
453 if (!detailsFragmentChanged
) {
454 detailsFragment
.updateFileDetails(false
, (success
));
461 public boolean onPrepareOptionsMenu(Menu menu
) {
462 if (BuildConfig
.DEBUG
) {
463 menu
.findItem(R
.id
.action_logger
).setVisible(true
);
465 menu
.findItem(R
.id
.action_logger
).setVisible(false
);
467 return super.onPrepareOptionsMenu(menu
);
471 public boolean onCreateOptionsMenu(Menu menu
) {
472 MenuInflater inflater
= getSherlock().getMenuInflater();
473 inflater
.inflate(R
.menu
.main_menu
, menu
);
478 public boolean onOptionsItemSelected(MenuItem item
) {
479 boolean retval
= true
;
480 switch (item
.getItemId()) {
481 case R
.id
.action_create_dir
: {
482 CreateFolderDialogFragment dialog
=
483 CreateFolderDialogFragment
.newInstance(getCurrentDir());
484 dialog
.show(getSupportFragmentManager(), "createdirdialog");
487 case R
.id
.action_sync_account
: {
488 startSynchronization();
491 case R
.id
.action_upload
: {
492 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE
);
495 case R
.id
.action_settings
: {
496 Intent settingsIntent
= new Intent(this, Preferences
.class);
497 startActivity(settingsIntent
);
500 case R
.id
.action_logger
: {
501 Intent loggerIntent
= new Intent(getApplicationContext(),LogHistoryActivity
.class);
502 startActivity(loggerIntent
);
505 case android
.R
.id
.home
: {
506 FileFragment second
= getSecondFragment();
507 OCFile currentDir
= getCurrentDir();
508 if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
509 (second
!= null
&& second
.getFile() != null
)) {
515 case R
.id
.action_sort
: {
516 SharedPreferences appPreferences
= PreferenceManager
517 .getDefaultSharedPreferences(this);
519 // Read sorting order, default to sort by name ascending
520 Integer sortOrder
= appPreferences
521 .getInt("sortOrder", FileListListAdapter
.SORT_NAME
);
523 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
524 builder
.setTitle(R
.string
.actionbar_sort_title
)
525 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
, new DialogInterface
.OnClickListener() {
526 public void onClick(DialogInterface dialog
, int which
) {
536 // TODO re-enable when server-side folder size calculation is available
538 // sortBySize(false);
546 builder
.create().show();
550 retval
= super.onOptionsItemSelected(item
);
555 private void startSynchronization() {
556 Log_OC
.e(TAG
, "Got to start sync");
557 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
558 Log_OC
.e(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
559 ContentResolver
.cancelSync(null
, MainApp
.getAuthority()); // cancel the current synchronizations of any ownCloud account
560 Bundle bundle
= new Bundle();
561 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
562 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
563 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority());
564 ContentResolver
.requestSync(
566 MainApp
.getAuthority(), bundle
);
568 Log_OC
.e(TAG
, "Requesting sync for " + getAccount().name
+ " at " + MainApp
.getAuthority() + " with new API");
569 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
570 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
571 builder
.setExpedited(true
);
572 builder
.setManual(true
);
574 SyncRequest request
= builder
.build();
575 ContentResolver
.requestSync(request
);
581 public boolean onNavigationItemSelected(int itemPosition
, long itemId
) {
582 if (itemPosition
!= 0) {
583 String targetPath
= "";
584 for (int i
=itemPosition
; i
< mDirectories
.getCount() - 1; i
++) {
585 targetPath
= mDirectories
.getItem(i
) + OCFile
.PATH_SEPARATOR
+ targetPath
;
587 targetPath
= OCFile
.PATH_SEPARATOR
+ targetPath
;
588 OCFile targetFolder
= getStorageManager().getFileByPath(targetPath
);
589 if (targetFolder
!= null
) {
590 browseTo(targetFolder
);
593 // the next operation triggers a new call to this method, but it's necessary to
594 // ensure that the name exposed in the action bar is the current directory when the
595 // user selected it in the navigation list
596 if (getSupportActionBar().getNavigationMode() == ActionBar
.NAVIGATION_MODE_LIST
&& itemPosition
!= 0)
597 getSupportActionBar().setSelectedNavigationItem(0);
603 * Called, when the user selected something for uploading
605 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
606 super.onActivityResult(requestCode
, resultCode
, data
);
608 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
609 requestSimpleUpload(data
, resultCode
);
611 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
|| resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
612 requestMultipleUpload(data
, resultCode
);
614 } else if (requestCode
== ACTION_MOVE_FILES
&& (resultCode
== RESULT_OK
||
615 resultCode
== MoveActivity
.RESULT_OK_AND_MOVE
)){
617 final Intent fData
= data
;
618 final int fResultCode
= resultCode
;
619 getHandler().postDelayed(
623 requestMoveOperation(fData
, fResultCode
);
626 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
631 private void requestMultipleUpload(Intent data
, int resultCode
) {
632 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
633 if (filePaths
!= null
) {
634 String
[] remotePaths
= new String
[filePaths
.length
];
635 String remotePathBase
= "";
636 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
637 remotePathBase
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
639 if (!remotePathBase
.endsWith(OCFile
.PATH_SEPARATOR
))
640 remotePathBase
+= OCFile
.PATH_SEPARATOR
;
641 for (int j
= 0; j
< remotePaths
.length
; j
++) {
642 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
645 Intent i
= new Intent(this, FileUploader
.class);
646 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
647 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
648 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
649 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
650 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
651 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
655 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
656 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
), Toast
.LENGTH_LONG
);
663 private void requestSimpleUpload(Intent data
, int resultCode
) {
664 String filepath
= null
;
665 String mimeType
= null
;
667 Uri selectedImageUri
= data
.getData();
670 mimeType
= getContentResolver().getType(selectedImageUri
);
672 String filemanagerstring
= selectedImageUri
.getPath();
673 String selectedImagePath
= getPath(selectedImageUri
);
675 if (selectedImagePath
!= null
)
676 filepath
= selectedImagePath
;
678 filepath
= filemanagerstring
;
680 } catch (Exception e
) {
681 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
685 if (filepath
== null
) {
686 Log_OC
.e(TAG
, "Couldnt resolve path to file");
687 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
693 Intent i
= new Intent(this, FileUploader
.class);
694 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
696 String remotepath
= new String();
697 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
698 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
700 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
701 remotepath
+= OCFile
.PATH_SEPARATOR
;
703 if (filepath
.startsWith(URI_CONTENT_SCHEME
)) {
705 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
706 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
709 if (cursor
!= null
&& cursor
.moveToFirst()) {
710 String displayName
= cursor
.getString(
711 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
712 Log
.i(TAG
, "Display Name: " + displayName
+ "; mimeType: " + mimeType
);
714 remotepath
+= displayName
+ getComposedFileExtension(filepath
);
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_MIME_TYPE
, mimeType
);
728 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
729 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
730 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
735 * Request the operation for moving the file/folder from one path to another
737 * @param data Intent received
738 * @param resultCode Result code received
740 private void requestMoveOperation(Intent data
, int resultCode
) {
741 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
742 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
743 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
747 public void onBackPressed() {
748 OCFileListFragment listOfFiles
= getListOfFilesFragment();
749 if (mDualPane
|| getSecondFragment() == null
) {
750 if (listOfFiles
!= null
) { // should never be null, indeed
751 if (mDirectories
.getCount() <= 1) {
755 int levelsUp
= listOfFiles
.onBrowseUp();
756 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
761 if (listOfFiles
!= null
) { // should never be null, indeed
762 setFile(listOfFiles
.getCurrentFile());
764 cleanSecondFragment();
769 protected void onSaveInstanceState(Bundle outState
) {
770 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
771 Log_OC
.e(TAG
, "onSaveInstanceState() start");
772 super.onSaveInstanceState(outState
);
773 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
774 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
775 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
776 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
778 Log_OC
.d(TAG
, "onSaveInstanceState() end");
784 protected void onResume() {
786 Log_OC
.e(TAG
, "onResume() start");
788 // refresh list of files
789 refreshListOfFilesFragment();
791 // Listen for sync messages
792 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
793 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
794 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
795 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
796 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
797 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
798 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
799 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
801 // Listen for upload messages
802 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
803 mUploadFinishReceiver
= new UploadFinishReceiver();
804 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
806 // Listen for download messages
807 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
808 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
809 mDownloadFinishReceiver
= new DownloadFinishReceiver();
810 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
812 Log_OC
.d(TAG
, "onResume() end");
817 protected void onPause() {
818 Log_OC
.e(TAG
, "onPause() start");
819 if (mSyncBroadcastReceiver
!= null
) {
820 unregisterReceiver(mSyncBroadcastReceiver
);
821 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
822 mSyncBroadcastReceiver
= null
;
824 if (mUploadFinishReceiver
!= null
) {
825 unregisterReceiver(mUploadFinishReceiver
);
826 mUploadFinishReceiver
= null
;
828 if (mDownloadFinishReceiver
!= null
) {
829 unregisterReceiver(mDownloadFinishReceiver
);
830 mDownloadFinishReceiver
= null
;
834 Log_OC
.d(TAG
, "onPause() end");
840 protected Dialog
onCreateDialog(int id
) {
841 Dialog dialog
= null
;
842 AlertDialog
.Builder builder
;
844 case DIALOG_SHORT_WAIT
: {
845 ProgressDialog working_dialog
= new ProgressDialog(this);
846 working_dialog
.setMessage(getResources().getString(
847 R
.string
.wait_a_moment
));
848 working_dialog
.setIndeterminate(true
);
849 working_dialog
.setCancelable(false
);
850 dialog
= working_dialog
;
853 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
856 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
857 getString(R
.string
.actionbar_upload_from_apps
) };
859 builder
= new AlertDialog
.Builder(this);
860 builder
.setTitle(R
.string
.actionbar_upload
);
861 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
862 public void onClick(DialogInterface dialog
, int item
) {
865 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
866 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
867 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
869 // TODO create and handle new fragment
870 // LocalFileListFragment
872 } else if (item
== 1) {
873 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
874 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
875 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
876 ACTION_SELECT_CONTENT_FROM_APPS
);
880 dialog
= builder
.create();
883 case DIALOG_CERT_NOT_SAVED
: {
884 builder
= new AlertDialog
.Builder(this);
885 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
886 builder
.setCancelable(false
);
887 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
889 public void onClick(DialogInterface dialog
, int which
) {
893 dialog
= builder
.create();
904 * Translates a content URI of an content to a physical path on the disk
906 * @param uri The URI to resolve
907 * @return The path to the content or null if it could not be found
909 public String
getPath(Uri uri
) {
910 final boolean isKitKat
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
913 if (isKitKat
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
914 // ExternalStorageProvider
915 if (isExternalStorageDocument(uri
)) {
916 final String docId
= DocumentsContract
.getDocumentId(uri
);
917 final String
[] split
= docId
.split(":");
918 final String type
= split
[0];
920 if ("primary".equalsIgnoreCase(type
)) {
921 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
925 else if (isDownloadsDocument(uri
)) {
927 final String id
= DocumentsContract
.getDocumentId(uri
);
928 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
931 return getDataColumn(getApplicationContext(), contentUri
, null
, null
);
934 else if (isMediaDocument(uri
)) {
935 final String docId
= DocumentsContract
.getDocumentId(uri
);
936 final String
[] split
= docId
.split(":");
937 final String type
= split
[0];
939 Uri contentUri
= null
;
940 if ("image".equals(type
)) {
941 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
942 } else if ("video".equals(type
)) {
943 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
944 } else if ("audio".equals(type
)) {
945 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
948 final String selection
= "_id=?";
949 final String
[] selectionArgs
= new String
[] { split
[1] };
951 return getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
953 // Documents providers returned as content://...
954 else if (isContentDocument(uri
)) {
955 return uri
.toString();
958 // MediaStore (and general)
959 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
961 // Return the remote address
962 if (isGooglePhotosUri(uri
))
963 return uri
.getLastPathSegment();
965 return getDataColumn(getApplicationContext(), uri
, null
, null
);
968 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
969 return uri
.getPath();
975 * Get the value of the data column for this Uri. This is useful for
976 * MediaStore Uris, and other file-based ContentProviders.
978 * @param context The context.
979 * @param uri The Uri to query.
980 * @param selection (Optional) Filter used in the query.
981 * @param selectionArgs (Optional) Selection arguments used in the query.
982 * @return The value of the _data column, which is typically a file path.
984 public static String
getDataColumn(Context context
, Uri uri
, String selection
, String
[] selectionArgs
) {
986 Cursor cursor
= null
;
987 final String column
= "_data";
988 final String
[] projection
= { column
};
991 cursor
= context
.getContentResolver().query(uri
, projection
, selection
, selectionArgs
, null
);
992 if (cursor
!= null
&& cursor
.moveToFirst()) {
994 final int column_index
= cursor
.getColumnIndexOrThrow(column
);
995 return cursor
.getString(column_index
);
1005 * @param uri The Uri to check.
1006 * @return Whether the Uri authority is ExternalStorageProvider.
1008 public static boolean isExternalStorageDocument(Uri uri
) {
1009 return "com.android.externalstorage.documents".equals(uri
.getAuthority());
1013 * @param uri The Uri to check.
1014 * @return Whether the Uri authority is DownloadsProvider.
1016 public static boolean isDownloadsDocument(Uri uri
) {
1017 return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
1021 * @param uri The Uri to check.
1022 * @return Whether the Uri authority is MediaProvider.
1024 public static boolean isMediaDocument(Uri uri
) {
1025 return "com.android.providers.media.documents".equals(uri
.getAuthority());
1029 * @param uri The Uri to check.
1030 * @return Whether the Uri authority is Google Photos.
1032 public static boolean isGooglePhotosUri(Uri uri
) {
1033 return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
1038 * @param uri The Uri to check.
1039 * @return Whether the Uri is from a content provider as kind "content://..."
1041 public static boolean isContentDocument(Uri uri
) {
1042 return uri
.toString().startsWith(URI_CONTENT_SCHEME
);
1046 * Pushes a directory to the drop down list
1047 * @param directory to push
1048 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1050 public void pushDirname(OCFile directory
) {
1051 if(!directory
.isFolder()){
1052 throw new IllegalArgumentException("Only directories may be pushed!");
1054 mDirectories
.insert(directory
.getFileName(), 0);
1059 * Pops a directory name from the drop down list
1060 * @return True, unless the stack is empty
1062 public boolean popDirname() {
1063 mDirectories
.remove(mDirectories
.getItem(0));
1064 return !mDirectories
.isEmpty();
1067 // Custom array adapter to override text colors
1068 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1070 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1074 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1075 View v
= super.getView(position
, convertView
, parent
);
1077 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1078 android
.R
.color
.white
));
1080 fixRoot((TextView
) v
);
1084 public View
getDropDownView(int position
, View convertView
,
1086 View v
= super.getDropDownView(position
, convertView
, parent
);
1088 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1089 android
.R
.color
.white
));
1091 fixRoot((TextView
) v
);
1095 private void fixRoot(TextView v
) {
1096 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1097 v
.setText(R
.string
.default_display_name_for_root_folder
);
1103 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1106 * {@link BroadcastReceiver} to enable syncing feedback in UI
1109 public void onReceive(Context context
, Intent intent
) {
1111 String event
= intent
.getAction();
1112 Log_OC
.d(TAG
, "Received broadcast " + event
);
1113 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1114 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1115 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1116 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1120 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1121 mSyncInProgress
= true
;
1124 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1125 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1127 if (currentDir
== null
) {
1128 // current folder was removed from the server
1129 Toast
.makeText( FileDisplayActivity
.this,
1130 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1136 if (currentFile
== null
&& !getFile().isFolder()) {
1137 // currently selected file was removed in the server, and now we know it
1138 cleanSecondFragment();
1139 currentFile
= currentDir
;
1142 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1143 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1144 if (fileListFragment
!= null
) {
1145 fileListFragment
.listDirectory(currentDir
);
1148 setFile(currentFile
);
1151 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1153 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1155 /// TODO refactor and make common
1156 synchResult
!= null
&& !synchResult
.isSuccess() &&
1157 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1158 synchResult
.isIdPRedirection() ||
1159 (synchResult
.isException() && synchResult
.getException()
1160 instanceof AuthenticatorException
))) {
1162 OwnCloudClient client
= null
;
1164 OwnCloudAccount ocAccount
=
1165 new OwnCloudAccount(getAccount(), context
);
1166 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1167 removeClientFor(ocAccount
));
1168 // TODO get rid of these exceptions
1169 } catch (AccountNotFoundException e
) {
1170 e
.printStackTrace();
1171 } catch (AuthenticatorException e
) {
1172 e
.printStackTrace();
1173 } catch (OperationCanceledException e
) {
1174 e
.printStackTrace();
1175 } catch (IOException e
) {
1176 e
.printStackTrace();
1179 if (client
!= null
) {
1180 OwnCloudCredentials cred
= client
.getCredentials();
1182 AccountManager am
= AccountManager
.get(context
);
1183 if (cred
.authTokenExpires()) {
1184 am
.invalidateAuthToken(
1189 am
.clearPassword(getAccount());
1194 requestCredentialsUpdate();
1198 removeStickyBroadcast(intent
);
1199 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1200 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1202 setBackgroundText();
1206 if (synchResult
!= null
) {
1207 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1208 mLastSslUntrustedServerResult
= synchResult
;
1211 } catch (RuntimeException e
) {
1212 // avoid app crashes after changing the serial id of RemoteOperationResult
1213 // in owncloud library with broadcast notifications pending to process
1214 removeStickyBroadcast(intent
);
1220 * Show a text message on screen view for notifying user if content is
1221 * loading or folder is empty
1223 private void setBackgroundText() {
1224 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1225 if (ocFileListFragment
!= null
) {
1226 int message
= R
.string
.file_list_loading
;
1227 if (!mSyncInProgress
) {
1228 // In case file list is empty
1229 message
= R
.string
.file_list_empty
;
1231 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1233 Log_OC
.e(TAG
, "OCFileListFragment is null");
1238 * Once the file upload has finished -> update view
1240 private class UploadFinishReceiver
extends BroadcastReceiver
{
1242 * Once the file upload has finished -> update view
1243 * @author David A. Velasco
1244 * {@link BroadcastReceiver} to enable upload feedback in UI
1247 public void onReceive(Context context
, Intent intent
) {
1249 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1250 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1251 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1252 OCFile currentDir
= getCurrentDir();
1253 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1254 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1256 if (sameAccount
&& isDescendant
) {
1257 refreshListOfFilesFragment();
1260 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1261 boolean renamedInUpload
= getFile().getRemotePath().
1262 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1263 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1265 FileFragment details
= getSecondFragment();
1266 boolean detailFragmentIsShown
= (details
!= null
&&
1267 details
instanceof FileDetailFragment
);
1269 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1270 if (uploadWasFine
) {
1271 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1273 if (renamedInUpload
) {
1274 String newName
= (new File(uploadedRemotePath
)).getName();
1275 Toast msg
= Toast
.makeText(
1278 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1283 if (uploadWasFine
|| getFile().fileExists()) {
1284 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1286 cleanSecondFragment();
1289 // Force the preview if the file is an image
1290 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1291 startImagePreview(getFile());
1292 } // TODO what about other kind of previews?
1296 if (intent
!= null
) {
1297 removeStickyBroadcast(intent
);
1307 * Class waiting for broadcast events from the {@link FielDownloader} service.
1309 * Updates the UI when a download is started or finished, provided that it is relevant for the
1312 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1314 public void onReceive(Context context
, Intent intent
) {
1316 boolean sameAccount
= isSameAccount(context
, intent
);
1317 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1318 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1320 if (sameAccount
&& isDescendant
) {
1321 refreshListOfFilesFragment();
1322 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1325 if (mWaitingToSend
!= null
) {
1326 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1327 if (mWaitingToSend
.isDown()) {
1328 sendDownloadedFile();
1333 if (intent
!= null
) {
1334 removeStickyBroadcast(intent
);
1339 private boolean isDescendant(String downloadedRemotePath
) {
1340 OCFile currentDir
= getCurrentDir();
1341 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1344 private boolean isSameAccount(Context context
, Intent intent
) {
1345 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1346 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1351 public void browseToRoot() {
1352 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1353 if (listOfFiles
!= null
) { // should never be null, indeed
1354 while (mDirectories
.getCount() > 1) {
1357 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1358 listOfFiles
.listDirectory(root
);
1359 setFile(listOfFiles
.getCurrentFile());
1360 startSyncFolderOperation(root
, false
);
1362 cleanSecondFragment();
1366 public void browseTo(OCFile folder
) {
1367 if (folder
== null
|| !folder
.isFolder()) {
1368 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1370 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1371 if (listOfFiles
!= null
) {
1372 setNavigationListWithFolder(folder
);
1373 listOfFiles
.listDirectory(folder
);
1374 setFile(listOfFiles
.getCurrentFile());
1375 startSyncFolderOperation(folder
, false
);
1377 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1379 cleanSecondFragment();
1386 * Updates action bar and second fragment, if in dual pane mode.
1389 public void onBrowsedDownTo(OCFile directory
) {
1390 pushDirname(directory
);
1391 cleanSecondFragment();
1394 startSyncFolderOperation(directory
, false
);
1399 * Shows the information of the {@link OCFile} received as a
1400 * parameter in the second fragment.
1402 * @param file {@link OCFile} whose details will be shown
1405 public void showDetails(OCFile file
) {
1406 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1407 setSecondFragment(detailFragment
);
1408 updateFragmentsVisibility(true
);
1409 updateNavigationElementsInActionBar(file
);
1417 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1418 ActionBar actionBar
= getSupportActionBar();
1419 if (chosenFile
== null
|| mDualPane
) {
1420 // only list of files - set for browsing through folders
1421 OCFile currentDir
= getCurrentDir();
1422 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1423 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1424 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1426 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1428 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1429 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1432 actionBar
.setDisplayHomeAsUpEnabled(true
);
1433 actionBar
.setDisplayShowTitleEnabled(true
);
1434 actionBar
.setTitle(chosenFile
.getFileName());
1435 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1441 protected ServiceConnection
newTransferenceServiceConnection() {
1442 return new ListServiceConnection();
1445 /** Defines callbacks for service binding, passed to bindService() */
1446 private class ListServiceConnection
implements ServiceConnection
{
1449 public void onServiceConnected(ComponentName component
, IBinder service
) {
1450 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1451 Log_OC
.d(TAG
, "Download service connected");
1452 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1453 if (mWaitingToPreview
!= null
)
1454 if (getStorageManager() != null
) {
1455 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1456 if (!mWaitingToPreview
.isDown()) {
1457 requestForDownload();
1461 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1462 Log_OC
.d(TAG
, "Upload service connected");
1463 mUploaderBinder
= (FileUploaderBinder
) service
;
1467 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1468 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1469 if (listOfFiles
!= null
) {
1470 listOfFiles
.listDirectory();
1472 FileFragment secondFragment
= getSecondFragment();
1473 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1474 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1475 detailFragment
.listenForTransferProgress();
1476 detailFragment
.updateFileDetails(false
, false
);
1481 public void onServiceDisconnected(ComponentName component
) {
1482 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1483 Log_OC
.d(TAG
, "Download service disconnected");
1484 mDownloaderBinder
= null
;
1485 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1486 Log_OC
.d(TAG
, "Upload service disconnected");
1487 mUploaderBinder
= null
;
1495 * Launch an intent to request the PIN code to the user before letting him use the app
1497 private void requestPinCode() {
1498 boolean pinStart
= false
;
1499 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1500 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1502 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1503 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1510 public void onSavedCertificate() {
1511 startSyncFolderOperation(getCurrentDir(), false
);
1516 public void onFailedSavingCertificate() {
1517 showDialog(DIALOG_CERT_NOT_SAVED
);
1521 public void onCancelCertificate() {
1526 * Updates the view associated to the activity after the finish of some operation over files
1527 * in the current account.
1529 * @param operation Removal operation performed.
1530 * @param result Result of the removal.
1533 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1534 super.onRemoteOperationFinish(operation
, result
);
1536 if (operation
instanceof RemoveFileOperation
) {
1537 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1539 } else if (operation
instanceof RenameFileOperation
) {
1540 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1542 } else if (operation
instanceof SynchronizeFileOperation
) {
1543 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1545 } else if (operation
instanceof CreateFolderOperation
) {
1546 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1548 } else if (operation
instanceof CreateShareOperation
) {
1549 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1551 } else if (operation
instanceof UnshareLinkOperation
) {
1552 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1554 } else if (operation
instanceof MoveFileOperation
) {
1555 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1561 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1562 if (result
.isSuccess()) {
1563 refreshShowDetails();
1564 refreshListOfFilesFragment();
1569 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1570 if (result
.isSuccess()) {
1571 refreshShowDetails();
1572 refreshListOfFilesFragment();
1574 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1575 cleanSecondFragment();
1576 refreshListOfFilesFragment();
1580 private void refreshShowDetails() {
1581 FileFragment details
= getSecondFragment();
1582 if (details
!= null
) {
1583 OCFile file
= details
.getFile();
1585 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1586 if (details
instanceof PreviewMediaFragment
) {
1587 // Refresh OCFile of the fragment
1588 ((PreviewMediaFragment
) details
).updateFile(file
);
1593 invalidateOptionsMenu();
1598 * Updates the view associated to the activity after the finish of an operation trying to remove a
1601 * @param operation Removal operation performed.
1602 * @param result Result of the removal.
1604 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1605 dismissLoadingDialog();
1607 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1611 if (result
.isSuccess()) {
1612 OCFile removedFile
= operation
.getFile();
1613 FileFragment second
= getSecondFragment();
1614 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1615 if (second
instanceof PreviewMediaFragment
) {
1616 ((PreviewMediaFragment
)second
).stopPreview(true
);
1618 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1619 cleanSecondFragment();
1621 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1622 refreshListOfFilesFragment();
1624 invalidateOptionsMenu();
1626 if (result
.isSslRecoverableException()) {
1627 mLastSslUntrustedServerResult
= result
;
1628 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1635 * Updates the view associated to the activity after the finish of an operation trying to move a
1638 * @param operation Move operation performed.
1639 * @param result Result of the move operation.
1641 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1642 if (result
.isSuccess()) {
1643 dismissLoadingDialog();
1644 refreshListOfFilesFragment();
1646 dismissLoadingDialog();
1648 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1649 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1653 } catch (NotFoundException e
) {
1654 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1661 * Updates the view associated to the activity after the finish of an operation trying to rename a
1664 * @param operation Renaming operation performed.
1665 * @param result Result of the renaming.
1667 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1668 dismissLoadingDialog();
1669 OCFile renamedFile
= operation
.getFile();
1670 if (result
.isSuccess()) {
1671 FileFragment details
= getSecondFragment();
1672 if (details
!= null
) {
1673 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1674 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1675 showDetails(renamedFile
);
1677 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1678 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1679 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1680 int position
= ((PreviewMediaFragment
)details
).getPosition();
1681 startMediaPreview(renamedFile
, position
, true
);
1683 getFileOperationsHelper().openFile(renamedFile
);
1688 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1689 refreshListOfFilesFragment();
1693 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1697 if (result
.isSslRecoverableException()) {
1698 mLastSslUntrustedServerResult
= result
;
1699 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1704 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1705 dismissLoadingDialog();
1706 OCFile syncedFile
= operation
.getLocalFile();
1707 if (!result
.isSuccess()) {
1708 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1709 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1710 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1711 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1717 if (operation
.transferWasRequested()) {
1718 onTransferStateChanged(syncedFile
, true
, true
);
1721 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1729 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1731 * @param operation Creation operation performed.
1732 * @param result Result of the creation.
1734 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1735 if (result
.isSuccess()) {
1736 dismissLoadingDialog();
1737 refreshListOfFilesFragment();
1739 dismissLoadingDialog();
1741 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1742 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1746 } catch (NotFoundException e
) {
1747 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1757 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1758 refreshListOfFilesFragment();
1759 FileFragment details
= getSecondFragment();
1760 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1761 if (downloading
|| uploading
) {
1762 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1764 if (!file
.fileExists()) {
1765 cleanSecondFragment();
1767 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1775 private void requestForDownload() {
1776 Account account
= getAccount();
1777 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1778 Intent i
= new Intent(this, FileDownloader
.class);
1779 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1780 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1786 private OCFile
getCurrentDir() {
1787 OCFile file
= getFile();
1789 if (file
.isFolder()) {
1791 } else if (getStorageManager() != null
) {
1792 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1793 return getStorageManager().getFileByPath(parentPath
);
1799 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1800 long currentSyncTime
= System
.currentTimeMillis();
1802 mSyncInProgress
= true
;
1804 // perform folder synchronization
1805 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1808 getFileOperationsHelper().isSharedSupported(),
1810 getStorageManager(),
1812 getApplicationContext()
1814 synchFolderOp
.execute(getAccount(), this, null
, null
);
1816 setSupportProgressBarIndeterminateVisibility(true
);
1818 setBackgroundText();
1822 * Show untrusted cert dialog
1824 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1825 // Show a dialog with the certificate info
1826 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1827 FragmentManager fm
= getSupportFragmentManager();
1828 FragmentTransaction ft
= fm
.beginTransaction();
1829 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1832 private void requestForDownload(OCFile file
) {
1833 Account account
= getAccount();
1834 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1835 Intent i
= new Intent(this, FileDownloader
.class);
1836 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1837 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1842 private void sendDownloadedFile(){
1843 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1844 mWaitingToSend
= null
;
1849 * Requests the download of the received {@link OCFile} , updates the UI
1850 * to monitor the download progress and prepares the activity to send the file
1851 * when the download finishes.
1853 * @param file {@link OCFile} to download and preview.
1855 public void startDownloadForSending(OCFile file
) {
1856 mWaitingToSend
= file
;
1857 requestForDownload(mWaitingToSend
);
1858 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1859 updateFragmentsVisibility(hasSecondFragment
);
1863 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1865 * @param file Image {@link OCFile} to show.
1867 public void startImagePreview(OCFile file
) {
1868 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1869 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1870 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1871 startActivity(showDetailsIntent
);
1876 * Stars the preview of an already down media {@link OCFile}.
1878 * @param file Media {@link OCFile} to preview.
1879 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1880 * @param autoplay When 'true', the playback will start without user interactions.
1882 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1883 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1884 setSecondFragment(mediaFragment
);
1885 updateFragmentsVisibility(true
);
1886 updateNavigationElementsInActionBar(file
);
1891 * Requests the download of the received {@link OCFile} , updates the UI
1892 * to monitor the download progress and prepares the activity to preview
1893 * or open the file when the download finishes.
1895 * @param file {@link OCFile} to download and preview.
1897 public void startDownloadForPreview(OCFile file
) {
1898 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1899 setSecondFragment(detailFragment
);
1900 mWaitingToPreview
= file
;
1901 requestForDownload();
1902 updateFragmentsVisibility(true
);
1903 updateNavigationElementsInActionBar(file
);
1908 public void cancelTransference(OCFile file
) {
1909 getFileOperationsHelper().cancelTransference(file
);
1910 if (mWaitingToPreview
!= null
&&
1911 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1912 mWaitingToPreview
= null
;
1914 if (mWaitingToSend
!= null
&&
1915 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1916 mWaitingToSend
= null
;
1918 onTransferStateChanged(file
, false
, false
);
1922 public void onRefresh(boolean ignoreETag
) {
1923 refreshList(ignoreETag
);
1927 public void onRefresh() {
1931 private void refreshList(boolean ignoreETag
) {
1932 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1933 if (listOfFiles
!= null
) {
1934 OCFile folder
= listOfFiles
.getCurrentFile();
1935 if (folder
!= null
) {
1936 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1937 listDirectory(mFile);*/
1938 startSyncFolderOperation(folder
, ignoreETag
);
1943 private void sortByDate(boolean ascending
){
1944 getListOfFilesFragment().sortByDate(ascending
);
1947 private void sortBySize(boolean ascending
){
1948 getListOfFilesFragment().sortBySize(ascending
);
1951 private void sortByName(boolean ascending
){
1952 getListOfFilesFragment().sortByName(ascending
);
1956 * Get the file extension if it is on path as type "content://.../DocInfo.doc"
1957 * @param filepath: Content Uri converted to string format
1958 * @return String: fileExtension (type '.pdf'). Empty if no extension
1960 private String
getComposedFileExtension(String filepath
) {
1961 String fileExtension
= "";
1962 String fileNameInContentUri
= filepath
.substring(filepath
.lastIndexOf("/"));
1964 // Check if extension is included in uri
1965 int pos
= fileNameInContentUri
.lastIndexOf('.');
1967 fileExtension
= fileNameInContentUri
.substring(pos
);
1969 return fileExtension
;