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
.OnSwipeTouchListener
;
101 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
102 import com
.owncloud
.android
.ui
.activity
.VideoActivity
;
103 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
104 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
105 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
107 import com
.owncloud
.android
.R
;
108 import eu
.alefzero
.webdav
.WebdavClient
;
109 import eu
.alefzero
.webdav
.WebdavUtils
;
112 * This Fragment is used to display the details about a file.
114 * @author Bartek Przybylski
115 * @author David A. Velasco
117 public class FileDetailFragment
extends SherlockFragment
implements
118 OnClickListener
, OnTouchListener
,
119 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
122 public static final String EXTRA_FILE
= "FILE";
123 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
125 private FileDetailFragment
.ContainerActivity mContainerActivity
;
129 private OCFile mFile
;
130 private Account mAccount
;
131 private FileDataStorageManager mStorageManager
;
132 private ImageView mPreview
;
134 private DownloadFinishReceiver mDownloadFinishReceiver
;
135 private UploadFinishReceiver mUploadFinishReceiver
;
137 private Handler mHandler
;
138 private RemoteOperation mLastRemoteOperation
;
139 private DialogFragment mCurrentDialog
;
141 private MediaServiceBinder mMediaServiceBinder
= null
;
142 private MediaController mMediaController
= null
;
143 private MediaServiceConnection mMediaServiceConnection
= null
;
145 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
146 public static final String FTAG
= "FileDetails";
147 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
151 * Creates an empty details fragment.
153 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
155 public FileDetailFragment() {
158 mStorageManager
= null
;
159 mLayout
= R
.layout
.file_details_empty
;
164 * Creates a details fragment.
166 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
168 * @param fileToDetail An {@link OCFile} to show in the fragment
169 * @param ocAccount An ownCloud account; needed to start downloads
171 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
172 mFile
= fileToDetail
;
173 mAccount
= ocAccount
;
174 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
175 mLayout
= R
.layout
.file_details_empty
;
180 public void onCreate(Bundle savedInstanceState
) {
181 super.onCreate(savedInstanceState
);
182 mHandler
= new Handler();
187 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
188 Bundle savedInstanceState
) {
189 super.onCreateView(inflater
, container
, savedInstanceState
);
191 if (savedInstanceState
!= null
) {
192 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
193 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
196 if(mFile
!= null
&& mAccount
!= null
) {
197 mLayout
= R
.layout
.file_details_fragment
;
201 view
= inflater
.inflate(mLayout
, container
, false
);
204 if (mLayout
== R
.layout
.file_details_fragment
) {
205 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
206 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
207 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
208 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
209 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
210 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
211 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
212 mPreview
.setOnTouchListener(this);
215 updateFileDetails(false
);
224 public void onAttach(Activity activity
) {
225 super.onAttach(activity
);
227 mContainerActivity
= (ContainerActivity
) activity
;
229 } catch (ClassCastException e
) {
230 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
239 public void onActivityCreated(Bundle savedInstanceState
) {
240 super.onActivityCreated(savedInstanceState
);
241 if (mAccount
!= null
) {
242 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
243 mView
.setOnTouchListener(new OnSwipeTouchListener(getActivity()));
249 public void onSaveInstanceState(Bundle outState
) {
250 Log
.i(getClass().toString(), "onSaveInstanceState() start");
251 super.onSaveInstanceState(outState
);
252 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
253 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
254 Log
.i(getClass().toString(), "onSaveInstanceState() end");
258 public void onStart() {
260 if (mFile
!= null
&& mFile
.isAudio()) {
266 public void onResume() {
269 mDownloadFinishReceiver
= new DownloadFinishReceiver();
270 IntentFilter filter
= new IntentFilter(
271 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
272 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
274 mUploadFinishReceiver
= new UploadFinishReceiver();
275 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
276 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
278 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
); // this is here just because it is nullified in onPause()
284 public void onPause() {
287 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
288 mDownloadFinishReceiver
= null
;
290 getActivity().unregisterReceiver(mUploadFinishReceiver
);
291 mUploadFinishReceiver
= null
;
293 if (mPreview
!= null
) { // why?
301 public void onStop() {
303 if (mMediaServiceConnection
!= null
) {
304 Log
.d(TAG
, "Unbinding from MediaService ...");
305 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
306 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
308 getActivity().unbindService(mMediaServiceConnection
);
309 mMediaServiceBinder
= null
;
310 if (mMediaController
!= null
) {
311 mMediaController
.hide();
312 mMediaController
= null
;
319 public View
getView() {
320 return super.getView() == null ? mView
: super.getView();
325 public void onClick(View v
) {
327 case R
.id
.fdDownloadBtn
: {
328 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
329 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
330 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
331 downloaderBinder
.cancel(mAccount
, mFile
);
332 if (mFile
.isDown()) {
335 setButtonsForRemote();
338 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
339 uploaderBinder
.cancel(mAccount
, mFile
);
340 if (!mFile
.fileExists()) {
341 // TODO make something better
342 if (getActivity() instanceof FileDisplayActivity
) {
344 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
345 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
346 transaction
.commit();
347 mContainerActivity
.onFileStateChanged();
349 getActivity().finish();
352 } else if (mFile
.isDown()) {
355 setButtonsForRemote();
359 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
360 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
361 mLastRemoteOperation
.execute(wc
, this, mHandler
);
364 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
365 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
366 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
371 case R
.id
.fdKeepInSync
: {
372 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
373 mFile
.setKeepInSync(cb
.isChecked());
374 mStorageManager
.saveFile(mFile
);
376 /// register the OCFile instance in the observer service to monitor local updates;
377 /// if necessary, the file is download
378 Intent intent
= new Intent(getActivity().getApplicationContext(),
379 FileObserverService
.class);
380 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
382 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
383 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
384 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
385 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
386 Log
.e(TAG
, "starting observer service");
387 getActivity().startService(intent
);
389 if (mFile
.keepInSync()) {
390 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
394 case R
.id
.fdRenameBtn
: {
395 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
396 dialog
.show(getFragmentManager(), "nameeditdialog");
399 case R
.id
.fdRemoveBtn
: {
400 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
401 R
.string
.confirmation_remove_alert
,
402 new String
[]{mFile
.getFileName()},
403 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
404 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
405 R
.string
.common_cancel
);
406 confDialog
.setOnConfirmationListener(this);
407 mCurrentDialog
= confDialog
;
408 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
411 case R
.id
.fdOpenBtn
: {
416 Log
.e(TAG
, "Incorrect view clicked!");
419 /* else if (v.getId() == R.id.fdShareBtn) {
420 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
427 public boolean onTouch(View v
, MotionEvent event
) {
428 if (v
== mPreview
&& event
.getAction() == MotionEvent
.ACTION_DOWN
&& mFile
!= null
&& mFile
.isDown()) {
429 if (mFile
.isVideo()) {
430 startVideoActivity();
437 private void startVideoActivity() {
438 Intent i
= new Intent(getActivity(), VideoActivity
.class);
439 i
.putExtra(VideoActivity
.EXTRA_FILE
, mFile
);
440 i
.putExtra(VideoActivity
.EXTRA_ACCOUNT
, mAccount
);
445 private void bindMediaService() {
446 Log
.d(TAG
, "Binding to MediaService...");
447 if (mMediaServiceConnection
== null
) {
448 mMediaServiceConnection
= new MediaServiceConnection();
450 getActivity().bindService( new Intent(getActivity(),
452 mMediaServiceConnection
,
453 Context
.BIND_AUTO_CREATE
);
454 // follow the flow in MediaServiceConnection#onServiceConnected(...)
457 /** Defines callbacks for service binding, passed to bindService() */
458 private class MediaServiceConnection
implements ServiceConnection
{
461 public void onServiceConnected(ComponentName component
, IBinder service
) {
462 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
463 Log
.d(TAG
, "Media service connected");
464 mMediaServiceBinder
= (MediaServiceBinder
) service
;
465 if (mMediaServiceBinder
!= null
) {
466 if (mMediaController
== null
) {
467 mMediaController
= new MediaController(getSherlockActivity());
469 prepareMediaController();
471 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
474 Log
.e(TAG
, "Unexpected response from MediaService while binding");
479 private void prepareMediaController() {
480 mMediaServiceBinder
.registerMediaController(mMediaController
);
481 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
482 mMediaController
.setAnchorView(getView());
483 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
487 public void onServiceDisconnected(ComponentName component
) {
488 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
489 Log
.e(TAG
, "Media service suddenly disconnected");
490 if (mMediaController
!= null
) {
491 mMediaController
.hide();
492 mMediaController
.setMediaPlayer(null
);
493 mMediaController
= null
;
495 mMediaServiceBinder
= null
;
496 mMediaServiceConnection
= null
;
505 private void openFile() {
507 String storagePath
= mFile
.getStoragePath();
508 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
510 Intent i
= new Intent(Intent
.ACTION_VIEW
);
511 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
512 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
515 } catch (Throwable t
) {
516 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
517 boolean toastIt
= true
;
518 String mimeType
= "";
520 Intent i
= new Intent(Intent
.ACTION_VIEW
);
521 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
522 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
523 if (mimeType
!= null
) {
524 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
527 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
529 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
534 } catch (IndexOutOfBoundsException e
) {
535 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
537 } catch (ActivityNotFoundException e
) {
538 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
540 } catch (Throwable th
) {
541 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
545 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
554 public void onConfirmation(String callerTag
) {
555 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
556 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
557 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
560 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
561 mLastRemoteOperation
.execute(wc
, this, mHandler
);
563 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
564 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
567 mCurrentDialog
.dismiss();
568 mCurrentDialog
= null
;
572 public void onNeutral(String callerTag
) {
574 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
576 mFile
.setStoragePath(null
);
577 mStorageManager
.saveFile(mFile
);
578 updateFileDetails(mFile
, mAccount
);
580 mCurrentDialog
.dismiss();
581 mCurrentDialog
= null
;
585 public void onCancel(String callerTag
) {
586 Log
.d(TAG
, "REMOVAL CANCELED");
587 mCurrentDialog
.dismiss();
588 mCurrentDialog
= null
;
593 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
595 * @return True when the fragment was created with the empty layout.
597 public boolean isEmpty() {
598 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
605 public OCFile
getFile(){
610 * Use this method to signal this Activity that it shall update its view.
612 * @param file : An {@link OCFile}
614 public void updateFileDetails(OCFile file
, Account ocAccount
) {
616 if (ocAccount
!= null
&& (
617 mStorageManager
== null
||
618 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
620 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
622 mAccount
= ocAccount
;
623 updateFileDetails(false
);
628 * Updates the view with all relevant details about that file.
630 * TODO Remove parameter when the transferring state of files is kept in database.
632 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
634 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
635 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
636 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
639 public void updateFileDetails(boolean transferring
) {
644 setFilename(mFile
.getFileName());
645 setFiletype(mFile
.getMimetype());
646 setFilesize(mFile
.getFileLength());
647 if(ocVersionSupportsTimeCreated()){
648 setTimeCreated(mFile
.getCreationTimestamp());
651 setTimeModified(mFile
.getModificationTimestamp());
653 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
654 cb
.setChecked(mFile
.keepInSync());
656 // configure UI for depending upon local state of the file
657 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
658 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
659 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
660 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
661 setButtonsForTransferring();
663 } else if (mFile
.isDown()) {
665 if (mFile
.getMimetype().startsWith("image/")) {
666 BitmapLoader bl
= new BitmapLoader();
667 bl
.execute(new String
[]{mFile
.getStoragePath()});
673 // TODO load default preview image; when the local file is removed, the preview remains there
674 setButtonsForRemote();
677 getView().invalidate();
682 * Checks if the fragment is ready to show details of a OCFile
684 * @return 'True' when the fragment is ready to show details of a file
686 private boolean readyToShow() {
687 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
693 * Updates the filename in view
694 * @param filename to set
696 private void setFilename(String filename
) {
697 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
699 tv
.setText(filename
);
703 * Updates the MIME type in view
704 * @param mimetype to set
706 private void setFiletype(String mimetype
) {
707 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
709 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
710 tv
.setText(printableMimetype
);
712 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
714 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
719 * Updates the file size in view
720 * @param filesize in bytes to set
722 private void setFilesize(long filesize
) {
723 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
725 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
729 * Updates the time that the file was created in view
730 * @param milliseconds Unix time to set
732 private void setTimeCreated(long milliseconds
){
733 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
734 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
736 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
737 tv
.setVisibility(View
.VISIBLE
);
738 tvLabel
.setVisibility(View
.VISIBLE
);
743 * Updates the time that the file was last modified
744 * @param milliseconds Unix time to set
746 private void setTimeModified(long milliseconds
){
747 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
749 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
754 * Enables or disables buttons for a file being downloaded
756 private void setButtonsForTransferring() {
758 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
759 downloadButton
.setText(R
.string
.common_cancel
);
760 //downloadButton.setEnabled(false);
762 // let's protect the user from himself ;)
763 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
764 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
765 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
766 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
771 * Enables or disables buttons for a file locally available
773 private void setButtonsForDown() {
775 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
776 downloadButton
.setText(R
.string
.filedetails_sync_file
);
778 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
779 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
780 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
781 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
786 * Enables or disables buttons for a file not locally available
788 private void setButtonsForRemote() {
790 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
791 downloadButton
.setText(R
.string
.filedetails_download
);
793 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
794 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
795 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
796 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
802 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
803 * the time that the file was created. There is a chance that this will
804 * be fixed in future versions. Use this method to check if this version of
805 * ownCloud has this fix.
806 * @return True, if ownCloud the ownCloud version is supporting creation time
808 private boolean ocVersionSupportsTimeCreated(){
809 /*if(mAccount != null){
810 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
811 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
812 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
813 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
822 * Interface to implement by any Activity that includes some instance of FileDetailFragment
824 * @author David A. Velasco
826 public interface ContainerActivity
extends TransferServiceGetter
{
829 * Callback method invoked when the detail fragment wants to notice its container
830 * activity about a relevant state the file shown by the fragment.
832 * Added to notify to FileDisplayActivity about the need of refresh the files list.
834 * Currently called when:
835 * - a download is started;
836 * - a rename is completed;
837 * - a deletion is completed;
838 * - the 'inSync' flag is changed;
840 public void onFileStateChanged();
846 * Once the file download has finished -> update view
847 * @author Bartek Przybylski
849 private class DownloadFinishReceiver
extends BroadcastReceiver
{
851 public void onReceive(Context context
, Intent intent
) {
852 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
854 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
855 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
856 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
857 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
858 if (downloadWasFine
) {
859 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
861 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
869 * Once the file upload has finished -> update view
871 * Being notified about the finish of an upload is necessary for the next sequence:
872 * 1. Upload a big file.
873 * 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
874 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
875 * 3. Click the file in the list to see its details.
876 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
878 private class UploadFinishReceiver
extends BroadcastReceiver
{
880 public void onReceive(Context context
, Intent intent
) {
881 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
883 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
884 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
885 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
886 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
887 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
890 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
892 if (renamedInUpload
) {
893 String newName
= (new File(uploadRemotePath
)).getName();
894 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
897 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
898 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
905 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
906 @SuppressWarnings("unused")
907 private class ShareRunnable
implements Runnable
{
908 private String mPath
;
910 public ShareRunnable(String path
) {
915 AccountManager am
= AccountManager
.get(getActivity());
916 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
917 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
918 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
920 Log
.d("share", "sharing for version " + ocv
.toString());
922 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
923 String APPS_PATH
= "/apps/files_sharing/";
924 String SHARE_PATH
= "ajax/share.php";
926 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
928 final String WEBDAV_SCRIPT
= "webdav.php";
929 final String WEBDAV_FILES_LOCATION
= "/files/";
931 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
932 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
933 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
935 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
936 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
938 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
940 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
941 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
942 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
943 Log
.d("share", mPath
+"");
944 formparams
.add(new BasicNameValuePair("sources",mPath
));
945 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
946 formparams
.add(new BasicNameValuePair("permissions", "0"));
947 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
951 PropFindMethod find
= new PropFindMethod(url
+"/");
952 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
953 Log
.d("sharer", ""+ url
+"/");
955 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
956 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
959 int status2
= wc
.executeMethod(find
);
961 Log
.d("sharer", "propstatus "+status2
);
963 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
964 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
966 status2
= wc
.executeMethod(get
);
968 Log
.d("sharer", "getstatus "+status2
);
969 Log
.d("sharer", "" + get
.getResponseBodyAsString());
971 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
972 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
975 status
= wc
.executeMethod(post
);
976 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
977 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
979 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
980 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
982 String resp
= post
.getResponseBodyAsString();
983 Log
.d("share", ""+post
.getURI().toString());
984 Log
.d("share", "returned status " + status
);
985 Log
.d("share", " " +resp
);
987 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
991 JSONObject jsonObject
= new JSONObject (resp
);
992 String jsonStatus
= jsonObject
.getString("status");
993 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
995 String token
= jsonObject
.getString("data");
996 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
997 Log
.d("Actions:shareFile ok", "url: " + uri
);
999 } catch (Exception e
) {
1000 e
.printStackTrace();
1003 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
1009 public void onDismiss(EditNameDialog dialog
) {
1010 if (dialog
.getResult()) {
1011 String newFilename
= dialog
.getNewFilename();
1012 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
1013 mLastRemoteOperation
= new RenameFileOperation( mFile
,
1016 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
1017 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
1018 mLastRemoteOperation
.execute(wc
, this, mHandler
);
1019 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1020 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1025 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1026 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1028 protected Bitmap
doInBackground(String
... params
) {
1029 Bitmap result
= null
;
1030 if (params
.length
!= 1) return result
;
1031 String storagePath
= params
[0];
1034 BitmapFactory
.Options options
= new Options();
1035 options
.inScaled
= true
;
1036 options
.inPurgeable
= true
;
1037 options
.inJustDecodeBounds
= true
;
1038 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1039 options
.inPreferQualityOverSpeed
= false
;
1041 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1042 options
.inMutable
= false
;
1045 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1046 options
.inJustDecodeBounds
= false
;
1048 int width
= options
.outWidth
;
1049 int height
= options
.outHeight
;
1051 if (width
>= 2048 || height
>= 2048) {
1052 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1053 options
.inSampleSize
= scale
;
1055 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1056 Point size
= new Point();
1058 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1059 display
.getSize(size
);
1060 screenwidth
= size
.x
;
1062 screenwidth
= display
.getWidth();
1065 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1067 if (width
> screenwidth
) {
1068 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1069 options
.inSampleSize
= scale
;
1072 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1074 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1076 } catch (OutOfMemoryError e
) {
1078 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1080 } catch (NoSuchFieldError e
) {
1082 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1084 } catch (Throwable t
) {
1086 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1091 protected void onPostExecute(Bitmap result
) {
1092 if (result
!= null
&& mPreview
!= null
) {
1093 mPreview
.setImageBitmap(result
);
1103 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1104 if (operation
.equals(mLastRemoteOperation
)) {
1105 if (operation
instanceof RemoveFileOperation
) {
1106 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1108 } else if (operation
instanceof RenameFileOperation
) {
1109 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1111 } else if (operation
instanceof SynchronizeFileOperation
) {
1112 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1118 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1119 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1120 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1122 if (result
.isSuccess()) {
1123 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1125 if (inDisplayActivity
) {
1127 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1128 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1129 transaction
.commit();
1130 mContainerActivity
.onFileStateChanged();
1132 getActivity().finish();
1136 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1138 if (result
.isSslRecoverableException()) {
1139 // TODO show the SSL warning dialog
1144 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1145 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1146 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1148 if (result
.isSuccess()) {
1149 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1150 mContainerActivity
.onFileStateChanged();
1153 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1154 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1156 // TODO throw again the new rename dialog
1158 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1160 if (result
.isSslRecoverableException()) {
1161 // TODO show the SSL warning dialog
1167 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1168 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1169 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1171 if (!result
.isSuccess()) {
1172 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1173 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1174 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1175 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1179 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1183 if (mFile
.isDown()) {
1184 setButtonsForDown();
1187 setButtonsForRemote();
1191 if (operation
.transferWasRequested()) {
1192 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1193 // checking the service to see if the file is downloading results in FALSE
1195 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1197 if (mFile
.isDown()) {
1198 setButtonsForDown();
1201 setButtonsForRemote();