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
.CreateShareViaLinkOperation
;
83 import com
.owncloud
.android
.operations
.CreateShareWithShareeOperation
;
84 import com
.owncloud
.android
.operations
.MoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RefreshFolderOperation
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.operations
.UnshareOperation
;
90 import com
.owncloud
.android
.services
.observer
.FileObserverService
;
91 import com
.owncloud
.android
.syncadapter
.FileSyncAdapter
;
92 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
93 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
95 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
96 import com
.owncloud
.android
.ui
.dialog
.UploadSourceDialogFragment
;
97 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
98 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
99 import com
.owncloud
.android
.ui
.fragment
.OCFileListFragment
;
100 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
101 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
102 import com
.owncloud
.android
.ui
.preview
.PreviewMediaFragment
;
103 import com
.owncloud
.android
.ui
.preview
.PreviewTextFragment
;
104 import com
.owncloud
.android
.ui
.preview
.PreviewVideoActivity
;
105 import com
.owncloud
.android
.utils
.DisplayUtils
;
106 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
107 import com
.owncloud
.android
.utils
.FileStorageUtils
;
108 import com
.owncloud
.android
.utils
.UriUtils
;
113 * Displays, what files the user has available in his ownCloud.
116 public class FileDisplayActivity
extends HookActivity
117 implements FileFragment
.ContainerActivity
,
118 OnSslUntrustedCertListener
, OnEnforceableRefreshListener
{
120 private SyncBroadcastReceiver mSyncBroadcastReceiver
;
121 private UploadFinishReceiver mUploadFinishReceiver
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private RemoteOperationResult mLastSslUntrustedServerResult
= null
;
125 private boolean mDualPane
;
126 private View mLeftFragmentContainer
;
127 private View mRightFragmentContainer
;
128 private ProgressBar mProgressBar
;
130 private static final String KEY_WAITING_TO_PREVIEW
= "WAITING_TO_PREVIEW";
131 private static final String KEY_SYNC_IN_PROGRESS
= "SYNC_IN_PROGRESS";
132 private static final String KEY_WAITING_TO_SEND
= "WAITING_TO_SEND";
134 public static final String ACTION_DETAILS
= "com.owncloud.android.ui.activity.action.DETAILS";
136 public static final int ACTION_SELECT_CONTENT_FROM_APPS
= 1;
137 public static final int ACTION_SELECT_MULTIPLE_FILES
= 2;
138 public static final int ACTION_MOVE_FILES
= 3;
139 public static final int ACTION_COPY_FILES
= 4;
141 private static final String TAG
= FileDisplayActivity
.class.getSimpleName();
143 private static final String TAG_LIST_OF_FILES
= "LIST_OF_FILES";
144 private static final String TAG_SECOND_FRAGMENT
= "SECOND_FRAGMENT";
146 private OCFile mWaitingToPreview
;
148 private boolean mSyncInProgress
= false
;
150 private static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
151 private static String DIALOG_CREATE_FOLDER
= "DIALOG_CREATE_FOLDER";
152 private static String DIALOG_UPLOAD_SOURCE
= "DIALOG_UPLOAD_SOURCE";
153 private static String DIALOG_CERT_NOT_SAVED
= "DIALOG_CERT_NOT_SAVED";
155 private OCFile mWaitingToSend
;
159 protected void onCreate(Bundle savedInstanceState
) {
160 Log_OC
.v(TAG
, "onCreate() start");
162 super.onCreate(savedInstanceState
); // this calls onAccountChanged() when ownCloud Account
165 /// grant that FileObserverService is watching favorite files
166 if (savedInstanceState
== null
) {
167 Intent initObserversIntent
= FileObserverService
.makeInitIntent(this);
168 startService(initObserversIntent
);
171 /// Load of saved instance state
172 if(savedInstanceState
!= null
) {
173 mWaitingToPreview
= (OCFile
) savedInstanceState
.getParcelable(
174 FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
);
175 mSyncInProgress
= savedInstanceState
.getBoolean(KEY_SYNC_IN_PROGRESS
);
176 mWaitingToSend
= (OCFile
) savedInstanceState
.getParcelable(
177 FileDisplayActivity
.KEY_WAITING_TO_SEND
);
179 mWaitingToPreview
= null
;
180 mSyncInProgress
= false
;
181 mWaitingToSend
= null
;
186 // Inflate and set the layout view
187 setContentView(R
.layout
.files
);
192 mProgressBar
= (ProgressBar
) findViewById(R
.id
.progressBar
);
193 mProgressBar
.setIndeterminateDrawable(
194 ContextCompat
.getDrawable(this,
195 R
.drawable
.actionbar_progress_indeterminate_horizontal
));
197 mDualPane
= getResources().getBoolean(R
.bool
.large_land_layout
);
198 mLeftFragmentContainer
= findViewById(R
.id
.left_fragment_container
);
199 mRightFragmentContainer
= findViewById(R
.id
.right_fragment_container
);
200 if (savedInstanceState
== null
) {
201 createMinFragments();
205 getSupportActionBar().setHomeButtonEnabled(true
); // mandatory since Android ICS,
206 // according to the official
209 // enable ActionBar app icon to behave as action to toggle nav drawer
210 //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
211 getSupportActionBar().setHomeButtonEnabled(true
);
213 mProgressBar
.setIndeterminate(mSyncInProgress
);
214 // always AFTER setContentView(...) ; to work around bug in its implementation
218 Log_OC
.v(TAG
, "onCreate() end");
222 protected void onStart() {
223 Log_OC
.v(TAG
, "onStart() start");
225 Log_OC
.v(TAG
, "onStart() end");
229 protected void onDestroy() {
230 Log_OC
.v(TAG
, "onDestroy() start");
232 Log_OC
.v(TAG
, "onDestroy() end");
236 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
239 protected void onAccountSet(boolean stateWasRecovered
) {
240 super.onAccountSet(stateWasRecovered
);
241 if (getAccount() != null
) {
242 /// Check whether the 'main' OCFile handled by the Activity is contained in the
244 OCFile file
= getFile();
245 // get parent from path
246 String parentPath
= "";
248 if (file
.isDown() && file
.getLastSyncDateForProperties() == 0) {
249 // upload in progress - right now, files are not inserted in the local
250 // cache until the upload is successful get parent from path
251 parentPath
= file
.getRemotePath().substring(0,
252 file
.getRemotePath().lastIndexOf(file
.getFileName()));
253 if (getStorageManager().getFileByPath(parentPath
) == null
)
254 file
= null
; // not able to know the directory where the file is uploading
256 file
= getStorageManager().getFileByPath(file
.getRemotePath());
257 // currentDir = null if not in the current Account
261 // fall back to root folder
262 file
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
); // never returns null
266 if (mAccountWasSet
) {
267 RelativeLayout navigationDrawerLayout
= (RelativeLayout
) findViewById(R
.id
.left_drawer
);
268 if (navigationDrawerLayout
!= null
&& getAccount() != null
) {
269 TextView username
= (TextView
) navigationDrawerLayout
.findViewById(R
.id
.drawer_username
);
270 int lastAtPos
= getAccount().name
.lastIndexOf("@");
271 username
.setText(getAccount().name
.substring(0, lastAtPos
));
275 if (!stateWasRecovered
) {
276 Log_OC
.d(TAG
, "Initializing Fragments in onAccountChanged..");
277 initFragmentsWithFile();
278 if (file
.isFolder()) {
279 startSyncFolderOperation(file
, false
);
283 updateFragmentsVisibility(!file
.isFolder());
284 updateActionBarTitleAndHomeButton(file
.isFolder() ? null
: file
);
289 private void createMinFragments() {
290 OCFileListFragment listOfFiles
= new OCFileListFragment();
291 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
292 transaction
.add(R
.id
.left_fragment_container
, listOfFiles
, TAG_LIST_OF_FILES
);
293 transaction
.commit();
296 private void initFragmentsWithFile() {
297 if (getAccount() != null
&& getFile() != null
) {
299 OCFileListFragment listOfFiles
= getListOfFilesFragment();
300 if (listOfFiles
!= null
) {
301 listOfFiles
.listDirectory(getCurrentDir());
302 // TODO Enable when "On Device" is recovered
303 // listOfFiles.listDirectory(getCurrentDir(), MainApp.getOnlyOnDevice());
306 Log_OC
.e(TAG
, "Still have a chance to lose the initializacion of list fragment >(");
310 OCFile file
= getFile();
311 Fragment secondFragment
= chooseInitialSecondFragment(file
);
312 if (secondFragment
!= null
) {
313 setSecondFragment(secondFragment
);
314 updateFragmentsVisibility(true
);
315 updateActionBarTitleAndHomeButton(file
);
318 cleanSecondFragment();
319 if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
))
320 startTextPreview(file
);
324 Log_OC
.wtf(TAG
, "initFragments() called with invalid NULLs!");
325 if (getAccount() == null
) {
326 Log_OC
.wtf(TAG
, "\t account is NULL");
328 if (getFile() == null
) {
329 Log_OC
.wtf(TAG
, "\t file is NULL");
334 private Fragment
chooseInitialSecondFragment(OCFile file
) {
335 Fragment secondFragment
= null
;
336 if (file
!= null
&& !file
.isFolder()) {
337 if (file
.isDown() && PreviewMediaFragment
.canBePreviewed(file
)
338 && file
.getLastSyncDateForProperties() > 0 // temporal fix
340 int startPlaybackPosition
=
341 getIntent().getIntExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, 0);
343 getIntent().getBooleanExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, true
);
344 secondFragment
= new PreviewMediaFragment(file
, getAccount(),
345 startPlaybackPosition
, autoplay
);
347 } else if (file
.isDown() && PreviewTextFragment
.canBePreviewed(file
)) {
348 secondFragment
= null
;
350 secondFragment
= FileDetailFragment
.newInstance(file
, getAccount());
353 return secondFragment
;
358 * Replaces the second fragment managed by the activity with the received as
361 * Assumes never will be more than two fragments managed at the same time.
363 * @param fragment New second Fragment to set.
365 private void setSecondFragment(Fragment fragment
) {
366 FragmentTransaction transaction
= getSupportFragmentManager().beginTransaction();
367 transaction
.replace(R
.id
.right_fragment_container
, fragment
, TAG_SECOND_FRAGMENT
);
368 transaction
.commit();
372 private void updateFragmentsVisibility(boolean existsSecondFragment
) {
374 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
375 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
377 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
378 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
381 } else if (existsSecondFragment
) {
382 if (mLeftFragmentContainer
.getVisibility() != View
.GONE
) {
383 mLeftFragmentContainer
.setVisibility(View
.GONE
);
385 if (mRightFragmentContainer
.getVisibility() != View
.VISIBLE
) {
386 mRightFragmentContainer
.setVisibility(View
.VISIBLE
);
390 if (mLeftFragmentContainer
.getVisibility() != View
.VISIBLE
) {
391 mLeftFragmentContainer
.setVisibility(View
.VISIBLE
);
393 if (mRightFragmentContainer
.getVisibility() != View
.GONE
) {
394 mRightFragmentContainer
.setVisibility(View
.GONE
);
400 private OCFileListFragment
getListOfFilesFragment() {
401 Fragment listOfFiles
= getSupportFragmentManager().findFragmentByTag(
402 FileDisplayActivity
.TAG_LIST_OF_FILES
);
403 if (listOfFiles
!= null
) {
404 return (OCFileListFragment
) listOfFiles
;
406 Log_OC
.wtf(TAG
, "Access to unexisting list of files fragment!!");
410 public FileFragment
getSecondFragment() {
411 Fragment second
= getSupportFragmentManager().findFragmentByTag(
412 FileDisplayActivity
.TAG_SECOND_FRAGMENT
);
413 if (second
!= null
) {
414 return (FileFragment
) second
;
419 protected void cleanSecondFragment() {
420 Fragment second
= getSecondFragment();
421 if (second
!= null
) {
422 FragmentTransaction tr
= getSupportFragmentManager().beginTransaction();
426 updateFragmentsVisibility(false
);
427 updateActionBarTitleAndHomeButton(null
);
430 protected void refreshListOfFilesFragment() {
431 OCFileListFragment fileListFragment
= getListOfFilesFragment();
432 if (fileListFragment
!= null
) {
433 fileListFragment
.listDirectory();
434 // TODO Enable when "On Device" is recovered ?
435 // fileListFragment.listDirectory(MainApp.getOnlyOnDevice());
439 protected void refreshSecondFragment(String downloadEvent
, String downloadedRemotePath
,
441 FileFragment secondFragment
= getSecondFragment();
442 boolean waitedPreview
= (mWaitingToPreview
!= null
&&
443 mWaitingToPreview
.getRemotePath().equals(downloadedRemotePath
));
444 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
445 FileDetailFragment detailsFragment
= (FileDetailFragment
) secondFragment
;
446 OCFile fileInFragment
= detailsFragment
.getFile();
447 if (fileInFragment
!= null
&&
448 !downloadedRemotePath
.equals(fileInFragment
.getRemotePath())) {
449 // the user browsed to other file ; forget the automatic preview
450 mWaitingToPreview
= null
;
452 } else if (downloadEvent
.equals(FileDownloader
.getDownloadAddedMessage())) {
453 // grant that the right panel updates the progress bar
454 detailsFragment
.listenForTransferProgress();
455 detailsFragment
.updateFileDetails(true
, false
);
457 } else if (downloadEvent
.equals(FileDownloader
.getDownloadFinishMessage())) {
458 // update the right panel
459 boolean detailsFragmentChanged
= false
;
462 mWaitingToPreview
= getStorageManager().getFileById(
463 mWaitingToPreview
.getFileId()); // update the file from database,
464 // for the local storage path
465 if (PreviewMediaFragment
.canBePreviewed(mWaitingToPreview
)) {
466 startMediaPreview(mWaitingToPreview
, 0, true
);
467 detailsFragmentChanged
= true
;
468 } else if (PreviewTextFragment
.canBePreviewed(mWaitingToPreview
)) {
469 startTextPreview(mWaitingToPreview
);
470 detailsFragmentChanged
= true
;
472 getFileOperationsHelper().openFile(mWaitingToPreview
);
475 mWaitingToPreview
= null
;
477 if (!detailsFragmentChanged
) {
478 detailsFragment
.updateFileDetails(false
, (success
));
485 public boolean onPrepareOptionsMenu(Menu menu
) {
486 boolean drawerOpen
= mDrawerLayout
.isDrawerOpen(GravityCompat
.START
);
487 menu
.findItem(R
.id
.action_upload
).setVisible(!drawerOpen
);
488 menu
.findItem(R
.id
.action_create_dir
).setVisible(!drawerOpen
);
489 menu
.findItem(R
.id
.action_sort
).setVisible(!drawerOpen
);
490 menu
.findItem(R
.id
.action_sync_account
).setVisible(!drawerOpen
);
492 return super.onPrepareOptionsMenu(menu
);
496 public boolean onCreateOptionsMenu(Menu menu
) {
497 MenuInflater inflater
= getMenuInflater();
498 inflater
.inflate(R
.menu
.main_menu
, menu
);
504 public boolean onOptionsItemSelected(MenuItem item
) {
505 boolean retval
= true
;
506 switch (item
.getItemId()) {
507 case R
.id
.action_create_dir
: {
508 CreateFolderDialogFragment dialog
=
509 CreateFolderDialogFragment
.newInstance(getCurrentDir());
510 dialog
.show(getSupportFragmentManager(), DIALOG_CREATE_FOLDER
);
514 case R
.id
.action_sync_account
: {
515 startSynchronization();
518 case R
.id
.action_upload
: {
519 UploadSourceDialogFragment dialog
=
520 UploadSourceDialogFragment
.newInstance(getAccount());
521 dialog
.show(getSupportFragmentManager(), DIALOG_UPLOAD_SOURCE
);
524 case android
.R
.id
.home
: {
525 FileFragment second
= getSecondFragment();
526 OCFile currentDir
= getCurrentDir();
527 if (mDrawerLayout
.isDrawerOpen(GravityCompat
.START
)) {
528 mDrawerLayout
.closeDrawer(GravityCompat
.START
);
529 } else if((currentDir
!= null
&& currentDir
.getParentId() != 0) ||
530 (second
!= null
&& second
.getFile() != null
)) {
534 mDrawerLayout
.openDrawer(GravityCompat
.START
);
538 case R
.id
.action_sort
: {
539 SharedPreferences appPreferences
= PreferenceManager
540 .getDefaultSharedPreferences(this);
542 // Read sorting order, default to sort by name ascending
543 Integer sortOrder
= appPreferences
544 .getInt("sortOrder", FileStorageUtils
.SORT_NAME
);
546 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
547 builder
.setTitle(R
.string
.actionbar_sort_title
)
548 .setSingleChoiceItems(R
.array
.actionbar_sortby
, sortOrder
,
549 new DialogInterface
.OnClickListener() {
550 public void onClick(DialogInterface dialog
, int which
) {
563 builder
.create().show();
567 retval
= super.onOptionsItemSelected(item
);
572 private void startSynchronization() {
573 Log_OC
.d(TAG
, "Got to start sync");
574 if (android
.os
.Build
.VERSION
.SDK_INT
< android
.os
.Build
.VERSION_CODES
.KITKAT
) {
575 Log_OC
.d(TAG
, "Canceling all syncs for " + MainApp
.getAuthority());
576 ContentResolver
.cancelSync(null
, MainApp
.getAuthority());
577 // cancel the current synchronizations of any ownCloud account
578 Bundle bundle
= new Bundle();
579 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
580 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_EXPEDITED
, true
);
581 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
582 MainApp
.getAuthority());
583 ContentResolver
.requestSync(
585 MainApp
.getAuthority(), bundle
);
587 Log_OC
.d(TAG
, "Requesting sync for " + getAccount().name
+ " at " +
588 MainApp
.getAuthority() + " with new API");
589 SyncRequest
.Builder builder
= new SyncRequest
.Builder();
590 builder
.setSyncAdapter(getAccount(), MainApp
.getAuthority());
591 builder
.setExpedited(true
);
592 builder
.setManual(true
);
595 // Fix bug in Android Lollipop when you click on refresh the whole account
596 Bundle extras
= new Bundle();
597 builder
.setExtras(extras
);
599 SyncRequest request
= builder
.build();
600 ContentResolver
.requestSync(request
);
605 * Called, when the user selected something for uploading
608 @TargetApi(Build
.VERSION_CODES
.JELLY_BEAN
)
610 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
612 if (requestCode
== ACTION_SELECT_CONTENT_FROM_APPS
&& (resultCode
== RESULT_OK
||
613 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
614 //getClipData is only supported on api level 16+, Jelly Bean
615 if (data
.getData() == null
&& Build
.VERSION
.SDK_INT
>= Build
.VERSION_CODES
.JELLY_BEAN
){
616 for( int i
= 0; i
< data
.getClipData().getItemCount(); i
++){
617 Intent intent
= new Intent();
618 intent
.setData(data
.getClipData().getItemAt(i
).getUri());
619 requestSimpleUpload(intent
, resultCode
);
622 requestSimpleUpload(data
, resultCode
);
624 } else if (requestCode
== ACTION_SELECT_MULTIPLE_FILES
&& (resultCode
== RESULT_OK
||
625 resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)) {
626 requestMultipleUpload(data
, resultCode
);
628 } else if (requestCode
== ACTION_MOVE_FILES
&& resultCode
== RESULT_OK
){
629 final Intent fData
= data
;
630 final int fResultCode
= resultCode
;
631 getHandler().postDelayed(
635 requestMoveOperation(fData
, fResultCode
);
638 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
641 } else if (requestCode
== ACTION_COPY_FILES
&& resultCode
== RESULT_OK
) {
643 final Intent fData
= data
;
644 final int fResultCode
= resultCode
;
645 getHandler().postDelayed(
649 requestCopyOperation(fData
, fResultCode
);
652 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
656 super.onActivityResult(requestCode
, resultCode
, data
);
661 private void requestMultipleUpload(Intent data
, int resultCode
) {
662 String
[] filePaths
= data
.getStringArrayExtra(UploadFilesActivity
.EXTRA_CHOSEN_FILES
);
663 if (filePaths
!= null
) {
664 String
[] remotePaths
= new String
[filePaths
.length
];
665 String remotePathBase
= getCurrentDir().getRemotePath();
666 for (int j
= 0; j
< remotePaths
.length
; j
++) {
667 remotePaths
[j
] = remotePathBase
+ (new File(filePaths
[j
])).getName();
670 Intent i
= new Intent(this, FileUploader
.class);
671 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
672 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePaths
);
673 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePaths
);
674 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
675 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
676 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
680 Log_OC
.d(TAG
, "User clicked on 'Update' with no selection");
681 Toast t
= Toast
.makeText(this, getString(R
.string
.filedisplay_no_file_selected
),
689 private void requestSimpleUpload(Intent data
, int resultCode
) {
690 String filePath
= null
;
691 String mimeType
= null
;
693 Uri selectedImageUri
= data
.getData();
696 mimeType
= getContentResolver().getType(selectedImageUri
);
698 String fileManagerString
= selectedImageUri
.getPath();
699 String selectedImagePath
= UriUtils
.getLocalPath(selectedImageUri
, this);
701 if (selectedImagePath
!= null
)
702 filePath
= selectedImagePath
;
704 filePath
= fileManagerString
;
706 } catch (Exception e
) {
707 Log_OC
.e(TAG
, "Unexpected exception when trying to read the result of " +
708 "Intent.ACTION_GET_CONTENT", e
);
711 if (filePath
== null
) {
712 Log_OC
.e(TAG
, "Couldn't resolve path to file");
713 Toast t
= Toast
.makeText(
714 this, getString(R
.string
.filedisplay_unexpected_bad_get_content
),
722 Intent i
= new Intent(this, FileUploader
.class);
723 i
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
724 OCFile currentDir
= getCurrentDir();
725 String remotePath
= (currentDir
!= null
) ? currentDir
.getRemotePath() : OCFile
.ROOT_PATH
;
727 if (filePath
.startsWith(UriUtils
.URI_CONTENT_SCHEME
)) {
728 Cursor cursor
= getContentResolver().query(Uri
.parse(filePath
), null
, null
, null
, null
);
730 if (cursor
!= null
&& cursor
.moveToFirst()) {
731 String displayName
= cursor
.getString(cursor
.getColumnIndex(
732 OpenableColumns
.DISPLAY_NAME
));
733 Log_OC
.v(TAG
, "Display Name: " + displayName
);
735 displayName
.replace(File
.separatorChar
, '_');
736 displayName
.replace(File
.pathSeparatorChar
, '_');
737 remotePath
+= displayName
+ DisplayUtils
.getComposedFileExtension(filePath
);
740 // and what happens in case of error?; wrong target name for the upload
746 remotePath
+= new File(filePath
).getName();
749 i
.putExtra(FileUploader
.KEY_LOCAL_FILE
, filePath
);
750 i
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remotePath
);
751 i
.putExtra(FileUploader
.KEY_MIME_TYPE
, mimeType
);
752 i
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_SINGLE_FILE
);
753 if (resultCode
== UploadFilesActivity
.RESULT_OK_AND_MOVE
)
754 i
.putExtra(FileUploader
.KEY_LOCAL_BEHAVIOUR
, FileUploader
.LOCAL_BEHAVIOUR_MOVE
);
759 * Request the operation for moving the file/folder from one path to another
761 * @param data Intent received
762 * @param resultCode Result code received
764 private void requestMoveOperation(Intent data
, int resultCode
) {
765 OCFile folderToMoveAt
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
766 OCFile targetFile
= (OCFile
) data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
767 getFileOperationsHelper().moveFile(folderToMoveAt
, targetFile
);
771 * Request the operation for copying the file/folder from one path to another
773 * @param data Intent received
774 * @param resultCode Result code received
776 private void requestCopyOperation(Intent data
, int resultCode
) {
777 OCFile folderToMoveAt
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FOLDER
);
778 OCFile targetFile
= data
.getParcelableExtra(FolderPickerActivity
.EXTRA_FILE
);
779 getFileOperationsHelper().copyFile(folderToMoveAt
, targetFile
);
783 public void onBackPressed() {
784 if (!isDrawerOpen()){
785 OCFileListFragment listOfFiles
= getListOfFilesFragment();
786 if (mDualPane
|| getSecondFragment() == null
) {
787 OCFile currentDir
= getCurrentDir();
788 if (currentDir
== null
|| currentDir
.getParentId() == FileDataStorageManager
.ROOT_PARENT_ID
) {
792 if (listOfFiles
!= null
) { // should never be null, indeed
793 listOfFiles
.onBrowseUp();
796 if (listOfFiles
!= null
) { // should never be null, indeed
797 setFile(listOfFiles
.getCurrentFile());
799 cleanSecondFragment();
801 super.onBackPressed();
806 protected void onSaveInstanceState(Bundle outState
) {
807 // responsibility of restore is preferred in onCreate() before than in
808 // onRestoreInstanceState when there are Fragments involved
809 Log_OC
.v(TAG
, "onSaveInstanceState() start");
810 super.onSaveInstanceState(outState
);
811 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_PREVIEW
, mWaitingToPreview
);
812 outState
.putBoolean(FileDisplayActivity
.KEY_SYNC_IN_PROGRESS
, mSyncInProgress
);
813 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,
814 // mRefreshSharesInProgress);
815 outState
.putParcelable(FileDisplayActivity
.KEY_WAITING_TO_SEND
, mWaitingToSend
);
817 Log_OC
.v(TAG
, "onSaveInstanceState() end");
822 protected void onResume() {
823 Log_OC
.v(TAG
, "onResume() start");
825 // refresh Navigation Drawer account list
826 mNavigationDrawerAdapter
.updateAccountList();
828 // refresh list of files
829 refreshListOfFilesFragment();
831 // Listen for sync messages
832 IntentFilter syncIntentFilter
= new IntentFilter(FileSyncAdapter
.EVENT_FULL_SYNC_START
);
833 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_END
);
834 syncIntentFilter
.addAction(FileSyncAdapter
.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED
);
835 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
);
836 syncIntentFilter
.addAction(RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
);
837 mSyncBroadcastReceiver
= new SyncBroadcastReceiver();
838 registerReceiver(mSyncBroadcastReceiver
, syncIntentFilter
);
839 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver,
840 // syncIntentFilter);
842 // Listen for upload messages
843 IntentFilter uploadIntentFilter
= new IntentFilter(FileUploader
.getUploadFinishMessage());
844 mUploadFinishReceiver
= new UploadFinishReceiver();
845 registerReceiver(mUploadFinishReceiver
, uploadIntentFilter
);
847 // Listen for download messages
848 IntentFilter downloadIntentFilter
= new IntentFilter(
849 FileDownloader
.getDownloadAddedMessage());
850 downloadIntentFilter
.addAction(FileDownloader
.getDownloadFinishMessage());
851 mDownloadFinishReceiver
= new DownloadFinishReceiver();
852 registerReceiver(mDownloadFinishReceiver
, downloadIntentFilter
);
854 Log_OC
.v(TAG
, "onResume() end");
860 protected void onPause() {
861 Log_OC
.v(TAG
, "onPause() start");
862 if (mSyncBroadcastReceiver
!= null
) {
863 unregisterReceiver(mSyncBroadcastReceiver
);
864 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
865 mSyncBroadcastReceiver
= null
;
867 if (mUploadFinishReceiver
!= null
) {
868 unregisterReceiver(mUploadFinishReceiver
);
869 mUploadFinishReceiver
= null
;
871 if (mDownloadFinishReceiver
!= null
) {
872 unregisterReceiver(mDownloadFinishReceiver
);
873 mDownloadFinishReceiver
= null
;
877 Log_OC
.v(TAG
, "onPause() end");
881 private class SyncBroadcastReceiver
extends BroadcastReceiver
{
884 * {@link BroadcastReceiver} to enable syncing feedback in UI
887 public void onReceive(Context context
, Intent intent
) {
889 String event
= intent
.getAction();
890 Log_OC
.d(TAG
, "Received broadcast " + event
);
891 String accountName
= intent
.getStringExtra(FileSyncAdapter
.EXTRA_ACCOUNT_NAME
);
892 String synchFolderRemotePath
=
893 intent
.getStringExtra(FileSyncAdapter
.EXTRA_FOLDER_PATH
);
894 RemoteOperationResult synchResult
=
895 (RemoteOperationResult
)intent
.getSerializableExtra(
896 FileSyncAdapter
.EXTRA_RESULT
);
897 boolean sameAccount
= (getAccount() != null
&&
898 accountName
.equals(getAccount().name
) && getStorageManager() != null
);
902 if (FileSyncAdapter
.EVENT_FULL_SYNC_START
.equals(event
)) {
903 mSyncInProgress
= true
;
906 OCFile currentFile
= (getFile() == null
) ? null
:
907 getStorageManager().getFileByPath(getFile().getRemotePath());
908 OCFile currentDir
= (getCurrentDir() == null
) ? null
:
909 getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
911 if (currentDir
== null
) {
912 // current folder was removed from the server
913 Toast
.makeText( FileDisplayActivity
.this,
916 sync_current_folder_was_removed
),
917 synchFolderRemotePath
),
924 if (currentFile
== null
&& !getFile().isFolder()) {
925 // currently selected file was removed in the server, and now we
927 cleanSecondFragment();
928 currentFile
= currentDir
;
931 if (synchFolderRemotePath
!= null
&&
932 currentDir
.getRemotePath().equals(synchFolderRemotePath
)) {
933 OCFileListFragment fileListFragment
= getListOfFilesFragment();
934 if (fileListFragment
!= null
) {
935 fileListFragment
.listDirectory();
936 // TODO Enable when "On Device" is recovered ?
937 // fileListFragment.listDirectory(currentDir,
938 // MainApp.getOnlyOnDevice());
941 setFile(currentFile
);
944 mSyncInProgress
= (!FileSyncAdapter
.EVENT_FULL_SYNC_END
.equals(event
) &&
945 !RefreshFolderOperation
.EVENT_SINGLE_FOLDER_SHARES_SYNCED
948 if (RefreshFolderOperation
.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED
.
949 equals(event
) &&/// TODO refactor and make common
951 synchResult
!= null
&& !synchResult
.isSuccess() &&
952 (synchResult
.getCode() == ResultCode
.UNAUTHORIZED
||
953 synchResult
.isIdPRedirection() ||
954 (synchResult
.isException() && synchResult
.getException()
955 instanceof AuthenticatorException
))) {
959 OwnCloudClient client
;
960 OwnCloudAccount ocAccount
=
961 new OwnCloudAccount(getAccount(), context
);
962 client
= (OwnCloudClientManagerFactory
.getDefaultSingleton().
963 removeClientFor(ocAccount
));
964 if (client
!= null
) {
965 OwnCloudCredentials cred
= client
.getCredentials();
967 AccountManager am
= AccountManager
.get(context
);
968 if (cred
.authTokenExpires()) {
969 am
.invalidateAuthToken(
974 am
.clearPassword(getAccount());
978 requestCredentialsUpdate();
980 } catch (AccountNotFoundException e
) {
981 Log_OC
.e(TAG
, "Account " + getAccount() + " was removed!", e
);
986 removeStickyBroadcast(intent
);
987 Log_OC
.d(TAG
, "Setting progress visibility to " + mSyncInProgress
);
988 mProgressBar
.setIndeterminate(mSyncInProgress
);
989 //mProgressBar.setVisibility((mSyncInProgress) ? View.VISIBLE : View.INVISIBLE);
990 //setSupportProgressBarIndeterminateVisibility(mSyncInProgress
991 /*|| mRefreshSharesInProgress*/ //);
997 if (synchResult
!= null
) {
998 if (synchResult
.getCode().equals(
999 RemoteOperationResult
.ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
)) {
1000 mLastSslUntrustedServerResult
= synchResult
;
1003 } catch (RuntimeException e
) {
1004 // avoid app crashes after changing the serial id of RemoteOperationResult
1005 // in owncloud library with broadcast notifications pending to process
1006 removeStickyBroadcast(intent
);
1012 * Show a text message on screen view for notifying user if content is
1013 * loading or folder is empty
1015 private void setBackgroundText() {
1016 OCFileListFragment ocFileListFragment
= getListOfFilesFragment();
1017 if (ocFileListFragment
!= null
) {
1018 int message
= R
.string
.file_list_loading
;
1019 if (!mSyncInProgress
) {
1020 // In case file list is empty
1021 message
= R
.string
.file_list_empty
;
1023 ocFileListFragment
.setMessageForEmptyList(getString(message
));
1025 Log_OC
.e(TAG
, "OCFileListFragment is null");
1030 * Once the file upload has finished -> update view
1032 private class UploadFinishReceiver
extends BroadcastReceiver
{
1034 * Once the file upload has finished -> update view
1036 * @author David A. Velasco
1037 * {@link BroadcastReceiver} to enable upload feedback in UI
1040 public void onReceive(Context context
, Intent intent
) {
1042 String uploadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1043 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
1044 boolean sameAccount
= getAccount() != null
&& accountName
.equals(getAccount().name
);
1045 OCFile currentDir
= getCurrentDir();
1046 boolean isDescendant
= (currentDir
!= null
) && (uploadedRemotePath
!= null
) &&
1047 (uploadedRemotePath
.startsWith(currentDir
.getRemotePath()));
1049 if (sameAccount
&& isDescendant
) {
1050 String linkedToRemotePath
=
1051 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1052 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1053 refreshListOfFilesFragment();
1057 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
,
1059 boolean renamedInUpload
= getFile().getRemotePath().
1060 equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
1061 boolean sameFile
= getFile().getRemotePath().equals(uploadedRemotePath
) ||
1063 FileFragment details
= getSecondFragment();
1064 boolean detailFragmentIsShown
= (details
!= null
&&
1065 details
instanceof FileDetailFragment
);
1067 if (sameAccount
&& sameFile
&& detailFragmentIsShown
) {
1068 if (uploadWasFine
) {
1069 setFile(getStorageManager().getFileByPath(uploadedRemotePath
));
1071 if (renamedInUpload
) {
1072 String newName
= (new File(uploadedRemotePath
)).getName();
1073 Toast msg
= Toast
.makeText(
1076 getString(R
.string
.filedetails_renamed_in_upload_msg
),
1081 if (uploadWasFine
|| getFile().fileExists()) {
1082 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1084 cleanSecondFragment();
1087 // Force the preview if the file is an image or text file
1088 if (uploadWasFine
) {
1089 OCFile ocFile
= getFile();
1090 if (PreviewImageFragment
.canBePreviewed(ocFile
))
1091 startImagePreview(getFile());
1092 else if (PreviewTextFragment
.canBePreviewed(ocFile
))
1093 startTextPreview(ocFile
);
1094 // TODO what about other kind of previews?
1098 mProgressBar
.setIndeterminate(false
);
1100 if (intent
!= null
) {
1101 removeStickyBroadcast(intent
);
1107 // TODO refactor this receiver, and maybe DownloadFinishReceiver; this method is duplicated :S
1108 private boolean isAscendant(String linkedToRemotePath
) {
1109 OCFile currentDir
= getCurrentDir();
1111 currentDir
!= null
&&
1112 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1121 * Class waiting for broadcast events from the {@link FileDownloader} service.
1123 * Updates the UI when a download is started or finished, provided that it is relevant for the
1126 private class DownloadFinishReceiver
extends BroadcastReceiver
{
1129 public void onReceive(Context context
, Intent intent
) {
1131 boolean sameAccount
= isSameAccount(intent
);
1132 String downloadedRemotePath
=
1133 intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
1134 boolean isDescendant
= isDescendant(downloadedRemotePath
);
1136 if (sameAccount
&& isDescendant
) {
1137 String linkedToRemotePath
=
1138 intent
.getStringExtra(FileDownloader
.EXTRA_LINKED_TO_PATH
);
1139 if (linkedToRemotePath
== null
|| isAscendant(linkedToRemotePath
)) {
1140 refreshListOfFilesFragment();
1142 refreshSecondFragment(
1144 downloadedRemotePath
,
1145 intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)
1149 if (mWaitingToSend
!= null
) {
1151 getStorageManager().getFileByPath(mWaitingToSend
.getRemotePath());
1152 if (mWaitingToSend
.isDown()) {
1153 sendDownloadedFile();
1158 if (intent
!= null
) {
1159 removeStickyBroadcast(intent
);
1164 private boolean isDescendant(String downloadedRemotePath
) {
1165 OCFile currentDir
= getCurrentDir();
1167 currentDir
!= null
&&
1168 downloadedRemotePath
!= null
&&
1169 downloadedRemotePath
.startsWith(currentDir
.getRemotePath())
1173 private boolean isAscendant(String linkedToRemotePath
) {
1174 OCFile currentDir
= getCurrentDir();
1176 currentDir
!= null
&&
1177 currentDir
.getRemotePath().startsWith(linkedToRemotePath
)
1181 private boolean isSameAccount(Intent intent
) {
1182 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
1183 return (accountName
!= null
&& getAccount() != null
&&
1184 accountName
.equals(getAccount().name
));
1189 public void browseToRoot() {
1190 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1191 if (listOfFiles
!= null
) { // should never be null, indeed
1192 OCFile root
= getStorageManager().getFileByPath(OCFile
.ROOT_PATH
);
1193 listOfFiles
.listDirectory(root
);
1194 // TODO Enable when "On Device" is recovered ?
1195 // listOfFiles.listDirectory(root, MainApp.getOnlyOnDevice());
1196 setFile(listOfFiles
.getCurrentFile());
1197 startSyncFolderOperation(root
, false
);
1199 cleanSecondFragment();
1206 * Updates action bar and second fragment, if in dual pane mode.
1209 public void onBrowsedDownTo(OCFile directory
) {
1211 cleanSecondFragment();
1213 startSyncFolderOperation(directory
, false
);
1217 * Shows the information of the {@link OCFile} received as a
1218 * parameter in the second fragment.
1220 * @param file {@link OCFile} whose details will be shown
1223 public void showDetails(OCFile file
) {
1224 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1225 setSecondFragment(detailFragment
);
1226 updateFragmentsVisibility(true
);
1227 updateActionBarTitleAndHomeButton(file
);
1232 * Shows the share view for sharing {@link OCFile} received as a
1233 * parameter in the second fragment.
1235 * @param file {@link OCFile} File to share with
1238 public void showShareFile(OCFile file
) {
1239 Intent intent
= new Intent(this, ShareActivity
.class);
1240 intent
.putExtra(EXTRA_FILE
, file
);
1241 intent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1242 startActivity(intent
);
1246 protected void updateActionBarTitleAndHomeButton(OCFile chosenFile
) {
1248 // in dual pane mode, keep the focus of title an action bar in the current folder
1249 super.updateActionBarTitleAndHomeButton(getCurrentDir());
1252 super.updateActionBarTitleAndHomeButton(chosenFile
);
1258 protected ServiceConnection
newTransferenceServiceConnection() {
1259 return new ListServiceConnection();
1263 * Defines callbacks for service binding, passed to bindService()
1265 private class ListServiceConnection
implements ServiceConnection
{
1268 public void onServiceConnected(ComponentName component
, IBinder service
) {
1269 if (component
.equals(new ComponentName(
1270 FileDisplayActivity
.this, FileDownloader
.class))) {
1271 Log_OC
.d(TAG
, "Download service connected");
1272 mDownloaderBinder
= (FileDownloaderBinder
) service
;
1273 if (mWaitingToPreview
!= null
)
1274 if (getStorageManager() != null
) {
1277 getStorageManager().getFileById(mWaitingToPreview
.getFileId());
1278 if (!mWaitingToPreview
.isDown()) {
1279 requestForDownload();
1283 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1284 FileUploader
.class))) {
1285 Log_OC
.d(TAG
, "Upload service connected");
1286 mUploaderBinder
= (FileUploaderBinder
) service
;
1290 // a new chance to get the mDownloadBinder through
1291 // getFileDownloadBinder() - THIS IS A MESS
1292 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1293 if (listOfFiles
!= null
) {
1294 listOfFiles
.listDirectory();
1295 // TODO Enable when "On Device" is recovered ?
1296 // listOfFiles.listDirectory(MainApp.getOnlyOnDevice());
1298 FileFragment secondFragment
= getSecondFragment();
1299 if (secondFragment
!= null
&& secondFragment
instanceof FileDetailFragment
) {
1300 FileDetailFragment detailFragment
= (FileDetailFragment
) secondFragment
;
1301 detailFragment
.listenForTransferProgress();
1302 detailFragment
.updateFileDetails(false
, false
);
1307 public void onServiceDisconnected(ComponentName component
) {
1308 if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1309 FileDownloader
.class))) {
1310 Log_OC
.d(TAG
, "Download service disconnected");
1311 mDownloaderBinder
= null
;
1312 } else if (component
.equals(new ComponentName(FileDisplayActivity
.this,
1313 FileUploader
.class))) {
1314 Log_OC
.d(TAG
, "Upload service disconnected");
1315 mUploaderBinder
= null
;
1321 public void onSavedCertificate() {
1322 startSyncFolderOperation(getCurrentDir(), false
);
1327 public void onFailedSavingCertificate() {
1328 ConfirmationDialogFragment dialog
= ConfirmationDialogFragment
.newInstance(
1329 R
.string
.ssl_validator_not_saved
, new String
[]{}, R
.string
.common_ok
, -1, -1
1331 dialog
.show(getSupportFragmentManager(), DIALOG_CERT_NOT_SAVED
);
1335 public void onCancelCertificate() {
1340 * Updates the view associated to the activity after the finish of some operation over files
1341 * in the current account.
1343 * @param operation Removal operation performed.
1344 * @param result Result of the removal.
1347 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1348 super.onRemoteOperationFinish(operation
, result
);
1350 if (operation
instanceof RemoveFileOperation
) {
1351 onRemoveFileOperationFinish((RemoveFileOperation
) operation
, result
);
1353 } else if (operation
instanceof RenameFileOperation
) {
1354 onRenameFileOperationFinish((RenameFileOperation
) operation
, result
);
1356 } else if (operation
instanceof SynchronizeFileOperation
) {
1357 onSynchronizeFileOperationFinish((SynchronizeFileOperation
) operation
, result
);
1359 } else if (operation
instanceof CreateFolderOperation
) {
1360 onCreateFolderOperationFinish((CreateFolderOperation
) operation
, result
);
1362 } else if (operation
instanceof CreateShareViaLinkOperation
||
1363 operation
instanceof CreateShareWithShareeOperation
) {
1365 refreshShowDetails();
1366 refreshListOfFilesFragment();
1368 } else if (operation
instanceof UnshareOperation
) {
1369 onUnshareLinkOperationFinish((UnshareOperation
) operation
, result
);
1371 } else if (operation
instanceof MoveFileOperation
) {
1372 onMoveFileOperationFinish((MoveFileOperation
) operation
, result
);
1374 } else if (operation
instanceof CopyFileOperation
) {
1375 onCopyFileOperationFinish((CopyFileOperation
) operation
, result
);
1380 private void onUnshareLinkOperationFinish(UnshareOperation operation
,
1381 RemoteOperationResult result
) {
1382 if (result
.isSuccess()) {
1383 refreshShowDetails();
1384 refreshListOfFilesFragment();
1386 } else if (result
.getCode() == ResultCode
.SHARE_NOT_FOUND
) {
1387 cleanSecondFragment();
1388 refreshListOfFilesFragment();
1392 private void refreshShowDetails() {
1393 FileFragment details
= getSecondFragment();
1394 if (details
!= null
) {
1395 OCFile file
= details
.getFile();
1397 file
= getStorageManager().getFileByPath(file
.getRemotePath());
1398 if (details
instanceof PreviewMediaFragment
) {
1399 // Refresh OCFile of the fragment
1400 ((PreviewMediaFragment
) details
).updateFile(file
);
1401 } else if (details
instanceof PreviewTextFragment
) {
1402 // Refresh OCFile of the fragment
1403 ((PreviewTextFragment
) details
).updateFile(file
);
1408 invalidateOptionsMenu();
1413 * Updates the view associated to the activity after the finish of an operation trying to
1416 * @param operation Removal operation performed.
1417 * @param result Result of the removal.
1419 private void onRemoveFileOperationFinish(RemoveFileOperation operation
,
1420 RemoteOperationResult result
) {
1421 Toast msg
= Toast
.makeText(this,
1422 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1426 if (result
.isSuccess()) {
1427 OCFile removedFile
= operation
.getFile();
1428 FileFragment second
= getSecondFragment();
1429 if (second
!= null
&& removedFile
.equals(second
.getFile())) {
1430 if (second
instanceof PreviewMediaFragment
) {
1431 ((PreviewMediaFragment
) second
).stopPreview(true
);
1433 setFile(getStorageManager().getFileById(removedFile
.getParentId()));
1434 cleanSecondFragment();
1436 if (getStorageManager().getFileById(removedFile
.getParentId()).equals(getCurrentDir())){
1437 refreshListOfFilesFragment();
1439 invalidateOptionsMenu();
1441 if (result
.isSslRecoverableException()) {
1442 mLastSslUntrustedServerResult
= result
;
1443 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1450 * Updates the view associated to the activity after the finish of an operation trying to move a
1453 * @param operation Move operation performed.
1454 * @param result Result of the move operation.
1456 private void onMoveFileOperationFinish(MoveFileOperation operation
,
1457 RemoteOperationResult result
) {
1458 if (result
.isSuccess()) {
1459 refreshListOfFilesFragment();
1462 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1463 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1467 } catch (NotFoundException e
) {
1468 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1474 * Updates the view associated to the activity after the finish of an operation trying to copy a
1477 * @param operation Copy operation performed.
1478 * @param result Result of the copy operation.
1480 private void onCopyFileOperationFinish(CopyFileOperation operation
, RemoteOperationResult result
) {
1481 if (result
.isSuccess()) {
1482 refreshListOfFilesFragment();
1485 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1486 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1490 } catch (NotFoundException e
) {
1491 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1497 * Updates the view associated to the activity after the finish of an operation trying to rename
1500 * @param operation Renaming operation performed.
1501 * @param result Result of the renaming.
1503 private void onRenameFileOperationFinish(RenameFileOperation operation
,
1504 RemoteOperationResult result
) {
1505 OCFile renamedFile
= operation
.getFile();
1506 if (result
.isSuccess()) {
1507 FileFragment details
= getSecondFragment();
1508 if (details
!= null
) {
1509 if (details
instanceof FileDetailFragment
&&
1510 renamedFile
.equals(details
.getFile()) ) {
1511 ((FileDetailFragment
) details
).updateFileDetails(renamedFile
, getAccount());
1512 showDetails(renamedFile
);
1514 } else if (details
instanceof PreviewMediaFragment
&&
1515 renamedFile
.equals(details
.getFile())) {
1516 ((PreviewMediaFragment
) details
).updateFile(renamedFile
);
1517 if (PreviewMediaFragment
.canBePreviewed(renamedFile
)) {
1518 int position
= ((PreviewMediaFragment
) details
).getPosition();
1519 startMediaPreview(renamedFile
, position
, true
);
1521 getFileOperationsHelper().openFile(renamedFile
);
1523 } else if (details
instanceof PreviewTextFragment
&&
1524 renamedFile
.equals(details
.getFile())) {
1525 ((PreviewTextFragment
) details
).updateFile(renamedFile
);
1526 if (PreviewTextFragment
.canBePreviewed(renamedFile
)) {
1527 startTextPreview(renamedFile
);
1529 getFileOperationsHelper().openFile(renamedFile
);
1534 if (getStorageManager().getFileById(renamedFile
.getParentId()).equals(getCurrentDir())){
1535 refreshListOfFilesFragment();
1539 Toast msg
= Toast
.makeText(this,
1540 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1544 if (result
.isSslRecoverableException()) {
1545 mLastSslUntrustedServerResult
= result
;
1546 showUntrustedCertDialog(mLastSslUntrustedServerResult
);
1551 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
,
1552 RemoteOperationResult result
) {
1553 if (result
.isSuccess()) {
1554 if (operation
.transferWasRequested()) {
1555 OCFile syncedFile
= operation
.getLocalFile();
1556 onTransferStateChanged(syncedFile
, true
, true
);
1557 invalidateOptionsMenu();
1558 refreshShowDetails();
1564 * Updates the view associated to the activity after the finish of an operation trying create a
1567 * @param operation Creation operation performed.
1568 * @param result Result of the creation.
1570 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
1571 RemoteOperationResult result
) {
1572 if (result
.isSuccess()) {
1573 refreshListOfFilesFragment();
1576 Toast msg
= Toast
.makeText(FileDisplayActivity
.this,
1577 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
1581 } catch (NotFoundException e
) {
1582 Log_OC
.e(TAG
, "Error while trying to show fail message ", e
);
1592 public void onTransferStateChanged(OCFile file
, boolean downloading
, boolean uploading
) {
1593 refreshListOfFilesFragment();
1594 FileFragment details
= getSecondFragment();
1595 if (details
!= null
&& details
instanceof FileDetailFragment
&&
1596 file
.equals(details
.getFile()) ) {
1597 if (downloading
|| uploading
) {
1598 ((FileDetailFragment
) details
).updateFileDetails(file
, getAccount());
1600 if (!file
.fileExists()) {
1601 cleanSecondFragment();
1603 ((FileDetailFragment
) details
).updateFileDetails(false
, true
);
1611 private void requestForDownload() {
1612 Account account
= getAccount();
1613 //if (!mWaitingToPreview.isDownloading()) {
1614 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1615 Intent i
= new Intent(this, FileDownloader
.class);
1616 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1617 i
.putExtra(FileDownloader
.EXTRA_FILE
, mWaitingToPreview
);
1623 private OCFile
getCurrentDir() {
1624 OCFile file
= getFile();
1626 if (file
.isFolder()) {
1628 } else if (getStorageManager() != null
) {
1629 String parentPath
= file
.getRemotePath().substring(0,
1630 file
.getRemotePath().lastIndexOf(file
.getFileName()));
1631 return getStorageManager().getFileByPath(parentPath
);
1637 public void startSyncFolderOperation(OCFile folder
, boolean ignoreETag
) {
1638 long currentSyncTime
= System
.currentTimeMillis();
1640 mSyncInProgress
= true
;
1642 // perform folder synchronization
1643 RemoteOperation synchFolderOp
= new RefreshFolderOperation( folder
,
1646 getFileOperationsHelper().isSharedSupported(),
1648 getStorageManager(),
1650 getApplicationContext()
1652 synchFolderOp
.execute(getAccount(), MainApp
.getAppContext(), this, null
, null
);
1654 mProgressBar
.setIndeterminate(true
);
1656 setBackgroundText();
1660 * Show untrusted cert dialog
1662 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1663 // Show a dialog with the certificate info
1664 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(
1665 (CertificateCombinedException
) result
.getException());
1666 FragmentManager fm
= getSupportFragmentManager();
1667 FragmentTransaction ft
= fm
.beginTransaction();
1668 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1671 private void requestForDownload(OCFile file
) {
1672 Account account
= getAccount();
1673 if (!mDownloaderBinder
.isDownloading(account
, mWaitingToPreview
)) {
1674 Intent i
= new Intent(this, FileDownloader
.class);
1675 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, account
);
1676 i
.putExtra(FileDownloader
.EXTRA_FILE
, file
);
1681 private void sendDownloadedFile() {
1682 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend
);
1683 mWaitingToSend
= null
;
1688 * Requests the download of the received {@link OCFile} , updates the UI
1689 * to monitor the download progress and prepares the activity to send the file
1690 * when the download finishes.
1692 * @param file {@link OCFile} to download and preview.
1694 public void startDownloadForSending(OCFile file
) {
1695 mWaitingToSend
= file
;
1696 requestForDownload(mWaitingToSend
);
1697 boolean hasSecondFragment
= (getSecondFragment() != null
);
1698 updateFragmentsVisibility(hasSecondFragment
);
1702 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1704 * @param file Image {@link OCFile} to show.
1706 public void startImagePreview(OCFile file
) {
1707 Intent showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
1708 showDetailsIntent
.putExtra(EXTRA_FILE
, file
);
1709 showDetailsIntent
.putExtra(EXTRA_ACCOUNT
, getAccount());
1710 startActivity(showDetailsIntent
);
1714 * Stars the preview of an already down media {@link OCFile}.
1716 * @param file Media {@link OCFile} to preview.
1717 * @param startPlaybackPosition Media position where the playback will be started,
1719 * @param autoplay When 'true', the playback will start without user
1722 public void startMediaPreview(OCFile file
, int startPlaybackPosition
, boolean autoplay
) {
1723 Fragment mediaFragment
= new PreviewMediaFragment(file
, getAccount(), startPlaybackPosition
,
1725 setSecondFragment(mediaFragment
);
1726 updateFragmentsVisibility(true
);
1727 updateActionBarTitleAndHomeButton(file
);
1732 * Stars the preview of a text file {@link OCFile}.
1734 * @param file Text {@link OCFile} to preview.
1736 public void startTextPreview(OCFile file
) {
1737 Bundle args
= new Bundle();
1738 args
.putParcelable(EXTRA_FILE
, file
);
1739 args
.putParcelable(EXTRA_ACCOUNT
, getAccount());
1740 Fragment textPreviewFragment
= Fragment
.instantiate(getApplicationContext(),
1741 PreviewTextFragment
.class.getName(), args
);
1742 setSecondFragment(textPreviewFragment
);
1743 updateFragmentsVisibility(true
);
1744 //updateNavigationElementsInActionBar(file);
1749 * Requests the download of the received {@link OCFile} , updates the UI
1750 * to monitor the download progress and prepares the activity to preview
1751 * or open the file when the download finishes.
1753 * @param file {@link OCFile} to download and preview.
1755 public void startDownloadForPreview(OCFile file
) {
1756 Fragment detailFragment
= FileDetailFragment
.newInstance(file
, getAccount());
1757 setSecondFragment(detailFragment
);
1758 mWaitingToPreview
= file
;
1759 requestForDownload();
1760 updateFragmentsVisibility(true
);
1761 updateActionBarTitleAndHomeButton(file
);
1766 public void cancelTransference(OCFile file
) {
1767 getFileOperationsHelper().cancelTransference(file
);
1768 if (mWaitingToPreview
!= null
&&
1769 mWaitingToPreview
.getRemotePath().equals(file
.getRemotePath())) {
1770 mWaitingToPreview
= null
;
1772 if (mWaitingToSend
!= null
&&
1773 mWaitingToSend
.getRemotePath().equals(file
.getRemotePath())) {
1774 mWaitingToSend
= null
;
1776 onTransferStateChanged(file
, false
, false
);
1780 public void onRefresh(boolean ignoreETag
) {
1781 refreshList(ignoreETag
);
1785 public void onRefresh() {
1789 private void refreshList(boolean ignoreETag
) {
1790 OCFileListFragment listOfFiles
= getListOfFilesFragment();
1791 if (listOfFiles
!= null
) {
1792 OCFile folder
= listOfFiles
.getCurrentFile();
1793 if (folder
!= null
) {
1794 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1795 listDirectory(mFile);*/
1796 startSyncFolderOperation(folder
, ignoreETag
);
1801 private void sortByDate(boolean ascending
) {
1802 getListOfFilesFragment().sortByDate(ascending
);
1805 private void sortBySize(boolean ascending
) {
1806 getListOfFilesFragment().sortBySize(ascending
);
1809 private void sortByName(boolean ascending
) {
1810 getListOfFilesFragment().sortByName(ascending
);
1813 public void allFilesOption() {