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_TYPE_OF_CONTENT_PROVIDER
= "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
;
666 Uri selectedImageUri
= data
.getData();
668 String filemanagerstring
= selectedImageUri
.getPath();
669 String selectedImagePath
= getPath(selectedImageUri
);
671 if (selectedImagePath
!= null
)
672 filepath
= selectedImagePath
;
674 filepath
= filemanagerstring
;
676 } catch (Exception e
) {
677 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e
);
681 if (filepath
== null
) {
682 Log_OC
.e(TAG
, "Couldnt resolve path to file");
683 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_unexpected_bad_get_content
), Toast
.LENGTH_LONG
);
689 Intent i
= new Intent(this, FileUploader
.class);
690 i
.putExtra(FileUploader
.KEY_ACCOUNT
,
692 String remotepath
= new String();
693 for (int j
= mDirectories
.getCount() - 2; j
>= 0; --j
) {
694 remotepath
+= OCFile
.PATH_SEPARATOR
+ mDirectories
.getItem(j
);
696 if (!remotepath
.endsWith(OCFile
.PATH_SEPARATOR
))
697 remotepath
+= OCFile
.PATH_SEPARATOR
;
699 if (filepath
.startsWith(URI_TYPE_OF_CONTENT_PROVIDER
)) {
700 // The query, since it only applies to a single document, will only return
702 Cursor cursor
= MainApp
.getAppContext().getContentResolver()
703 .query(Uri
.parse(filepath
), null
, null
, null
, null
, null
);
706 if (cursor
!= null
&& cursor
.moveToFirst()) {
707 String displayName
= cursor
.getString(
708 cursor
.getColumnIndex(OpenableColumns
.DISPLAY_NAME
));
709 Log
.i(TAG
, "Display Name: " + displayName
);
711 remotepath
+= displayName
;
718 remotepath
+= new File(filepath
).getName();
721 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filepath
);
722 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotepath
);
723 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
724 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
725 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
730 * Request the operation for moving the file/folder from one path to another
732 * @param data Intent received
733 * @param resultCode Result code received
735 private void requestMoveOperation(Intent data
, int resultCode
) {
736 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_CURRENT_FOLDER
);
737 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(MoveActivity
.EXTRA_TARGET_FILE
);
738 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
742 public void onBackPressed() {
743 OCFileListFragment listOfFiles
= getListOfFilesFragment();
744 if (mDualPane
|| getSecondFragment() == null
) {
745 if (listOfFiles
!= null
) { // should never be null, indeed
746 if (mDirectories
.getCount() <= 1) {
750 int levelsUp
= listOfFiles
.onBrowseUp();
751 for (int i
=0; i
< levelsUp
&& mDirectories
.getCount() > 1 ; i
++) {
756 if (listOfFiles
!= null
) { // should never be null, indeed
757 setFile(listOfFiles
.getCurrentFile());
759 cleanSecondFragment();
764 protected void onSaveInstanceState(Bundle outState
) {
765 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
766 Log_OC
.e(TAG
, "onSaveInstanceState() start");
767 super.onSaveInstanceState(outState
);
768 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
769 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
770 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
771 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
773 Log_OC
.d(TAG
, "onSaveInstanceState() end");
779 protected void onResume() {
781 Log_OC
.e(TAG
, "onResume() start");
783 // refresh list of files
784 refreshListOfFilesFragment();
786 // Listen for sync messages
787 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
788 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
789 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
790 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
791 syncIntentFilter
.addAction(SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
792 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
793 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
794 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
796 // Listen for upload messages
797 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
798 mUploadFinishReceiver
= new UploadFinishReceiver();
799 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
801 // Listen for download messages
802 IntentFilter downloadIntentFilter
= new IntentFilter(FileDownloader
.getDownloadAddedMessage());
803 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
804 mDownloadFinishReceiver
= new DownloadFinishReceiver();
805 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
807 Log_OC
.d(TAG
, "onResume() end");
812 protected void onPause() {
813 Log_OC
.e(TAG
, "onPause() start");
814 if (mSyncBroadcastReceiver
!= null
) {
815 unregisterReceiver(mSyncBroadcastReceiver
);
816 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
817 mSyncBroadcastReceiver
= null
;
819 if (mUploadFinishReceiver
!= null
) {
820 unregisterReceiver(mUploadFinishReceiver
);
821 mUploadFinishReceiver
= null
;
823 if (mDownloadFinishReceiver
!= null
) {
824 unregisterReceiver(mDownloadFinishReceiver
);
825 mDownloadFinishReceiver
= null
;
829 Log_OC
.d(TAG
, "onPause() end");
835 protected Dialog
onCreateDialog(int id
) {
836 Dialog dialog
= null
;
837 AlertDialog
.Builder builder
;
839 case DIALOG_SHORT_WAIT
: {
840 ProgressDialog working_dialog
= new ProgressDialog(this);
841 working_dialog
.setMessage(getResources().getString(
842 R
.string
.wait_a_moment
));
843 working_dialog
.setIndeterminate(true
);
844 working_dialog
.setCancelable(false
);
845 dialog
= working_dialog
;
848 case DIALOG_CHOOSE_UPLOAD_SOURCE
: {
851 String
[] allTheItems
= { getString(R
.string
.actionbar_upload_files
),
852 getString(R
.string
.actionbar_upload_from_apps
) };
854 builder
= new AlertDialog
.Builder(this);
855 builder
.setTitle(R
.string
.actionbar_upload
);
856 builder
.setItems(allTheItems
, new DialogInterface
.OnClickListener() {
857 public void onClick(DialogInterface dialog
, int item
) {
860 Intent action
= new Intent(FileDisplayActivity
.this, UploadFilesActivity
.class);
861 action
.putExtra(UploadFilesActivity
.EXTRA_ACCOUNT
, FileDisplayActivity
.this.getAccount());
862 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
864 // TODO create and handle new fragment
865 // LocalFileListFragment
867 } else if (item
== 1) {
868 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
869 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
870 startActivityForResult(Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
871 ACTION_SELECT_CONTENT_FROM_APPS
);
875 dialog
= builder
.create();
878 case DIALOG_CERT_NOT_SAVED
: {
879 builder
= new AlertDialog
.Builder(this);
880 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
881 builder
.setCancelable(false
);
882 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
884 public void onClick(DialogInterface dialog
, int which
) {
888 dialog
= builder
.create();
899 * Translates a content URI of an content to a physical path on the disk
901 * @param uri The URI to resolve
902 * @return The path to the content or null if it could not be found
904 public String
getPath(Uri uri
) {
905 final boolean isKitKat
= Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.KITKAT
;
908 if (isKitKat
&& DocumentsContract
.isDocumentUri(getApplicationContext(), uri
)) {
909 // ExternalStorageProvider
910 if (isExternalStorageDocument(uri
)) {
911 final String docId
= DocumentsContract
.getDocumentId(uri
);
912 final String
[] split
= docId
.split(":");
913 final String type
= split
[0];
915 if ("primary".equalsIgnoreCase(type
)) {
916 return Environment
.getExternalStorageDirectory() + "/" + split
[1];
920 else if (isDownloadsDocument(uri
)) {
922 final String id
= DocumentsContract
.getDocumentId(uri
);
923 final Uri contentUri
= ContentUris
.withAppendedId(Uri
.parse("content://downloads/public_downloads"),
926 return getDataColumn(getApplicationContext(), contentUri
, null
, null
);
929 else if (isMediaDocument(uri
)) {
930 final String docId
= DocumentsContract
.getDocumentId(uri
);
931 final String
[] split
= docId
.split(":");
932 final String type
= split
[0];
934 Uri contentUri
= null
;
935 if ("image".equals(type
)) {
936 contentUri
= MediaStore
.Images
.Media
.EXTERNAL_CONTENT_URI
;
937 } else if ("video".equals(type
)) {
938 contentUri
= MediaStore
.Video
.Media
.EXTERNAL_CONTENT_URI
;
939 } else if ("audio".equals(type
)) {
940 contentUri
= MediaStore
.Audio
.Media
.EXTERNAL_CONTENT_URI
;
943 final String selection
= "_id=?";
944 final String
[] selectionArgs
= new String
[] { split
[1] };
946 return getDataColumn(getApplicationContext(), contentUri
, selection
, selectionArgs
);
948 // Documents providers returned as content://...
949 else if (isContentDocument(uri
)) {
950 return uri
.toString();
953 // MediaStore (and general)
954 else if ("content".equalsIgnoreCase(uri
.getScheme())) {
956 // Return the remote address
957 if (isGooglePhotosUri(uri
))
958 return uri
.getLastPathSegment();
960 return getDataColumn(getApplicationContext(), uri
, null
, null
);
963 else if ("file".equalsIgnoreCase(uri
.getScheme())) {
964 return uri
.getPath();
970 * Get the value of the data column for this Uri. This is useful for
971 * MediaStore Uris, and other file-based ContentProviders.
973 * @param context The context.
974 * @param uri The Uri to query.
975 * @param selection (Optional) Filter used in the query.
976 * @param selectionArgs (Optional) Selection arguments used in the query.
977 * @return The value of the _data column, which is typically a file path.
979 public static String
getDataColumn(Context context
, Uri uri
, String selection
, String
[] selectionArgs
) {
981 Cursor cursor
= null
;
982 final String column
= "_data";
983 final String
[] projection
= { column
};
986 cursor
= context
.getContentResolver().query(uri
, projection
, selection
, selectionArgs
, null
);
987 if (cursor
!= null
&& cursor
.moveToFirst()) {
989 final int column_index
= cursor
.getColumnIndexOrThrow(column
);
990 return cursor
.getString(column_index
);
1000 * @param uri The Uri to check.
1001 * @return Whether the Uri authority is ExternalStorageProvider.
1003 public static boolean isExternalStorageDocument(Uri uri
) {
1004 return "com.android.externalstorage.documents".equals(uri
.getAuthority());
1008 * @param uri The Uri to check.
1009 * @return Whether the Uri authority is DownloadsProvider.
1011 public static boolean isDownloadsDocument(Uri uri
) {
1012 return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
1016 * @param uri The Uri to check.
1017 * @return Whether the Uri authority is MediaProvider.
1019 public static boolean isMediaDocument(Uri uri
) {
1020 return "com.android.providers.media.documents".equals(uri
.getAuthority());
1024 * @param uri The Uri to check.
1025 * @return Whether the Uri authority is Google Photos.
1027 public static boolean isGooglePhotosUri(Uri uri
) {
1028 return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
1033 * @param uri The Uri to check.
1034 * @return Whether the Uri is from a content provider as kind "content://..."
1036 public static boolean isContentDocument(Uri uri
) {
1037 return uri
.toString().startsWith(URI_TYPE_OF_CONTENT_PROVIDER
);
1041 * Pushes a directory to the drop down list
1042 * @param directory to push
1043 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
1045 public void pushDirname(OCFile directory
) {
1046 if(!directory
.isFolder()){
1047 throw new IllegalArgumentException("Only directories may be pushed!");
1049 mDirectories
.insert(directory
.getFileName(), 0);
1054 * Pops a directory name from the drop down list
1055 * @return True, unless the stack is empty
1057 public boolean popDirname() {
1058 mDirectories
.remove(mDirectories
.getItem(0));
1059 return !mDirectories
.isEmpty();
1062 // Custom array adapter to override text colors
1063 private class CustomArrayAdapter
<T
> extends ArrayAdapter
<T
> {
1065 public CustomArrayAdapter(FileDisplayActivity ctx
, int view
) {
1069 public View
getView(int position
, View convertView
, ViewGroup parent
) {
1070 View v
= super.getView(position
, convertView
, parent
);
1072 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1073 android
.R
.color
.white
));
1075 fixRoot((TextView
) v
);
1079 public View
getDropDownView(int position
, View convertView
,
1081 View v
= super.getDropDownView(position
, convertView
, parent
);
1083 ((TextView
) v
).setTextColor(getResources().getColorStateList(
1084 android
.R
.color
.white
));
1086 fixRoot((TextView
) v
);
1090 private void fixRoot(TextView v
) {
1091 if (v
.getText().equals(OCFile
.PATH_SEPARATOR
)) {
1092 v
.setText(R
.string
.default_display_name_for_root_folder
);
1098 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
1101 * {@link BroadcastReceiver} to enable syncing feedback in UI
1104 public void onReceive(Context context
, Intent intent
) {
1106 String event
= intent
.getAction();
1107 Log_OC
.d(TAG
, "Received broadcast " + event
);
1108 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
1109 String synchFolderRemotePath
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
1110 RemoteOperationResult synchResult
= (RemoteOperationResult
)intent
.getSerializableExtra(FileSyncAdapter
.EXTRA_RESULT
);
1111 boolean sameAccount
= (getAccount() != null
&& accountName
.equals(getAccount().name
) && getStorageManager() != null
);
1115 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
1116 mSyncInProgress
= true
;
1119 OCFile currentFile
= (getFile() == null
) ? null
: getStorageManager().getFileByPath(getFile().getRemotePath());
1120 OCFile currentDir
= (getCurrentDir() == null
) ? null
: getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
1122 if (currentDir
== null
) {
1123 // current folder was removed from the server
1124 Toast
.makeText( FileDisplayActivity
.this,
1125 String
.format(getString(R
.string
.sync_current_folder_was_removed
), mDirectories
.getItem(0)),
1131 if (currentFile
== null
&& !getFile().isFolder()) {
1132 // currently selected file was removed in the server, and now we know it
1133 cleanSecondFragment();
1134 currentFile
= currentDir
;
1137 if (synchFolderRemotePath
!= null
&& currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1138 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1139 if (fileListFragment
!= null
) {
1140 fileListFragment
.listDirectory(currentDir
);
1143 setFile(currentFile
);
1146 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) && !SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
.equals(event
));
1148 if (SynchronizeFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1150 /// TODO refactor and make common
1151 synchResult
!= null
&& !synchResult
.isSuccess() &&
1152 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1153 synchResult
.isIdPRedirection() ||
1154 (synchResult
.isException() && synchResult
.getException()
1155 instanceof AuthenticatorException
))) {
1157 OwnCloudClient client
= null
;
1159 OwnCloudAccount ocAccount
=
1160 new OwnCloudAccount(getAccount(), context
);
1161 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1162 removeClientFor(ocAccount
));
1163 // TODO get rid of these exceptions
1164 } catch (AccountNotFoundException e
) {
1165 e
.printStackTrace();
1166 } catch (AuthenticatorException e
) {
1167 e
.printStackTrace();
1168 } catch (OperationCanceledException e
) {
1169 e
.printStackTrace();
1170 } catch (IOException e
) {
1171 e
.printStackTrace();
1174 if (client
!= null
) {
1175 OwnCloudCredentials cred
= client
.getCredentials();
1177 AccountManager am
= AccountManager
.get(context
);
1178 if (cred
.authTokenExpires()) {
1179 am
.invalidateAuthToken(
1184 am
.clearPassword(getAccount());
1189 requestCredentialsUpdate();
1193 removeStickyBroadcast(intent
);
1194 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1195 setSupportProgressBarIndeterminateVisibility(mSyncInProgress
/*|| mRefreshSharesInProgress*/);
1197 setBackgroundText();
1201 if (synchResult
!= null
) {
1202 if (synchResult
.getCode().equals(RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1203 mLastSslUntrustedServerResult
= synchResult
;
1206 } catch (RuntimeException e
) {
1207 // avoid app crashes after changing the serial id of RemoteOperationResult
1208 // in owncloud library with broadcast notifications pending to process
1209 removeStickyBroadcast(intent
);
1215 * Show a text message on screen view for notifying user if content is
1216 * loading or folder is empty
1218 private void setBackgroundText() {
1219 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1220 if (ocFileListFragment
!= null
) {
1221 int message
= R
.string
.file_list_loading
;
1222 if (!mSyncInProgress
) {
1223 // In case file list is empty
1224 message
= R
.string
.file_list_empty
;
1226 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1228 Log_OC
.e(TAG
, "OCFileListFragment is null");
1233 * Once the file upload has finished -> update view
1235 private class UploadFinishReceiver
extends BroadcastReceiver
{
1237 * Once the file upload has finished -> update view
1238 * @author David A. Velasco
1239 * {@link BroadcastReceiver} to enable upload feedback in UI
1242 public void onReceive(Context context
, Intent intent
) {
1244 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1245 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1246 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1247 OCFile currentDir
= getCurrentDir();
1248 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1249 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1251 if (sameAccount
&& isDescendant
) {
1252 refreshListOfFilesFragment();
1255 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
1256 boolean renamedInUpload
= getFile().getRemotePath().
1257 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1258 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1260 FileFragment details
= getSecondFragment();
1261 boolean detailFragmentIsShown
= (details
!= null
&&
1262 details
instanceof FileDetailFragment
);
1264 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1265 if (uploadWasFine
) {
1266 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1268 if (renamedInUpload
) {
1269 String newName
= (new File(uploadedRemotePath
)).getName();
1270 Toast msg
= Toast
.makeText(
1273 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1278 if (uploadWasFine
|| getFile().fileExists()) {
1279 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1281 cleanSecondFragment();
1284 // Force the preview if the file is an image
1285 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1286 startImagePreview(getFile());
1287 } // TODO what about other kind of previews?
1291 if (intent
!= null
) {
1292 removeStickyBroadcast(intent
);
1302 * Class waiting for broadcast events from the {@link FielDownloader} service.
1304 * Updates the UI when a download is started or finished, provided that it is relevant for the
1307 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1309 public void onReceive(Context context
, Intent intent
) {
1311 boolean sameAccount
= isSameAccount(context
, intent
);
1312 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1313 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1315 if (sameAccount
&& isDescendant
) {
1316 refreshListOfFilesFragment();
1317 refreshSecondFragment(intent
.getAction(), downloadedRemotePath
, intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
));
1320 if (mWaitingToSend
!= null
) {
1321 mWaitingToSend
= getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath()); // Update the file to send
1322 if (mWaitingToSend
.isDown()) {
1323 sendDownloadedFile();
1328 if (intent
!= null
) {
1329 removeStickyBroadcast(intent
);
1334 private boolean isDescendant(String downloadedRemotePath
) {
1335 OCFile currentDir
= getCurrentDir();
1336 return (currentDir
!= null
&& downloadedRemotePath
!= null
&& downloadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1339 private boolean isSameAccount(Context context
, Intent intent
) {
1340 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1341 return (accountName
!= null
&& getAccount() != null
&& accountName
.equals(getAccount().name
));
1346 public void browseToRoot() {
1347 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1348 if (listOfFiles
!= null
) { // should never be null, indeed
1349 while (mDirectories
.getCount() > 1) {
1352 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1353 listOfFiles
.listDirectory(root
);
1354 setFile(listOfFiles
.getCurrentFile());
1355 startSyncFolderOperation(root
, false
);
1357 cleanSecondFragment();
1361 public void browseTo(OCFile folder
) {
1362 if (folder
== null
|| !folder
.isFolder()) {
1363 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder
);
1365 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1366 if (listOfFiles
!= null
) {
1367 setNavigationListWithFolder(folder
);
1368 listOfFiles
.listDirectory(folder
);
1369 setFile(listOfFiles
.getCurrentFile());
1370 startSyncFolderOperation(folder
, false
);
1372 Log_OC
.e(TAG
, "Unexpected null when accessing list fragment");
1374 cleanSecondFragment();
1381 * Updates action bar and second fragment, if in dual pane mode.
1384 public void onBrowsedDownTo(OCFile directory
) {
1385 pushDirname(directory
);
1386 cleanSecondFragment();
1389 startSyncFolderOperation(directory
, false
);
1394 * Shows the information of the {@link OCFile} received as a
1395 * parameter in the second fragment.
1397 * @param file {@link OCFile} whose details will be shown
1400 public void showDetails(OCFile file
) {
1401 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1402 setSecondFragment(detailFragment
);
1403 updateFragmentsVisibility(true
);
1404 updateNavigationElementsInActionBar(file
);
1412 private void updateNavigationElementsInActionBar(OCFile chosenFile
) {
1413 ActionBar actionBar
= getSupportActionBar();
1414 if (chosenFile
== null
|| mDualPane
) {
1415 // only list of files - set for browsing through folders
1416 OCFile currentDir
= getCurrentDir();
1417 boolean noRoot
= (currentDir
!= null
&& currentDir
.getParentId() != 0);
1418 actionBar
.setDisplayHomeAsUpEnabled(noRoot
);
1419 actionBar
.setDisplayShowTitleEnabled(!noRoot
);
1421 actionBar
.setTitle(getString(R
.string
.default_display_name_for_root_folder
));
1423 actionBar
.setNavigationMode(!noRoot ? ActionBar
.NAVIGATION_MODE_STANDARD
: ActionBar
.NAVIGATION_MODE_LIST
);
1424 actionBar
.setListNavigationCallbacks(mDirectories
, this); // assuming mDirectories is updated
1427 actionBar
.setDisplayHomeAsUpEnabled(true
);
1428 actionBar
.setDisplayShowTitleEnabled(true
);
1429 actionBar
.setTitle(chosenFile
.getFileName());
1430 actionBar
.setNavigationMode(ActionBar
.NAVIGATION_MODE_STANDARD
);
1436 protected ServiceConnection
newTransferenceServiceConnection() {
1437 return new ListServiceConnection();
1440 /** Defines callbacks for service binding, passed to bindService() */
1441 private class ListServiceConnection
implements ServiceConnection
{
1444 public void onServiceConnected(ComponentName component
, IBinder service
) {
1445 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1446 Log_OC
.d(TAG
, "Download service connected");
1447 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1448 if (mWaitingToPreview
!= null
)
1449 if (getStorageManager() != null
) {
1450 mWaitingToPreview
= getStorageManager().getFileById(mWaitingToPreview
.getFileId()); // update the file
1451 if (!mWaitingToPreview
.isDown()) {
1452 requestForDownload();
1456 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1457 Log_OC
.d(TAG
, "Upload service connected");
1458 mUploaderBinder
= (FileUploaderBinder
) service
;
1462 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1463 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1464 if (listOfFiles
!= null
) {
1465 listOfFiles
.listDirectory();
1467 FileFragment secondFragment
= getSecondFragment();
1468 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1469 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1470 detailFragment
.listenForTransferProgress();
1471 detailFragment
.updateFileDetails(false
, false
);
1476 public void onServiceDisconnected(ComponentName component
) {
1477 if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileDownloader
.class))) {
1478 Log_OC
.d(TAG
, "Download service disconnected");
1479 mDownloaderBinder
= null
;
1480 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this, FileUploader
.class))) {
1481 Log_OC
.d(TAG
, "Upload service disconnected");
1482 mUploaderBinder
= null
;
1490 * Launch an intent to request the PIN code to the user before letting him use the app
1492 private void requestPinCode() {
1493 boolean pinStart
= false
;
1494 SharedPreferences appPrefs
= PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
1495 pinStart
= appPrefs
.getBoolean("set_pincode", false
);
1497 Intent i
= new Intent(getApplicationContext(), PinCodeActivity
.class);
1498 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "FileDisplayActivity");
1505 public void onSavedCertificate() {
1506 startSyncFolderOperation(getCurrentDir(), false
);
1511 public void onFailedSavingCertificate() {
1512 showDialog(DIALOG_CERT_NOT_SAVED
);
1516 public void onCancelCertificate() {
1521 * Updates the view associated to the activity after the finish of some operation over files
1522 * in the current account.
1524 * @param operation Removal operation performed.
1525 * @param result Result of the removal.
1528 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1529 super.onRemoteOperationFinish(operation
, result
);
1531 if (operation
instanceof RemoveFileOperation
) {
1532 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1534 } else if (operation
instanceof RenameFileOperation
) {
1535 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1537 } else if (operation
instanceof SynchronizeFileOperation
) {
1538 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1540 } else if (operation
instanceof CreateFolderOperation
) {
1541 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1543 } else if (operation
instanceof CreateShareOperation
) {
1544 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1546 } else if (operation
instanceof UnshareLinkOperation
) {
1547 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1549 } else if (operation
instanceof MoveFileOperation
) {
1550 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1556 private void onCreateShareOperationFinish(CreateShareOperation operation
, RemoteOperationResult result
) {
1557 if (result
.isSuccess()) {
1558 refreshShowDetails();
1559 refreshListOfFilesFragment();
1564 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
, RemoteOperationResult result
) {
1565 if (result
.isSuccess()) {
1566 refreshShowDetails();
1567 refreshListOfFilesFragment();
1569 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1570 cleanSecondFragment();
1571 refreshListOfFilesFragment();
1575 private void refreshShowDetails() {
1576 FileFragment details
= getSecondFragment();
1577 if (details
!= null
) {
1578 OCFile file
= details
.getFile();
1580 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1581 if (details
instanceof PreviewMediaFragment
) {
1582 // Refresh OCFile of the fragment
1583 ((PreviewMediaFragment
) details
).updateFile(file
);
1588 invalidateOptionsMenu();
1593 * Updates the view associated to the activity after the finish of an operation trying to remove a
1596 * @param operation Removal operation performed.
1597 * @param result Result of the removal.
1599 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1600 dismissLoadingDialog();
1602 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1606 if (result
.isSuccess()) {
1607 OCFile removedFile
= operation
.getFile();
1608 FileFragment second
= getSecondFragment();
1609 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1610 if (second
instanceof PreviewMediaFragment
) {
1611 ((PreviewMediaFragment
)second
).stopPreview(true
);
1613 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1614 cleanSecondFragment();
1616 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1617 refreshListOfFilesFragment();
1619 invalidateOptionsMenu();
1621 if (result
.isSslRecoverableException()) {
1622 mLastSslUntrustedServerResult
= result
;
1623 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1630 * Updates the view associated to the activity after the finish of an operation trying to move a
1633 * @param operation Move operation performed.
1634 * @param result Result of the move operation.
1636 private void onMoveFileOperationFinish(MoveFileOperation operation
, RemoteOperationResult result
) {
1637 if (result
.isSuccess()) {
1638 dismissLoadingDialog();
1639 refreshListOfFilesFragment();
1641 dismissLoadingDialog();
1643 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1644 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1648 } catch (NotFoundException e
) {
1649 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1656 * Updates the view associated to the activity after the finish of an operation trying to rename a
1659 * @param operation Renaming operation performed.
1660 * @param result Result of the renaming.
1662 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1663 dismissLoadingDialog();
1664 OCFile renamedFile
= operation
.getFile();
1665 if (result
.isSuccess()) {
1666 FileFragment details
= getSecondFragment();
1667 if (details
!= null
) {
1668 if (details
instanceof FileDetailFragment
&& renamedFile
.equals(details
.getFile()) ) {
1669 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1670 showDetails(renamedFile
);
1672 } else if (details
instanceof PreviewMediaFragment
&& renamedFile
.equals(details
.getFile())) {
1673 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1674 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1675 int position
= ((PreviewMediaFragment
)details
).getPosition();
1676 startMediaPreview(renamedFile
, position
, true
);
1678 getFileOperationsHelper().openFile(renamedFile
);
1683 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())) {
1684 refreshListOfFilesFragment();
1688 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1692 if (result
.isSslRecoverableException()) {
1693 mLastSslUntrustedServerResult
= result
;
1694 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1699 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1700 dismissLoadingDialog();
1701 OCFile syncedFile
= operation
.getLocalFile();
1702 if (!result
.isSuccess()) {
1703 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1704 Intent i
= new Intent(this, ConflictsResolveActivity
.class);
1705 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, syncedFile
);
1706 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, getAccount());
1712 if (operation
.transferWasRequested()) {
1713 onTransferStateChanged(syncedFile
, true
, true
);
1716 Toast msg
= Toast
.makeText(this, ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1724 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1726 * @param operation Creation operation performed.
1727 * @param result Result of the creation.
1729 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
1730 if (result
.isSuccess()) {
1731 dismissLoadingDialog();
1732 refreshListOfFilesFragment();
1734 dismissLoadingDialog();
1736 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1737 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1741 } catch (NotFoundException e
) {
1742 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1752 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1753 refreshListOfFilesFragment();
1754 FileFragment details
= getSecondFragment();
1755 if (details
!= null
&& details
instanceof FileDetailFragment
&& file
.equals(details
.getFile()) ) {
1756 if (downloading
|| uploading
) {
1757 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1759 if (!file
.fileExists()) {
1760 cleanSecondFragment();
1762 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1770 private void requestForDownload() {
1771 Account account
= getAccount();
1772 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1773 Intent i
= new Intent(this, FileDownloader
.class);
1774 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1775 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1781 private OCFile
getCurrentDir() {
1782 OCFile file
= getFile();
1784 if (file
.isFolder()) {
1786 } else if (getStorageManager() != null
) {
1787 String parentPath
= file
.getRemotePath().substring(0, file
.getRemotePath().lastIndexOf(file
.getFileName()));
1788 return getStorageManager().getFileByPath(parentPath
);
1794 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1795 long currentSyncTime
= System
.currentTimeMillis();
1797 mSyncInProgress
= true
;
1799 // perform folder synchronization
1800 RemoteOperation synchFolderOp
= new SynchronizeFolderOperation( folder
,
1803 getFileOperationsHelper().isSharedSupported(),
1805 getStorageManager(),
1807 getApplicationContext()
1809 synchFolderOp
.execute(getAccount(), this, null
, null
);
1811 setSupportProgressBarIndeterminateVisibility(true
);
1813 setBackgroundText();
1817 * Show untrusted cert dialog
1819 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1820 // Show a dialog with the certificate info
1821 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1822 FragmentManager fm
= getSupportFragmentManager();
1823 FragmentTransaction ft
= fm
.beginTransaction();
1824 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1827 private void requestForDownload(OCFile file
) {
1828 Account account
= getAccount();
1829 if (!mDownloaderBinder
.isDownloading(account
, file
)) {
1830 Intent i
= new Intent(this, FileDownloader
.class);
1831 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1832 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1837 private void sendDownloadedFile(){
1838 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1839 mWaitingToSend
= null
;
1844 * Requests the download of the received {@link OCFile} , updates the UI
1845 * to monitor the download progress and prepares the activity to send the file
1846 * when the download finishes.
1848 * @param file {@link OCFile} to download and preview.
1850 public void startDownloadForSending(OCFile file
) {
1851 mWaitingToSend
= file
;
1852 requestForDownload(mWaitingToSend
);
1853 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1854 updateFragmentsVisibility(hasSecondFragment
);
1858 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1860 * @param file Image {@link OCFile} to show.
1862 public void startImagePreview(OCFile file
) {
1863 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1864 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1865 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1866 startActivity(showDetailsIntent
);
1871 * Stars the preview of an already down media {@link OCFile}.
1873 * @param file Media {@link OCFile} to preview.
1874 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1875 * @param autoplay When 'true', the playback will start without user interactions.
1877 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1878 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
, autoplay
);
1879 setSecondFragment(mediaFragment
);
1880 updateFragmentsVisibility(true
);
1881 updateNavigationElementsInActionBar(file
);
1886 * Requests the download of the received {@link OCFile} , updates the UI
1887 * to monitor the download progress and prepares the activity to preview
1888 * or open the file when the download finishes.
1890 * @param file {@link OCFile} to download and preview.
1892 public void startDownloadForPreview(OCFile file
) {
1893 Fragment detailFragment
= new FileDetailFragment(file
, getAccount());
1894 setSecondFragment(detailFragment
);
1895 mWaitingToPreview
= file
;
1896 requestForDownload();
1897 updateFragmentsVisibility(true
);
1898 updateNavigationElementsInActionBar(file
);
1903 public void cancelTransference(OCFile file
) {
1904 getFileOperationsHelper().cancelTransference(file
);
1905 if (mWaitingToPreview
!= null
&&
1906 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1907 mWaitingToPreview
= null
;
1909 if (mWaitingToSend
!= null
&&
1910 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1911 mWaitingToSend
= null
;
1913 onTransferStateChanged(file
, false
, false
);
1917 public void onRefresh(boolean ignoreETag
) {
1918 refreshList(ignoreETag
);
1922 public void onRefresh() {
1926 private void refreshList(boolean ignoreETag
) {
1927 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1928 if (listOfFiles
!= null
) {
1929 OCFile folder
= listOfFiles
.getCurrentFile();
1930 if (folder
!= null
) {
1931 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1932 listDirectory(mFile);*/
1933 startSyncFolderOperation(folder
, ignoreETag
);
1938 private void sortByDate(boolean ascending
){
1939 getListOfFilesFragment().sortByDate(ascending
);
1942 private void sortBySize(boolean ascending
){
1943 getListOfFilesFragment().sortBySize(ascending
);
1946 private void sortByName(boolean ascending
){
1947 getListOfFilesFragment().sortByName(ascending
);