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 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
275 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
276 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
277 int lastAtPos
= getAccount().name
.lastIndexOf("@");
278 username
.setText(getAccount().name
.substring(0, lastAtPos
));
282 if (!stateWasRecovered
) {
283 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
284 initFragmentsWithFile();
285 if (file
.isFolder()) {
286 startSyncFolderOperation(file
, false
);
290 updateFragmentsVisibility(!file
.isFolder());
291 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
296 private void createMinFragments() {
297 OCFileListFragment listOfFiles
= new OCFileListFragment();
298 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
299 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
300 transaction
.commit();
303 private void initFragmentsWithFile() {
304 if (getAccount() != null
&& getFile() != null
) {
306 OCFileListFragment listOfFiles
= getListOfFilesFragment();
307 if (listOfFiles
!= null
) {
308 listOfFiles
.listDirectory(getCurrentDir());
309 // TODO Enable when "On Device" is recovered
310 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
313 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
317 OCFile file
= getFile();
318 Fragment secondFragment
= chooseInitialSecondFragment(file
);
319 if (secondFragment
!= null
) {
320 setSecondFragment(secondFragment
);
321 updateFragmentsVisibility(true
);
322 updateActionBarTitleAndHomeButton(file
);
325 cleanSecondFragment();
326 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
327 startTextPreview(file
);
331 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
332 if (getAccount() == null
) {
333 Log_OC
.wtf(TAG
, "\t account is NULL");
335 if (getFile() == null
) {
336 Log_OC
.wtf(TAG
, "\t file is NULL");
341 private Fragment
chooseInitialSecondFragment(OCFile file
) {
342 Fragment secondFragment
= null
;
343 if (file
!= null
&& !file
.isFolder()) {
344 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
345 && file
.getLastSyncDateForProperties() > 0 // temporal fix
347 int startPlaybackPosition
=
348 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
350 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
351 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
352 startPlaybackPosition
, autoplay
);
354 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
355 secondFragment
= null
;
357 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
360 return secondFragment
;
365 * Replaces the second fragment managed by the activity with the received as
368 * Assumes never will be more than two fragments managed at the same time.
370 * @param fragment New second Fragment to set.
372 private void setSecondFragment(Fragment fragment
) {
373 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
374 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
375 transaction
.commit();
379 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
381 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
384 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
385 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
388 } else if (existsSecondFragment
) {
389 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
390 mLeftFragmentContainer
.setVisibility(View
.GONE
);
392 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
393 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
397 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
398 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
400 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
401 mRightFragmentContainer
.setVisibility(View
.GONE
);
407 private OCFileListFragment
getListOfFilesFragment() {
408 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
409 FileDisplayActivity
.TAG_LIST_OF_FILES
);
410 if (listOfFiles
!= null
) {
411 return (OCFileListFragment
) listOfFiles
;
413 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
417 public FileFragment
getSecondFragment() {
418 Fragment second
= getSupportFragmentManager().findFragmentByTag(
419 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
420 if (second
!= null
) {
421 return (FileFragment
) second
;
426 protected void cleanSecondFragment() {
427 Fragment second
= getSecondFragment();
428 if (second
!= null
) {
429 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
433 updateFragmentsVisibility(false
);
434 updateActionBarTitleAndHomeButton(null
);
437 protected void refreshListOfFilesFragment() {
438 OCFileListFragment fileListFragment
= getListOfFilesFragment();
439 if (fileListFragment
!= null
) {
440 fileListFragment
.listDirectory();
441 // TODO Enable when "On Device" is recovered ?
442 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
446 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
448 FileFragment secondFragment
= getSecondFragment();
449 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
450 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
451 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
452 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
453 OCFile fileInFragment
= detailsFragment
.getFile();
454 if (fileInFragment
!= null
&&
455 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
456 // the user browsed to other file ; forget the automatic preview
457 mWaitingToPreview
= null
;
459 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
460 // grant that the right panel updates the progress bar
461 detailsFragment
.listenForTransferProgress();
462 detailsFragment
.updateFileDetails(true
, false
);
464 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
465 // update the right panel
466 boolean detailsFragmentChanged
= false
;
469 mWaitingToPreview
= getStorageManager().getFileById(
470 mWaitingToPreview
.getFileId()); // update the file from database,
471 // for the local storage path
472 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
473 startMediaPreview(mWaitingToPreview
, 0, true
);
474 detailsFragmentChanged
= true
;
475 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
476 startTextPreview(mWaitingToPreview
);
477 detailsFragmentChanged
= true
;
479 getFileOperationsHelper().openFile(mWaitingToPreview
);
482 mWaitingToPreview
= null
;
484 if (!detailsFragmentChanged
) {
485 detailsFragment
.updateFileDetails(false
, (success
));
492 public boolean onPrepareOptionsMenu(Menu menu
) {
493 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
494 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
495 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
496 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
497 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
499 return super.onPrepareOptionsMenu(menu
);
503 public boolean onCreateOptionsMenu(Menu menu
) {
504 MenuInflater inflater
= getMenuInflater();
505 inflater
.inflate(R
.menu
.main_menu
, menu
);
511 public boolean onOptionsItemSelected(MenuItem item
) {
512 boolean retval
= true
;
513 switch (item
.getItemId()) {
514 case R
.id
.action_create_dir
: {
515 CreateFolderDialogFragment dialog
=
516 CreateFolderDialogFragment
.newInstance(getCurrentDir());
517 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
521 case R
.id
.action_sync_account
: {
522 startSynchronization();
525 case R
.id
.action_upload
: {
526 UploadSourceDialogFragment dialog
=
527 UploadSourceDialogFragment
.newInstance(getAccount());
528 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
531 case android
.R
.id
.home
: {
532 FileFragment second
= getSecondFragment();
533 OCFile currentDir
= getCurrentDir();
534 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
535 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
536 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
537 (second
!= null
&& second
.getFile() != null
)) {
541 mDrawerLayout
.openDrawer(GravityCompat
.START
);
545 case R
.id
.action_sort
: {
546 SharedPreferences appPreferences
= PreferenceManager
547 .getDefaultSharedPreferences(this);
549 // Read sorting order, default to sort by name ascending
550 Integer sortOrder
= appPreferences
551 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
553 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
554 builder
.setTitle(R
.string
.actionbar_sort_title
)
555 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
556 new DialogInterface
.OnClickListener() {
557 public void onClick(DialogInterface dialog
, int which
) {
570 builder
.create().show();
574 retval
= super.onOptionsItemSelected(item
);
579 private void startSynchronization() {
580 Log_OC
.d(TAG
, "Got to start sync");
581 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
582 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
583 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
584 // cancel the current synchronizations of any ownCloud account
585 Bundle bundle
= new Bundle();
586 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
587 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
588 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
589 MainApp
.getAuthority());
590 ContentResolver
.requestSync(
592 MainApp
.getAuthority(), bundle
);
594 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
595 MainApp
.getAuthority() + " with new API");
596 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
597 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
598 builder
.setExpedited(true
);
599 builder
.setManual(true
);
602 // Fix bug in Android Lollipop when you click on refresh the whole account
603 Bundle extras
= new Bundle();
604 builder
.setExtras(extras
);
606 SyncRequest request
= builder
.build();
607 ContentResolver
.requestSync(request
);
612 * Called, when the user selected something for uploading
615 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
617 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
619 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
620 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
621 //getClipData is only supported on api level 16+, Jelly Bean
622 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
623 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
624 Intent intent
= new Intent();
625 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
626 requestSimpleUpload(intent
, resultCode
);
629 requestSimpleUpload(data
, resultCode
);
631 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
632 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
633 requestMultipleUpload(data
, resultCode
);
635 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
636 final Intent fData
= data
;
637 final int fResultCode
= resultCode
;
638 getHandler().postDelayed(
642 requestMoveOperation(fData
, fResultCode
);
645 DELAY_TO_REQUEST_OPERATIONS_LATER
648 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
650 final Intent fData
= data
;
651 final int fResultCode
= resultCode
;
652 getHandler().postDelayed(
656 requestCopyOperation(fData
, fResultCode
);
659 DELAY_TO_REQUEST_OPERATIONS_LATER
663 super.onActivityResult(requestCode
, resultCode
, data
);
668 private void requestMultipleUpload(Intent data
, int resultCode
) {
669 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
670 if (filePaths
!= null
) {
671 String
[] remotePaths
= new String
[filePaths
.length
];
672 String remotePathBase
= getCurrentDir().getRemotePath();
673 for (int j
= 0; j
< remotePaths
.length
; j
++) {
674 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
677 Intent i
= new Intent(this, FileUploader
.class);
678 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
679 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
680 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
681 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
682 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
683 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
687 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
688 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
696 private void requestSimpleUpload(Intent data
, int resultCode
) {
697 String filePath
= null
;
698 String mimeType
= null
;
700 Uri selectedImageUri
= data
.getData();
703 mimeType
= getContentResolver().getType(selectedImageUri
);
705 String fileManagerString
= selectedImageUri
.getPath();
706 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
708 if (selectedImagePath
!= null
)
709 filePath
= selectedImagePath
;
711 filePath
= fileManagerString
;
713 } catch (Exception e
) {
714 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
715 "Intent.ACTION_GET_CONTENT", e
);
718 if (filePath
== null
) {
719 Log_OC
.e(TAG
, "Couldn't resolve path to file");
720 Toast t
= Toast
.makeText(
721 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
729 Intent i
= new Intent(this, FileUploader
.class);
730 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
731 OCFile currentDir
= getCurrentDir();
732 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
734 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
735 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
737 if (cursor
!= null
&& cursor
.moveToFirst()) {
738 String displayName
= cursor
.getString(cursor
.getColumnIndex(
739 OpenableColumns
.DISPLAY_NAME
));
740 Log_OC
.v(TAG
, "Display Name: " + displayName
);
742 displayName
.replace(File
.separatorChar
, '_');
743 displayName
.replace(File
.pathSeparatorChar
, '_');
744 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
747 // and what happens in case of error?; wrong target name for the upload
753 remotePath
+= new File(filePath
).getName();
756 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
757 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
758 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
759 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
760 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
761 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
766 * Request the operation for moving the file/folder from one path to another
768 * @param data Intent received
769 * @param resultCode Result code received
771 private void requestMoveOperation(Intent data
, int resultCode
) {
772 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
773 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
774 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
778 * Request the operation for copying the file/folder from one path to another
780 * @param data Intent received
781 * @param resultCode Result code received
783 private void requestCopyOperation(Intent data
, int resultCode
) {
784 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
785 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
786 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
790 public void onBackPressed() {
791 if (!isDrawerOpen()){
792 OCFileListFragment listOfFiles
= getListOfFilesFragment();
793 if (mDualPane
|| getSecondFragment() == null
) {
794 OCFile currentDir
= getCurrentDir();
795 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
799 if (listOfFiles
!= null
) { // should never be null, indeed
800 listOfFiles
.onBrowseUp();
803 if (listOfFiles
!= null
) { // should never be null, indeed
804 setFile(listOfFiles
.getCurrentFile());
806 cleanSecondFragment();
808 super.onBackPressed();
813 protected void onSaveInstanceState(Bundle outState
) {
814 // responsibility of restore is preferred in onCreate() before than in
815 // onRestoreInstanceState when there are Fragments involved
816 Log_OC
.v(TAG
, "onSaveInstanceState() start");
817 super.onSaveInstanceState(outState
);
818 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
819 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
820 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
821 // mRefreshSharesInProgress);
822 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
824 Log_OC
.v(TAG
, "onSaveInstanceState() end");
829 protected void onResume() {
830 Log_OC
.v(TAG
, "onResume() start");
832 // refresh Navigation Drawer account list
833 mNavigationDrawerAdapter
.updateAccountList();
835 // refresh list of files
836 refreshListOfFilesFragment();
838 // Listen for sync messages
839 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
840 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
841 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
842 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
843 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
844 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
845 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
846 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
847 // syncIntentFilter);
849 // Listen for upload messages
850 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
851 mUploadFinishReceiver
= new UploadFinishReceiver();
852 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
854 // Listen for download messages
855 IntentFilter downloadIntentFilter
= new IntentFilter(
856 FileDownloader
.getDownloadAddedMessage());
857 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
858 mDownloadFinishReceiver
= new DownloadFinishReceiver();
859 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
861 Log_OC
.v(TAG
, "onResume() end");
867 protected void onPause() {
868 Log_OC
.v(TAG
, "onPause() start");
869 if (mSyncBroadcastReceiver
!= null
) {
870 unregisterReceiver(mSyncBroadcastReceiver
);
871 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
872 mSyncBroadcastReceiver
= null
;
874 if (mUploadFinishReceiver
!= null
) {
875 unregisterReceiver(mUploadFinishReceiver
);
876 mUploadFinishReceiver
= null
;
878 if (mDownloadFinishReceiver
!= null
) {
879 unregisterReceiver(mDownloadFinishReceiver
);
880 mDownloadFinishReceiver
= null
;
884 Log_OC
.v(TAG
, "onPause() end");
888 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
891 * {@link BroadcastReceiver} to enable syncing feedback in UI
894 public void onReceive(Context context
, Intent intent
) {
896 String event
= intent
.getAction();
897 Log_OC
.d(TAG
, "Received broadcast " + event
);
898 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
899 String synchFolderRemotePath
=
900 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
901 RemoteOperationResult synchResult
=
902 (RemoteOperationResult
)intent
.getSerializableExtra(
903 FileSyncAdapter
.EXTRA_RESULT
);
904 boolean sameAccount
= (getAccount() != null
&&
905 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
909 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
910 mSyncInProgress
= true
;
913 OCFile currentFile
= (getFile() == null
) ? null
:
914 getStorageManager().getFileByPath(getFile().getRemotePath());
915 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
916 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
918 if (currentDir
== null
) {
919 // current folder was removed from the server
920 Toast
.makeText( FileDisplayActivity
.this,
923 sync_current_folder_was_removed
),
924 synchFolderRemotePath
),
931 if (currentFile
== null
&& !getFile().isFolder()) {
932 // currently selected file was removed in the server, and now we
934 cleanSecondFragment();
935 currentFile
= currentDir
;
938 if (synchFolderRemotePath
!= null
&&
939 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
940 OCFileListFragment fileListFragment
= getListOfFilesFragment();
941 if (fileListFragment
!= null
) {
942 fileListFragment
.listDirectory();
943 // TODO Enable when "On Device" is recovered ?
944 // fileListFragment.listDirectory(currentDir,
945 // MainApp.getOnlyOnDevice());
948 setFile(currentFile
);
951 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
952 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
955 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
956 equals(event
) &&/// TODO refactor and make common
958 synchResult
!= null
&& !synchResult
.isSuccess() &&
959 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
960 synchResult
.isIdPRedirection() ||
961 (synchResult
.isException() && synchResult
.getException()
962 instanceof AuthenticatorException
))) {
966 OwnCloudClient client
;
967 OwnCloudAccount ocAccount
=
968 new OwnCloudAccount(getAccount(), context
);
969 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
970 removeClientFor(ocAccount
));
971 if (client
!= null
) {
972 OwnCloudCredentials cred
= client
.getCredentials();
974 AccountManager am
= AccountManager
.get(context
);
975 if (cred
.authTokenExpires()) {
976 am
.invalidateAuthToken(
981 am
.clearPassword(getAccount());
985 requestCredentialsUpdate();
987 } catch (AccountNotFoundException e
) {
988 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
994 removeStickyBroadcast(intent
);
995 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
996 mProgressBar
.setIndeterminate(mSyncInProgress
);
997 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
998 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
999 /*|| mRefreshSharesInProgress*/ //);
1001 setBackgroundText();
1005 if (synchResult
!= null
) {
1006 if (synchResult
.getCode().equals(
1007 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1008 mLastSslUntrustedServerResult
= synchResult
;
1011 } catch (RuntimeException e
) {
1012 // avoid app crashes after changing the serial id of RemoteOperationResult
1013 // in owncloud library with broadcast notifications pending to process
1014 removeStickyBroadcast(intent
);
1020 * Show a text message on screen view for notifying user if content is
1021 * loading or folder is empty
1023 private void setBackgroundText() {
1024 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1025 if (ocFileListFragment
!= null
) {
1026 int message
= R
.string
.file_list_loading
;
1027 if (!mSyncInProgress
) {
1028 // In case file list is empty
1029 message
= R
.string
.file_list_empty
;
1031 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1033 Log_OC
.e(TAG
, "OCFileListFragment is null");
1038 * Once the file upload has finished -> update view
1040 private class UploadFinishReceiver
extends BroadcastReceiver
{
1042 * Once the file upload has finished -> update view
1044 * @author David A. Velasco
1045 * {@link BroadcastReceiver} to enable upload feedback in UI
1048 public void onReceive(Context context
, Intent intent
) {
1050 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1051 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1052 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1053 OCFile currentDir
= getCurrentDir();
1054 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1055 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1057 if (sameAccount
&& isDescendant
) {
1058 String linkedToRemotePath
=
1059 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1060 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1061 refreshListOfFilesFragment();
1065 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1067 boolean renamedInUpload
= getFile().getRemotePath().
1068 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1069 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1071 FileFragment details
= getSecondFragment();
1072 boolean detailFragmentIsShown
= (details
!= null
&&
1073 details
instanceof FileDetailFragment
);
1075 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1076 if (uploadWasFine
) {
1077 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1079 if (renamedInUpload
) {
1080 String newName
= (new File(uploadedRemotePath
)).getName();
1081 Toast msg
= Toast
.makeText(
1084 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1089 if (uploadWasFine
|| getFile().fileExists()) {
1090 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1092 cleanSecondFragment();
1095 // Force the preview if the file is an image or text file
1096 if (uploadWasFine
) {
1097 OCFile ocFile
= getFile();
1098 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1099 startImagePreview(getFile());
1100 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1101 startTextPreview(ocFile
);
1102 // TODO what about other kind of previews?
1106 mProgressBar
.setIndeterminate(false
);
1108 if (intent
!= null
) {
1109 removeStickyBroadcast(intent
);
1115 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1116 private boolean isAscendant(String linkedToRemotePath
) {
1117 OCFile currentDir
= getCurrentDir();
1119 currentDir
!= null
&&
1120 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1129 * Class waiting for broadcast events from the {@link FileDownloader} service.
1131 * Updates the UI when a download is started or finished, provided that it is relevant for the
1134 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1137 public void onReceive(Context context
, Intent intent
) {
1139 boolean sameAccount
= isSameAccount(intent
);
1140 String downloadedRemotePath
=
1141 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1142 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1144 if (sameAccount
&& isDescendant
) {
1145 String linkedToRemotePath
=
1146 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1147 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1148 refreshListOfFilesFragment();
1150 refreshSecondFragment(
1152 downloadedRemotePath
,
1153 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1157 if (mWaitingToSend
!= null
) {
1159 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1160 if (mWaitingToSend
.isDown()) {
1161 sendDownloadedFile();
1166 if (intent
!= null
) {
1167 removeStickyBroadcast(intent
);
1172 private boolean isDescendant(String downloadedRemotePath
) {
1173 OCFile currentDir
= getCurrentDir();
1175 currentDir
!= null
&&
1176 downloadedRemotePath
!= null
&&
1177 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1181 private boolean isAscendant(String linkedToRemotePath
) {
1182 OCFile currentDir
= getCurrentDir();
1184 currentDir
!= null
&&
1185 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1189 private boolean isSameAccount(Intent intent
) {
1190 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1191 return (accountName
!= null
&& getAccount() != null
&&
1192 accountName
.equals(getAccount().name
));
1197 public void browseToRoot() {
1198 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1199 if (listOfFiles
!= null
) { // should never be null, indeed
1200 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1201 listOfFiles
.listDirectory(root
);
1202 // TODO Enable when "On Device" is recovered ?
1203 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1204 setFile(listOfFiles
.getCurrentFile());
1205 startSyncFolderOperation(root
, false
);
1207 cleanSecondFragment();
1214 * Updates action bar and second fragment, if in dual pane mode.
1217 public void onBrowsedDownTo(OCFile directory
) {
1219 cleanSecondFragment();
1221 startSyncFolderOperation(directory
, false
);
1225 * Shows the information of the {@link OCFile} received as a
1226 * parameter in the second fragment.
1228 * @param file {@link OCFile} whose details will be shown
1231 public void showDetails(OCFile file
) {
1232 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1233 setSecondFragment(detailFragment
);
1234 updateFragmentsVisibility(true
);
1235 updateActionBarTitleAndHomeButton(file
);
1240 * Shows the share view for sharing {@link OCFile} received as a
1241 * parameter in the second fragment.
1243 * @param file {@link OCFile} File to share with
1246 public void showShareFile(OCFile file
) {
1247 Intent intent
= new Intent(this, ShareActivity
.class);
1248 intent
.putExtra(EXTRA_FILE
, file
);
1249 intent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1250 startActivity(intent
);
1254 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1256 // in dual pane mode, keep the focus of title an action bar in the current folder
1257 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1260 super.updateActionBarTitleAndHomeButton(chosenFile
);
1266 protected ServiceConnection
newTransferenceServiceConnection() {
1267 return new ListServiceConnection();
1271 * Defines callbacks for service binding, passed to bindService()
1273 private class ListServiceConnection
implements ServiceConnection
{
1276 public void onServiceConnected(ComponentName component
, IBinder service
) {
1277 if (component
.equals(new ComponentName(
1278 FileDisplayActivity
.this, FileDownloader
.class))) {
1279 Log_OC
.d(TAG
, "Download service connected");
1280 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1281 if (mWaitingToPreview
!= null
)
1282 if (getStorageManager() != null
) {
1285 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1286 if (!mWaitingToPreview
.isDown()) {
1287 requestForDownload();
1291 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1292 FileUploader
.class))) {
1293 Log_OC
.d(TAG
, "Upload service connected");
1294 mUploaderBinder
= (FileUploaderBinder
) service
;
1298 // a new chance to get the mDownloadBinder through
1299 // getFileDownloadBinder() - THIS IS A MESS
1300 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1301 if (listOfFiles
!= null
) {
1302 listOfFiles
.listDirectory();
1303 // TODO Enable when "On Device" is recovered ?
1304 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1306 FileFragment secondFragment
= getSecondFragment();
1307 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1308 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1309 detailFragment
.listenForTransferProgress();
1310 detailFragment
.updateFileDetails(false
, false
);
1315 public void onServiceDisconnected(ComponentName component
) {
1316 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1317 FileDownloader
.class))) {
1318 Log_OC
.d(TAG
, "Download service disconnected");
1319 mDownloaderBinder
= null
;
1320 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1321 FileUploader
.class))) {
1322 Log_OC
.d(TAG
, "Upload service disconnected");
1323 mUploaderBinder
= null
;
1329 public void onSavedCertificate() {
1330 startSyncFolderOperation(getCurrentDir(), false
);
1335 public void onFailedSavingCertificate() {
1336 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1337 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1339 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1343 public void onCancelCertificate() {
1348 * Updates the view associated to the activity after the finish of some operation over files
1349 * in the current account.
1351 * @param operation Removal operation performed.
1352 * @param result Result of the removal.
1355 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1356 super.onRemoteOperationFinish(operation
, result
);
1358 if (operation
instanceof RemoveFileOperation
) {
1359 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1361 } else if (operation
instanceof RenameFileOperation
) {
1362 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1364 } else if (operation
instanceof SynchronizeFileOperation
) {
1365 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1367 } else if (operation
instanceof CreateFolderOperation
) {
1368 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1370 } else if (operation
instanceof CreateShareViaLinkOperation
||
1371 operation
instanceof CreateShareWithShareeOperation
) {
1373 refreshShowDetails();
1374 refreshListOfFilesFragment();
1376 } else if (operation
instanceof UnshareOperation
) {
1377 onUnshareLinkOperationFinish((UnshareOperation
) operation
, result
);
1379 } else if (operation
instanceof MoveFileOperation
) {
1380 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1382 } else if (operation
instanceof CopyFileOperation
) {
1383 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1388 private void onUnshareLinkOperationFinish(UnshareOperation operation
,
1389 RemoteOperationResult result
) {
1390 if (result
.isSuccess()) {
1391 refreshShowDetails();
1392 refreshListOfFilesFragment();
1394 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1395 cleanSecondFragment();
1396 refreshListOfFilesFragment();
1400 private void refreshShowDetails() {
1401 FileFragment details
= getSecondFragment();
1402 if (details
!= null
) {
1403 OCFile file
= details
.getFile();
1405 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1406 if (details
instanceof PreviewMediaFragment
) {
1407 // Refresh OCFile of the fragment
1408 ((PreviewMediaFragment
) details
).updateFile(file
);
1409 } else if (details
instanceof PreviewTextFragment
) {
1410 // Refresh OCFile of the fragment
1411 ((PreviewTextFragment
) details
).updateFile(file
);
1416 invalidateOptionsMenu();
1421 * Updates the view associated to the activity after the finish of an operation trying to
1424 * @param operation Removal operation performed.
1425 * @param result Result of the removal.
1427 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1428 RemoteOperationResult result
) {
1429 Toast msg
= Toast
.makeText(this,
1430 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1434 if (result
.isSuccess()) {
1435 OCFile removedFile
= operation
.getFile();
1436 FileFragment second
= getSecondFragment();
1437 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1438 if (second
instanceof PreviewMediaFragment
) {
1439 ((PreviewMediaFragment
) second
).stopPreview(true
);
1441 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1442 cleanSecondFragment();
1444 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1445 refreshListOfFilesFragment();
1447 invalidateOptionsMenu();
1449 if (result
.isSslRecoverableException()) {
1450 mLastSslUntrustedServerResult
= result
;
1451 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1458 * Updates the view associated to the activity after the finish of an operation trying to move a
1461 * @param operation Move operation performed.
1462 * @param result Result of the move operation.
1464 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1465 RemoteOperationResult result
) {
1466 if (result
.isSuccess()) {
1467 refreshListOfFilesFragment();
1470 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1471 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1475 } catch (NotFoundException e
) {
1476 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1482 * Updates the view associated to the activity after the finish of an operation trying to copy a
1485 * @param operation Copy operation performed.
1486 * @param result Result of the copy operation.
1488 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1489 if (result
.isSuccess()) {
1490 refreshListOfFilesFragment();
1493 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1494 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1498 } catch (NotFoundException e
) {
1499 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1505 * Updates the view associated to the activity after the finish of an operation trying to rename
1508 * @param operation Renaming operation performed.
1509 * @param result Result of the renaming.
1511 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1512 RemoteOperationResult result
) {
1513 OCFile renamedFile
= operation
.getFile();
1514 if (result
.isSuccess()) {
1515 FileFragment details
= getSecondFragment();
1516 if (details
!= null
) {
1517 if (details
instanceof FileDetailFragment
&&
1518 renamedFile
.equals(details
.getFile()) ) {
1519 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1520 showDetails(renamedFile
);
1522 } else if (details
instanceof PreviewMediaFragment
&&
1523 renamedFile
.equals(details
.getFile())) {
1524 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1525 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1526 int position
= ((PreviewMediaFragment
) details
).getPosition();
1527 startMediaPreview(renamedFile
, position
, true
);
1529 getFileOperationsHelper().openFile(renamedFile
);
1531 } else if (details
instanceof PreviewTextFragment
&&
1532 renamedFile
.equals(details
.getFile())) {
1533 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1534 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1535 startTextPreview(renamedFile
);
1537 getFileOperationsHelper().openFile(renamedFile
);
1542 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1543 refreshListOfFilesFragment();
1547 Toast msg
= Toast
.makeText(this,
1548 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1552 if (result
.isSslRecoverableException()) {
1553 mLastSslUntrustedServerResult
= result
;
1554 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1559 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1560 RemoteOperationResult result
) {
1561 if (result
.isSuccess()) {
1562 if (operation
.transferWasRequested()) {
1563 OCFile syncedFile
= operation
.getLocalFile();
1564 onTransferStateChanged(syncedFile
, true
, true
);
1565 invalidateOptionsMenu();
1566 refreshShowDetails();
1572 * Updates the view associated to the activity after the finish of an operation trying create a
1575 * @param operation Creation operation performed.
1576 * @param result Result of the creation.
1578 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1579 RemoteOperationResult result
) {
1580 if (result
.isSuccess()) {
1581 refreshListOfFilesFragment();
1584 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1585 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1589 } catch (NotFoundException e
) {
1590 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1600 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1601 refreshListOfFilesFragment();
1602 FileFragment details
= getSecondFragment();
1603 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1604 file
.equals(details
.getFile()) ) {
1605 if (downloading
|| uploading
) {
1606 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1608 if (!file
.fileExists()) {
1609 cleanSecondFragment();
1611 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1619 private void requestForDownload() {
1620 Account account
= getAccount();
1621 //if (!mWaitingToPreview.isDownloading()) {
1622 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1623 Intent i
= new Intent(this, FileDownloader
.class);
1624 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1625 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1631 private OCFile
getCurrentDir() {
1632 OCFile file
= getFile();
1634 if (file
.isFolder()) {
1636 } else if (getStorageManager() != null
) {
1637 String parentPath
= file
.getRemotePath().substring(0,
1638 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1639 return getStorageManager().getFileByPath(parentPath
);
1646 * Starts an operation to refresh the requested folder.
1648 * The operation is run in a new background thread created on the fly.
1650 * The refresh updates is a "light sync": properties of regular files in folder are updated (including
1651 * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
1654 * @param folder Folder to refresh.
1655 * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
1658 public void startSyncFolderOperation(final OCFile folder
, final boolean ignoreETag
) {
1660 // the execution is slightly delayed to allow the activity get the window focus if it's being started
1661 // or if the method is called from a dialog that is being dismissed
1662 getHandler().postDelayed(
1666 if (hasWindowFocus()) {
1667 long currentSyncTime
= System
.currentTimeMillis();
1668 mSyncInProgress
= true
;
1670 // perform folder synchronization
1671 RemoteOperation synchFolderOp
= new RefreshFolderOperation(folder
,
1674 getFileOperationsHelper().isSharedSupported(),
1676 getStorageManager(),
1678 getApplicationContext()
1680 synchFolderOp
.execute(
1682 MainApp
.getAppContext(),
1683 FileDisplayActivity
.this,
1688 mProgressBar
.setIndeterminate(true
);
1690 setBackgroundText();
1692 } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
1693 // another window floating over
1696 DELAY_TO_REQUEST_OPERATIONS_LATER
1702 * Show untrusted cert dialog
1704 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1705 // Show a dialog with the certificate info
1706 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1707 (CertificateCombinedException
) result
.getException());
1708 FragmentManager fm
= getSupportFragmentManager();
1709 FragmentTransaction ft
= fm
.beginTransaction();
1710 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1713 private void requestForDownload(OCFile file
) {
1714 Account account
= getAccount();
1715 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1716 Intent i
= new Intent(this, FileDownloader
.class);
1717 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1718 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1723 private void sendDownloadedFile() {
1724 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1725 mWaitingToSend
= null
;
1730 * Requests the download of the received {@link OCFile} , updates the UI
1731 * to monitor the download progress and prepares the activity to send the file
1732 * when the download finishes.
1734 * @param file {@link OCFile} to download and preview.
1736 public void startDownloadForSending(OCFile file
) {
1737 mWaitingToSend
= file
;
1738 requestForDownload(mWaitingToSend
);
1739 boolean hasSecondFragment
= (getSecondFragment() != null
);
1740 updateFragmentsVisibility(hasSecondFragment
);
1744 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1746 * @param file Image {@link OCFile} to show.
1748 public void startImagePreview(OCFile file
) {
1749 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1750 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1751 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1752 startActivity(showDetailsIntent
);
1756 * Stars the preview of an already down media {@link OCFile}.
1758 * @param file Media {@link OCFile} to preview.
1759 * @param startPlaybackPosition Media position where the playback will be started,
1761 * @param autoplay When 'true', the playback will start without user
1764 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1765 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1767 setSecondFragment(mediaFragment
);
1768 updateFragmentsVisibility(true
);
1769 updateActionBarTitleAndHomeButton(file
);
1774 * Stars the preview of a text file {@link OCFile}.
1776 * @param file Text {@link OCFile} to preview.
1778 public void startTextPreview(OCFile file
) {
1779 Bundle args
= new Bundle();
1780 args
.putParcelable(EXTRA_FILE
, file
);
1781 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1782 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1783 PreviewTextFragment
.class.getName(), args
);
1784 setSecondFragment(textPreviewFragment
);
1785 updateFragmentsVisibility(true
);
1786 //updateNavigationElementsInActionBar(file);
1791 * Requests the download of the received {@link OCFile} , updates the UI
1792 * to monitor the download progress and prepares the activity to preview
1793 * or open the file when the download finishes.
1795 * @param file {@link OCFile} to download and preview.
1797 public void startDownloadForPreview(OCFile file
) {
1798 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1799 setSecondFragment(detailFragment
);
1800 mWaitingToPreview
= file
;
1801 requestForDownload();
1802 updateFragmentsVisibility(true
);
1803 updateActionBarTitleAndHomeButton(file
);
1808 public void cancelTransference(OCFile file
) {
1809 getFileOperationsHelper().cancelTransference(file
);
1810 if (mWaitingToPreview
!= null
&&
1811 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1812 mWaitingToPreview
= null
;
1814 if (mWaitingToSend
!= null
&&
1815 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1816 mWaitingToSend
= null
;
1818 onTransferStateChanged(file
, false
, false
);
1822 public void onRefresh(boolean ignoreETag
) {
1823 refreshList(ignoreETag
);
1827 public void onRefresh() {
1831 private void refreshList(boolean ignoreETag
) {
1832 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1833 if (listOfFiles
!= null
) {
1834 OCFile folder
= listOfFiles
.getCurrentFile();
1835 if (folder
!= null
) {
1836 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1837 listDirectory(mFile);*/
1838 startSyncFolderOperation(folder
, ignoreETag
);
1843 private void sortByDate(boolean ascending
) {
1844 getListOfFilesFragment().sortByDate(ascending
);
1847 private void sortBySize(boolean ascending
) {
1848 getListOfFilesFragment().sortBySize(ascending
);
1851 private void sortByName(boolean ascending
) {
1852 getListOfFilesFragment().sortByName(ascending
);
1855 public void allFilesOption() {