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
.os
.Parcelable
;
30 import android
.support
.v7
.app
.AlertDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Build
;
45 import android
.os
.Bundle
;
46 import android
.os
.IBinder
;
47 import android
.preference
.PreferenceManager
;
48 import android
.provider
.OpenableColumns
;
49 import android
.support
.v4
.app
.Fragment
;
50 import android
.support
.v4
.app
.FragmentManager
;
51 import android
.support
.v4
.app
.FragmentTransaction
;
52 import android
.support
.v4
.content
.ContextCompat
;
53 import android
.support
.v4
.view
.GravityCompat
;
54 import android
.view
.Menu
;
55 import android
.view
.MenuInflater
;
56 import android
.view
.MenuItem
;
57 import android
.view
.View
;
58 import android
.widget
.ProgressBar
;
59 import android
.widget
.RelativeLayout
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import com
.owncloud
.android
.MainApp
;
64 import com
.owncloud
.android
.R
;
65 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
81 import com
.owncloud
.android
.operations
.CopyFileOperation
;
82 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 import com
.owncloud
.android
.utils
.FileStorageUtils
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
111 import java
.util
.ArrayList
;
112 import java
.util
.Iterator
;
115 * Displays, what files the user has available in his ownCloud.
118 public class FileDisplayActivity
extends HookActivity
119 implements FileFragment
.ContainerActivity
,
120 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
124 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
125 private UploadFinishReceiver mUploadFinishReceiver
;
126 private DownloadFinishReceiver mDownloadFinishReceiver
;
127 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
129 private boolean mDualPane
;
130 private View mLeftFragmentContainer
;
131 private View mRightFragmentContainer
;
132 private ProgressBar mProgressBar
;
134 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
135 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
136 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
138 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
140 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
141 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
142 public static final int ACTION_MOVE_FILES
= 3;
143 public static final int ACTION_COPY_FILES
= 4;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
152 private boolean mSyncInProgress
= false
;
154 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
155 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
156 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
157 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
159 private OCFile mWaitingToSend
;
163 protected void onCreate(Bundle savedInstanceState
) {
164 Log_OC
.v(TAG
, "onCreate() start");
166 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
169 /// grant that FileObserverService is watching favorite files
170 if (savedInstanceState
== null
) {
171 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
172 startService(initObserversIntent
);
175 /// Load of saved instance state
176 if(savedInstanceState
!= null
) {
177 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
178 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
179 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
180 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
181 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
183 mWaitingToPreview
= null
;
184 mSyncInProgress
= false
;
185 mWaitingToSend
= null
;
190 // Inflate and set the layout view
191 setContentView(R
.layout
.files
);
196 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
197 mProgressBar
.setIndeterminateDrawable(
198 ContextCompat
.getDrawable(this,
199 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
201 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
202 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
203 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
204 if (savedInstanceState
== null
) {
205 createMinFragments();
209 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
210 // according to the official
213 // enable ActionBar app icon to behave as action to toggle nav drawer
214 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
215 getSupportActionBar().setHomeButtonEnabled(true
);
217 mProgressBar
.setIndeterminate(mSyncInProgress
);
218 // always AFTER setContentView(...) ; to work around bug in its implementation
222 Log_OC
.v(TAG
, "onCreate() end");
226 protected void onStart() {
227 Log_OC
.v(TAG
, "onStart() start");
229 Log_OC
.v(TAG
, "onStart() end");
233 protected void onDestroy() {
234 Log_OC
.v(TAG
, "onDestroy() start");
236 Log_OC
.v(TAG
, "onDestroy() end");
240 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
243 protected void onAccountSet(boolean stateWasRecovered
) {
244 super.onAccountSet(stateWasRecovered
);
245 if (getAccount() != null
) {
246 /// Check whether the 'main' OCFile handled by the Activity is contained in the
248 OCFile file
= getFile();
249 // get parent from path
250 String parentPath
= "";
252 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
253 // upload in progress - right now, files are not inserted in the local
254 // cache until the upload is successful get parent from path
255 parentPath
= file
.getRemotePath().substring(0,
256 file
.getRemotePath().lastIndexOf(file
.getFileName()));
257 if (getStorageManager().getFileByPath(parentPath
) == null
)
258 file
= null
; // not able to know the directory where the file is uploading
260 file
= getStorageManager().getFileByPath(file
.getRemotePath());
261 // currentDir = null if not in the current Account
265 // fall back to root folder
266 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
270 if (mAccountWasSet
) {
271 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
272 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
273 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
274 int lastAtPos
= getAccount().name
.lastIndexOf("@");
275 username
.setText(getAccount().name
.substring(0, lastAtPos
));
279 if (!stateWasRecovered
) {
280 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
281 initFragmentsWithFile();
282 if (file
.isFolder()) {
283 startSyncFolderOperation(file
, false
);
287 updateFragmentsVisibility(!file
.isFolder());
288 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
293 private void createMinFragments() {
294 OCFileListFragment listOfFiles
= new OCFileListFragment();
295 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
296 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
297 transaction
.commit();
300 private void initFragmentsWithFile() {
301 if (getAccount() != null
&& getFile() != null
) {
303 OCFileListFragment listOfFiles
= getListOfFilesFragment();
304 if (listOfFiles
!= null
) {
305 listOfFiles
.listDirectory(getCurrentDir());
306 // TODO Enable when "On Device" is recovered
307 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
310 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
314 OCFile file
= getFile();
315 Fragment secondFragment
= chooseInitialSecondFragment(file
);
316 if (secondFragment
!= null
) {
317 setSecondFragment(secondFragment
);
318 updateFragmentsVisibility(true
);
319 updateActionBarTitleAndHomeButton(file
);
322 cleanSecondFragment();
323 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
324 startTextPreview(file
);
328 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
329 if (getAccount() == null
) {
330 Log_OC
.wtf(TAG
, "\t account is NULL");
332 if (getFile() == null
) {
333 Log_OC
.wtf(TAG
, "\t file is NULL");
338 private Fragment
chooseInitialSecondFragment(OCFile file
) {
339 Fragment secondFragment
= null
;
340 if (file
!= null
&& !file
.isFolder()) {
341 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
342 && file
.getLastSyncDateForProperties() > 0 // temporal fix
344 int startPlaybackPosition
=
345 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
347 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
348 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
349 startPlaybackPosition
, autoplay
);
351 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
352 secondFragment
= null
;
354 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
357 return secondFragment
;
362 * Replaces the second fragment managed by the activity with the received as
365 * Assumes never will be more than two fragments managed at the same time.
367 * @param fragment New second Fragment to set.
369 private void setSecondFragment(Fragment fragment
) {
370 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
371 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
372 transaction
.commit();
376 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
378 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
381 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
382 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
385 } else if (existsSecondFragment
) {
386 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
387 mLeftFragmentContainer
.setVisibility(View
.GONE
);
389 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
390 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
394 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
395 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
397 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
398 mRightFragmentContainer
.setVisibility(View
.GONE
);
404 private OCFileListFragment
getListOfFilesFragment() {
405 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
406 FileDisplayActivity
.TAG_LIST_OF_FILES
);
407 if (listOfFiles
!= null
) {
408 return (OCFileListFragment
) listOfFiles
;
410 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
414 public FileFragment
getSecondFragment() {
415 Fragment second
= getSupportFragmentManager().findFragmentByTag(
416 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
417 if (second
!= null
) {
418 return (FileFragment
) second
;
423 protected void cleanSecondFragment() {
424 Fragment second
= getSecondFragment();
425 if (second
!= null
) {
426 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
430 updateFragmentsVisibility(false
);
431 updateActionBarTitleAndHomeButton(null
);
434 protected void refreshListOfFilesFragment() {
435 OCFileListFragment fileListFragment
= getListOfFilesFragment();
436 if (fileListFragment
!= null
) {
437 fileListFragment
.listDirectory();
438 // TODO Enable when "On Device" is recovered ?
439 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
443 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
445 FileFragment secondFragment
= getSecondFragment();
446 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
447 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
448 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
449 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
450 OCFile fileInFragment
= detailsFragment
.getFile();
451 if (fileInFragment
!= null
&&
452 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
453 // the user browsed to other file ; forget the automatic preview
454 mWaitingToPreview
= null
;
456 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
457 // grant that the right panel updates the progress bar
458 detailsFragment
.listenForTransferProgress();
459 detailsFragment
.updateFileDetails(true
, false
);
461 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
462 // update the right panel
463 boolean detailsFragmentChanged
= false
;
466 mWaitingToPreview
= getStorageManager().getFileById(
467 mWaitingToPreview
.getFileId()); // update the file from database,
468 // for the local storage path
469 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
470 startMediaPreview(mWaitingToPreview
, 0, true
);
471 detailsFragmentChanged
= true
;
472 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
473 startTextPreview(mWaitingToPreview
);
474 detailsFragmentChanged
= true
;
476 getFileOperationsHelper().openFile(mWaitingToPreview
);
479 mWaitingToPreview
= null
;
481 if (!detailsFragmentChanged
) {
482 detailsFragment
.updateFileDetails(false
, (success
));
489 public boolean onPrepareOptionsMenu(Menu menu
) {
490 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
491 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
492 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
493 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
494 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
496 return super.onPrepareOptionsMenu(menu
);
500 public boolean onCreateOptionsMenu(Menu menu
) {
501 MenuInflater inflater
= getMenuInflater();
502 inflater
.inflate(R
.menu
.main_menu
, menu
);
508 public boolean onOptionsItemSelected(MenuItem item
) {
509 boolean retval
= true
;
510 switch (item
.getItemId()) {
511 case R
.id
.action_create_dir
: {
512 CreateFolderDialogFragment dialog
=
513 CreateFolderDialogFragment
.newInstance(getCurrentDir());
514 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
518 case R
.id
.action_sync_account
: {
519 startSynchronization();
522 case R
.id
.action_upload
: {
523 UploadSourceDialogFragment dialog
=
524 UploadSourceDialogFragment
.newInstance(getAccount());
525 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
528 case android
.R
.id
.home
: {
529 FileFragment second
= getSecondFragment();
530 OCFile currentDir
= getCurrentDir();
531 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
532 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
533 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
534 (second
!= null
&& second
.getFile() != null
)) {
538 mDrawerLayout
.openDrawer(GravityCompat
.START
);
542 case R
.id
.action_sort
: {
543 SharedPreferences appPreferences
= PreferenceManager
544 .getDefaultSharedPreferences(this);
546 // Read sorting order, default to sort by name ascending
547 Integer sortOrder
= appPreferences
548 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
550 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
551 builder
.setTitle(R
.string
.actionbar_sort_title
)
552 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
553 new DialogInterface
.OnClickListener() {
554 public void onClick(DialogInterface dialog
, int which
) {
567 builder
.create().show();
571 retval
= super.onOptionsItemSelected(item
);
576 private void startSynchronization() {
577 Log_OC
.d(TAG
, "Got to start sync");
578 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
579 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
580 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
581 // cancel the current synchronizations of any ownCloud account
582 Bundle bundle
= new Bundle();
583 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
584 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
585 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
586 MainApp
.getAuthority());
587 ContentResolver
.requestSync(
589 MainApp
.getAuthority(), bundle
);
591 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
592 MainApp
.getAuthority() + " with new API");
593 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
594 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
595 builder
.setExpedited(true
);
596 builder
.setManual(true
);
599 // Fix bug in Android Lollipop when you click on refresh the whole account
600 Bundle extras
= new Bundle();
601 builder
.setExtras(extras
);
603 SyncRequest request
= builder
.build();
604 ContentResolver
.requestSync(request
);
609 * Called, when the user selected something for uploading
612 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
614 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
616 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
617 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
618 //getClipData is only supported on api level 16+, Jelly Bean
619 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
620 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
621 Intent intent
= new Intent();
622 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
623 requestSimpleUpload(intent
, resultCode
);
626 requestSimpleUpload(data
, resultCode
);
628 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
629 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
630 requestMultipleUpload(data
, resultCode
);
632 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
633 final Intent fData
= data
;
634 final int fResultCode
= resultCode
;
635 getHandler().postDelayed(
639 requestMoveOperation(fData
, fResultCode
);
642 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
645 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
647 final Intent fData
= data
;
648 final int fResultCode
= resultCode
;
649 getHandler().postDelayed(
653 requestCopyOperation(fData
, fResultCode
);
656 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
660 super.onActivityResult(requestCode
, resultCode
, data
);
665 private void requestMultipleUpload(Intent data
, int resultCode
) {
666 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
667 if (filePaths
!= null
) {
668 String
[] remotePaths
= new String
[filePaths
.length
];
669 String remotePathBase
= getCurrentDir().getRemotePath();
670 for (int j
= 0; j
< remotePaths
.length
; j
++) {
671 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
674 Intent i
= new Intent(this, FileUploader
.class);
675 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
676 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
677 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
678 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
679 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
680 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
684 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
685 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
693 private void requestSimpleUpload(Intent data
, int resultCode
) {
694 String filePath
= null
;
695 String mimeType
= null
;
697 Uri selectedImageUri
= data
.getData();
700 mimeType
= getContentResolver().getType(selectedImageUri
);
702 String fileManagerString
= selectedImageUri
.getPath();
703 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
705 if (selectedImagePath
!= null
)
706 filePath
= selectedImagePath
;
708 filePath
= fileManagerString
;
710 } catch (Exception e
) {
711 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
712 "Intent.ACTION_GET_CONTENT", e
);
715 if (filePath
== null
) {
716 Log_OC
.e(TAG
, "Couldn't resolve path to file");
717 Toast t
= Toast
.makeText(
718 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
726 Intent i
= new Intent(this, FileUploader
.class);
727 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
728 OCFile currentDir
= getCurrentDir();
729 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
731 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
732 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
734 if (cursor
!= null
&& cursor
.moveToFirst()) {
735 String displayName
= cursor
.getString(cursor
.getColumnIndex(
736 OpenableColumns
.DISPLAY_NAME
));
737 Log_OC
.v(TAG
, "Display Name: " + displayName
);
739 displayName
.replace(File
.separatorChar
, '_');
740 displayName
.replace(File
.pathSeparatorChar
, '_');
741 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
744 // and what happens in case of error?; wrong target name for the upload
750 remotePath
+= new File(filePath
).getName();
753 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
754 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
755 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
756 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
757 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
758 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
763 * Request the operation for moving the file/folder from one path to another
765 * @param data Intent received
766 * @param resultCode Result code received
768 private void requestMoveOperation(Intent data
, int resultCode
) {
769 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
771 ArrayList
<OCFile
> files
= data
.getParcelableArrayListExtra(FolderPickerActivity
.EXTRA_FILES
);
773 for (Parcelable file
: files
) {
774 getFileOperationsHelper().moveFile(folderToMoveAt
, (OCFile
) file
);
779 * Request the operation for copying the file/folder from one path to another
781 * @param data Intent received
782 * @param resultCode Result code received
784 private void requestCopyOperation(Intent data
, int resultCode
) {
785 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
787 ArrayList
<OCFile
> files
= data
.getParcelableArrayListExtra(FolderPickerActivity
.EXTRA_FILES
);
789 for (Parcelable file
: files
) {
790 getFileOperationsHelper().copyFile(folderToMoveAt
, (OCFile
) file
);
795 public void onBackPressed() {
796 if (!isDrawerOpen()){
797 OCFileListFragment listOfFiles
= getListOfFilesFragment();
798 if (mDualPane
|| getSecondFragment() == null
) {
799 OCFile currentDir
= getCurrentDir();
800 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
804 if (listOfFiles
!= null
) { // should never be null, indeed
805 listOfFiles
.onBrowseUp();
808 if (listOfFiles
!= null
) { // should never be null, indeed
809 setFile(listOfFiles
.getCurrentFile());
811 cleanSecondFragment();
813 super.onBackPressed();
818 protected void onSaveInstanceState(Bundle outState
) {
819 // responsibility of restore is preferred in onCreate() before than in
820 // onRestoreInstanceState when there are Fragments involved
821 Log_OC
.v(TAG
, "onSaveInstanceState() start");
822 super.onSaveInstanceState(outState
);
823 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
824 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
825 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
826 // mRefreshSharesInProgress);
827 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
829 Log_OC
.v(TAG
, "onSaveInstanceState() end");
834 protected void onResume() {
835 Log_OC
.v(TAG
, "onResume() start");
837 // refresh Navigation Drawer account list
838 mNavigationDrawerAdapter
.updateAccountList();
840 // refresh list of files
841 refreshListOfFilesFragment();
843 // Listen for sync messages
844 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
845 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
846 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
847 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
848 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
849 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
850 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
851 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
852 // syncIntentFilter);
854 // Listen for upload messages
855 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
856 mUploadFinishReceiver
= new UploadFinishReceiver();
857 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
859 // Listen for download messages
860 IntentFilter downloadIntentFilter
= new IntentFilter(
861 FileDownloader
.getDownloadAddedMessage());
862 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
863 mDownloadFinishReceiver
= new DownloadFinishReceiver();
864 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
866 Log_OC
.v(TAG
, "onResume() end");
872 protected void onPause() {
873 Log_OC
.v(TAG
, "onPause() start");
874 if (mSyncBroadcastReceiver
!= null
) {
875 unregisterReceiver(mSyncBroadcastReceiver
);
876 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
877 mSyncBroadcastReceiver
= null
;
879 if (mUploadFinishReceiver
!= null
) {
880 unregisterReceiver(mUploadFinishReceiver
);
881 mUploadFinishReceiver
= null
;
883 if (mDownloadFinishReceiver
!= null
) {
884 unregisterReceiver(mDownloadFinishReceiver
);
885 mDownloadFinishReceiver
= null
;
889 Log_OC
.v(TAG
, "onPause() end");
893 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
896 * {@link BroadcastReceiver} to enable syncing feedback in UI
899 public void onReceive(Context context
, Intent intent
) {
901 String event
= intent
.getAction();
902 Log_OC
.d(TAG
, "Received broadcast " + event
);
903 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
904 String synchFolderRemotePath
=
905 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
906 RemoteOperationResult synchResult
=
907 (RemoteOperationResult
)intent
.getSerializableExtra(
908 FileSyncAdapter
.EXTRA_RESULT
);
909 boolean sameAccount
= (getAccount() != null
&&
910 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
914 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
915 mSyncInProgress
= true
;
918 OCFile currentFile
= (getFile() == null
) ? null
:
919 getStorageManager().getFileByPath(getFile().getRemotePath());
920 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
921 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
923 if (currentDir
== null
) {
924 // current folder was removed from the server
925 Toast
.makeText( FileDisplayActivity
.this,
928 sync_current_folder_was_removed
),
929 synchFolderRemotePath
),
936 if (currentFile
== null
&& !getFile().isFolder()) {
937 // currently selected file was removed in the server, and now we
939 cleanSecondFragment();
940 currentFile
= currentDir
;
943 if (synchFolderRemotePath
!= null
&&
944 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
945 OCFileListFragment fileListFragment
= getListOfFilesFragment();
946 if (fileListFragment
!= null
) {
947 fileListFragment
.listDirectory();
948 // TODO Enable when "On Device" is recovered ?
949 // fileListFragment.listDirectory(currentDir,
950 // MainApp.getOnlyOnDevice());
953 setFile(currentFile
);
956 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
957 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
960 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
961 equals(event
) &&/// TODO refactor and make common
963 synchResult
!= null
&& !synchResult
.isSuccess() &&
964 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
965 synchResult
.isIdPRedirection() ||
966 (synchResult
.isException() && synchResult
.getException()
967 instanceof AuthenticatorException
))) {
971 OwnCloudClient client
;
972 OwnCloudAccount ocAccount
=
973 new OwnCloudAccount(getAccount(), context
);
974 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
975 removeClientFor(ocAccount
));
976 if (client
!= null
) {
977 OwnCloudCredentials cred
= client
.getCredentials();
979 AccountManager am
= AccountManager
.get(context
);
980 if (cred
.authTokenExpires()) {
981 am
.invalidateAuthToken(
986 am
.clearPassword(getAccount());
990 requestCredentialsUpdate();
992 } catch (AccountNotFoundException e
) {
993 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
998 removeStickyBroadcast(intent
);
999 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1000 mProgressBar
.setIndeterminate(mSyncInProgress
);
1001 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1002 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1003 /*|| mRefreshSharesInProgress*/ //);
1005 setBackgroundText();
1009 if (synchResult
!= null
) {
1010 if (synchResult
.getCode().equals(
1011 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1012 mLastSslUntrustedServerResult
= synchResult
;
1015 } catch (RuntimeException e
) {
1016 // avoid app crashes after changing the serial id of RemoteOperationResult
1017 // in owncloud library with broadcast notifications pending to process
1018 removeStickyBroadcast(intent
);
1024 * Show a text message on screen view for notifying user if content is
1025 * loading or folder is empty
1027 private void setBackgroundText() {
1028 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1029 if (ocFileListFragment
!= null
) {
1030 int message
= R
.string
.file_list_loading
;
1031 if (!mSyncInProgress
) {
1032 // In case file list is empty
1033 message
= R
.string
.file_list_empty
;
1035 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1037 Log_OC
.e(TAG
, "OCFileListFragment is null");
1042 * Once the file upload has finished -> update view
1044 private class UploadFinishReceiver
extends BroadcastReceiver
{
1046 * Once the file upload has finished -> update view
1048 * @author David A. Velasco
1049 * {@link BroadcastReceiver} to enable upload feedback in UI
1052 public void onReceive(Context context
, Intent intent
) {
1054 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1055 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1056 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1057 OCFile currentDir
= getCurrentDir();
1058 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1059 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1061 if (sameAccount
&& isDescendant
) {
1062 refreshListOfFilesFragment();
1065 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1067 boolean renamedInUpload
= getFile().getRemotePath().
1068 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1069 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1071 FileFragment details
= getSecondFragment();
1072 boolean detailFragmentIsShown
= (details
!= null
&&
1073 details
instanceof FileDetailFragment
);
1075 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1076 if (uploadWasFine
) {
1077 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1079 if (renamedInUpload
) {
1080 String newName
= (new File(uploadedRemotePath
)).getName();
1081 Toast msg
= Toast
.makeText(
1084 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1089 if (uploadWasFine
|| getFile().fileExists()) {
1090 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1092 cleanSecondFragment();
1095 // Force the preview if the file is an image or text file
1096 if (uploadWasFine
) {
1097 OCFile ocFile
= getFile();
1098 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1099 startImagePreview(getFile());
1100 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1101 startTextPreview(ocFile
);
1102 // TODO what about other kind of previews?
1106 mProgressBar
.setIndeterminate(false
);
1108 if (intent
!= null
) {
1109 removeStickyBroadcast(intent
);
1119 * Class waiting for broadcast events from the {@link FileDownloader} service.
1121 * Updates the UI when a download is started or finished, provided that it is relevant for the
1124 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1126 //int refreshCounter = 0;
1128 public void onReceive(Context context
, Intent intent
) {
1130 boolean sameAccount
= isSameAccount(context
, 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 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1140 refreshListOfFilesFragment();
1142 refreshSecondFragment(
1144 downloadedRemotePath
,
1145 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1149 if (mWaitingToSend
!= null
) {
1151 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1152 if (mWaitingToSend
.isDown()) {
1153 sendDownloadedFile();
1158 if (intent
!= null
) {
1159 removeStickyBroadcast(intent
);
1164 private boolean isDescendant(String downloadedRemotePath
) {
1165 OCFile currentDir
= getCurrentDir();
1167 currentDir
!= null
&&
1168 downloadedRemotePath
!= null
&&
1169 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1173 private boolean isAscendant(String linkedToRemotePath
) {
1174 OCFile currentDir
= getCurrentDir();
1176 currentDir
!= null
&&
1177 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1181 private boolean isSameAccount(Context context
, Intent intent
) {
1182 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1183 return (accountName
!= null
&& getAccount() != null
&&
1184 accountName
.equals(getAccount().name
));
1189 public void browseToRoot() {
1190 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1191 if (listOfFiles
!= null
) { // should never be null, indeed
1192 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1193 listOfFiles
.listDirectory(root
);
1194 // TODO Enable when "On Device" is recovered ?
1195 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1196 setFile(listOfFiles
.getCurrentFile());
1197 startSyncFolderOperation(root
, false
);
1199 cleanSecondFragment();
1206 * Updates action bar and second fragment, if in dual pane mode.
1209 public void onBrowsedDownTo(OCFile directory
) {
1211 cleanSecondFragment();
1213 startSyncFolderOperation(directory
, false
);
1217 * Shows the information of the {@link OCFile} received as a
1218 * parameter in the second fragment.
1220 * @param file {@link OCFile} whose details will be shown
1223 public void showDetails(OCFile file
) {
1224 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1225 setSecondFragment(detailFragment
);
1226 updateFragmentsVisibility(true
);
1227 updateActionBarTitleAndHomeButton(file
);
1232 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1234 // in dual pane mode, keep the focus of title an action bar in the current folder
1235 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1238 super.updateActionBarTitleAndHomeButton(chosenFile
);
1244 protected ServiceConnection
newTransferenceServiceConnection() {
1245 return new ListServiceConnection();
1249 * Defines callbacks for service binding, passed to bindService()
1251 private class ListServiceConnection
implements ServiceConnection
{
1254 public void onServiceConnected(ComponentName component
, IBinder service
) {
1255 if (component
.equals(new ComponentName(
1256 FileDisplayActivity
.this, FileDownloader
.class))) {
1257 Log_OC
.d(TAG
, "Download service connected");
1258 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1259 if (mWaitingToPreview
!= null
)
1260 if (getStorageManager() != null
) {
1263 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1264 if (!mWaitingToPreview
.isDown()) {
1265 requestForDownload();
1269 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1270 FileUploader
.class))) {
1271 Log_OC
.d(TAG
, "Upload service connected");
1272 mUploaderBinder
= (FileUploaderBinder
) service
;
1276 // a new chance to get the mDownloadBinder through
1277 // getFileDownloadBinder() - THIS IS A MESS
1278 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1279 if (listOfFiles
!= null
) {
1280 listOfFiles
.listDirectory();
1281 // TODO Enable when "On Device" is recovered ?
1282 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1284 FileFragment secondFragment
= getSecondFragment();
1285 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1286 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1287 detailFragment
.listenForTransferProgress();
1288 detailFragment
.updateFileDetails(false
, false
);
1293 public void onServiceDisconnected(ComponentName component
) {
1294 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1295 FileDownloader
.class))) {
1296 Log_OC
.d(TAG
, "Download service disconnected");
1297 mDownloaderBinder
= null
;
1298 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1299 FileUploader
.class))) {
1300 Log_OC
.d(TAG
, "Upload service disconnected");
1301 mUploaderBinder
= null
;
1307 public void onSavedCertificate() {
1308 startSyncFolderOperation(getCurrentDir(), false
);
1313 public void onFailedSavingCertificate() {
1314 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1315 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1317 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1321 public void onCancelCertificate() {
1326 * Updates the view associated to the activity after the finish of some operation over files
1327 * in the current account.
1329 * @param operation Removal operation performed.
1330 * @param result Result of the removal.
1333 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1334 super.onRemoteOperationFinish(operation
, result
);
1336 if (operation
instanceof RemoveFileOperation
) {
1337 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1339 } else if (operation
instanceof RenameFileOperation
) {
1340 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1342 } else if (operation
instanceof SynchronizeFileOperation
) {
1343 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1345 } else if (operation
instanceof CreateFolderOperation
) {
1346 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1348 } else if (operation
instanceof CreateShareOperation
) {
1349 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1351 } else if (operation
instanceof UnshareLinkOperation
) {
1352 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1354 } else if (operation
instanceof MoveFileOperation
) {
1355 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1357 } else if (operation
instanceof CopyFileOperation
) {
1358 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1362 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1363 RemoteOperationResult result
) {
1364 if (result
.isSuccess()) {
1365 refreshShowDetails();
1366 refreshListOfFilesFragment();
1370 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1371 RemoteOperationResult result
) {
1372 if (result
.isSuccess()) {
1373 refreshShowDetails();
1374 refreshListOfFilesFragment();
1376 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1377 cleanSecondFragment();
1378 refreshListOfFilesFragment();
1382 private void refreshShowDetails() {
1383 FileFragment details
= getSecondFragment();
1384 if (details
!= null
) {
1385 OCFile file
= details
.getFile();
1387 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1388 if (details
instanceof PreviewMediaFragment
) {
1389 // Refresh OCFile of the fragment
1390 ((PreviewMediaFragment
) details
).updateFile(file
);
1391 } else if (details
instanceof PreviewTextFragment
) {
1392 // Refresh OCFile of the fragment
1393 ((PreviewTextFragment
) details
).updateFile(file
);
1398 invalidateOptionsMenu();
1403 * Updates the view associated to the activity after the finish of an operation trying to
1406 * @param operation Removal operation performed.
1407 * @param result Result of the removal.
1409 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1410 RemoteOperationResult result
) {
1411 dismissLoadingDialog();
1413 Toast msg
= Toast
.makeText(this,
1414 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1418 if (result
.isSuccess()) {
1419 OCFile removedFile
= operation
.getFile();
1420 FileFragment second
= getSecondFragment();
1421 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1422 if (second
instanceof PreviewMediaFragment
) {
1423 ((PreviewMediaFragment
) second
).stopPreview(true
);
1425 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1426 cleanSecondFragment();
1428 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1429 refreshListOfFilesFragment();
1431 invalidateOptionsMenu();
1433 if (result
.isSslRecoverableException()) {
1434 mLastSslUntrustedServerResult
= result
;
1435 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1442 * Updates the view associated to the activity after the finish of an operation trying to move a
1445 * @param operation Move operation performed.
1446 * @param result Result of the move operation.
1448 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1449 RemoteOperationResult result
) {
1450 if (result
.isSuccess()) {
1451 dismissLoadingDialog();
1452 refreshListOfFilesFragment();
1454 dismissLoadingDialog();
1456 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1457 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1461 } catch (NotFoundException e
) {
1462 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1468 * Updates the view associated to the activity after the finish of an operation trying to copy a
1471 * @param operation Copy operation performed.
1472 * @param result Result of the copy operation.
1474 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1475 if (result
.isSuccess()) {
1476 dismissLoadingDialog();
1477 refreshListOfFilesFragment();
1479 dismissLoadingDialog();
1481 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1482 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1486 } catch (NotFoundException e
) {
1487 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1493 * Updates the view associated to the activity after the finish of an operation trying to rename
1496 * @param operation Renaming operation performed.
1497 * @param result Result of the renaming.
1499 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1500 RemoteOperationResult result
) {
1501 dismissLoadingDialog();
1502 OCFile renamedFile
= operation
.getFile();
1503 if (result
.isSuccess()) {
1504 FileFragment details
= getSecondFragment();
1505 if (details
!= null
) {
1506 if (details
instanceof FileDetailFragment
&&
1507 renamedFile
.equals(details
.getFile()) ) {
1508 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1509 showDetails(renamedFile
);
1511 } else if (details
instanceof PreviewMediaFragment
&&
1512 renamedFile
.equals(details
.getFile())) {
1513 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1514 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1515 int position
= ((PreviewMediaFragment
) details
).getPosition();
1516 startMediaPreview(renamedFile
, position
, true
);
1518 getFileOperationsHelper().openFile(renamedFile
);
1520 } else if (details
instanceof PreviewTextFragment
&&
1521 renamedFile
.equals(details
.getFile())) {
1522 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1523 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1524 startTextPreview(renamedFile
);
1526 getFileOperationsHelper().openFile(renamedFile
);
1531 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1532 refreshListOfFilesFragment();
1536 Toast msg
= Toast
.makeText(this,
1537 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1541 if (result
.isSslRecoverableException()) {
1542 mLastSslUntrustedServerResult
= result
;
1543 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1548 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1549 RemoteOperationResult result
) {
1550 if (result
.isSuccess()) {
1551 if (operation
.transferWasRequested()) {
1552 OCFile syncedFile
= operation
.getLocalFile();
1553 onTransferStateChanged(syncedFile
, true
, true
);
1554 invalidateOptionsMenu();
1560 * Updates the view associated to the activity after the finish of an operation trying create a
1563 * @param operation Creation operation performed.
1564 * @param result Result of the creation.
1566 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1567 RemoteOperationResult result
) {
1568 if (result
.isSuccess()) {
1569 dismissLoadingDialog();
1570 refreshListOfFilesFragment();
1572 dismissLoadingDialog();
1574 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1575 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1579 } catch (NotFoundException e
) {
1580 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1590 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1591 refreshListOfFilesFragment();
1592 FileFragment details
= getSecondFragment();
1593 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1594 file
.equals(details
.getFile()) ) {
1595 if (downloading
|| uploading
) {
1596 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1598 if (!file
.fileExists()) {
1599 cleanSecondFragment();
1601 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1609 private void requestForDownload() {
1610 Account account
= getAccount();
1611 //if (!mWaitingToPreview.isDownloading()) {
1612 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1613 Intent i
= new Intent(this, FileDownloader
.class);
1614 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1615 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1621 private OCFile
getCurrentDir() {
1622 OCFile file
= getFile();
1624 if (file
.isFolder()) {
1626 } else if (getStorageManager() != null
) {
1627 String parentPath
= file
.getRemotePath().substring(0,
1628 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1629 return getStorageManager().getFileByPath(parentPath
);
1635 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1636 long currentSyncTime
= System
.currentTimeMillis();
1638 mSyncInProgress
= true
;
1640 // perform folder synchronization
1641 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1644 getFileOperationsHelper().isSharedSupported(),
1646 getStorageManager(),
1648 getApplicationContext()
1650 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1652 mProgressBar
.setIndeterminate(true
);
1654 setBackgroundText();
1658 * Show untrusted cert dialog
1660 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1661 // Show a dialog with the certificate info
1662 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1663 (CertificateCombinedException
) result
.getException());
1664 FragmentManager fm
= getSupportFragmentManager();
1665 FragmentTransaction ft
= fm
.beginTransaction();
1666 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1669 private void requestForDownload(OCFile file
) {
1670 Account account
= getAccount();
1671 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1672 Intent i
= new Intent(this, FileDownloader
.class);
1673 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1674 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1679 private void sendDownloadedFile() {
1680 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1681 mWaitingToSend
= null
;
1686 * Requests the download of the received {@link OCFile} , updates the UI
1687 * to monitor the download progress and prepares the activity to send the file
1688 * when the download finishes.
1690 * @param file {@link OCFile} to download and preview.
1692 public void startDownloadForSending(OCFile file
) {
1693 mWaitingToSend
= file
;
1694 requestForDownload(mWaitingToSend
);
1695 boolean hasSecondFragment
= (getSecondFragment() != null
);
1696 updateFragmentsVisibility(hasSecondFragment
);
1700 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1702 * @param file Image {@link OCFile} to show.
1704 public void startImagePreview(OCFile file
) {
1705 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1706 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1707 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1708 startActivity(showDetailsIntent
);
1712 * Stars the preview of an already down media {@link OCFile}.
1714 * @param file Media {@link OCFile} to preview.
1715 * @param startPlaybackPosition Media position where the playback will be started,
1717 * @param autoplay When 'true', the playback will start without user
1720 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1721 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1723 setSecondFragment(mediaFragment
);
1724 updateFragmentsVisibility(true
);
1725 updateActionBarTitleAndHomeButton(file
);
1730 * Stars the preview of a text file {@link OCFile}.
1732 * @param file Text {@link OCFile} to preview.
1734 public void startTextPreview(OCFile file
) {
1735 Bundle args
= new Bundle();
1736 args
.putParcelable(EXTRA_FILE
, file
);
1737 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1738 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1739 PreviewTextFragment
.class.getName(), args
);
1740 setSecondFragment(textPreviewFragment
);
1741 updateFragmentsVisibility(true
);
1742 //updateNavigationElementsInActionBar(file);
1747 * Requests the download of the received {@link OCFile} , updates the UI
1748 * to monitor the download progress and prepares the activity to preview
1749 * or open the file when the download finishes.
1751 * @param file {@link OCFile} to download and preview.
1753 public void startDownloadForPreview(OCFile file
) {
1754 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1755 setSecondFragment(detailFragment
);
1756 mWaitingToPreview
= file
;
1757 requestForDownload();
1758 updateFragmentsVisibility(true
);
1759 updateActionBarTitleAndHomeButton(file
);
1764 public void cancelTransference(OCFile file
) {
1765 getFileOperationsHelper().cancelTransference(file
);
1766 if (mWaitingToPreview
!= null
&&
1767 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1768 mWaitingToPreview
= null
;
1770 if (mWaitingToSend
!= null
&&
1771 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1772 mWaitingToSend
= null
;
1774 onTransferStateChanged(file
, false
, false
);
1778 public void onRefresh(boolean ignoreETag
) {
1779 refreshList(ignoreETag
);
1783 public void onRefresh() {
1787 private void refreshList(boolean ignoreETag
) {
1788 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1789 if (listOfFiles
!= null
) {
1790 OCFile folder
= listOfFiles
.getCurrentFile();
1791 if (folder
!= null
) {
1792 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1793 listDirectory(mFile);*/
1794 startSyncFolderOperation(folder
, ignoreETag
);
1799 private void sortByDate(boolean ascending
) {
1800 getListOfFilesFragment().sortByDate(ascending
);
1803 private void sortBySize(boolean ascending
) {
1804 getListOfFilesFragment().sortBySize(ascending
);
1807 private void sortByName(boolean ascending
) {
1808 getListOfFilesFragment().sortByName(ascending
);
1811 public void allFilesOption() {