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
.UnshareOperation
;
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
{
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
);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= false
;
180 mWaitingToSend
= null
;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
191 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
192 mProgressBar
.setIndeterminateDrawable(
193 ContextCompat
.getDrawable(this,
194 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
196 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
197 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
198 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
199 if (savedInstanceState
== null
) {
200 createMinFragments();
204 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
205 // according to the official
208 // enable ActionBar app icon to behave as action to toggle nav drawer
209 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
210 getSupportActionBar().setHomeButtonEnabled(true
);
212 mProgressBar
.setIndeterminate(mSyncInProgress
);
213 // always AFTER setContentView(...) ; to work around bug in its implementation
217 Log_OC
.v(TAG
, "onCreate() end");
221 protected void onStart() {
222 Log_OC
.v(TAG
, "onStart() start");
224 Log_OC
.v(TAG
, "onStart() end");
228 protected void onDestroy() {
229 Log_OC
.v(TAG
, "onDestroy() start");
231 Log_OC
.v(TAG
, "onDestroy() end");
235 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
238 protected void onAccountSet(boolean stateWasRecovered
) {
239 super.onAccountSet(stateWasRecovered
);
240 if (getAccount() != null
) {
241 /// Check whether the 'main' OCFile handled by the Activity is contained in the
243 OCFile file
= getFile();
244 // get parent from path
245 String parentPath
= "";
247 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
248 // upload in progress - right now, files are not inserted in the local
249 // cache until the upload is successful get parent from path
250 parentPath
= file
.getRemotePath().substring(0,
251 file
.getRemotePath().lastIndexOf(file
.getFileName()));
252 if (getStorageManager().getFileByPath(parentPath
) == null
)
253 file
= null
; // not able to know the directory where the file is uploading
255 file
= getStorageManager().getFileByPath(file
.getRemotePath());
256 // currentDir = null if not in the current Account
260 // fall back to root folder
261 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
265 if (mAccountWasSet
) {
266 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
267 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
268 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
269 int lastAtPos
= getAccount().name
.lastIndexOf("@");
270 username
.setText(getAccount().name
.substring(0, lastAtPos
));
274 if (!stateWasRecovered
) {
275 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
276 initFragmentsWithFile();
277 if (file
.isFolder()) {
278 startSyncFolderOperation(file
, false
);
282 updateFragmentsVisibility(!file
.isFolder());
283 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
288 private void createMinFragments() {
289 OCFileListFragment listOfFiles
= new OCFileListFragment();
290 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
291 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
292 transaction
.commit();
295 private void initFragmentsWithFile() {
296 if (getAccount() != null
&& getFile() != null
) {
298 OCFileListFragment listOfFiles
= getListOfFilesFragment();
299 if (listOfFiles
!= null
) {
300 listOfFiles
.listDirectory(getCurrentDir());
301 // TODO Enable when "On Device" is recovered
302 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
305 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
309 OCFile file
= getFile();
310 Fragment secondFragment
= chooseInitialSecondFragment(file
);
311 if (secondFragment
!= null
) {
312 setSecondFragment(secondFragment
);
313 updateFragmentsVisibility(true
);
314 updateActionBarTitleAndHomeButton(file
);
317 cleanSecondFragment();
318 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
319 startTextPreview(file
);
323 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
324 if (getAccount() == null
) {
325 Log_OC
.wtf(TAG
, "\t account is NULL");
327 if (getFile() == null
) {
328 Log_OC
.wtf(TAG
, "\t file is NULL");
333 private Fragment
chooseInitialSecondFragment(OCFile file
) {
334 Fragment secondFragment
= null
;
335 if (file
!= null
&& !file
.isFolder()) {
336 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
337 && file
.getLastSyncDateForProperties() > 0 // temporal fix
339 int startPlaybackPosition
=
340 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
342 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
343 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
344 startPlaybackPosition
, autoplay
);
346 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
347 secondFragment
= null
;
349 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
352 return secondFragment
;
357 * Replaces the second fragment managed by the activity with the received as
360 * Assumes never will be more than two fragments managed at the same time.
362 * @param fragment New second Fragment to set.
364 private void setSecondFragment(Fragment fragment
) {
365 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
366 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
367 transaction
.commit();
371 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
373 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
374 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
376 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
377 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
380 } else if (existsSecondFragment
) {
381 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
382 mLeftFragmentContainer
.setVisibility(View
.GONE
);
384 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
385 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
389 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
390 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
392 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
393 mRightFragmentContainer
.setVisibility(View
.GONE
);
399 private OCFileListFragment
getListOfFilesFragment() {
400 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
401 FileDisplayActivity
.TAG_LIST_OF_FILES
);
402 if (listOfFiles
!= null
) {
403 return (OCFileListFragment
) listOfFiles
;
405 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
409 public FileFragment
getSecondFragment() {
410 Fragment second
= getSupportFragmentManager().findFragmentByTag(
411 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
412 if (second
!= null
) {
413 return (FileFragment
) second
;
418 protected void cleanSecondFragment() {
419 Fragment second
= getSecondFragment();
420 if (second
!= null
) {
421 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
425 updateFragmentsVisibility(false
);
426 updateActionBarTitleAndHomeButton(null
);
429 protected void refreshListOfFilesFragment() {
430 OCFileListFragment fileListFragment
= getListOfFilesFragment();
431 if (fileListFragment
!= null
) {
432 fileListFragment
.listDirectory();
433 // TODO Enable when "On Device" is recovered ?
434 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
438 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
440 FileFragment secondFragment
= getSecondFragment();
441 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
442 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
443 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
444 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
445 OCFile fileInFragment
= detailsFragment
.getFile();
446 if (fileInFragment
!= null
&&
447 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
448 // the user browsed to other file ; forget the automatic preview
449 mWaitingToPreview
= null
;
451 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
452 // grant that the right panel updates the progress bar
453 detailsFragment
.listenForTransferProgress();
454 detailsFragment
.updateFileDetails(true
, false
);
456 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
457 // update the right panel
458 boolean detailsFragmentChanged
= false
;
461 mWaitingToPreview
= getStorageManager().getFileById(
462 mWaitingToPreview
.getFileId()); // update the file from database,
463 // for the local storage path
464 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
465 startMediaPreview(mWaitingToPreview
, 0, true
);
466 detailsFragmentChanged
= true
;
467 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
468 startTextPreview(mWaitingToPreview
);
469 detailsFragmentChanged
= true
;
471 getFileOperationsHelper().openFile(mWaitingToPreview
);
474 mWaitingToPreview
= null
;
476 if (!detailsFragmentChanged
) {
477 detailsFragment
.updateFileDetails(false
, (success
));
484 public boolean onPrepareOptionsMenu(Menu menu
) {
485 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
486 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
487 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
488 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
491 return super.onPrepareOptionsMenu(menu
);
495 public boolean onCreateOptionsMenu(Menu menu
) {
496 MenuInflater inflater
= getMenuInflater();
497 inflater
.inflate(R
.menu
.main_menu
, menu
);
503 public boolean onOptionsItemSelected(MenuItem item
) {
504 boolean retval
= true
;
505 switch (item
.getItemId()) {
506 case R
.id
.action_create_dir
: {
507 CreateFolderDialogFragment dialog
=
508 CreateFolderDialogFragment
.newInstance(getCurrentDir());
509 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
513 case R
.id
.action_sync_account
: {
514 startSynchronization();
517 case R
.id
.action_upload
: {
518 UploadSourceDialogFragment dialog
=
519 UploadSourceDialogFragment
.newInstance(getAccount());
520 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
523 case android
.R
.id
.home
: {
524 FileFragment second
= getSecondFragment();
525 OCFile currentDir
= getCurrentDir();
526 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
527 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
528 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
529 (second
!= null
&& second
.getFile() != null
)) {
533 mDrawerLayout
.openDrawer(GravityCompat
.START
);
537 case R
.id
.action_sort
: {
538 SharedPreferences appPreferences
= PreferenceManager
539 .getDefaultSharedPreferences(this);
541 // Read sorting order, default to sort by name ascending
542 Integer sortOrder
= appPreferences
543 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
545 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
546 builder
.setTitle(R
.string
.actionbar_sort_title
)
547 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
548 new DialogInterface
.OnClickListener() {
549 public void onClick(DialogInterface dialog
, int which
) {
562 builder
.create().show();
566 retval
= super.onOptionsItemSelected(item
);
571 private void startSynchronization() {
572 Log_OC
.d(TAG
, "Got to start sync");
573 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
574 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
575 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
576 // cancel the current synchronizations of any ownCloud account
577 Bundle bundle
= new Bundle();
578 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
579 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
580 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
581 MainApp
.getAuthority());
582 ContentResolver
.requestSync(
584 MainApp
.getAuthority(), bundle
);
586 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
587 MainApp
.getAuthority() + " with new API");
588 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
589 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
590 builder
.setExpedited(true
);
591 builder
.setManual(true
);
594 // Fix bug in Android Lollipop when you click on refresh the whole account
595 Bundle extras
= new Bundle();
596 builder
.setExtras(extras
);
598 SyncRequest request
= builder
.build();
599 ContentResolver
.requestSync(request
);
604 * Called, when the user selected something for uploading
607 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
609 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
611 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
612 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
613 //getClipData is only supported on api level 16+, Jelly Bean
614 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
615 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
616 Intent intent
= new Intent();
617 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
618 requestSimpleUpload(intent
, resultCode
);
621 requestSimpleUpload(data
, resultCode
);
623 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
624 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
625 requestMultipleUpload(data
, resultCode
);
627 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
628 final Intent fData
= data
;
629 final int fResultCode
= resultCode
;
630 getHandler().postDelayed(
634 requestMoveOperation(fData
, fResultCode
);
637 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
640 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
642 final Intent fData
= data
;
643 final int fResultCode
= resultCode
;
644 getHandler().postDelayed(
648 requestCopyOperation(fData
, fResultCode
);
651 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
655 super.onActivityResult(requestCode
, resultCode
, data
);
660 private void requestMultipleUpload(Intent data
, int resultCode
) {
661 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
662 if (filePaths
!= null
) {
663 String
[] remotePaths
= new String
[filePaths
.length
];
664 String remotePathBase
= getCurrentDir().getRemotePath();
665 for (int j
= 0; j
< remotePaths
.length
; j
++) {
666 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
669 Intent i
= new Intent(this, FileUploader
.class);
670 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
671 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
672 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
673 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
674 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
675 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
679 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
680 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
688 private void requestSimpleUpload(Intent data
, int resultCode
) {
689 String filePath
= null
;
690 String mimeType
= null
;
692 Uri selectedImageUri
= data
.getData();
695 mimeType
= getContentResolver().getType(selectedImageUri
);
697 String fileManagerString
= selectedImageUri
.getPath();
698 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
700 if (selectedImagePath
!= null
)
701 filePath
= selectedImagePath
;
703 filePath
= fileManagerString
;
705 } catch (Exception e
) {
706 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
707 "Intent.ACTION_GET_CONTENT", e
);
710 if (filePath
== null
) {
711 Log_OC
.e(TAG
, "Couldn't resolve path to file");
712 Toast t
= Toast
.makeText(
713 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
721 Intent i
= new Intent(this, FileUploader
.class);
722 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
723 OCFile currentDir
= getCurrentDir();
724 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
726 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
727 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
729 if (cursor
!= null
&& cursor
.moveToFirst()) {
730 String displayName
= cursor
.getString(cursor
.getColumnIndex(
731 OpenableColumns
.DISPLAY_NAME
));
732 Log_OC
.v(TAG
, "Display Name: " + displayName
);
734 displayName
.replace(File
.separatorChar
, '_');
735 displayName
.replace(File
.pathSeparatorChar
, '_');
736 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
739 // and what happens in case of error?; wrong target name for the upload
745 remotePath
+= new File(filePath
).getName();
748 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
749 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
750 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
751 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
752 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
753 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
758 * Request the operation for moving the file/folder from one path to another
760 * @param data Intent received
761 * @param resultCode Result code received
763 private void requestMoveOperation(Intent data
, int resultCode
) {
764 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
765 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
766 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
770 * Request the operation for copying the file/folder from one path to another
772 * @param data Intent received
773 * @param resultCode Result code received
775 private void requestCopyOperation(Intent data
, int resultCode
) {
776 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
777 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
778 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
782 public void onBackPressed() {
783 if (!isDrawerOpen()){
784 OCFileListFragment listOfFiles
= getListOfFilesFragment();
785 if (mDualPane
|| getSecondFragment() == null
) {
786 OCFile currentDir
= getCurrentDir();
787 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
791 if (listOfFiles
!= null
) { // should never be null, indeed
792 listOfFiles
.onBrowseUp();
795 if (listOfFiles
!= null
) { // should never be null, indeed
796 setFile(listOfFiles
.getCurrentFile());
798 cleanSecondFragment();
800 super.onBackPressed();
805 protected void onSaveInstanceState(Bundle outState
) {
806 // responsibility of restore is preferred in onCreate() before than in
807 // onRestoreInstanceState when there are Fragments involved
808 Log_OC
.v(TAG
, "onSaveInstanceState() start");
809 super.onSaveInstanceState(outState
);
810 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
811 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
812 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
813 // mRefreshSharesInProgress);
814 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
816 Log_OC
.v(TAG
, "onSaveInstanceState() end");
821 protected void onResume() {
822 Log_OC
.v(TAG
, "onResume() start");
824 // refresh Navigation Drawer account list
825 mNavigationDrawerAdapter
.updateAccountList();
827 // refresh list of files
828 refreshListOfFilesFragment();
830 // Listen for sync messages
831 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
832 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
833 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
834 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
835 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
836 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
837 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
838 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
839 // syncIntentFilter);
841 // Listen for upload messages
842 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
843 mUploadFinishReceiver
= new UploadFinishReceiver();
844 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
846 // Listen for download messages
847 IntentFilter downloadIntentFilter
= new IntentFilter(
848 FileDownloader
.getDownloadAddedMessage());
849 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
850 mDownloadFinishReceiver
= new DownloadFinishReceiver();
851 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
853 Log_OC
.v(TAG
, "onResume() end");
859 protected void onPause() {
860 Log_OC
.v(TAG
, "onPause() start");
861 if (mSyncBroadcastReceiver
!= null
) {
862 unregisterReceiver(mSyncBroadcastReceiver
);
863 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
864 mSyncBroadcastReceiver
= null
;
866 if (mUploadFinishReceiver
!= null
) {
867 unregisterReceiver(mUploadFinishReceiver
);
868 mUploadFinishReceiver
= null
;
870 if (mDownloadFinishReceiver
!= null
) {
871 unregisterReceiver(mDownloadFinishReceiver
);
872 mDownloadFinishReceiver
= null
;
876 Log_OC
.v(TAG
, "onPause() end");
880 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
883 * {@link BroadcastReceiver} to enable syncing feedback in UI
886 public void onReceive(Context context
, Intent intent
) {
888 String event
= intent
.getAction();
889 Log_OC
.d(TAG
, "Received broadcast " + event
);
890 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
891 String synchFolderRemotePath
=
892 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
893 RemoteOperationResult synchResult
=
894 (RemoteOperationResult
)intent
.getSerializableExtra(
895 FileSyncAdapter
.EXTRA_RESULT
);
896 boolean sameAccount
= (getAccount() != null
&&
897 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
901 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
902 mSyncInProgress
= true
;
905 OCFile currentFile
= (getFile() == null
) ? null
:
906 getStorageManager().getFileByPath(getFile().getRemotePath());
907 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
908 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
910 if (currentDir
== null
) {
911 // current folder was removed from the server
912 Toast
.makeText( FileDisplayActivity
.this,
915 sync_current_folder_was_removed
),
916 synchFolderRemotePath
),
923 if (currentFile
== null
&& !getFile().isFolder()) {
924 // currently selected file was removed in the server, and now we
926 cleanSecondFragment();
927 currentFile
= currentDir
;
930 if (synchFolderRemotePath
!= null
&&
931 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
932 OCFileListFragment fileListFragment
= getListOfFilesFragment();
933 if (fileListFragment
!= null
) {
934 fileListFragment
.listDirectory();
935 // TODO Enable when "On Device" is recovered ?
936 // fileListFragment.listDirectory(currentDir,
937 // MainApp.getOnlyOnDevice());
940 setFile(currentFile
);
943 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
944 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
947 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
948 equals(event
) &&/// TODO refactor and make common
950 synchResult
!= null
&& !synchResult
.isSuccess() &&
951 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
952 synchResult
.isIdPRedirection() ||
953 (synchResult
.isException() && synchResult
.getException()
954 instanceof AuthenticatorException
))) {
958 OwnCloudClient client
;
959 OwnCloudAccount ocAccount
=
960 new OwnCloudAccount(getAccount(), context
);
961 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
962 removeClientFor(ocAccount
));
963 if (client
!= null
) {
964 OwnCloudCredentials cred
= client
.getCredentials();
966 AccountManager am
= AccountManager
.get(context
);
967 if (cred
.authTokenExpires()) {
968 am
.invalidateAuthToken(
973 am
.clearPassword(getAccount());
977 requestCredentialsUpdate();
979 } catch (AccountNotFoundException e
) {
980 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
985 removeStickyBroadcast(intent
);
986 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
987 mProgressBar
.setIndeterminate(mSyncInProgress
);
988 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
989 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
990 /*|| mRefreshSharesInProgress*/ //);
996 if (synchResult
!= null
) {
997 if (synchResult
.getCode().equals(
998 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
999 mLastSslUntrustedServerResult
= synchResult
;
1002 } catch (RuntimeException e
) {
1003 // avoid app crashes after changing the serial id of RemoteOperationResult
1004 // in owncloud library with broadcast notifications pending to process
1005 removeStickyBroadcast(intent
);
1011 * Show a text message on screen view for notifying user if content is
1012 * loading or folder is empty
1014 private void setBackgroundText() {
1015 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1016 if (ocFileListFragment
!= null
) {
1017 int message
= R
.string
.file_list_loading
;
1018 if (!mSyncInProgress
) {
1019 // In case file list is empty
1020 message
= R
.string
.file_list_empty
;
1022 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1024 Log_OC
.e(TAG
, "OCFileListFragment is null");
1029 * Once the file upload has finished -> update view
1031 private class UploadFinishReceiver
extends BroadcastReceiver
{
1033 * Once the file upload has finished -> update view
1035 * @author David A. Velasco
1036 * {@link BroadcastReceiver} to enable upload feedback in UI
1039 public void onReceive(Context context
, Intent intent
) {
1041 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1042 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1043 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1044 OCFile currentDir
= getCurrentDir();
1045 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1046 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1048 if (sameAccount
&& isDescendant
) {
1049 String linkedToRemotePath
=
1050 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1051 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1052 refreshListOfFilesFragment();
1056 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1058 boolean renamedInUpload
= getFile().getRemotePath().
1059 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1060 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1062 FileFragment details
= getSecondFragment();
1063 boolean detailFragmentIsShown
= (details
!= null
&&
1064 details
instanceof FileDetailFragment
);
1066 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1067 if (uploadWasFine
) {
1068 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1070 if (renamedInUpload
) {
1071 String newName
= (new File(uploadedRemotePath
)).getName();
1072 Toast msg
= Toast
.makeText(
1075 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1080 if (uploadWasFine
|| getFile().fileExists()) {
1081 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1083 cleanSecondFragment();
1086 // Force the preview if the file is an image or text file
1087 if (uploadWasFine
) {
1088 OCFile ocFile
= getFile();
1089 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1090 startImagePreview(getFile());
1091 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1092 startTextPreview(ocFile
);
1093 // TODO what about other kind of previews?
1097 mProgressBar
.setIndeterminate(false
);
1099 if (intent
!= null
) {
1100 removeStickyBroadcast(intent
);
1106 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1107 private boolean isAscendant(String linkedToRemotePath
) {
1108 OCFile currentDir
= getCurrentDir();
1110 currentDir
!= null
&&
1111 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1120 * Class waiting for broadcast events from the {@link FileDownloader} service.
1122 * Updates the UI when a download is started or finished, provided that it is relevant for the
1125 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1128 public void onReceive(Context context
, Intent intent
) {
1130 boolean sameAccount
= isSameAccount(intent
);
1131 String downloadedRemotePath
=
1132 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1133 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1135 if (sameAccount
&& isDescendant
) {
1136 String linkedToRemotePath
=
1137 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1138 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1139 refreshListOfFilesFragment();
1141 refreshSecondFragment(
1143 downloadedRemotePath
,
1144 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1148 if (mWaitingToSend
!= null
) {
1150 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1151 if (mWaitingToSend
.isDown()) {
1152 sendDownloadedFile();
1157 if (intent
!= null
) {
1158 removeStickyBroadcast(intent
);
1163 private boolean isDescendant(String downloadedRemotePath
) {
1164 OCFile currentDir
= getCurrentDir();
1166 currentDir
!= null
&&
1167 downloadedRemotePath
!= null
&&
1168 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1172 private boolean isAscendant(String linkedToRemotePath
) {
1173 OCFile currentDir
= getCurrentDir();
1175 currentDir
!= null
&&
1176 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1180 private boolean isSameAccount(Intent intent
) {
1181 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1182 return (accountName
!= null
&& getAccount() != null
&&
1183 accountName
.equals(getAccount().name
));
1188 public void browseToRoot() {
1189 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1190 if (listOfFiles
!= null
) { // should never be null, indeed
1191 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1192 listOfFiles
.listDirectory(root
);
1193 // TODO Enable when "On Device" is recovered ?
1194 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1195 setFile(listOfFiles
.getCurrentFile());
1196 startSyncFolderOperation(root
, false
);
1198 cleanSecondFragment();
1205 * Updates action bar and second fragment, if in dual pane mode.
1208 public void onBrowsedDownTo(OCFile directory
) {
1210 cleanSecondFragment();
1212 startSyncFolderOperation(directory
, false
);
1216 * Shows the information of the {@link OCFile} received as a
1217 * parameter in the second fragment.
1219 * @param file {@link OCFile} whose details will be shown
1222 public void showDetails(OCFile file
) {
1223 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1224 setSecondFragment(detailFragment
);
1225 updateFragmentsVisibility(true
);
1226 updateActionBarTitleAndHomeButton(file
);
1231 * Shows the share view for sharing {@link OCFile} received as a
1232 * parameter in the second fragment.
1234 * @param file {@link OCFile} File to share with
1237 public void showShareFile(OCFile file
) {
1238 Intent intent
= new Intent(this, ShareActivity
.class);
1239 intent
.putExtra(EXTRA_FILE
, file
);
1240 intent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1241 startActivity(intent
);
1245 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1247 // in dual pane mode, keep the focus of title an action bar in the current folder
1248 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1251 super.updateActionBarTitleAndHomeButton(chosenFile
);
1257 protected ServiceConnection
newTransferenceServiceConnection() {
1258 return new ListServiceConnection();
1262 * Defines callbacks for service binding, passed to bindService()
1264 private class ListServiceConnection
implements ServiceConnection
{
1267 public void onServiceConnected(ComponentName component
, IBinder service
) {
1268 if (component
.equals(new ComponentName(
1269 FileDisplayActivity
.this, FileDownloader
.class))) {
1270 Log_OC
.d(TAG
, "Download service connected");
1271 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1272 if (mWaitingToPreview
!= null
)
1273 if (getStorageManager() != null
) {
1276 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1277 if (!mWaitingToPreview
.isDown()) {
1278 requestForDownload();
1282 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1283 FileUploader
.class))) {
1284 Log_OC
.d(TAG
, "Upload service connected");
1285 mUploaderBinder
= (FileUploaderBinder
) service
;
1289 // a new chance to get the mDownloadBinder through
1290 // getFileDownloadBinder() - THIS IS A MESS
1291 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1292 if (listOfFiles
!= null
) {
1293 listOfFiles
.listDirectory();
1294 // TODO Enable when "On Device" is recovered ?
1295 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1297 FileFragment secondFragment
= getSecondFragment();
1298 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1299 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1300 detailFragment
.listenForTransferProgress();
1301 detailFragment
.updateFileDetails(false
, false
);
1306 public void onServiceDisconnected(ComponentName component
) {
1307 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1308 FileDownloader
.class))) {
1309 Log_OC
.d(TAG
, "Download service disconnected");
1310 mDownloaderBinder
= null
;
1311 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1312 FileUploader
.class))) {
1313 Log_OC
.d(TAG
, "Upload service disconnected");
1314 mUploaderBinder
= null
;
1320 public void onSavedCertificate() {
1321 startSyncFolderOperation(getCurrentDir(), false
);
1326 public void onFailedSavingCertificate() {
1327 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1328 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1330 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1334 public void onCancelCertificate() {
1339 * Updates the view associated to the activity after the finish of some operation over files
1340 * in the current account.
1342 * @param operation Removal operation performed.
1343 * @param result Result of the removal.
1346 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1347 super.onRemoteOperationFinish(operation
, result
);
1349 if (operation
instanceof RemoveFileOperation
) {
1350 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1352 } else if (operation
instanceof RenameFileOperation
) {
1353 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1355 } else if (operation
instanceof SynchronizeFileOperation
) {
1356 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1358 } else if (operation
instanceof CreateFolderOperation
) {
1359 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1361 } else if (operation
instanceof CreateShareOperation
) {
1362 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1364 } else if (operation
instanceof UnshareOperation
) {
1365 onUnshareLinkOperationFinish((UnshareOperation
) operation
, result
);
1367 } else if (operation
instanceof MoveFileOperation
) {
1368 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1370 } else if (operation
instanceof CopyFileOperation
) {
1371 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1375 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1376 RemoteOperationResult result
) {
1377 if (result
.isSuccess()) {
1378 refreshShowDetails();
1379 refreshListOfFilesFragment();
1383 private void onUnshareLinkOperationFinish(UnshareOperation operation
,
1384 RemoteOperationResult result
) {
1385 if (result
.isSuccess()) {
1386 refreshShowDetails();
1387 refreshListOfFilesFragment();
1389 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1390 cleanSecondFragment();
1391 refreshListOfFilesFragment();
1395 private void refreshShowDetails() {
1396 FileFragment details
= getSecondFragment();
1397 if (details
!= null
) {
1398 OCFile file
= details
.getFile();
1400 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1401 if (details
instanceof PreviewMediaFragment
) {
1402 // Refresh OCFile of the fragment
1403 ((PreviewMediaFragment
) details
).updateFile(file
);
1404 } else if (details
instanceof PreviewTextFragment
) {
1405 // Refresh OCFile of the fragment
1406 ((PreviewTextFragment
) details
).updateFile(file
);
1411 invalidateOptionsMenu();
1416 * Updates the view associated to the activity after the finish of an operation trying to
1419 * @param operation Removal operation performed.
1420 * @param result Result of the removal.
1422 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1423 RemoteOperationResult result
) {
1424 dismissLoadingDialog();
1426 Toast msg
= Toast
.makeText(this,
1427 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1431 if (result
.isSuccess()) {
1432 OCFile removedFile
= operation
.getFile();
1433 FileFragment second
= getSecondFragment();
1434 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1435 if (second
instanceof PreviewMediaFragment
) {
1436 ((PreviewMediaFragment
) second
).stopPreview(true
);
1438 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1439 cleanSecondFragment();
1441 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1442 refreshListOfFilesFragment();
1444 invalidateOptionsMenu();
1446 if (result
.isSslRecoverableException()) {
1447 mLastSslUntrustedServerResult
= result
;
1448 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1455 * Updates the view associated to the activity after the finish of an operation trying to move a
1458 * @param operation Move operation performed.
1459 * @param result Result of the move operation.
1461 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1462 RemoteOperationResult result
) {
1463 if (result
.isSuccess()) {
1464 dismissLoadingDialog();
1465 refreshListOfFilesFragment();
1467 dismissLoadingDialog();
1469 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1470 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1474 } catch (NotFoundException e
) {
1475 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1481 * Updates the view associated to the activity after the finish of an operation trying to copy a
1484 * @param operation Copy operation performed.
1485 * @param result Result of the copy operation.
1487 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1488 if (result
.isSuccess()) {
1489 dismissLoadingDialog();
1490 refreshListOfFilesFragment();
1492 dismissLoadingDialog();
1494 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1495 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1499 } catch (NotFoundException e
) {
1500 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1506 * Updates the view associated to the activity after the finish of an operation trying to rename
1509 * @param operation Renaming operation performed.
1510 * @param result Result of the renaming.
1512 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1513 RemoteOperationResult result
) {
1514 dismissLoadingDialog();
1515 OCFile renamedFile
= operation
.getFile();
1516 if (result
.isSuccess()) {
1517 FileFragment details
= getSecondFragment();
1518 if (details
!= null
) {
1519 if (details
instanceof FileDetailFragment
&&
1520 renamedFile
.equals(details
.getFile()) ) {
1521 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1522 showDetails(renamedFile
);
1524 } else if (details
instanceof PreviewMediaFragment
&&
1525 renamedFile
.equals(details
.getFile())) {
1526 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1527 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1528 int position
= ((PreviewMediaFragment
) details
).getPosition();
1529 startMediaPreview(renamedFile
, position
, true
);
1531 getFileOperationsHelper().openFile(renamedFile
);
1533 } else if (details
instanceof PreviewTextFragment
&&
1534 renamedFile
.equals(details
.getFile())) {
1535 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1536 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1537 startTextPreview(renamedFile
);
1539 getFileOperationsHelper().openFile(renamedFile
);
1544 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1545 refreshListOfFilesFragment();
1549 Toast msg
= Toast
.makeText(this,
1550 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1554 if (result
.isSslRecoverableException()) {
1555 mLastSslUntrustedServerResult
= result
;
1556 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1561 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1562 RemoteOperationResult result
) {
1563 if (result
.isSuccess()) {
1564 if (operation
.transferWasRequested()) {
1565 OCFile syncedFile
= operation
.getLocalFile();
1566 onTransferStateChanged(syncedFile
, true
, true
);
1567 invalidateOptionsMenu();
1568 refreshShowDetails();
1574 * Updates the view associated to the activity after the finish of an operation trying create a
1577 * @param operation Creation operation performed.
1578 * @param result Result of the creation.
1580 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1581 RemoteOperationResult result
) {
1582 if (result
.isSuccess()) {
1583 dismissLoadingDialog();
1584 refreshListOfFilesFragment();
1586 dismissLoadingDialog();
1588 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1589 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1593 } catch (NotFoundException e
) {
1594 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1604 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1605 refreshListOfFilesFragment();
1606 FileFragment details
= getSecondFragment();
1607 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1608 file
.equals(details
.getFile()) ) {
1609 if (downloading
|| uploading
) {
1610 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1612 if (!file
.fileExists()) {
1613 cleanSecondFragment();
1615 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1623 private void requestForDownload() {
1624 Account account
= getAccount();
1625 //if (!mWaitingToPreview.isDownloading()) {
1626 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1627 Intent i
= new Intent(this, FileDownloader
.class);
1628 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1629 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1635 private OCFile
getCurrentDir() {
1636 OCFile file
= getFile();
1638 if (file
.isFolder()) {
1640 } else if (getStorageManager() != null
) {
1641 String parentPath
= file
.getRemotePath().substring(0,
1642 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1643 return getStorageManager().getFileByPath(parentPath
);
1649 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1650 long currentSyncTime
= System
.currentTimeMillis();
1652 mSyncInProgress
= true
;
1654 // perform folder synchronization
1655 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1658 getFileOperationsHelper().isSharedSupported(),
1660 getStorageManager(),
1662 getApplicationContext()
1664 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1666 mProgressBar
.setIndeterminate(true
);
1668 setBackgroundText();
1672 * Show untrusted cert dialog
1674 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1675 // Show a dialog with the certificate info
1676 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1677 (CertificateCombinedException
) result
.getException());
1678 FragmentManager fm
= getSupportFragmentManager();
1679 FragmentTransaction ft
= fm
.beginTransaction();
1680 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1683 private void requestForDownload(OCFile file
) {
1684 Account account
= getAccount();
1685 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1686 Intent i
= new Intent(this, FileDownloader
.class);
1687 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1688 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1693 private void sendDownloadedFile() {
1694 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1695 mWaitingToSend
= null
;
1700 * Requests the download of the received {@link OCFile} , updates the UI
1701 * to monitor the download progress and prepares the activity to send the file
1702 * when the download finishes.
1704 * @param file {@link OCFile} to download and preview.
1706 public void startDownloadForSending(OCFile file
) {
1707 mWaitingToSend
= file
;
1708 requestForDownload(mWaitingToSend
);
1709 boolean hasSecondFragment
= (getSecondFragment() != null
);
1710 updateFragmentsVisibility(hasSecondFragment
);
1714 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1716 * @param file Image {@link OCFile} to show.
1718 public void startImagePreview(OCFile file
) {
1719 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1720 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1721 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1722 startActivity(showDetailsIntent
);
1726 * Stars the preview of an already down media {@link OCFile}.
1728 * @param file Media {@link OCFile} to preview.
1729 * @param startPlaybackPosition Media position where the playback will be started,
1731 * @param autoplay When 'true', the playback will start without user
1734 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1735 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1737 setSecondFragment(mediaFragment
);
1738 updateFragmentsVisibility(true
);
1739 updateActionBarTitleAndHomeButton(file
);
1744 * Stars the preview of a text file {@link OCFile}.
1746 * @param file Text {@link OCFile} to preview.
1748 public void startTextPreview(OCFile file
) {
1749 Bundle args
= new Bundle();
1750 args
.putParcelable(EXTRA_FILE
, file
);
1751 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1752 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1753 PreviewTextFragment
.class.getName(), args
);
1754 setSecondFragment(textPreviewFragment
);
1755 updateFragmentsVisibility(true
);
1756 //updateNavigationElementsInActionBar(file);
1761 * Requests the download of the received {@link OCFile} , updates the UI
1762 * to monitor the download progress and prepares the activity to preview
1763 * or open the file when the download finishes.
1765 * @param file {@link OCFile} to download and preview.
1767 public void startDownloadForPreview(OCFile file
) {
1768 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1769 setSecondFragment(detailFragment
);
1770 mWaitingToPreview
= file
;
1771 requestForDownload();
1772 updateFragmentsVisibility(true
);
1773 updateActionBarTitleAndHomeButton(file
);
1778 public void cancelTransference(OCFile file
) {
1779 getFileOperationsHelper().cancelTransference(file
);
1780 if (mWaitingToPreview
!= null
&&
1781 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1782 mWaitingToPreview
= null
;
1784 if (mWaitingToSend
!= null
&&
1785 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1786 mWaitingToSend
= null
;
1788 onTransferStateChanged(file
, false
, false
);
1792 public void onRefresh(boolean ignoreETag
) {
1793 refreshList(ignoreETag
);
1797 public void onRefresh() {
1801 private void refreshList(boolean ignoreETag
) {
1802 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1803 if (listOfFiles
!= null
) {
1804 OCFile folder
= listOfFiles
.getCurrentFile();
1805 if (folder
!= null
) {
1806 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1807 listDirectory(mFile);*/
1808 startSyncFolderOperation(folder
, ignoreETag
);
1813 private void sortByDate(boolean ascending
) {
1814 getListOfFilesFragment().sortByDate(ascending
);
1817 private void sortBySize(boolean ascending
) {
1818 getListOfFilesFragment().sortBySize(ascending
);
1821 private void sortByName(boolean ascending
) {
1822 getListOfFilesFragment().sortByName(ascending
);
1825 public void allFilesOption() {