2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.support
.v7
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.content
.ContextCompat
;
52 import android
.support
.v4
.view
.GravityCompat
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.FileStorageUtils
;
107 import com
.owncloud
.android
.utils
.UriUtils
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
116 implements FileFragment
.ContainerActivity
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
129 private ProgressBar mProgressBar
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
140 public static final int ACTION_COPY_FILES
= 4;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
152 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
153 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
154 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
157 private Menu mOptionsMenu
;
161 protected void onCreate(Bundle savedInstanceState
) {
162 Log_OC
.v(TAG
, "onCreate() start");
164 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
167 /// grant that FileObserverService is watching favorite files
168 if (savedInstanceState
== null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
176 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
177 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
179 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 mWaitingToSend
= null
;
188 // Inflate and set the layout view
189 setContentView(R
.layout
.files
);
194 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
195 mProgressBar
.setIndeterminateDrawable(
196 ContextCompat
.getDrawable(this,
197 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
199 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
200 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
201 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
202 if (savedInstanceState
== null
) {
203 createMinFragments();
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
208 // according to the official
211 // enable ActionBar app icon to behave as action to toggle nav drawer
212 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
213 getSupportActionBar().setHomeButtonEnabled(true
);
215 mProgressBar
.setIndeterminate(mSyncInProgress
);
216 // always AFTER setContentView(...) ; to work around bug in its implementation
220 Log_OC
.v(TAG
, "onCreate() end");
224 protected void onStart() {
225 Log_OC
.v(TAG
, "onStart() start");
227 Log_OC
.v(TAG
, "onStart() end");
231 protected void onDestroy() {
232 Log_OC
.v(TAG
, "onDestroy() start");
234 Log_OC
.v(TAG
, "onDestroy() end");
238 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
241 protected void onAccountSet(boolean stateWasRecovered
) {
242 super.onAccountSet(stateWasRecovered
);
243 if (getAccount() != null
) {
244 /// Check whether the 'main' OCFile handled by the Activity is contained in the
246 OCFile file
= getFile();
247 // get parent from path
248 String parentPath
= "";
250 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
251 // upload in progress - right now, files are not inserted in the local
252 // cache until the upload is successful get parent from path
253 parentPath
= file
.getRemotePath().substring(0,
254 file
.getRemotePath().lastIndexOf(file
.getFileName()));
255 if (getStorageManager().getFileByPath(parentPath
) == null
)
256 file
= null
; // not able to know the directory where the file is uploading
258 file
= getStorageManager().getFileByPath(file
.getRemotePath());
259 // currentDir = null if not in the current Account
263 // fall back to root folder
264 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
268 if (mAccountWasSet
) {
269 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
270 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
271 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
272 int lastAtPos
= getAccount().name
.lastIndexOf("@");
273 username
.setText(getAccount().name
.substring(0, lastAtPos
));
277 if (!stateWasRecovered
) {
278 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
279 initFragmentsWithFile();
280 if (file
.isFolder()) {
281 startSyncFolderOperation(file
, false
);
285 updateFragmentsVisibility(!file
.isFolder());
286 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
291 private void createMinFragments() {
292 OCFileListFragment listOfFiles
= new OCFileListFragment();
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
295 transaction
.commit();
298 private void initFragmentsWithFile() {
299 if (getAccount() != null
&& getFile() != null
) {
301 OCFileListFragment listOfFiles
= getListOfFilesFragment();
302 if (listOfFiles
!= null
) {
303 listOfFiles
.listDirectory(getCurrentDir());
304 // TODO Enable when "On Device" is recovered
305 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
308 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
312 OCFile file
= getFile();
313 Fragment secondFragment
= chooseInitialSecondFragment(file
);
314 if (secondFragment
!= null
) {
315 setSecondFragment(secondFragment
);
316 updateFragmentsVisibility(true
);
317 updateActionBarTitleAndHomeButton(file
);
320 cleanSecondFragment();
321 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
322 startTextPreview(file
);
325 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
332 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
333 if (getAccount() == null
) {
334 Log_OC
.wtf(TAG
, "\t account is NULL");
336 if (getFile() == null
) {
337 Log_OC
.wtf(TAG
, "\t file is NULL");
342 private Fragment
chooseInitialSecondFragment(OCFile file
) {
343 Fragment secondFragment
= null
;
344 if (file
!= null
&& !file
.isFolder()) {
345 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
346 && file
.getLastSyncDateForProperties() > 0 // temporal fix
348 int startPlaybackPosition
=
349 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
351 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
352 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
353 startPlaybackPosition
, autoplay
);
355 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
356 secondFragment
= null
;
358 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
361 return secondFragment
;
366 * Replaces the second fragment managed by the activity with the received as
369 * Assumes never will be more than two fragments managed at the same time.
371 * @param fragment New second Fragment to set.
373 private void setSecondFragment(Fragment fragment
) {
374 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
375 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
376 transaction
.commit();
380 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
382 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
383 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
385 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
386 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
389 } else if (existsSecondFragment
) {
390 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
391 mLeftFragmentContainer
.setVisibility(View
.GONE
);
393 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
394 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
398 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
399 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
401 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
402 mRightFragmentContainer
.setVisibility(View
.GONE
);
408 private OCFileListFragment
getListOfFilesFragment() {
409 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
410 FileDisplayActivity
.TAG_LIST_OF_FILES
);
411 if (listOfFiles
!= null
) {
412 return (OCFileListFragment
) listOfFiles
;
414 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
418 public FileFragment
getSecondFragment() {
419 Fragment second
= getSupportFragmentManager().findFragmentByTag(
420 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
421 if (second
!= null
) {
422 return (FileFragment
) second
;
427 protected void cleanSecondFragment() {
428 Fragment second
= getSecondFragment();
429 if (second
!= null
) {
430 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
434 updateFragmentsVisibility(false
);
435 updateActionBarTitleAndHomeButton(null
);
438 protected void refreshListOfFilesFragment() {
439 OCFileListFragment fileListFragment
= getListOfFilesFragment();
440 if (fileListFragment
!= null
) {
441 fileListFragment
.listDirectory();
442 // TODO Enable when "On Device" is recovered ?
443 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
447 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
449 FileFragment secondFragment
= getSecondFragment();
450 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
451 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
452 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
453 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
454 OCFile fileInFragment
= detailsFragment
.getFile();
455 if (fileInFragment
!= null
&&
456 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
457 // the user browsed to other file ; forget the automatic preview
458 mWaitingToPreview
= null
;
460 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
461 // grant that the right panel updates the progress bar
462 detailsFragment
.listenForTransferProgress();
463 detailsFragment
.updateFileDetails(true
, false
);
465 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
466 // update the right panel
467 boolean detailsFragmentChanged
= false
;
470 mWaitingToPreview
= getStorageManager().getFileById(
471 mWaitingToPreview
.getFileId()); // update the file from database,
472 // for the local storage path
473 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
474 startMediaPreview(mWaitingToPreview
, 0, true
);
475 detailsFragmentChanged
= true
;
476 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
477 startTextPreview(mWaitingToPreview
);
478 detailsFragmentChanged
= true
;
480 getFileOperationsHelper().openFile(mWaitingToPreview
);
483 mWaitingToPreview
= null
;
485 if (!detailsFragmentChanged
) {
486 detailsFragment
.updateFileDetails(false
, (success
));
493 public boolean onPrepareOptionsMenu(Menu menu
) {
494 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
495 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
496 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
497 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
498 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
499 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
501 return super.onPrepareOptionsMenu(menu
);
505 public boolean onCreateOptionsMenu(Menu menu
) {
506 MenuInflater inflater
= getMenuInflater();
507 inflater
.inflate(R
.menu
.main_menu
, menu
);
510 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
519 public boolean onOptionsItemSelected(MenuItem item
) {
520 boolean retval
= true
;
521 switch (item
.getItemId()) {
522 case R
.id
.action_create_dir
: {
523 CreateFolderDialogFragment dialog
=
524 CreateFolderDialogFragment
.newInstance(getCurrentDir());
525 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
529 case R
.id
.action_sync_account
: {
530 startSynchronization();
533 case R
.id
.action_upload
: {
534 UploadSourceDialogFragment dialog
=
535 UploadSourceDialogFragment
.newInstance(getAccount());
536 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
539 case android
.R
.id
.home
: {
540 FileFragment second
= getSecondFragment();
541 OCFile currentDir
= getCurrentDir();
542 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
543 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
544 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
545 (second
!= null
&& second
.getFile() != null
)) {
549 mDrawerLayout
.openDrawer(GravityCompat
.START
);
553 case R
.id
.action_sort
: {
554 SharedPreferences appPreferences
= PreferenceManager
555 .getDefaultSharedPreferences(this);
557 // Read sorting order, default to sort by name ascending
558 Integer sortOrder
= appPreferences
559 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
561 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
562 builder
.setTitle(R
.string
.actionbar_sort_title
)
563 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
564 new DialogInterface
.OnClickListener() {
565 public void onClick(DialogInterface dialog
, int which
) {
578 builder
.create().show();
581 case R
.id
.action_switch_view
:{
583 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
584 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
585 R
.drawable
.ic_view_module
));
586 DisplayUtils
.setViewMode(getFile(), false
);
589 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
590 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
591 R
.drawable
.ic_view_list
));
592 DisplayUtils
.setViewMode(getFile(), true
);
599 retval
= super.onOptionsItemSelected(item
);
604 private void startSynchronization() {
605 Log_OC
.d(TAG
, "Got to start sync");
606 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
607 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
608 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
609 // cancel the current synchronizations of any ownCloud account
610 Bundle bundle
= new Bundle();
611 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
612 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
613 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
614 MainApp
.getAuthority());
615 ContentResolver
.requestSync(
617 MainApp
.getAuthority(), bundle
);
619 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
620 MainApp
.getAuthority() + " with new API");
621 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
622 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
623 builder
.setExpedited(true
);
624 builder
.setManual(true
);
627 // Fix bug in Android Lollipop when you click on refresh the whole account
628 Bundle extras
= new Bundle();
629 builder
.setExtras(extras
);
631 SyncRequest request
= builder
.build();
632 ContentResolver
.requestSync(request
);
637 * Called, when the user selected something for uploading
640 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
642 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
644 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
645 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
646 //getClipData is only supported on api level 16+, Jelly Bean
647 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
648 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
649 Intent intent
= new Intent();
650 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
651 requestSimpleUpload(intent
, resultCode
);
654 requestSimpleUpload(data
, resultCode
);
656 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
657 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
658 requestMultipleUpload(data
, resultCode
);
660 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
661 final Intent fData
= data
;
662 final int fResultCode
= resultCode
;
663 getHandler().postDelayed(
667 requestMoveOperation(fData
, fResultCode
);
670 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
673 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
675 final Intent fData
= data
;
676 final int fResultCode
= resultCode
;
677 getHandler().postDelayed(
681 requestCopyOperation(fData
, fResultCode
);
684 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
688 super.onActivityResult(requestCode
, resultCode
, data
);
693 private void requestMultipleUpload(Intent data
, int resultCode
) {
694 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
695 if (filePaths
!= null
) {
696 String
[] remotePaths
= new String
[filePaths
.length
];
697 String remotePathBase
= getCurrentDir().getRemotePath();
698 for (int j
= 0; j
< remotePaths
.length
; j
++) {
699 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
702 Intent i
= new Intent(this, FileUploader
.class);
703 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
704 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
705 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
706 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
707 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
708 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
712 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
713 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
721 private void requestSimpleUpload(Intent data
, int resultCode
) {
722 String filePath
= null
;
723 String mimeType
= null
;
725 Uri selectedImageUri
= data
.getData();
728 mimeType
= getContentResolver().getType(selectedImageUri
);
730 String fileManagerString
= selectedImageUri
.getPath();
731 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
733 if (selectedImagePath
!= null
)
734 filePath
= selectedImagePath
;
736 filePath
= fileManagerString
;
738 } catch (Exception e
) {
739 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
740 "Intent.ACTION_GET_CONTENT", e
);
743 if (filePath
== null
) {
744 Log_OC
.e(TAG
, "Couldn't resolve path to file");
745 Toast t
= Toast
.makeText(
746 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
754 Intent i
= new Intent(this, FileUploader
.class);
755 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
756 OCFile currentDir
= getCurrentDir();
757 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
759 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
760 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
762 if (cursor
!= null
&& cursor
.moveToFirst()) {
763 String displayName
= cursor
.getString(cursor
.getColumnIndex(
764 OpenableColumns
.DISPLAY_NAME
));
765 Log_OC
.v(TAG
, "Display Name: " + displayName
);
767 displayName
.replace(File
.separatorChar
, '_');
768 displayName
.replace(File
.pathSeparatorChar
, '_');
769 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
772 // and what happens in case of error?; wrong target name for the upload
778 remotePath
+= new File(filePath
).getName();
781 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
782 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
783 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
784 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
785 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
786 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
791 * Request the operation for moving the file/folder from one path to another
793 * @param data Intent received
794 * @param resultCode Result code received
796 private void requestMoveOperation(Intent data
, int resultCode
) {
797 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
798 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
799 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
803 * Request the operation for copying the file/folder from one path to another
805 * @param data Intent received
806 * @param resultCode Result code received
808 private void requestCopyOperation(Intent data
, int resultCode
) {
809 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
810 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
811 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
815 public void onBackPressed() {
816 if (!isDrawerOpen()){
817 OCFileListFragment listOfFiles
= getListOfFilesFragment();
818 if (mDualPane
|| getSecondFragment() == null
) {
819 OCFile currentDir
= getCurrentDir();
820 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
824 if (listOfFiles
!= null
) { // should never be null, indeed
825 listOfFiles
.onBrowseUp();
828 if (listOfFiles
!= null
) { // should never be null, indeed
829 setFile(listOfFiles
.getCurrentFile());
831 cleanSecondFragment();
835 super.onBackPressed();
839 private void changeGridIcon(){
840 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
841 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
842 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
843 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
844 R
.drawable
.ic_view_list
));
846 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
847 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
848 R
.drawable
.ic_view_module
));
853 protected void onSaveInstanceState(Bundle outState
) {
854 // responsibility of restore is preferred in onCreate() before than in
855 // onRestoreInstanceState when there are Fragments involved
856 Log_OC
.v(TAG
, "onSaveInstanceState() start");
857 super.onSaveInstanceState(outState
);
858 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
859 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
860 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
861 // mRefreshSharesInProgress);
862 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
864 Log_OC
.v(TAG
, "onSaveInstanceState() end");
869 protected void onResume() {
870 Log_OC
.v(TAG
, "onResume() start");
872 // refresh Navigation Drawer account list
873 mNavigationDrawerAdapter
.updateAccountList();
875 // refresh list of files
876 refreshListOfFilesFragment();
878 // Listen for sync messages
879 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
880 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
881 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
882 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
883 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
884 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
885 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
886 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
887 // syncIntentFilter);
889 // Listen for upload messages
890 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
891 mUploadFinishReceiver
= new UploadFinishReceiver();
892 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
894 // Listen for download messages
895 IntentFilter downloadIntentFilter
= new IntentFilter(
896 FileDownloader
.getDownloadAddedMessage());
897 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
898 mDownloadFinishReceiver
= new DownloadFinishReceiver();
899 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
901 Log_OC
.v(TAG
, "onResume() end");
907 protected void onPause() {
908 Log_OC
.v(TAG
, "onPause() start");
909 if (mSyncBroadcastReceiver
!= null
) {
910 unregisterReceiver(mSyncBroadcastReceiver
);
911 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
912 mSyncBroadcastReceiver
= null
;
914 if (mUploadFinishReceiver
!= null
) {
915 unregisterReceiver(mUploadFinishReceiver
);
916 mUploadFinishReceiver
= null
;
918 if (mDownloadFinishReceiver
!= null
) {
919 unregisterReceiver(mDownloadFinishReceiver
);
920 mDownloadFinishReceiver
= null
;
924 Log_OC
.v(TAG
, "onPause() end");
928 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
931 * {@link BroadcastReceiver} to enable syncing feedback in UI
934 public void onReceive(Context context
, Intent intent
) {
936 String event
= intent
.getAction();
937 Log_OC
.d(TAG
, "Received broadcast " + event
);
938 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
939 String synchFolderRemotePath
=
940 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
941 RemoteOperationResult synchResult
=
942 (RemoteOperationResult
)intent
.getSerializableExtra(
943 FileSyncAdapter
.EXTRA_RESULT
);
944 boolean sameAccount
= (getAccount() != null
&&
945 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
949 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
950 mSyncInProgress
= true
;
953 OCFile currentFile
= (getFile() == null
) ? null
:
954 getStorageManager().getFileByPath(getFile().getRemotePath());
955 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
956 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
958 if (currentDir
== null
) {
959 // current folder was removed from the server
960 Toast
.makeText( FileDisplayActivity
.this,
963 sync_current_folder_was_removed
),
964 synchFolderRemotePath
),
971 if (currentFile
== null
&& !getFile().isFolder()) {
972 // currently selected file was removed in the server, and now we
974 cleanSecondFragment();
975 currentFile
= currentDir
;
978 if (synchFolderRemotePath
!= null
&&
979 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
980 OCFileListFragment fileListFragment
= getListOfFilesFragment();
981 if (fileListFragment
!= null
) {
982 fileListFragment
.listDirectory();
983 // TODO Enable when "On Device" is recovered ?
984 // fileListFragment.listDirectory(currentDir,
985 // MainApp.getOnlyOnDevice());
988 setFile(currentFile
);
991 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
992 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
995 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
996 equals(event
) &&/// TODO refactor and make common
998 synchResult
!= null
&& !synchResult
.isSuccess() &&
999 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1000 synchResult
.isIdPRedirection() ||
1001 (synchResult
.isException() && synchResult
.getException()
1002 instanceof AuthenticatorException
))) {
1006 OwnCloudClient client
;
1007 OwnCloudAccount ocAccount
=
1008 new OwnCloudAccount(getAccount(), context
);
1009 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1010 removeClientFor(ocAccount
));
1011 if (client
!= null
) {
1012 OwnCloudCredentials cred
= client
.getCredentials();
1014 AccountManager am
= AccountManager
.get(context
);
1015 if (cred
.authTokenExpires()) {
1016 am
.invalidateAuthToken(
1021 am
.clearPassword(getAccount());
1025 requestCredentialsUpdate();
1027 } catch (AccountNotFoundException e
) {
1028 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1033 removeStickyBroadcast(intent
);
1034 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1035 mProgressBar
.setIndeterminate(mSyncInProgress
);
1036 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1037 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1038 /*|| mRefreshSharesInProgress*/ //);
1040 setBackgroundText();
1044 if (synchResult
!= null
) {
1045 if (synchResult
.getCode().equals(
1046 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1047 mLastSslUntrustedServerResult
= synchResult
;
1050 } catch (RuntimeException e
) {
1051 // avoid app crashes after changing the serial id of RemoteOperationResult
1052 // in owncloud library with broadcast notifications pending to process
1053 removeStickyBroadcast(intent
);
1059 * Show a text message on screen view for notifying user if content is
1060 * loading or folder is empty
1062 private void setBackgroundText() {
1063 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1064 if (ocFileListFragment
!= null
) {
1065 int message
= R
.string
.file_list_loading
;
1066 if (!mSyncInProgress
) {
1067 // In case file list is empty
1068 message
= R
.string
.file_list_empty
;
1070 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1072 Log_OC
.e(TAG
, "OCFileListFragment is null");
1077 * Once the file upload has finished -> update view
1079 private class UploadFinishReceiver
extends BroadcastReceiver
{
1081 * Once the file upload has finished -> update view
1083 * @author David A. Velasco
1084 * {@link BroadcastReceiver} to enable upload feedback in UI
1087 public void onReceive(Context context
, Intent intent
) {
1089 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1090 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1091 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1092 OCFile currentDir
= getCurrentDir();
1093 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1094 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1096 if (sameAccount
&& isDescendant
) {
1097 refreshListOfFilesFragment();
1100 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1102 boolean renamedInUpload
= getFile().getRemotePath().
1103 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1104 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1106 FileFragment details
= getSecondFragment();
1107 boolean detailFragmentIsShown
= (details
!= null
&&
1108 details
instanceof FileDetailFragment
);
1110 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1111 if (uploadWasFine
) {
1112 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1114 if (renamedInUpload
) {
1115 String newName
= (new File(uploadedRemotePath
)).getName();
1116 Toast msg
= Toast
.makeText(
1119 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1124 if (uploadWasFine
|| getFile().fileExists()) {
1125 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1127 cleanSecondFragment();
1130 // Force the preview if the file is an image or text file
1131 if (uploadWasFine
) {
1132 OCFile ocFile
= getFile();
1133 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1134 startImagePreview(getFile());
1135 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1136 startTextPreview(ocFile
);
1137 // TODO what about other kind of previews?
1141 mProgressBar
.setIndeterminate(false
);
1143 if (intent
!= null
) {
1144 removeStickyBroadcast(intent
);
1154 * Class waiting for broadcast events from the {@link FileDownloader} service.
1156 * Updates the UI when a download is started or finished, provided that it is relevant for the
1159 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1161 //int refreshCounter = 0;
1163 public void onReceive(Context context
, Intent intent
) {
1165 boolean sameAccount
= isSameAccount(context
, intent
);
1166 String downloadedRemotePath
=
1167 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1168 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1170 if (sameAccount
&& isDescendant
) {
1171 String linkedToRemotePath
=
1172 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1173 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1174 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1175 refreshListOfFilesFragment();
1177 refreshSecondFragment(
1179 downloadedRemotePath
,
1180 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1184 if (mWaitingToSend
!= null
) {
1186 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1187 if (mWaitingToSend
.isDown()) {
1188 sendDownloadedFile();
1193 if (intent
!= null
) {
1194 removeStickyBroadcast(intent
);
1199 private boolean isDescendant(String downloadedRemotePath
) {
1200 OCFile currentDir
= getCurrentDir();
1202 currentDir
!= null
&&
1203 downloadedRemotePath
!= null
&&
1204 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1208 private boolean isAscendant(String linkedToRemotePath
) {
1209 OCFile currentDir
= getCurrentDir();
1211 currentDir
!= null
&&
1212 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1216 private boolean isSameAccount(Context context
, Intent intent
) {
1217 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1218 return (accountName
!= null
&& getAccount() != null
&&
1219 accountName
.equals(getAccount().name
));
1224 public void browseToRoot() {
1225 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1226 if (listOfFiles
!= null
) { // should never be null, indeed
1227 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1228 listOfFiles
.listDirectory(root
);
1229 // TODO Enable when "On Device" is recovered ?
1230 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1231 setFile(listOfFiles
.getCurrentFile());
1232 startSyncFolderOperation(root
, false
);
1234 cleanSecondFragment();
1241 * Updates action bar and second fragment, if in dual pane mode.
1244 public void onBrowsedDownTo(OCFile directory
) {
1246 cleanSecondFragment();
1248 startSyncFolderOperation(directory
, false
);
1250 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1253 if (DisplayUtils
.isGridView(directory
, getStorageManager())){
1261 * Shows the information of the {@link OCFile} received as a
1262 * parameter in the second fragment.
1264 * @param file {@link OCFile} whose details will be shown
1267 public void showDetails(OCFile file
) {
1268 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1269 setSecondFragment(detailFragment
);
1270 updateFragmentsVisibility(true
);
1271 updateActionBarTitleAndHomeButton(file
);
1276 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1278 // in dual pane mode, keep the focus of title an action bar in the current folder
1279 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1282 super.updateActionBarTitleAndHomeButton(chosenFile
);
1288 protected ServiceConnection
newTransferenceServiceConnection() {
1289 return new ListServiceConnection();
1293 * Defines callbacks for service binding, passed to bindService()
1295 private class ListServiceConnection
implements ServiceConnection
{
1298 public void onServiceConnected(ComponentName component
, IBinder service
) {
1299 if (component
.equals(new ComponentName(
1300 FileDisplayActivity
.this, FileDownloader
.class))) {
1301 Log_OC
.d(TAG
, "Download service connected");
1302 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1303 if (mWaitingToPreview
!= null
)
1304 if (getStorageManager() != null
) {
1307 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1308 if (!mWaitingToPreview
.isDown()) {
1309 requestForDownload();
1313 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1314 FileUploader
.class))) {
1315 Log_OC
.d(TAG
, "Upload service connected");
1316 mUploaderBinder
= (FileUploaderBinder
) service
;
1320 // a new chance to get the mDownloadBinder through
1321 // getFileDownloadBinder() - THIS IS A MESS
1322 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1323 if (listOfFiles
!= null
) {
1324 listOfFiles
.listDirectory();
1325 // TODO Enable when "On Device" is recovered ?
1326 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1328 FileFragment secondFragment
= getSecondFragment();
1329 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1330 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1331 detailFragment
.listenForTransferProgress();
1332 detailFragment
.updateFileDetails(false
, false
);
1337 public void onServiceDisconnected(ComponentName component
) {
1338 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1339 FileDownloader
.class))) {
1340 Log_OC
.d(TAG
, "Download service disconnected");
1341 mDownloaderBinder
= null
;
1342 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1343 FileUploader
.class))) {
1344 Log_OC
.d(TAG
, "Upload service disconnected");
1345 mUploaderBinder
= null
;
1351 public void onSavedCertificate() {
1352 startSyncFolderOperation(getCurrentDir(), false
);
1357 public void onFailedSavingCertificate() {
1358 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1359 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1361 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1365 public void onCancelCertificate() {
1370 * Updates the view associated to the activity after the finish of some operation over files
1371 * in the current account.
1373 * @param operation Removal operation performed.
1374 * @param result Result of the removal.
1377 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1378 super.onRemoteOperationFinish(operation
, result
);
1380 if (operation
instanceof RemoveFileOperation
) {
1381 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1383 } else if (operation
instanceof RenameFileOperation
) {
1384 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1386 } else if (operation
instanceof SynchronizeFileOperation
) {
1387 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1389 } else if (operation
instanceof CreateFolderOperation
) {
1390 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1392 } else if (operation
instanceof CreateShareOperation
) {
1393 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1395 } else if (operation
instanceof UnshareLinkOperation
) {
1396 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1398 } else if (operation
instanceof MoveFileOperation
) {
1399 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1401 } else if (operation
instanceof CopyFileOperation
) {
1402 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1406 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1407 RemoteOperationResult result
) {
1408 if (result
.isSuccess()) {
1409 refreshShowDetails();
1410 refreshListOfFilesFragment();
1414 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1415 RemoteOperationResult result
) {
1416 if (result
.isSuccess()) {
1417 refreshShowDetails();
1418 refreshListOfFilesFragment();
1420 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1421 cleanSecondFragment();
1422 refreshListOfFilesFragment();
1426 private void refreshShowDetails() {
1427 FileFragment details
= getSecondFragment();
1428 if (details
!= null
) {
1429 OCFile file
= details
.getFile();
1431 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1432 if (details
instanceof PreviewMediaFragment
) {
1433 // Refresh OCFile of the fragment
1434 ((PreviewMediaFragment
) details
).updateFile(file
);
1435 } else if (details
instanceof PreviewTextFragment
) {
1436 // Refresh OCFile of the fragment
1437 ((PreviewTextFragment
) details
).updateFile(file
);
1442 invalidateOptionsMenu();
1447 * Updates the view associated to the activity after the finish of an operation trying to
1450 * @param operation Removal operation performed.
1451 * @param result Result of the removal.
1453 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1454 RemoteOperationResult result
) {
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 if (result
.isSuccess()) {
1463 OCFile removedFile
= operation
.getFile();
1464 FileFragment second
= getSecondFragment();
1465 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1466 if (second
instanceof PreviewMediaFragment
) {
1467 ((PreviewMediaFragment
) second
).stopPreview(true
);
1469 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1470 cleanSecondFragment();
1472 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1473 refreshListOfFilesFragment();
1475 invalidateOptionsMenu();
1477 if (result
.isSslRecoverableException()) {
1478 mLastSslUntrustedServerResult
= result
;
1479 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1486 * Updates the view associated to the activity after the finish of an operation trying to move a
1489 * @param operation Move operation performed.
1490 * @param result Result of the move operation.
1492 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1493 RemoteOperationResult result
) {
1494 if (result
.isSuccess()) {
1495 dismissLoadingDialog();
1496 refreshListOfFilesFragment();
1498 dismissLoadingDialog();
1500 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1501 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1505 } catch (NotFoundException e
) {
1506 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1512 * Updates the view associated to the activity after the finish of an operation trying to copy a
1515 * @param operation Copy operation performed.
1516 * @param result Result of the copy operation.
1518 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1519 if (result
.isSuccess()) {
1520 dismissLoadingDialog();
1521 refreshListOfFilesFragment();
1523 dismissLoadingDialog();
1525 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1526 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1530 } catch (NotFoundException e
) {
1531 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1537 * Updates the view associated to the activity after the finish of an operation trying to rename
1540 * @param operation Renaming operation performed.
1541 * @param result Result of the renaming.
1543 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1544 RemoteOperationResult result
) {
1545 dismissLoadingDialog();
1546 OCFile renamedFile
= operation
.getFile();
1547 if (result
.isSuccess()) {
1548 FileFragment details
= getSecondFragment();
1549 if (details
!= null
) {
1550 if (details
instanceof FileDetailFragment
&&
1551 renamedFile
.equals(details
.getFile()) ) {
1552 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1553 showDetails(renamedFile
);
1555 } else if (details
instanceof PreviewMediaFragment
&&
1556 renamedFile
.equals(details
.getFile())) {
1557 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1558 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1559 int position
= ((PreviewMediaFragment
) details
).getPosition();
1560 startMediaPreview(renamedFile
, position
, true
);
1562 getFileOperationsHelper().openFile(renamedFile
);
1564 } else if (details
instanceof PreviewTextFragment
&&
1565 renamedFile
.equals(details
.getFile())) {
1566 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1567 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1568 startTextPreview(renamedFile
);
1570 getFileOperationsHelper().openFile(renamedFile
);
1575 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1576 refreshListOfFilesFragment();
1580 Toast msg
= Toast
.makeText(this,
1581 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1585 if (result
.isSslRecoverableException()) {
1586 mLastSslUntrustedServerResult
= result
;
1587 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1592 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1593 RemoteOperationResult result
) {
1594 if (result
.isSuccess()) {
1595 if (operation
.transferWasRequested()) {
1596 OCFile syncedFile
= operation
.getLocalFile();
1597 onTransferStateChanged(syncedFile
, true
, true
);
1598 invalidateOptionsMenu();
1599 refreshShowDetails();
1605 * Updates the view associated to the activity after the finish of an operation trying create a
1608 * @param operation Creation operation performed.
1609 * @param result Result of the creation.
1611 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1612 RemoteOperationResult result
) {
1613 if (result
.isSuccess()) {
1614 dismissLoadingDialog();
1615 refreshListOfFilesFragment();
1617 dismissLoadingDialog();
1619 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1620 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1624 } catch (NotFoundException e
) {
1625 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1635 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1636 refreshListOfFilesFragment();
1637 FileFragment details
= getSecondFragment();
1638 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1639 file
.equals(details
.getFile()) ) {
1640 if (downloading
|| uploading
) {
1641 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1643 if (!file
.fileExists()) {
1644 cleanSecondFragment();
1646 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1654 private void requestForDownload() {
1655 Account account
= getAccount();
1656 //if (!mWaitingToPreview.isDownloading()) {
1657 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1658 Intent i
= new Intent(this, FileDownloader
.class);
1659 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1660 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1666 private OCFile
getCurrentDir() {
1667 OCFile file
= getFile();
1669 if (file
.isFolder()) {
1671 } else if (getStorageManager() != null
) {
1672 String parentPath
= file
.getRemotePath().substring(0,
1673 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1674 return getStorageManager().getFileByPath(parentPath
);
1680 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1681 long currentSyncTime
= System
.currentTimeMillis();
1683 mSyncInProgress
= true
;
1685 // perform folder synchronization
1686 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1689 getFileOperationsHelper().isSharedSupported(),
1691 getStorageManager(),
1693 getApplicationContext()
1695 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1697 mProgressBar
.setIndeterminate(true
);
1699 setBackgroundText();
1703 * Show untrusted cert dialog
1705 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1706 // Show a dialog with the certificate info
1707 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1708 (CertificateCombinedException
) result
.getException());
1709 FragmentManager fm
= getSupportFragmentManager();
1710 FragmentTransaction ft
= fm
.beginTransaction();
1711 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1714 private void requestForDownload(OCFile file
) {
1715 Account account
= getAccount();
1716 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1717 Intent i
= new Intent(this, FileDownloader
.class);
1718 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1719 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1724 private void sendDownloadedFile() {
1725 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1726 mWaitingToSend
= null
;
1731 * Requests the download of the received {@link OCFile} , updates the UI
1732 * to monitor the download progress and prepares the activity to send the file
1733 * when the download finishes.
1735 * @param file {@link OCFile} to download and preview.
1737 public void startDownloadForSending(OCFile file
) {
1738 mWaitingToSend
= file
;
1739 requestForDownload(mWaitingToSend
);
1740 boolean hasSecondFragment
= (getSecondFragment() != null
);
1741 updateFragmentsVisibility(hasSecondFragment
);
1745 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1747 * @param file Image {@link OCFile} to show.
1749 public void startImagePreview(OCFile file
) {
1750 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1751 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1752 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1753 startActivity(showDetailsIntent
);
1757 * Stars the preview of an already down media {@link OCFile}.
1759 * @param file Media {@link OCFile} to preview.
1760 * @param startPlaybackPosition Media position where the playback will be started,
1762 * @param autoplay When 'true', the playback will start without user
1765 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1766 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1768 setSecondFragment(mediaFragment
);
1769 updateFragmentsVisibility(true
);
1770 updateActionBarTitleAndHomeButton(file
);
1775 * Stars the preview of a text file {@link OCFile}.
1777 * @param file Text {@link OCFile} to preview.
1779 public void startTextPreview(OCFile file
) {
1780 Bundle args
= new Bundle();
1781 args
.putParcelable(EXTRA_FILE
, file
);
1782 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1783 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1784 PreviewTextFragment
.class.getName(), args
);
1785 setSecondFragment(textPreviewFragment
);
1786 updateFragmentsVisibility(true
);
1787 //updateNavigationElementsInActionBar(file);
1792 * Requests the download of the received {@link OCFile} , updates the UI
1793 * to monitor the download progress and prepares the activity to preview
1794 * or open the file when the download finishes.
1796 * @param file {@link OCFile} to download and preview.
1798 public void startDownloadForPreview(OCFile file
) {
1799 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1800 setSecondFragment(detailFragment
);
1801 mWaitingToPreview
= file
;
1802 requestForDownload();
1803 updateFragmentsVisibility(true
);
1804 updateActionBarTitleAndHomeButton(file
);
1809 public void cancelTransference(OCFile file
) {
1810 getFileOperationsHelper().cancelTransference(file
);
1811 if (mWaitingToPreview
!= null
&&
1812 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1813 mWaitingToPreview
= null
;
1815 if (mWaitingToSend
!= null
&&
1816 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1817 mWaitingToSend
= null
;
1819 onTransferStateChanged(file
, false
, false
);
1823 public void onRefresh(boolean ignoreETag
) {
1824 refreshList(ignoreETag
);
1828 public void onRefresh() {
1832 private void refreshList(boolean ignoreETag
) {
1833 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1834 if (listOfFiles
!= null
) {
1835 OCFile folder
= listOfFiles
.getCurrentFile();
1836 if (folder
!= null
) {
1837 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1838 listDirectory(mFile);*/
1839 startSyncFolderOperation(folder
, ignoreETag
);
1844 private void sortByDate(boolean ascending
) {
1845 getListOfFilesFragment().sortByDate(ascending
);
1848 private void sortBySize(boolean ascending
) {
1849 getListOfFilesFragment().sortBySize(ascending
);
1852 private void sortByName(boolean ascending
) {
1853 getListOfFilesFragment().sortByName(ascending
);
1855 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1856 private void switchToGridView() {
1857 getListOfFilesFragment().switchToGridView();
1859 private void switchToListView() {
1860 getListOfFilesFragment().switchToListView();
1863 public void allFilesOption() {