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
.CreateFolderOperation
;
81 import com
.owncloud
.android
.operations
.CreateShareOperation
;
82 import com
.owncloud
.android
.operations
.MoveFileOperation
;
83 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
88 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
89 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
90 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
95 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
98 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
102 import com
.owncloud
.android
.utils
.DisplayUtils
;
103 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
104 import com
.owncloud
.android
.utils
.FileStorageUtils
;
105 import com
.owncloud
.android
.utils
.UriUtils
;
111 * Displays, what files the user has available in his ownCloud.
114 public class FileDisplayActivity
extends HookActivity
115 implements FileFragment
.ContainerActivity
,
116 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
118 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
119 private UploadFinishReceiver mUploadFinishReceiver
;
120 private DownloadFinishReceiver mDownloadFinishReceiver
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
123 private boolean mDualPane
;
124 private View mLeftFragmentContainer
;
125 private View mRightFragmentContainer
;
126 private ProgressBar mProgressBar
;
128 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
129 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
130 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
132 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
134 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
135 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
136 public static final int ACTION_MOVE_FILES
= 3;
138 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
140 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
141 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
143 private OCFile mWaitingToPreview
;
145 private boolean mSyncInProgress
= false
;
147 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
148 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
149 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
150 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
152 private OCFile mWaitingToSend
;
153 private Menu mOptionsMenu
;
157 protected void onCreate(Bundle savedInstanceState
) {
158 Log_OC
.v(TAG
, "onCreate() start");
160 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
163 /// grant that FileObserverService is watching favorite files
164 if (savedInstanceState
== null
) {
165 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
166 startService(initObserversIntent
);
169 /// Load of saved instance state
170 if(savedInstanceState
!= null
) {
171 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
172 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
173 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
174 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
175 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
178 mWaitingToPreview
= null
;
179 mSyncInProgress
= false
;
180 mWaitingToSend
= null
;
185 // Inflate and set the layout view
186 setContentView(R
.layout
.files
);
191 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
192 mProgressBar
.setIndeterminateDrawable(
193 ContextCompat
.getDrawable(this,
194 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
196 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
197 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
198 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
199 if (savedInstanceState
== null
) {
200 createMinFragments();
204 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
205 // according to the official
208 // enable ActionBar app icon to behave as action to toggle nav drawer
209 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
210 getSupportActionBar().setHomeButtonEnabled(true
);
212 mProgressBar
.setIndeterminate(mSyncInProgress
);
213 // always AFTER setContentView(...) ; to work around bug in its implementation
217 Log_OC
.v(TAG
, "onCreate() end");
221 protected void onStart() {
222 Log_OC
.v(TAG
, "onStart() start");
224 Log_OC
.v(TAG
, "onStart() end");
228 protected void onDestroy() {
229 Log_OC
.v(TAG
, "onDestroy() start");
231 Log_OC
.v(TAG
, "onDestroy() end");
235 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
238 protected void onAccountSet(boolean stateWasRecovered
) {
239 super.onAccountSet(stateWasRecovered
);
240 if (getAccount() != null
) {
241 /// Check whether the 'main' OCFile handled by the Activity is contained in the
243 OCFile file
= getFile();
244 // get parent from path
245 String parentPath
= "";
247 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
248 // upload in progress - right now, files are not inserted in the local
249 // cache until the upload is successful get parent from path
250 parentPath
= file
.getRemotePath().substring(0,
251 file
.getRemotePath().lastIndexOf(file
.getFileName()));
252 if (getStorageManager().getFileByPath(parentPath
) == null
)
253 file
= null
; // not able to know the directory where the file is uploading
255 file
= getStorageManager().getFileByPath(file
.getRemotePath());
256 // currentDir = null if not in the current Account
260 // fall back to root folder
261 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
265 if (mAccountWasSet
) {
266 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
267 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
268 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
269 int lastAtPos
= getAccount().name
.lastIndexOf("@");
270 username
.setText(getAccount().name
.substring(0, lastAtPos
));
274 if (!stateWasRecovered
) {
275 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
276 initFragmentsWithFile();
277 if (file
.isFolder()) {
278 startSyncFolderOperation(file
, false
);
282 updateFragmentsVisibility(!file
.isFolder());
283 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());
302 // TODO Enable when "On Device" is recovered
303 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
305 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
309 OCFile file
= getFile();
310 Fragment secondFragment
= chooseInitialSecondFragment(file
);
311 if (secondFragment
!= null
) {
312 setSecondFragment(secondFragment
);
313 updateFragmentsVisibility(true
);
314 updateActionBarTitleAndHomeButton(file
);
317 cleanSecondFragment();
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
);
351 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
354 return secondFragment
;
359 * Replaces the second fragment managed by the activity with the received as
362 * Assumes never will be more than two fragments managed at the same time.
364 * @param fragment New second Fragment to set.
366 private void setSecondFragment(Fragment fragment
) {
367 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
368 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
369 transaction
.commit();
373 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
375 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
376 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
378 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
379 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
382 } else if (existsSecondFragment
) {
383 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
384 mLeftFragmentContainer
.setVisibility(View
.GONE
);
386 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
391 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
392 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
394 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
395 mRightFragmentContainer
.setVisibility(View
.GONE
);
401 private OCFileListFragment
getListOfFilesFragment() {
402 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
403 FileDisplayActivity
.TAG_LIST_OF_FILES
);
404 if (listOfFiles
!= null
) {
405 return (OCFileListFragment
)listOfFiles
;
407 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
411 public FileFragment
getSecondFragment() {
412 Fragment second
= getSupportFragmentManager().findFragmentByTag(
413 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
414 if (second
!= null
) {
415 return (FileFragment
)second
;
420 protected void cleanSecondFragment() {
421 Fragment second
= getSecondFragment();
422 if (second
!= null
) {
423 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
427 updateFragmentsVisibility(false
);
428 updateActionBarTitleAndHomeButton(null
);
431 protected void refreshListOfFilesFragment() {
432 OCFileListFragment fileListFragment
= getListOfFilesFragment();
433 if (fileListFragment
!= null
) {
434 fileListFragment
.listDirectory();
435 // TODO Enable when "On Device" is recovered ?
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
;
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_upload
).setVisible(!drawerOpen
);
486 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
487 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
488 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
491 return super.onPrepareOptionsMenu(menu
);
495 public boolean onCreateOptionsMenu(Menu menu
) {
496 MenuInflater inflater
= getMenuInflater();
497 inflater
.inflate(R
.menu
.main_menu
, menu
);
500 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
509 public boolean onOptionsItemSelected(MenuItem item
) {
510 boolean retval
= true
;
511 switch (item
.getItemId()) {
512 case R
.id
.action_create_dir
: {
513 CreateFolderDialogFragment dialog
=
514 CreateFolderDialogFragment
.newInstance(getCurrentDir());
515 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
518 case R
.id
.action_sync_account
: {
519 startSynchronization();
522 case R
.id
.action_upload
: {
523 UploadSourceDialogFragment dialog
=
524 UploadSourceDialogFragment
.newInstance(getAccount());
525 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
529 case android
.R
.id
.home
: {
530 FileFragment second
= getSecondFragment();
531 OCFile currentDir
= getCurrentDir();
532 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
533 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
534 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
535 (second
!= null
&& second
.getFile() != null
)) {
539 mDrawerLayout
.openDrawer(GravityCompat
.START
);
543 case R
.id
.action_sort
: {
544 SharedPreferences appPreferences
= PreferenceManager
545 .getDefaultSharedPreferences(this);
547 // Read sorting order, default to sort by name ascending
548 Integer sortOrder
= appPreferences
549 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
551 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
552 builder
.setTitle(R
.string
.actionbar_sort_title
)
553 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
554 new DialogInterface
.OnClickListener() {
555 public void onClick(DialogInterface dialog
, int which
) {
568 builder
.create().show();
571 case R
.id
.action_switch_view
:{
573 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
574 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
575 R
.drawable
.ic_view_module
));
576 DisplayUtils
.setViewMode(getFile(), false
);
579 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
580 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
581 R
.drawable
.ic_view_list
));
582 DisplayUtils
.setViewMode(getFile(), true
);
589 retval
= super.onOptionsItemSelected(item
);
594 private void startSynchronization() {
595 Log_OC
.d(TAG
, "Got to start sync");
596 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
597 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
598 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
599 // cancel the current synchronizations of any ownCloud account
600 Bundle bundle
= new Bundle();
601 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
602 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
603 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
604 MainApp
.getAuthority());
605 ContentResolver
.requestSync(
607 MainApp
.getAuthority(), bundle
);
609 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
610 MainApp
.getAuthority() + " with new API");
611 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
612 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
613 builder
.setExpedited(true
);
614 builder
.setManual(true
);
617 // Fix bug in Android Lollipop when you click on refresh the whole account
618 Bundle extras
= new Bundle();
619 builder
.setExtras(extras
);
621 SyncRequest request
= builder
.build();
622 ContentResolver
.requestSync(request
);
627 * Called, when the user selected something for uploading
630 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
632 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
634 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
635 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
636 //getClipData is only supported on api level 16+, Jelly Bean
637 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
638 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
639 Intent intent
= new Intent();
640 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
641 requestSimpleUpload(intent
, resultCode
);
644 requestSimpleUpload(data
, resultCode
);
646 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
647 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
648 requestMultipleUpload(data
, resultCode
);
650 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
652 final Intent fData
= data
;
653 final int fResultCode
= resultCode
;
654 getHandler().postDelayed(
658 requestMoveOperation(fData
, fResultCode
);
661 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
665 super.onActivityResult(requestCode
, resultCode
, data
);
670 private void requestMultipleUpload(Intent data
, int resultCode
) {
671 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
672 if (filePaths
!= null
) {
673 String
[] remotePaths
= new String
[filePaths
.length
];
674 String remotePathBase
= getCurrentDir().getRemotePath();
675 for (int j
= 0; j
< remotePaths
.length
; j
++) {
676 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
679 Intent i
= new Intent(this, FileUploader
.class);
680 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
681 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
682 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
683 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
684 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
685 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
689 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
690 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
698 private void requestSimpleUpload(Intent data
, int resultCode
) {
699 String filePath
= null
;
700 String mimeType
= null
;
702 Uri selectedImageUri
= data
.getData();
705 mimeType
= getContentResolver().getType(selectedImageUri
);
707 String fileManagerString
= selectedImageUri
.getPath();
708 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
710 if (selectedImagePath
!= null
)
711 filePath
= selectedImagePath
;
713 filePath
= fileManagerString
;
715 } catch (Exception e
) {
716 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
717 "Intent.ACTION_GET_CONTENT", e
);
720 if (filePath
== null
) {
721 Log_OC
.e(TAG
, "Couldn't resolve path to file");
722 Toast t
= Toast
.makeText(
723 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
731 Intent i
= new Intent(this, FileUploader
.class);
732 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
733 OCFile currentDir
= getCurrentDir();
734 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
736 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
737 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
739 if (cursor
!= null
&& cursor
.moveToFirst()) {
740 String displayName
= cursor
.getString(cursor
.getColumnIndex(
741 OpenableColumns
.DISPLAY_NAME
));
742 Log_OC
.v(TAG
, "Display Name: " + displayName
);
744 displayName
.replace(File
.separatorChar
, '_');
745 displayName
.replace(File
.pathSeparatorChar
, '_');
746 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
749 // and what happens in case of error?; wrong target name for the upload
755 remotePath
+= new File(filePath
).getName();
758 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
759 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
760 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
761 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
762 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
763 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
768 * Request the operation for moving the file/folder from one path to another
770 * @param data Intent received
771 * @param resultCode Result code received
773 private void requestMoveOperation(Intent data
, int resultCode
) {
774 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
775 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
776 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
780 public void onBackPressed() {
781 if (!isDrawerOpen()){
782 OCFileListFragment listOfFiles
= getListOfFilesFragment();
783 if (mDualPane
|| getSecondFragment() == null
) {
784 OCFile currentDir
= getCurrentDir();
785 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
789 if (listOfFiles
!= null
) { // should never be null, indeed
790 listOfFiles
.onBrowseUp();
793 if (listOfFiles
!= null
) { // should never be null, indeed
794 setFile(listOfFiles
.getCurrentFile());
796 cleanSecondFragment();
800 super.onBackPressed();
804 private void changeGridIcon(){
805 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
806 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
807 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
808 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
809 R
.drawable
.ic_view_list
));
811 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
812 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
813 R
.drawable
.ic_view_module
));
818 protected void onSaveInstanceState(Bundle outState
) {
819 // responsibility of restore is preferred in onCreate() before than in
820 // onRestoreInstanceState when there are Fragments involved
821 Log_OC
.v(TAG
, "onSaveInstanceState() start");
822 super.onSaveInstanceState(outState
);
823 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
824 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
825 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
826 // mRefreshSharesInProgress);
827 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
829 Log_OC
.v(TAG
, "onSaveInstanceState() end");
835 protected void onResume() {
836 Log_OC
.v(TAG
, "onResume() start");
839 // refresh Navigation Drawer account list
840 mNavigationDrawerAdapter
.updateAccountList();
843 // refresh list of files
844 refreshListOfFilesFragment();
846 // Listen for sync messages
847 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
848 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
849 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
850 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
851 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
852 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
853 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
854 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
855 // syncIntentFilter);
857 // Listen for upload messages
858 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
859 mUploadFinishReceiver
= new UploadFinishReceiver();
860 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
862 // Listen for download messages
863 IntentFilter downloadIntentFilter
= new IntentFilter(
864 FileDownloader
.getDownloadAddedMessage());
865 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
866 mDownloadFinishReceiver
= new DownloadFinishReceiver();
867 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
869 Log_OC
.v(TAG
, "onResume() end");
874 protected void onPause() {
875 Log_OC
.v(TAG
, "onPause() start");
876 if (mSyncBroadcastReceiver
!= null
) {
877 unregisterReceiver(mSyncBroadcastReceiver
);
878 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
879 mSyncBroadcastReceiver
= null
;
881 if (mUploadFinishReceiver
!= null
) {
882 unregisterReceiver(mUploadFinishReceiver
);
883 mUploadFinishReceiver
= null
;
885 if (mDownloadFinishReceiver
!= null
) {
886 unregisterReceiver(mDownloadFinishReceiver
);
887 mDownloadFinishReceiver
= null
;
891 Log_OC
.v(TAG
, "onPause() end");
895 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
898 * {@link BroadcastReceiver} to enable syncing feedback in UI
901 public void onReceive(Context context
, Intent intent
) {
903 String event
= intent
.getAction();
904 Log_OC
.d(TAG
, "Received broadcast " + event
);
905 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
906 String synchFolderRemotePath
=
907 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
908 RemoteOperationResult synchResult
=
909 (RemoteOperationResult
)intent
.getSerializableExtra(
910 FileSyncAdapter
.EXTRA_RESULT
);
911 boolean sameAccount
= (getAccount() != null
&&
912 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
916 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
917 mSyncInProgress
= true
;
920 OCFile currentFile
= (getFile() == null
) ? null
:
921 getStorageManager().getFileByPath(getFile().getRemotePath());
922 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
923 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
925 if (currentDir
== null
) {
926 // current folder was removed from the server
927 Toast
.makeText( FileDisplayActivity
.this,
930 sync_current_folder_was_removed
),
931 synchFolderRemotePath
),
937 if (currentFile
== null
&& !getFile().isFolder()) {
938 // currently selected file was removed in the server, and now we
940 cleanSecondFragment();
941 currentFile
= currentDir
;
944 if (synchFolderRemotePath
!= null
&&
945 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
946 OCFileListFragment fileListFragment
= getListOfFilesFragment();
947 if (fileListFragment
!= null
) {
948 fileListFragment
.listDirectory();
949 // TODO Enable when "On Device" is recovered ?
950 // fileListFragment.listDirectory(currentDir,
951 // MainApp.getOnlyOnDevice());
954 setFile(currentFile
);
957 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
958 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
961 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
963 /// TODO refactor and make common
964 synchResult
!= null
&& !synchResult
.isSuccess() &&
965 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
966 synchResult
.isIdPRedirection() ||
967 (synchResult
.isException() && synchResult
.getException()
968 instanceof AuthenticatorException
))) {
972 OwnCloudClient client
;
973 OwnCloudAccount ocAccount
=
974 new OwnCloudAccount(getAccount(), context
);
975 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
976 removeClientFor(ocAccount
));
978 if (client
!= null
) {
979 OwnCloudCredentials cred
= client
.getCredentials();
981 AccountManager am
= AccountManager
.get(context
);
982 if (cred
.authTokenExpires()) {
983 am
.invalidateAuthToken(
988 am
.clearPassword(getAccount());
992 requestCredentialsUpdate();
994 } catch (AccountNotFoundException e
) {
995 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1000 removeStickyBroadcast(intent
);
1001 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1002 mProgressBar
.setIndeterminate(mSyncInProgress
);
1003 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1004 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1005 /*|| mRefreshSharesInProgress*/ //);
1007 setBackgroundText();
1011 if (synchResult
!= null
) {
1012 if (synchResult
.getCode().equals(
1013 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1014 mLastSslUntrustedServerResult
= synchResult
;
1017 } catch (RuntimeException e
) {
1018 // avoid app crashes after changing the serial id of RemoteOperationResult
1019 // in owncloud library with broadcast notifications pending to process
1020 removeStickyBroadcast(intent
);
1026 * Show a text message on screen view for notifying user if content is
1027 * loading or folder is empty
1029 private void setBackgroundText() {
1030 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1031 if (ocFileListFragment
!= null
) {
1032 int message
= R
.string
.file_list_loading
;
1033 if (!mSyncInProgress
) {
1034 // In case file list is empty
1035 message
= R
.string
.file_list_empty
;
1037 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1039 Log_OC
.e(TAG
, "OCFileListFragment is null");
1044 * Once the file upload has finished -> update view
1046 private class UploadFinishReceiver
extends BroadcastReceiver
{
1048 * Once the file upload has finished -> update view
1049 * @author David A. Velasco
1050 * {@link BroadcastReceiver} to enable upload feedback in UI
1053 public void onReceive(Context context
, Intent intent
) {
1055 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1056 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1057 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1058 OCFile currentDir
= getCurrentDir();
1059 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1060 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1062 if (sameAccount
&& isDescendant
) {
1063 refreshListOfFilesFragment();
1066 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1068 boolean renamedInUpload
= getFile().getRemotePath().
1069 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1070 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1072 FileFragment details
= getSecondFragment();
1073 boolean detailFragmentIsShown
= (details
!= null
&&
1074 details
instanceof FileDetailFragment
);
1076 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1077 if (uploadWasFine
) {
1078 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1080 if (renamedInUpload
) {
1081 String newName
= (new File(uploadedRemotePath
)).getName();
1082 Toast msg
= Toast
.makeText(
1085 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1090 if (uploadWasFine
|| getFile().fileExists()) {
1091 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1093 cleanSecondFragment();
1096 // Force the preview if the file is an image
1097 if (uploadWasFine
&& PreviewImageFragment
.canBePreviewed(getFile())) {
1098 startImagePreview(getFile());
1099 } // TODO what about other kind of previews?
1102 mProgressBar
.setIndeterminate(false
);
1104 if (intent
!= null
) {
1105 removeStickyBroadcast(intent
);
1115 * Class waiting for broadcast events from the {@link FileDownloader} service.
1117 * Updates the UI when a download is started or finished, provided that it is relevant for the
1120 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1122 //int refreshCounter = 0;
1124 public void onReceive(Context context
, Intent intent
) {
1126 boolean sameAccount
= isSameAccount(context
, intent
);
1127 String downloadedRemotePath
=
1128 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1129 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1131 if (sameAccount
&& isDescendant
) {
1132 String linkedToRemotePath
=
1133 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1134 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1135 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1136 refreshListOfFilesFragment();
1138 refreshSecondFragment(
1140 downloadedRemotePath
,
1141 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1145 if (mWaitingToSend
!= null
) {
1147 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1148 if (mWaitingToSend
.isDown()) {
1149 sendDownloadedFile();
1154 if (intent
!= null
) {
1155 removeStickyBroadcast(intent
);
1160 private boolean isDescendant(String downloadedRemotePath
) {
1161 OCFile currentDir
= getCurrentDir();
1163 currentDir
!= null
&&
1164 downloadedRemotePath
!= null
&&
1165 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1169 private boolean isAscendant(String linkedToRemotePath
) {
1170 OCFile currentDir
= getCurrentDir();
1172 currentDir
!= null
&&
1173 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1177 private boolean isSameAccount(Context context
, Intent intent
) {
1178 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1179 return (accountName
!= null
&& getAccount() != null
&&
1180 accountName
.equals(getAccount().name
));
1185 public void browseToRoot() {
1186 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1187 if (listOfFiles
!= null
) { // should never be null, indeed
1188 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1189 listOfFiles
.listDirectory(root
);
1190 // TODO Enable when "On Device" is recovered ?
1191 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1192 setFile(listOfFiles
.getCurrentFile());
1193 startSyncFolderOperation(root
, false
);
1195 cleanSecondFragment();
1203 * Updates action bar and second fragment, if in dual pane mode.
1206 public void onBrowsedDownTo(OCFile directory
) {
1208 cleanSecondFragment();
1210 startSyncFolderOperation(directory
, false
);
1212 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1215 if (DisplayUtils
.isGridView(directory
, getStorageManager())){
1223 * Shows the information of the {@link OCFile} received as a
1224 * parameter in the second fragment.
1226 * @param file {@link OCFile} whose details will be shown
1229 public void showDetails(OCFile file
) {
1230 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1231 setSecondFragment(detailFragment
);
1232 updateFragmentsVisibility(true
);
1233 updateActionBarTitleAndHomeButton(file
);
1238 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1240 // in dual pane mode, keep the focus of title an action bar in the current folder
1241 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1244 super.updateActionBarTitleAndHomeButton(chosenFile
);
1250 protected ServiceConnection
newTransferenceServiceConnection() {
1251 return new ListServiceConnection();
1254 /** Defines callbacks for service binding, passed to bindService() */
1255 private class ListServiceConnection
implements ServiceConnection
{
1258 public void onServiceConnected(ComponentName component
, IBinder service
) {
1259 if (component
.equals(new ComponentName(
1260 FileDisplayActivity
.this, FileDownloader
.class))) {
1261 Log_OC
.d(TAG
, "Download service connected");
1262 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1263 if (mWaitingToPreview
!= null
)
1264 if (getStorageManager() != null
) {
1267 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1268 if (!mWaitingToPreview
.isDown()) {
1269 requestForDownload();
1273 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1274 FileUploader
.class))) {
1275 Log_OC
.d(TAG
, "Upload service connected");
1276 mUploaderBinder
= (FileUploaderBinder
) service
;
1280 // a new chance to get the mDownloadBinder through
1281 // getFileDownloadBinder() - THIS IS A MESS
1282 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1283 if (listOfFiles
!= null
) {
1284 listOfFiles
.listDirectory();
1285 // TODO Enable when "On Device" is recovered ?
1286 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1288 FileFragment secondFragment
= getSecondFragment();
1289 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1290 FileDetailFragment detailFragment
= (FileDetailFragment
)secondFragment
;
1291 detailFragment
.listenForTransferProgress();
1292 detailFragment
.updateFileDetails(false
, false
);
1297 public void onServiceDisconnected(ComponentName component
) {
1298 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1299 FileDownloader
.class))) {
1300 Log_OC
.d(TAG
, "Download service disconnected");
1301 mDownloaderBinder
= null
;
1302 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1303 FileUploader
.class))) {
1304 Log_OC
.d(TAG
, "Upload service disconnected");
1305 mUploaderBinder
= null
;
1311 public void onSavedCertificate() {
1312 startSyncFolderOperation(getCurrentDir(), false
);
1317 public void onFailedSavingCertificate() {
1318 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1319 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1321 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1325 public void onCancelCertificate() {
1330 * Updates the view associated to the activity after the finish of some operation over files
1331 * in the current account.
1333 * @param operation Removal operation performed.
1334 * @param result Result of the removal.
1337 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1338 super.onRemoteOperationFinish(operation
, result
);
1340 if (operation
instanceof RemoveFileOperation
) {
1341 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1343 } else if (operation
instanceof RenameFileOperation
) {
1344 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1346 } else if (operation
instanceof SynchronizeFileOperation
) {
1347 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1349 } else if (operation
instanceof CreateFolderOperation
) {
1350 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
1352 } else if (operation
instanceof CreateShareOperation
) {
1353 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1355 } else if (operation
instanceof UnshareLinkOperation
) {
1356 onUnshareLinkOperationFinish((UnshareLinkOperation
)operation
, result
);
1358 } else if (operation
instanceof MoveFileOperation
) {
1359 onMoveFileOperationFinish((MoveFileOperation
)operation
, result
);
1365 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1366 RemoteOperationResult result
) {
1367 if (result
.isSuccess()) {
1368 refreshShowDetails();
1369 refreshListOfFilesFragment();
1374 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1375 RemoteOperationResult result
) {
1376 if (result
.isSuccess()) {
1377 refreshShowDetails();
1378 refreshListOfFilesFragment();
1380 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1381 cleanSecondFragment();
1382 refreshListOfFilesFragment();
1386 private void refreshShowDetails() {
1387 FileFragment details
= getSecondFragment();
1388 if (details
!= null
) {
1389 OCFile file
= details
.getFile();
1391 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1392 if (details
instanceof PreviewMediaFragment
) {
1393 // Refresh OCFile of the fragment
1394 ((PreviewMediaFragment
) details
).updateFile(file
);
1399 invalidateOptionsMenu();
1404 * Updates the view associated to the activity after the finish of an operation trying to
1407 * @param operation Removal operation performed.
1408 * @param result Result of the removal.
1410 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1411 RemoteOperationResult result
) {
1412 dismissLoadingDialog();
1414 Toast msg
= Toast
.makeText(this,
1415 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1419 if (result
.isSuccess()) {
1420 OCFile removedFile
= operation
.getFile();
1421 FileFragment second
= getSecondFragment();
1422 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1423 if (second
instanceof PreviewMediaFragment
) {
1424 ((PreviewMediaFragment
)second
).stopPreview(true
);
1426 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1427 cleanSecondFragment();
1429 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())) {
1430 refreshListOfFilesFragment();
1432 invalidateOptionsMenu();
1434 if (result
.isSslRecoverableException()) {
1435 mLastSslUntrustedServerResult
= result
;
1436 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1443 * Updates the view associated to the activity after the finish of an operation trying to move a
1446 * @param operation Move operation performed.
1447 * @param result Result of the move operation.
1449 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1450 RemoteOperationResult result
) {
1451 if (result
.isSuccess()) {
1452 dismissLoadingDialog();
1453 refreshListOfFilesFragment();
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 } catch (NotFoundException e
) {
1463 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1470 * Updates the view associated to the activity after the finish of an operation trying to rename
1473 * @param operation Renaming operation performed.
1474 * @param result Result of the renaming.
1476 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1477 RemoteOperationResult result
) {
1478 dismissLoadingDialog();
1479 OCFile renamedFile
= operation
.getFile();
1480 if (result
.isSuccess()) {
1481 FileFragment details
= getSecondFragment();
1482 if (details
!= null
) {
1483 if (details
instanceof FileDetailFragment
&&
1484 renamedFile
.equals(details
.getFile()) ) {
1485 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1486 showDetails(renamedFile
);
1488 } else if (details
instanceof PreviewMediaFragment
&&
1489 renamedFile
.equals(details
.getFile())) {
1490 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1491 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1492 int position
= ((PreviewMediaFragment
)details
).getPosition();
1493 startMediaPreview(renamedFile
, position
, true
);
1495 getFileOperationsHelper().openFile(renamedFile
);
1500 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1501 refreshListOfFilesFragment();
1505 Toast msg
= Toast
.makeText(this,
1506 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1510 if (result
.isSslRecoverableException()) {
1511 mLastSslUntrustedServerResult
= result
;
1512 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1517 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1518 RemoteOperationResult result
) {
1519 if (result
.isSuccess()) {
1520 if (operation
.transferWasRequested()) {
1521 OCFile syncedFile
= operation
.getLocalFile();
1522 onTransferStateChanged(syncedFile
, true
, true
);
1523 invalidateOptionsMenu();
1529 * Updates the view associated to the activity after the finish of an operation trying create a
1532 * @param operation Creation operation performed.
1533 * @param result Result of the creation.
1535 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1536 RemoteOperationResult result
) {
1537 if (result
.isSuccess()) {
1538 dismissLoadingDialog();
1539 refreshListOfFilesFragment();
1541 dismissLoadingDialog();
1543 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1544 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1548 } catch (NotFoundException e
) {
1549 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
1559 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1560 refreshListOfFilesFragment();
1561 FileFragment details
= getSecondFragment();
1562 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1563 file
.equals(details
.getFile()) ) {
1564 if (downloading
|| uploading
) {
1565 ((FileDetailFragment
)details
).updateFileDetails(file
, getAccount());
1567 if (!file
.fileExists()) {
1568 cleanSecondFragment();
1570 ((FileDetailFragment
)details
).updateFileDetails(false
, true
);
1578 private void requestForDownload() {
1579 Account account
= getAccount();
1580 //if (!mWaitingToPreview.isDownloading()) {
1581 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1582 Intent i
= new Intent(this, FileDownloader
.class);
1583 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1584 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1590 private OCFile
getCurrentDir() {
1591 OCFile file
= getFile();
1593 if (file
.isFolder()) {
1595 } else if (getStorageManager() != null
) {
1596 String parentPath
= file
.getRemotePath().substring(0,
1597 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1598 return getStorageManager().getFileByPath(parentPath
);
1604 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1605 long currentSyncTime
= System
.currentTimeMillis();
1607 mSyncInProgress
= true
;
1609 // perform folder synchronization
1610 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1613 getFileOperationsHelper().isSharedSupported(),
1615 getStorageManager(),
1617 getApplicationContext()
1619 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1620 mProgressBar
.setIndeterminate(true
);
1622 setBackgroundText();
1626 * Show untrusted cert dialog
1628 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1629 // Show a dialog with the certificate info
1630 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1631 (CertificateCombinedException
) result
.getException());
1632 FragmentManager fm
= getSupportFragmentManager();
1633 FragmentTransaction ft
= fm
.beginTransaction();
1634 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1637 private void requestForDownload(OCFile file
) {
1638 Account account
= getAccount();
1639 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1640 Intent i
= new Intent(this, FileDownloader
.class);
1641 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1642 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1647 private void sendDownloadedFile(){
1648 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1649 mWaitingToSend
= null
;
1654 * Requests the download of the received {@link OCFile} , updates the UI
1655 * to monitor the download progress and prepares the activity to send the file
1656 * when the download finishes.
1658 * @param file {@link OCFile} to download and preview.
1660 public void startDownloadForSending(OCFile file
) {
1661 mWaitingToSend
= file
;
1662 requestForDownload(mWaitingToSend
);
1663 boolean hasSecondFragment
= (getSecondFragment()!= null
);
1664 updateFragmentsVisibility(hasSecondFragment
);
1668 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1670 * @param file Image {@link OCFile} to show.
1672 public void startImagePreview(OCFile file
) {
1673 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1674 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1675 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1676 startActivity(showDetailsIntent
);
1681 * Stars the preview of an already down media {@link OCFile}.
1683 * @param file Media {@link OCFile} to preview.
1684 * @param startPlaybackPosition Media position where the playback will be started,
1686 * @param autoplay When 'true', the playback will start without user
1689 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1690 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1692 setSecondFragment(mediaFragment
);
1693 updateFragmentsVisibility(true
);
1694 updateActionBarTitleAndHomeButton(file
);
1699 * Requests the download of the received {@link OCFile} , updates the UI
1700 * to monitor the download progress and prepares the activity to preview
1701 * or open the file when the download finishes.
1703 * @param file {@link OCFile} to download and preview.
1705 public void startDownloadForPreview(OCFile file
) {
1706 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1707 setSecondFragment(detailFragment
);
1708 mWaitingToPreview
= file
;
1709 requestForDownload();
1710 updateFragmentsVisibility(true
);
1711 updateActionBarTitleAndHomeButton(file
);
1716 public void cancelTransference(OCFile file
) {
1717 getFileOperationsHelper().cancelTransference(file
);
1718 if (mWaitingToPreview
!= null
&&
1719 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1720 mWaitingToPreview
= null
;
1722 if (mWaitingToSend
!= null
&&
1723 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1724 mWaitingToSend
= null
;
1726 onTransferStateChanged(file
, false
, false
);
1730 public void onRefresh(boolean ignoreETag
) {
1731 refreshList(ignoreETag
);
1735 public void onRefresh() {
1739 private void refreshList(boolean ignoreETag
) {
1740 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1741 if (listOfFiles
!= null
) {
1742 OCFile folder
= listOfFiles
.getCurrentFile();
1743 if (folder
!= null
) {
1744 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1745 listDirectory(mFile);*/
1746 startSyncFolderOperation(folder
, ignoreETag
);
1751 private void sortByDate(boolean ascending
){
1752 getListOfFilesFragment().sortByDate(ascending
);
1755 private void sortBySize(boolean ascending
){
1756 getListOfFilesFragment().sortBySize(ascending
);
1759 private void sortByName(boolean ascending
){
1760 getListOfFilesFragment().sortByName(ascending
);
1762 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1763 private void switchToGridView() {
1764 getListOfFilesFragment().switchToGridView();
1766 private void switchToListView() {
1767 getListOfFilesFragment().switchToListView();
1770 public void allFilesOption() {