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
.lang
.ref
.WeakReference
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
28 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
29 import org
.apache
.http
.HttpStatus
;
30 import org
.apache
.http
.NameValuePair
;
31 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
32 import org
.apache
.http
.entity
.FileEntity
;
33 import org
.apache
.http
.message
.BasicNameValuePair
;
34 import org
.apache
.http
.protocol
.HTTP
;
35 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import org
.json
.JSONObject
;
38 import android
.accounts
.Account
;
39 import android
.accounts
.AccountManager
;
40 import android
.annotation
.SuppressLint
;
41 import android
.app
.Activity
;
42 import android
.content
.ActivityNotFoundException
;
43 import android
.content
.BroadcastReceiver
;
44 import android
.content
.ComponentName
;
45 import android
.content
.Context
;
46 import android
.content
.Intent
;
47 import android
.content
.IntentFilter
;
48 import android
.content
.ServiceConnection
;
49 import android
.graphics
.Bitmap
;
50 import android
.graphics
.BitmapFactory
;
51 import android
.graphics
.BitmapFactory
.Options
;
52 import android
.graphics
.Point
;
53 import android
.net
.Uri
;
54 import android
.os
.AsyncTask
;
55 import android
.os
.Bundle
;
56 import android
.os
.Handler
;
57 import android
.os
.IBinder
;
58 import android
.support
.v4
.app
.DialogFragment
;
59 import android
.support
.v4
.app
.FragmentTransaction
;
60 import android
.util
.Log
;
61 import android
.view
.Display
;
62 import android
.view
.LayoutInflater
;
63 import android
.view
.MotionEvent
;
64 import android
.view
.View
;
65 import android
.view
.View
.OnClickListener
;
66 import android
.view
.View
.OnTouchListener
;
67 import android
.view
.ViewGroup
;
68 import android
.webkit
.MimeTypeMap
;
69 import android
.webkit
.WebView
.FindListener
;
70 import android
.widget
.Button
;
71 import android
.widget
.CheckBox
;
72 import android
.widget
.ImageView
;
73 import android
.widget
.MediaController
;
74 import android
.widget
.ProgressBar
;
75 import android
.widget
.TextView
;
76 import android
.widget
.Toast
;
77 import android
.widget
.VideoView
;
79 import com
.actionbarsherlock
.app
.SherlockFragment
;
80 import com
.owncloud
.android
.AccountUtils
;
81 import com
.owncloud
.android
.DisplayUtils
;
82 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
83 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
84 import com
.owncloud
.android
.datamodel
.OCFile
;
85 import com
.owncloud
.android
.files
.services
.FileDownloader
;
86 import com
.owncloud
.android
.files
.services
.FileObserverService
;
87 import com
.owncloud
.android
.files
.services
.FileUploader
;
88 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
89 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
90 import com
.owncloud
.android
.media
.MediaService
;
91 import com
.owncloud
.android
.media
.MediaServiceBinder
;
92 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
93 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
94 import com
.owncloud
.android
.operations
.RemoteOperation
;
95 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
96 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
97 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
98 import com
.owncloud
.android
.operations
.RenameFileOperation
;
99 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
100 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
101 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
102 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
103 import com
.owncloud
.android
.ui
.OnSwipeTouchListener
;
104 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
105 import com
.owncloud
.android
.ui
.activity
.VideoActivity
;
106 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
107 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
108 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
110 import com
.owncloud
.android
.R
;
112 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
113 import eu
.alefzero
.webdav
.WebdavClient
;
114 import eu
.alefzero
.webdav
.WebdavUtils
;
117 * This Fragment is used to display the details about a file.
119 * @author Bartek Przybylski
120 * @author David A. Velasco
122 public class FileDetailFragment
extends SherlockFragment
implements
124 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
127 public static final String EXTRA_FILE
= "FILE";
128 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
130 private FileFragment
.ContainerActivity mContainerActivity
;
134 private OCFile mFile
;
135 private Account mAccount
;
136 private FileDataStorageManager mStorageManager
;
138 private DownloadFinishReceiver mDownloadFinishReceiver
;
139 private UploadFinishReceiver mUploadFinishReceiver
;
140 public ProgressListener mProgressListener
;
142 private Handler mHandler
;
143 private RemoteOperation mLastRemoteOperation
;
145 private MediaServiceBinder mMediaServiceBinder
= null
;
146 private MediaController mMediaController
= null
;
147 private MediaServiceConnection mMediaServiceConnection
= null
;
149 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
150 public static final String FTAG
= "FileDetails";
151 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
155 * Creates an empty details fragment.
157 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
159 public FileDetailFragment() {
162 mStorageManager
= null
;
163 mLayout
= R
.layout
.file_details_empty
;
164 mProgressListener
= null
;
169 * Creates a details fragment.
171 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
173 * @param fileToDetail An {@link OCFile} to show in the fragment
174 * @param ocAccount An ownCloud account; needed to start downloads
176 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
177 mFile
= fileToDetail
;
178 mAccount
= ocAccount
;
179 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
180 mLayout
= R
.layout
.file_details_empty
;
181 mProgressListener
= null
;
186 public void onCreate(Bundle savedInstanceState
) {
187 super.onCreate(savedInstanceState
);
188 mHandler
= new Handler();
193 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
194 Bundle savedInstanceState
) {
195 super.onCreateView(inflater
, container
, savedInstanceState
);
197 if (savedInstanceState
!= null
) {
198 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
199 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
202 if(mFile
!= null
&& mAccount
!= null
) {
203 mLayout
= R
.layout
.file_details_fragment
;
207 view
= inflater
.inflate(mLayout
, container
, false
);
210 if (mLayout
== R
.layout
.file_details_fragment
) {
211 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
212 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
213 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
214 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
215 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
216 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
217 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
218 mProgressListener
= new ProgressListener(progressBar
);
221 updateFileDetails(false
);
230 public void onAttach(Activity activity
) {
231 super.onAttach(activity
);
233 mContainerActivity
= (ContainerActivity
) activity
;
235 } catch (ClassCastException e
) {
236 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
245 public void onActivityCreated(Bundle savedInstanceState
) {
246 super.onActivityCreated(savedInstanceState
);
247 if (mAccount
!= null
) {
248 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
249 mView
.setOnTouchListener(new OnSwipeTouchListener(getActivity()));
255 public void onSaveInstanceState(Bundle outState
) {
256 Log
.i(getClass().toString(), "onSaveInstanceState() start");
257 super.onSaveInstanceState(outState
);
258 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
259 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
260 Log
.i(getClass().toString(), "onSaveInstanceState() end");
264 public void onStart() {
266 if (mFile
!= null
&& mFile
.isAudio()) {
269 listenForTransferProgress();
273 public void onResume() {
276 mDownloadFinishReceiver
= new DownloadFinishReceiver();
277 IntentFilter filter
= new IntentFilter(
278 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
279 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
281 mUploadFinishReceiver
= new UploadFinishReceiver();
282 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
283 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
289 public void onPause() {
292 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
293 mDownloadFinishReceiver
= null
;
295 getActivity().unregisterReceiver(mUploadFinishReceiver
);
296 mUploadFinishReceiver
= null
;
302 public void onStop() {
304 if (mMediaServiceConnection
!= null
) {
305 Log
.d(TAG
, "Unbinding from MediaService ...");
306 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
307 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
309 getActivity().unbindService(mMediaServiceConnection
);
310 mMediaServiceBinder
= null
;
311 if (mMediaController
!= null
) {
312 mMediaController
.hide();
313 mMediaController
= null
;
316 leaveTransferProgress();
321 public View
getView() {
322 return super.getView() == null ? mView
: super.getView();
327 public void onClick(View v
) {
329 case R
.id
.fdDownloadBtn
: {
330 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
331 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
332 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
333 downloaderBinder
.cancel(mAccount
, mFile
);
334 if (mFile
.isDown()) {
337 setButtonsForRemote();
340 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
341 uploaderBinder
.cancel(mAccount
, mFile
);
342 if (!mFile
.fileExists()) {
343 // TODO make something better
344 if (getActivity() instanceof FileDisplayActivity
) {
346 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
347 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
348 transaction
.commit();
349 mContainerActivity
.onFileStateChanged();
351 getActivity().finish();
354 } else if (mFile
.isDown()) {
357 setButtonsForRemote();
361 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
362 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
363 mLastRemoteOperation
.execute(wc
, this, mHandler
);
366 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
367 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
368 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
373 case R
.id
.fdKeepInSync
: {
374 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
375 mFile
.setKeepInSync(cb
.isChecked());
376 mStorageManager
.saveFile(mFile
);
378 /// register the OCFile instance in the observer service to monitor local updates;
379 /// if necessary, the file is download
380 Intent intent
= new Intent(getActivity().getApplicationContext(),
381 FileObserverService
.class);
382 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
384 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
385 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
386 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
387 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
388 Log
.e(TAG
, "starting observer service");
389 getActivity().startService(intent
);
391 if (mFile
.keepInSync()) {
392 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
396 case R
.id
.fdRenameBtn
: {
397 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
398 dialog
.show(getFragmentManager(), "nameeditdialog");
401 case R
.id
.fdRemoveBtn
: {
402 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
403 R
.string
.confirmation_remove_alert
,
404 new String
[]{mFile
.getFileName()},
405 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
406 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
407 R
.string
.common_cancel
);
408 confDialog
.setOnConfirmationListener(this);
409 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
412 case R
.id
.fdOpenBtn
: {
417 Log
.e(TAG
, "Incorrect view clicked!");
420 /* else if (v.getId() == R.id.fdShareBtn) {
421 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
427 private void startVideoActivity() {
428 Intent i
= new Intent(getActivity(), VideoActivity
.class);
429 i
.putExtra(VideoActivity
.EXTRA_FILE
, mFile
);
430 i
.putExtra(VideoActivity
.EXTRA_ACCOUNT
, mAccount
);
435 private void bindMediaService() {
436 Log
.d(TAG
, "Binding to MediaService...");
437 if (mMediaServiceConnection
== null
) {
438 mMediaServiceConnection
= new MediaServiceConnection();
440 getActivity().bindService( new Intent(getActivity(),
442 mMediaServiceConnection
,
443 Context
.BIND_AUTO_CREATE
);
444 // follow the flow in MediaServiceConnection#onServiceConnected(...)
447 /** Defines callbacks for service binding, passed to bindService() */
448 private class MediaServiceConnection
implements ServiceConnection
{
451 public void onServiceConnected(ComponentName component
, IBinder service
) {
452 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
453 Log
.d(TAG
, "Media service connected");
454 mMediaServiceBinder
= (MediaServiceBinder
) service
;
455 if (mMediaServiceBinder
!= null
) {
456 if (mMediaController
== null
) {
457 mMediaController
= new MediaController(getSherlockActivity());
459 prepareMediaController();
461 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
464 Log
.e(TAG
, "Unexpected response from MediaService while binding");
469 private void prepareMediaController() {
470 mMediaServiceBinder
.registerMediaController(mMediaController
);
471 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
472 mMediaController
.setAnchorView(getView());
473 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
477 public void onServiceDisconnected(ComponentName component
) {
478 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
479 Log
.e(TAG
, "Media service suddenly disconnected");
480 if (mMediaController
!= null
) {
481 mMediaController
.hide();
482 mMediaController
.setMediaPlayer(null
);
483 mMediaController
= null
;
485 mMediaServiceBinder
= null
;
486 mMediaServiceConnection
= null
;
495 private void openFile() {
497 String storagePath
= mFile
.getStoragePath();
498 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
500 Intent i
= new Intent(Intent
.ACTION_VIEW
);
501 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
502 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
505 } catch (Throwable t
) {
506 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
507 boolean toastIt
= true
;
508 String mimeType
= "";
510 Intent i
= new Intent(Intent
.ACTION_VIEW
);
511 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
512 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
513 if (mimeType
!= null
) {
514 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
517 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
519 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
524 } catch (IndexOutOfBoundsException e
) {
525 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
527 } catch (ActivityNotFoundException e
) {
528 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
530 } catch (Throwable th
) {
531 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
535 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
544 public void onConfirmation(String callerTag
) {
545 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
546 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
547 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
550 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
551 mLastRemoteOperation
.execute(wc
, this, mHandler
);
553 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
554 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
560 public void onNeutral(String callerTag
) {
562 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
564 mFile
.setStoragePath(null
);
565 mStorageManager
.saveFile(mFile
);
566 updateFileDetails(mFile
, mAccount
);
571 public void onCancel(String callerTag
) {
572 Log
.d(TAG
, "REMOVAL CANCELED");
577 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
579 * @return True when the fragment was created with the empty layout.
581 public boolean isEmpty() {
582 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
589 public OCFile
getFile(){
594 * Use this method to signal this Activity that it shall update its view.
596 * @param file : An {@link OCFile}
598 public void updateFileDetails(OCFile file
, Account ocAccount
) {
600 if (ocAccount
!= null
&& (
601 mStorageManager
== null
||
602 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
604 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
606 mAccount
= ocAccount
;
607 updateFileDetails(false
);
612 * Updates the view with all relevant details about that file.
614 * TODO Remove parameter when the transferring state of files is kept in database.
616 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
618 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
619 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
620 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
623 public void updateFileDetails(boolean transferring
) {
628 setFilename(mFile
.getFileName());
629 setFiletype(mFile
.getMimetype());
630 setFilesize(mFile
.getFileLength());
631 if(ocVersionSupportsTimeCreated()){
632 setTimeCreated(mFile
.getCreationTimestamp());
635 setTimeModified(mFile
.getModificationTimestamp());
637 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
638 cb
.setChecked(mFile
.keepInSync());
640 // configure UI for depending upon local state of the file
641 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
642 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
643 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
644 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
645 setButtonsForTransferring();
647 } else if (mFile
.isDown()) {
652 // TODO load default preview image; when the local file is removed, the preview remains there
653 setButtonsForRemote();
656 getView().invalidate();
661 * Checks if the fragment is ready to show details of a OCFile
663 * @return 'True' when the fragment is ready to show details of a file
665 private boolean readyToShow() {
666 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
672 * Updates the filename in view
673 * @param filename to set
675 private void setFilename(String filename
) {
676 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
678 tv
.setText(filename
);
682 * Updates the MIME type in view
683 * @param mimetype to set
685 private void setFiletype(String mimetype
) {
686 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
688 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
689 tv
.setText(printableMimetype
);
691 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
693 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
698 * Updates the file size in view
699 * @param filesize in bytes to set
701 private void setFilesize(long filesize
) {
702 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
704 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
708 * Updates the time that the file was created in view
709 * @param milliseconds Unix time to set
711 private void setTimeCreated(long milliseconds
){
712 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
713 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
715 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
716 tv
.setVisibility(View
.VISIBLE
);
717 tvLabel
.setVisibility(View
.VISIBLE
);
722 * Updates the time that the file was last modified
723 * @param milliseconds Unix time to set
725 private void setTimeModified(long milliseconds
){
726 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
728 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
733 * Enables or disables buttons for a file being downloaded
735 private void setButtonsForTransferring() {
737 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
738 downloadButton
.setText(R
.string
.common_cancel
);
739 //downloadButton.setEnabled(false);
741 // let's protect the user from himself ;)
742 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
743 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
744 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
745 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
747 // show the progress bar for the transfer
748 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
749 progressBar
.setVisibility(View
.VISIBLE
);
750 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
751 progressText
.setVisibility(View
.VISIBLE
);
752 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
753 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
754 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
755 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
756 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
757 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
764 * Enables or disables buttons for a file locally available
766 private void setButtonsForDown() {
768 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
769 downloadButton
.setText(R
.string
.filedetails_sync_file
);
771 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
772 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
773 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
774 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
776 // hides the progress bar
777 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
778 progressBar
.setVisibility(View
.GONE
);
783 * Enables or disables buttons for a file not locally available
785 private void setButtonsForRemote() {
787 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
788 downloadButton
.setText(R
.string
.filedetails_download
);
790 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
791 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
792 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
793 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
795 // hides the progress bar
796 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
797 progressBar
.setVisibility(View
.GONE
);
803 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
804 * the time that the file was created. There is a chance that this will
805 * be fixed in future versions. Use this method to check if this version of
806 * ownCloud has this fix.
807 * @return True, if ownCloud the ownCloud version is supporting creation time
809 private boolean ocVersionSupportsTimeCreated(){
810 /*if(mAccount != null){
811 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
812 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
813 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
814 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
823 * Once the file download has finished -> update view
824 * @author Bartek Przybylski
826 private class DownloadFinishReceiver
extends BroadcastReceiver
{
828 public void onReceive(Context context
, Intent intent
) {
829 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
831 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
832 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
833 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
834 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
835 if (downloadWasFine
) {
836 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
838 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
846 * Once the file upload has finished -> update view
848 * Being notified about the finish of an upload is necessary for the next sequence:
849 * 1. Upload a big file.
850 * 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
851 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
852 * 3. Click the file in the list to see its details.
853 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
855 private class UploadFinishReceiver
extends BroadcastReceiver
{
857 public void onReceive(Context context
, Intent intent
) {
858 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
860 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
861 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
862 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
863 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
864 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
867 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
869 if (renamedInUpload
) {
870 String newName
= (new File(uploadRemotePath
)).getName();
871 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
874 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
875 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
882 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
883 @SuppressWarnings("unused")
884 private class ShareRunnable
implements Runnable
{
885 private String mPath
;
887 public ShareRunnable(String path
) {
892 AccountManager am
= AccountManager
.get(getActivity());
893 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
894 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
895 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
897 Log
.d("share", "sharing for version " + ocv
.toString());
899 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
900 String APPS_PATH
= "/apps/files_sharing/";
901 String SHARE_PATH
= "ajax/share.php";
903 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
905 final String WEBDAV_SCRIPT
= "webdav.php";
906 final String WEBDAV_FILES_LOCATION
= "/files/";
908 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
909 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
910 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
912 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
913 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
915 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
917 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
918 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
919 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
920 Log
.d("share", mPath
+"");
921 formparams
.add(new BasicNameValuePair("sources",mPath
));
922 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
923 formparams
.add(new BasicNameValuePair("permissions", "0"));
924 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
928 PropFindMethod find
= new PropFindMethod(url
+"/");
929 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
930 Log
.d("sharer", ""+ url
+"/");
932 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
933 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
936 int status2
= wc
.executeMethod(find
);
938 Log
.d("sharer", "propstatus "+status2
);
940 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
941 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
943 status2
= wc
.executeMethod(get
);
945 Log
.d("sharer", "getstatus "+status2
);
946 Log
.d("sharer", "" + get
.getResponseBodyAsString());
948 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
949 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
952 status
= wc
.executeMethod(post
);
953 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
954 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
956 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
957 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
959 String resp
= post
.getResponseBodyAsString();
960 Log
.d("share", ""+post
.getURI().toString());
961 Log
.d("share", "returned status " + status
);
962 Log
.d("share", " " +resp
);
964 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
968 JSONObject jsonObject
= new JSONObject (resp
);
969 String jsonStatus
= jsonObject
.getString("status");
970 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
972 String token
= jsonObject
.getString("data");
973 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
974 Log
.d("Actions:shareFile ok", "url: " + uri
);
976 } catch (Exception e
) {
980 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
986 public void onDismiss(EditNameDialog dialog
) {
987 if (dialog
.getResult()) {
988 String newFilename
= dialog
.getNewFilename();
989 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
990 mLastRemoteOperation
= new RenameFileOperation( mFile
,
993 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
994 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
995 mLastRemoteOperation
.execute(wc
, this, mHandler
);
996 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
997 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1006 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1007 if (operation
.equals(mLastRemoteOperation
)) {
1008 if (operation
instanceof RemoveFileOperation
) {
1009 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1011 } else if (operation
instanceof RenameFileOperation
) {
1012 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1014 } else if (operation
instanceof SynchronizeFileOperation
) {
1015 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1021 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1022 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1023 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1025 if (result
.isSuccess()) {
1026 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1028 if (inDisplayActivity
) {
1030 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1031 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1032 transaction
.commit();
1033 mContainerActivity
.onFileStateChanged();
1035 getActivity().finish();
1039 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1041 if (result
.isSslRecoverableException()) {
1042 // TODO show the SSL warning dialog
1047 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1048 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1049 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1051 if (result
.isSuccess()) {
1052 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1053 mContainerActivity
.onFileStateChanged();
1056 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1057 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1059 // TODO throw again the new rename dialog
1061 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1063 if (result
.isSslRecoverableException()) {
1064 // TODO show the SSL warning dialog
1070 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1071 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1072 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1074 if (!result
.isSuccess()) {
1075 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1076 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1077 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1078 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1082 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1086 if (mFile
.isDown()) {
1087 setButtonsForDown();
1090 setButtonsForRemote();
1094 if (operation
.transferWasRequested()) {
1095 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1096 // checking the service to see if the file is downloading results in FALSE
1098 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1100 if (mFile
.isDown()) {
1101 setButtonsForDown();
1104 setButtonsForRemote();
1111 public void listenForTransferProgress() {
1112 if (mProgressListener
!= null
) {
1113 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1114 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1116 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1117 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1123 public void leaveTransferProgress() {
1124 if (mProgressListener
!= null
) {
1125 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1126 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1128 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1129 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1137 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1139 * @author David A. Velasco
1141 private class ProgressListener
implements OnDatatransferProgressListener
{
1142 int mLastPercent
= 0;
1143 WeakReference
<ProgressBar
> mProgressBar
= null
;
1145 ProgressListener(ProgressBar progressBar
) {
1146 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1150 public void onTransferProgress(long progressRate
) {
1151 // old method, nothing here
1155 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1156 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1157 if (percent
!= mLastPercent
) {
1158 ProgressBar pb
= mProgressBar
.get();
1160 pb
.setProgress(percent
);
1161 pb
.postInvalidate();
1164 mLastPercent
= percent
;