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
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.FileStorageUtils
;
107 import com
.owncloud
.android
.utils
.UriUtils
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
116 implements FileFragment
.ContainerActivity
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
129 private ProgressBar mProgressBar
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
140 public static final int ACTION_COPY_FILES
= 4;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
152 public static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
153 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
154 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
160 protected void onCreate(Bundle savedInstanceState
) {
161 Log_OC
.v(TAG
, "onCreate() start");
163 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
166 /// grant that FileObserverService is watching favorite files
167 if (savedInstanceState
== null
) {
168 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
169 startService(initObserversIntent
);
172 /// Load of saved instance state
173 if(savedInstanceState
!= null
) {
174 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
175 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
176 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
177 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
178 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
180 mWaitingToPreview
= null
;
181 mSyncInProgress
= false
;
182 mWaitingToSend
= null
;
187 // Inflate and set the layout view
188 setContentView(R
.layout
.files
);
193 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
194 mProgressBar
.setIndeterminateDrawable(
195 ContextCompat
.getDrawable(this,
196 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
198 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
199 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
200 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
201 if (savedInstanceState
== null
) {
202 createMinFragments();
206 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
207 // according to the official
210 // enable ActionBar app icon to behave as action to toggle nav drawer
211 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
212 getSupportActionBar().setHomeButtonEnabled(true
);
214 mProgressBar
.setIndeterminate(mSyncInProgress
);
215 // always AFTER setContentView(...) ; to work around bug in its implementation
219 Log_OC
.v(TAG
, "onCreate() end");
223 protected void onStart() {
224 Log_OC
.v(TAG
, "onStart() start");
226 Log_OC
.v(TAG
, "onStart() end");
230 protected void onDestroy() {
231 Log_OC
.v(TAG
, "onDestroy() start");
233 Log_OC
.v(TAG
, "onDestroy() end");
237 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
240 protected void onAccountSet(boolean stateWasRecovered
) {
241 super.onAccountSet(stateWasRecovered
);
242 if (getAccount() != null
) {
243 /// Check whether the 'main' OCFile handled by the Activity is contained in the
245 OCFile file
= getFile();
246 // get parent from path
247 String parentPath
= "";
249 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
250 // upload in progress - right now, files are not inserted in the local
251 // cache until the upload is successful get parent from path
252 parentPath
= file
.getRemotePath().substring(0,
253 file
.getRemotePath().lastIndexOf(file
.getFileName()));
254 if (getStorageManager().getFileByPath(parentPath
) == null
)
255 file
= null
; // not able to know the directory where the file is uploading
257 file
= getStorageManager().getFileByPath(file
.getRemotePath());
258 // currentDir = null if not in the current Account
262 // fall back to root folder
263 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
267 if (mAccountWasSet
) {
268 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
271 if (!stateWasRecovered
) {
272 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
273 initFragmentsWithFile();
274 if (file
.isFolder()) {
275 startSyncFolderOperation(file
, false
);
279 updateFragmentsVisibility(!file
.isFolder());
280 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
285 private void createMinFragments() {
286 OCFileListFragment listOfFiles
= new OCFileListFragment();
287 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
288 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
289 transaction
.commit();
292 private void initFragmentsWithFile() {
293 if (getAccount() != null
&& getFile() != null
) {
295 OCFileListFragment listOfFiles
= getListOfFilesFragment();
296 if (listOfFiles
!= null
) {
297 listOfFiles
.listDirectory(getCurrentDir());
298 // TODO Enable when "On Device" is recovered
299 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
302 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
306 OCFile file
= getFile();
307 Fragment secondFragment
= chooseInitialSecondFragment(file
);
308 if (secondFragment
!= null
) {
309 setSecondFragment(secondFragment
);
310 updateFragmentsVisibility(true
);
311 updateActionBarTitleAndHomeButton(file
);
314 cleanSecondFragment();
315 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
316 startTextPreview(file
);
320 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
321 if (getAccount() == null
) {
322 Log_OC
.wtf(TAG
, "\t account is NULL");
324 if (getFile() == null
) {
325 Log_OC
.wtf(TAG
, "\t file is NULL");
330 private Fragment
chooseInitialSecondFragment(OCFile file
) {
331 Fragment secondFragment
= null
;
332 if (file
!= null
&& !file
.isFolder()) {
333 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
334 && file
.getLastSyncDateForProperties() > 0 // temporal fix
336 int startPlaybackPosition
=
337 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
339 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
340 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
341 startPlaybackPosition
, autoplay
);
343 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
344 secondFragment
= null
;
346 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
349 return secondFragment
;
354 * Replaces the second fragment managed by the activity with the received as
357 * Assumes never will be more than two fragments managed at the same time.
359 * @param fragment New second Fragment to set.
361 private void setSecondFragment(Fragment fragment
) {
362 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
363 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
364 transaction
.commit();
368 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
370 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
371 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
373 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
377 } else if (existsSecondFragment
) {
378 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
379 mLeftFragmentContainer
.setVisibility(View
.GONE
);
381 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
386 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
389 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
390 mRightFragmentContainer
.setVisibility(View
.GONE
);
396 private OCFileListFragment
getListOfFilesFragment() {
397 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
398 FileDisplayActivity
.TAG_LIST_OF_FILES
);
399 if (listOfFiles
!= null
) {
400 return (OCFileListFragment
) listOfFiles
;
402 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
406 public FileFragment
getSecondFragment() {
407 Fragment second
= getSupportFragmentManager().findFragmentByTag(
408 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
409 if (second
!= null
) {
410 return (FileFragment
) second
;
415 protected void cleanSecondFragment() {
416 Fragment second
= getSecondFragment();
417 if (second
!= null
) {
418 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
422 updateFragmentsVisibility(false
);
423 updateActionBarTitleAndHomeButton(null
);
426 protected void refreshListOfFilesFragment() {
427 OCFileListFragment fileListFragment
= getListOfFilesFragment();
428 if (fileListFragment
!= null
) {
429 fileListFragment
.listDirectory();
430 // TODO Enable when "On Device" is recovered ?
431 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
435 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
437 FileFragment secondFragment
= getSecondFragment();
438 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
439 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
440 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
441 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
442 OCFile fileInFragment
= detailsFragment
.getFile();
443 if (fileInFragment
!= null
&&
444 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
445 // the user browsed to other file ; forget the automatic preview
446 mWaitingToPreview
= null
;
448 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
449 // grant that the right panel updates the progress bar
450 detailsFragment
.listenForTransferProgress();
451 detailsFragment
.updateFileDetails(true
, false
);
453 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
454 // update the right panel
455 boolean detailsFragmentChanged
= false
;
458 mWaitingToPreview
= getStorageManager().getFileById(
459 mWaitingToPreview
.getFileId()); // update the file from database,
460 // for the local storage path
461 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
462 startMediaPreview(mWaitingToPreview
, 0, true
);
463 detailsFragmentChanged
= true
;
464 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
465 startTextPreview(mWaitingToPreview
);
466 detailsFragmentChanged
= true
;
468 getFileOperationsHelper().openFile(mWaitingToPreview
);
471 mWaitingToPreview
= null
;
473 if (!detailsFragmentChanged
) {
474 detailsFragment
.updateFileDetails(false
, (success
));
481 public boolean onPrepareOptionsMenu(Menu menu
) {
482 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
483 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
484 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
486 return super.onPrepareOptionsMenu(menu
);
490 public boolean onCreateOptionsMenu(Menu menu
) {
491 MenuInflater inflater
= getMenuInflater();
492 inflater
.inflate(R
.menu
.main_menu
, menu
);
493 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
499 public boolean onOptionsItemSelected(MenuItem item
) {
500 boolean retval
= true
;
501 switch (item
.getItemId()) {
502 case R
.id
.action_sync_account
: {
503 startSynchronization();
506 case android
.R
.id
.home
: {
507 FileFragment second
= getSecondFragment();
508 OCFile currentDir
= getCurrentDir();
509 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
510 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
511 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
512 (second
!= null
&& second
.getFile() != null
)) {
516 mDrawerLayout
.openDrawer(GravityCompat
.START
);
520 case R
.id
.action_sort
: {
521 SharedPreferences appPreferences
= PreferenceManager
522 .getDefaultSharedPreferences(this);
524 // Read sorting order, default to sort by name ascending
525 Integer sortOrder
= appPreferences
526 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
528 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
529 builder
.setTitle(R
.string
.actionbar_sort_title
)
530 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
531 new DialogInterface
.OnClickListener() {
532 public void onClick(DialogInterface dialog
, int which
) {
545 builder
.create().show();
549 retval
= super.onOptionsItemSelected(item
);
554 public void createFolder() {
555 CreateFolderDialogFragment dialog
=
556 CreateFolderDialogFragment
.newInstance(getCurrentDir());
557 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
560 public void uploadLocalFilesSelected() {
561 Intent action
= new Intent(this, UploadFilesActivity
.class);
563 UploadFilesActivity
.EXTRA_ACCOUNT
,
566 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
569 public void uploadFromOtherAppsSelected() {
570 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
571 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
572 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
573 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
574 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
576 startActivityForResult(
577 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
578 ACTION_SELECT_CONTENT_FROM_APPS
582 private void startSynchronization() {
583 Log_OC
.d(TAG
, "Got to start sync");
584 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
585 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
586 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
587 // cancel the current synchronizations of any ownCloud account
588 Bundle bundle
= new Bundle();
589 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
590 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
591 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
592 MainApp
.getAuthority());
593 ContentResolver
.requestSync(
595 MainApp
.getAuthority(), bundle
);
597 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
598 MainApp
.getAuthority() + " with new API");
599 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
600 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
601 builder
.setExpedited(true
);
602 builder
.setManual(true
);
605 // Fix bug in Android Lollipop when you click on refresh the whole account
606 Bundle extras
= new Bundle();
607 builder
.setExtras(extras
);
609 SyncRequest request
= builder
.build();
610 ContentResolver
.requestSync(request
);
615 * Called, when the user selected something for uploading
618 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
620 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
622 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
623 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
624 //getClipData is only supported on api level 16+, Jelly Bean
625 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
626 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
627 Intent intent
= new Intent();
628 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
629 requestSimpleUpload(intent
, resultCode
);
632 requestSimpleUpload(data
, resultCode
);
634 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
635 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
636 requestMultipleUpload(data
, resultCode
);
638 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
639 final Intent fData
= data
;
640 final int fResultCode
= resultCode
;
641 getHandler().postDelayed(
645 requestMoveOperation(fData
, fResultCode
);
648 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
651 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
653 final Intent fData
= data
;
654 final int fResultCode
= resultCode
;
655 getHandler().postDelayed(
659 requestCopyOperation(fData
, fResultCode
);
662 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
666 super.onActivityResult(requestCode
, resultCode
, data
);
671 private void requestMultipleUpload(Intent data
, int resultCode
) {
672 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
673 if (filePaths
!= null
) {
674 String
[] remotePaths
= new String
[filePaths
.length
];
675 String remotePathBase
= getCurrentDir().getRemotePath();
676 for (int j
= 0; j
< remotePaths
.length
; j
++) {
677 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
680 Intent i
= new Intent(this, FileUploader
.class);
681 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
682 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
683 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
684 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
685 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
686 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
690 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
691 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
699 private void requestSimpleUpload(Intent data
, int resultCode
) {
700 String filePath
= null
;
701 String mimeType
= null
;
703 Uri selectedImageUri
= data
.getData();
706 mimeType
= getContentResolver().getType(selectedImageUri
);
708 String fileManagerString
= selectedImageUri
.getPath();
709 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
711 if (selectedImagePath
!= null
)
712 filePath
= selectedImagePath
;
714 filePath
= fileManagerString
;
716 } catch (Exception e
) {
717 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
718 "Intent.ACTION_GET_CONTENT", e
);
721 if (filePath
== null
) {
722 Log_OC
.e(TAG
, "Couldn't resolve path to file");
723 Toast t
= Toast
.makeText(
724 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
732 Intent i
= new Intent(this, FileUploader
.class);
733 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
734 OCFile currentDir
= getCurrentDir();
735 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
737 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
738 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
740 if (cursor
!= null
&& cursor
.moveToFirst()) {
741 String displayName
= cursor
.getString(cursor
.getColumnIndex(
742 OpenableColumns
.DISPLAY_NAME
));
743 Log_OC
.v(TAG
, "Display Name: " + displayName
);
745 displayName
.replace(File
.separatorChar
, '_');
746 displayName
.replace(File
.pathSeparatorChar
, '_');
747 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
750 // and what happens in case of error?; wrong target name for the upload
756 remotePath
+= new File(filePath
).getName();
759 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
760 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
761 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
762 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
763 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
764 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
769 * Request the operation for moving the file/folder from one path to another
771 * @param data Intent received
772 * @param resultCode Result code received
774 private void requestMoveOperation(Intent data
, int resultCode
) {
775 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
776 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
777 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
781 * Request the operation for copying the file/folder from one path to another
783 * @param data Intent received
784 * @param resultCode Result code received
786 private void requestCopyOperation(Intent data
, int resultCode
) {
787 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
788 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
789 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
793 public void onBackPressed() {
794 boolean isFabOpen
= isFabOpen();
795 boolean isDrawerOpen
= isDrawerOpen();
798 * BackPressed priority/hierarchy:
799 * 1. close drawer if opened
800 * 2. close FAB if open (only if drawer isn't open)
801 * 3. navigate up (only if drawer and FAB aren't open)
803 if(isDrawerOpen
&& isFabOpen
) {
804 // close drawer first
805 super.onBackPressed();
806 } else if(isDrawerOpen
&& !isFabOpen
) {
808 super.onBackPressed();
809 } else if (!isDrawerOpen
&& isFabOpen
) {
811 getListOfFilesFragment().getFabMain().collapse();
814 OCFileListFragment listOfFiles
= getListOfFilesFragment();
815 if (mDualPane
|| getSecondFragment() == null
) {
816 OCFile currentDir
= getCurrentDir();
817 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
821 if (listOfFiles
!= null
) { // should never be null, indeed
822 listOfFiles
.onBrowseUp();
825 if (listOfFiles
!= null
) { // should never be null, indeed
826 setFile(listOfFiles
.getCurrentFile());
828 cleanSecondFragment();
833 protected void onSaveInstanceState(Bundle outState
) {
834 // responsibility of restore is preferred in onCreate() before than in
835 // onRestoreInstanceState when there are Fragments involved
836 Log_OC
.v(TAG
, "onSaveInstanceState() start");
837 super.onSaveInstanceState(outState
);
838 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
839 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
840 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
841 // mRefreshSharesInProgress);
842 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
844 Log_OC
.v(TAG
, "onSaveInstanceState() end");
849 protected void onResume() {
850 Log_OC
.v(TAG
, "onResume() start");
852 // refresh Navigation Drawer account list
853 mNavigationDrawerAdapter
.updateAccountList();
855 // refresh list of files
856 refreshListOfFilesFragment();
858 // Listen for sync messages
859 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
860 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
861 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
862 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
863 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
864 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
865 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
866 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
867 // syncIntentFilter);
869 // Listen for upload messages
870 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
871 mUploadFinishReceiver
= new UploadFinishReceiver();
872 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
874 // Listen for download messages
875 IntentFilter downloadIntentFilter
= new IntentFilter(
876 FileDownloader
.getDownloadAddedMessage());
877 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
878 mDownloadFinishReceiver
= new DownloadFinishReceiver();
879 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
881 Log_OC
.v(TAG
, "onResume() end");
887 protected void onPause() {
888 Log_OC
.v(TAG
, "onPause() start");
889 if (mSyncBroadcastReceiver
!= null
) {
890 unregisterReceiver(mSyncBroadcastReceiver
);
891 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
892 mSyncBroadcastReceiver
= null
;
894 if (mUploadFinishReceiver
!= null
) {
895 unregisterReceiver(mUploadFinishReceiver
);
896 mUploadFinishReceiver
= null
;
898 if (mDownloadFinishReceiver
!= null
) {
899 unregisterReceiver(mDownloadFinishReceiver
);
900 mDownloadFinishReceiver
= null
;
904 Log_OC
.v(TAG
, "onPause() end");
907 public boolean isFabOpen() {
908 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
916 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
919 * {@link BroadcastReceiver} to enable syncing feedback in UI
922 public void onReceive(Context context
, Intent intent
) {
924 String event
= intent
.getAction();
925 Log_OC
.d(TAG
, "Received broadcast " + event
);
926 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
927 String synchFolderRemotePath
=
928 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
929 RemoteOperationResult synchResult
=
930 (RemoteOperationResult
)intent
.getSerializableExtra(
931 FileSyncAdapter
.EXTRA_RESULT
);
932 boolean sameAccount
= (getAccount() != null
&&
933 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
937 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
938 mSyncInProgress
= true
;
941 OCFile currentFile
= (getFile() == null
) ? null
:
942 getStorageManager().getFileByPath(getFile().getRemotePath());
943 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
944 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
946 if (currentDir
== null
) {
947 // current folder was removed from the server
948 Toast
.makeText( FileDisplayActivity
.this,
951 sync_current_folder_was_removed
),
952 synchFolderRemotePath
),
959 if (currentFile
== null
&& !getFile().isFolder()) {
960 // currently selected file was removed in the server, and now we
962 cleanSecondFragment();
963 currentFile
= currentDir
;
966 if (synchFolderRemotePath
!= null
&&
967 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
968 OCFileListFragment fileListFragment
= getListOfFilesFragment();
969 if (fileListFragment
!= null
) {
970 fileListFragment
.listDirectory();
971 // TODO Enable when "On Device" is recovered ?
972 // fileListFragment.listDirectory(currentDir,
973 // MainApp.getOnlyOnDevice());
976 setFile(currentFile
);
979 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
980 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
983 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
984 equals(event
) &&/// TODO refactor and make common
986 synchResult
!= null
&& !synchResult
.isSuccess() &&
987 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
988 synchResult
.isIdPRedirection() ||
989 (synchResult
.isException() && synchResult
.getException()
990 instanceof AuthenticatorException
))) {
994 OwnCloudClient client
;
995 OwnCloudAccount ocAccount
=
996 new OwnCloudAccount(getAccount(), context
);
997 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
998 removeClientFor(ocAccount
));
999 if (client
!= null
) {
1000 OwnCloudCredentials cred
= client
.getCredentials();
1002 AccountManager am
= AccountManager
.get(context
);
1003 if (cred
.authTokenExpires()) {
1004 am
.invalidateAuthToken(
1009 am
.clearPassword(getAccount());
1013 requestCredentialsUpdate();
1015 } catch (AccountNotFoundException e
) {
1016 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1021 removeStickyBroadcast(intent
);
1022 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1023 mProgressBar
.setIndeterminate(mSyncInProgress
);
1024 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1025 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1026 /*|| mRefreshSharesInProgress*/ //);
1028 setBackgroundText();
1032 if (synchResult
!= null
) {
1033 if (synchResult
.getCode().equals(
1034 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1035 mLastSslUntrustedServerResult
= synchResult
;
1038 } catch (RuntimeException e
) {
1039 // avoid app crashes after changing the serial id of RemoteOperationResult
1040 // in owncloud library with broadcast notifications pending to process
1041 removeStickyBroadcast(intent
);
1047 * Show a text message on screen view for notifying user if content is
1048 * loading or folder is empty
1050 private void setBackgroundText() {
1051 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1052 if (ocFileListFragment
!= null
) {
1053 int message
= R
.string
.file_list_loading
;
1054 if (!mSyncInProgress
) {
1055 // In case file list is empty
1056 message
= R
.string
.file_list_empty
;
1058 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1060 Log_OC
.e(TAG
, "OCFileListFragment is null");
1065 * Once the file upload has finished -> update view
1067 private class UploadFinishReceiver
extends BroadcastReceiver
{
1069 * Once the file upload has finished -> update view
1071 * @author David A. Velasco
1072 * {@link BroadcastReceiver} to enable upload feedback in UI
1075 public void onReceive(Context context
, Intent intent
) {
1077 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1078 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1079 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1080 OCFile currentDir
= getCurrentDir();
1081 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1082 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1084 if (sameAccount
&& isDescendant
) {
1085 String linkedToRemotePath
=
1086 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1087 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1088 refreshListOfFilesFragment();
1092 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1094 boolean renamedInUpload
= getFile().getRemotePath().
1095 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1096 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1098 FileFragment details
= getSecondFragment();
1099 boolean detailFragmentIsShown
= (details
!= null
&&
1100 details
instanceof FileDetailFragment
);
1102 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1103 if (uploadWasFine
) {
1104 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1106 if (renamedInUpload
) {
1107 String newName
= (new File(uploadedRemotePath
)).getName();
1108 Toast msg
= Toast
.makeText(
1111 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1116 if (uploadWasFine
|| getFile().fileExists()) {
1117 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1119 cleanSecondFragment();
1122 // Force the preview if the file is an image or text file
1123 if (uploadWasFine
) {
1124 OCFile ocFile
= getFile();
1125 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1126 startImagePreview(getFile());
1127 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1128 startTextPreview(ocFile
);
1129 // TODO what about other kind of previews?
1133 mProgressBar
.setIndeterminate(false
);
1135 if (intent
!= null
) {
1136 removeStickyBroadcast(intent
);
1142 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1143 private boolean isAscendant(String linkedToRemotePath
) {
1144 OCFile currentDir
= getCurrentDir();
1146 currentDir
!= null
&&
1147 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1156 * Class waiting for broadcast events from the {@link FileDownloader} service.
1158 * Updates the UI when a download is started or finished, provided that it is relevant for the
1161 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1164 public void onReceive(Context context
, Intent intent
) {
1166 boolean sameAccount
= isSameAccount(intent
);
1167 String downloadedRemotePath
=
1168 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1169 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1171 if (sameAccount
&& isDescendant
) {
1172 String linkedToRemotePath
=
1173 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1174 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1175 refreshListOfFilesFragment();
1177 refreshSecondFragment(
1179 downloadedRemotePath
,
1180 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1184 if (mWaitingToSend
!= null
) {
1186 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1187 if (mWaitingToSend
.isDown()) {
1188 sendDownloadedFile();
1193 if (intent
!= null
) {
1194 removeStickyBroadcast(intent
);
1199 private boolean isDescendant(String downloadedRemotePath
) {
1200 OCFile currentDir
= getCurrentDir();
1202 currentDir
!= null
&&
1203 downloadedRemotePath
!= null
&&
1204 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1208 private boolean isAscendant(String linkedToRemotePath
) {
1209 OCFile currentDir
= getCurrentDir();
1211 currentDir
!= null
&&
1212 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1216 private boolean isSameAccount(Intent intent
) {
1217 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1218 return (accountName
!= null
&& getAccount() != null
&&
1219 accountName
.equals(getAccount().name
));
1224 public void browseToRoot() {
1225 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1226 if (listOfFiles
!= null
) { // should never be null, indeed
1227 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1228 listOfFiles
.listDirectory(root
);
1229 // TODO Enable when "On Device" is recovered ?
1230 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1231 setFile(listOfFiles
.getCurrentFile());
1232 startSyncFolderOperation(root
, false
);
1234 cleanSecondFragment();
1241 * Updates action bar and second fragment, if in dual pane mode.
1244 public void onBrowsedDownTo(OCFile directory
) {
1246 cleanSecondFragment();
1248 startSyncFolderOperation(directory
, false
);
1252 * Shows the information of the {@link OCFile} received as a
1253 * parameter in the second fragment.
1255 * @param file {@link OCFile} whose details will be shown
1258 public void showDetails(OCFile file
) {
1259 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1260 setSecondFragment(detailFragment
);
1261 updateFragmentsVisibility(true
);
1262 updateActionBarTitleAndHomeButton(file
);
1267 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1269 // in dual pane mode, keep the focus of title an action bar in the current folder
1270 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1273 super.updateActionBarTitleAndHomeButton(chosenFile
);
1279 protected ServiceConnection
newTransferenceServiceConnection() {
1280 return new ListServiceConnection();
1284 * Defines callbacks for service binding, passed to bindService()
1286 private class ListServiceConnection
implements ServiceConnection
{
1289 public void onServiceConnected(ComponentName component
, IBinder service
) {
1290 if (component
.equals(new ComponentName(
1291 FileDisplayActivity
.this, FileDownloader
.class))) {
1292 Log_OC
.d(TAG
, "Download service connected");
1293 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1294 if (mWaitingToPreview
!= null
)
1295 if (getStorageManager() != null
) {
1298 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1299 if (!mWaitingToPreview
.isDown()) {
1300 requestForDownload();
1304 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1305 FileUploader
.class))) {
1306 Log_OC
.d(TAG
, "Upload service connected");
1307 mUploaderBinder
= (FileUploaderBinder
) service
;
1311 // a new chance to get the mDownloadBinder through
1312 // getFileDownloadBinder() - THIS IS A MESS
1313 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1314 if (listOfFiles
!= null
) {
1315 listOfFiles
.listDirectory();
1316 // TODO Enable when "On Device" is recovered ?
1317 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1319 FileFragment secondFragment
= getSecondFragment();
1320 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1321 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1322 detailFragment
.listenForTransferProgress();
1323 detailFragment
.updateFileDetails(false
, false
);
1328 public void onServiceDisconnected(ComponentName component
) {
1329 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1330 FileDownloader
.class))) {
1331 Log_OC
.d(TAG
, "Download service disconnected");
1332 mDownloaderBinder
= null
;
1333 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1334 FileUploader
.class))) {
1335 Log_OC
.d(TAG
, "Upload service disconnected");
1336 mUploaderBinder
= null
;
1342 public void onSavedCertificate() {
1343 startSyncFolderOperation(getCurrentDir(), false
);
1348 public void onFailedSavingCertificate() {
1349 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1350 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1352 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1356 public void onCancelCertificate() {
1361 * Updates the view associated to the activity after the finish of some operation over files
1362 * in the current account.
1364 * @param operation Removal operation performed.
1365 * @param result Result of the removal.
1368 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1369 super.onRemoteOperationFinish(operation
, result
);
1371 if (operation
instanceof RemoveFileOperation
) {
1372 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1374 } else if (operation
instanceof RenameFileOperation
) {
1375 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1377 } else if (operation
instanceof SynchronizeFileOperation
) {
1378 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1380 } else if (operation
instanceof CreateFolderOperation
) {
1381 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1383 } else if (operation
instanceof CreateShareOperation
) {
1384 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1386 } else if (operation
instanceof UnshareLinkOperation
) {
1387 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1389 } else if (operation
instanceof MoveFileOperation
) {
1390 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1392 } else if (operation
instanceof CopyFileOperation
) {
1393 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1397 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1398 RemoteOperationResult result
) {
1399 if (result
.isSuccess()) {
1400 refreshShowDetails();
1401 refreshListOfFilesFragment();
1405 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1406 RemoteOperationResult result
) {
1407 if (result
.isSuccess()) {
1408 refreshShowDetails();
1409 refreshListOfFilesFragment();
1411 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1412 cleanSecondFragment();
1413 refreshListOfFilesFragment();
1417 private void refreshShowDetails() {
1418 FileFragment details
= getSecondFragment();
1419 if (details
!= null
) {
1420 OCFile file
= details
.getFile();
1422 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1423 if (details
instanceof PreviewMediaFragment
) {
1424 // Refresh OCFile of the fragment
1425 ((PreviewMediaFragment
) details
).updateFile(file
);
1426 } else if (details
instanceof PreviewTextFragment
) {
1427 // Refresh OCFile of the fragment
1428 ((PreviewTextFragment
) details
).updateFile(file
);
1433 invalidateOptionsMenu();
1438 * Updates the view associated to the activity after the finish of an operation trying to
1441 * @param operation Removal operation performed.
1442 * @param result Result of the removal.
1444 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1445 RemoteOperationResult result
) {
1446 dismissLoadingDialog();
1448 Toast msg
= Toast
.makeText(this,
1449 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1453 if (result
.isSuccess()) {
1454 OCFile removedFile
= operation
.getFile();
1455 FileFragment second
= getSecondFragment();
1456 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1457 if (second
instanceof PreviewMediaFragment
) {
1458 ((PreviewMediaFragment
) second
).stopPreview(true
);
1460 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1461 cleanSecondFragment();
1463 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1464 refreshListOfFilesFragment();
1466 invalidateOptionsMenu();
1468 if (result
.isSslRecoverableException()) {
1469 mLastSslUntrustedServerResult
= result
;
1470 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1477 * Updates the view associated to the activity after the finish of an operation trying to move a
1480 * @param operation Move operation performed.
1481 * @param result Result of the move operation.
1483 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1484 RemoteOperationResult result
) {
1485 if (result
.isSuccess()) {
1486 dismissLoadingDialog();
1487 refreshListOfFilesFragment();
1489 dismissLoadingDialog();
1491 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1492 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1496 } catch (NotFoundException e
) {
1497 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1503 * Updates the view associated to the activity after the finish of an operation trying to copy a
1506 * @param operation Copy operation performed.
1507 * @param result Result of the copy operation.
1509 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1510 if (result
.isSuccess()) {
1511 dismissLoadingDialog();
1512 refreshListOfFilesFragment();
1514 dismissLoadingDialog();
1516 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1517 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1521 } catch (NotFoundException e
) {
1522 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1528 * Updates the view associated to the activity after the finish of an operation trying to rename
1531 * @param operation Renaming operation performed.
1532 * @param result Result of the renaming.
1534 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1535 RemoteOperationResult result
) {
1536 dismissLoadingDialog();
1537 OCFile renamedFile
= operation
.getFile();
1538 if (result
.isSuccess()) {
1539 FileFragment details
= getSecondFragment();
1540 if (details
!= null
) {
1541 if (details
instanceof FileDetailFragment
&&
1542 renamedFile
.equals(details
.getFile()) ) {
1543 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1544 showDetails(renamedFile
);
1546 } else if (details
instanceof PreviewMediaFragment
&&
1547 renamedFile
.equals(details
.getFile())) {
1548 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1549 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1550 int position
= ((PreviewMediaFragment
) details
).getPosition();
1551 startMediaPreview(renamedFile
, position
, true
);
1553 getFileOperationsHelper().openFile(renamedFile
);
1555 } else if (details
instanceof PreviewTextFragment
&&
1556 renamedFile
.equals(details
.getFile())) {
1557 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1558 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1559 startTextPreview(renamedFile
);
1561 getFileOperationsHelper().openFile(renamedFile
);
1566 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1567 refreshListOfFilesFragment();
1571 Toast msg
= Toast
.makeText(this,
1572 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1576 if (result
.isSslRecoverableException()) {
1577 mLastSslUntrustedServerResult
= result
;
1578 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1583 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1584 RemoteOperationResult result
) {
1585 if (result
.isSuccess()) {
1586 if (operation
.transferWasRequested()) {
1587 OCFile syncedFile
= operation
.getLocalFile();
1588 onTransferStateChanged(syncedFile
, true
, true
);
1589 invalidateOptionsMenu();
1590 refreshShowDetails();
1596 * Updates the view associated to the activity after the finish of an operation trying create a
1599 * @param operation Creation operation performed.
1600 * @param result Result of the creation.
1602 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1603 RemoteOperationResult result
) {
1604 if (result
.isSuccess()) {
1605 dismissLoadingDialog();
1606 refreshListOfFilesFragment();
1608 dismissLoadingDialog();
1610 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1611 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1615 } catch (NotFoundException e
) {
1616 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1626 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1627 refreshListOfFilesFragment();
1628 FileFragment details
= getSecondFragment();
1629 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1630 file
.equals(details
.getFile()) ) {
1631 if (downloading
|| uploading
) {
1632 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1634 if (!file
.fileExists()) {
1635 cleanSecondFragment();
1637 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1645 private void requestForDownload() {
1646 Account account
= getAccount();
1647 //if (!mWaitingToPreview.isDownloading()) {
1648 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1649 Intent i
= new Intent(this, FileDownloader
.class);
1650 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1651 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1657 private OCFile
getCurrentDir() {
1658 OCFile file
= getFile();
1660 if (file
.isFolder()) {
1662 } else if (getStorageManager() != null
) {
1663 String parentPath
= file
.getRemotePath().substring(0,
1664 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1665 return getStorageManager().getFileByPath(parentPath
);
1671 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1672 long currentSyncTime
= System
.currentTimeMillis();
1674 mSyncInProgress
= true
;
1676 // perform folder synchronization
1677 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1680 getFileOperationsHelper().isSharedSupported(),
1682 getStorageManager(),
1684 getApplicationContext()
1686 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1688 mProgressBar
.setIndeterminate(true
);
1690 setBackgroundText();
1694 * Show untrusted cert dialog
1696 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1697 // Show a dialog with the certificate info
1698 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1699 (CertificateCombinedException
) result
.getException());
1700 FragmentManager fm
= getSupportFragmentManager();
1701 FragmentTransaction ft
= fm
.beginTransaction();
1702 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1705 private void requestForDownload(OCFile file
) {
1706 Account account
= getAccount();
1707 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1708 Intent i
= new Intent(this, FileDownloader
.class);
1709 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1710 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1715 private void sendDownloadedFile() {
1716 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1717 mWaitingToSend
= null
;
1722 * Requests the download of the received {@link OCFile} , updates the UI
1723 * to monitor the download progress and prepares the activity to send the file
1724 * when the download finishes.
1726 * @param file {@link OCFile} to download and preview.
1728 public void startDownloadForSending(OCFile file
) {
1729 mWaitingToSend
= file
;
1730 requestForDownload(mWaitingToSend
);
1731 boolean hasSecondFragment
= (getSecondFragment() != null
);
1732 updateFragmentsVisibility(hasSecondFragment
);
1736 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1738 * @param file Image {@link OCFile} to show.
1740 public void startImagePreview(OCFile file
) {
1741 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1742 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1743 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1744 startActivity(showDetailsIntent
);
1748 * Stars the preview of an already down media {@link OCFile}.
1750 * @param file Media {@link OCFile} to preview.
1751 * @param startPlaybackPosition Media position where the playback will be started,
1753 * @param autoplay When 'true', the playback will start without user
1756 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1757 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1759 setSecondFragment(mediaFragment
);
1760 updateFragmentsVisibility(true
);
1761 updateActionBarTitleAndHomeButton(file
);
1766 * Stars the preview of a text file {@link OCFile}.
1768 * @param file Text {@link OCFile} to preview.
1770 public void startTextPreview(OCFile file
) {
1771 Bundle args
= new Bundle();
1772 args
.putParcelable(EXTRA_FILE
, file
);
1773 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1774 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1775 PreviewTextFragment
.class.getName(), args
);
1776 setSecondFragment(textPreviewFragment
);
1777 updateFragmentsVisibility(true
);
1778 //updateNavigationElementsInActionBar(file);
1783 * Requests the download of the received {@link OCFile} , updates the UI
1784 * to monitor the download progress and prepares the activity to preview
1785 * or open the file when the download finishes.
1787 * @param file {@link OCFile} to download and preview.
1789 public void startDownloadForPreview(OCFile file
) {
1790 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1791 setSecondFragment(detailFragment
);
1792 mWaitingToPreview
= file
;
1793 requestForDownload();
1794 updateFragmentsVisibility(true
);
1795 updateActionBarTitleAndHomeButton(file
);
1800 public void cancelTransference(OCFile file
) {
1801 getFileOperationsHelper().cancelTransference(file
);
1802 if (mWaitingToPreview
!= null
&&
1803 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1804 mWaitingToPreview
= null
;
1806 if (mWaitingToSend
!= null
&&
1807 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1808 mWaitingToSend
= null
;
1810 onTransferStateChanged(file
, false
, false
);
1814 public void onRefresh(boolean ignoreETag
) {
1815 refreshList(ignoreETag
);
1819 public void onRefresh() {
1823 private void refreshList(boolean ignoreETag
) {
1824 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1825 if (listOfFiles
!= null
) {
1826 OCFile folder
= listOfFiles
.getCurrentFile();
1827 if (folder
!= null
) {
1828 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1829 listDirectory(mFile);*/
1830 startSyncFolderOperation(folder
, ignoreETag
);
1835 private void sortByDate(boolean ascending
) {
1836 getListOfFilesFragment().sortByDate(ascending
);
1839 private void sortBySize(boolean ascending
) {
1840 getListOfFilesFragment().sortBySize(ascending
);
1843 private void sortByName(boolean ascending
) {
1844 getListOfFilesFragment().sortByName(ascending
);
1847 public void allFilesOption() {