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 public 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 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
272 if (!stateWasRecovered
) {
273 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
274 initFragmentsWithFile();
275 if (file
.isFolder()) {
276 startSyncFolderOperation(file
, false
);
280 updateFragmentsVisibility(!file
.isFolder());
281 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
286 private void createMinFragments() {
287 OCFileListFragment listOfFiles
= new OCFileListFragment();
288 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
289 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
290 transaction
.commit();
293 private void initFragmentsWithFile() {
294 if (getAccount() != null
&& getFile() != null
) {
296 OCFileListFragment listOfFiles
= getListOfFilesFragment();
297 if (listOfFiles
!= null
) {
298 listOfFiles
.listDirectory(getCurrentDir());
299 // TODO Enable when "On Device" is recovered
300 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
303 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
307 OCFile file
= getFile();
308 Fragment secondFragment
= chooseInitialSecondFragment(file
);
309 if (secondFragment
!= null
) {
310 setSecondFragment(secondFragment
);
311 updateFragmentsVisibility(true
);
312 updateActionBarTitleAndHomeButton(file
);
315 cleanSecondFragment();
316 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
317 startTextPreview(file
);
320 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
327 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
328 if (getAccount() == null
) {
329 Log_OC
.wtf(TAG
, "\t account is NULL");
331 if (getFile() == null
) {
332 Log_OC
.wtf(TAG
, "\t file is NULL");
337 private Fragment
chooseInitialSecondFragment(OCFile file
) {
338 Fragment secondFragment
= null
;
339 if (file
!= null
&& !file
.isFolder()) {
340 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
341 && file
.getLastSyncDateForProperties() > 0 // temporal fix
343 int startPlaybackPosition
=
344 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
346 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
347 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
348 startPlaybackPosition
, autoplay
);
350 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
351 secondFragment
= null
;
353 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
356 return secondFragment
;
361 * Replaces the second fragment managed by the activity with the received as
364 * Assumes never will be more than two fragments managed at the same time.
366 * @param fragment New second Fragment to set.
368 private void setSecondFragment(Fragment fragment
) {
369 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
370 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
371 transaction
.commit();
375 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
377 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
380 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
381 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
384 } else if (existsSecondFragment
) {
385 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
386 mLeftFragmentContainer
.setVisibility(View
.GONE
);
388 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
389 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
393 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
394 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
396 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
397 mRightFragmentContainer
.setVisibility(View
.GONE
);
403 private OCFileListFragment
getListOfFilesFragment() {
404 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
405 FileDisplayActivity
.TAG_LIST_OF_FILES
);
406 if (listOfFiles
!= null
) {
407 return (OCFileListFragment
) listOfFiles
;
409 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
413 public FileFragment
getSecondFragment() {
414 Fragment second
= getSupportFragmentManager().findFragmentByTag(
415 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
416 if (second
!= null
) {
417 return (FileFragment
) second
;
422 protected void cleanSecondFragment() {
423 Fragment second
= getSecondFragment();
424 if (second
!= null
) {
425 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
429 updateFragmentsVisibility(false
);
430 updateActionBarTitleAndHomeButton(null
);
433 protected void refreshListOfFilesFragment() {
434 OCFileListFragment fileListFragment
= getListOfFilesFragment();
435 if (fileListFragment
!= null
) {
436 fileListFragment
.listDirectory();
437 // TODO Enable when "On Device" is recovered ?
438 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
442 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
444 FileFragment secondFragment
= getSecondFragment();
445 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
446 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
447 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
448 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
449 OCFile fileInFragment
= detailsFragment
.getFile();
450 if (fileInFragment
!= null
&&
451 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
452 // the user browsed to other file ; forget the automatic preview
453 mWaitingToPreview
= null
;
455 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
456 // grant that the right panel updates the progress bar
457 detailsFragment
.listenForTransferProgress();
458 detailsFragment
.updateFileDetails(true
, false
);
460 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
461 // update the right panel
462 boolean detailsFragmentChanged
= false
;
465 mWaitingToPreview
= getStorageManager().getFileById(
466 mWaitingToPreview
.getFileId()); // update the file from database,
467 // for the local storage path
468 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
469 startMediaPreview(mWaitingToPreview
, 0, true
);
470 detailsFragmentChanged
= true
;
471 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
472 startTextPreview(mWaitingToPreview
);
473 detailsFragmentChanged
= true
;
475 getFileOperationsHelper().openFile(mWaitingToPreview
);
478 mWaitingToPreview
= null
;
480 if (!detailsFragmentChanged
) {
481 detailsFragment
.updateFileDetails(false
, (success
));
488 public boolean onPrepareOptionsMenu(Menu menu
) {
489 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
490 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
491 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
492 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
494 return super.onPrepareOptionsMenu(menu
);
498 public boolean onCreateOptionsMenu(Menu menu
) {
499 MenuInflater inflater
= getMenuInflater();
500 inflater
.inflate(R
.menu
.main_menu
, menu
);
501 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
504 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
513 public boolean onOptionsItemSelected(MenuItem item
) {
514 boolean retval
= true
;
515 switch (item
.getItemId()) {
516 case R
.id
.action_sync_account
: {
517 startSynchronization();
520 case android
.R
.id
.home
: {
521 FileFragment second
= getSecondFragment();
522 OCFile currentDir
= getCurrentDir();
523 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
524 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
525 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
526 (second
!= null
&& second
.getFile() != null
)) {
530 mDrawerLayout
.openDrawer(GravityCompat
.START
);
534 case R
.id
.action_sort
: {
535 SharedPreferences appPreferences
= PreferenceManager
536 .getDefaultSharedPreferences(this);
538 // Read sorting order, default to sort by name ascending
539 Integer sortOrder
= appPreferences
540 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
542 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
543 builder
.setTitle(R
.string
.actionbar_sort_title
)
544 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
545 new DialogInterface
.OnClickListener() {
546 public void onClick(DialogInterface dialog
, int which
) {
559 builder
.create().show();
562 case R
.id
.action_switch_view
:{
564 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
565 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
566 R
.drawable
.ic_view_module
));
567 DisplayUtils
.setViewMode(getFile(), false
);
570 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
571 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
572 R
.drawable
.ic_view_list
));
573 DisplayUtils
.setViewMode(getFile(), true
);
580 retval
= super.onOptionsItemSelected(item
);
585 public void createFolder() {
586 CreateFolderDialogFragment dialog
=
587 CreateFolderDialogFragment
.newInstance(getCurrentDir());
588 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
591 public void uploadLocalFilesSelected() {
592 Intent action
= new Intent(this, UploadFilesActivity
.class);
594 UploadFilesActivity
.EXTRA_ACCOUNT
,
597 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
600 public void uploadFromOtherAppsSelected() {
601 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
602 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
603 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
604 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
605 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
607 startActivityForResult(
608 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
609 ACTION_SELECT_CONTENT_FROM_APPS
613 private void startSynchronization() {
614 Log_OC
.d(TAG
, "Got to start sync");
615 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
616 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
617 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
618 // cancel the current synchronizations of any ownCloud account
619 Bundle bundle
= new Bundle();
620 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
621 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
622 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
623 MainApp
.getAuthority());
624 ContentResolver
.requestSync(
626 MainApp
.getAuthority(), bundle
);
628 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
629 MainApp
.getAuthority() + " with new API");
630 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
631 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
632 builder
.setExpedited(true
);
633 builder
.setManual(true
);
636 // Fix bug in Android Lollipop when you click on refresh the whole account
637 Bundle extras
= new Bundle();
638 builder
.setExtras(extras
);
640 SyncRequest request
= builder
.build();
641 ContentResolver
.requestSync(request
);
646 * Called, when the user selected something for uploading
649 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
651 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
653 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
654 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
655 //getClipData is only supported on api level 16+, Jelly Bean
656 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
657 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
658 Intent intent
= new Intent();
659 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
660 requestSimpleUpload(intent
, resultCode
);
663 requestSimpleUpload(data
, resultCode
);
665 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
666 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
667 requestMultipleUpload(data
, resultCode
);
669 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
670 final Intent fData
= data
;
671 final int fResultCode
= resultCode
;
672 getHandler().postDelayed(
676 requestMoveOperation(fData
, fResultCode
);
679 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
682 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
684 final Intent fData
= data
;
685 final int fResultCode
= resultCode
;
686 getHandler().postDelayed(
690 requestCopyOperation(fData
, fResultCode
);
693 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
697 super.onActivityResult(requestCode
, resultCode
, data
);
702 private void requestMultipleUpload(Intent data
, int resultCode
) {
703 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
704 if (filePaths
!= null
) {
705 String
[] remotePaths
= new String
[filePaths
.length
];
706 String remotePathBase
= getCurrentDir().getRemotePath();
707 for (int j
= 0; j
< remotePaths
.length
; j
++) {
708 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
711 Intent i
= new Intent(this, FileUploader
.class);
712 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
713 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
714 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
715 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
716 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
717 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
721 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
722 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
730 private void requestSimpleUpload(Intent data
, int resultCode
) {
731 String filePath
= null
;
732 String mimeType
= null
;
734 Uri selectedImageUri
= data
.getData();
737 mimeType
= getContentResolver().getType(selectedImageUri
);
739 String fileManagerString
= selectedImageUri
.getPath();
740 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
742 if (selectedImagePath
!= null
)
743 filePath
= selectedImagePath
;
745 filePath
= fileManagerString
;
747 } catch (Exception e
) {
748 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
749 "Intent.ACTION_GET_CONTENT", e
);
752 if (filePath
== null
) {
753 Log_OC
.e(TAG
, "Couldn't resolve path to file");
754 Toast t
= Toast
.makeText(
755 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
763 Intent i
= new Intent(this, FileUploader
.class);
764 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
765 OCFile currentDir
= getCurrentDir();
766 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
768 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
769 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
771 if (cursor
!= null
&& cursor
.moveToFirst()) {
772 String displayName
= cursor
.getString(cursor
.getColumnIndex(
773 OpenableColumns
.DISPLAY_NAME
));
774 Log_OC
.v(TAG
, "Display Name: " + displayName
);
776 displayName
.replace(File
.separatorChar
, '_');
777 displayName
.replace(File
.pathSeparatorChar
, '_');
778 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
781 // and what happens in case of error?; wrong target name for the upload
787 remotePath
+= new File(filePath
).getName();
790 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
791 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
792 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
793 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
794 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
795 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
800 * Request the operation for moving the file/folder from one path to another
802 * @param data Intent received
803 * @param resultCode Result code received
805 private void requestMoveOperation(Intent data
, int resultCode
) {
806 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
807 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
808 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
812 * Request the operation for copying the file/folder from one path to another
814 * @param data Intent received
815 * @param resultCode Result code received
817 private void requestCopyOperation(Intent data
, int resultCode
) {
818 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
819 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
820 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
824 public void onBackPressed() {
825 boolean isFabOpen
= isFabOpen();
826 boolean isDrawerOpen
= isDrawerOpen();
829 * BackPressed priority/hierarchy:
830 * 1. close drawer if opened
831 * 2. close FAB if open (only if drawer isn't open)
832 * 3. navigate up (only if drawer and FAB aren't open)
834 if(isDrawerOpen
&& isFabOpen
) {
835 // close drawer first
836 super.onBackPressed();
837 } else if(isDrawerOpen
&& !isFabOpen
) {
839 super.onBackPressed();
840 } else if (!isDrawerOpen
&& isFabOpen
) {
842 getListOfFilesFragment().getFabMain().collapse();
845 OCFileListFragment listOfFiles
= getListOfFilesFragment();
846 if (mDualPane
|| getSecondFragment() == null
) {
847 OCFile currentDir
= getCurrentDir();
848 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
852 if (listOfFiles
!= null
) { // should never be null, indeed
853 listOfFiles
.onBrowseUp();
856 if (listOfFiles
!= null
) { // should never be null, indeed
857 setFile(listOfFiles
.getCurrentFile());
859 cleanSecondFragment();
864 private void changeGridIcon(){
865 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
866 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
867 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
868 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
869 R
.drawable
.ic_view_list
));
871 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
872 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
873 R
.drawable
.ic_view_module
));
878 protected void onSaveInstanceState(Bundle outState
) {
879 // responsibility of restore is preferred in onCreate() before than in
880 // onRestoreInstanceState when there are Fragments involved
881 Log_OC
.v(TAG
, "onSaveInstanceState() start");
882 super.onSaveInstanceState(outState
);
883 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
884 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
885 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
886 // mRefreshSharesInProgress);
887 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
889 Log_OC
.v(TAG
, "onSaveInstanceState() end");
894 protected void onResume() {
895 Log_OC
.v(TAG
, "onResume() start");
897 // refresh Navigation Drawer account list
898 mNavigationDrawerAdapter
.updateAccountList();
900 // refresh list of files
901 refreshListOfFilesFragment();
903 // Listen for sync messages
904 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
905 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
906 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
907 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
908 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
909 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
910 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
911 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
912 // syncIntentFilter);
914 // Listen for upload messages
915 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
916 mUploadFinishReceiver
= new UploadFinishReceiver();
917 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
919 // Listen for download messages
920 IntentFilter downloadIntentFilter
= new IntentFilter(
921 FileDownloader
.getDownloadAddedMessage());
922 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
923 mDownloadFinishReceiver
= new DownloadFinishReceiver();
924 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
926 Log_OC
.v(TAG
, "onResume() end");
932 protected void onPause() {
933 Log_OC
.v(TAG
, "onPause() start");
934 if (mSyncBroadcastReceiver
!= null
) {
935 unregisterReceiver(mSyncBroadcastReceiver
);
936 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
937 mSyncBroadcastReceiver
= null
;
939 if (mUploadFinishReceiver
!= null
) {
940 unregisterReceiver(mUploadFinishReceiver
);
941 mUploadFinishReceiver
= null
;
943 if (mDownloadFinishReceiver
!= null
) {
944 unregisterReceiver(mDownloadFinishReceiver
);
945 mDownloadFinishReceiver
= null
;
949 Log_OC
.v(TAG
, "onPause() end");
952 public boolean isFabOpen() {
953 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
961 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
964 * {@link BroadcastReceiver} to enable syncing feedback in UI
967 public void onReceive(Context context
, Intent intent
) {
969 String event
= intent
.getAction();
970 Log_OC
.d(TAG
, "Received broadcast " + event
);
971 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
972 String synchFolderRemotePath
=
973 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
974 RemoteOperationResult synchResult
=
975 (RemoteOperationResult
)intent
.getSerializableExtra(
976 FileSyncAdapter
.EXTRA_RESULT
);
977 boolean sameAccount
= (getAccount() != null
&&
978 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
982 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
983 mSyncInProgress
= true
;
986 OCFile currentFile
= (getFile() == null
) ? null
:
987 getStorageManager().getFileByPath(getFile().getRemotePath());
988 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
989 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
991 if (currentDir
== null
) {
992 // current folder was removed from the server
993 Toast
.makeText( FileDisplayActivity
.this,
996 sync_current_folder_was_removed
),
997 synchFolderRemotePath
),
1004 if (currentFile
== null
&& !getFile().isFolder()) {
1005 // currently selected file was removed in the server, and now we
1007 cleanSecondFragment();
1008 currentFile
= currentDir
;
1011 if (synchFolderRemotePath
!= null
&&
1012 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1013 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1014 if (fileListFragment
!= null
) {
1015 fileListFragment
.listDirectory();
1016 // TODO Enable when "On Device" is recovered ?
1017 // fileListFragment.listDirectory(currentDir,
1018 // MainApp.getOnlyOnDevice());
1021 setFile(currentFile
);
1024 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
1025 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1028 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1029 equals(event
) &&/// TODO refactor and make common
1031 synchResult
!= null
&& !synchResult
.isSuccess() &&
1032 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1033 synchResult
.isIdPRedirection() ||
1034 (synchResult
.isException() && synchResult
.getException()
1035 instanceof AuthenticatorException
))) {
1039 OwnCloudClient client
;
1040 OwnCloudAccount ocAccount
=
1041 new OwnCloudAccount(getAccount(), context
);
1042 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1043 removeClientFor(ocAccount
));
1044 if (client
!= null
) {
1045 OwnCloudCredentials cred
= client
.getCredentials();
1047 AccountManager am
= AccountManager
.get(context
);
1048 if (cred
.authTokenExpires()) {
1049 am
.invalidateAuthToken(
1054 am
.clearPassword(getAccount());
1058 requestCredentialsUpdate();
1060 } catch (AccountNotFoundException e
) {
1061 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1066 removeStickyBroadcast(intent
);
1067 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1068 mProgressBar
.setIndeterminate(mSyncInProgress
);
1069 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1070 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1071 /*|| mRefreshSharesInProgress*/ //);
1073 setBackgroundText();
1077 if (synchResult
!= null
) {
1078 if (synchResult
.getCode().equals(
1079 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1080 mLastSslUntrustedServerResult
= synchResult
;
1083 } catch (RuntimeException e
) {
1084 // avoid app crashes after changing the serial id of RemoteOperationResult
1085 // in owncloud library with broadcast notifications pending to process
1086 removeStickyBroadcast(intent
);
1092 * Show a text message on screen view for notifying user if content is
1093 * loading or folder is empty
1095 private void setBackgroundText() {
1096 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1097 if (ocFileListFragment
!= null
) {
1098 int message
= R
.string
.file_list_loading
;
1099 if (!mSyncInProgress
) {
1100 // In case file list is empty
1101 message
= R
.string
.file_list_empty
;
1103 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1105 Log_OC
.e(TAG
, "OCFileListFragment is null");
1110 * Once the file upload has finished -> update view
1112 private class UploadFinishReceiver
extends BroadcastReceiver
{
1114 * Once the file upload has finished -> update view
1116 * @author David A. Velasco
1117 * {@link BroadcastReceiver} to enable upload feedback in UI
1120 public void onReceive(Context context
, Intent intent
) {
1122 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1123 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1124 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1125 OCFile currentDir
= getCurrentDir();
1126 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1127 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1129 if (sameAccount
&& isDescendant
) {
1130 refreshListOfFilesFragment();
1133 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1135 boolean renamedInUpload
= getFile().getRemotePath().
1136 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1137 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1139 FileFragment details
= getSecondFragment();
1140 boolean detailFragmentIsShown
= (details
!= null
&&
1141 details
instanceof FileDetailFragment
);
1143 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1144 if (uploadWasFine
) {
1145 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1147 if (renamedInUpload
) {
1148 String newName
= (new File(uploadedRemotePath
)).getName();
1149 Toast msg
= Toast
.makeText(
1152 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1157 if (uploadWasFine
|| getFile().fileExists()) {
1158 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1160 cleanSecondFragment();
1163 // Force the preview if the file is an image or text file
1164 if (uploadWasFine
) {
1165 OCFile ocFile
= getFile();
1166 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1167 startImagePreview(getFile());
1168 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1169 startTextPreview(ocFile
);
1170 // TODO what about other kind of previews?
1174 mProgressBar
.setIndeterminate(false
);
1176 if (intent
!= null
) {
1177 removeStickyBroadcast(intent
);
1187 * Class waiting for broadcast events from the {@link FileDownloader} service.
1189 * Updates the UI when a download is started or finished, provided that it is relevant for the
1192 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1194 //int refreshCounter = 0;
1196 public void onReceive(Context context
, Intent intent
) {
1198 boolean sameAccount
= isSameAccount(context
, intent
);
1199 String downloadedRemotePath
=
1200 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1201 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1203 if (sameAccount
&& isDescendant
) {
1204 String linkedToRemotePath
=
1205 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1206 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1207 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1208 refreshListOfFilesFragment();
1210 refreshSecondFragment(
1212 downloadedRemotePath
,
1213 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1217 if (mWaitingToSend
!= null
) {
1219 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1220 if (mWaitingToSend
.isDown()) {
1221 sendDownloadedFile();
1226 if (intent
!= null
) {
1227 removeStickyBroadcast(intent
);
1232 private boolean isDescendant(String downloadedRemotePath
) {
1233 OCFile currentDir
= getCurrentDir();
1235 currentDir
!= null
&&
1236 downloadedRemotePath
!= null
&&
1237 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1241 private boolean isAscendant(String linkedToRemotePath
) {
1242 OCFile currentDir
= getCurrentDir();
1244 currentDir
!= null
&&
1245 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1249 private boolean isSameAccount(Context context
, Intent intent
) {
1250 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1251 return (accountName
!= null
&& getAccount() != null
&&
1252 accountName
.equals(getAccount().name
));
1257 public void browseToRoot() {
1258 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1259 if (listOfFiles
!= null
) { // should never be null, indeed
1260 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1261 listOfFiles
.listDirectory(root
);
1262 // TODO Enable when "On Device" is recovered ?
1263 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1264 setFile(listOfFiles
.getCurrentFile());
1265 startSyncFolderOperation(root
, false
);
1267 cleanSecondFragment();
1274 * Updates action bar and second fragment, if in dual pane mode.
1277 public void onBrowsedDownTo(OCFile directory
) {
1279 cleanSecondFragment();
1281 startSyncFolderOperation(directory
, false
);
1283 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1286 if (DisplayUtils
.isGridView(directory
, getStorageManager())){
1294 * Shows the information of the {@link OCFile} received as a
1295 * parameter in the second fragment.
1297 * @param file {@link OCFile} whose details will be shown
1300 public void showDetails(OCFile file
) {
1301 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1302 setSecondFragment(detailFragment
);
1303 updateFragmentsVisibility(true
);
1304 updateActionBarTitleAndHomeButton(file
);
1309 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1311 // in dual pane mode, keep the focus of title an action bar in the current folder
1312 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1315 super.updateActionBarTitleAndHomeButton(chosenFile
);
1321 protected ServiceConnection
newTransferenceServiceConnection() {
1322 return new ListServiceConnection();
1326 * Defines callbacks for service binding, passed to bindService()
1328 private class ListServiceConnection
implements ServiceConnection
{
1331 public void onServiceConnected(ComponentName component
, IBinder service
) {
1332 if (component
.equals(new ComponentName(
1333 FileDisplayActivity
.this, FileDownloader
.class))) {
1334 Log_OC
.d(TAG
, "Download service connected");
1335 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1336 if (mWaitingToPreview
!= null
)
1337 if (getStorageManager() != null
) {
1340 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1341 if (!mWaitingToPreview
.isDown()) {
1342 requestForDownload();
1346 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1347 FileUploader
.class))) {
1348 Log_OC
.d(TAG
, "Upload service connected");
1349 mUploaderBinder
= (FileUploaderBinder
) service
;
1353 // a new chance to get the mDownloadBinder through
1354 // getFileDownloadBinder() - THIS IS A MESS
1355 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1356 if (listOfFiles
!= null
) {
1357 listOfFiles
.listDirectory();
1358 // TODO Enable when "On Device" is recovered ?
1359 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1361 FileFragment secondFragment
= getSecondFragment();
1362 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1363 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1364 detailFragment
.listenForTransferProgress();
1365 detailFragment
.updateFileDetails(false
, false
);
1370 public void onServiceDisconnected(ComponentName component
) {
1371 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1372 FileDownloader
.class))) {
1373 Log_OC
.d(TAG
, "Download service disconnected");
1374 mDownloaderBinder
= null
;
1375 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1376 FileUploader
.class))) {
1377 Log_OC
.d(TAG
, "Upload service disconnected");
1378 mUploaderBinder
= null
;
1384 public void onSavedCertificate() {
1385 startSyncFolderOperation(getCurrentDir(), false
);
1390 public void onFailedSavingCertificate() {
1391 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1392 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1394 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1398 public void onCancelCertificate() {
1403 * Updates the view associated to the activity after the finish of some operation over files
1404 * in the current account.
1406 * @param operation Removal operation performed.
1407 * @param result Result of the removal.
1410 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1411 super.onRemoteOperationFinish(operation
, result
);
1413 if (operation
instanceof RemoveFileOperation
) {
1414 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1416 } else if (operation
instanceof RenameFileOperation
) {
1417 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1419 } else if (operation
instanceof SynchronizeFileOperation
) {
1420 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1422 } else if (operation
instanceof CreateFolderOperation
) {
1423 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1425 } else if (operation
instanceof CreateShareOperation
) {
1426 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1428 } else if (operation
instanceof UnshareLinkOperation
) {
1429 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1431 } else if (operation
instanceof MoveFileOperation
) {
1432 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1434 } else if (operation
instanceof CopyFileOperation
) {
1435 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1439 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1440 RemoteOperationResult result
) {
1441 if (result
.isSuccess()) {
1442 refreshShowDetails();
1443 refreshListOfFilesFragment();
1447 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1448 RemoteOperationResult result
) {
1449 if (result
.isSuccess()) {
1450 refreshShowDetails();
1451 refreshListOfFilesFragment();
1453 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1454 cleanSecondFragment();
1455 refreshListOfFilesFragment();
1459 private void refreshShowDetails() {
1460 FileFragment details
= getSecondFragment();
1461 if (details
!= null
) {
1462 OCFile file
= details
.getFile();
1464 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1465 if (details
instanceof PreviewMediaFragment
) {
1466 // Refresh OCFile of the fragment
1467 ((PreviewMediaFragment
) details
).updateFile(file
);
1468 } else if (details
instanceof PreviewTextFragment
) {
1469 // Refresh OCFile of the fragment
1470 ((PreviewTextFragment
) details
).updateFile(file
);
1475 invalidateOptionsMenu();
1480 * Updates the view associated to the activity after the finish of an operation trying to
1483 * @param operation Removal operation performed.
1484 * @param result Result of the removal.
1486 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1487 RemoteOperationResult result
) {
1488 dismissLoadingDialog();
1490 Toast msg
= Toast
.makeText(this,
1491 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1495 if (result
.isSuccess()) {
1496 OCFile removedFile
= operation
.getFile();
1497 FileFragment second
= getSecondFragment();
1498 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1499 if (second
instanceof PreviewMediaFragment
) {
1500 ((PreviewMediaFragment
) second
).stopPreview(true
);
1502 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1503 cleanSecondFragment();
1505 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1506 refreshListOfFilesFragment();
1508 invalidateOptionsMenu();
1510 if (result
.isSslRecoverableException()) {
1511 mLastSslUntrustedServerResult
= result
;
1512 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1519 * Updates the view associated to the activity after the finish of an operation trying to move a
1522 * @param operation Move operation performed.
1523 * @param result Result of the move operation.
1525 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1526 RemoteOperationResult result
) {
1527 if (result
.isSuccess()) {
1528 dismissLoadingDialog();
1529 refreshListOfFilesFragment();
1531 dismissLoadingDialog();
1533 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1534 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1538 } catch (NotFoundException e
) {
1539 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1545 * Updates the view associated to the activity after the finish of an operation trying to copy a
1548 * @param operation Copy operation performed.
1549 * @param result Result of the copy operation.
1551 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1552 if (result
.isSuccess()) {
1553 dismissLoadingDialog();
1554 refreshListOfFilesFragment();
1556 dismissLoadingDialog();
1558 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1559 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1563 } catch (NotFoundException e
) {
1564 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1570 * Updates the view associated to the activity after the finish of an operation trying to rename
1573 * @param operation Renaming operation performed.
1574 * @param result Result of the renaming.
1576 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1577 RemoteOperationResult result
) {
1578 dismissLoadingDialog();
1579 OCFile renamedFile
= operation
.getFile();
1580 if (result
.isSuccess()) {
1581 FileFragment details
= getSecondFragment();
1582 if (details
!= null
) {
1583 if (details
instanceof FileDetailFragment
&&
1584 renamedFile
.equals(details
.getFile()) ) {
1585 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1586 showDetails(renamedFile
);
1588 } else if (details
instanceof PreviewMediaFragment
&&
1589 renamedFile
.equals(details
.getFile())) {
1590 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1591 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1592 int position
= ((PreviewMediaFragment
) details
).getPosition();
1593 startMediaPreview(renamedFile
, position
, true
);
1595 getFileOperationsHelper().openFile(renamedFile
);
1597 } else if (details
instanceof PreviewTextFragment
&&
1598 renamedFile
.equals(details
.getFile())) {
1599 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1600 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1601 startTextPreview(renamedFile
);
1603 getFileOperationsHelper().openFile(renamedFile
);
1608 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1609 refreshListOfFilesFragment();
1613 Toast msg
= Toast
.makeText(this,
1614 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1618 if (result
.isSslRecoverableException()) {
1619 mLastSslUntrustedServerResult
= result
;
1620 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1625 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1626 RemoteOperationResult result
) {
1627 if (result
.isSuccess()) {
1628 if (operation
.transferWasRequested()) {
1629 OCFile syncedFile
= operation
.getLocalFile();
1630 onTransferStateChanged(syncedFile
, true
, true
);
1631 invalidateOptionsMenu();
1632 refreshShowDetails();
1638 * Updates the view associated to the activity after the finish of an operation trying create a
1641 * @param operation Creation operation performed.
1642 * @param result Result of the creation.
1644 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1645 RemoteOperationResult result
) {
1646 if (result
.isSuccess()) {
1647 dismissLoadingDialog();
1648 refreshListOfFilesFragment();
1650 dismissLoadingDialog();
1652 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1653 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1657 } catch (NotFoundException e
) {
1658 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1668 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1669 refreshListOfFilesFragment();
1670 FileFragment details
= getSecondFragment();
1671 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1672 file
.equals(details
.getFile()) ) {
1673 if (downloading
|| uploading
) {
1674 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1676 if (!file
.fileExists()) {
1677 cleanSecondFragment();
1679 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1687 private void requestForDownload() {
1688 Account account
= getAccount();
1689 //if (!mWaitingToPreview.isDownloading()) {
1690 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1691 Intent i
= new Intent(this, FileDownloader
.class);
1692 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1693 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1699 private OCFile
getCurrentDir() {
1700 OCFile file
= getFile();
1702 if (file
.isFolder()) {
1704 } else if (getStorageManager() != null
) {
1705 String parentPath
= file
.getRemotePath().substring(0,
1706 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1707 return getStorageManager().getFileByPath(parentPath
);
1713 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1714 long currentSyncTime
= System
.currentTimeMillis();
1716 mSyncInProgress
= true
;
1718 // perform folder synchronization
1719 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1722 getFileOperationsHelper().isSharedSupported(),
1724 getStorageManager(),
1726 getApplicationContext()
1728 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1730 mProgressBar
.setIndeterminate(true
);
1732 setBackgroundText();
1736 * Show untrusted cert dialog
1738 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1739 // Show a dialog with the certificate info
1740 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1741 (CertificateCombinedException
) result
.getException());
1742 FragmentManager fm
= getSupportFragmentManager();
1743 FragmentTransaction ft
= fm
.beginTransaction();
1744 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1747 private void requestForDownload(OCFile file
) {
1748 Account account
= getAccount();
1749 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1750 Intent i
= new Intent(this, FileDownloader
.class);
1751 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1752 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1757 private void sendDownloadedFile() {
1758 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1759 mWaitingToSend
= null
;
1764 * Requests the download of the received {@link OCFile} , updates the UI
1765 * to monitor the download progress and prepares the activity to send the file
1766 * when the download finishes.
1768 * @param file {@link OCFile} to download and preview.
1770 public void startDownloadForSending(OCFile file
) {
1771 mWaitingToSend
= file
;
1772 requestForDownload(mWaitingToSend
);
1773 boolean hasSecondFragment
= (getSecondFragment() != null
);
1774 updateFragmentsVisibility(hasSecondFragment
);
1778 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1780 * @param file Image {@link OCFile} to show.
1782 public void startImagePreview(OCFile file
) {
1783 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1784 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1785 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1786 startActivity(showDetailsIntent
);
1790 * Stars the preview of an already down media {@link OCFile}.
1792 * @param file Media {@link OCFile} to preview.
1793 * @param startPlaybackPosition Media position where the playback will be started,
1795 * @param autoplay When 'true', the playback will start without user
1798 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1799 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1801 setSecondFragment(mediaFragment
);
1802 updateFragmentsVisibility(true
);
1803 updateActionBarTitleAndHomeButton(file
);
1808 * Stars the preview of a text file {@link OCFile}.
1810 * @param file Text {@link OCFile} to preview.
1812 public void startTextPreview(OCFile file
) {
1813 Bundle args
= new Bundle();
1814 args
.putParcelable(EXTRA_FILE
, file
);
1815 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1816 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1817 PreviewTextFragment
.class.getName(), args
);
1818 setSecondFragment(textPreviewFragment
);
1819 updateFragmentsVisibility(true
);
1820 //updateNavigationElementsInActionBar(file);
1825 * Requests the download of the received {@link OCFile} , updates the UI
1826 * to monitor the download progress and prepares the activity to preview
1827 * or open the file when the download finishes.
1829 * @param file {@link OCFile} to download and preview.
1831 public void startDownloadForPreview(OCFile file
) {
1832 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1833 setSecondFragment(detailFragment
);
1834 mWaitingToPreview
= file
;
1835 requestForDownload();
1836 updateFragmentsVisibility(true
);
1837 updateActionBarTitleAndHomeButton(file
);
1842 public void cancelTransference(OCFile file
) {
1843 getFileOperationsHelper().cancelTransference(file
);
1844 if (mWaitingToPreview
!= null
&&
1845 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1846 mWaitingToPreview
= null
;
1848 if (mWaitingToSend
!= null
&&
1849 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1850 mWaitingToSend
= null
;
1852 onTransferStateChanged(file
, false
, false
);
1856 public void onRefresh(boolean ignoreETag
) {
1857 refreshList(ignoreETag
);
1861 public void onRefresh() {
1865 private void refreshList(boolean ignoreETag
) {
1866 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1867 if (listOfFiles
!= null
) {
1868 OCFile folder
= listOfFiles
.getCurrentFile();
1869 if (folder
!= null
) {
1870 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1871 listDirectory(mFile);*/
1872 startSyncFolderOperation(folder
, ignoreETag
);
1877 private void sortByDate(boolean ascending
) {
1878 getListOfFilesFragment().sortByDate(ascending
);
1881 private void sortBySize(boolean ascending
) {
1882 getListOfFilesFragment().sortBySize(ascending
);
1885 private void sortByName(boolean ascending
) {
1886 getListOfFilesFragment().sortByName(ascending
);
1888 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1889 private void switchToGridView() {
1890 getListOfFilesFragment().switchToGridView();
1892 private void switchToListView() {
1893 getListOfFilesFragment().switchToListView();
1896 public void allFilesOption() {