2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.content
.BroadcastReceiver
;
30 import android
.content
.ComponentName
;
31 import android
.content
.ContentResolver
;
32 import android
.content
.Context
;
33 import android
.content
.DialogInterface
;
34 import android
.content
.Intent
;
35 import android
.content
.IntentFilter
;
36 import android
.content
.ServiceConnection
;
37 import android
.content
.SharedPreferences
;
38 import android
.content
.SyncRequest
;
39 import android
.content
.res
.Resources
.NotFoundException
;
40 import android
.database
.Cursor
;
41 import android
.net
.Uri
;
42 import android
.os
.Build
;
43 import android
.os
.Bundle
;
44 import android
.os
.IBinder
;
45 import android
.preference
.PreferenceManager
;
46 import android
.provider
.OpenableColumns
;
47 import android
.support
.v4
.app
.Fragment
;
48 import android
.support
.v4
.app
.FragmentManager
;
49 import android
.support
.v4
.app
.FragmentTransaction
;
50 import android
.support
.v4
.content
.ContextCompat
;
51 import android
.support
.v4
.view
.GravityCompat
;
52 import android
.support
.v7
.app
.AlertDialog
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.MoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
88 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
89 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
94 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
97 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import com
.owncloud
.android
.utils
.FileStorageUtils
;
105 import com
.owncloud
.android
.utils
.UriUtils
;
110 * Displays, what files the user has available in his ownCloud.
113 public class FileDisplayActivity
extends HookActivity
114 implements FileFragment
.ContainerActivity
,
115 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
117 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
118 private UploadFinishReceiver mUploadFinishReceiver
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
122 private boolean mDualPane
;
123 private View mLeftFragmentContainer
;
124 private View mRightFragmentContainer
;
125 private ProgressBar mProgressBar
;
127 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
128 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
129 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
131 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
133 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
134 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
135 public static final int ACTION_MOVE_FILES
= 3;
136 public static final int ACTION_COPY_FILES
= 4;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
148 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
149 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
150 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
152 private OCFile mWaitingToSend
;
156 protected void onCreate(Bundle savedInstanceState
) {
157 Log_OC
.v(TAG
, "onCreate() start");
159 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
162 /// grant that FileObserverService is watching favorite files
163 if (savedInstanceState
== null
) {
164 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
165 startService(initObserversIntent
);
168 /// Load of saved instance state
169 if(savedInstanceState
!= null
) {
170 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
171 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
172 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
173 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
176 mWaitingToPreview
= null
;
177 mSyncInProgress
= false
;
178 mWaitingToSend
= null
;
183 // Inflate and set the layout view
184 setContentView(R
.layout
.files
);
189 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
190 mProgressBar
.setIndeterminateDrawable(
191 ContextCompat
.getDrawable(this,
192 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
194 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
195 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
196 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
197 if (savedInstanceState
== null
) {
198 createMinFragments();
202 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
203 // according to the official
206 // enable ActionBar app icon to behave as action to toggle nav drawer
207 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
208 getSupportActionBar().setHomeButtonEnabled(true
);
210 mProgressBar
.setIndeterminate(mSyncInProgress
);
211 // always AFTER setContentView(...) ; to work around bug in its implementation
215 Log_OC
.v(TAG
, "onCreate() end");
219 protected void onStart() {
220 Log_OC
.v(TAG
, "onStart() start");
222 Log_OC
.v(TAG
, "onStart() end");
226 protected void onStop() {
227 Log_OC
.v(TAG
, "onStop() start");
229 Log_OC
.v(TAG
, "onStop() end");
233 protected void onDestroy() {
234 Log_OC
.v(TAG
, "onDestroy() start");
236 Log_OC
.v(TAG
, "onDestroy() end");
240 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
243 protected void onAccountSet(boolean stateWasRecovered
) {
244 super.onAccountSet(stateWasRecovered
);
245 if (getAccount() != null
) {
246 /// Check whether the 'main' OCFile handled by the Activity is contained in the
248 OCFile file
= getFile();
249 // get parent from path
250 String parentPath
= "";
252 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
253 // upload in progress - right now, files are not inserted in the local
254 // cache until the upload is successful get parent from path
255 parentPath
= file
.getRemotePath().substring(0,
256 file
.getRemotePath().lastIndexOf(file
.getFileName()));
257 if (getStorageManager().getFileByPath(parentPath
) == null
)
258 file
= null
; // not able to know the directory where the file is uploading
260 file
= getStorageManager().getFileByPath(file
.getRemotePath());
261 // currentDir = null if not in the current Account
265 // fall back to root folder
266 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
270 if (mAccountWasSet
) {
271 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_OPERATIONS_LATER
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_OPERATIONS_LATER
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
);
770 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
771 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
775 * Request the operation for copying the file/folder from one path to another
777 * @param data Intent received
778 * @param resultCode Result code received
780 private void requestCopyOperation(Intent data
, int resultCode
) {
781 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
782 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
783 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
787 public void onBackPressed() {
788 if (!isDrawerOpen()){
789 OCFileListFragment listOfFiles
= getListOfFilesFragment();
790 if (mDualPane
|| getSecondFragment() == null
) {
791 OCFile currentDir
= getCurrentDir();
792 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
796 if (listOfFiles
!= null
) { // should never be null, indeed
797 listOfFiles
.onBrowseUp();
800 if (listOfFiles
!= null
) { // should never be null, indeed
801 setFile(listOfFiles
.getCurrentFile());
803 cleanSecondFragment();
805 super.onBackPressed();
810 protected void onSaveInstanceState(Bundle outState
) {
811 // responsibility of restore is preferred in onCreate() before than in
812 // onRestoreInstanceState when there are Fragments involved
813 Log_OC
.v(TAG
, "onSaveInstanceState() start");
814 super.onSaveInstanceState(outState
);
815 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
816 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
817 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
818 // mRefreshSharesInProgress);
819 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
821 Log_OC
.v(TAG
, "onSaveInstanceState() end");
826 protected void onResume() {
827 Log_OC
.v(TAG
, "onResume() start");
829 // refresh Navigation Drawer account list
830 mNavigationDrawerAdapter
.updateAccountList();
832 // refresh list of files
833 refreshListOfFilesFragment();
835 // Listen for sync messages
836 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
837 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
838 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
839 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
840 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
841 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
842 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
843 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
844 // syncIntentFilter);
846 // Listen for upload messages
847 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
848 mUploadFinishReceiver
= new UploadFinishReceiver();
849 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
851 // Listen for download messages
852 IntentFilter downloadIntentFilter
= new IntentFilter(
853 FileDownloader
.getDownloadAddedMessage());
854 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
855 mDownloadFinishReceiver
= new DownloadFinishReceiver();
856 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
858 Log_OC
.v(TAG
, "onResume() end");
864 protected void onPause() {
865 Log_OC
.v(TAG
, "onPause() start");
866 if (mSyncBroadcastReceiver
!= null
) {
867 unregisterReceiver(mSyncBroadcastReceiver
);
868 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
869 mSyncBroadcastReceiver
= null
;
871 if (mUploadFinishReceiver
!= null
) {
872 unregisterReceiver(mUploadFinishReceiver
);
873 mUploadFinishReceiver
= null
;
875 if (mDownloadFinishReceiver
!= null
) {
876 unregisterReceiver(mDownloadFinishReceiver
);
877 mDownloadFinishReceiver
= null
;
881 Log_OC
.v(TAG
, "onPause() end");
885 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
888 * {@link BroadcastReceiver} to enable syncing feedback in UI
891 public void onReceive(Context context
, Intent intent
) {
893 String event
= intent
.getAction();
894 Log_OC
.d(TAG
, "Received broadcast " + event
);
895 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
896 String synchFolderRemotePath
=
897 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
898 RemoteOperationResult synchResult
=
899 (RemoteOperationResult
)intent
.getSerializableExtra(
900 FileSyncAdapter
.EXTRA_RESULT
);
901 boolean sameAccount
= (getAccount() != null
&&
902 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
906 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
907 mSyncInProgress
= true
;
910 OCFile currentFile
= (getFile() == null
) ? null
:
911 getStorageManager().getFileByPath(getFile().getRemotePath());
912 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
913 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
915 if (currentDir
== null
) {
916 // current folder was removed from the server
917 Toast
.makeText( FileDisplayActivity
.this,
920 sync_current_folder_was_removed
),
921 synchFolderRemotePath
),
928 if (currentFile
== null
&& !getFile().isFolder()) {
929 // currently selected file was removed in the server, and now we
931 cleanSecondFragment();
932 currentFile
= currentDir
;
935 if (synchFolderRemotePath
!= null
&&
936 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
937 OCFileListFragment fileListFragment
= getListOfFilesFragment();
938 if (fileListFragment
!= null
) {
939 fileListFragment
.listDirectory();
940 // TODO Enable when "On Device" is recovered ?
941 // fileListFragment.listDirectory(currentDir,
942 // MainApp.getOnlyOnDevice());
945 setFile(currentFile
);
948 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
949 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
952 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
953 equals(event
) &&/// TODO refactor and make common
955 synchResult
!= null
&& !synchResult
.isSuccess() &&
956 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
957 synchResult
.isIdPRedirection() ||
958 (synchResult
.isException() && synchResult
.getException()
959 instanceof AuthenticatorException
))) {
963 OwnCloudClient client
;
964 OwnCloudAccount ocAccount
=
965 new OwnCloudAccount(getAccount(), context
);
966 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
967 removeClientFor(ocAccount
));
968 if (client
!= null
) {
969 OwnCloudCredentials cred
= client
.getCredentials();
971 AccountManager am
= AccountManager
.get(context
);
972 if (cred
.authTokenExpires()) {
973 am
.invalidateAuthToken(
978 am
.clearPassword(getAccount());
982 requestCredentialsUpdate();
984 } catch (AccountNotFoundException e
) {
985 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
991 removeStickyBroadcast(intent
);
992 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
993 mProgressBar
.setIndeterminate(mSyncInProgress
);
994 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
995 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
996 /*|| mRefreshSharesInProgress*/ //);
1002 if (synchResult
!= null
) {
1003 if (synchResult
.getCode().equals(
1004 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1005 mLastSslUntrustedServerResult
= synchResult
;
1008 } catch (RuntimeException e
) {
1009 // avoid app crashes after changing the serial id of RemoteOperationResult
1010 // in owncloud library with broadcast notifications pending to process
1011 removeStickyBroadcast(intent
);
1017 * Show a text message on screen view for notifying user if content is
1018 * loading or folder is empty
1020 private void setBackgroundText() {
1021 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1022 if (ocFileListFragment
!= null
) {
1023 int message
= R
.string
.file_list_loading
;
1024 if (!mSyncInProgress
) {
1025 // In case file list is empty
1026 message
= R
.string
.file_list_empty
;
1028 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1030 Log_OC
.e(TAG
, "OCFileListFragment is null");
1035 * Once the file upload has finished -> update view
1037 private class UploadFinishReceiver
extends BroadcastReceiver
{
1039 * Once the file upload has finished -> update view
1041 * @author David A. Velasco
1042 * {@link BroadcastReceiver} to enable upload feedback in UI
1045 public void onReceive(Context context
, Intent intent
) {
1047 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1048 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1049 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1050 OCFile currentDir
= getCurrentDir();
1051 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1052 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1054 if (sameAccount
&& isDescendant
) {
1055 String linkedToRemotePath
=
1056 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1057 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1058 refreshListOfFilesFragment();
1062 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1064 boolean renamedInUpload
= getFile().getRemotePath().
1065 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1066 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1068 FileFragment details
= getSecondFragment();
1069 boolean detailFragmentIsShown
= (details
!= null
&&
1070 details
instanceof FileDetailFragment
);
1072 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1073 if (uploadWasFine
) {
1074 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1076 if (renamedInUpload
) {
1077 String newName
= (new File(uploadedRemotePath
)).getName();
1078 Toast msg
= Toast
.makeText(
1081 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1086 if (uploadWasFine
|| getFile().fileExists()) {
1087 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1089 cleanSecondFragment();
1092 // Force the preview if the file is an image or text file
1093 if (uploadWasFine
) {
1094 OCFile ocFile
= getFile();
1095 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1096 startImagePreview(getFile());
1097 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1098 startTextPreview(ocFile
);
1099 // TODO what about other kind of previews?
1103 mProgressBar
.setIndeterminate(false
);
1105 if (intent
!= null
) {
1106 removeStickyBroadcast(intent
);
1112 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1113 private boolean isAscendant(String linkedToRemotePath
) {
1114 OCFile currentDir
= getCurrentDir();
1116 currentDir
!= null
&&
1117 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1126 * Class waiting for broadcast events from the {@link FileDownloader} service.
1128 * Updates the UI when a download is started or finished, provided that it is relevant for the
1131 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1134 public void onReceive(Context context
, Intent intent
) {
1136 boolean sameAccount
= isSameAccount(intent
);
1137 String downloadedRemotePath
=
1138 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1139 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1141 if (sameAccount
&& isDescendant
) {
1142 String linkedToRemotePath
=
1143 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1144 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1145 refreshListOfFilesFragment();
1147 refreshSecondFragment(
1149 downloadedRemotePath
,
1150 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1154 if (mWaitingToSend
!= null
) {
1156 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1157 if (mWaitingToSend
.isDown()) {
1158 sendDownloadedFile();
1163 if (intent
!= null
) {
1164 removeStickyBroadcast(intent
);
1169 private boolean isDescendant(String downloadedRemotePath
) {
1170 OCFile currentDir
= getCurrentDir();
1172 currentDir
!= null
&&
1173 downloadedRemotePath
!= null
&&
1174 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1178 private boolean isAscendant(String linkedToRemotePath
) {
1179 OCFile currentDir
= getCurrentDir();
1181 currentDir
!= null
&&
1182 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1186 private boolean isSameAccount(Intent intent
) {
1187 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1188 return (accountName
!= null
&& getAccount() != null
&&
1189 accountName
.equals(getAccount().name
));
1194 public void browseToRoot() {
1195 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1196 if (listOfFiles
!= null
) { // should never be null, indeed
1197 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1198 listOfFiles
.listDirectory(root
);
1199 // TODO Enable when "On Device" is recovered ?
1200 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1201 setFile(listOfFiles
.getCurrentFile());
1202 startSyncFolderOperation(root
, false
);
1204 cleanSecondFragment();
1211 * Updates action bar and second fragment, if in dual pane mode.
1214 public void onBrowsedDownTo(OCFile directory
) {
1216 cleanSecondFragment();
1218 startSyncFolderOperation(directory
, false
);
1222 * Shows the information of the {@link OCFile} received as a
1223 * parameter in the second fragment.
1225 * @param file {@link OCFile} whose details will be shown
1228 public void showDetails(OCFile file
) {
1229 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1230 setSecondFragment(detailFragment
);
1231 updateFragmentsVisibility(true
);
1232 updateActionBarTitleAndHomeButton(file
);
1237 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1239 // in dual pane mode, keep the focus of title an action bar in the current folder
1240 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1243 super.updateActionBarTitleAndHomeButton(chosenFile
);
1249 protected ServiceConnection
newTransferenceServiceConnection() {
1250 return new ListServiceConnection();
1254 * Defines callbacks for service binding, passed to bindService()
1256 private class ListServiceConnection
implements ServiceConnection
{
1259 public void onServiceConnected(ComponentName component
, IBinder service
) {
1260 if (component
.equals(new ComponentName(
1261 FileDisplayActivity
.this, FileDownloader
.class))) {
1262 Log_OC
.d(TAG
, "Download service connected");
1263 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1264 if (mWaitingToPreview
!= null
)
1265 if (getStorageManager() != null
) {
1268 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1269 if (!mWaitingToPreview
.isDown()) {
1270 requestForDownload();
1274 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1275 FileUploader
.class))) {
1276 Log_OC
.d(TAG
, "Upload service connected");
1277 mUploaderBinder
= (FileUploaderBinder
) service
;
1281 // a new chance to get the mDownloadBinder through
1282 // getFileDownloadBinder() - THIS IS A MESS
1283 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1284 if (listOfFiles
!= null
) {
1285 listOfFiles
.listDirectory();
1286 // TODO Enable when "On Device" is recovered ?
1287 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1289 FileFragment secondFragment
= getSecondFragment();
1290 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1291 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1292 detailFragment
.listenForTransferProgress();
1293 detailFragment
.updateFileDetails(false
, false
);
1298 public void onServiceDisconnected(ComponentName component
) {
1299 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1300 FileDownloader
.class))) {
1301 Log_OC
.d(TAG
, "Download service disconnected");
1302 mDownloaderBinder
= null
;
1303 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1304 FileUploader
.class))) {
1305 Log_OC
.d(TAG
, "Upload service disconnected");
1306 mUploaderBinder
= null
;
1312 public void onSavedCertificate() {
1313 startSyncFolderOperation(getCurrentDir(), false
);
1318 public void onFailedSavingCertificate() {
1319 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1320 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1322 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1326 public void onCancelCertificate() {
1331 * Updates the view associated to the activity after the finish of some operation over files
1332 * in the current account.
1334 * @param operation Removal operation performed.
1335 * @param result Result of the removal.
1338 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1339 super.onRemoteOperationFinish(operation
, result
);
1341 if (operation
instanceof RemoveFileOperation
) {
1342 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1344 } else if (operation
instanceof RenameFileOperation
) {
1345 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1347 } else if (operation
instanceof SynchronizeFileOperation
) {
1348 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1350 } else if (operation
instanceof CreateFolderOperation
) {
1351 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1353 } else if (operation
instanceof MoveFileOperation
) {
1354 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1356 } else if (operation
instanceof CopyFileOperation
) {
1357 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1362 private void refreshShowDetails() {
1363 FileFragment details
= getSecondFragment();
1364 if (details
!= null
) {
1365 OCFile file
= details
.getFile();
1367 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1368 if (details
instanceof PreviewMediaFragment
) {
1369 // Refresh OCFile of the fragment
1370 ((PreviewMediaFragment
) details
).updateFile(file
);
1371 } else if (details
instanceof PreviewTextFragment
) {
1372 // Refresh OCFile of the fragment
1373 ((PreviewTextFragment
) details
).updateFile(file
);
1378 invalidateOptionsMenu();
1383 * Updates the view associated to the activity after the finish of an operation trying to
1386 * @param operation Removal operation performed.
1387 * @param result Result of the removal.
1389 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1390 RemoteOperationResult result
) {
1391 Toast msg
= Toast
.makeText(this,
1392 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1396 if (result
.isSuccess()) {
1397 OCFile removedFile
= operation
.getFile();
1398 FileFragment second
= getSecondFragment();
1399 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1400 if (second
instanceof PreviewMediaFragment
) {
1401 ((PreviewMediaFragment
) second
).stopPreview(true
);
1403 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1404 cleanSecondFragment();
1406 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1407 refreshListOfFilesFragment();
1409 invalidateOptionsMenu();
1411 if (result
.isSslRecoverableException()) {
1412 mLastSslUntrustedServerResult
= result
;
1413 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1420 * Updates the view associated to the activity after the finish of an operation trying to move a
1423 * @param operation Move operation performed.
1424 * @param result Result of the move operation.
1426 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1427 RemoteOperationResult result
) {
1428 if (result
.isSuccess()) {
1429 refreshListOfFilesFragment();
1432 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1433 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1437 } catch (NotFoundException e
) {
1438 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1444 * Updates the view associated to the activity after the finish of an operation trying to copy a
1447 * @param operation Copy operation performed.
1448 * @param result Result of the copy operation.
1450 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 refreshListOfFilesFragment();
1455 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1456 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1460 } catch (NotFoundException e
) {
1461 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1467 * Updates the view associated to the activity after the finish of an operation trying to rename
1470 * @param operation Renaming operation performed.
1471 * @param result Result of the renaming.
1473 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1474 RemoteOperationResult result
) {
1475 OCFile renamedFile
= operation
.getFile();
1476 if (result
.isSuccess()) {
1477 FileFragment details
= getSecondFragment();
1478 if (details
!= null
) {
1479 if (details
instanceof FileDetailFragment
&&
1480 renamedFile
.equals(details
.getFile()) ) {
1481 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1482 showDetails(renamedFile
);
1484 } else if (details
instanceof PreviewMediaFragment
&&
1485 renamedFile
.equals(details
.getFile())) {
1486 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1487 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1488 int position
= ((PreviewMediaFragment
) details
).getPosition();
1489 startMediaPreview(renamedFile
, position
, true
);
1491 getFileOperationsHelper().openFile(renamedFile
);
1493 } else if (details
instanceof PreviewTextFragment
&&
1494 renamedFile
.equals(details
.getFile())) {
1495 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1496 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1497 startTextPreview(renamedFile
);
1499 getFileOperationsHelper().openFile(renamedFile
);
1504 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1505 refreshListOfFilesFragment();
1509 Toast msg
= Toast
.makeText(this,
1510 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1514 if (result
.isSslRecoverableException()) {
1515 mLastSslUntrustedServerResult
= result
;
1516 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1521 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1522 RemoteOperationResult result
) {
1523 if (result
.isSuccess()) {
1524 if (operation
.transferWasRequested()) {
1525 OCFile syncedFile
= operation
.getLocalFile();
1526 onTransferStateChanged(syncedFile
, true
, true
);
1527 invalidateOptionsMenu();
1528 refreshShowDetails();
1534 * Updates the view associated to the activity after the finish of an operation trying create a
1537 * @param operation Creation operation performed.
1538 * @param result Result of the creation.
1540 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1541 RemoteOperationResult result
) {
1542 if (result
.isSuccess()) {
1543 refreshListOfFilesFragment();
1546 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1547 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1551 } catch (NotFoundException e
) {
1552 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1562 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1563 refreshListOfFilesFragment();
1564 FileFragment details
= getSecondFragment();
1565 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1566 file
.equals(details
.getFile()) ) {
1567 if (downloading
|| uploading
) {
1568 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1570 if (!file
.fileExists()) {
1571 cleanSecondFragment();
1573 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1581 private void requestForDownload() {
1582 Account account
= getAccount();
1583 //if (!mWaitingToPreview.isDownloading()) {
1584 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1585 Intent i
= new Intent(this, FileDownloader
.class);
1586 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1587 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1593 private OCFile
getCurrentDir() {
1594 OCFile file
= getFile();
1596 if (file
.isFolder()) {
1598 } else if (getStorageManager() != null
) {
1599 String parentPath
= file
.getRemotePath().substring(0,
1600 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1601 return getStorageManager().getFileByPath(parentPath
);
1608 * Starts an operation to refresh the requested folder.
1610 * The operation is run in a new background thread created on the fly.
1612 * The refresh updates is a "light sync": properties of regular files in folder are updated (including
1613 * associated shares), but not their contents. Only the contents of files marked to be kept-in-sync are
1616 * @param folder Folder to refresh.
1617 * @param ignoreETag If 'true', the data from the server will be fetched and sync'ed even if the eTag
1620 public void startSyncFolderOperation(final OCFile folder
, final boolean ignoreETag
) {
1622 // the execution is slightly delayed to allow the activity get the window focus if it's being started
1623 // or if the method is called from a dialog that is being dismissed
1624 getHandler().postDelayed(
1628 if (hasWindowFocus()) {
1629 long currentSyncTime
= System
.currentTimeMillis();
1630 mSyncInProgress
= true
;
1632 // perform folder synchronization
1633 RemoteOperation synchFolderOp
= new RefreshFolderOperation(folder
,
1636 getFileOperationsHelper().isSharedSupported(),
1638 getStorageManager(),
1640 getApplicationContext()
1642 synchFolderOp
.execute(
1644 MainApp
.getAppContext(),
1645 FileDisplayActivity
.this,
1650 mProgressBar
.setIndeterminate(true
);
1652 setBackgroundText();
1654 } // else: NOTHING ; lets' not refresh when the user rotates the device but there is
1655 // another window floating over
1658 DELAY_TO_REQUEST_OPERATIONS_LATER
1664 * Show untrusted cert dialog
1666 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1667 // Show a dialog with the certificate info
1668 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1669 (CertificateCombinedException
) result
.getException());
1670 FragmentManager fm
= getSupportFragmentManager();
1671 FragmentTransaction ft
= fm
.beginTransaction();
1672 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1675 private void requestForDownload(OCFile file
) {
1676 Account account
= getAccount();
1677 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1678 Intent i
= new Intent(this, FileDownloader
.class);
1679 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1680 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1685 private void sendDownloadedFile() {
1686 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1687 mWaitingToSend
= null
;
1692 * Requests the download of the received {@link OCFile} , updates the UI
1693 * to monitor the download progress and prepares the activity to send the file
1694 * when the download finishes.
1696 * @param file {@link OCFile} to download and preview.
1698 public void startDownloadForSending(OCFile file
) {
1699 mWaitingToSend
= file
;
1700 requestForDownload(mWaitingToSend
);
1701 boolean hasSecondFragment
= (getSecondFragment() != null
);
1702 updateFragmentsVisibility(hasSecondFragment
);
1706 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1708 * @param file Image {@link OCFile} to show.
1710 public void startImagePreview(OCFile file
) {
1711 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1712 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1713 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1714 startActivity(showDetailsIntent
);
1718 * Stars the preview of an already down media {@link OCFile}.
1720 * @param file Media {@link OCFile} to preview.
1721 * @param startPlaybackPosition Media position where the playback will be started,
1723 * @param autoplay When 'true', the playback will start without user
1726 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1727 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1729 setSecondFragment(mediaFragment
);
1730 updateFragmentsVisibility(true
);
1731 updateActionBarTitleAndHomeButton(file
);
1736 * Stars the preview of a text file {@link OCFile}.
1738 * @param file Text {@link OCFile} to preview.
1740 public void startTextPreview(OCFile file
) {
1741 Bundle args
= new Bundle();
1742 args
.putParcelable(EXTRA_FILE
, file
);
1743 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1744 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1745 PreviewTextFragment
.class.getName(), args
);
1746 setSecondFragment(textPreviewFragment
);
1747 updateFragmentsVisibility(true
);
1748 //updateNavigationElementsInActionBar(file);
1753 * Requests the download of the received {@link OCFile} , updates the UI
1754 * to monitor the download progress and prepares the activity to preview
1755 * or open the file when the download finishes.
1757 * @param file {@link OCFile} to download and preview.
1759 public void startDownloadForPreview(OCFile file
) {
1760 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1761 setSecondFragment(detailFragment
);
1762 mWaitingToPreview
= file
;
1763 requestForDownload();
1764 updateFragmentsVisibility(true
);
1765 updateActionBarTitleAndHomeButton(file
);
1770 public void cancelTransference(OCFile file
) {
1771 getFileOperationsHelper().cancelTransference(file
);
1772 if (mWaitingToPreview
!= null
&&
1773 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1774 mWaitingToPreview
= null
;
1776 if (mWaitingToSend
!= null
&&
1777 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1778 mWaitingToSend
= null
;
1780 onTransferStateChanged(file
, false
, false
);
1784 public void onRefresh(boolean ignoreETag
) {
1785 refreshList(ignoreETag
);
1789 public void onRefresh() {
1793 private void refreshList(boolean ignoreETag
) {
1794 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1795 if (listOfFiles
!= null
) {
1796 OCFile folder
= listOfFiles
.getCurrentFile();
1797 if (folder
!= null
) {
1798 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1799 listDirectory(mFile);*/
1800 startSyncFolderOperation(folder
, ignoreETag
);
1805 private void sortByDate(boolean ascending
) {
1806 getListOfFilesFragment().sortByDate(ascending
);
1809 private void sortBySize(boolean ascending
) {
1810 getListOfFilesFragment().sortBySize(ascending
);
1813 private void sortByName(boolean ascending
) {
1814 getListOfFilesFragment().sortByName(ascending
);
1817 public void allFilesOption() {