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
.content
.BroadcastReceiver
;
30 import android
.content
.ComponentName
;
31 import android
.content
.ContentResolver
;
32 import android
.content
.Context
;
33 import android
.content
.DialogInterface
;
34 import android
.content
.Intent
;
35 import android
.content
.IntentFilter
;
36 import android
.content
.ServiceConnection
;
37 import android
.content
.SharedPreferences
;
38 import android
.content
.SyncRequest
;
39 import android
.content
.res
.Resources
.NotFoundException
;
40 import android
.database
.Cursor
;
41 import android
.net
.Uri
;
42 import android
.os
.Build
;
43 import android
.os
.Bundle
;
44 import android
.os
.IBinder
;
45 import android
.preference
.PreferenceManager
;
46 import android
.provider
.OpenableColumns
;
47 import android
.support
.v4
.app
.Fragment
;
48 import android
.support
.v4
.app
.FragmentManager
;
49 import android
.support
.v4
.app
.FragmentTransaction
;
50 import android
.support
.v4
.content
.ContextCompat
;
51 import android
.support
.v4
.view
.GravityCompat
;
52 import android
.support
.v7
.app
.AlertDialog
;
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
.MoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import com
.owncloud
.android
.utils
.FileStorageUtils
;
105 import com
.owncloud
.android
.utils
.UriUtils
;
110 * Displays, what files the user has available in his ownCloud.
113 public class FileDisplayActivity
extends HookActivity
114 implements FileFragment
.ContainerActivity
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
122 private boolean mDualPane
;
123 private View mLeftFragmentContainer
;
124 private View mRightFragmentContainer
;
125 private ProgressBar mProgressBar
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 public static final int ACTION_MOVE_FILES
= 3;
136 public static final int ACTION_COPY_FILES
= 4;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
148 public static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
149 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
150 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
152 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.v(TAG
, "onCreate() start");
159 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
162 /// grant that FileObserverService is watching favorite files
163 if (savedInstanceState
== null
) {
164 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
165 startService(initObserversIntent
);
168 /// Load of saved instance state
169 if(savedInstanceState
!= null
) {
170 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
171 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
176 mWaitingToPreview
= null
;
177 mSyncInProgress
= false
;
178 mWaitingToSend
= null
;
183 // Inflate and set the layout view
184 setContentView(R
.layout
.files
);
189 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
190 mProgressBar
.setIndeterminateDrawable(
191 ContextCompat
.getDrawable(this,
192 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
202 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
203 // according to the official
206 // enable ActionBar app icon to behave as action to toggle nav drawer
207 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
208 getSupportActionBar().setHomeButtonEnabled(true
);
210 mProgressBar
.setIndeterminate(mSyncInProgress
);
211 // always AFTER setContentView(...) ; to work around bug in its implementation
215 Log_OC
.v(TAG
, "onCreate() end");
219 protected void onStart() {
220 Log_OC
.v(TAG
, "onStart() start");
222 Log_OC
.v(TAG
, "onStart() end");
226 protected void onStop() {
227 Log_OC
.v(TAG
, "onStop() start");
229 Log_OC
.v(TAG
, "onStop() end");
233 protected void onDestroy() {
234 Log_OC
.v(TAG
, "onDestroy() start");
236 Log_OC
.v(TAG
, "onDestroy() end");
240 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
243 protected void onAccountSet(boolean stateWasRecovered
) {
244 super.onAccountSet(stateWasRecovered
);
245 if (getAccount() != null
) {
246 /// Check whether the 'main' OCFile handled by the Activity is contained in the
248 OCFile file
= getFile();
249 // get parent from path
250 String parentPath
= "";
252 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
253 // upload in progress - right now, files are not inserted in the local
254 // cache until the upload is successful get parent from path
255 parentPath
= file
.getRemotePath().substring(0,
256 file
.getRemotePath().lastIndexOf(file
.getFileName()));
257 if (getStorageManager().getFileByPath(parentPath
) == null
)
258 file
= null
; // not able to know the directory where the file is uploading
260 file
= getStorageManager().getFileByPath(file
.getRemotePath());
261 // currentDir = null if not in the current Account
265 // fall back to root folder
266 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
270 if (mAccountWasSet
) {
271 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
274 if (!stateWasRecovered
) {
275 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
276 initFragmentsWithFile();
277 if (file
.isFolder()) {
278 startSyncFolderOperation(file
, false
);
282 updateFragmentsVisibility(!file
.isFolder());
283 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
301 // TODO Enable when "On Device" is recovered
302 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
305 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
309 OCFile file
= getFile();
310 Fragment secondFragment
= chooseInitialSecondFragment(file
);
311 if (secondFragment
!= null
) {
312 setSecondFragment(secondFragment
);
313 updateFragmentsVisibility(true
);
314 updateActionBarTitleAndHomeButton(file
);
317 cleanSecondFragment();
318 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
319 startTextPreview(file
);
323 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
324 if (getAccount() == null
) {
325 Log_OC
.wtf(TAG
, "\t account is NULL");
327 if (getFile() == null
) {
328 Log_OC
.wtf(TAG
, "\t file is NULL");
333 private Fragment
chooseInitialSecondFragment(OCFile file
) {
334 Fragment secondFragment
= null
;
335 if (file
!= null
&& !file
.isFolder()) {
336 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
337 && file
.getLastSyncDateForProperties() > 0 // temporal fix
339 int startPlaybackPosition
=
340 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
342 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
343 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
344 startPlaybackPosition
, autoplay
);
346 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
347 secondFragment
= null
;
349 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
352 return secondFragment
;
357 * Replaces the second fragment managed by the activity with the received as
360 * Assumes never will be more than two fragments managed at the same time.
362 * @param fragment New second Fragment to set.
364 private void setSecondFragment(Fragment fragment
) {
365 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
366 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
367 transaction
.commit();
371 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 } else if (existsSecondFragment
) {
381 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
382 mLeftFragmentContainer
.setVisibility(View
.GONE
);
384 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
385 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
389 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
390 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
392 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
393 mRightFragmentContainer
.setVisibility(View
.GONE
);
399 private OCFileListFragment
getListOfFilesFragment() {
400 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
401 FileDisplayActivity
.TAG_LIST_OF_FILES
);
402 if (listOfFiles
!= null
) {
403 return (OCFileListFragment
) listOfFiles
;
405 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
409 public FileFragment
getSecondFragment() {
410 Fragment second
= getSupportFragmentManager().findFragmentByTag(
411 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
412 if (second
!= null
) {
413 return (FileFragment
) second
;
418 protected void cleanSecondFragment() {
419 Fragment second
= getSecondFragment();
420 if (second
!= null
) {
421 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
425 updateFragmentsVisibility(false
);
426 updateActionBarTitleAndHomeButton(null
);
429 protected void refreshListOfFilesFragment() {
430 OCFileListFragment fileListFragment
= getListOfFilesFragment();
431 if (fileListFragment
!= null
) {
432 fileListFragment
.listDirectory();
433 // TODO Enable when "On Device" is recovered ?
434 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
438 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
440 FileFragment secondFragment
= getSecondFragment();
441 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
442 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
443 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
444 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
445 OCFile fileInFragment
= detailsFragment
.getFile();
446 if (fileInFragment
!= null
&&
447 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
448 // the user browsed to other file ; forget the automatic preview
449 mWaitingToPreview
= null
;
451 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
452 // grant that the right panel updates the progress bar
453 detailsFragment
.listenForTransferProgress();
454 detailsFragment
.updateFileDetails(true
, false
);
456 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
457 // update the right panel
458 boolean detailsFragmentChanged
= false
;
461 mWaitingToPreview
= getStorageManager().getFileById(
462 mWaitingToPreview
.getFileId()); // update the file from database,
463 // for the local storage path
464 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
465 startMediaPreview(mWaitingToPreview
, 0, true
);
466 detailsFragmentChanged
= true
;
467 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
468 startTextPreview(mWaitingToPreview
);
469 detailsFragmentChanged
= true
;
471 getFileOperationsHelper().openFile(mWaitingToPreview
);
474 mWaitingToPreview
= null
;
476 if (!detailsFragmentChanged
) {
477 detailsFragment
.updateFileDetails(false
, (success
));
484 public boolean onPrepareOptionsMenu(Menu menu
) {
485 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
486 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
487 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
489 return super.onPrepareOptionsMenu(menu
);
493 public boolean onCreateOptionsMenu(Menu menu
) {
494 MenuInflater inflater
= getMenuInflater();
495 inflater
.inflate(R
.menu
.main_menu
, menu
);
496 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
502 public boolean onOptionsItemSelected(MenuItem item
) {
503 boolean retval
= true
;
504 switch (item
.getItemId()) {
505 case R
.id
.action_sync_account
: {
506 startSynchronization();
509 case android
.R
.id
.home
: {
510 FileFragment second
= getSecondFragment();
511 OCFile currentDir
= getCurrentDir();
512 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
513 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
514 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
515 (second
!= null
&& second
.getFile() != null
)) {
519 mDrawerLayout
.openDrawer(GravityCompat
.START
);
523 case R
.id
.action_sort
: {
524 SharedPreferences appPreferences
= PreferenceManager
525 .getDefaultSharedPreferences(this);
527 // Read sorting order, default to sort by name ascending
528 Integer sortOrder
= appPreferences
529 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
531 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
532 builder
.setTitle(R
.string
.actionbar_sort_title
)
533 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
534 new DialogInterface
.OnClickListener() {
535 public void onClick(DialogInterface dialog
, int which
) {
548 builder
.create().show();
552 retval
= super.onOptionsItemSelected(item
);
557 public void createFolder() {
558 CreateFolderDialogFragment dialog
=
559 CreateFolderDialogFragment
.newInstance(getCurrentDir());
560 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
563 public void uploadLocalFilesSelected() {
564 Intent action
= new Intent(this, UploadFilesActivity
.class);
566 UploadFilesActivity
.EXTRA_ACCOUNT
,
569 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
572 public void uploadFromOtherAppsSelected() {
573 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
574 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
575 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
576 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
577 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
579 startActivityForResult(
580 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
581 ACTION_SELECT_CONTENT_FROM_APPS
585 private void startSynchronization() {
586 Log_OC
.d(TAG
, "Got to start sync");
587 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
588 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
589 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
590 // cancel the current synchronizations of any ownCloud account
591 Bundle bundle
= new Bundle();
592 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
593 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
594 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
595 MainApp
.getAuthority());
596 ContentResolver
.requestSync(
598 MainApp
.getAuthority(), bundle
);
600 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
601 MainApp
.getAuthority() + " with new API");
602 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
603 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
604 builder
.setExpedited(true
);
605 builder
.setManual(true
);
608 // Fix bug in Android Lollipop when you click on refresh the whole account
609 Bundle extras
= new Bundle();
610 builder
.setExtras(extras
);
612 SyncRequest request
= builder
.build();
613 ContentResolver
.requestSync(request
);
618 * Called, when the user selected something for uploading
621 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
623 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
625 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
626 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
627 //getClipData is only supported on api level 16+, Jelly Bean
628 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
629 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
630 Intent intent
= new Intent();
631 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
632 requestSimpleUpload(intent
, resultCode
);
635 requestSimpleUpload(data
, resultCode
);
637 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
638 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
639 requestMultipleUpload(data
, resultCode
);
641 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
642 final Intent fData
= data
;
643 final int fResultCode
= resultCode
;
644 getHandler().postDelayed(
648 requestMoveOperation(fData
, fResultCode
);
651 DELAY_TO_REQUEST_OPERATIONS_LATER
654 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
656 final Intent fData
= data
;
657 final int fResultCode
= resultCode
;
658 getHandler().postDelayed(
662 requestCopyOperation(fData
, fResultCode
);
665 DELAY_TO_REQUEST_OPERATIONS_LATER
669 super.onActivityResult(requestCode
, resultCode
, data
);
674 private void requestMultipleUpload(Intent data
, int resultCode
) {
675 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
676 if (filePaths
!= null
) {
677 String
[] remotePaths
= new String
[filePaths
.length
];
678 String remotePathBase
= getCurrentDir().getRemotePath();
679 for (int j
= 0; j
< remotePaths
.length
; j
++) {
680 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
683 Intent i
= new Intent(this, FileUploader
.class);
684 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
685 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
686 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
687 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
688 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
689 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
693 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
694 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
702 private void requestSimpleUpload(Intent data
, int resultCode
) {
703 String filePath
= null
;
704 String mimeType
= null
;
706 Uri selectedImageUri
= data
.getData();
709 mimeType
= getContentResolver().getType(selectedImageUri
);
711 String fileManagerString
= selectedImageUri
.getPath();
712 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
714 if (selectedImagePath
!= null
)
715 filePath
= selectedImagePath
;
717 filePath
= fileManagerString
;
719 } catch (Exception e
) {
720 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
721 "Intent.ACTION_GET_CONTENT", e
);
724 if (filePath
== null
) {
725 Log_OC
.e(TAG
, "Couldn't resolve path to file");
726 Toast t
= Toast
.makeText(
727 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
735 Intent i
= new Intent(this, FileUploader
.class);
736 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
737 OCFile currentDir
= getCurrentDir();
738 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
740 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
741 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
743 if (cursor
!= null
&& cursor
.moveToFirst()) {
744 String displayName
= cursor
.getString(cursor
.getColumnIndex(
745 OpenableColumns
.DISPLAY_NAME
));
746 Log_OC
.v(TAG
, "Display Name: " + displayName
);
748 displayName
.replace(File
.separatorChar
, '_');
749 displayName
.replace(File
.pathSeparatorChar
, '_');
750 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
753 // and what happens in case of error?; wrong target name for the upload
759 remotePath
+= new File(filePath
).getName();
762 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
763 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
764 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
765 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
766 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
767 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
772 * Request the operation for moving the file/folder from one path to another
774 * @param data Intent received
775 * @param resultCode Result code received
777 private void requestMoveOperation(Intent data
, int resultCode
) {
778 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
779 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
780 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
784 * Request the operation for copying the file/folder from one path to another
786 * @param data Intent received
787 * @param resultCode Result code received
789 private void requestCopyOperation(Intent data
, int resultCode
) {
790 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
791 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
792 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
796 public void onBackPressed() {
797 boolean isFabOpen
= isFabOpen();
798 boolean isDrawerOpen
= isDrawerOpen();
801 * BackPressed priority/hierarchy:
802 * 1. close drawer if opened
803 * 2. close FAB if open (only if drawer isn't open)
804 * 3. navigate up (only if drawer and FAB aren't open)
806 if(isDrawerOpen
&& isFabOpen
) {
807 // close drawer first
808 super.onBackPressed();
809 } else if(isDrawerOpen
&& !isFabOpen
) {
811 super.onBackPressed();
812 } else if (!isDrawerOpen
&& isFabOpen
) {
814 getListOfFilesFragment().getFabMain().collapse();
817 OCFileListFragment listOfFiles
= getListOfFilesFragment();
818 if (mDualPane
|| getSecondFragment() == null
) {
819 OCFile currentDir
= getCurrentDir();
820 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
824 if (listOfFiles
!= null
) { // should never be null, indeed
825 listOfFiles
.onBrowseUp();
828 if (listOfFiles
!= null
) { // should never be null, indeed
829 setFile(listOfFiles
.getCurrentFile());
831 cleanSecondFragment();
836 protected void onSaveInstanceState(Bundle outState
) {
837 // responsibility of restore is preferred in onCreate() before than in
838 // onRestoreInstanceState when there are Fragments involved
839 Log_OC
.v(TAG
, "onSaveInstanceState() start");
840 super.onSaveInstanceState(outState
);
841 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
842 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
843 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
844 // mRefreshSharesInProgress);
845 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
847 Log_OC
.v(TAG
, "onSaveInstanceState() end");
852 protected void onResume() {
853 Log_OC
.v(TAG
, "onResume() start");
855 // refresh Navigation Drawer account list
856 mNavigationDrawerAdapter
.updateAccountList();
858 // refresh list of files
859 refreshListOfFilesFragment();
861 // Listen for sync messages
862 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
863 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
864 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
865 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
866 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
867 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
868 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
869 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
870 // syncIntentFilter);
872 // Listen for upload messages
873 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
874 mUploadFinishReceiver
= new UploadFinishReceiver();
875 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
877 // Listen for download messages
878 IntentFilter downloadIntentFilter
= new IntentFilter(
879 FileDownloader
.getDownloadAddedMessage());
880 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
881 mDownloadFinishReceiver
= new DownloadFinishReceiver();
882 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
884 Log_OC
.v(TAG
, "onResume() end");
890 protected void onPause() {
891 Log_OC
.v(TAG
, "onPause() start");
892 if (mSyncBroadcastReceiver
!= null
) {
893 unregisterReceiver(mSyncBroadcastReceiver
);
894 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
895 mSyncBroadcastReceiver
= null
;
897 if (mUploadFinishReceiver
!= null
) {
898 unregisterReceiver(mUploadFinishReceiver
);
899 mUploadFinishReceiver
= null
;
901 if (mDownloadFinishReceiver
!= null
) {
902 unregisterReceiver(mDownloadFinishReceiver
);
903 mDownloadFinishReceiver
= null
;
907 Log_OC
.v(TAG
, "onPause() end");
910 public boolean isFabOpen() {
911 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
919 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
922 * {@link BroadcastReceiver} to enable syncing feedback in UI
925 public void onReceive(Context context
, Intent intent
) {
927 String event
= intent
.getAction();
928 Log_OC
.d(TAG
, "Received broadcast " + event
);
929 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
930 String synchFolderRemotePath
=
931 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
932 RemoteOperationResult synchResult
=
933 (RemoteOperationResult
)intent
.getSerializableExtra(
934 FileSyncAdapter
.EXTRA_RESULT
);
935 boolean sameAccount
= (getAccount() != null
&&
936 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
940 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
941 mSyncInProgress
= true
;
944 OCFile currentFile
= (getFile() == null
) ? null
:
945 getStorageManager().getFileByPath(getFile().getRemotePath());
946 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
947 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
949 if (currentDir
== null
) {
950 // current folder was removed from the server
951 Toast
.makeText( FileDisplayActivity
.this,
954 sync_current_folder_was_removed
),
955 synchFolderRemotePath
),
962 if (currentFile
== null
&& !getFile().isFolder()) {
963 // currently selected file was removed in the server, and now we
965 cleanSecondFragment();
966 currentFile
= currentDir
;
969 if (synchFolderRemotePath
!= null
&&
970 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
971 OCFileListFragment fileListFragment
= getListOfFilesFragment();
972 if (fileListFragment
!= null
) {
973 fileListFragment
.listDirectory();
974 // TODO Enable when "On Device" is recovered ?
975 // fileListFragment.listDirectory(currentDir,
976 // MainApp.getOnlyOnDevice());
979 setFile(currentFile
);
982 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
983 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
986 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
987 equals(event
) &&/// TODO refactor and make common
989 synchResult
!= null
&& !synchResult
.isSuccess() &&
990 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
991 synchResult
.isIdPRedirection() ||
992 (synchResult
.isException() && synchResult
.getException()
993 instanceof AuthenticatorException
))) {
997 OwnCloudClient client
;
998 OwnCloudAccount ocAccount
=
999 new OwnCloudAccount(getAccount(), context
);
1000 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1001 removeClientFor(ocAccount
));
1002 if (client
!= null
) {
1003 OwnCloudCredentials cred
= client
.getCredentials();
1005 AccountManager am
= AccountManager
.get(context
);
1006 if (cred
.authTokenExpires()) {
1007 am
.invalidateAuthToken(
1012 am
.clearPassword(getAccount());
1016 requestCredentialsUpdate();
1018 } catch (AccountNotFoundException e
) {
1019 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1025 removeStickyBroadcast(intent
);
1026 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1027 mProgressBar
.setIndeterminate(mSyncInProgress
);
1028 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1029 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1030 /*|| mRefreshSharesInProgress*/ //);
1032 setBackgroundText();
1036 if (synchResult
!= null
) {
1037 if (synchResult
.getCode().equals(
1038 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1039 mLastSslUntrustedServerResult
= synchResult
;
1042 } catch (RuntimeException e
) {
1043 // avoid app crashes after changing the serial id of RemoteOperationResult
1044 // in owncloud library with broadcast notifications pending to process
1045 removeStickyBroadcast(intent
);
1051 * Show a text message on screen view for notifying user if content is
1052 * loading or folder is empty
1054 private void setBackgroundText() {
1055 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1056 if (ocFileListFragment
!= null
) {
1057 int message
= R
.string
.file_list_loading
;
1058 if (!mSyncInProgress
) {
1059 // In case file list is empty
1060 message
= R
.string
.file_list_empty
;
1062 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1064 Log_OC
.e(TAG
, "OCFileListFragment is null");
1069 * Once the file upload has finished -> update view
1071 private class UploadFinishReceiver
extends BroadcastReceiver
{
1073 * Once the file upload has finished -> update view
1075 * @author David A. Velasco
1076 * {@link BroadcastReceiver} to enable upload feedback in UI
1079 public void onReceive(Context context
, Intent intent
) {
1081 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1082 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1083 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1084 OCFile currentDir
= getCurrentDir();
1085 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1086 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1088 if (sameAccount
&& isDescendant
) {
1089 String linkedToRemotePath
=
1090 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1091 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1092 refreshListOfFilesFragment();
1096 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1098 boolean renamedInUpload
= getFile().getRemotePath().
1099 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1100 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1102 FileFragment details
= getSecondFragment();
1103 boolean detailFragmentIsShown
= (details
!= null
&&
1104 details
instanceof FileDetailFragment
);
1106 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1107 if (uploadWasFine
) {
1108 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1110 if (renamedInUpload
) {
1111 String newName
= (new File(uploadedRemotePath
)).getName();
1112 Toast msg
= Toast
.makeText(
1115 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1120 if (uploadWasFine
|| getFile().fileExists()) {
1121 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1123 cleanSecondFragment();
1126 // Force the preview if the file is an image or text file
1127 if (uploadWasFine
) {
1128 OCFile ocFile
= getFile();
1129 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1130 startImagePreview(getFile());
1131 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1132 startTextPreview(ocFile
);
1133 // TODO what about other kind of previews?
1137 mProgressBar
.setIndeterminate(false
);
1139 if (intent
!= null
) {
1140 removeStickyBroadcast(intent
);
1146 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1147 private boolean isAscendant(String linkedToRemotePath
) {
1148 OCFile currentDir
= getCurrentDir();
1150 currentDir
!= null
&&
1151 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1160 * Class waiting for broadcast events from the {@link FileDownloader} service.
1162 * Updates the UI when a download is started or finished, provided that it is relevant for the
1165 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1168 public void onReceive(Context context
, Intent intent
) {
1170 boolean sameAccount
= isSameAccount(intent
);
1171 String downloadedRemotePath
=
1172 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1173 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1175 if (sameAccount
&& isDescendant
) {
1176 String linkedToRemotePath
=
1177 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1178 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1179 refreshListOfFilesFragment();
1181 refreshSecondFragment(
1183 downloadedRemotePath
,
1184 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1188 if (mWaitingToSend
!= null
) {
1190 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1191 if (mWaitingToSend
.isDown()) {
1192 sendDownloadedFile();
1197 if (intent
!= null
) {
1198 removeStickyBroadcast(intent
);
1203 private boolean isDescendant(String downloadedRemotePath
) {
1204 OCFile currentDir
= getCurrentDir();
1206 currentDir
!= null
&&
1207 downloadedRemotePath
!= null
&&
1208 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1212 private boolean isAscendant(String linkedToRemotePath
) {
1213 OCFile currentDir
= getCurrentDir();
1215 currentDir
!= null
&&
1216 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1220 private boolean isSameAccount(Intent intent
) {
1221 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1222 return (accountName
!= null
&& getAccount() != null
&&
1223 accountName
.equals(getAccount().name
));
1228 public void browseToRoot() {
1229 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1230 if (listOfFiles
!= null
) { // should never be null, indeed
1231 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1232 listOfFiles
.listDirectory(root
);
1233 // TODO Enable when "On Device" is recovered ?
1234 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1235 setFile(listOfFiles
.getCurrentFile());
1236 startSyncFolderOperation(root
, false
);
1238 cleanSecondFragment();
1245 * Updates action bar and second fragment, if in dual pane mode.
1248 public void onBrowsedDownTo(OCFile directory
) {
1250 cleanSecondFragment();
1252 startSyncFolderOperation(directory
, false
);
1256 * Shows the information of the {@link OCFile} received as a
1257 * parameter in the second fragment.
1259 * @param file {@link OCFile} whose details will be shown
1262 public void showDetails(OCFile file
) {
1263 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1264 setSecondFragment(detailFragment
);
1265 updateFragmentsVisibility(true
);
1266 updateActionBarTitleAndHomeButton(file
);
1271 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1273 // in dual pane mode, keep the focus of title an action bar in the current folder
1274 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1277 super.updateActionBarTitleAndHomeButton(chosenFile
);
1283 protected ServiceConnection
newTransferenceServiceConnection() {
1284 return new ListServiceConnection();
1288 * Defines callbacks for service binding, passed to bindService()
1290 private class ListServiceConnection
implements ServiceConnection
{
1293 public void onServiceConnected(ComponentName component
, IBinder service
) {
1294 if (component
.equals(new ComponentName(
1295 FileDisplayActivity
.this, FileDownloader
.class))) {
1296 Log_OC
.d(TAG
, "Download service connected");
1297 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1298 if (mWaitingToPreview
!= null
)
1299 if (getStorageManager() != null
) {
1302 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1303 if (!mWaitingToPreview
.isDown()) {
1304 requestForDownload();
1308 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1309 FileUploader
.class))) {
1310 Log_OC
.d(TAG
, "Upload service connected");
1311 mUploaderBinder
= (FileUploaderBinder
) service
;
1315 // a new chance to get the mDownloadBinder through
1316 // getFileDownloadBinder() - THIS IS A MESS
1317 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1318 if (listOfFiles
!= null
) {
1319 listOfFiles
.listDirectory();
1320 // TODO Enable when "On Device" is recovered ?
1321 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1323 FileFragment secondFragment
= getSecondFragment();
1324 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1325 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1326 detailFragment
.listenForTransferProgress();
1327 detailFragment
.updateFileDetails(false
, false
);
1332 public void onServiceDisconnected(ComponentName component
) {
1333 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1334 FileDownloader
.class))) {
1335 Log_OC
.d(TAG
, "Download service disconnected");
1336 mDownloaderBinder
= null
;
1337 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1338 FileUploader
.class))) {
1339 Log_OC
.d(TAG
, "Upload service disconnected");
1340 mUploaderBinder
= null
;
1346 public void onSavedCertificate() {
1347 startSyncFolderOperation(getCurrentDir(), false
);
1352 public void onFailedSavingCertificate() {
1353 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1354 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1356 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1360 public void onCancelCertificate() {
1365 * Updates the view associated to the activity after the finish of some operation over files
1366 * in the current account.
1368 * @param operation Removal operation performed.
1369 * @param result Result of the removal.
1372 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1373 super.onRemoteOperationFinish(operation
, result
);
1375 if (operation
instanceof RemoveFileOperation
) {
1376 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1378 } else if (operation
instanceof RenameFileOperation
) {
1379 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1381 } else if (operation
instanceof SynchronizeFileOperation
) {
1382 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1384 } else if (operation
instanceof CreateFolderOperation
) {
1385 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1387 } else if (operation
instanceof MoveFileOperation
) {
1388 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1390 } else if (operation
instanceof CopyFileOperation
) {
1391 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1396 private void refreshShowDetails() {
1397 FileFragment details
= getSecondFragment();
1398 if (details
!= null
) {
1399 OCFile file
= details
.getFile();
1401 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1402 if (details
instanceof PreviewMediaFragment
) {
1403 // Refresh OCFile of the fragment
1404 ((PreviewMediaFragment
) details
).updateFile(file
);
1405 } else if (details
instanceof PreviewTextFragment
) {
1406 // Refresh OCFile of the fragment
1407 ((PreviewTextFragment
) details
).updateFile(file
);
1412 invalidateOptionsMenu();
1417 * Updates the view associated to the activity after the finish of an operation trying to
1420 * @param operation Removal operation performed.
1421 * @param result Result of the removal.
1423 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1424 RemoteOperationResult result
) {
1425 Toast msg
= Toast
.makeText(this,
1426 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1430 if (result
.isSuccess()) {
1431 OCFile removedFile
= operation
.getFile();
1432 FileFragment second
= getSecondFragment();
1433 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1434 if (second
instanceof PreviewMediaFragment
) {
1435 ((PreviewMediaFragment
) second
).stopPreview(true
);
1437 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1438 cleanSecondFragment();
1440 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1441 refreshListOfFilesFragment();
1443 invalidateOptionsMenu();
1445 if (result
.isSslRecoverableException()) {
1446 mLastSslUntrustedServerResult
= result
;
1447 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1454 * Updates the view associated to the activity after the finish of an operation trying to move a
1457 * @param operation Move operation performed.
1458 * @param result Result of the move operation.
1460 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1461 RemoteOperationResult result
) {
1462 if (result
.isSuccess()) {
1463 refreshListOfFilesFragment();
1466 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1467 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1471 } catch (NotFoundException e
) {
1472 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1478 * Updates the view associated to the activity after the finish of an operation trying to copy a
1481 * @param operation Copy operation performed.
1482 * @param result Result of the copy operation.
1484 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1485 if (result
.isSuccess()) {
1486 refreshListOfFilesFragment();
1489 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1490 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1494 } catch (NotFoundException e
) {
1495 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1501 * Updates the view associated to the activity after the finish of an operation trying to rename
1504 * @param operation Renaming operation performed.
1505 * @param result Result of the renaming.
1507 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1508 RemoteOperationResult result
) {
1509 OCFile renamedFile
= operation
.getFile();
1510 if (result
.isSuccess()) {
1511 FileFragment details
= getSecondFragment();
1512 if (details
!= null
) {
1513 if (details
instanceof FileDetailFragment
&&
1514 renamedFile
.equals(details
.getFile()) ) {
1515 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1516 showDetails(renamedFile
);
1518 } else if (details
instanceof PreviewMediaFragment
&&
1519 renamedFile
.equals(details
.getFile())) {
1520 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1521 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1522 int position
= ((PreviewMediaFragment
) details
).getPosition();
1523 startMediaPreview(renamedFile
, position
, true
);
1525 getFileOperationsHelper().openFile(renamedFile
);
1527 } else if (details
instanceof PreviewTextFragment
&&
1528 renamedFile
.equals(details
.getFile())) {
1529 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1530 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1531 startTextPreview(renamedFile
);
1533 getFileOperationsHelper().openFile(renamedFile
);
1538 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1539 refreshListOfFilesFragment();
1543 Toast msg
= Toast
.makeText(this,
1544 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1548 if (result
.isSslRecoverableException()) {
1549 mLastSslUntrustedServerResult
= result
;
1550 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1555 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1556 RemoteOperationResult result
) {
1557 if (result
.isSuccess()) {
1558 if (operation
.transferWasRequested()) {
1559 OCFile syncedFile
= operation
.getLocalFile();
1560 onTransferStateChanged(syncedFile
, true
, true
);
1561 invalidateOptionsMenu();
1562 refreshShowDetails();
1568 * Updates the view associated to the activity after the finish of an operation trying create a
1571 * @param operation Creation operation performed.
1572 * @param result Result of the creation.
1574 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1575 RemoteOperationResult result
) {
1576 if (result
.isSuccess()) {
1577 refreshListOfFilesFragment();
1580 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1581 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1585 } catch (NotFoundException e
) {
1586 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1596 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1597 refreshListOfFilesFragment();
1598 FileFragment details
= getSecondFragment();
1599 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1600 file
.equals(details
.getFile()) ) {
1601 if (downloading
|| uploading
) {
1602 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1604 if (!file
.fileExists()) {
1605 cleanSecondFragment();
1607 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1615 private void requestForDownload() {
1616 Account account
= getAccount();
1617 //if (!mWaitingToPreview.isDownloading()) {
1618 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1619 Intent i
= new Intent(this, FileDownloader
.class);
1620 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1621 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1627 private OCFile
getCurrentDir() {
1628 OCFile file
= getFile();
1630 if (file
.isFolder()) {
1632 } else if (getStorageManager() != null
) {
1633 String parentPath
= file
.getRemotePath().substring(0,
1634 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1635 return getStorageManager().getFileByPath(parentPath
);
1642 * Starts an operation to refresh the requested folder.
1644 * The operation is run in a new background thread created on the fly.
1646 * The refresh updates is a "light sync": properties of regular files in folder are updated (including
1647 * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
1650 * @param folder Folder to refresh.
1651 * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
1654 public void startSyncFolderOperation(final OCFile folder
, final boolean ignoreETag
) {
1656 // the execution is slightly delayed to allow the activity get the window focus if it's being started
1657 // or if the method is called from a dialog that is being dismissed
1658 getHandler().postDelayed(
1662 if (hasWindowFocus()) {
1663 long currentSyncTime
= System
.currentTimeMillis();
1664 mSyncInProgress
= true
;
1666 // perform folder synchronization
1667 RemoteOperation synchFolderOp
= new RefreshFolderOperation(folder
,
1670 getFileOperationsHelper().isSharedSupported(),
1672 getStorageManager(),
1674 getApplicationContext()
1676 synchFolderOp
.execute(
1678 MainApp
.getAppContext(),
1679 FileDisplayActivity
.this,
1684 mProgressBar
.setIndeterminate(true
);
1686 setBackgroundText();
1688 } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
1689 // another window floating over
1692 DELAY_TO_REQUEST_OPERATIONS_LATER
1698 * Show untrusted cert dialog
1700 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1701 // Show a dialog with the certificate info
1702 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1703 (CertificateCombinedException
) result
.getException());
1704 FragmentManager fm
= getSupportFragmentManager();
1705 FragmentTransaction ft
= fm
.beginTransaction();
1706 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1709 private void requestForDownload(OCFile file
) {
1710 Account account
= getAccount();
1711 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1712 Intent i
= new Intent(this, FileDownloader
.class);
1713 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1714 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1719 private void sendDownloadedFile() {
1720 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1721 mWaitingToSend
= null
;
1726 * Requests the download of the received {@link OCFile} , updates the UI
1727 * to monitor the download progress and prepares the activity to send the file
1728 * when the download finishes.
1730 * @param file {@link OCFile} to download and preview.
1732 public void startDownloadForSending(OCFile file
) {
1733 mWaitingToSend
= file
;
1734 requestForDownload(mWaitingToSend
);
1735 boolean hasSecondFragment
= (getSecondFragment() != null
);
1736 updateFragmentsVisibility(hasSecondFragment
);
1740 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1742 * @param file Image {@link OCFile} to show.
1744 public void startImagePreview(OCFile file
) {
1745 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1746 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1747 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1748 startActivity(showDetailsIntent
);
1752 * Stars the preview of an already down media {@link OCFile}.
1754 * @param file Media {@link OCFile} to preview.
1755 * @param startPlaybackPosition Media position where the playback will be started,
1757 * @param autoplay When 'true', the playback will start without user
1760 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1761 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1763 setSecondFragment(mediaFragment
);
1764 updateFragmentsVisibility(true
);
1765 updateActionBarTitleAndHomeButton(file
);
1770 * Stars the preview of a text file {@link OCFile}.
1772 * @param file Text {@link OCFile} to preview.
1774 public void startTextPreview(OCFile file
) {
1775 Bundle args
= new Bundle();
1776 args
.putParcelable(EXTRA_FILE
, file
);
1777 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1778 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1779 PreviewTextFragment
.class.getName(), args
);
1780 setSecondFragment(textPreviewFragment
);
1781 updateFragmentsVisibility(true
);
1782 //updateNavigationElementsInActionBar(file);
1787 * Requests the download of the received {@link OCFile} , updates the UI
1788 * to monitor the download progress and prepares the activity to preview
1789 * or open the file when the download finishes.
1791 * @param file {@link OCFile} to download and preview.
1793 public void startDownloadForPreview(OCFile file
) {
1794 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1795 setSecondFragment(detailFragment
);
1796 mWaitingToPreview
= file
;
1797 requestForDownload();
1798 updateFragmentsVisibility(true
);
1799 updateActionBarTitleAndHomeButton(file
);
1804 public void cancelTransference(OCFile file
) {
1805 getFileOperationsHelper().cancelTransference(file
);
1806 if (mWaitingToPreview
!= null
&&
1807 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1808 mWaitingToPreview
= null
;
1810 if (mWaitingToSend
!= null
&&
1811 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1812 mWaitingToSend
= null
;
1814 onTransferStateChanged(file
, false
, false
);
1818 public void onRefresh(boolean ignoreETag
) {
1819 refreshList(ignoreETag
);
1823 public void onRefresh() {
1827 private void refreshList(boolean ignoreETag
) {
1828 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1829 if (listOfFiles
!= null
) {
1830 OCFile folder
= listOfFiles
.getCurrentFile();
1831 if (folder
!= null
) {
1832 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1833 listDirectory(mFile);*/
1834 startSyncFolderOperation(folder
, ignoreETag
);
1839 private void sortByDate(boolean ascending
) {
1840 getListOfFilesFragment().sortByDate(ascending
);
1843 private void sortBySize(boolean ascending
) {
1844 getListOfFilesFragment().sortBySize(ascending
);
1847 private void sortByName(boolean ascending
) {
1848 getListOfFilesFragment().sortByName(ascending
);
1851 public void allFilesOption() {