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
.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
.app
.Activity
;
40 import android
.content
.ActivityNotFoundException
;
41 import android
.content
.BroadcastReceiver
;
42 import android
.content
.ComponentName
;
43 import android
.content
.Context
;
44 import android
.content
.Intent
;
45 import android
.content
.IntentFilter
;
46 import android
.content
.ServiceConnection
;
47 import android
.net
.Uri
;
48 import android
.os
.Bundle
;
49 import android
.os
.Handler
;
50 import android
.os
.IBinder
;
51 import android
.support
.v4
.app
.FragmentTransaction
;
52 import android
.util
.Log
;
53 import android
.view
.LayoutInflater
;
54 import android
.view
.View
;
55 import android
.view
.View
.OnClickListener
;
56 import android
.view
.ViewGroup
;
57 import android
.webkit
.MimeTypeMap
;
58 import android
.widget
.Button
;
59 import android
.widget
.CheckBox
;
60 import android
.widget
.ImageView
;
61 import android
.widget
.MediaController
;
62 import android
.widget
.ProgressBar
;
63 import android
.widget
.TextView
;
64 import android
.widget
.Toast
;
66 import com
.actionbarsherlock
.app
.SherlockFragment
;
67 import com
.owncloud
.android
.AccountUtils
;
68 import com
.owncloud
.android
.DisplayUtils
;
69 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
70 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
71 import com
.owncloud
.android
.datamodel
.OCFile
;
72 import com
.owncloud
.android
.files
.services
.FileDownloader
;
73 import com
.owncloud
.android
.files
.services
.FileObserverService
;
74 import com
.owncloud
.android
.files
.services
.FileUploader
;
75 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
76 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
77 import com
.owncloud
.android
.media
.MediaService
;
78 import com
.owncloud
.android
.media
.MediaServiceBinder
;
79 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
80 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
81 import com
.owncloud
.android
.operations
.RemoteOperation
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
83 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
84 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
85 import com
.owncloud
.android
.operations
.RenameFileOperation
;
86 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
87 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
88 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
89 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
90 import com
.owncloud
.android
.ui
.activity
.PreviewVideoActivity
;
91 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
93 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
95 import com
.owncloud
.android
.R
;
97 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
98 import eu
.alefzero
.webdav
.WebdavClient
;
99 import eu
.alefzero
.webdav
.WebdavUtils
;
102 * This Fragment is used to display the details about a file.
104 * @author Bartek Przybylski
105 * @author David A. Velasco
107 public class FileDetailFragment
extends SherlockFragment
implements
109 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
112 public static final String EXTRA_FILE
= "FILE";
113 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
115 private FileFragment
.ContainerActivity mContainerActivity
;
119 private OCFile mFile
;
120 private Account mAccount
;
121 private FileDataStorageManager mStorageManager
;
123 //private DownloadFinishReceiver mDownloadFinishReceiver;
124 private UploadFinishReceiver mUploadFinishReceiver
;
125 public ProgressListener mProgressListener
;
127 private Handler mHandler
;
128 private RemoteOperation mLastRemoteOperation
;
130 private MediaServiceBinder mMediaServiceBinder
= null
;
131 private MediaController mMediaController
= null
;
132 private MediaServiceConnection mMediaServiceConnection
= null
;
134 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
135 public static final String FTAG
= "FileDetails";
136 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
140 * Creates an empty details fragment.
142 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
144 public FileDetailFragment() {
147 mStorageManager
= null
;
148 mLayout
= R
.layout
.file_details_empty
;
149 mProgressListener
= null
;
154 * Creates a details fragment.
156 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
158 * @param fileToDetail An {@link OCFile} to show in the fragment
159 * @param ocAccount An ownCloud account; needed to start downloads
161 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
162 mFile
= fileToDetail
;
163 mAccount
= ocAccount
;
164 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
165 mLayout
= R
.layout
.file_details_empty
;
166 mProgressListener
= null
;
171 public void onCreate(Bundle savedInstanceState
) {
172 super.onCreate(savedInstanceState
);
173 mHandler
= new Handler();
178 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
179 Bundle savedInstanceState
) {
180 super.onCreateView(inflater
, container
, savedInstanceState
);
182 if (savedInstanceState
!= null
) {
183 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
184 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
187 if(mFile
!= null
&& mAccount
!= null
) {
188 mLayout
= R
.layout
.file_details_fragment
;
192 view
= inflater
.inflate(mLayout
, container
, false
);
195 if (mLayout
== R
.layout
.file_details_fragment
) {
196 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
197 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
198 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
199 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
200 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
201 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
202 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
203 mProgressListener
= new ProgressListener(progressBar
);
206 updateFileDetails(false
, false
);
215 public void onAttach(Activity activity
) {
216 super.onAttach(activity
);
218 mContainerActivity
= (ContainerActivity
) activity
;
220 } catch (ClassCastException e
) {
221 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
230 public void onActivityCreated(Bundle savedInstanceState
) {
231 super.onActivityCreated(savedInstanceState
);
232 if (mAccount
!= null
) {
233 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
239 public void onSaveInstanceState(Bundle outState
) {
240 super.onSaveInstanceState(outState
);
241 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
242 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
246 public void onStart() {
248 if (mFile
!= null
&& mFile
.isAudio()) {
251 listenForTransferProgress();
255 public void onResume() {
259 mDownloadFinishReceiver = new DownloadFinishReceiver();
260 IntentFilter filter = new IntentFilter(
261 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
262 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
265 mUploadFinishReceiver
= new UploadFinishReceiver();
266 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
267 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
273 public void onPause() {
277 if (mDownloadFinishReceiver != null) {
278 getActivity().unregisterReceiver(mDownloadFinishReceiver);
279 mDownloadFinishReceiver = null;
283 if (mUploadFinishReceiver
!= null
) {
284 getActivity().unregisterReceiver(mUploadFinishReceiver
);
285 mUploadFinishReceiver
= null
;
291 public void onStop() {
293 if (mMediaServiceConnection
!= null
) {
294 Log
.d(TAG
, "Unbinding from MediaService ...");
295 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
296 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
298 getActivity().unbindService(mMediaServiceConnection
);
299 mMediaServiceBinder
= null
;
300 if (mMediaController
!= null
) {
301 mMediaController
.hide();
302 mMediaController
= null
;
305 leaveTransferProgress();
310 public View
getView() {
311 return super.getView() == null ? mView
: super.getView();
316 public void onClick(View v
) {
318 case R
.id
.fdDownloadBtn
: {
319 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
320 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
321 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
322 downloaderBinder
.cancel(mAccount
, mFile
);
323 if (mFile
.isDown()) {
326 setButtonsForRemote();
329 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
330 uploaderBinder
.cancel(mAccount
, mFile
);
331 if (!mFile
.fileExists()) {
332 // TODO make something better
333 if (getActivity() instanceof FileDisplayActivity
) {
335 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
336 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
337 transaction
.commit();
338 mContainerActivity
.onFileStateChanged();
340 getActivity().finish();
343 } else if (mFile
.isDown()) {
346 setButtonsForRemote();
350 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
351 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
352 mLastRemoteOperation
.execute(wc
, this, mHandler
);
355 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
356 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
361 case R
.id
.fdKeepInSync
: {
362 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
363 mFile
.setKeepInSync(cb
.isChecked());
364 mStorageManager
.saveFile(mFile
);
366 /// register the OCFile instance in the observer service to monitor local updates;
367 /// if necessary, the file is download
368 Intent intent
= new Intent(getActivity().getApplicationContext(),
369 FileObserverService
.class);
370 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
372 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
373 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
374 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
375 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
376 getActivity().startService(intent
);
378 if (mFile
.keepInSync()) {
379 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
383 case R
.id
.fdRenameBtn
: {
384 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
385 dialog
.show(getFragmentManager(), "nameeditdialog");
388 case R
.id
.fdRemoveBtn
: {
389 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
390 R
.string
.confirmation_remove_alert
,
391 new String
[]{mFile
.getFileName()},
392 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
393 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
394 R
.string
.common_cancel
);
395 confDialog
.setOnConfirmationListener(this);
396 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
399 case R
.id
.fdOpenBtn
: {
404 Log
.e(TAG
, "Incorrect view clicked!");
407 /* else if (v.getId() == R.id.fdShareBtn) {
408 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
414 private void startVideoActivity() {
415 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
416 i
.putExtra(PreviewVideoActivity
.EXTRA_FILE
, mFile
);
417 i
.putExtra(PreviewVideoActivity
.EXTRA_ACCOUNT
, mAccount
);
422 private void bindMediaService() {
423 Log
.d(TAG
, "Binding to MediaService...");
424 if (mMediaServiceConnection
== null
) {
425 mMediaServiceConnection
= new MediaServiceConnection();
427 getActivity().bindService( new Intent(getActivity(),
429 mMediaServiceConnection
,
430 Context
.BIND_AUTO_CREATE
);
431 // follow the flow in MediaServiceConnection#onServiceConnected(...)
434 /** Defines callbacks for service binding, passed to bindService() */
435 private class MediaServiceConnection
implements ServiceConnection
{
438 public void onServiceConnected(ComponentName component
, IBinder service
) {
439 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
440 Log
.d(TAG
, "Media service connected");
441 mMediaServiceBinder
= (MediaServiceBinder
) service
;
442 if (mMediaServiceBinder
!= null
) {
443 if (mMediaController
== null
) {
444 mMediaController
= new MediaController(getSherlockActivity());
446 prepareMediaController();
448 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
451 Log
.e(TAG
, "Unexpected response from MediaService while binding");
456 private void prepareMediaController() {
457 mMediaServiceBinder
.registerMediaController(mMediaController
);
458 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
459 mMediaController
.setAnchorView(getView());
460 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
464 public void onServiceDisconnected(ComponentName component
) {
465 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
466 Log
.e(TAG
, "Media service suddenly disconnected");
467 if (mMediaController
!= null
) {
468 mMediaController
.hide();
469 mMediaController
.setMediaPlayer(null
);
470 mMediaController
= null
;
472 mMediaServiceBinder
= null
;
473 mMediaServiceConnection
= null
;
482 private void openFile() {
484 String storagePath
= mFile
.getStoragePath();
485 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
487 Intent i
= new Intent(Intent
.ACTION_VIEW
);
488 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
489 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
492 } catch (Throwable t
) {
493 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
494 boolean toastIt
= true
;
495 String mimeType
= "";
497 Intent i
= new Intent(Intent
.ACTION_VIEW
);
498 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
499 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
500 if (mimeType
!= null
) {
501 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
504 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
506 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
511 } catch (IndexOutOfBoundsException e
) {
512 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
514 } catch (ActivityNotFoundException e
) {
515 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
517 } catch (Throwable th
) {
518 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
522 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
531 public void onConfirmation(String callerTag
) {
532 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
533 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
534 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
537 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
538 mLastRemoteOperation
.execute(wc
, this, mHandler
);
540 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
541 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
547 public void onNeutral(String callerTag
) {
549 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
551 mFile
.setStoragePath(null
);
552 mStorageManager
.saveFile(mFile
);
553 updateFileDetails(mFile
, mAccount
);
558 public void onCancel(String callerTag
) {
559 Log
.d(TAG
, "REMOVAL CANCELED");
564 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
566 * @return True when the fragment was created with the empty layout.
568 public boolean isEmpty() {
569 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
576 public OCFile
getFile(){
581 * Use this method to signal this Activity that it shall update its view.
583 * @param file : An {@link OCFile}
585 public void updateFileDetails(OCFile file
, Account ocAccount
) {
587 if (ocAccount
!= null
&& (
588 mStorageManager
== null
||
589 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
591 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
593 mAccount
= ocAccount
;
594 updateFileDetails(false
, false
);
599 * Updates the view with all relevant details about that file.
601 * TODO Remove parameter when the transferring state of files is kept in database.
603 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
605 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
606 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
607 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
609 * @param refresh If 'true', try to refresh the hold file from the database
611 public void updateFileDetails(boolean transferring
, boolean refresh
) {
615 if (refresh
&& mStorageManager
!= null
) {
616 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
620 setFilename(mFile
.getFileName());
621 setFiletype(mFile
.getMimetype());
622 setFilesize(mFile
.getFileLength());
623 if(ocVersionSupportsTimeCreated()){
624 setTimeCreated(mFile
.getCreationTimestamp());
627 setTimeModified(mFile
.getModificationTimestamp());
629 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
630 cb
.setChecked(mFile
.keepInSync());
632 // configure UI for depending upon local state of the file
633 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
634 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
635 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
636 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
637 setButtonsForTransferring();
639 } else if (mFile
.isDown()) {
644 // TODO load default preview image; when the local file is removed, the preview remains there
645 setButtonsForRemote();
648 getView().invalidate();
653 * Checks if the fragment is ready to show details of a OCFile
655 * @return 'True' when the fragment is ready to show details of a file
657 private boolean readyToShow() {
658 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
664 * Updates the filename in view
665 * @param filename to set
667 private void setFilename(String filename
) {
668 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
670 tv
.setText(filename
);
674 * Updates the MIME type in view
675 * @param mimetype to set
677 private void setFiletype(String mimetype
) {
678 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
680 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
681 tv
.setText(printableMimetype
);
683 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
685 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
690 * Updates the file size in view
691 * @param filesize in bytes to set
693 private void setFilesize(long filesize
) {
694 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
696 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
700 * Updates the time that the file was created in view
701 * @param milliseconds Unix time to set
703 private void setTimeCreated(long milliseconds
){
704 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
705 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
707 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
708 tv
.setVisibility(View
.VISIBLE
);
709 tvLabel
.setVisibility(View
.VISIBLE
);
714 * Updates the time that the file was last modified
715 * @param milliseconds Unix time to set
717 private void setTimeModified(long milliseconds
){
718 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
720 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
725 * Enables or disables buttons for a file being downloaded
727 private void setButtonsForTransferring() {
729 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
730 downloadButton
.setText(R
.string
.common_cancel
);
731 //downloadButton.setEnabled(false);
733 // let's protect the user from himself ;)
734 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
735 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
736 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
737 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
739 // show the progress bar for the transfer
740 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
741 progressBar
.setVisibility(View
.VISIBLE
);
742 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
743 progressText
.setVisibility(View
.VISIBLE
);
744 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
745 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
746 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
747 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
748 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
749 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
756 * Enables or disables buttons for a file locally available
758 private void setButtonsForDown() {
760 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
761 downloadButton
.setText(R
.string
.filedetails_sync_file
);
763 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
764 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
765 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
766 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
768 // hides the progress bar
769 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
770 progressBar
.setVisibility(View
.GONE
);
771 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
772 progressText
.setVisibility(View
.GONE
);
777 * Enables or disables buttons for a file not locally available
779 private void setButtonsForRemote() {
781 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
782 downloadButton
.setText(R
.string
.filedetails_download
);
784 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
785 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
786 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
787 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
789 // hides the progress bar
790 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
791 progressBar
.setVisibility(View
.GONE
);
792 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
793 progressText
.setVisibility(View
.GONE
);
799 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
800 * the time that the file was created. There is a chance that this will
801 * be fixed in future versions. Use this method to check if this version of
802 * ownCloud has this fix.
803 * @return True, if ownCloud the ownCloud version is supporting creation time
805 private boolean ocVersionSupportsTimeCreated(){
806 /*if(mAccount != null){
807 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
808 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
809 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
810 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
819 * Once the file download has finished -> update view
820 * @author Bartek Przybylski
822 private class DownloadFinishReceiver extends BroadcastReceiver {
824 public void onReceive(Context context, Intent intent) {
825 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
827 if (!isEmpty() && accountName.equals(mAccount.name)) {
828 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
829 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
830 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
831 if (downloadWasFine) {
832 mFile = mStorageManager.getFileByPath(downloadedRemotePath);
834 mContainerActivity.notifySuccessfulDownload(mFile, intent, downloadWasFine);
835 getActivity().removeStickyBroadcast(intent);
836 updateFileDetails(false); // it updates the buttons; must be called although !downloadWasFine
845 * Once the file upload has finished -> update view
847 * Being notified about the finish of an upload is necessary for the next sequence:
848 * 1. Upload a big file.
849 * 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
850 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
851 * 3. Click the file in the list to see its details.
852 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
854 private class UploadFinishReceiver
extends BroadcastReceiver
{
856 public void onReceive(Context context
, Intent intent
) {
857 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
859 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
860 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
861 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
862 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
863 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
866 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
868 if (renamedInUpload
) {
869 String newName
= (new File(uploadRemotePath
)).getName();
870 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
873 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
874 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
881 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
882 @SuppressWarnings("unused")
883 private class ShareRunnable
implements Runnable
{
884 private String mPath
;
886 public ShareRunnable(String path
) {
891 AccountManager am
= AccountManager
.get(getActivity());
892 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
893 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
894 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
896 Log
.d("share", "sharing for version " + ocv
.toString());
898 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
899 String APPS_PATH
= "/apps/files_sharing/";
900 String SHARE_PATH
= "ajax/share.php";
902 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
904 final String WEBDAV_SCRIPT
= "webdav.php";
905 final String WEBDAV_FILES_LOCATION
= "/files/";
907 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
908 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
909 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
911 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
912 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
914 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
916 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
917 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
918 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
919 Log
.d("share", mPath
+"");
920 formparams
.add(new BasicNameValuePair("sources",mPath
));
921 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
922 formparams
.add(new BasicNameValuePair("permissions", "0"));
923 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
927 PropFindMethod find
= new PropFindMethod(url
+"/");
928 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
929 Log
.d("sharer", ""+ url
+"/");
931 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
932 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
935 int status2
= wc
.executeMethod(find
);
937 Log
.d("sharer", "propstatus "+status2
);
939 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
940 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
942 status2
= wc
.executeMethod(get
);
944 Log
.d("sharer", "getstatus "+status2
);
945 Log
.d("sharer", "" + get
.getResponseBodyAsString());
947 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
948 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
951 status
= wc
.executeMethod(post
);
952 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
953 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
955 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
956 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
958 String resp
= post
.getResponseBodyAsString();
959 Log
.d("share", ""+post
.getURI().toString());
960 Log
.d("share", "returned status " + status
);
961 Log
.d("share", " " +resp
);
963 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
967 JSONObject jsonObject
= new JSONObject (resp
);
968 String jsonStatus
= jsonObject
.getString("status");
969 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
971 String token
= jsonObject
.getString("data");
972 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
973 Log
.d("Actions:shareFile ok", "url: " + uri
);
975 } catch (Exception e
) {
979 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
985 public void onDismiss(EditNameDialog dialog
) {
986 if (dialog
.getResult()) {
987 String newFilename
= dialog
.getNewFilename();
988 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
989 mLastRemoteOperation
= new RenameFileOperation( mFile
,
992 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
993 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
994 mLastRemoteOperation
.execute(wc
, this, mHandler
);
995 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
996 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1005 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1006 if (operation
.equals(mLastRemoteOperation
)) {
1007 if (operation
instanceof RemoveFileOperation
) {
1008 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
1010 } else if (operation
instanceof RenameFileOperation
) {
1011 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
1013 } else if (operation
instanceof SynchronizeFileOperation
) {
1014 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1020 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1021 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1022 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1024 if (result
.isSuccess()) {
1025 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1027 if (inDisplayActivity
) {
1029 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1030 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1031 transaction
.commit();
1032 mContainerActivity
.onFileStateChanged();
1034 getActivity().finish();
1038 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1040 if (result
.isSslRecoverableException()) {
1041 // TODO show the SSL warning dialog
1046 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1047 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1048 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1050 if (result
.isSuccess()) {
1051 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1052 mContainerActivity
.onFileStateChanged();
1055 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1056 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1058 // TODO throw again the new rename dialog
1060 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1062 if (result
.isSslRecoverableException()) {
1063 // TODO show the SSL warning dialog
1069 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1070 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1071 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1073 if (!result
.isSuccess()) {
1074 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1075 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1076 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1077 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1081 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1085 if (mFile
.isDown()) {
1086 setButtonsForDown();
1089 setButtonsForRemote();
1093 if (operation
.transferWasRequested()) {
1094 setButtonsForTransferring();
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
;