1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
25 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
27 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
28 import org
.apache
.http
.HttpStatus
;
29 import org
.apache
.http
.NameValuePair
;
30 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
31 import org
.apache
.http
.entity
.FileEntity
;
32 import org
.apache
.http
.message
.BasicNameValuePair
;
33 import org
.apache
.http
.protocol
.HTTP
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
35 import org
.json
.JSONObject
;
37 import android
.accounts
.Account
;
38 import android
.accounts
.AccountManager
;
39 import android
.annotation
.SuppressLint
;
40 import android
.app
.Activity
;
41 import android
.content
.ActivityNotFoundException
;
42 import android
.content
.BroadcastReceiver
;
43 import android
.content
.ComponentName
;
44 import android
.content
.Context
;
45 import android
.content
.Intent
;
46 import android
.content
.IntentFilter
;
47 import android
.content
.ServiceConnection
;
48 import android
.graphics
.Bitmap
;
49 import android
.graphics
.BitmapFactory
;
50 import android
.graphics
.BitmapFactory
.Options
;
51 import android
.graphics
.Point
;
52 import android
.net
.Uri
;
53 import android
.os
.AsyncTask
;
54 import android
.os
.Bundle
;
55 import android
.os
.Handler
;
56 import android
.os
.IBinder
;
57 import android
.support
.v4
.app
.DialogFragment
;
58 import android
.support
.v4
.app
.FragmentTransaction
;
59 import android
.util
.Log
;
60 import android
.view
.Display
;
61 import android
.view
.LayoutInflater
;
62 import android
.view
.MotionEvent
;
63 import android
.view
.View
;
64 import android
.view
.View
.OnClickListener
;
65 import android
.view
.View
.OnTouchListener
;
66 import android
.view
.ViewGroup
;
67 import android
.webkit
.MimeTypeMap
;
68 import android
.widget
.Button
;
69 import android
.widget
.CheckBox
;
70 import android
.widget
.ImageView
;
71 import android
.widget
.MediaController
;
72 import android
.widget
.TextView
;
73 import android
.widget
.Toast
;
74 import android
.widget
.VideoView
;
76 import com
.actionbarsherlock
.app
.SherlockFragment
;
77 import com
.owncloud
.android
.AccountUtils
;
78 import com
.owncloud
.android
.DisplayUtils
;
79 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
80 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
81 import com
.owncloud
.android
.datamodel
.OCFile
;
82 import com
.owncloud
.android
.files
.services
.FileDownloader
;
83 import com
.owncloud
.android
.files
.services
.FileObserverService
;
84 import com
.owncloud
.android
.files
.services
.FileUploader
;
85 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
86 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
87 import com
.owncloud
.android
.media
.MediaService
;
88 import com
.owncloud
.android
.media
.MediaServiceBinder
;
89 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
90 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
91 import com
.owncloud
.android
.operations
.RemoteOperation
;
92 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
93 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
94 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
95 import com
.owncloud
.android
.operations
.RenameFileOperation
;
96 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
97 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
98 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
99 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
100 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
101 import com
.owncloud
.android
.ui
.activity
.VideoActivity
;
102 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
103 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
104 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
106 import com
.owncloud
.android
.R
;
107 import eu
.alefzero
.webdav
.WebdavClient
;
108 import eu
.alefzero
.webdav
.WebdavUtils
;
111 * This Fragment is used to display the details about a file.
113 * @author Bartek Przybylski
116 public class FileDetailFragment
extends SherlockFragment
implements
117 OnClickListener
, OnTouchListener
,
118 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
120 public static final String EXTRA_FILE
= "FILE";
121 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
123 private FileDetailFragment
.ContainerActivity mContainerActivity
;
127 private OCFile mFile
;
128 private Account mAccount
;
129 private FileDataStorageManager mStorageManager
;
130 private ImageView mPreview
;
132 private DownloadFinishReceiver mDownloadFinishReceiver
;
133 private UploadFinishReceiver mUploadFinishReceiver
;
135 private Handler mHandler
;
136 private RemoteOperation mLastRemoteOperation
;
137 private DialogFragment mCurrentDialog
;
139 private MediaServiceBinder mMediaServiceBinder
= null
;
140 private MediaController mMediaController
= null
;
141 private MediaServiceConnection mMediaServiceConnection
= null
;
143 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
144 public static final String FTAG
= "FileDetails";
145 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
149 * Creates an empty details fragment.
151 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
153 public FileDetailFragment() {
156 mStorageManager
= null
;
157 mLayout
= R
.layout
.file_details_empty
;
162 * Creates a details fragment.
164 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
166 * @param fileToDetail An {@link OCFile} to show in the fragment
167 * @param ocAccount An ownCloud account; needed to start downloads
169 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
170 mFile
= fileToDetail
;
171 mAccount
= ocAccount
;
172 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
173 mLayout
= R
.layout
.file_details_empty
;
178 public void onCreate(Bundle savedInstanceState
) {
179 super.onCreate(savedInstanceState
);
180 mHandler
= new Handler();
185 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
186 Bundle savedInstanceState
) {
187 super.onCreateView(inflater
, container
, savedInstanceState
);
189 if (savedInstanceState
!= null
) {
190 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
191 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
194 if(mFile
!= null
&& mAccount
!= null
) {
195 mLayout
= R
.layout
.file_details_fragment
;
199 view
= inflater
.inflate(mLayout
, container
, false
);
202 if (mLayout
== R
.layout
.file_details_fragment
) {
203 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
204 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
205 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
206 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
207 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
208 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
209 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
210 mPreview
.setOnTouchListener(this);
213 updateFileDetails(false
);
222 public void onAttach(Activity activity
) {
223 super.onAttach(activity
);
225 mContainerActivity
= (ContainerActivity
) activity
;
226 } catch (ClassCastException e
) {
227 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
236 public void onActivityCreated(Bundle savedInstanceState
) {
237 super.onActivityCreated(savedInstanceState
);
238 if (mAccount
!= null
) {
239 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
245 public void onSaveInstanceState(Bundle outState
) {
246 Log
.i(getClass().toString(), "onSaveInstanceState() start");
247 super.onSaveInstanceState(outState
);
248 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
249 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
250 Log
.i(getClass().toString(), "onSaveInstanceState() end");
254 public void onStart() {
256 if (mFile
!= null
&& mFile
.isAudio()) {
262 public void onResume() {
265 mDownloadFinishReceiver
= new DownloadFinishReceiver();
266 IntentFilter filter
= new IntentFilter(
267 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
268 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
270 mUploadFinishReceiver
= new UploadFinishReceiver();
271 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
272 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
274 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
); // this is here just because it is nullified in onPause()
276 if (mMediaController
!= null
) {
277 mMediaController
.show();
283 public void onPause() {
286 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
287 mDownloadFinishReceiver
= null
;
289 getActivity().unregisterReceiver(mUploadFinishReceiver
);
290 mUploadFinishReceiver
= null
;
292 if (mPreview
!= null
) { // why?
296 if (mMediaController
!= null
) {
297 mMediaController
.hide();
303 public void onStop() {
305 if (mMediaServiceConnection
!= null
) {
306 Log
.d(TAG
, "Unbinding from MediaService ...");
307 getActivity().unbindService(mMediaServiceConnection
);
308 mMediaServiceBinder
= null
;
309 mMediaController
= null
;
315 public View
getView() {
316 return super.getView() == null ? mView
: super.getView();
321 public void onClick(View v
) {
323 case R
.id
.fdDownloadBtn
: {
324 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
325 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
326 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
327 downloaderBinder
.cancel(mAccount
, mFile
);
328 if (mFile
.isDown()) {
331 setButtonsForRemote();
334 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
335 uploaderBinder
.cancel(mAccount
, mFile
);
336 if (!mFile
.fileExists()) {
337 // TODO make something better
338 if (getActivity() instanceof FileDisplayActivity
) {
340 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
341 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
342 transaction
.commit();
343 mContainerActivity
.onFileStateChanged();
345 getActivity().finish();
348 } else if (mFile
.isDown()) {
351 setButtonsForRemote();
355 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
356 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
357 mLastRemoteOperation
.execute(wc
, this, mHandler
);
360 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
361 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
362 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
367 case R
.id
.fdKeepInSync
: {
368 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
369 mFile
.setKeepInSync(cb
.isChecked());
370 mStorageManager
.saveFile(mFile
);
372 /// register the OCFile instance in the observer service to monitor local updates;
373 /// if necessary, the file is download
374 Intent intent
= new Intent(getActivity().getApplicationContext(),
375 FileObserverService
.class);
376 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
378 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
379 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
380 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
381 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
382 Log
.e(TAG
, "starting observer service");
383 getActivity().startService(intent
);
385 if (mFile
.keepInSync()) {
386 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
390 case R
.id
.fdRenameBtn
: {
391 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
392 dialog
.show(getFragmentManager(), "nameeditdialog");
395 case R
.id
.fdRemoveBtn
: {
396 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
397 R
.string
.confirmation_remove_alert
,
398 new String
[]{mFile
.getFileName()},
399 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
400 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
401 R
.string
.common_cancel
);
402 confDialog
.setOnConfirmationListener(this);
403 mCurrentDialog
= confDialog
;
404 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
407 case R
.id
.fdOpenBtn
: {
412 Log
.e(TAG
, "Incorrect view clicked!");
415 /* else if (v.getId() == R.id.fdShareBtn) {
416 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
423 public boolean onTouch(View v
, MotionEvent event
) {
424 if (v
== mPreview
&& event
.getAction() == MotionEvent
.ACTION_DOWN
&& mFile
!= null
&& mFile
.isDown()) {
425 if (mFile
.isAudio()) {
426 if (!mMediaServiceBinder
.isPlaying(mFile
)) {
427 Log
.d(TAG
, "starting playback of " + mFile
.getStoragePath());
428 mMediaServiceBinder
.start(mAccount
, mFile
);
429 // this is a patch; need to synchronize this with the onPrepared() coming from MediaPlayer in the MediaService
430 mMediaController
.postDelayed(new Runnable() {
433 mMediaController
.show(0);
437 mMediaController
.show(0);
440 } else if (mFile
.isVideo()) {
441 startVideoActivity();
448 private void startVideoActivity() {
449 Intent i
= new Intent(getActivity(), VideoActivity
.class);
450 i
.putExtra(VideoActivity
.EXTRA_PATH
, mFile
.getStoragePath());
453 // TODO THROW AN ACTIVTIY JUST FOR PREVIEW VIDEO
455 if (mMediaController == null) {
456 mMediaController = new MediaController(getActivity());
457 mMediaController.setAnchorView(mVideoPreview);
458 //mMediaController.setEnabled(true);
460 //mMediaController.setMediaPlayer(mMediaServiceBinder);
461 if (!mVideoPreviewIsLoaded) {
462 mVideoPreviewIsLoaded = true;
463 mMediaController.setMediaPlayer(mVideoPreview);
464 mVideoPreview.setMediaController(mMediaController);
465 mVideoPreview.setVideoPath(mFile.getStoragePath());
466 mVideoPreview.start();
467 //mMediaController.show(0);
469 mMediaController.show(0);
474 private void bindMediaService() {
475 Log
.d(TAG
, "Binding to MediaService...");
476 if (mMediaServiceConnection
== null
) {
477 mMediaServiceConnection
= new MediaServiceConnection();
479 getActivity().bindService( new Intent(getActivity(),
481 mMediaServiceConnection
,
482 Context
.BIND_AUTO_CREATE
);
485 /** Defines callbacks for service binding, passed to bindService() */
486 private class MediaServiceConnection
implements ServiceConnection
{
489 public void onServiceConnected(ComponentName component
, IBinder service
) {
490 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
491 Log
.d(TAG
, "Media service connected");
492 mMediaServiceBinder
= (MediaServiceBinder
) service
;
493 if (mMediaServiceBinder
!= null
) {
494 if (mMediaController
== null
) {
495 mMediaController
= new MediaController(getSherlockActivity());
497 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
498 mMediaController
.setAnchorView(mPreview
);
499 mMediaController
.setEnabled(true
);
501 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
504 Log
.e(TAG
, "Unexpected response from MediaService while binding");
510 public void onServiceDisconnected(ComponentName component
) {
511 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
512 Log
.d(TAG
, "Media service suddenly disconnected");
513 if (mMediaController
!= null
) {
514 mMediaController
.hide();
515 mMediaController
.setMediaPlayer(null
); // TODO check this is not an error
516 mMediaController
= null
;
518 mMediaServiceBinder
= null
;
519 mMediaServiceConnection
= null
;
528 private void openFile() {
530 String storagePath
= mFile
.getStoragePath();
531 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
533 Intent i
= new Intent(Intent
.ACTION_VIEW
);
534 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
535 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
538 } catch (Throwable t
) {
539 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
540 boolean toastIt
= true
;
541 String mimeType
= "";
543 Intent i
= new Intent(Intent
.ACTION_VIEW
);
544 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
545 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
546 if (mimeType
!= null
) {
547 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
550 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
552 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
557 } catch (IndexOutOfBoundsException e
) {
558 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
560 } catch (ActivityNotFoundException e
) {
561 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
563 } catch (Throwable th
) {
564 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
568 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
577 public void onConfirmation(String callerTag
) {
578 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
579 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
580 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
583 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
584 mLastRemoteOperation
.execute(wc
, this, mHandler
);
586 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
587 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
590 mCurrentDialog
.dismiss();
591 mCurrentDialog
= null
;
595 public void onNeutral(String callerTag
) {
597 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
599 mFile
.setStoragePath(null
);
600 mStorageManager
.saveFile(mFile
);
601 updateFileDetails(mFile
, mAccount
);
603 mCurrentDialog
.dismiss();
604 mCurrentDialog
= null
;
608 public void onCancel(String callerTag
) {
609 Log
.d(TAG
, "REMOVAL CANCELED");
610 mCurrentDialog
.dismiss();
611 mCurrentDialog
= null
;
616 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
618 * @return True when the fragment was created with the empty layout.
620 public boolean isEmpty() {
621 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
626 * Can be used to get the file that is currently being displayed.
627 * @return The file on the screen.
629 public OCFile
getDisplayedFile(){
634 * Use this method to signal this Activity that it shall update its view.
636 * @param file : An {@link OCFile}
638 public void updateFileDetails(OCFile file
, Account ocAccount
) {
640 if (ocAccount
!= null
&& (
641 mStorageManager
== null
||
642 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
644 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
646 mAccount
= ocAccount
;
647 updateFileDetails(false
);
652 * Updates the view with all relevant details about that file.
654 * TODO Remove parameter when the transferring state of files is kept in database.
656 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
658 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
659 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
660 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
663 public void updateFileDetails(boolean transferring
) {
668 setFilename(mFile
.getFileName());
669 setFiletype(mFile
.getMimetype());
670 setFilesize(mFile
.getFileLength());
671 if(ocVersionSupportsTimeCreated()){
672 setTimeCreated(mFile
.getCreationTimestamp());
675 setTimeModified(mFile
.getModificationTimestamp());
677 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
678 cb
.setChecked(mFile
.keepInSync());
680 // configure UI for depending upon local state of the file
681 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
682 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
683 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
684 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
685 setButtonsForTransferring();
687 } else if (mFile
.isDown()) {
689 if (mFile
.getMimetype().startsWith("image/")) {
690 BitmapLoader bl
= new BitmapLoader();
691 bl
.execute(new String
[]{mFile
.getStoragePath()});
697 // TODO load default preview image; when the local file is removed, the preview remains there
698 setButtonsForRemote();
701 getView().invalidate();
706 * Checks if the fragment is ready to show details of a OCFile
708 * @return 'True' when the fragment is ready to show details of a file
710 private boolean readyToShow() {
711 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
717 * Updates the filename in view
718 * @param filename to set
720 private void setFilename(String filename
) {
721 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
723 tv
.setText(filename
);
727 * Updates the MIME type in view
728 * @param mimetype to set
730 private void setFiletype(String mimetype
) {
731 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
733 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
734 tv
.setText(printableMimetype
);
736 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
738 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
743 * Updates the file size in view
744 * @param filesize in bytes to set
746 private void setFilesize(long filesize
) {
747 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
749 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
753 * Updates the time that the file was created in view
754 * @param milliseconds Unix time to set
756 private void setTimeCreated(long milliseconds
){
757 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
758 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
760 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
761 tv
.setVisibility(View
.VISIBLE
);
762 tvLabel
.setVisibility(View
.VISIBLE
);
767 * Updates the time that the file was last modified
768 * @param milliseconds Unix time to set
770 private void setTimeModified(long milliseconds
){
771 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
773 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
778 * Enables or disables buttons for a file being downloaded
780 private void setButtonsForTransferring() {
782 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
783 downloadButton
.setText(R
.string
.common_cancel
);
784 //downloadButton.setEnabled(false);
786 // let's protect the user from himself ;)
787 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
788 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
789 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
790 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
795 * Enables or disables buttons for a file locally available
797 private void setButtonsForDown() {
799 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
800 downloadButton
.setText(R
.string
.filedetails_sync_file
);
802 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
803 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
804 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
805 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
810 * Enables or disables buttons for a file not locally available
812 private void setButtonsForRemote() {
814 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
815 downloadButton
.setText(R
.string
.filedetails_download
);
817 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
818 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
819 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
820 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
826 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
827 * the time that the file was created. There is a chance that this will
828 * be fixed in future versions. Use this method to check if this version of
829 * ownCloud has this fix.
830 * @return True, if ownCloud the ownCloud version is supporting creation time
832 private boolean ocVersionSupportsTimeCreated(){
833 /*if(mAccount != null){
834 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
835 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
836 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
837 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
846 * Interface to implement by any Activity that includes some instance of FileDetailFragment
848 * @author David A. Velasco
850 public interface ContainerActivity
extends TransferServiceGetter
{
853 * Callback method invoked when the detail fragment wants to notice its container
854 * activity about a relevant state the file shown by the fragment.
856 * Added to notify to FileDisplayActivity about the need of refresh the files list.
858 * Currently called when:
859 * - a download is started;
860 * - a rename is completed;
861 * - a deletion is completed;
862 * - the 'inSync' flag is changed;
864 public void onFileStateChanged();
870 * Once the file download has finished -> update view
871 * @author Bartek Przybylski
873 private class DownloadFinishReceiver
extends BroadcastReceiver
{
875 public void onReceive(Context context
, Intent intent
) {
876 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
878 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
879 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
880 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
881 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
882 if (downloadWasFine
) {
883 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
885 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
893 * Once the file upload has finished -> update view
895 * Being notified about the finish of an upload is necessary for the next sequence:
896 * 1. Upload a big file.
897 * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
898 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
899 * 3. Click the file in the list to see its details.
900 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
902 private class UploadFinishReceiver
extends BroadcastReceiver
{
904 public void onReceive(Context context
, Intent intent
) {
905 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
907 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
908 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
909 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
910 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
911 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
914 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
916 if (renamedInUpload
) {
917 String newName
= (new File(uploadRemotePath
)).getName();
918 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
921 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
922 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
929 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
930 @SuppressWarnings("unused")
931 private class ShareRunnable
implements Runnable
{
932 private String mPath
;
934 public ShareRunnable(String path
) {
939 AccountManager am
= AccountManager
.get(getActivity());
940 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
941 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
942 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
944 Log
.d("share", "sharing for version " + ocv
.toString());
946 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
947 String APPS_PATH
= "/apps/files_sharing/";
948 String SHARE_PATH
= "ajax/share.php";
950 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
952 final String WEBDAV_SCRIPT
= "webdav.php";
953 final String WEBDAV_FILES_LOCATION
= "/files/";
955 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
956 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
957 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
959 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
960 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
962 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
964 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
965 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
966 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
967 Log
.d("share", mPath
+"");
968 formparams
.add(new BasicNameValuePair("sources",mPath
));
969 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
970 formparams
.add(new BasicNameValuePair("permissions", "0"));
971 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
975 PropFindMethod find
= new PropFindMethod(url
+"/");
976 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
977 Log
.d("sharer", ""+ url
+"/");
979 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
980 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
983 int status2
= wc
.executeMethod(find
);
985 Log
.d("sharer", "propstatus "+status2
);
987 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
988 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
990 status2
= wc
.executeMethod(get
);
992 Log
.d("sharer", "getstatus "+status2
);
993 Log
.d("sharer", "" + get
.getResponseBodyAsString());
995 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
996 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
999 status
= wc
.executeMethod(post
);
1000 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
1001 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
1003 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
1004 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
1006 String resp
= post
.getResponseBodyAsString();
1007 Log
.d("share", ""+post
.getURI().toString());
1008 Log
.d("share", "returned status " + status
);
1009 Log
.d("share", " " +resp
);
1011 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
1015 JSONObject jsonObject
= new JSONObject (resp
);
1016 String jsonStatus
= jsonObject
.getString("status");
1017 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
1019 String token
= jsonObject
.getString("data");
1020 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
1021 Log
.d("Actions:shareFile ok", "url: " + uri
);
1023 } catch (Exception e
) {
1024 e
.printStackTrace();
1027 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
1033 public void onDismiss(EditNameDialog dialog
) {
1034 if (dialog
.getResult()) {
1035 String newFilename
= dialog
.getNewFilename();
1036 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
1037 mLastRemoteOperation
= new RenameFileOperation( mFile
,
1040 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
1041 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
1042 mLastRemoteOperation
.execute(wc
, this, mHandler
);
1043 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1044 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1049 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1050 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1052 protected Bitmap
doInBackground(String
... params
) {
1053 Bitmap result
= null
;
1054 if (params
.length
!= 1) return result
;
1055 String storagePath
= params
[0];
1058 BitmapFactory
.Options options
= new Options();
1059 options
.inScaled
= true
;
1060 options
.inPurgeable
= true
;
1061 options
.inJustDecodeBounds
= true
;
1062 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1063 options
.inPreferQualityOverSpeed
= false
;
1065 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1066 options
.inMutable
= false
;
1069 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1070 options
.inJustDecodeBounds
= false
;
1072 int width
= options
.outWidth
;
1073 int height
= options
.outHeight
;
1075 if (width
>= 2048 || height
>= 2048) {
1076 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1077 options
.inSampleSize
= scale
;
1079 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1080 Point size
= new Point();
1082 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1083 display
.getSize(size
);
1084 screenwidth
= size
.x
;
1086 screenwidth
= display
.getWidth();
1089 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1091 if (width
> screenwidth
) {
1092 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1093 options
.inSampleSize
= scale
;
1096 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1098 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1100 } catch (OutOfMemoryError e
) {
1102 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1104 } catch (NoSuchFieldError e
) {
1106 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1108 } catch (Throwable t
) {
1110 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1115 protected void onPostExecute(Bitmap result
) {
1116 if (result
!= null
&& mPreview
!= null
) {
1117 mPreview
.setImageBitmap(result
);
1127 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1128 if (operation
.equals(mLastRemoteOperation
)) {
1129 if (operation
instanceof RemoveFileOperation
) {
1130 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1132 } else if (operation
instanceof RenameFileOperation
) {
1133 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1135 } else if (operation
instanceof SynchronizeFileOperation
) {
1136 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1142 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1143 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1144 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1146 if (result
.isSuccess()) {
1147 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1149 if (inDisplayActivity
) {
1151 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1152 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1153 transaction
.commit();
1154 mContainerActivity
.onFileStateChanged();
1156 getActivity().finish();
1160 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1162 if (result
.isSslRecoverableException()) {
1163 // TODO show the SSL warning dialog
1168 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1169 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1170 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1172 if (result
.isSuccess()) {
1173 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1174 mContainerActivity
.onFileStateChanged();
1177 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1178 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1180 // TODO throw again the new rename dialog
1182 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1184 if (result
.isSslRecoverableException()) {
1185 // TODO show the SSL warning dialog
1191 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1192 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1193 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1195 if (!result
.isSuccess()) {
1196 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1197 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1198 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1199 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1203 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1207 if (mFile
.isDown()) {
1208 setButtonsForDown();
1211 setButtonsForRemote();
1215 if (operation
.transferWasRequested()) {
1216 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1217 // checking the service to see if the file is downloading results in FALSE
1219 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1221 if (mFile
.isDown()) {
1222 setButtonsForDown();
1225 setButtonsForRemote();