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
.PreviewVideoActivity
;
103 import com
.owncloud
.android
.utils
.DisplayUtils
;
104 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
105 import com
.owncloud
.android
.utils
.FileStorageUtils
;
106 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
{
119 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
121 private DownloadFinishReceiver mDownloadFinishReceiver
;
122 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
124 private boolean mDualPane
;
125 private View mLeftFragmentContainer
;
126 private View mRightFragmentContainer
;
127 private ProgressBar mProgressBar
;
129 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
131 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
133 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
135 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
136 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
137 public static final int ACTION_MOVE_FILES
= 3;
138 public static final int ACTION_COPY_FILES
= 4;
140 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
142 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
143 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
145 private OCFile mWaitingToPreview
;
147 private boolean mSyncInProgress
= false
;
149 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
150 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
151 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
152 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
154 private OCFile mWaitingToSend
;
158 protected void onCreate(Bundle savedInstanceState
) {
159 Log_OC
.v(TAG
, "onCreate() start");
161 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
164 /// grant that FileObserverService is watching favorite files
165 if (savedInstanceState
== null
) {
166 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
167 startService(initObserversIntent
);
170 /// Load of saved instance state
171 if(savedInstanceState
!= null
) {
172 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
173 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
174 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
175 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
176 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
192 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
193 mProgressBar
.setIndeterminateDrawable(
194 ContextCompat
.getDrawable(this,
195 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
197 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
198 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
199 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
200 if (savedInstanceState
== null
) {
201 createMinFragments();
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
206 // according to the official
209 // enable ActionBar app icon to behave as action to toggle nav drawer
210 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
211 getSupportActionBar().setHomeButtonEnabled(true
);
213 mProgressBar
.setIndeterminate(mSyncInProgress
);
214 // always AFTER setContentView(...) ; to work around bug in its implementation
218 Log_OC
.v(TAG
, "onCreate() end");
222 protected void onStart() {
223 Log_OC
.v(TAG
, "onStart() start");
225 Log_OC
.v(TAG
, "onStart() end");
229 protected void onDestroy() {
230 Log_OC
.v(TAG
, "onDestroy() start");
232 Log_OC
.v(TAG
, "onDestroy() end");
236 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
239 protected void onAccountSet(boolean stateWasRecovered
) {
240 super.onAccountSet(stateWasRecovered
);
241 if (getAccount() != null
) {
242 /// Check whether the 'main' OCFile handled by the Activity is contained in the
244 OCFile file
= getFile();
245 // get parent from path
246 String parentPath
= "";
248 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
249 // upload in progress - right now, files are not inserted in the local
250 // cache until the upload is successful get parent from path
251 parentPath
= file
.getRemotePath().substring(0,
252 file
.getRemotePath().lastIndexOf(file
.getFileName()));
253 if (getStorageManager().getFileByPath(parentPath
) == null
)
254 file
= null
; // not able to know the directory where the file is uploading
256 file
= getStorageManager().getFileByPath(file
.getRemotePath());
257 // currentDir = null if not in the current Account
261 // fall back to root folder
262 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
266 if (mAccountWasSet
) {
267 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
270 if (!stateWasRecovered
) {
271 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
272 initFragmentsWithFile();
273 if (file
.isFolder()) {
274 startSyncFolderOperation(file
, false
);
278 updateFragmentsVisibility(!file
.isFolder());
279 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
284 private void createMinFragments() {
285 OCFileListFragment listOfFiles
= new OCFileListFragment();
286 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
287 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
288 transaction
.commit();
291 private void initFragmentsWithFile() {
292 if (getAccount() != null
&& getFile() != null
) {
294 OCFileListFragment listOfFiles
= getListOfFilesFragment();
295 if (listOfFiles
!= null
) {
296 listOfFiles
.listDirectory(getCurrentDir());
297 // TODO Enable when "On Device" is recovered
298 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
300 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
304 OCFile file
= getFile();
305 Fragment secondFragment
= chooseInitialSecondFragment(file
);
306 if (secondFragment
!= null
) {
307 setSecondFragment(secondFragment
);
308 updateFragmentsVisibility(true
);
309 updateActionBarTitleAndHomeButton(file
);
312 cleanSecondFragment();
316 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
317 if (getAccount() == null
) {
318 Log_OC
.wtf(TAG
, "\t account is NULL");
320 if (getFile() == null
) {
321 Log_OC
.wtf(TAG
, "\t file is NULL");
326 private Fragment
chooseInitialSecondFragment(OCFile file
) {
327 Fragment secondFragment
= null
;
328 if (file
!= null
&& !file
.isFolder()) {
329 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
330 && file
.getLastSyncDateForProperties() > 0 // temporal fix
332 int startPlaybackPosition
=
333 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
335 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
336 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
337 startPlaybackPosition
, autoplay
);
340 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
343 return secondFragment
;
348 * Replaces the second fragment managed by the activity with the received as
351 * Assumes never will be more than two fragments managed at the same time.
353 * @param fragment New second Fragment to set.
355 private void setSecondFragment(Fragment fragment
) {
356 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
357 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
358 transaction
.commit();
362 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
364 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
365 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
367 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
368 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
371 } else if (existsSecondFragment
) {
372 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
373 mLeftFragmentContainer
.setVisibility(View
.GONE
);
375 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
383 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
384 mRightFragmentContainer
.setVisibility(View
.GONE
);
390 private OCFileListFragment
getListOfFilesFragment() {
391 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
392 FileDisplayActivity
.TAG_LIST_OF_FILES
);
393 if (listOfFiles
!= null
) {
394 return (OCFileListFragment
) listOfFiles
;
396 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
400 public FileFragment
getSecondFragment() {
401 Fragment second
= getSupportFragmentManager().findFragmentByTag(
402 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
403 if (second
!= null
) {
404 return (FileFragment
) second
;
409 protected void cleanSecondFragment() {
410 Fragment second
= getSecondFragment();
411 if (second
!= null
) {
412 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
416 updateFragmentsVisibility(false
);
417 updateActionBarTitleAndHomeButton(null
);
420 protected void refreshListOfFilesFragment() {
421 OCFileListFragment fileListFragment
= getListOfFilesFragment();
422 if (fileListFragment
!= null
) {
423 fileListFragment
.listDirectory();
424 // TODO Enable when "On Device" is recovered ?
425 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
429 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
431 FileFragment secondFragment
= getSecondFragment();
432 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
433 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
434 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
435 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
436 OCFile fileInFragment
= detailsFragment
.getFile();
437 if (fileInFragment
!= null
&&
438 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
439 // the user browsed to other file ; forget the automatic preview
440 mWaitingToPreview
= null
;
442 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
443 // grant that the right panel updates the progress bar
444 detailsFragment
.listenForTransferProgress();
445 detailsFragment
.updateFileDetails(true
, false
);
447 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
448 // update the right panel
449 boolean detailsFragmentChanged
= false
;
452 mWaitingToPreview
= getStorageManager().getFileById(
453 mWaitingToPreview
.getFileId()); // update the file from database,
454 // for the local storage path
455 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
456 startMediaPreview(mWaitingToPreview
, 0, true
);
457 detailsFragmentChanged
= true
;
459 getFileOperationsHelper().openFile(mWaitingToPreview
);
462 mWaitingToPreview
= null
;
464 if (!detailsFragmentChanged
) {
465 detailsFragment
.updateFileDetails(false
, (success
));
472 public boolean onPrepareOptionsMenu(Menu menu
) {
473 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
474 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
475 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
476 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
477 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
479 return super.onPrepareOptionsMenu(menu
);
483 public boolean onCreateOptionsMenu(Menu menu
) {
484 MenuInflater inflater
= getMenuInflater();
485 inflater
.inflate(R
.menu
.main_menu
, menu
);
491 public boolean onOptionsItemSelected(MenuItem item
) {
492 boolean retval
= true
;
493 switch (item
.getItemId()) {
494 case R
.id
.action_create_dir
: {
498 case R
.id
.action_sync_account
: {
499 startSynchronization();
502 case R
.id
.action_upload
: {
503 UploadSourceDialogFragment dialog
=
504 UploadSourceDialogFragment
.newInstance(getAccount());
505 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
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_OPERATION_ON_ACTIVITY_RESULTS
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_OPERATION_ON_ACTIVITY_RESULTS
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 if (!isDrawerOpen()){
798 OCFileListFragment listOfFiles
= getListOfFilesFragment();
799 if (mDualPane
|| getSecondFragment() == null
) {
800 OCFile currentDir
= getCurrentDir();
801 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
805 if (listOfFiles
!= null
) { // should never be null, indeed
806 listOfFiles
.onBrowseUp();
809 if (listOfFiles
!= null
) { // should never be null, indeed
810 setFile(listOfFiles
.getCurrentFile());
812 cleanSecondFragment();
814 super.onBackPressed();
819 protected void onSaveInstanceState(Bundle outState
) {
820 // responsibility of restore is preferred in onCreate() before than in
821 // onRestoreInstanceState when there are Fragments involved
822 Log_OC
.v(TAG
, "onSaveInstanceState() start");
823 super.onSaveInstanceState(outState
);
824 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
825 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
826 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
827 // mRefreshSharesInProgress);
828 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
830 Log_OC
.v(TAG
, "onSaveInstanceState() end");
835 protected void onResume() {
836 Log_OC
.v(TAG
, "onResume() start");
839 // refresh Navigation Drawer account list
840 mNavigationDrawerAdapter
.updateAccountList();
843 // refresh list of files
844 refreshListOfFilesFragment();
846 // Listen for sync messages
847 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
848 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
849 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
850 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
851 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
852 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
853 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
854 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
855 // syncIntentFilter);
857 // Listen for upload messages
858 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
859 mUploadFinishReceiver
= new UploadFinishReceiver();
860 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
862 // Listen for download messages
863 IntentFilter downloadIntentFilter
= new IntentFilter(
864 FileDownloader
.getDownloadAddedMessage());
865 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
866 mDownloadFinishReceiver
= new DownloadFinishReceiver();
867 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
869 Log_OC
.v(TAG
, "onResume() end");
874 protected void onPause() {
875 Log_OC
.v(TAG
, "onPause() start");
876 if (mSyncBroadcastReceiver
!= null
) {
877 unregisterReceiver(mSyncBroadcastReceiver
);
878 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
879 mSyncBroadcastReceiver
= null
;
881 if (mUploadFinishReceiver
!= null
) {
882 unregisterReceiver(mUploadFinishReceiver
);
883 mUploadFinishReceiver
= null
;
885 if (mDownloadFinishReceiver
!= null
) {
886 unregisterReceiver(mDownloadFinishReceiver
);
887 mDownloadFinishReceiver
= null
;
891 Log_OC
.v(TAG
, "onPause() end");
895 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
898 * {@link BroadcastReceiver} to enable syncing feedback in UI
901 public void onReceive(Context context
, Intent intent
) {
903 String event
= intent
.getAction();
904 Log_OC
.d(TAG
, "Received broadcast " + event
);
905 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
906 String synchFolderRemotePath
=
907 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
908 RemoteOperationResult synchResult
=
909 (RemoteOperationResult
)intent
.getSerializableExtra(
910 FileSyncAdapter
.EXTRA_RESULT
);
911 boolean sameAccount
= (getAccount() != null
&&
912 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
916 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
917 mSyncInProgress
= true
;
920 OCFile currentFile
= (getFile() == null
) ? null
:
921 getStorageManager().getFileByPath(getFile().getRemotePath());
922 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
923 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
925 if (currentDir
== null
) {
926 // current folder was removed from the server
927 Toast
.makeText( FileDisplayActivity
.this,
930 sync_current_folder_was_removed
),
931 synchFolderRemotePath
),
937 if (currentFile
== null
&& !getFile().isFolder()) {
938 // currently selected file was removed in the server, and now we
940 cleanSecondFragment();
941 currentFile
= currentDir
;
944 if (synchFolderRemotePath
!= null
&&
945 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
946 OCFileListFragment fileListFragment
= getListOfFilesFragment();
947 if (fileListFragment
!= null
) {
948 fileListFragment
.listDirectory();
949 // TODO Enable when "On Device" is recovered ?
950 // fileListFragment.listDirectory(currentDir,
951 // MainApp.getOnlyOnDevice());
954 setFile(currentFile
);
957 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
958 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
961 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
963 /// TODO refactor and make common
964 synchResult
!= null
&& !synchResult
.isSuccess() &&
965 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
966 synchResult
.isIdPRedirection() ||
967 (synchResult
.isException() && synchResult
.getException()
968 instanceof AuthenticatorException
))) {
972 OwnCloudClient client
;
973 OwnCloudAccount ocAccount
=
974 new OwnCloudAccount(getAccount(), context
);
975 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
976 removeClientFor(ocAccount
));
978 if (client
!= null
) {
979 OwnCloudCredentials cred
= client
.getCredentials();
981 AccountManager am
= AccountManager
.get(context
);
982 if (cred
.authTokenExpires()) {
983 am
.invalidateAuthToken(
988 am
.clearPassword(getAccount());
992 requestCredentialsUpdate();
994 } catch (AccountNotFoundException e
) {
995 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1000 removeStickyBroadcast(intent
);
1001 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1002 mProgressBar
.setIndeterminate(mSyncInProgress
);
1003 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1004 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1005 /*|| mRefreshSharesInProgress*/ //);
1007 setBackgroundText();
1011 if (synchResult
!= null
) {
1012 if (synchResult
.getCode().equals(
1013 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1014 mLastSslUntrustedServerResult
= synchResult
;
1017 } catch (RuntimeException e
) {
1018 // avoid app crashes after changing the serial id of RemoteOperationResult
1019 // in owncloud library with broadcast notifications pending to process
1020 removeStickyBroadcast(intent
);
1026 * Show a text message on screen view for notifying user if content is
1027 * loading or folder is empty
1029 private void setBackgroundText() {
1030 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1031 if (ocFileListFragment
!= null
) {
1032 int message
= R
.string
.file_list_loading
;
1033 if (!mSyncInProgress
) {
1034 // In case file list is empty
1035 message
= R
.string
.file_list_empty
;
1037 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1039 Log_OC
.e(TAG
, "OCFileListFragment is null");
1044 * Once the file upload has finished -> update view
1046 private class UploadFinishReceiver
extends BroadcastReceiver
{
1048 * Once the file upload has finished -> update view
1050 * @author David A. Velasco
1051 * {@link BroadcastReceiver} to enable upload feedback in UI
1054 public void onReceive(Context context
, Intent intent
) {
1056 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1057 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1058 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1059 OCFile currentDir
= getCurrentDir();
1060 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1061 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1063 if (sameAccount
&& isDescendant
) {
1064 refreshListOfFilesFragment();
1067 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1069 boolean renamedInUpload
= getFile().getRemotePath().
1070 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1071 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1073 FileFragment details
= getSecondFragment();
1074 boolean detailFragmentIsShown
= (details
!= null
&&
1075 details
instanceof FileDetailFragment
);
1077 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1078 if (uploadWasFine
) {
1079 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1081 if (renamedInUpload
) {
1082 String newName
= (new File(uploadedRemotePath
)).getName();
1083 Toast msg
= Toast
.makeText(
1086 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1091 if (uploadWasFine
|| getFile().fileExists()) {
1092 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1094 cleanSecondFragment();
1097 // Force the preview if the file is an image
1098 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1099 startImagePreview(getFile());
1100 } // TODO what about other kind of previews?
1103 mProgressBar
.setIndeterminate(false
);
1105 if (intent
!= null
) {
1106 removeStickyBroadcast(intent
);
1116 * Class waiting for broadcast events from the {@link FileDownloader} service.
1118 * Updates the UI when a download is started or finished, provided that it is relevant for the
1121 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1123 //int refreshCounter = 0;
1125 public void onReceive(Context context
, Intent intent
) {
1127 boolean sameAccount
= isSameAccount(context
, intent
);
1128 String downloadedRemotePath
=
1129 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1130 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1132 if (sameAccount
&& isDescendant
) {
1133 String linkedToRemotePath
=
1134 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1135 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1136 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1137 refreshListOfFilesFragment();
1139 refreshSecondFragment(
1141 downloadedRemotePath
,
1142 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1146 if (mWaitingToSend
!= null
) {
1148 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1149 if (mWaitingToSend
.isDown()) {
1150 sendDownloadedFile();
1155 if (intent
!= null
) {
1156 removeStickyBroadcast(intent
);
1161 private boolean isDescendant(String downloadedRemotePath
) {
1162 OCFile currentDir
= getCurrentDir();
1164 currentDir
!= null
&&
1165 downloadedRemotePath
!= null
&&
1166 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1170 private boolean isAscendant(String linkedToRemotePath
) {
1171 OCFile currentDir
= getCurrentDir();
1173 currentDir
!= null
&&
1174 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1178 private boolean isSameAccount(Context context
, Intent intent
) {
1179 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1180 return (accountName
!= null
&& getAccount() != null
&&
1181 accountName
.equals(getAccount().name
));
1186 public void browseToRoot() {
1187 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1188 if (listOfFiles
!= null
) { // should never be null, indeed
1189 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1190 listOfFiles
.listDirectory(root
);
1191 // TODO Enable when "On Device" is recovered ?
1192 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1193 setFile(listOfFiles
.getCurrentFile());
1194 startSyncFolderOperation(root
, false
);
1196 cleanSecondFragment();
1204 * Updates action bar and second fragment, if in dual pane mode.
1207 public void onBrowsedDownTo(OCFile directory
) {
1209 cleanSecondFragment();
1211 startSyncFolderOperation(directory
, false
);
1215 * Shows the information of the {@link OCFile} received as a
1216 * parameter in the second fragment.
1218 * @param file {@link OCFile} whose details will be shown
1221 public void showDetails(OCFile file
) {
1222 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1223 setSecondFragment(detailFragment
);
1224 updateFragmentsVisibility(true
);
1225 updateActionBarTitleAndHomeButton(file
);
1230 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1232 // in dual pane mode, keep the focus of title an action bar in the current folder
1233 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1236 super.updateActionBarTitleAndHomeButton(chosenFile
);
1242 protected ServiceConnection
newTransferenceServiceConnection() {
1243 return new ListServiceConnection();
1247 * Defines callbacks for service binding, passed to bindService()
1249 private class ListServiceConnection
implements ServiceConnection
{
1252 public void onServiceConnected(ComponentName component
, IBinder service
) {
1253 if (component
.equals(new ComponentName(
1254 FileDisplayActivity
.this, FileDownloader
.class))) {
1255 Log_OC
.d(TAG
, "Download service connected");
1256 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1257 if (mWaitingToPreview
!= null
)
1258 if (getStorageManager() != null
) {
1261 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1262 if (!mWaitingToPreview
.isDown()) {
1263 requestForDownload();
1267 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1268 FileUploader
.class))) {
1269 Log_OC
.d(TAG
, "Upload service connected");
1270 mUploaderBinder
= (FileUploaderBinder
) service
;
1274 // a new chance to get the mDownloadBinder through
1275 // getFileDownloadBinder() - THIS IS A MESS
1276 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1277 if (listOfFiles
!= null
) {
1278 listOfFiles
.listDirectory();
1279 // TODO Enable when "On Device" is recovered ?
1280 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1282 FileFragment secondFragment
= getSecondFragment();
1283 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1284 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1285 detailFragment
.listenForTransferProgress();
1286 detailFragment
.updateFileDetails(false
, false
);
1291 public void onServiceDisconnected(ComponentName component
) {
1292 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1293 FileDownloader
.class))) {
1294 Log_OC
.d(TAG
, "Download service disconnected");
1295 mDownloaderBinder
= null
;
1296 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1297 FileUploader
.class))) {
1298 Log_OC
.d(TAG
, "Upload service disconnected");
1299 mUploaderBinder
= null
;
1305 public void onSavedCertificate() {
1306 startSyncFolderOperation(getCurrentDir(), false
);
1311 public void onFailedSavingCertificate() {
1312 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1313 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1315 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1319 public void onCancelCertificate() {
1324 * Updates the view associated to the activity after the finish of some operation over files
1325 * in the current account.
1327 * @param operation Removal operation performed.
1328 * @param result Result of the removal.
1331 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1332 super.onRemoteOperationFinish(operation
, result
);
1334 if (operation
instanceof RemoveFileOperation
) {
1335 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1337 } else if (operation
instanceof RenameFileOperation
) {
1338 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1340 } else if (operation
instanceof SynchronizeFileOperation
) {
1341 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1343 } else if (operation
instanceof CreateFolderOperation
) {
1344 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1346 } else if (operation
instanceof CreateShareOperation
) {
1347 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1349 } else if (operation
instanceof UnshareLinkOperation
) {
1350 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1352 } else if (operation
instanceof MoveFileOperation
) {
1353 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1355 } else if (operation
instanceof CopyFileOperation
) {
1356 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1362 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1363 RemoteOperationResult result
) {
1364 if (result
.isSuccess()) {
1365 refreshShowDetails();
1366 refreshListOfFilesFragment();
1371 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1372 RemoteOperationResult result
) {
1373 if (result
.isSuccess()) {
1374 refreshShowDetails();
1375 refreshListOfFilesFragment();
1377 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1378 cleanSecondFragment();
1379 refreshListOfFilesFragment();
1383 private void refreshShowDetails() {
1384 FileFragment details
= getSecondFragment();
1385 if (details
!= null
) {
1386 OCFile file
= details
.getFile();
1388 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1389 if (details
instanceof PreviewMediaFragment
) {
1390 // Refresh OCFile of the fragment
1391 ((PreviewMediaFragment
) details
).updateFile(file
);
1396 invalidateOptionsMenu();
1401 * Updates the view associated to the activity after the finish of an operation trying to
1404 * @param operation Removal operation performed.
1405 * @param result Result of the removal.
1407 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1408 RemoteOperationResult result
) {
1409 dismissLoadingDialog();
1411 Toast msg
= Toast
.makeText(this,
1412 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1416 if (result
.isSuccess()) {
1417 OCFile removedFile
= operation
.getFile();
1418 FileFragment second
= getSecondFragment();
1419 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1420 if (second
instanceof PreviewMediaFragment
) {
1421 ((PreviewMediaFragment
) second
).stopPreview(true
);
1423 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1424 cleanSecondFragment();
1426 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1427 refreshListOfFilesFragment();
1429 invalidateOptionsMenu();
1431 if (result
.isSslRecoverableException()) {
1432 mLastSslUntrustedServerResult
= result
;
1433 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1440 * Updates the view associated to the activity after the finish of an operation trying to move a
1443 * @param operation Move operation performed.
1444 * @param result Result of the move operation.
1446 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1447 RemoteOperationResult result
) {
1448 if (result
.isSuccess()) {
1449 dismissLoadingDialog();
1450 refreshListOfFilesFragment();
1452 dismissLoadingDialog();
1454 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1455 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1459 } catch (NotFoundException e
) {
1460 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1466 * Updates the view associated to the activity after the finish of an operation trying to copy a
1469 * @param operation Copy operation performed.
1470 * @param result Result of the copy operation.
1472 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1473 if (result
.isSuccess()) {
1474 dismissLoadingDialog();
1475 refreshListOfFilesFragment();
1477 dismissLoadingDialog();
1479 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1480 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1484 } catch (NotFoundException e
) {
1485 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1491 * Updates the view associated to the activity after the finish of an operation trying to rename
1494 * @param operation Renaming operation performed.
1495 * @param result Result of the renaming.
1497 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1498 RemoteOperationResult result
) {
1499 dismissLoadingDialog();
1500 OCFile renamedFile
= operation
.getFile();
1501 if (result
.isSuccess()) {
1502 FileFragment details
= getSecondFragment();
1503 if (details
!= null
) {
1504 if (details
instanceof FileDetailFragment
&&
1505 renamedFile
.equals(details
.getFile()) ) {
1506 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1507 showDetails(renamedFile
);
1509 } else if (details
instanceof PreviewMediaFragment
&&
1510 renamedFile
.equals(details
.getFile())) {
1511 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1512 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1513 int position
= ((PreviewMediaFragment
) details
).getPosition();
1514 startMediaPreview(renamedFile
, position
, true
);
1516 getFileOperationsHelper().openFile(renamedFile
);
1521 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1522 refreshListOfFilesFragment();
1526 Toast msg
= Toast
.makeText(this,
1527 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1531 if (result
.isSslRecoverableException()) {
1532 mLastSslUntrustedServerResult
= result
;
1533 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1538 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1539 RemoteOperationResult result
) {
1540 if (result
.isSuccess()) {
1541 if (operation
.transferWasRequested()) {
1542 OCFile syncedFile
= operation
.getLocalFile();
1543 onTransferStateChanged(syncedFile
, true
, true
);
1544 invalidateOptionsMenu();
1550 * Updates the view associated to the activity after the finish of an operation trying create a
1553 * @param operation Creation operation performed.
1554 * @param result Result of the creation.
1556 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1557 RemoteOperationResult result
) {
1558 if (result
.isSuccess()) {
1559 dismissLoadingDialog();
1560 refreshListOfFilesFragment();
1562 dismissLoadingDialog();
1564 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1565 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1569 } catch (NotFoundException e
) {
1570 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1580 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1581 refreshListOfFilesFragment();
1582 FileFragment details
= getSecondFragment();
1583 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1584 file
.equals(details
.getFile()) ) {
1585 if (downloading
|| uploading
) {
1586 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1588 if (!file
.fileExists()) {
1589 cleanSecondFragment();
1591 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1599 private void requestForDownload() {
1600 Account account
= getAccount();
1601 //if (!mWaitingToPreview.isDownloading()) {
1602 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1603 Intent i
= new Intent(this, FileDownloader
.class);
1604 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1605 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1611 private OCFile
getCurrentDir() {
1612 OCFile file
= getFile();
1614 if (file
.isFolder()) {
1616 } else if (getStorageManager() != null
) {
1617 String parentPath
= file
.getRemotePath().substring(0,
1618 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1619 return getStorageManager().getFileByPath(parentPath
);
1625 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1626 long currentSyncTime
= System
.currentTimeMillis();
1628 mSyncInProgress
= true
;
1630 // perform folder synchronization
1631 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1634 getFileOperationsHelper().isSharedSupported(),
1636 getStorageManager(),
1638 getApplicationContext()
1640 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1641 mProgressBar
.setIndeterminate(true
);
1643 setBackgroundText();
1647 * Show untrusted cert dialog
1649 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1650 // Show a dialog with the certificate info
1651 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1652 (CertificateCombinedException
) result
.getException());
1653 FragmentManager fm
= getSupportFragmentManager();
1654 FragmentTransaction ft
= fm
.beginTransaction();
1655 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1658 private void requestForDownload(OCFile file
) {
1659 Account account
= getAccount();
1660 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1661 Intent i
= new Intent(this, FileDownloader
.class);
1662 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1663 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1668 private void sendDownloadedFile() {
1669 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1670 mWaitingToSend
= null
;
1675 * Requests the download of the received {@link OCFile} , updates the UI
1676 * to monitor the download progress and prepares the activity to send the file
1677 * when the download finishes.
1679 * @param file {@link OCFile} to download and preview.
1681 public void startDownloadForSending(OCFile file
) {
1682 mWaitingToSend
= file
;
1683 requestForDownload(mWaitingToSend
);
1684 boolean hasSecondFragment
= (getSecondFragment() != null
);
1685 updateFragmentsVisibility(hasSecondFragment
);
1689 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1691 * @param file Image {@link OCFile} to show.
1693 public void startImagePreview(OCFile file
) {
1694 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1695 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1696 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1697 startActivity(showDetailsIntent
);
1702 * Stars the preview of an already down media {@link OCFile}.
1704 * @param file Media {@link OCFile} to preview.
1705 * @param startPlaybackPosition Media position where the playback will be started,
1707 * @param autoplay When 'true', the playback will start without user
1710 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1711 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1713 setSecondFragment(mediaFragment
);
1714 updateFragmentsVisibility(true
);
1715 updateActionBarTitleAndHomeButton(file
);
1720 * Requests the download of the received {@link OCFile} , updates the UI
1721 * to monitor the download progress and prepares the activity to preview
1722 * or open the file when the download finishes.
1724 * @param file {@link OCFile} to download and preview.
1726 public void startDownloadForPreview(OCFile file
) {
1727 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1728 setSecondFragment(detailFragment
);
1729 mWaitingToPreview
= file
;
1730 requestForDownload();
1731 updateFragmentsVisibility(true
);
1732 updateActionBarTitleAndHomeButton(file
);
1737 public void cancelTransference(OCFile file
) {
1738 getFileOperationsHelper().cancelTransference(file
);
1739 if (mWaitingToPreview
!= null
&&
1740 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1741 mWaitingToPreview
= null
;
1743 if (mWaitingToSend
!= null
&&
1744 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1745 mWaitingToSend
= null
;
1747 onTransferStateChanged(file
, false
, false
);
1751 public void onRefresh(boolean ignoreETag
) {
1752 refreshList(ignoreETag
);
1756 public void onRefresh() {
1760 private void refreshList(boolean ignoreETag
) {
1761 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1762 if (listOfFiles
!= null
) {
1763 OCFile folder
= listOfFiles
.getCurrentFile();
1764 if (folder
!= null
) {
1765 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1766 listDirectory(mFile);*/
1767 startSyncFolderOperation(folder
, ignoreETag
);
1772 private void sortByDate(boolean ascending
) {
1773 getListOfFilesFragment().sortByDate(ascending
);
1776 private void sortBySize(boolean ascending
) {
1777 getListOfFilesFragment().sortBySize(ascending
);
1780 private void sortByName(boolean ascending
) {
1781 getListOfFilesFragment().sortByName(ascending
);
1784 public void allFilesOption() {