2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.support
.v7
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.content
.ContextCompat
;
52 import android
.support
.v4
.view
.GravityCompat
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareViaLinkOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareWithShareeOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.UnshareOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 import com
.owncloud
.android
.utils
.FileStorageUtils
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
117 implements FileFragment
.ContainerActivity
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
128 private ProgressBar mProgressBar
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 public static final int ACTION_MOVE_FILES
= 3;
139 public static final int ACTION_COPY_FILES
= 4;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
151 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
155 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.v(TAG
, "onCreate() start");
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
165 /// grant that FileObserverService is watching favorite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
177 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
192 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
193 mProgressBar
.setIndeterminateDrawable(
194 ContextCompat
.getDrawable(this,
195 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
197 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
198 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
199 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
200 if (savedInstanceState
== null
) {
201 createMinFragments();
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
206 // according to the official
209 // enable ActionBar app icon to behave as action to toggle nav drawer
210 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
211 getSupportActionBar().setHomeButtonEnabled(true
);
213 mProgressBar
.setIndeterminate(mSyncInProgress
);
214 // always AFTER setContentView(...) ; to work around bug in its implementation
218 Log_OC
.v(TAG
, "onCreate() end");
222 protected void onStart() {
223 Log_OC
.v(TAG
, "onStart() start");
225 Log_OC
.v(TAG
, "onStart() end");
229 protected void onStop() {
230 Log_OC
.v(TAG
, "onStop() start");
232 Log_OC
.v(TAG
, "onStop() end");
236 protected void onDestroy() {
237 Log_OC
.v(TAG
, "onDestroy() start");
239 Log_OC
.v(TAG
, "onDestroy() end");
243 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
246 protected void onAccountSet(boolean stateWasRecovered
) {
247 super.onAccountSet(stateWasRecovered
);
248 if (getAccount() != null
) {
249 /// Check whether the 'main' OCFile handled by the Activity is contained in the
251 OCFile file
= getFile();
252 // get parent from path
253 String parentPath
= "";
255 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
256 // upload in progress - right now, files are not inserted in the local
257 // cache until the upload is successful get parent from path
258 parentPath
= file
.getRemotePath().substring(0,
259 file
.getRemotePath().lastIndexOf(file
.getFileName()));
260 if (getStorageManager().getFileByPath(parentPath
) == null
)
261 file
= null
; // not able to know the directory where the file is uploading
263 file
= getStorageManager().getFileByPath(file
.getRemotePath());
264 // currentDir = null if not in the current Account
268 // fall back to root folder
269 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
273 if (mAccountWasSet
) {
274 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
277 if (!stateWasRecovered
) {
278 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
279 initFragmentsWithFile();
280 if (file
.isFolder()) {
281 startSyncFolderOperation(file
, false
);
285 updateFragmentsVisibility(!file
.isFolder());
286 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
291 private void createMinFragments() {
292 OCFileListFragment listOfFiles
= new OCFileListFragment();
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
295 transaction
.commit();
298 private void initFragmentsWithFile() {
299 if (getAccount() != null
&& getFile() != null
) {
301 OCFileListFragment listOfFiles
= getListOfFilesFragment();
302 if (listOfFiles
!= null
) {
303 listOfFiles
.listDirectory(getCurrentDir());
304 // TODO Enable when "On Device" is recovered
305 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
308 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
312 OCFile file
= getFile();
313 Fragment secondFragment
= chooseInitialSecondFragment(file
);
314 if (secondFragment
!= null
) {
315 setSecondFragment(secondFragment
);
316 updateFragmentsVisibility(true
);
317 updateActionBarTitleAndHomeButton(file
);
320 cleanSecondFragment();
321 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
322 startTextPreview(file
);
326 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
327 if (getAccount() == null
) {
328 Log_OC
.wtf(TAG
, "\t account is NULL");
330 if (getFile() == null
) {
331 Log_OC
.wtf(TAG
, "\t file is NULL");
336 private Fragment
chooseInitialSecondFragment(OCFile file
) {
337 Fragment secondFragment
= null
;
338 if (file
!= null
&& !file
.isFolder()) {
339 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
340 && file
.getLastSyncDateForProperties() > 0 // temporal fix
342 int startPlaybackPosition
=
343 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
345 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
346 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
347 startPlaybackPosition
, autoplay
);
349 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
350 secondFragment
= null
;
352 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
355 return secondFragment
;
360 * Replaces the second fragment managed by the activity with the received as
363 * Assumes never will be more than two fragments managed at the same time.
365 * @param fragment New second Fragment to set.
367 private void setSecondFragment(Fragment fragment
) {
368 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
369 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
370 transaction
.commit();
374 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
376 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
379 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
380 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
383 } else if (existsSecondFragment
) {
384 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
385 mLeftFragmentContainer
.setVisibility(View
.GONE
);
387 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
388 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
392 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
393 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
395 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
396 mRightFragmentContainer
.setVisibility(View
.GONE
);
402 private OCFileListFragment
getListOfFilesFragment() {
403 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
404 FileDisplayActivity
.TAG_LIST_OF_FILES
);
405 if (listOfFiles
!= null
) {
406 return (OCFileListFragment
) listOfFiles
;
408 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
412 public FileFragment
getSecondFragment() {
413 Fragment second
= getSupportFragmentManager().findFragmentByTag(
414 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
415 if (second
!= null
) {
416 return (FileFragment
) second
;
421 protected void cleanSecondFragment() {
422 Fragment second
= getSecondFragment();
423 if (second
!= null
) {
424 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
428 updateFragmentsVisibility(false
);
429 updateActionBarTitleAndHomeButton(null
);
432 protected void refreshListOfFilesFragment() {
433 OCFileListFragment fileListFragment
= getListOfFilesFragment();
434 if (fileListFragment
!= null
) {
435 fileListFragment
.listDirectory();
436 // TODO Enable when "On Device" is recovered ?
437 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
441 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
443 FileFragment secondFragment
= getSecondFragment();
444 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
445 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
446 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
447 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
448 OCFile fileInFragment
= detailsFragment
.getFile();
449 if (fileInFragment
!= null
&&
450 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
451 // the user browsed to other file ; forget the automatic preview
452 mWaitingToPreview
= null
;
454 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
455 // grant that the right panel updates the progress bar
456 detailsFragment
.listenForTransferProgress();
457 detailsFragment
.updateFileDetails(true
, false
);
459 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
460 // update the right panel
461 boolean detailsFragmentChanged
= false
;
464 mWaitingToPreview
= getStorageManager().getFileById(
465 mWaitingToPreview
.getFileId()); // update the file from database,
466 // for the local storage path
467 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
468 startMediaPreview(mWaitingToPreview
, 0, true
);
469 detailsFragmentChanged
= true
;
470 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
471 startTextPreview(mWaitingToPreview
);
472 detailsFragmentChanged
= true
;
474 getFileOperationsHelper().openFile(mWaitingToPreview
);
477 mWaitingToPreview
= null
;
479 if (!detailsFragmentChanged
) {
480 detailsFragment
.updateFileDetails(false
, (success
));
487 public boolean onPrepareOptionsMenu(Menu menu
) {
488 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
489 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
491 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
492 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
494 return super.onPrepareOptionsMenu(menu
);
498 public boolean onCreateOptionsMenu(Menu menu
) {
499 MenuInflater inflater
= getMenuInflater();
500 inflater
.inflate(R
.menu
.main_menu
, menu
);
506 public boolean onOptionsItemSelected(MenuItem item
) {
507 boolean retval
= true
;
508 switch (item
.getItemId()) {
509 case R
.id
.action_create_dir
: {
510 CreateFolderDialogFragment dialog
=
511 CreateFolderDialogFragment
.newInstance(getCurrentDir());
512 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
516 case R
.id
.action_sync_account
: {
517 startSynchronization();
520 case R
.id
.action_upload
: {
521 UploadSourceDialogFragment dialog
=
522 UploadSourceDialogFragment
.newInstance(getAccount());
523 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
526 case android
.R
.id
.home
: {
527 FileFragment second
= getSecondFragment();
528 OCFile currentDir
= getCurrentDir();
529 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
530 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
531 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
532 (second
!= null
&& second
.getFile() != null
)) {
536 mDrawerLayout
.openDrawer(GravityCompat
.START
);
540 case R
.id
.action_sort
: {
541 SharedPreferences appPreferences
= PreferenceManager
542 .getDefaultSharedPreferences(this);
544 // Read sorting order, default to sort by name ascending
545 Integer sortOrder
= appPreferences
546 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
548 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
549 builder
.setTitle(R
.string
.actionbar_sort_title
)
550 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
551 new DialogInterface
.OnClickListener() {
552 public void onClick(DialogInterface dialog
, int which
) {
565 builder
.create().show();
569 retval
= super.onOptionsItemSelected(item
);
574 private void startSynchronization() {
575 Log_OC
.d(TAG
, "Got to start sync");
576 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
577 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
578 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
579 // cancel the current synchronizations of any ownCloud account
580 Bundle bundle
= new Bundle();
581 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
582 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
583 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
584 MainApp
.getAuthority());
585 ContentResolver
.requestSync(
587 MainApp
.getAuthority(), bundle
);
589 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
590 MainApp
.getAuthority() + " with new API");
591 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
592 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
593 builder
.setExpedited(true
);
594 builder
.setManual(true
);
597 // Fix bug in Android Lollipop when you click on refresh the whole account
598 Bundle extras
= new Bundle();
599 builder
.setExtras(extras
);
601 SyncRequest request
= builder
.build();
602 ContentResolver
.requestSync(request
);
607 * Called, when the user selected something for uploading
610 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
612 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
614 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
615 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
616 //getClipData is only supported on api level 16+, Jelly Bean
617 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
618 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
619 Intent intent
= new Intent();
620 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
621 requestSimpleUpload(intent
, resultCode
);
624 requestSimpleUpload(data
, resultCode
);
626 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
627 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
628 requestMultipleUpload(data
, resultCode
);
630 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
631 final Intent fData
= data
;
632 final int fResultCode
= resultCode
;
633 getHandler().postDelayed(
637 requestMoveOperation(fData
, fResultCode
);
640 DELAY_TO_REQUEST_OPERATIONS_LATER
643 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
645 final Intent fData
= data
;
646 final int fResultCode
= resultCode
;
647 getHandler().postDelayed(
651 requestCopyOperation(fData
, fResultCode
);
654 DELAY_TO_REQUEST_OPERATIONS_LATER
658 super.onActivityResult(requestCode
, resultCode
, data
);
663 private void requestMultipleUpload(Intent data
, int resultCode
) {
664 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
665 if (filePaths
!= null
) {
666 String
[] remotePaths
= new String
[filePaths
.length
];
667 String remotePathBase
= getCurrentDir().getRemotePath();
668 for (int j
= 0; j
< remotePaths
.length
; j
++) {
669 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
672 Intent i
= new Intent(this, FileUploader
.class);
673 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
674 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
675 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
676 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
677 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
678 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
682 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
683 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
691 private void requestSimpleUpload(Intent data
, int resultCode
) {
692 String filePath
= null
;
693 String mimeType
= null
;
695 Uri selectedImageUri
= data
.getData();
698 mimeType
= getContentResolver().getType(selectedImageUri
);
700 String fileManagerString
= selectedImageUri
.getPath();
701 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
703 if (selectedImagePath
!= null
)
704 filePath
= selectedImagePath
;
706 filePath
= fileManagerString
;
708 } catch (Exception e
) {
709 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
710 "Intent.ACTION_GET_CONTENT", e
);
713 if (filePath
== null
) {
714 Log_OC
.e(TAG
, "Couldn't resolve path to file");
715 Toast t
= Toast
.makeText(
716 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
724 Intent i
= new Intent(this, FileUploader
.class);
725 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
726 OCFile currentDir
= getCurrentDir();
727 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
729 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
730 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
732 if (cursor
!= null
&& cursor
.moveToFirst()) {
733 String displayName
= cursor
.getString(cursor
.getColumnIndex(
734 OpenableColumns
.DISPLAY_NAME
));
735 Log_OC
.v(TAG
, "Display Name: " + displayName
);
737 displayName
.replace(File
.separatorChar
, '_');
738 displayName
.replace(File
.pathSeparatorChar
, '_');
739 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
742 // and what happens in case of error?; wrong target name for the upload
748 remotePath
+= new File(filePath
).getName();
751 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
752 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
753 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
754 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
755 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
756 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
761 * Request the operation for moving the file/folder from one path to another
763 * @param data Intent received
764 * @param resultCode Result code received
766 private void requestMoveOperation(Intent data
, int resultCode
) {
767 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
768 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
769 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
773 * Request the operation for copying the file/folder from one path to another
775 * @param data Intent received
776 * @param resultCode Result code received
778 private void requestCopyOperation(Intent data
, int resultCode
) {
779 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
780 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
781 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
785 public void onBackPressed() {
786 if (!isDrawerOpen()){
787 OCFileListFragment listOfFiles
= getListOfFilesFragment();
788 if (mDualPane
|| getSecondFragment() == null
) {
789 OCFile currentDir
= getCurrentDir();
790 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
794 if (listOfFiles
!= null
) { // should never be null, indeed
795 listOfFiles
.onBrowseUp();
798 if (listOfFiles
!= null
) { // should never be null, indeed
799 setFile(listOfFiles
.getCurrentFile());
801 cleanSecondFragment();
803 super.onBackPressed();
808 protected void onSaveInstanceState(Bundle outState
) {
809 // responsibility of restore is preferred in onCreate() before than in
810 // onRestoreInstanceState when there are Fragments involved
811 Log_OC
.v(TAG
, "onSaveInstanceState() start");
812 super.onSaveInstanceState(outState
);
813 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
814 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
815 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
816 // mRefreshSharesInProgress);
817 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
819 Log_OC
.v(TAG
, "onSaveInstanceState() end");
824 protected void onResume() {
825 Log_OC
.v(TAG
, "onResume() start");
827 // refresh Navigation Drawer account list
828 mNavigationDrawerAdapter
.updateAccountList();
830 // refresh list of files
831 refreshListOfFilesFragment();
833 // Listen for sync messages
834 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
835 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
836 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
837 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
838 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
839 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
840 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
841 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
842 // syncIntentFilter);
844 // Listen for upload messages
845 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
846 mUploadFinishReceiver
= new UploadFinishReceiver();
847 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
849 // Listen for download messages
850 IntentFilter downloadIntentFilter
= new IntentFilter(
851 FileDownloader
.getDownloadAddedMessage());
852 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
853 mDownloadFinishReceiver
= new DownloadFinishReceiver();
854 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
856 Log_OC
.v(TAG
, "onResume() end");
862 protected void onPause() {
863 Log_OC
.v(TAG
, "onPause() start");
864 if (mSyncBroadcastReceiver
!= null
) {
865 unregisterReceiver(mSyncBroadcastReceiver
);
866 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
867 mSyncBroadcastReceiver
= null
;
869 if (mUploadFinishReceiver
!= null
) {
870 unregisterReceiver(mUploadFinishReceiver
);
871 mUploadFinishReceiver
= null
;
873 if (mDownloadFinishReceiver
!= null
) {
874 unregisterReceiver(mDownloadFinishReceiver
);
875 mDownloadFinishReceiver
= null
;
879 Log_OC
.v(TAG
, "onPause() end");
883 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
886 * {@link BroadcastReceiver} to enable syncing feedback in UI
889 public void onReceive(Context context
, Intent intent
) {
891 String event
= intent
.getAction();
892 Log_OC
.d(TAG
, "Received broadcast " + event
);
893 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
894 String synchFolderRemotePath
=
895 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
896 RemoteOperationResult synchResult
=
897 (RemoteOperationResult
)intent
.getSerializableExtra(
898 FileSyncAdapter
.EXTRA_RESULT
);
899 boolean sameAccount
= (getAccount() != null
&&
900 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
904 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
905 mSyncInProgress
= true
;
908 OCFile currentFile
= (getFile() == null
) ? null
:
909 getStorageManager().getFileByPath(getFile().getRemotePath());
910 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
911 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
913 if (currentDir
== null
) {
914 // current folder was removed from the server
915 Toast
.makeText( FileDisplayActivity
.this,
918 sync_current_folder_was_removed
),
919 synchFolderRemotePath
),
926 if (currentFile
== null
&& !getFile().isFolder()) {
927 // currently selected file was removed in the server, and now we
929 cleanSecondFragment();
930 currentFile
= currentDir
;
933 if (synchFolderRemotePath
!= null
&&
934 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
935 OCFileListFragment fileListFragment
= getListOfFilesFragment();
936 if (fileListFragment
!= null
) {
937 fileListFragment
.listDirectory();
938 // TODO Enable when "On Device" is recovered ?
939 // fileListFragment.listDirectory(currentDir,
940 // MainApp.getOnlyOnDevice());
943 setFile(currentFile
);
946 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
947 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
950 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
951 equals(event
) &&/// TODO refactor and make common
953 synchResult
!= null
&& !synchResult
.isSuccess() &&
954 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
955 synchResult
.isIdPRedirection() ||
956 (synchResult
.isException() && synchResult
.getException()
957 instanceof AuthenticatorException
))) {
961 OwnCloudClient client
;
962 OwnCloudAccount ocAccount
=
963 new OwnCloudAccount(getAccount(), context
);
964 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
965 removeClientFor(ocAccount
));
966 if (client
!= null
) {
967 OwnCloudCredentials cred
= client
.getCredentials();
969 AccountManager am
= AccountManager
.get(context
);
970 if (cred
.authTokenExpires()) {
971 am
.invalidateAuthToken(
976 am
.clearPassword(getAccount());
980 requestCredentialsUpdate();
982 } catch (AccountNotFoundException e
) {
983 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
989 removeStickyBroadcast(intent
);
990 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
991 mProgressBar
.setIndeterminate(mSyncInProgress
);
992 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
993 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
994 /*|| mRefreshSharesInProgress*/ //);
1000 if (synchResult
!= null
) {
1001 if (synchResult
.getCode().equals(
1002 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1003 mLastSslUntrustedServerResult
= synchResult
;
1006 } catch (RuntimeException e
) {
1007 // avoid app crashes after changing the serial id of RemoteOperationResult
1008 // in owncloud library with broadcast notifications pending to process
1009 removeStickyBroadcast(intent
);
1015 * Show a text message on screen view for notifying user if content is
1016 * loading or folder is empty
1018 private void setBackgroundText() {
1019 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1020 if (ocFileListFragment
!= null
) {
1021 int message
= R
.string
.file_list_loading
;
1022 if (!mSyncInProgress
) {
1023 // In case file list is empty
1024 message
= R
.string
.file_list_empty
;
1026 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1028 Log_OC
.e(TAG
, "OCFileListFragment is null");
1033 * Once the file upload has finished -> update view
1035 private class UploadFinishReceiver
extends BroadcastReceiver
{
1037 * Once the file upload has finished -> update view
1039 * @author David A. Velasco
1040 * {@link BroadcastReceiver} to enable upload feedback in UI
1043 public void onReceive(Context context
, Intent intent
) {
1045 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1046 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1047 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1048 OCFile currentDir
= getCurrentDir();
1049 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1050 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1052 if (sameAccount
&& isDescendant
) {
1053 String linkedToRemotePath
=
1054 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1055 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1056 refreshListOfFilesFragment();
1060 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1062 boolean renamedInUpload
= getFile().getRemotePath().
1063 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1064 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1066 FileFragment details
= getSecondFragment();
1067 boolean detailFragmentIsShown
= (details
!= null
&&
1068 details
instanceof FileDetailFragment
);
1070 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1071 if (uploadWasFine
) {
1072 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1074 if (renamedInUpload
) {
1075 String newName
= (new File(uploadedRemotePath
)).getName();
1076 Toast msg
= Toast
.makeText(
1079 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1084 if (uploadWasFine
|| getFile().fileExists()) {
1085 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1087 cleanSecondFragment();
1090 // Force the preview if the file is an image or text file
1091 if (uploadWasFine
) {
1092 OCFile ocFile
= getFile();
1093 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1094 startImagePreview(getFile());
1095 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1096 startTextPreview(ocFile
);
1097 // TODO what about other kind of previews?
1101 mProgressBar
.setIndeterminate(false
);
1103 if (intent
!= null
) {
1104 removeStickyBroadcast(intent
);
1110 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1111 private boolean isAscendant(String linkedToRemotePath
) {
1112 OCFile currentDir
= getCurrentDir();
1114 currentDir
!= null
&&
1115 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1124 * Class waiting for broadcast events from the {@link FileDownloader} service.
1126 * Updates the UI when a download is started or finished, provided that it is relevant for the
1129 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1132 public void onReceive(Context context
, Intent intent
) {
1134 boolean sameAccount
= isSameAccount(intent
);
1135 String downloadedRemotePath
=
1136 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1137 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1139 if (sameAccount
&& isDescendant
) {
1140 String linkedToRemotePath
=
1141 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1142 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1143 refreshListOfFilesFragment();
1145 refreshSecondFragment(
1147 downloadedRemotePath
,
1148 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1152 if (mWaitingToSend
!= null
) {
1154 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1155 if (mWaitingToSend
.isDown()) {
1156 sendDownloadedFile();
1161 if (intent
!= null
) {
1162 removeStickyBroadcast(intent
);
1167 private boolean isDescendant(String downloadedRemotePath
) {
1168 OCFile currentDir
= getCurrentDir();
1170 currentDir
!= null
&&
1171 downloadedRemotePath
!= null
&&
1172 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1176 private boolean isAscendant(String linkedToRemotePath
) {
1177 OCFile currentDir
= getCurrentDir();
1179 currentDir
!= null
&&
1180 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1184 private boolean isSameAccount(Intent intent
) {
1185 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1186 return (accountName
!= null
&& getAccount() != null
&&
1187 accountName
.equals(getAccount().name
));
1192 public void browseToRoot() {
1193 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1194 if (listOfFiles
!= null
) { // should never be null, indeed
1195 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1196 listOfFiles
.listDirectory(root
);
1197 // TODO Enable when "On Device" is recovered ?
1198 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1199 setFile(listOfFiles
.getCurrentFile());
1200 startSyncFolderOperation(root
, false
);
1202 cleanSecondFragment();
1209 * Updates action bar and second fragment, if in dual pane mode.
1212 public void onBrowsedDownTo(OCFile directory
) {
1214 cleanSecondFragment();
1216 startSyncFolderOperation(directory
, false
);
1220 * Shows the information of the {@link OCFile} received as a
1221 * parameter in the second fragment.
1223 * @param file {@link OCFile} whose details will be shown
1226 public void showDetails(OCFile file
) {
1227 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1228 setSecondFragment(detailFragment
);
1229 updateFragmentsVisibility(true
);
1230 updateActionBarTitleAndHomeButton(file
);
1235 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1237 // in dual pane mode, keep the focus of title an action bar in the current folder
1238 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1241 super.updateActionBarTitleAndHomeButton(chosenFile
);
1247 protected ServiceConnection
newTransferenceServiceConnection() {
1248 return new ListServiceConnection();
1252 * Defines callbacks for service binding, passed to bindService()
1254 private class ListServiceConnection
implements ServiceConnection
{
1257 public void onServiceConnected(ComponentName component
, IBinder service
) {
1258 if (component
.equals(new ComponentName(
1259 FileDisplayActivity
.this, FileDownloader
.class))) {
1260 Log_OC
.d(TAG
, "Download service connected");
1261 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1262 if (mWaitingToPreview
!= null
)
1263 if (getStorageManager() != null
) {
1266 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1267 if (!mWaitingToPreview
.isDown()) {
1268 requestForDownload();
1272 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1273 FileUploader
.class))) {
1274 Log_OC
.d(TAG
, "Upload service connected");
1275 mUploaderBinder
= (FileUploaderBinder
) service
;
1279 // a new chance to get the mDownloadBinder through
1280 // getFileDownloadBinder() - THIS IS A MESS
1281 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1282 if (listOfFiles
!= null
) {
1283 listOfFiles
.listDirectory();
1284 // TODO Enable when "On Device" is recovered ?
1285 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1287 FileFragment secondFragment
= getSecondFragment();
1288 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1289 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1290 detailFragment
.listenForTransferProgress();
1291 detailFragment
.updateFileDetails(false
, false
);
1296 public void onServiceDisconnected(ComponentName component
) {
1297 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1298 FileDownloader
.class))) {
1299 Log_OC
.d(TAG
, "Download service disconnected");
1300 mDownloaderBinder
= null
;
1301 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1302 FileUploader
.class))) {
1303 Log_OC
.d(TAG
, "Upload service disconnected");
1304 mUploaderBinder
= null
;
1310 public void onSavedCertificate() {
1311 startSyncFolderOperation(getCurrentDir(), false
);
1316 public void onFailedSavingCertificate() {
1317 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1318 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1320 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1324 public void onCancelCertificate() {
1329 * Updates the view associated to the activity after the finish of some operation over files
1330 * in the current account.
1332 * @param operation Removal operation performed.
1333 * @param result Result of the removal.
1336 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1337 super.onRemoteOperationFinish(operation
, result
);
1339 if (operation
instanceof RemoveFileOperation
) {
1340 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1342 } else if (operation
instanceof RenameFileOperation
) {
1343 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1345 } else if (operation
instanceof SynchronizeFileOperation
) {
1346 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1348 } else if (operation
instanceof CreateFolderOperation
) {
1349 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1351 } else if (operation
instanceof CreateShareViaLinkOperation
||
1352 operation
instanceof CreateShareWithShareeOperation
) {
1354 refreshShowDetails();
1355 refreshListOfFilesFragment();
1357 } else if (operation
instanceof UnshareOperation
) {
1358 onUnshareLinkOperationFinish((UnshareOperation
) operation
, result
);
1360 } else if (operation
instanceof MoveFileOperation
) {
1361 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1363 } else if (operation
instanceof CopyFileOperation
) {
1364 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1369 private void onUnshareLinkOperationFinish(UnshareOperation operation
,
1370 RemoteOperationResult result
) {
1371 if (result
.isSuccess()) {
1372 refreshShowDetails();
1373 refreshListOfFilesFragment();
1375 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1376 cleanSecondFragment();
1377 refreshListOfFilesFragment();
1381 private void refreshShowDetails() {
1382 FileFragment details
= getSecondFragment();
1383 if (details
!= null
) {
1384 OCFile file
= details
.getFile();
1386 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1387 if (details
instanceof PreviewMediaFragment
) {
1388 // Refresh OCFile of the fragment
1389 ((PreviewMediaFragment
) details
).updateFile(file
);
1390 } else if (details
instanceof PreviewTextFragment
) {
1391 // Refresh OCFile of the fragment
1392 ((PreviewTextFragment
) details
).updateFile(file
);
1397 invalidateOptionsMenu();
1402 * Updates the view associated to the activity after the finish of an operation trying to
1405 * @param operation Removal operation performed.
1406 * @param result Result of the removal.
1408 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1409 RemoteOperationResult result
) {
1410 Toast msg
= Toast
.makeText(this,
1411 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1415 if (result
.isSuccess()) {
1416 OCFile removedFile
= operation
.getFile();
1417 FileFragment second
= getSecondFragment();
1418 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1419 if (second
instanceof PreviewMediaFragment
) {
1420 ((PreviewMediaFragment
) second
).stopPreview(true
);
1422 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1423 cleanSecondFragment();
1425 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1426 refreshListOfFilesFragment();
1428 invalidateOptionsMenu();
1430 if (result
.isSslRecoverableException()) {
1431 mLastSslUntrustedServerResult
= result
;
1432 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1439 * Updates the view associated to the activity after the finish of an operation trying to move a
1442 * @param operation Move operation performed.
1443 * @param result Result of the move operation.
1445 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1446 RemoteOperationResult result
) {
1447 if (result
.isSuccess()) {
1448 refreshListOfFilesFragment();
1451 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1452 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1456 } catch (NotFoundException e
) {
1457 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1463 * Updates the view associated to the activity after the finish of an operation trying to copy a
1466 * @param operation Copy operation performed.
1467 * @param result Result of the copy operation.
1469 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1470 if (result
.isSuccess()) {
1471 refreshListOfFilesFragment();
1474 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1475 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1479 } catch (NotFoundException e
) {
1480 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1486 * Updates the view associated to the activity after the finish of an operation trying to rename
1489 * @param operation Renaming operation performed.
1490 * @param result Result of the renaming.
1492 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1493 RemoteOperationResult result
) {
1494 OCFile renamedFile
= operation
.getFile();
1495 if (result
.isSuccess()) {
1496 FileFragment details
= getSecondFragment();
1497 if (details
!= null
) {
1498 if (details
instanceof FileDetailFragment
&&
1499 renamedFile
.equals(details
.getFile()) ) {
1500 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1501 showDetails(renamedFile
);
1503 } else if (details
instanceof PreviewMediaFragment
&&
1504 renamedFile
.equals(details
.getFile())) {
1505 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1506 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1507 int position
= ((PreviewMediaFragment
) details
).getPosition();
1508 startMediaPreview(renamedFile
, position
, true
);
1510 getFileOperationsHelper().openFile(renamedFile
);
1512 } else if (details
instanceof PreviewTextFragment
&&
1513 renamedFile
.equals(details
.getFile())) {
1514 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1515 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1516 startTextPreview(renamedFile
);
1518 getFileOperationsHelper().openFile(renamedFile
);
1523 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1524 refreshListOfFilesFragment();
1528 Toast msg
= Toast
.makeText(this,
1529 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1533 if (result
.isSslRecoverableException()) {
1534 mLastSslUntrustedServerResult
= result
;
1535 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1540 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1541 RemoteOperationResult result
) {
1542 if (result
.isSuccess()) {
1543 if (operation
.transferWasRequested()) {
1544 OCFile syncedFile
= operation
.getLocalFile();
1545 onTransferStateChanged(syncedFile
, true
, true
);
1546 invalidateOptionsMenu();
1547 refreshShowDetails();
1553 * Updates the view associated to the activity after the finish of an operation trying create a
1556 * @param operation Creation operation performed.
1557 * @param result Result of the creation.
1559 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1560 RemoteOperationResult result
) {
1561 if (result
.isSuccess()) {
1562 refreshListOfFilesFragment();
1565 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1566 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1570 } catch (NotFoundException e
) {
1571 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1581 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1582 refreshListOfFilesFragment();
1583 FileFragment details
= getSecondFragment();
1584 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1585 file
.equals(details
.getFile()) ) {
1586 if (downloading
|| uploading
) {
1587 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1589 if (!file
.fileExists()) {
1590 cleanSecondFragment();
1592 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1600 private void requestForDownload() {
1601 Account account
= getAccount();
1602 //if (!mWaitingToPreview.isDownloading()) {
1603 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1604 Intent i
= new Intent(this, FileDownloader
.class);
1605 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1606 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1612 private OCFile
getCurrentDir() {
1613 OCFile file
= getFile();
1615 if (file
.isFolder()) {
1617 } else if (getStorageManager() != null
) {
1618 String parentPath
= file
.getRemotePath().substring(0,
1619 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1620 return getStorageManager().getFileByPath(parentPath
);
1627 * Starts an operation to refresh the requested folder.
1629 * The operation is run in a new background thread created on the fly.
1631 * The refresh updates is a "light sync": properties of regular files in folder are updated (including
1632 * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
1635 * @param folder Folder to refresh.
1636 * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
1639 public void startSyncFolderOperation(final OCFile folder
, final boolean ignoreETag
) {
1641 // the execution is slightly delayed to allow the activity get the window focus if it's being started
1642 // or if the method is called from a dialog that is being dismissed
1643 getHandler().postDelayed(
1647 if (hasWindowFocus()) {
1648 long currentSyncTime
= System
.currentTimeMillis();
1649 mSyncInProgress
= true
;
1651 // perform folder synchronization
1652 RemoteOperation synchFolderOp
= new RefreshFolderOperation(folder
,
1655 getFileOperationsHelper().isSharedSupported(),
1657 getStorageManager(),
1659 getApplicationContext()
1661 synchFolderOp
.execute(
1663 MainApp
.getAppContext(),
1664 FileDisplayActivity
.this,
1669 mProgressBar
.setIndeterminate(true
);
1671 setBackgroundText();
1673 } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
1674 // another window floating over
1677 DELAY_TO_REQUEST_OPERATIONS_LATER
1683 * Show untrusted cert dialog
1685 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1686 // Show a dialog with the certificate info
1687 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1688 (CertificateCombinedException
) result
.getException());
1689 FragmentManager fm
= getSupportFragmentManager();
1690 FragmentTransaction ft
= fm
.beginTransaction();
1691 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1694 private void requestForDownload(OCFile file
) {
1695 Account account
= getAccount();
1696 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1697 Intent i
= new Intent(this, FileDownloader
.class);
1698 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1699 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1704 private void sendDownloadedFile() {
1705 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1706 mWaitingToSend
= null
;
1711 * Requests the download of the received {@link OCFile} , updates the UI
1712 * to monitor the download progress and prepares the activity to send the file
1713 * when the download finishes.
1715 * @param file {@link OCFile} to download and preview.
1717 public void startDownloadForSending(OCFile file
) {
1718 mWaitingToSend
= file
;
1719 requestForDownload(mWaitingToSend
);
1720 boolean hasSecondFragment
= (getSecondFragment() != null
);
1721 updateFragmentsVisibility(hasSecondFragment
);
1725 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1727 * @param file Image {@link OCFile} to show.
1729 public void startImagePreview(OCFile file
) {
1730 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1731 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1732 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1733 startActivity(showDetailsIntent
);
1737 * Stars the preview of an already down media {@link OCFile}.
1739 * @param file Media {@link OCFile} to preview.
1740 * @param startPlaybackPosition Media position where the playback will be started,
1742 * @param autoplay When 'true', the playback will start without user
1745 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1746 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1748 setSecondFragment(mediaFragment
);
1749 updateFragmentsVisibility(true
);
1750 updateActionBarTitleAndHomeButton(file
);
1755 * Stars the preview of a text file {@link OCFile}.
1757 * @param file Text {@link OCFile} to preview.
1759 public void startTextPreview(OCFile file
) {
1760 Bundle args
= new Bundle();
1761 args
.putParcelable(EXTRA_FILE
, file
);
1762 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1763 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1764 PreviewTextFragment
.class.getName(), args
);
1765 setSecondFragment(textPreviewFragment
);
1766 updateFragmentsVisibility(true
);
1767 //updateNavigationElementsInActionBar(file);
1772 * Requests the download of the received {@link OCFile} , updates the UI
1773 * to monitor the download progress and prepares the activity to preview
1774 * or open the file when the download finishes.
1776 * @param file {@link OCFile} to download and preview.
1778 public void startDownloadForPreview(OCFile file
) {
1779 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1780 setSecondFragment(detailFragment
);
1781 mWaitingToPreview
= file
;
1782 requestForDownload();
1783 updateFragmentsVisibility(true
);
1784 updateActionBarTitleAndHomeButton(file
);
1789 public void cancelTransference(OCFile file
) {
1790 getFileOperationsHelper().cancelTransference(file
);
1791 if (mWaitingToPreview
!= null
&&
1792 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1793 mWaitingToPreview
= null
;
1795 if (mWaitingToSend
!= null
&&
1796 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1797 mWaitingToSend
= null
;
1799 onTransferStateChanged(file
, false
, false
);
1803 public void onRefresh(boolean ignoreETag
) {
1804 refreshList(ignoreETag
);
1808 public void onRefresh() {
1812 private void refreshList(boolean ignoreETag
) {
1813 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1814 if (listOfFiles
!= null
) {
1815 OCFile folder
= listOfFiles
.getCurrentFile();
1816 if (folder
!= null
) {
1817 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1818 listDirectory(mFile);*/
1819 startSyncFolderOperation(folder
, ignoreETag
);
1824 private void sortByDate(boolean ascending
) {
1825 getListOfFilesFragment().sortByDate(ascending
);
1828 private void sortBySize(boolean ascending
) {
1829 getListOfFilesFragment().sortBySize(ascending
);
1832 private void sortByName(boolean ascending
) {
1833 getListOfFilesFragment().sortByName(ascending
);
1836 public void allFilesOption() {