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(), MainApp
.getOnlyOnDevice());
300 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
304 OCFile file
= getFile();
305 Fragment secondFragment
= chooseInitialSecondFragment(file
);
306 if (secondFragment
!= null
) {
307 setSecondFragment(secondFragment
);
308 updateFragmentsVisibility(true
);
309 updateActionBarTitleAndHomeButton(file
);
312 cleanSecondFragment();
313 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
314 startTextPreview(file
);
317 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
324 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
325 if (getAccount() == null
) {
326 Log_OC
.wtf(TAG
, "\t account is NULL");
328 if (getFile() == null
) {
329 Log_OC
.wtf(TAG
, "\t file is NULL");
334 private Fragment
chooseInitialSecondFragment(OCFile file
) {
335 Fragment secondFragment
= null
;
336 if (file
!= null
&& !file
.isFolder()) {
337 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
338 && file
.getLastSyncDateForProperties() > 0 // temporal fix
340 int startPlaybackPosition
=
341 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
343 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
344 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
345 startPlaybackPosition
, autoplay
);
347 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
348 secondFragment
= null
;
350 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
353 return secondFragment
;
358 * Replaces the second fragment managed by the activity with the received as
361 * Assumes never will be more than two fragments managed at the same time.
363 * @param fragment New second Fragment to set.
365 private void setSecondFragment(Fragment fragment
) {
366 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
367 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
368 transaction
.commit();
372 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
381 } else if (existsSecondFragment
) {
382 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
383 mLeftFragmentContainer
.setVisibility(View
.GONE
);
385 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
386 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
390 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
391 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
393 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
394 mRightFragmentContainer
.setVisibility(View
.GONE
);
400 private OCFileListFragment
getListOfFilesFragment() {
401 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
402 FileDisplayActivity
.TAG_LIST_OF_FILES
);
403 if (listOfFiles
!= null
) {
404 return (OCFileListFragment
) listOfFiles
;
406 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
410 public FileFragment
getSecondFragment() {
411 Fragment second
= getSupportFragmentManager().findFragmentByTag(
412 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
413 if (second
!= null
) {
414 return (FileFragment
) second
;
419 protected void cleanSecondFragment() {
420 Fragment second
= getSecondFragment();
421 if (second
!= null
) {
422 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
426 updateFragmentsVisibility(false
);
427 updateActionBarTitleAndHomeButton(null
);
430 protected void refreshListOfFilesFragment() {
431 OCFileListFragment fileListFragment
= getListOfFilesFragment();
432 if (fileListFragment
!= null
) {
433 fileListFragment
.listDirectory(MainApp
.getOnlyOnDevice());
437 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
439 FileFragment secondFragment
= getSecondFragment();
440 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
441 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
442 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
443 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
444 OCFile fileInFragment
= detailsFragment
.getFile();
445 if (fileInFragment
!= null
&&
446 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
447 // the user browsed to other file ; forget the automatic preview
448 mWaitingToPreview
= null
;
450 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
451 // grant that the right panel updates the progress bar
452 detailsFragment
.listenForTransferProgress();
453 detailsFragment
.updateFileDetails(true
, false
);
455 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
456 // update the right panel
457 boolean detailsFragmentChanged
= false
;
460 mWaitingToPreview
= getStorageManager().getFileById(
461 mWaitingToPreview
.getFileId()); // update the file from database,
462 // for the local storage path
463 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
464 startMediaPreview(mWaitingToPreview
, 0, true
);
465 detailsFragmentChanged
= true
;
466 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
467 startTextPreview(mWaitingToPreview
);
468 detailsFragmentChanged
= true
;
470 getFileOperationsHelper().openFile(mWaitingToPreview
);
473 mWaitingToPreview
= null
;
475 if (!detailsFragmentChanged
) {
476 detailsFragment
.updateFileDetails(false
, (success
));
483 public boolean onPrepareOptionsMenu(Menu menu
) {
484 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
485 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
486 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
487 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
489 return super.onPrepareOptionsMenu(menu
);
493 public boolean onCreateOptionsMenu(Menu menu
) {
494 MenuInflater inflater
= getMenuInflater();
495 inflater
.inflate(R
.menu
.main_menu
, menu
);
496 menu
.findItem(R
.id
.action_create_dir
).setVisible(false
);
499 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
508 public boolean onOptionsItemSelected(MenuItem item
) {
509 boolean retval
= true
;
510 switch (item
.getItemId()) {
511 case R
.id
.action_sync_account
: {
512 startSynchronization();
515 case android
.R
.id
.home
: {
516 FileFragment second
= getSecondFragment();
517 OCFile currentDir
= getCurrentDir();
518 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
519 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
520 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
521 (second
!= null
&& second
.getFile() != null
)) {
525 mDrawerLayout
.openDrawer(GravityCompat
.START
);
529 case R
.id
.action_sort
: {
530 SharedPreferences appPreferences
= PreferenceManager
531 .getDefaultSharedPreferences(this);
533 // Read sorting order, default to sort by name ascending
534 Integer sortOrder
= appPreferences
535 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
537 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
538 builder
.setTitle(R
.string
.actionbar_sort_title
)
539 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
540 new DialogInterface
.OnClickListener() {
541 public void onClick(DialogInterface dialog
, int which
) {
554 builder
.create().show();
557 case R
.id
.action_switch_view
:{
559 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
560 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
561 R
.drawable
.ic_view_module
));
562 DisplayUtils
.setViewMode(getFile(), false
);
565 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
566 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
567 R
.drawable
.ic_view_list
));
568 DisplayUtils
.setViewMode(getFile(), true
);
575 retval
= super.onOptionsItemSelected(item
);
580 public void createFolder() {
581 CreateFolderDialogFragment dialog
=
582 CreateFolderDialogFragment
.newInstance(getCurrentDir());
583 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
586 public void uploadLocalFilesSelected() {
587 Intent action
= new Intent(this, UploadFilesActivity
.class);
589 UploadFilesActivity
.EXTRA_ACCOUNT
,
592 startActivityForResult(action
, ACTION_SELECT_MULTIPLE_FILES
);
595 public void uploadFromOtherAppsSelected() {
596 Intent action
= new Intent(Intent
.ACTION_GET_CONTENT
);
597 action
= action
.setType("*/*").addCategory(Intent
.CATEGORY_OPENABLE
);
598 //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
599 if (Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN_MR2
) {
600 action
.putExtra(Intent
.EXTRA_ALLOW_MULTIPLE
, true
);
602 startActivityForResult(
603 Intent
.createChooser(action
, getString(R
.string
.upload_chooser_title
)),
604 ACTION_SELECT_CONTENT_FROM_APPS
608 private void startSynchronization() {
609 Log_OC
.d(TAG
, "Got to start sync");
610 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
611 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
612 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
613 // cancel the current synchronizations of any ownCloud account
614 Bundle bundle
= new Bundle();
615 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
616 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
617 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
618 MainApp
.getAuthority());
619 ContentResolver
.requestSync(
621 MainApp
.getAuthority(), bundle
);
623 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
624 MainApp
.getAuthority() + " with new API");
625 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
626 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
627 builder
.setExpedited(true
);
628 builder
.setManual(true
);
631 // Fix bug in Android Lollipop when you click on refresh the whole account
632 Bundle extras
= new Bundle();
633 builder
.setExtras(extras
);
635 SyncRequest request
= builder
.build();
636 ContentResolver
.requestSync(request
);
641 * Called, when the user selected something for uploading
644 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
646 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
648 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
649 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
650 //getClipData is only supported on api level 16+, Jelly Bean
651 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
652 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
653 Intent intent
= new Intent();
654 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
655 requestSimpleUpload(intent
, resultCode
);
658 requestSimpleUpload(data
, resultCode
);
660 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
661 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
662 requestMultipleUpload(data
, resultCode
);
664 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
665 final Intent fData
= data
;
666 final int fResultCode
= resultCode
;
667 getHandler().postDelayed(
671 requestMoveOperation(fData
, fResultCode
);
674 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
677 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
679 final Intent fData
= data
;
680 final int fResultCode
= resultCode
;
681 getHandler().postDelayed(
685 requestCopyOperation(fData
, fResultCode
);
688 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
692 super.onActivityResult(requestCode
, resultCode
, data
);
697 private void requestMultipleUpload(Intent data
, int resultCode
) {
698 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
699 if (filePaths
!= null
) {
700 String
[] remotePaths
= new String
[filePaths
.length
];
701 String remotePathBase
= getCurrentDir().getRemotePath();
702 for (int j
= 0; j
< remotePaths
.length
; j
++) {
703 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
706 Intent i
= new Intent(this, FileUploader
.class);
707 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
708 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
709 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
710 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
711 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
712 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
716 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
717 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
725 private void requestSimpleUpload(Intent data
, int resultCode
) {
726 String filePath
= null
;
727 String mimeType
= null
;
729 Uri selectedImageUri
= data
.getData();
732 mimeType
= getContentResolver().getType(selectedImageUri
);
734 String fileManagerString
= selectedImageUri
.getPath();
735 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
737 if (selectedImagePath
!= null
)
738 filePath
= selectedImagePath
;
740 filePath
= fileManagerString
;
742 } catch (Exception e
) {
743 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
744 "Intent.ACTION_GET_CONTENT", e
);
747 if (filePath
== null
) {
748 Log_OC
.e(TAG
, "Couldn't resolve path to file");
749 Toast t
= Toast
.makeText(
750 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
758 Intent i
= new Intent(this, FileUploader
.class);
759 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
760 OCFile currentDir
= getCurrentDir();
761 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
763 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
764 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
766 if (cursor
!= null
&& cursor
.moveToFirst()) {
767 String displayName
= cursor
.getString(cursor
.getColumnIndex(
768 OpenableColumns
.DISPLAY_NAME
));
769 Log_OC
.v(TAG
, "Display Name: " + displayName
);
771 displayName
.replace(File
.separatorChar
, '_');
772 displayName
.replace(File
.pathSeparatorChar
, '_');
773 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
776 // and what happens in case of error?; wrong target name for the upload
782 remotePath
+= new File(filePath
).getName();
785 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
786 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
787 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
788 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
789 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
790 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
795 * Request the operation for moving the file/folder from one path to another
797 * @param data Intent received
798 * @param resultCode Result code received
800 private void requestMoveOperation(Intent data
, int resultCode
) {
801 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
802 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
803 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
807 * Request the operation for copying the file/folder from one path to another
809 * @param data Intent received
810 * @param resultCode Result code received
812 private void requestCopyOperation(Intent data
, int resultCode
) {
813 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
814 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
815 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
819 public void onBackPressed() {
820 boolean isFabOpen
= isFabOpen();
821 boolean isDrawerOpen
= isDrawerOpen();
824 * BackPressed priority/hierarchy:
825 * 1. close drawer if opened
826 * 2. close FAB if open (only if drawer isn't open)
827 * 3. navigate up (only if drawer and FAB aren't open)
829 if(isDrawerOpen
&& isFabOpen
) {
830 // close drawer first
831 super.onBackPressed();
832 } else if(isDrawerOpen
&& !isFabOpen
) {
834 super.onBackPressed();
835 } else if (!isDrawerOpen
&& isFabOpen
) {
837 getListOfFilesFragment().getFabMain().collapse();
840 OCFileListFragment listOfFiles
= getListOfFilesFragment();
841 if (mDualPane
|| getSecondFragment() == null
) {
842 OCFile currentDir
= getCurrentDir();
843 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
847 if (listOfFiles
!= null
) { // should never be null, indeed
848 listOfFiles
.onBrowseUp();
851 if (listOfFiles
!= null
) { // should never be null, indeed
852 setFile(listOfFiles
.getCurrentFile());
854 cleanSecondFragment();
859 private void changeGridIcon(){
860 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
861 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
862 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
863 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
864 R
.drawable
.ic_view_list
));
866 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
867 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
868 R
.drawable
.ic_view_module
));
873 protected void onSaveInstanceState(Bundle outState
) {
874 // responsibility of restore is preferred in onCreate() before than in
875 // onRestoreInstanceState when there are Fragments involved
876 Log_OC
.v(TAG
, "onSaveInstanceState() start");
877 super.onSaveInstanceState(outState
);
878 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
879 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
880 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
881 // mRefreshSharesInProgress);
882 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
884 Log_OC
.v(TAG
, "onSaveInstanceState() end");
889 protected void onResume() {
890 Log_OC
.v(TAG
, "onResume() start");
892 // refresh Navigation Drawer account list
893 mNavigationDrawerAdapter
.updateAccountList();
895 // refresh list of files
896 refreshListOfFilesFragment();
898 // Listen for sync messages
899 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
900 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
901 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
902 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
903 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
904 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
905 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
906 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
907 // syncIntentFilter);
909 // Listen for upload messages
910 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
911 mUploadFinishReceiver
= new UploadFinishReceiver();
912 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
914 // Listen for download messages
915 IntentFilter downloadIntentFilter
= new IntentFilter(
916 FileDownloader
.getDownloadAddedMessage());
917 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
918 mDownloadFinishReceiver
= new DownloadFinishReceiver();
919 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
921 Log_OC
.v(TAG
, "onResume() end");
927 protected void onPause() {
928 Log_OC
.v(TAG
, "onPause() start");
929 if (mSyncBroadcastReceiver
!= null
) {
930 unregisterReceiver(mSyncBroadcastReceiver
);
931 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
932 mSyncBroadcastReceiver
= null
;
934 if (mUploadFinishReceiver
!= null
) {
935 unregisterReceiver(mUploadFinishReceiver
);
936 mUploadFinishReceiver
= null
;
938 if (mDownloadFinishReceiver
!= null
) {
939 unregisterReceiver(mDownloadFinishReceiver
);
940 mDownloadFinishReceiver
= null
;
944 Log_OC
.v(TAG
, "onPause() end");
947 public boolean isFabOpen() {
948 if(getListOfFilesFragment() != null
&& getListOfFilesFragment().getFabMain() != null
&& getListOfFilesFragment().getFabMain().isExpanded()) {
956 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
959 * {@link BroadcastReceiver} to enable syncing feedback in UI
962 public void onReceive(Context context
, Intent intent
) {
964 String event
= intent
.getAction();
965 Log_OC
.d(TAG
, "Received broadcast " + event
);
966 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
967 String synchFolderRemotePath
=
968 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
969 RemoteOperationResult synchResult
=
970 (RemoteOperationResult
)intent
.getSerializableExtra(
971 FileSyncAdapter
.EXTRA_RESULT
);
972 boolean sameAccount
= (getAccount() != null
&&
973 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
977 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
978 mSyncInProgress
= true
;
981 OCFile currentFile
= (getFile() == null
) ? null
:
982 getStorageManager().getFileByPath(getFile().getRemotePath());
983 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
984 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
986 if (currentDir
== null
) {
987 // current folder was removed from the server
988 Toast
.makeText( FileDisplayActivity
.this,
991 sync_current_folder_was_removed
),
992 synchFolderRemotePath
),
999 if (currentFile
== null
&& !getFile().isFolder()) {
1000 // currently selected file was removed in the server, and now we
1002 cleanSecondFragment();
1003 currentFile
= currentDir
;
1006 if (synchFolderRemotePath
!= null
&&
1007 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
1008 OCFileListFragment fileListFragment
= getListOfFilesFragment();
1009 if (fileListFragment
!= null
) {
1010 fileListFragment
.listDirectory(currentDir
,
1011 MainApp
.getOnlyOnDevice());
1014 setFile(currentFile
);
1017 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
1018 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
1021 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1022 equals(event
) &&/// TODO refactor and make common
1024 synchResult
!= null
&& !synchResult
.isSuccess() &&
1025 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1026 synchResult
.isIdPRedirection() ||
1027 (synchResult
.isException() && synchResult
.getException()
1028 instanceof AuthenticatorException
))) {
1032 OwnCloudClient client
;
1033 OwnCloudAccount ocAccount
=
1034 new OwnCloudAccount(getAccount(), context
);
1035 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1036 removeClientFor(ocAccount
));
1037 if (client
!= null
) {
1038 OwnCloudCredentials cred
= client
.getCredentials();
1040 AccountManager am
= AccountManager
.get(context
);
1041 if (cred
.authTokenExpires()) {
1042 am
.invalidateAuthToken(
1047 am
.clearPassword(getAccount());
1051 requestCredentialsUpdate();
1053 } catch (AccountNotFoundException e
) {
1054 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1059 removeStickyBroadcast(intent
);
1060 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1061 mProgressBar
.setIndeterminate(mSyncInProgress
);
1062 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1063 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1064 /*|| mRefreshSharesInProgress*/ //);
1066 setBackgroundText();
1070 if (synchResult
!= null
) {
1071 if (synchResult
.getCode().equals(
1072 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1073 mLastSslUntrustedServerResult
= synchResult
;
1076 } catch (RuntimeException e
) {
1077 // avoid app crashes after changing the serial id of RemoteOperationResult
1078 // in owncloud library with broadcast notifications pending to process
1079 removeStickyBroadcast(intent
);
1085 * Show a text message on screen view for notifying user if content is
1086 * loading or folder is empty
1088 private void setBackgroundText() {
1089 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1090 if (ocFileListFragment
!= null
) {
1091 int message
= R
.string
.file_list_loading
;
1092 if (!mSyncInProgress
) {
1093 // In case file list is empty
1094 message
= R
.string
.file_list_empty
;
1096 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1098 Log_OC
.e(TAG
, "OCFileListFragment is null");
1103 * Once the file upload has finished -> update view
1105 private class UploadFinishReceiver
extends BroadcastReceiver
{
1107 * Once the file upload has finished -> update view
1109 * @author David A. Velasco
1110 * {@link BroadcastReceiver} to enable upload feedback in UI
1113 public void onReceive(Context context
, Intent intent
) {
1115 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1116 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1117 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1118 OCFile currentDir
= getCurrentDir();
1119 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1120 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1122 if (sameAccount
&& isDescendant
) {
1123 refreshListOfFilesFragment();
1126 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1128 boolean renamedInUpload
= getFile().getRemotePath().
1129 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1130 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1132 FileFragment details
= getSecondFragment();
1133 boolean detailFragmentIsShown
= (details
!= null
&&
1134 details
instanceof FileDetailFragment
);
1136 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1137 if (uploadWasFine
) {
1138 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1140 if (renamedInUpload
) {
1141 String newName
= (new File(uploadedRemotePath
)).getName();
1142 Toast msg
= Toast
.makeText(
1145 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1150 if (uploadWasFine
|| getFile().fileExists()) {
1151 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1153 cleanSecondFragment();
1156 // Force the preview if the file is an image or text file
1157 if (uploadWasFine
) {
1158 OCFile ocFile
= getFile();
1159 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1160 startImagePreview(getFile());
1161 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1162 startTextPreview(ocFile
);
1163 // TODO what about other kind of previews?
1167 mProgressBar
.setIndeterminate(false
);
1169 if (intent
!= null
) {
1170 removeStickyBroadcast(intent
);
1180 * Class waiting for broadcast events from the {@link FileDownloader} service.
1182 * Updates the UI when a download is started or finished, provided that it is relevant for the
1185 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1187 //int refreshCounter = 0;
1189 public void onReceive(Context context
, Intent intent
) {
1191 boolean sameAccount
= isSameAccount(context
, intent
);
1192 String downloadedRemotePath
=
1193 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1194 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1196 if (sameAccount
&& isDescendant
) {
1197 String linkedToRemotePath
=
1198 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1199 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1200 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1201 refreshListOfFilesFragment();
1203 refreshSecondFragment(
1205 downloadedRemotePath
,
1206 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1210 if (mWaitingToSend
!= null
) {
1212 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1213 if (mWaitingToSend
.isDown()) {
1214 sendDownloadedFile();
1219 if (intent
!= null
) {
1220 removeStickyBroadcast(intent
);
1225 private boolean isDescendant(String downloadedRemotePath
) {
1226 OCFile currentDir
= getCurrentDir();
1228 currentDir
!= null
&&
1229 downloadedRemotePath
!= null
&&
1230 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1234 private boolean isAscendant(String linkedToRemotePath
) {
1235 OCFile currentDir
= getCurrentDir();
1237 currentDir
!= null
&&
1238 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1242 private boolean isSameAccount(Context context
, Intent intent
) {
1243 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1244 return (accountName
!= null
&& getAccount() != null
&&
1245 accountName
.equals(getAccount().name
));
1250 public void browseToRoot() {
1251 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1252 if (listOfFiles
!= null
) { // should never be null, indeed
1253 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1254 listOfFiles
.listDirectory(root
, MainApp
.getOnlyOnDevice());
1255 setFile(listOfFiles
.getCurrentFile());
1256 startSyncFolderOperation(root
, false
);
1258 cleanSecondFragment();
1265 * Updates action bar and second fragment, if in dual pane mode.
1268 public void onBrowsedDownTo(OCFile directory
) {
1270 cleanSecondFragment();
1272 startSyncFolderOperation(directory
, false
);
1274 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1277 if (DisplayUtils
.isGridView(directory
, getStorageManager())){
1285 * Shows the information of the {@link OCFile} received as a
1286 * parameter in the second fragment.
1288 * @param file {@link OCFile} whose details will be shown
1291 public void showDetails(OCFile file
) {
1292 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1293 setSecondFragment(detailFragment
);
1294 updateFragmentsVisibility(true
);
1295 updateActionBarTitleAndHomeButton(file
);
1300 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1302 // in dual pane mode, keep the focus of title an action bar in the current folder
1303 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1306 super.updateActionBarTitleAndHomeButton(chosenFile
);
1312 protected ServiceConnection
newTransferenceServiceConnection() {
1313 return new ListServiceConnection();
1317 * Defines callbacks for service binding, passed to bindService()
1319 private class ListServiceConnection
implements ServiceConnection
{
1322 public void onServiceConnected(ComponentName component
, IBinder service
) {
1323 if (component
.equals(new ComponentName(
1324 FileDisplayActivity
.this, FileDownloader
.class))) {
1325 Log_OC
.d(TAG
, "Download service connected");
1326 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1327 if (mWaitingToPreview
!= null
)
1328 if (getStorageManager() != null
) {
1331 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1332 if (!mWaitingToPreview
.isDown()) {
1333 requestForDownload();
1337 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1338 FileUploader
.class))) {
1339 Log_OC
.d(TAG
, "Upload service connected");
1340 mUploaderBinder
= (FileUploaderBinder
) service
;
1344 // a new chance to get the mDownloadBinder through
1345 // getFileDownloadBinder() - THIS IS A MESS
1346 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1347 if (listOfFiles
!= null
) {
1348 listOfFiles
.listDirectory(MainApp
.getOnlyOnDevice());
1350 FileFragment secondFragment
= getSecondFragment();
1351 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1352 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1353 detailFragment
.listenForTransferProgress();
1354 detailFragment
.updateFileDetails(false
, false
);
1359 public void onServiceDisconnected(ComponentName component
) {
1360 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1361 FileDownloader
.class))) {
1362 Log_OC
.d(TAG
, "Download service disconnected");
1363 mDownloaderBinder
= null
;
1364 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1365 FileUploader
.class))) {
1366 Log_OC
.d(TAG
, "Upload service disconnected");
1367 mUploaderBinder
= null
;
1373 public void onSavedCertificate() {
1374 startSyncFolderOperation(getCurrentDir(), false
);
1379 public void onFailedSavingCertificate() {
1380 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1381 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1383 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1387 public void onCancelCertificate() {
1392 * Updates the view associated to the activity after the finish of some operation over files
1393 * in the current account.
1395 * @param operation Removal operation performed.
1396 * @param result Result of the removal.
1399 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1400 super.onRemoteOperationFinish(operation
, result
);
1402 if (operation
instanceof RemoveFileOperation
) {
1403 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1405 } else if (operation
instanceof RenameFileOperation
) {
1406 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1408 } else if (operation
instanceof SynchronizeFileOperation
) {
1409 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1411 } else if (operation
instanceof CreateFolderOperation
) {
1412 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1414 } else if (operation
instanceof CreateShareOperation
) {
1415 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1417 } else if (operation
instanceof UnshareLinkOperation
) {
1418 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1420 } else if (operation
instanceof MoveFileOperation
) {
1421 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1423 } else if (operation
instanceof CopyFileOperation
) {
1424 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1428 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1429 RemoteOperationResult result
) {
1430 if (result
.isSuccess()) {
1431 refreshShowDetails();
1432 refreshListOfFilesFragment();
1436 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1437 RemoteOperationResult result
) {
1438 if (result
.isSuccess()) {
1439 refreshShowDetails();
1440 refreshListOfFilesFragment();
1442 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1443 cleanSecondFragment();
1444 refreshListOfFilesFragment();
1448 private void refreshShowDetails() {
1449 FileFragment details
= getSecondFragment();
1450 if (details
!= null
) {
1451 OCFile file
= details
.getFile();
1453 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1454 if (details
instanceof PreviewMediaFragment
) {
1455 // Refresh OCFile of the fragment
1456 ((PreviewMediaFragment
) details
).updateFile(file
);
1457 } else if (details
instanceof PreviewTextFragment
) {
1458 // Refresh OCFile of the fragment
1459 ((PreviewTextFragment
) details
).updateFile(file
);
1464 invalidateOptionsMenu();
1469 * Updates the view associated to the activity after the finish of an operation trying to
1472 * @param operation Removal operation performed.
1473 * @param result Result of the removal.
1475 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1476 RemoteOperationResult result
) {
1477 dismissLoadingDialog();
1479 Toast msg
= Toast
.makeText(this,
1480 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1484 if (result
.isSuccess()) {
1485 OCFile removedFile
= operation
.getFile();
1486 FileFragment second
= getSecondFragment();
1487 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1488 if (second
instanceof PreviewMediaFragment
) {
1489 ((PreviewMediaFragment
) second
).stopPreview(true
);
1491 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1492 cleanSecondFragment();
1494 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1495 refreshListOfFilesFragment();
1497 invalidateOptionsMenu();
1499 if (result
.isSslRecoverableException()) {
1500 mLastSslUntrustedServerResult
= result
;
1501 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1508 * Updates the view associated to the activity after the finish of an operation trying to move a
1511 * @param operation Move operation performed.
1512 * @param result Result of the move operation.
1514 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1515 RemoteOperationResult result
) {
1516 if (result
.isSuccess()) {
1517 dismissLoadingDialog();
1518 refreshListOfFilesFragment();
1520 dismissLoadingDialog();
1522 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1523 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1527 } catch (NotFoundException e
) {
1528 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1534 * Updates the view associated to the activity after the finish of an operation trying to copy a
1537 * @param operation Copy operation performed.
1538 * @param result Result of the copy operation.
1540 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1541 if (result
.isSuccess()) {
1542 dismissLoadingDialog();
1543 refreshListOfFilesFragment();
1545 dismissLoadingDialog();
1547 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1548 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1552 } catch (NotFoundException e
) {
1553 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1559 * Updates the view associated to the activity after the finish of an operation trying to rename
1562 * @param operation Renaming operation performed.
1563 * @param result Result of the renaming.
1565 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1566 RemoteOperationResult result
) {
1567 dismissLoadingDialog();
1568 OCFile renamedFile
= operation
.getFile();
1569 if (result
.isSuccess()) {
1570 FileFragment details
= getSecondFragment();
1571 if (details
!= null
) {
1572 if (details
instanceof FileDetailFragment
&&
1573 renamedFile
.equals(details
.getFile()) ) {
1574 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1575 showDetails(renamedFile
);
1577 } else if (details
instanceof PreviewMediaFragment
&&
1578 renamedFile
.equals(details
.getFile())) {
1579 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1580 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1581 int position
= ((PreviewMediaFragment
) details
).getPosition();
1582 startMediaPreview(renamedFile
, position
, true
);
1584 getFileOperationsHelper().openFile(renamedFile
);
1586 } else if (details
instanceof PreviewTextFragment
&&
1587 renamedFile
.equals(details
.getFile())) {
1588 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1589 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1590 startTextPreview(renamedFile
);
1592 getFileOperationsHelper().openFile(renamedFile
);
1597 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1598 refreshListOfFilesFragment();
1602 Toast msg
= Toast
.makeText(this,
1603 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1607 if (result
.isSslRecoverableException()) {
1608 mLastSslUntrustedServerResult
= result
;
1609 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1614 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1615 RemoteOperationResult result
) {
1616 if (result
.isSuccess()) {
1617 if (operation
.transferWasRequested()) {
1618 OCFile syncedFile
= operation
.getLocalFile();
1619 onTransferStateChanged(syncedFile
, true
, true
);
1620 invalidateOptionsMenu();
1621 refreshShowDetails();
1627 * Updates the view associated to the activity after the finish of an operation trying create a
1630 * @param operation Creation operation performed.
1631 * @param result Result of the creation.
1633 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1634 RemoteOperationResult result
) {
1635 if (result
.isSuccess()) {
1636 dismissLoadingDialog();
1637 refreshListOfFilesFragment();
1639 dismissLoadingDialog();
1641 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1642 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1646 } catch (NotFoundException e
) {
1647 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1657 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1658 refreshListOfFilesFragment();
1659 FileFragment details
= getSecondFragment();
1660 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1661 file
.equals(details
.getFile()) ) {
1662 if (downloading
|| uploading
) {
1663 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1665 if (!file
.fileExists()) {
1666 cleanSecondFragment();
1668 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1676 private void requestForDownload() {
1677 Account account
= getAccount();
1678 //if (!mWaitingToPreview.isDownloading()) {
1679 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1680 Intent i
= new Intent(this, FileDownloader
.class);
1681 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1682 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1688 private OCFile
getCurrentDir() {
1689 OCFile file
= getFile();
1691 if (file
.isFolder()) {
1693 } else if (getStorageManager() != null
) {
1694 String parentPath
= file
.getRemotePath().substring(0,
1695 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1696 return getStorageManager().getFileByPath(parentPath
);
1702 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1703 long currentSyncTime
= System
.currentTimeMillis();
1705 mSyncInProgress
= true
;
1707 // perform folder synchronization
1708 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1711 getFileOperationsHelper().isSharedSupported(),
1713 getStorageManager(),
1715 getApplicationContext()
1717 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1719 mProgressBar
.setIndeterminate(true
);
1721 setBackgroundText();
1725 * Show untrusted cert dialog
1727 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1728 // Show a dialog with the certificate info
1729 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1730 (CertificateCombinedException
) result
.getException());
1731 FragmentManager fm
= getSupportFragmentManager();
1732 FragmentTransaction ft
= fm
.beginTransaction();
1733 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1736 private void requestForDownload(OCFile file
) {
1737 Account account
= getAccount();
1738 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1739 Intent i
= new Intent(this, FileDownloader
.class);
1740 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1741 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1746 private void sendDownloadedFile() {
1747 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1748 mWaitingToSend
= null
;
1753 * Requests the download of the received {@link OCFile} , updates the UI
1754 * to monitor the download progress and prepares the activity to send the file
1755 * when the download finishes.
1757 * @param file {@link OCFile} to download and preview.
1759 public void startDownloadForSending(OCFile file
) {
1760 mWaitingToSend
= file
;
1761 requestForDownload(mWaitingToSend
);
1762 boolean hasSecondFragment
= (getSecondFragment() != null
);
1763 updateFragmentsVisibility(hasSecondFragment
);
1767 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1769 * @param file Image {@link OCFile} to show.
1771 public void startImagePreview(OCFile file
) {
1772 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1773 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1774 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1775 startActivity(showDetailsIntent
);
1779 * Stars the preview of an already down media {@link OCFile}.
1781 * @param file Media {@link OCFile} to preview.
1782 * @param startPlaybackPosition Media position where the playback will be started,
1784 * @param autoplay When 'true', the playback will start without user
1787 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1788 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1790 setSecondFragment(mediaFragment
);
1791 updateFragmentsVisibility(true
);
1792 updateActionBarTitleAndHomeButton(file
);
1797 * Stars the preview of a text file {@link OCFile}.
1799 * @param file Text {@link OCFile} to preview.
1801 public void startTextPreview(OCFile file
) {
1802 Bundle args
= new Bundle();
1803 args
.putParcelable(EXTRA_FILE
, file
);
1804 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1805 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1806 PreviewTextFragment
.class.getName(), args
);
1807 setSecondFragment(textPreviewFragment
);
1808 updateFragmentsVisibility(true
);
1809 //updateNavigationElementsInActionBar(file);
1814 * Requests the download of the received {@link OCFile} , updates the UI
1815 * to monitor the download progress and prepares the activity to preview
1816 * or open the file when the download finishes.
1818 * @param file {@link OCFile} to download and preview.
1820 public void startDownloadForPreview(OCFile file
) {
1821 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1822 setSecondFragment(detailFragment
);
1823 mWaitingToPreview
= file
;
1824 requestForDownload();
1825 updateFragmentsVisibility(true
);
1826 updateActionBarTitleAndHomeButton(file
);
1831 public void cancelTransference(OCFile file
) {
1832 getFileOperationsHelper().cancelTransference(file
);
1833 if (mWaitingToPreview
!= null
&&
1834 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1835 mWaitingToPreview
= null
;
1837 if (mWaitingToSend
!= null
&&
1838 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1839 mWaitingToSend
= null
;
1841 onTransferStateChanged(file
, false
, false
);
1845 public void onRefresh(boolean ignoreETag
) {
1846 refreshList(ignoreETag
);
1850 public void onRefresh() {
1854 private void refreshList(boolean ignoreETag
) {
1855 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1856 if (listOfFiles
!= null
) {
1857 OCFile folder
= listOfFiles
.getCurrentFile();
1858 if (folder
!= null
) {
1859 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1860 listDirectory(mFile);*/
1861 startSyncFolderOperation(folder
, ignoreETag
);
1866 private void sortByDate(boolean ascending
) {
1867 getListOfFilesFragment().sortByDate(ascending
);
1870 private void sortBySize(boolean ascending
) {
1871 getListOfFilesFragment().sortBySize(ascending
);
1874 private void sortByName(boolean ascending
) {
1875 getListOfFilesFragment().sortByName(ascending
);
1877 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1878 private void switchToGridView() {
1879 getListOfFilesFragment().switchToGridView();
1881 private void switchToListView() {
1882 getListOfFilesFragment().switchToListView();
1885 public void allFilesOption() {
1889 public void refreshDirectory(){
1890 getListOfFilesFragment().refreshDirectory();