2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.os
.Parcelable
;
30 import android
.support
.v7
.app
.AlertDialog
;
31 import android
.content
.BroadcastReceiver
;
32 import android
.content
.ComponentName
;
33 import android
.content
.ContentResolver
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.IntentFilter
;
38 import android
.content
.ServiceConnection
;
39 import android
.content
.SharedPreferences
;
40 import android
.content
.SyncRequest
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Build
;
45 import android
.os
.Bundle
;
46 import android
.os
.IBinder
;
47 import android
.preference
.PreferenceManager
;
48 import android
.provider
.OpenableColumns
;
49 import android
.support
.v4
.app
.Fragment
;
50 import android
.support
.v4
.app
.FragmentManager
;
51 import android
.support
.v4
.app
.FragmentTransaction
;
52 import android
.support
.v4
.content
.ContextCompat
;
53 import android
.support
.v4
.view
.GravityCompat
;
54 import android
.view
.Menu
;
55 import android
.view
.MenuInflater
;
56 import android
.view
.MenuItem
;
57 import android
.view
.View
;
58 import android
.widget
.ProgressBar
;
59 import android
.widget
.RelativeLayout
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import com
.owncloud
.android
.MainApp
;
64 import com
.owncloud
.android
.R
;
65 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
66 import com
.owncloud
.android
.datamodel
.OCFile
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
;
68 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
74 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
81 import com
.owncloud
.android
.operations
.CopyFileOperation
;
82 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 import com
.owncloud
.android
.utils
.FileStorageUtils
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
111 import java
.util
.ArrayList
;
112 import java
.util
.Iterator
;
115 * Displays, what files the user has available in his ownCloud.
118 public class FileDisplayActivity
extends HookActivity
119 implements FileFragment
.ContainerActivity
,
120 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
124 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
125 private UploadFinishReceiver mUploadFinishReceiver
;
126 private DownloadFinishReceiver mDownloadFinishReceiver
;
127 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
129 private boolean mDualPane
;
130 private View mLeftFragmentContainer
;
131 private View mRightFragmentContainer
;
132 private ProgressBar mProgressBar
;
134 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
135 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
136 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
138 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
140 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
141 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
142 public static final int ACTION_MOVE_FILES
= 3;
143 public static final int ACTION_COPY_FILES
= 4;
145 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
147 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
148 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
150 private OCFile mWaitingToPreview
;
152 private boolean mSyncInProgress
= false
;
154 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
155 public static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
156 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
157 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
159 private OCFile mWaitingToSend
;
160 private Menu mOptionsMenu
;
164 protected void onCreate(Bundle savedInstanceState
) {
165 Log_OC
.v(TAG
, "onCreate() start");
167 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
170 /// grant that FileObserverService is watching favorite files
171 if (savedInstanceState
== null
) {
172 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
173 startService(initObserversIntent
);
176 /// Load of saved instance state
177 if(savedInstanceState
!= null
) {
178 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
179 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
180 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
181 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
182 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
184 mWaitingToPreview
= null
;
185 mSyncInProgress
= false
;
186 mWaitingToSend
= null
;
191 // Inflate and set the layout view
192 setContentView(R
.layout
.files
);
197 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
198 mProgressBar
.setIndeterminateDrawable(
199 ContextCompat
.getDrawable(this,
200 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
202 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
203 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
204 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
205 if (savedInstanceState
== null
) {
206 createMinFragments();
210 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
211 // according to the official
214 // enable ActionBar app icon to behave as action to toggle nav drawer
215 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
216 getSupportActionBar().setHomeButtonEnabled(true
);
218 mProgressBar
.setIndeterminate(mSyncInProgress
);
219 // always AFTER setContentView(...) ; to work around bug in its implementation
223 Log_OC
.v(TAG
, "onCreate() end");
227 protected void onStart() {
228 Log_OC
.v(TAG
, "onStart() start");
230 Log_OC
.v(TAG
, "onStart() end");
234 protected void onDestroy() {
235 Log_OC
.v(TAG
, "onDestroy() start");
237 Log_OC
.v(TAG
, "onDestroy() end");
241 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
244 protected void onAccountSet(boolean stateWasRecovered
) {
245 super.onAccountSet(stateWasRecovered
);
246 if (getAccount() != null
) {
247 /// Check whether the 'main' OCFile handled by the Activity is contained in the
249 OCFile file
= getFile();
250 // get parent from path
251 String parentPath
= "";
253 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
254 // upload in progress - right now, files are not inserted in the local
255 // cache until the upload is successful get parent from path
256 parentPath
= file
.getRemotePath().substring(0,
257 file
.getRemotePath().lastIndexOf(file
.getFileName()));
258 if (getStorageManager().getFileByPath(parentPath
) == null
)
259 file
= null
; // not able to know the directory where the file is uploading
261 file
= getStorageManager().getFileByPath(file
.getRemotePath());
262 // currentDir = null if not in the current Account
266 // fall back to root folder
267 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
271 if (mAccountWasSet
) {
272 setUsernameInDrawer((RelativeLayout
) findViewById(R
.id
.left_drawer
), getAccount());
275 if (!stateWasRecovered
) {
276 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
277 initFragmentsWithFile();
278 if (file
.isFolder()) {
279 startSyncFolderOperation(file
, false
);
283 updateFragmentsVisibility(!file
.isFolder());
284 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 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(MainApp
.getOnlyOnDevice());
440 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
442 FileFragment secondFragment
= getSecondFragment();
443 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
444 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
445 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
446 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
447 OCFile fileInFragment
= detailsFragment
.getFile();
448 if (fileInFragment
!= null
&&
449 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
450 // the user browsed to other file ; forget the automatic preview
451 mWaitingToPreview
= null
;
453 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
454 // grant that the right panel updates the progress bar
455 detailsFragment
.listenForTransferProgress();
456 detailsFragment
.updateFileDetails(true
, false
);
458 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
459 // update the right panel
460 boolean detailsFragmentChanged
= false
;
463 mWaitingToPreview
= getStorageManager().getFileById(
464 mWaitingToPreview
.getFileId()); // update the file from database,
465 // for the local storage path
466 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
467 startMediaPreview(mWaitingToPreview
, 0, true
);
468 detailsFragmentChanged
= true
;
469 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
470 startTextPreview(mWaitingToPreview
);
471 detailsFragmentChanged
= true
;
473 getFileOperationsHelper().openFile(mWaitingToPreview
);
476 mWaitingToPreview
= null
;
478 if (!detailsFragmentChanged
) {
479 detailsFragment
.updateFileDetails(false
, (success
));
486 public boolean onPrepareOptionsMenu(Menu menu
) {
487 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
488 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
492 return super.onPrepareOptionsMenu(menu
);
496 public boolean onCreateOptionsMenu(Menu menu
) {
497 MenuInflater inflater
= getMenuInflater();
498 inflater
.inflate(R
.menu
.main_menu
, menu
);
499 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
502 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
511 public boolean onOptionsItemSelected(MenuItem item
) {
512 boolean retval
= true
;
513 switch (item
.getItemId()) {
514 case R
.id
.action_sync_account
: {
515 startSynchronization();
518 case android
.R
.id
.home
: {
519 FileFragment second
= getSecondFragment();
520 OCFile currentDir
= getCurrentDir();
521 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
522 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
523 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
524 (second
!= null
&& second
.getFile() != null
)) {
528 mDrawerLayout
.openDrawer(GravityCompat
.START
);
532 case R
.id
.action_sort
: {
533 SharedPreferences appPreferences
= PreferenceManager
534 .getDefaultSharedPreferences(this);
536 // Read sorting order, default to sort by name ascending
537 Integer sortOrder
= appPreferences
538 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
540 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
541 builder
.setTitle(R
.string
.actionbar_sort_title
)
542 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
543 new DialogInterface
.OnClickListener() {
544 public void onClick(DialogInterface dialog
, int which
) {
557 builder
.create().show();
560 case R
.id
.action_switch_view
:{
562 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
563 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
564 R
.drawable
.ic_view_module
));
565 DisplayUtils
.setViewMode(getFile(), false
);
568 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
569 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
570 R
.drawable
.ic_view_list
));
571 DisplayUtils
.setViewMode(getFile(), true
);
578 retval
= super.onOptionsItemSelected(item
);
583 public void createFolder() {
584 CreateFolderDialogFragment dialog
=
585 CreateFolderDialogFragment
.newInstance(getCurrentDir());
586 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
589 public void uploadLocalFilesSelected() {
590 Intent action
= new Intent(this, UploadFilesActivity
.class);
592 UploadFilesActivity
.EXTRA_ACCOUNT
,
595 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
598 public void uploadFromOtherAppsSelected() {
599 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
600 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
601 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
602 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
603 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
605 startActivityForResult(
606 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
607 ACTION_SELECT_CONTENT_FROM_APPS
611 private void startSynchronization() {
612 Log_OC
.d(TAG
, "Got to start sync");
613 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
614 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
615 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
616 // cancel the current synchronizations of any ownCloud account
617 Bundle bundle
= new Bundle();
618 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
619 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
620 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
621 MainApp
.getAuthority());
622 ContentResolver
.requestSync(
624 MainApp
.getAuthority(), bundle
);
626 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
627 MainApp
.getAuthority() + " with new API");
628 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
629 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
630 builder
.setExpedited(true
);
631 builder
.setManual(true
);
634 // Fix bug in Android Lollipop when you click on refresh the whole account
635 Bundle extras
= new Bundle();
636 builder
.setExtras(extras
);
638 SyncRequest request
= builder
.build();
639 ContentResolver
.requestSync(request
);
644 * Called, when the user selected something for uploading
647 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
649 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
651 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
652 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
653 //getClipData is only supported on api level 16+, Jelly Bean
654 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
655 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
656 Intent intent
= new Intent();
657 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
658 requestSimpleUpload(intent
, resultCode
);
661 requestSimpleUpload(data
, resultCode
);
663 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
664 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
665 requestMultipleUpload(data
, resultCode
);
667 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
668 final Intent fData
= data
;
669 final int fResultCode
= resultCode
;
670 getHandler().postDelayed(
674 requestMoveOperation(fData
, fResultCode
);
677 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
680 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
682 final Intent fData
= data
;
683 final int fResultCode
= resultCode
;
684 getHandler().postDelayed(
688 requestCopyOperation(fData
, fResultCode
);
691 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
695 super.onActivityResult(requestCode
, resultCode
, data
);
700 private void requestMultipleUpload(Intent data
, int resultCode
) {
701 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
702 if (filePaths
!= null
) {
703 String
[] remotePaths
= new String
[filePaths
.length
];
704 String remotePathBase
= getCurrentDir().getRemotePath();
705 for (int j
= 0; j
< remotePaths
.length
; j
++) {
706 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
709 Intent i
= new Intent(this, FileUploader
.class);
710 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
711 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
712 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
713 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
714 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
715 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
719 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
720 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
728 private void requestSimpleUpload(Intent data
, int resultCode
) {
729 String filePath
= null
;
730 String mimeType
= null
;
732 Uri selectedImageUri
= data
.getData();
735 mimeType
= getContentResolver().getType(selectedImageUri
);
737 String fileManagerString
= selectedImageUri
.getPath();
738 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
740 if (selectedImagePath
!= null
)
741 filePath
= selectedImagePath
;
743 filePath
= fileManagerString
;
745 } catch (Exception e
) {
746 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
747 "Intent.ACTION_GET_CONTENT", e
);
750 if (filePath
== null
) {
751 Log_OC
.e(TAG
, "Couldn't resolve path to file");
752 Toast t
= Toast
.makeText(
753 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
761 Intent i
= new Intent(this, FileUploader
.class);
762 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
763 OCFile currentDir
= getCurrentDir();
764 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
766 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
767 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
769 if (cursor
!= null
&& cursor
.moveToFirst()) {
770 String displayName
= cursor
.getString(cursor
.getColumnIndex(
771 OpenableColumns
.DISPLAY_NAME
));
772 Log_OC
.v(TAG
, "Display Name: " + displayName
);
774 displayName
.replace(File
.separatorChar
, '_');
775 displayName
.replace(File
.pathSeparatorChar
, '_');
776 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
779 // and what happens in case of error?; wrong target name for the upload
785 remotePath
+= new File(filePath
).getName();
788 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
789 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
790 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
791 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
792 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
793 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
798 * Request the operation for moving the file/folder from one path to another
800 * @param data Intent received
801 * @param resultCode Result code received
803 private void requestMoveOperation(Intent data
, int resultCode
) {
804 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
806 ArrayList
<OCFile
> files
= data
.getParcelableArrayListExtra(FolderPickerActivity
.EXTRA_FILES
);
808 for (Parcelable file
: files
) {
809 getFileOperationsHelper().moveFile(folderToMoveAt
, (OCFile
) file
);
814 * Request the operation for copying the file/folder from one path to another
816 * @param data Intent received
817 * @param resultCode Result code received
819 private void requestCopyOperation(Intent data
, int resultCode
) {
820 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
822 ArrayList
<OCFile
> files
= data
.getParcelableArrayListExtra(FolderPickerActivity
.EXTRA_FILES
);
824 for (Parcelable file
: files
) {
825 getFileOperationsHelper().copyFile(folderToMoveAt
, (OCFile
) file
);
830 public void onBackPressed() {
831 boolean isFabOpen
= isFabOpen();
832 boolean isDrawerOpen
= isDrawerOpen();
835 * BackPressed priority/hierarchy:
836 * 1. close drawer if opened
837 * 2. close FAB if open (only if drawer isn't open)
838 * 3. navigate up (only if drawer and FAB aren't open)
840 if(isDrawerOpen
&& isFabOpen
) {
841 // close drawer first
842 super.onBackPressed();
843 } else if(isDrawerOpen
&& !isFabOpen
) {
845 super.onBackPressed();
846 } else if (!isDrawerOpen
&& isFabOpen
) {
848 getListOfFilesFragment().getFabMain().collapse();
851 OCFileListFragment listOfFiles
= getListOfFilesFragment();
852 if (mDualPane
|| getSecondFragment() == null
) {
853 OCFile currentDir
= getCurrentDir();
854 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
858 if (listOfFiles
!= null
) { // should never be null, indeed
859 listOfFiles
.onBrowseUp();
862 if (listOfFiles
!= null
) { // should never be null, indeed
863 setFile(listOfFiles
.getCurrentFile());
865 cleanSecondFragment();
870 private void changeGridIcon(){
871 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
872 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
873 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
874 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
875 R
.drawable
.ic_view_list
));
877 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
878 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
879 R
.drawable
.ic_view_module
));
884 protected void onSaveInstanceState(Bundle outState
) {
885 // responsibility of restore is preferred in onCreate() before than in
886 // onRestoreInstanceState when there are Fragments involved
887 Log_OC
.v(TAG
, "onSaveInstanceState() start");
888 super.onSaveInstanceState(outState
);
889 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
890 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
891 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
892 // mRefreshSharesInProgress);
893 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
895 Log_OC
.v(TAG
, "onSaveInstanceState() end");
900 protected void onResume() {
901 Log_OC
.v(TAG
, "onResume() start");
903 // refresh Navigation Drawer account list
904 mNavigationDrawerAdapter
.updateAccountList();
906 // refresh list of files
907 refreshListOfFilesFragment();
909 // Listen for sync messages
910 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
911 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
912 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
913 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
914 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
915 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
916 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
917 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
918 // syncIntentFilter);
920 // Listen for upload messages
921 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
922 mUploadFinishReceiver
= new UploadFinishReceiver();
923 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
925 // Listen for download messages
926 IntentFilter downloadIntentFilter
= new IntentFilter(
927 FileDownloader
.getDownloadAddedMessage());
928 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
929 mDownloadFinishReceiver
= new DownloadFinishReceiver();
930 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
932 Log_OC
.v(TAG
, "onResume() end");
938 protected void onPause() {
939 Log_OC
.v(TAG
, "onPause() start");
940 if (mSyncBroadcastReceiver
!= null
) {
941 unregisterReceiver(mSyncBroadcastReceiver
);
942 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
943 mSyncBroadcastReceiver
= null
;
945 if (mUploadFinishReceiver
!= null
) {
946 unregisterReceiver(mUploadFinishReceiver
);
947 mUploadFinishReceiver
= null
;
949 if (mDownloadFinishReceiver
!= null
) {
950 unregisterReceiver(mDownloadFinishReceiver
);
951 mDownloadFinishReceiver
= null
;
955 Log_OC
.v(TAG
, "onPause() end");
958 public boolean isFabOpen() {
959 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
967 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
970 * {@link BroadcastReceiver} to enable syncing feedback in UI
973 public void onReceive(Context context
, Intent intent
) {
975 String event
= intent
.getAction();
976 Log_OC
.d(TAG
, "Received broadcast " + event
);
977 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
978 String synchFolderRemotePath
=
979 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
980 RemoteOperationResult synchResult
=
981 (RemoteOperationResult
)intent
.getSerializableExtra(
982 FileSyncAdapter
.EXTRA_RESULT
);
983 boolean sameAccount
= (getAccount() != null
&&
984 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
988 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
989 mSyncInProgress
= true
;
992 OCFile currentFile
= (getFile() == null
) ? null
:
993 getStorageManager().getFileByPath(getFile().getRemotePath());
994 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
995 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
997 if (currentDir
== null
) {
998 // current folder was removed from the server
999 Toast
.makeText( FileDisplayActivity
.this,
1002 sync_current_folder_was_removed
),
1003 synchFolderRemotePath
),
1010 if (currentFile
== null
&& !getFile().isFolder()) {
1011 // currently selected file was removed in the server, and now we
1013 cleanSecondFragment();
1014 currentFile
= currentDir
;
1017 if (synchFolderRemotePath
!= null
&&
1018 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1019 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1020 if (fileListFragment
!= null
) {
1021 fileListFragment
.listDirectory(currentDir
,
1022 MainApp
.getOnlyOnDevice());
1025 setFile(currentFile
);
1028 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
1029 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1032 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1033 equals(event
) &&/// TODO refactor and make common
1035 synchResult
!= null
&& !synchResult
.isSuccess() &&
1036 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1037 synchResult
.isIdPRedirection() ||
1038 (synchResult
.isException() && synchResult
.getException()
1039 instanceof AuthenticatorException
))) {
1043 OwnCloudClient client
;
1044 OwnCloudAccount ocAccount
=
1045 new OwnCloudAccount(getAccount(), context
);
1046 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1047 removeClientFor(ocAccount
));
1048 if (client
!= null
) {
1049 OwnCloudCredentials cred
= client
.getCredentials();
1051 AccountManager am
= AccountManager
.get(context
);
1052 if (cred
.authTokenExpires()) {
1053 am
.invalidateAuthToken(
1058 am
.clearPassword(getAccount());
1062 requestCredentialsUpdate();
1064 } catch (AccountNotFoundException e
) {
1065 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1070 removeStickyBroadcast(intent
);
1071 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1072 mProgressBar
.setIndeterminate(mSyncInProgress
);
1073 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1074 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1075 /*|| mRefreshSharesInProgress*/ //);
1077 setBackgroundText();
1081 if (synchResult
!= null
) {
1082 if (synchResult
.getCode().equals(
1083 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1084 mLastSslUntrustedServerResult
= synchResult
;
1087 } catch (RuntimeException e
) {
1088 // avoid app crashes after changing the serial id of RemoteOperationResult
1089 // in owncloud library with broadcast notifications pending to process
1090 removeStickyBroadcast(intent
);
1096 * Show a text message on screen view for notifying user if content is
1097 * loading or folder is empty
1099 private void setBackgroundText() {
1100 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1101 if (ocFileListFragment
!= null
) {
1102 int message
= R
.string
.file_list_loading
;
1103 if (!mSyncInProgress
) {
1104 // In case file list is empty
1105 message
= R
.string
.file_list_empty
;
1107 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1109 Log_OC
.e(TAG
, "OCFileListFragment is null");
1114 * Once the file upload has finished -> update view
1116 private class UploadFinishReceiver
extends BroadcastReceiver
{
1118 * Once the file upload has finished -> update view
1120 * @author David A. Velasco
1121 * {@link BroadcastReceiver} to enable upload feedback in UI
1124 public void onReceive(Context context
, Intent intent
) {
1126 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1127 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1128 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1129 OCFile currentDir
= getCurrentDir();
1130 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1131 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1133 if (sameAccount
&& isDescendant
) {
1134 String linkedToRemotePath
=
1135 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1136 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1137 refreshListOfFilesFragment();
1141 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1143 boolean renamedInUpload
= getFile().getRemotePath().
1144 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1145 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1147 FileFragment details
= getSecondFragment();
1148 boolean detailFragmentIsShown
= (details
!= null
&&
1149 details
instanceof FileDetailFragment
);
1151 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1152 if (uploadWasFine
) {
1153 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1155 if (renamedInUpload
) {
1156 String newName
= (new File(uploadedRemotePath
)).getName();
1157 Toast msg
= Toast
.makeText(
1160 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1165 if (uploadWasFine
|| getFile().fileExists()) {
1166 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1168 cleanSecondFragment();
1171 // Force the preview if the file is an image or text file
1172 if (uploadWasFine
) {
1173 OCFile ocFile
= getFile();
1174 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1175 startImagePreview(getFile());
1176 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1177 startTextPreview(ocFile
);
1178 // TODO what about other kind of previews?
1182 mProgressBar
.setIndeterminate(false
);
1184 if (intent
!= null
) {
1185 removeStickyBroadcast(intent
);
1191 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1192 private boolean isAscendant(String linkedToRemotePath
) {
1193 OCFile currentDir
= getCurrentDir();
1195 currentDir
!= null
&&
1196 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1205 * Class waiting for broadcast events from the {@link FileDownloader} service.
1207 * Updates the UI when a download is started or finished, provided that it is relevant for the
1210 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1213 public void onReceive(Context context
, Intent intent
) {
1215 boolean sameAccount
= isSameAccount(intent
);
1216 String downloadedRemotePath
=
1217 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1218 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1220 if (sameAccount
&& isDescendant
) {
1221 String linkedToRemotePath
=
1222 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1223 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1224 refreshListOfFilesFragment();
1226 refreshSecondFragment(
1228 downloadedRemotePath
,
1229 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1233 if (mWaitingToSend
!= null
) {
1235 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1236 if (mWaitingToSend
.isDown()) {
1237 sendDownloadedFile();
1242 if (intent
!= null
) {
1243 removeStickyBroadcast(intent
);
1248 private boolean isDescendant(String downloadedRemotePath
) {
1249 OCFile currentDir
= getCurrentDir();
1251 currentDir
!= null
&&
1252 downloadedRemotePath
!= null
&&
1253 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1257 private boolean isAscendant(String linkedToRemotePath
) {
1258 OCFile currentDir
= getCurrentDir();
1260 currentDir
!= null
&&
1261 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1265 private boolean isSameAccount(Intent intent
) {
1266 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1267 return (accountName
!= null
&& getAccount() != null
&&
1268 accountName
.equals(getAccount().name
));
1273 public void browseToRoot() {
1274 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1275 if (listOfFiles
!= null
) { // should never be null, indeed
1276 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1277 listOfFiles
.listDirectory(root
, MainApp
.getOnlyOnDevice());
1278 setFile(listOfFiles
.getCurrentFile());
1279 startSyncFolderOperation(root
, false
);
1281 cleanSecondFragment();
1288 * Updates action bar and second fragment, if in dual pane mode.
1291 public void onBrowsedDownTo(OCFile directory
) {
1293 cleanSecondFragment();
1295 startSyncFolderOperation(directory
, false
);
1297 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1300 if (DisplayUtils
.isGridView(directory
, getStorageManager())){
1308 * Shows the information of the {@link OCFile} received as a
1309 * parameter in the second fragment.
1311 * @param file {@link OCFile} whose details will be shown
1314 public void showDetails(OCFile file
) {
1315 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1316 setSecondFragment(detailFragment
);
1317 updateFragmentsVisibility(true
);
1318 updateActionBarTitleAndHomeButton(file
);
1323 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1325 // in dual pane mode, keep the focus of title an action bar in the current folder
1326 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1329 super.updateActionBarTitleAndHomeButton(chosenFile
);
1335 protected ServiceConnection
newTransferenceServiceConnection() {
1336 return new ListServiceConnection();
1340 * Defines callbacks for service binding, passed to bindService()
1342 private class ListServiceConnection
implements ServiceConnection
{
1345 public void onServiceConnected(ComponentName component
, IBinder service
) {
1346 if (component
.equals(new ComponentName(
1347 FileDisplayActivity
.this, FileDownloader
.class))) {
1348 Log_OC
.d(TAG
, "Download service connected");
1349 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1350 if (mWaitingToPreview
!= null
)
1351 if (getStorageManager() != null
) {
1354 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1355 if (!mWaitingToPreview
.isDown()) {
1356 requestForDownload();
1360 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1361 FileUploader
.class))) {
1362 Log_OC
.d(TAG
, "Upload service connected");
1363 mUploaderBinder
= (FileUploaderBinder
) service
;
1367 // a new chance to get the mDownloadBinder through
1368 // getFileDownloadBinder() - THIS IS A MESS
1369 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1370 if (listOfFiles
!= null
) {
1371 listOfFiles
.listDirectory(MainApp
.getOnlyOnDevice());
1373 FileFragment secondFragment
= getSecondFragment();
1374 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1375 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1376 detailFragment
.listenForTransferProgress();
1377 detailFragment
.updateFileDetails(false
, false
);
1382 public void onServiceDisconnected(ComponentName component
) {
1383 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1384 FileDownloader
.class))) {
1385 Log_OC
.d(TAG
, "Download service disconnected");
1386 mDownloaderBinder
= null
;
1387 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1388 FileUploader
.class))) {
1389 Log_OC
.d(TAG
, "Upload service disconnected");
1390 mUploaderBinder
= null
;
1396 public void onSavedCertificate() {
1397 startSyncFolderOperation(getCurrentDir(), false
);
1402 public void onFailedSavingCertificate() {
1403 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1404 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1406 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1410 public void onCancelCertificate() {
1415 * Updates the view associated to the activity after the finish of some operation over files
1416 * in the current account.
1418 * @param operation Removal operation performed.
1419 * @param result Result of the removal.
1422 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1423 super.onRemoteOperationFinish(operation
, result
);
1425 if (operation
instanceof RemoveFileOperation
) {
1426 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1428 } else if (operation
instanceof RenameFileOperation
) {
1429 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1431 } else if (operation
instanceof SynchronizeFileOperation
) {
1432 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1434 } else if (operation
instanceof CreateFolderOperation
) {
1435 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1437 } else if (operation
instanceof CreateShareOperation
) {
1438 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1440 } else if (operation
instanceof UnshareLinkOperation
) {
1441 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1443 } else if (operation
instanceof MoveFileOperation
) {
1444 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1446 } else if (operation
instanceof CopyFileOperation
) {
1447 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1451 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1452 RemoteOperationResult result
) {
1453 if (result
.isSuccess()) {
1454 refreshShowDetails();
1455 refreshListOfFilesFragment();
1459 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1460 RemoteOperationResult result
) {
1461 if (result
.isSuccess()) {
1462 refreshShowDetails();
1463 refreshListOfFilesFragment();
1465 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1466 cleanSecondFragment();
1467 refreshListOfFilesFragment();
1471 private void refreshShowDetails() {
1472 FileFragment details
= getSecondFragment();
1473 if (details
!= null
) {
1474 OCFile file
= details
.getFile();
1476 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1477 if (details
instanceof PreviewMediaFragment
) {
1478 // Refresh OCFile of the fragment
1479 ((PreviewMediaFragment
) details
).updateFile(file
);
1480 } else if (details
instanceof PreviewTextFragment
) {
1481 // Refresh OCFile of the fragment
1482 ((PreviewTextFragment
) details
).updateFile(file
);
1487 invalidateOptionsMenu();
1492 * Updates the view associated to the activity after the finish of an operation trying to
1495 * @param operation Removal operation performed.
1496 * @param result Result of the removal.
1498 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1499 RemoteOperationResult result
) {
1500 dismissLoadingDialog();
1502 Toast msg
= Toast
.makeText(this,
1503 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1507 if (result
.isSuccess()) {
1508 OCFile removedFile
= operation
.getFile();
1509 FileFragment second
= getSecondFragment();
1510 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1511 if (second
instanceof PreviewMediaFragment
) {
1512 ((PreviewMediaFragment
) second
).stopPreview(true
);
1514 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1515 cleanSecondFragment();
1517 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1518 refreshListOfFilesFragment();
1520 invalidateOptionsMenu();
1522 if (result
.isSslRecoverableException()) {
1523 mLastSslUntrustedServerResult
= result
;
1524 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1531 * Updates the view associated to the activity after the finish of an operation trying to move a
1534 * @param operation Move operation performed.
1535 * @param result Result of the move operation.
1537 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1538 RemoteOperationResult result
) {
1539 if (result
.isSuccess()) {
1540 dismissLoadingDialog();
1541 refreshListOfFilesFragment();
1543 dismissLoadingDialog();
1545 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1546 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1550 } catch (NotFoundException e
) {
1551 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1557 * Updates the view associated to the activity after the finish of an operation trying to copy a
1560 * @param operation Copy operation performed.
1561 * @param result Result of the copy operation.
1563 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1564 if (result
.isSuccess()) {
1565 dismissLoadingDialog();
1566 refreshListOfFilesFragment();
1568 dismissLoadingDialog();
1570 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1571 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1575 } catch (NotFoundException e
) {
1576 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1582 * Updates the view associated to the activity after the finish of an operation trying to rename
1585 * @param operation Renaming operation performed.
1586 * @param result Result of the renaming.
1588 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1589 RemoteOperationResult result
) {
1590 dismissLoadingDialog();
1591 OCFile renamedFile
= operation
.getFile();
1592 if (result
.isSuccess()) {
1593 FileFragment details
= getSecondFragment();
1594 if (details
!= null
) {
1595 if (details
instanceof FileDetailFragment
&&
1596 renamedFile
.equals(details
.getFile()) ) {
1597 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1598 showDetails(renamedFile
);
1600 } else if (details
instanceof PreviewMediaFragment
&&
1601 renamedFile
.equals(details
.getFile())) {
1602 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1603 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1604 int position
= ((PreviewMediaFragment
) details
).getPosition();
1605 startMediaPreview(renamedFile
, position
, true
);
1607 getFileOperationsHelper().openFile(renamedFile
);
1609 } else if (details
instanceof PreviewTextFragment
&&
1610 renamedFile
.equals(details
.getFile())) {
1611 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1612 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1613 startTextPreview(renamedFile
);
1615 getFileOperationsHelper().openFile(renamedFile
);
1620 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1621 refreshListOfFilesFragment();
1625 Toast msg
= Toast
.makeText(this,
1626 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1630 if (result
.isSslRecoverableException()) {
1631 mLastSslUntrustedServerResult
= result
;
1632 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1637 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1638 RemoteOperationResult result
) {
1639 if (result
.isSuccess()) {
1640 if (operation
.transferWasRequested()) {
1641 OCFile syncedFile
= operation
.getLocalFile();
1642 onTransferStateChanged(syncedFile
, true
, true
);
1643 invalidateOptionsMenu();
1644 refreshShowDetails();
1650 * Updates the view associated to the activity after the finish of an operation trying create a
1653 * @param operation Creation operation performed.
1654 * @param result Result of the creation.
1656 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1657 RemoteOperationResult result
) {
1658 if (result
.isSuccess()) {
1659 dismissLoadingDialog();
1660 refreshListOfFilesFragment();
1662 dismissLoadingDialog();
1664 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1665 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1669 } catch (NotFoundException e
) {
1670 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1680 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1681 refreshListOfFilesFragment();
1682 FileFragment details
= getSecondFragment();
1683 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1684 file
.equals(details
.getFile()) ) {
1685 if (downloading
|| uploading
) {
1686 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1688 if (!file
.fileExists()) {
1689 cleanSecondFragment();
1691 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1699 private void requestForDownload() {
1700 Account account
= getAccount();
1701 //if (!mWaitingToPreview.isDownloading()) {
1702 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1703 Intent i
= new Intent(this, FileDownloader
.class);
1704 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1705 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1711 private OCFile
getCurrentDir() {
1712 OCFile file
= getFile();
1714 if (file
.isFolder()) {
1716 } else if (getStorageManager() != null
) {
1717 String parentPath
= file
.getRemotePath().substring(0,
1718 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1719 return getStorageManager().getFileByPath(parentPath
);
1725 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1726 long currentSyncTime
= System
.currentTimeMillis();
1728 mSyncInProgress
= true
;
1730 // perform folder synchronization
1731 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1734 getFileOperationsHelper().isSharedSupported(),
1736 getStorageManager(),
1738 getApplicationContext()
1740 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1742 mProgressBar
.setIndeterminate(true
);
1744 setBackgroundText();
1748 * Show untrusted cert dialog
1750 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1751 // Show a dialog with the certificate info
1752 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1753 (CertificateCombinedException
) result
.getException());
1754 FragmentManager fm
= getSupportFragmentManager();
1755 FragmentTransaction ft
= fm
.beginTransaction();
1756 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1759 private void requestForDownload(OCFile file
) {
1760 Account account
= getAccount();
1761 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1762 Intent i
= new Intent(this, FileDownloader
.class);
1763 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1764 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1769 private void sendDownloadedFile() {
1770 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1771 mWaitingToSend
= null
;
1776 * Requests the download of the received {@link OCFile} , updates the UI
1777 * to monitor the download progress and prepares the activity to send the file
1778 * when the download finishes.
1780 * @param file {@link OCFile} to download and preview.
1782 public void startDownloadForSending(OCFile file
) {
1783 mWaitingToSend
= file
;
1784 requestForDownload(mWaitingToSend
);
1785 boolean hasSecondFragment
= (getSecondFragment() != null
);
1786 updateFragmentsVisibility(hasSecondFragment
);
1790 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1792 * @param file Image {@link OCFile} to show.
1794 public void startImagePreview(OCFile file
) {
1795 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1796 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1797 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1798 startActivity(showDetailsIntent
);
1802 * Stars the preview of an already down media {@link OCFile}.
1804 * @param file Media {@link OCFile} to preview.
1805 * @param startPlaybackPosition Media position where the playback will be started,
1807 * @param autoplay When 'true', the playback will start without user
1810 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1811 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1813 setSecondFragment(mediaFragment
);
1814 updateFragmentsVisibility(true
);
1815 updateActionBarTitleAndHomeButton(file
);
1820 * Stars the preview of a text file {@link OCFile}.
1822 * @param file Text {@link OCFile} to preview.
1824 public void startTextPreview(OCFile file
) {
1825 Bundle args
= new Bundle();
1826 args
.putParcelable(EXTRA_FILE
, file
);
1827 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1828 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1829 PreviewTextFragment
.class.getName(), args
);
1830 setSecondFragment(textPreviewFragment
);
1831 updateFragmentsVisibility(true
);
1832 //updateNavigationElementsInActionBar(file);
1837 * Requests the download of the received {@link OCFile} , updates the UI
1838 * to monitor the download progress and prepares the activity to preview
1839 * or open the file when the download finishes.
1841 * @param file {@link OCFile} to download and preview.
1843 public void startDownloadForPreview(OCFile file
) {
1844 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1845 setSecondFragment(detailFragment
);
1846 mWaitingToPreview
= file
;
1847 requestForDownload();
1848 updateFragmentsVisibility(true
);
1849 updateActionBarTitleAndHomeButton(file
);
1854 public void cancelTransference(OCFile file
) {
1855 getFileOperationsHelper().cancelTransference(file
);
1856 if (mWaitingToPreview
!= null
&&
1857 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1858 mWaitingToPreview
= null
;
1860 if (mWaitingToSend
!= null
&&
1861 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1862 mWaitingToSend
= null
;
1864 onTransferStateChanged(file
, false
, false
);
1868 public void onRefresh(boolean ignoreETag
) {
1869 refreshList(ignoreETag
);
1873 public void onRefresh() {
1877 private void refreshList(boolean ignoreETag
) {
1878 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1879 if (listOfFiles
!= null
) {
1880 OCFile folder
= listOfFiles
.getCurrentFile();
1881 if (folder
!= null
) {
1882 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1883 listDirectory(mFile);*/
1884 startSyncFolderOperation(folder
, ignoreETag
);
1889 private void sortByDate(boolean ascending
) {
1890 getListOfFilesFragment().sortByDate(ascending
);
1893 private void sortBySize(boolean ascending
) {
1894 getListOfFilesFragment().sortBySize(ascending
);
1897 private void sortByName(boolean ascending
) {
1898 getListOfFilesFragment().sortByName(ascending
);
1900 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1901 private void switchToGridView() {
1902 getListOfFilesFragment().switchToGridView();
1904 private void switchToListView() {
1905 getListOfFilesFragment().switchToListView();
1908 public void allFilesOption() {
1912 public void refreshDirectory(){
1913 getListOfFilesFragment().refreshDirectory();