2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * Copyright (C) 2011 Bartek Przybylski
7 * Copyright (C) 2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.ui
.activity
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.annotation
.TargetApi
;
29 import android
.support
.v7
.app
.AlertDialog
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.ComponentName
;
32 import android
.content
.ContentResolver
;
33 import android
.content
.Context
;
34 import android
.content
.DialogInterface
;
35 import android
.content
.Intent
;
36 import android
.content
.IntentFilter
;
37 import android
.content
.ServiceConnection
;
38 import android
.content
.SharedPreferences
;
39 import android
.content
.SyncRequest
;
40 import android
.content
.res
.Resources
.NotFoundException
;
41 import android
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Build
;
44 import android
.os
.Bundle
;
45 import android
.os
.IBinder
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.OpenableColumns
;
48 import android
.support
.v4
.app
.Fragment
;
49 import android
.support
.v4
.app
.FragmentManager
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.support
.v4
.content
.ContextCompat
;
52 import android
.support
.v4
.view
.GravityCompat
;
53 import android
.view
.Menu
;
54 import android
.view
.MenuInflater
;
55 import android
.view
.MenuItem
;
56 import android
.view
.View
;
57 import android
.widget
.ProgressBar
;
58 import android
.widget
.RelativeLayout
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileDownloader
;
67 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CopyFileOperation
;
81 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
82 import com
.owncloud
.android
.operations
.CreateShareOperation
;
83 import com
.owncloud
.android
.operations
.MoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
85 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
86 import com
.owncloud
.android
.operations
.RenameFileOperation
;
87 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
88 import com
.owncloud
.android
.operations
.UnshareLinkOperation
;
89 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
90 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
91 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
92 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
96 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
99 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
104 import com
.owncloud
.android
.utils
.DisplayUtils
;
105 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
106 import com
.owncloud
.android
.utils
.FileStorageUtils
;
107 import com
.owncloud
.android
.utils
.UriUtils
;
112 * Displays, what files the user has available in his ownCloud.
115 public class FileDisplayActivity
extends HookActivity
116 implements FileFragment
.ContainerActivity
,
117 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
121 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
122 private UploadFinishReceiver mUploadFinishReceiver
;
123 private DownloadFinishReceiver mDownloadFinishReceiver
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
126 private boolean mDualPane
;
127 private View mLeftFragmentContainer
;
128 private View mRightFragmentContainer
;
129 private ProgressBar mProgressBar
;
131 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
132 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
133 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
135 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
137 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
138 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
139 public static final int ACTION_MOVE_FILES
= 3;
140 public static final int ACTION_COPY_FILES
= 4;
142 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
144 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
145 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
147 private OCFile mWaitingToPreview
;
149 private boolean mSyncInProgress
= false
;
151 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
152 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
153 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
154 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
156 private OCFile mWaitingToSend
;
157 private Menu mOptionsMenu
;
161 protected void onCreate(Bundle savedInstanceState
) {
162 Log_OC
.v(TAG
, "onCreate() start");
164 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
167 /// grant that FileObserverService is watching favorite files
168 if (savedInstanceState
== null
) {
169 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
170 startService(initObserversIntent
);
173 /// Load of saved instance state
174 if(savedInstanceState
!= null
) {
175 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
176 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
177 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
178 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
179 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
181 mWaitingToPreview
= null
;
182 mSyncInProgress
= false
;
183 mWaitingToSend
= null
;
188 // Inflate and set the layout view
189 setContentView(R
.layout
.files
);
194 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
195 mProgressBar
.setIndeterminateDrawable(
196 ContextCompat
.getDrawable(this,
197 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
199 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
200 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
201 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
202 if (savedInstanceState
== null
) {
203 createMinFragments();
207 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
208 // according to the official
211 // enable ActionBar app icon to behave as action to toggle nav drawer
212 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
213 getSupportActionBar().setHomeButtonEnabled(true
);
215 mProgressBar
.setIndeterminate(mSyncInProgress
);
216 // always AFTER setContentView(...) ; to work around bug in its implementation
220 Log_OC
.v(TAG
, "onCreate() end");
224 protected void onStart() {
225 Log_OC
.v(TAG
, "onStart() start");
227 Log_OC
.v(TAG
, "onStart() end");
231 protected void onDestroy() {
232 Log_OC
.v(TAG
, "onDestroy() start");
234 Log_OC
.v(TAG
, "onDestroy() end");
238 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
241 protected void onAccountSet(boolean stateWasRecovered
) {
242 super.onAccountSet(stateWasRecovered
);
243 if (getAccount() != null
) {
244 /// Check whether the 'main' OCFile handled by the Activity is contained in the
246 OCFile file
= getFile();
247 // get parent from path
248 String parentPath
= "";
250 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
251 // upload in progress - right now, files are not inserted in the local
252 // cache until the upload is successful get parent from path
253 parentPath
= file
.getRemotePath().substring(0,
254 file
.getRemotePath().lastIndexOf(file
.getFileName()));
255 if (getStorageManager().getFileByPath(parentPath
) == null
)
256 file
= null
; // not able to know the directory where the file is uploading
258 file
= getStorageManager().getFileByPath(file
.getRemotePath());
259 // currentDir = null if not in the current Account
263 // fall back to root folder
264 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
268 if (mAccountWasSet
) {
269 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
270 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
271 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
272 int lastAtPos
= getAccount().name
.lastIndexOf("@");
273 username
.setText(getAccount().name
.substring(0, lastAtPos
));
277 if (!stateWasRecovered
) {
278 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
279 initFragmentsWithFile();
280 if (file
.isFolder()) {
281 startSyncFolderOperation(file
, false
);
285 updateFragmentsVisibility(!file
.isFolder());
286 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
291 private void createMinFragments() {
292 OCFileListFragment listOfFiles
= new OCFileListFragment();
293 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
294 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
295 transaction
.commit();
298 private void initFragmentsWithFile() {
299 if (getAccount() != null
&& getFile() != null
) {
301 OCFileListFragment listOfFiles
= getListOfFilesFragment();
302 if (listOfFiles
!= null
) {
303 listOfFiles
.listDirectory(getCurrentDir());
304 // TODO Enable when "On Device" is recovered
305 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
308 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
312 OCFile file
= getFile();
313 Fragment secondFragment
= chooseInitialSecondFragment(file
);
314 if (secondFragment
!= null
) {
315 setSecondFragment(secondFragment
);
316 updateFragmentsVisibility(true
);
317 updateActionBarTitleAndHomeButton(file
);
320 cleanSecondFragment();
321 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
322 startTextPreview(file
);
325 switchLayout(getFile());
328 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
329 if (getAccount() == null
) {
330 Log_OC
.wtf(TAG
, "\t account is NULL");
332 if (getFile() == null
) {
333 Log_OC
.wtf(TAG
, "\t file is NULL");
338 private void switchLayout(OCFile file
){
339 if (DisplayUtils
.isGridView(file
, getStorageManager())){
346 private Fragment
chooseInitialSecondFragment(OCFile file
) {
347 Fragment secondFragment
= null
;
348 if (file
!= null
&& !file
.isFolder()) {
349 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
350 && file
.getLastSyncDateForProperties() > 0 // temporal fix
352 int startPlaybackPosition
=
353 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
355 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
356 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
357 startPlaybackPosition
, autoplay
);
359 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
360 secondFragment
= null
;
362 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
365 return secondFragment
;
370 * Replaces the second fragment managed by the activity with the received as
373 * Assumes never will be more than two fragments managed at the same time.
375 * @param fragment New second Fragment to set.
377 private void setSecondFragment(Fragment fragment
) {
378 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
379 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
380 transaction
.commit();
384 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
386 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
387 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
389 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
390 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
393 } else if (existsSecondFragment
) {
394 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
395 mLeftFragmentContainer
.setVisibility(View
.GONE
);
397 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
398 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
402 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
403 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
405 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
406 mRightFragmentContainer
.setVisibility(View
.GONE
);
412 private OCFileListFragment
getListOfFilesFragment() {
413 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
414 FileDisplayActivity
.TAG_LIST_OF_FILES
);
415 if (listOfFiles
!= null
) {
416 return (OCFileListFragment
) listOfFiles
;
418 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
422 public FileFragment
getSecondFragment() {
423 Fragment second
= getSupportFragmentManager().findFragmentByTag(
424 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
425 if (second
!= null
) {
426 return (FileFragment
) second
;
431 protected void cleanSecondFragment() {
432 Fragment second
= getSecondFragment();
433 if (second
!= null
) {
434 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
438 updateFragmentsVisibility(false
);
439 updateActionBarTitleAndHomeButton(null
);
442 protected void refreshListOfFilesFragment() {
443 OCFileListFragment fileListFragment
= getListOfFilesFragment();
444 if (fileListFragment
!= null
) {
445 fileListFragment
.listDirectory();
446 // TODO Enable when "On Device" is recovered ?
447 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
451 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
453 FileFragment secondFragment
= getSecondFragment();
454 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
455 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
456 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
457 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
458 OCFile fileInFragment
= detailsFragment
.getFile();
459 if (fileInFragment
!= null
&&
460 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
461 // the user browsed to other file ; forget the automatic preview
462 mWaitingToPreview
= null
;
464 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
465 // grant that the right panel updates the progress bar
466 detailsFragment
.listenForTransferProgress();
467 detailsFragment
.updateFileDetails(true
, false
);
469 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
470 // update the right panel
471 boolean detailsFragmentChanged
= false
;
474 mWaitingToPreview
= getStorageManager().getFileById(
475 mWaitingToPreview
.getFileId()); // update the file from database,
476 // for the local storage path
477 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
478 startMediaPreview(mWaitingToPreview
, 0, true
);
479 detailsFragmentChanged
= true
;
480 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
481 startTextPreview(mWaitingToPreview
);
482 detailsFragmentChanged
= true
;
484 getFileOperationsHelper().openFile(mWaitingToPreview
);
487 mWaitingToPreview
= null
;
489 if (!detailsFragmentChanged
) {
490 detailsFragment
.updateFileDetails(false
, (success
));
497 public boolean onPrepareOptionsMenu(Menu menu
) {
498 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
499 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
500 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
501 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
502 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
503 menu
.findItem(R
.id
.action_switch_view
).setVisible(!drawerOpen
);
505 return super.onPrepareOptionsMenu(menu
);
509 public boolean onCreateOptionsMenu(Menu menu
) {
510 MenuInflater inflater
= getMenuInflater();
511 inflater
.inflate(R
.menu
.main_menu
, menu
);
514 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
523 public boolean onOptionsItemSelected(MenuItem item
) {
524 boolean retval
= true
;
525 switch (item
.getItemId()) {
526 case R
.id
.action_create_dir
: {
527 CreateFolderDialogFragment dialog
=
528 CreateFolderDialogFragment
.newInstance(getCurrentDir());
529 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
533 case R
.id
.action_sync_account
: {
534 startSynchronization();
537 case R
.id
.action_upload
: {
538 UploadSourceDialogFragment dialog
=
539 UploadSourceDialogFragment
.newInstance(getAccount());
540 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
543 case android
.R
.id
.home
: {
544 FileFragment second
= getSecondFragment();
545 OCFile currentDir
= getCurrentDir();
546 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
547 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
548 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
549 (second
!= null
&& second
.getFile() != null
)) {
553 mDrawerLayout
.openDrawer(GravityCompat
.START
);
557 case R
.id
.action_sort
: {
558 SharedPreferences appPreferences
= PreferenceManager
559 .getDefaultSharedPreferences(this);
561 // Read sorting order, default to sort by name ascending
562 Integer sortOrder
= appPreferences
563 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
565 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
566 builder
.setTitle(R
.string
.actionbar_sort_title
)
567 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
568 new DialogInterface
.OnClickListener() {
569 public void onClick(DialogInterface dialog
, int which
) {
582 builder
.create().show();
585 case R
.id
.action_switch_view
:{
587 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
588 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
589 R
.drawable
.ic_view_module
));
590 DisplayUtils
.setViewMode(getFile(), false
);
593 item
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
594 item
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
595 R
.drawable
.ic_view_list
));
596 DisplayUtils
.setViewMode(getFile(), true
);
603 retval
= super.onOptionsItemSelected(item
);
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 if (!isDrawerOpen()){
821 OCFileListFragment listOfFiles
= getListOfFilesFragment();
822 if (mDualPane
|| getSecondFragment() == null
) {
823 OCFile currentDir
= getCurrentDir();
824 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
828 if (listOfFiles
!= null
) { // should never be null, indeed
829 listOfFiles
.onBrowseUp();
832 if (listOfFiles
!= null
) { // should never be null, indeed
833 setFile(listOfFiles
.getCurrentFile());
835 cleanSecondFragment();
839 super.onBackPressed();
843 private void changeGridIcon(){
844 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
845 if (DisplayUtils
.isGridView(getFile(), getStorageManager())){
846 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_list_view
));
847 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
848 R
.drawable
.ic_view_list
));
850 menuItem
.setTitle(getApplicationContext().getString(R
.string
.action_switch_grid_view
));
851 menuItem
.setIcon(ContextCompat
.getDrawable(getApplicationContext(),
852 R
.drawable
.ic_view_module
));
857 protected void onSaveInstanceState(Bundle outState
) {
858 // responsibility of restore is preferred in onCreate() before than in
859 // onRestoreInstanceState when there are Fragments involved
860 Log_OC
.v(TAG
, "onSaveInstanceState() start");
861 super.onSaveInstanceState(outState
);
862 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
863 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
864 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
865 // mRefreshSharesInProgress);
866 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
868 Log_OC
.v(TAG
, "onSaveInstanceState() end");
873 protected void onResume() {
874 Log_OC
.v(TAG
, "onResume() start");
876 // refresh Navigation Drawer account list
877 mNavigationDrawerAdapter
.updateAccountList();
879 // refresh list of files
880 refreshListOfFilesFragment();
882 // Listen for sync messages
883 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
884 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
885 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
886 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
887 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
888 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
889 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
890 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
891 // syncIntentFilter);
893 // Listen for upload messages
894 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
895 mUploadFinishReceiver
= new UploadFinishReceiver();
896 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
898 // Listen for download messages
899 IntentFilter downloadIntentFilter
= new IntentFilter(
900 FileDownloader
.getDownloadAddedMessage());
901 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
902 mDownloadFinishReceiver
= new DownloadFinishReceiver();
903 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
905 Log_OC
.v(TAG
, "onResume() end");
911 protected void onPause() {
912 Log_OC
.v(TAG
, "onPause() start");
913 if (mSyncBroadcastReceiver
!= null
) {
914 unregisterReceiver(mSyncBroadcastReceiver
);
915 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
916 mSyncBroadcastReceiver
= null
;
918 if (mUploadFinishReceiver
!= null
) {
919 unregisterReceiver(mUploadFinishReceiver
);
920 mUploadFinishReceiver
= null
;
922 if (mDownloadFinishReceiver
!= null
) {
923 unregisterReceiver(mDownloadFinishReceiver
);
924 mDownloadFinishReceiver
= null
;
928 Log_OC
.v(TAG
, "onPause() end");
932 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
935 * {@link BroadcastReceiver} to enable syncing feedback in UI
938 public void onReceive(Context context
, Intent intent
) {
940 String event
= intent
.getAction();
941 Log_OC
.d(TAG
, "Received broadcast " + event
);
942 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
943 String synchFolderRemotePath
=
944 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
945 RemoteOperationResult synchResult
=
946 (RemoteOperationResult
)intent
.getSerializableExtra(
947 FileSyncAdapter
.EXTRA_RESULT
);
948 boolean sameAccount
= (getAccount() != null
&&
949 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
953 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
954 mSyncInProgress
= true
;
957 OCFile currentFile
= (getFile() == null
) ? null
:
958 getStorageManager().getFileByPath(getFile().getRemotePath());
959 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
960 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
962 if (currentDir
== null
) {
963 // current folder was removed from the server
964 Toast
.makeText( FileDisplayActivity
.this,
967 sync_current_folder_was_removed
),
968 synchFolderRemotePath
),
975 if (currentFile
== null
&& !getFile().isFolder()) {
976 // currently selected file was removed in the server, and now we
978 cleanSecondFragment();
979 currentFile
= currentDir
;
982 if (synchFolderRemotePath
!= null
&&
983 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
984 OCFileListFragment fileListFragment
= getListOfFilesFragment();
985 if (fileListFragment
!= null
) {
986 fileListFragment
.listDirectory();
987 // TODO Enable when "On Device" is recovered ?
988 // fileListFragment.listDirectory(currentDir,
989 // MainApp.getOnlyOnDevice());
992 setFile(currentFile
);
995 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
996 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
999 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
1000 equals(event
) &&/// TODO refactor and make common
1002 synchResult
!= null
&& !synchResult
.isSuccess() &&
1003 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
1004 synchResult
.isIdPRedirection() ||
1005 (synchResult
.isException() && synchResult
.getException()
1006 instanceof AuthenticatorException
))) {
1010 OwnCloudClient client
;
1011 OwnCloudAccount ocAccount
=
1012 new OwnCloudAccount(getAccount(), context
);
1013 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
1014 removeClientFor(ocAccount
));
1015 if (client
!= null
) {
1016 OwnCloudCredentials cred
= client
.getCredentials();
1018 AccountManager am
= AccountManager
.get(context
);
1019 if (cred
.authTokenExpires()) {
1020 am
.invalidateAuthToken(
1025 am
.clearPassword(getAccount());
1029 requestCredentialsUpdate();
1031 } catch (AccountNotFoundException e
) {
1032 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
1037 removeStickyBroadcast(intent
);
1038 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
1039 mProgressBar
.setIndeterminate(mSyncInProgress
);
1040 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
1041 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
1042 /*|| mRefreshSharesInProgress*/ //);
1044 setBackgroundText();
1048 if (synchResult
!= null
) {
1049 if (synchResult
.getCode().equals(
1050 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1051 mLastSslUntrustedServerResult
= synchResult
;
1054 } catch (RuntimeException e
) {
1055 // avoid app crashes after changing the serial id of RemoteOperationResult
1056 // in owncloud library with broadcast notifications pending to process
1057 removeStickyBroadcast(intent
);
1063 * Show a text message on screen view for notifying user if content is
1064 * loading or folder is empty
1066 private void setBackgroundText() {
1067 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1068 if (ocFileListFragment
!= null
) {
1069 int message
= R
.string
.file_list_loading
;
1070 if (!mSyncInProgress
) {
1071 // In case file list is empty
1072 message
= R
.string
.file_list_empty
;
1074 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1076 Log_OC
.e(TAG
, "OCFileListFragment is null");
1081 * Once the file upload has finished -> update view
1083 private class UploadFinishReceiver
extends BroadcastReceiver
{
1085 * Once the file upload has finished -> update view
1087 * @author David A. Velasco
1088 * {@link BroadcastReceiver} to enable upload feedback in UI
1091 public void onReceive(Context context
, Intent intent
) {
1093 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1094 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1095 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1096 OCFile currentDir
= getCurrentDir();
1097 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1098 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1100 if (sameAccount
&& isDescendant
) {
1101 refreshListOfFilesFragment();
1104 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1106 boolean renamedInUpload
= getFile().getRemotePath().
1107 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1108 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1110 FileFragment details
= getSecondFragment();
1111 boolean detailFragmentIsShown
= (details
!= null
&&
1112 details
instanceof FileDetailFragment
);
1114 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1115 if (uploadWasFine
) {
1116 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1118 if (renamedInUpload
) {
1119 String newName
= (new File(uploadedRemotePath
)).getName();
1120 Toast msg
= Toast
.makeText(
1123 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1128 if (uploadWasFine
|| getFile().fileExists()) {
1129 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1131 cleanSecondFragment();
1134 // Force the preview if the file is an image or text file
1135 if (uploadWasFine
) {
1136 OCFile ocFile
= getFile();
1137 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1138 startImagePreview(getFile());
1139 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1140 startTextPreview(ocFile
);
1141 // TODO what about other kind of previews?
1145 mProgressBar
.setIndeterminate(false
);
1147 if (intent
!= null
) {
1148 removeStickyBroadcast(intent
);
1158 * Class waiting for broadcast events from the {@link FileDownloader} service.
1160 * Updates the UI when a download is started or finished, provided that it is relevant for the
1163 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1165 //int refreshCounter = 0;
1167 public void onReceive(Context context
, Intent intent
) {
1169 boolean sameAccount
= isSameAccount(context
, intent
);
1170 String downloadedRemotePath
=
1171 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1172 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1174 if (sameAccount
&& isDescendant
) {
1175 String linkedToRemotePath
=
1176 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1177 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1178 //Log_OC.v(TAG, "refresh #" + ++refreshCounter);
1179 refreshListOfFilesFragment();
1181 refreshSecondFragment(
1183 downloadedRemotePath
,
1184 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1188 if (mWaitingToSend
!= null
) {
1190 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1191 if (mWaitingToSend
.isDown()) {
1192 sendDownloadedFile();
1197 if (intent
!= null
) {
1198 removeStickyBroadcast(intent
);
1203 private boolean isDescendant(String downloadedRemotePath
) {
1204 OCFile currentDir
= getCurrentDir();
1206 currentDir
!= null
&&
1207 downloadedRemotePath
!= null
&&
1208 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1212 private boolean isAscendant(String linkedToRemotePath
) {
1213 OCFile currentDir
= getCurrentDir();
1215 currentDir
!= null
&&
1216 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1220 private boolean isSameAccount(Context context
, Intent intent
) {
1221 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1222 return (accountName
!= null
&& getAccount() != null
&&
1223 accountName
.equals(getAccount().name
));
1228 public void browseToRoot() {
1229 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1230 if (listOfFiles
!= null
) { // should never be null, indeed
1231 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1232 listOfFiles
.listDirectory(root
);
1233 // TODO Enable when "On Device" is recovered ?
1234 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1235 setFile(listOfFiles
.getCurrentFile());
1236 startSyncFolderOperation(root
, false
);
1238 cleanSecondFragment();
1245 * Updates action bar and second fragment, if in dual pane mode.
1248 public void onBrowsedDownTo(OCFile directory
) {
1250 cleanSecondFragment();
1252 startSyncFolderOperation(directory
, false
);
1254 MenuItem menuItem
= mOptionsMenu
.findItem(R
.id
.action_switch_view
);
1257 switchLayout(directory
);
1261 * Shows the information of the {@link OCFile} received as a
1262 * parameter in the second fragment.
1264 * @param file {@link OCFile} whose details will be shown
1267 public void showDetails(OCFile file
) {
1268 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1269 setSecondFragment(detailFragment
);
1270 updateFragmentsVisibility(true
);
1271 updateActionBarTitleAndHomeButton(file
);
1276 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1278 // in dual pane mode, keep the focus of title an action bar in the current folder
1279 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1282 super.updateActionBarTitleAndHomeButton(chosenFile
);
1288 protected ServiceConnection
newTransferenceServiceConnection() {
1289 return new ListServiceConnection();
1293 * Defines callbacks for service binding, passed to bindService()
1295 private class ListServiceConnection
implements ServiceConnection
{
1298 public void onServiceConnected(ComponentName component
, IBinder service
) {
1299 if (component
.equals(new ComponentName(
1300 FileDisplayActivity
.this, FileDownloader
.class))) {
1301 Log_OC
.d(TAG
, "Download service connected");
1302 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1303 if (mWaitingToPreview
!= null
)
1304 if (getStorageManager() != null
) {
1307 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1308 if (!mWaitingToPreview
.isDown()) {
1309 requestForDownload();
1313 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1314 FileUploader
.class))) {
1315 Log_OC
.d(TAG
, "Upload service connected");
1316 mUploaderBinder
= (FileUploaderBinder
) service
;
1320 // a new chance to get the mDownloadBinder through
1321 // getFileDownloadBinder() - THIS IS A MESS
1322 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1323 if (listOfFiles
!= null
) {
1324 listOfFiles
.listDirectory();
1325 // TODO Enable when "On Device" is recovered ?
1326 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1328 FileFragment secondFragment
= getSecondFragment();
1329 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1330 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1331 detailFragment
.listenForTransferProgress();
1332 detailFragment
.updateFileDetails(false
, false
);
1337 public void onServiceDisconnected(ComponentName component
) {
1338 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1339 FileDownloader
.class))) {
1340 Log_OC
.d(TAG
, "Download service disconnected");
1341 mDownloaderBinder
= null
;
1342 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1343 FileUploader
.class))) {
1344 Log_OC
.d(TAG
, "Upload service disconnected");
1345 mUploaderBinder
= null
;
1351 public void onSavedCertificate() {
1352 startSyncFolderOperation(getCurrentDir(), false
);
1357 public void onFailedSavingCertificate() {
1358 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1359 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1361 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1365 public void onCancelCertificate() {
1370 * Updates the view associated to the activity after the finish of some operation over files
1371 * in the current account.
1373 * @param operation Removal operation performed.
1374 * @param result Result of the removal.
1377 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1378 super.onRemoteOperationFinish(operation
, result
);
1380 if (operation
instanceof RemoveFileOperation
) {
1381 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1383 } else if (operation
instanceof RenameFileOperation
) {
1384 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1386 } else if (operation
instanceof SynchronizeFileOperation
) {
1387 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1389 } else if (operation
instanceof CreateFolderOperation
) {
1390 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1392 } else if (operation
instanceof CreateShareOperation
) {
1393 onCreateShareOperationFinish((CreateShareOperation
) operation
, result
);
1395 } else if (operation
instanceof UnshareLinkOperation
) {
1396 onUnshareLinkOperationFinish((UnshareLinkOperation
) operation
, result
);
1398 } else if (operation
instanceof MoveFileOperation
) {
1399 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1401 } else if (operation
instanceof CopyFileOperation
) {
1402 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1406 private void onCreateShareOperationFinish(CreateShareOperation operation
,
1407 RemoteOperationResult result
) {
1408 if (result
.isSuccess()) {
1409 refreshShowDetails();
1410 refreshListOfFilesFragment();
1414 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation
,
1415 RemoteOperationResult result
) {
1416 if (result
.isSuccess()) {
1417 refreshShowDetails();
1418 refreshListOfFilesFragment();
1420 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1421 cleanSecondFragment();
1422 refreshListOfFilesFragment();
1426 private void refreshShowDetails() {
1427 FileFragment details
= getSecondFragment();
1428 if (details
!= null
) {
1429 OCFile file
= details
.getFile();
1431 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1432 if (details
instanceof PreviewMediaFragment
) {
1433 // Refresh OCFile of the fragment
1434 ((PreviewMediaFragment
) details
).updateFile(file
);
1435 } else if (details
instanceof PreviewTextFragment
) {
1436 // Refresh OCFile of the fragment
1437 ((PreviewTextFragment
) details
).updateFile(file
);
1442 invalidateOptionsMenu();
1447 * Updates the view associated to the activity after the finish of an operation trying to
1450 * @param operation Removal operation performed.
1451 * @param result Result of the removal.
1453 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1454 RemoteOperationResult result
) {
1455 dismissLoadingDialog();
1457 Toast msg
= Toast
.makeText(this,
1458 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1462 if (result
.isSuccess()) {
1463 OCFile removedFile
= operation
.getFile();
1464 FileFragment second
= getSecondFragment();
1465 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1466 if (second
instanceof PreviewMediaFragment
) {
1467 ((PreviewMediaFragment
) second
).stopPreview(true
);
1469 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1470 cleanSecondFragment();
1472 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1473 refreshListOfFilesFragment();
1475 invalidateOptionsMenu();
1477 if (result
.isSslRecoverableException()) {
1478 mLastSslUntrustedServerResult
= result
;
1479 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1486 * Updates the view associated to the activity after the finish of an operation trying to move a
1489 * @param operation Move operation performed.
1490 * @param result Result of the move operation.
1492 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1493 RemoteOperationResult result
) {
1494 if (result
.isSuccess()) {
1495 dismissLoadingDialog();
1496 refreshListOfFilesFragment();
1498 dismissLoadingDialog();
1500 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1501 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1505 } catch (NotFoundException e
) {
1506 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1512 * Updates the view associated to the activity after the finish of an operation trying to copy a
1515 * @param operation Copy operation performed.
1516 * @param result Result of the copy operation.
1518 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1519 if (result
.isSuccess()) {
1520 dismissLoadingDialog();
1521 refreshListOfFilesFragment();
1523 dismissLoadingDialog();
1525 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1526 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1530 } catch (NotFoundException e
) {
1531 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1537 * Updates the view associated to the activity after the finish of an operation trying to rename
1540 * @param operation Renaming operation performed.
1541 * @param result Result of the renaming.
1543 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1544 RemoteOperationResult result
) {
1545 dismissLoadingDialog();
1546 OCFile renamedFile
= operation
.getFile();
1547 if (result
.isSuccess()) {
1548 FileFragment details
= getSecondFragment();
1549 if (details
!= null
) {
1550 if (details
instanceof FileDetailFragment
&&
1551 renamedFile
.equals(details
.getFile()) ) {
1552 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1553 showDetails(renamedFile
);
1555 } else if (details
instanceof PreviewMediaFragment
&&
1556 renamedFile
.equals(details
.getFile())) {
1557 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1558 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1559 int position
= ((PreviewMediaFragment
) details
).getPosition();
1560 startMediaPreview(renamedFile
, position
, true
);
1562 getFileOperationsHelper().openFile(renamedFile
);
1564 } else if (details
instanceof PreviewTextFragment
&&
1565 renamedFile
.equals(details
.getFile())) {
1566 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1567 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1568 startTextPreview(renamedFile
);
1570 getFileOperationsHelper().openFile(renamedFile
);
1575 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1576 refreshListOfFilesFragment();
1580 Toast msg
= Toast
.makeText(this,
1581 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1585 if (result
.isSslRecoverableException()) {
1586 mLastSslUntrustedServerResult
= result
;
1587 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1592 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1593 RemoteOperationResult result
) {
1594 if (result
.isSuccess()) {
1595 if (operation
.transferWasRequested()) {
1596 OCFile syncedFile
= operation
.getLocalFile();
1597 onTransferStateChanged(syncedFile
, true
, true
);
1598 invalidateOptionsMenu();
1599 refreshShowDetails();
1605 * Updates the view associated to the activity after the finish of an operation trying create a
1608 * @param operation Creation operation performed.
1609 * @param result Result of the creation.
1611 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1612 RemoteOperationResult result
) {
1613 if (result
.isSuccess()) {
1614 dismissLoadingDialog();
1615 refreshListOfFilesFragment();
1617 dismissLoadingDialog();
1619 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1620 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1624 } catch (NotFoundException e
) {
1625 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1635 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1636 refreshListOfFilesFragment();
1637 FileFragment details
= getSecondFragment();
1638 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1639 file
.equals(details
.getFile()) ) {
1640 if (downloading
|| uploading
) {
1641 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1643 if (!file
.fileExists()) {
1644 cleanSecondFragment();
1646 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1654 private void requestForDownload() {
1655 Account account
= getAccount();
1656 //if (!mWaitingToPreview.isDownloading()) {
1657 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1658 Intent i
= new Intent(this, FileDownloader
.class);
1659 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1660 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1666 private OCFile
getCurrentDir() {
1667 OCFile file
= getFile();
1669 if (file
.isFolder()) {
1671 } else if (getStorageManager() != null
) {
1672 String parentPath
= file
.getRemotePath().substring(0,
1673 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1674 return getStorageManager().getFileByPath(parentPath
);
1680 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1681 long currentSyncTime
= System
.currentTimeMillis();
1683 mSyncInProgress
= true
;
1685 // perform folder synchronization
1686 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1689 getFileOperationsHelper().isSharedSupported(),
1691 getStorageManager(),
1693 getApplicationContext()
1695 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1697 mProgressBar
.setIndeterminate(true
);
1699 setBackgroundText();
1703 * Show untrusted cert dialog
1705 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1706 // Show a dialog with the certificate info
1707 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1708 (CertificateCombinedException
) result
.getException());
1709 FragmentManager fm
= getSupportFragmentManager();
1710 FragmentTransaction ft
= fm
.beginTransaction();
1711 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1714 private void requestForDownload(OCFile file
) {
1715 Account account
= getAccount();
1716 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1717 Intent i
= new Intent(this, FileDownloader
.class);
1718 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1719 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1724 private void sendDownloadedFile() {
1725 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1726 mWaitingToSend
= null
;
1731 * Requests the download of the received {@link OCFile} , updates the UI
1732 * to monitor the download progress and prepares the activity to send the file
1733 * when the download finishes.
1735 * @param file {@link OCFile} to download and preview.
1737 public void startDownloadForSending(OCFile file
) {
1738 mWaitingToSend
= file
;
1739 requestForDownload(mWaitingToSend
);
1740 boolean hasSecondFragment
= (getSecondFragment() != null
);
1741 updateFragmentsVisibility(hasSecondFragment
);
1745 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1747 * @param file Image {@link OCFile} to show.
1749 public void startImagePreview(OCFile file
) {
1750 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1751 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1752 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1753 startActivity(showDetailsIntent
);
1757 * Stars the preview of an already down media {@link OCFile}.
1759 * @param file Media {@link OCFile} to preview.
1760 * @param startPlaybackPosition Media position where the playback will be started,
1762 * @param autoplay When 'true', the playback will start without user
1765 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1766 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1768 setSecondFragment(mediaFragment
);
1769 updateFragmentsVisibility(true
);
1770 updateActionBarTitleAndHomeButton(file
);
1775 * Stars the preview of a text file {@link OCFile}.
1777 * @param file Text {@link OCFile} to preview.
1779 public void startTextPreview(OCFile file
) {
1780 Bundle args
= new Bundle();
1781 args
.putParcelable(EXTRA_FILE
, file
);
1782 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1783 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1784 PreviewTextFragment
.class.getName(), args
);
1785 setSecondFragment(textPreviewFragment
);
1786 updateFragmentsVisibility(true
);
1787 //updateNavigationElementsInActionBar(file);
1792 * Requests the download of the received {@link OCFile} , updates the UI
1793 * to monitor the download progress and prepares the activity to preview
1794 * or open the file when the download finishes.
1796 * @param file {@link OCFile} to download and preview.
1798 public void startDownloadForPreview(OCFile file
) {
1799 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1800 setSecondFragment(detailFragment
);
1801 mWaitingToPreview
= file
;
1802 requestForDownload();
1803 updateFragmentsVisibility(true
);
1804 updateActionBarTitleAndHomeButton(file
);
1809 public void cancelTransference(OCFile file
) {
1810 getFileOperationsHelper().cancelTransference(file
);
1811 if (mWaitingToPreview
!= null
&&
1812 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1813 mWaitingToPreview
= null
;
1815 if (mWaitingToSend
!= null
&&
1816 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1817 mWaitingToSend
= null
;
1819 onTransferStateChanged(file
, false
, false
);
1823 public void onRefresh(boolean ignoreETag
) {
1824 refreshList(ignoreETag
);
1828 public void onRefresh() {
1832 private void refreshList(boolean ignoreETag
) {
1833 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1834 if (listOfFiles
!= null
) {
1835 OCFile folder
= listOfFiles
.getCurrentFile();
1836 if (folder
!= null
) {
1837 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1838 listDirectory(mFile);*/
1839 startSyncFolderOperation(folder
, ignoreETag
);
1844 private void sortByDate(boolean ascending
) {
1845 getListOfFilesFragment().sortByDate(ascending
);
1848 private void sortBySize(boolean ascending
) {
1849 getListOfFilesFragment().sortBySize(ascending
);
1852 private void sortByName(boolean ascending
) {
1853 getListOfFilesFragment().sortByName(ascending
);
1855 private boolean isGridView(){ return getListOfFilesFragment().isGridView(); }
1856 private void switchToGridView() {
1857 getListOfFilesFragment().switchToGridView();
1859 private void switchToListView() {
1860 getListOfFilesFragment().switchToListView();
1863 public void allFilesOption() {