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
);
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() {
258 mDownloadFinishReceiver
= new DownloadFinishReceiver();
259 IntentFilter filter
= new IntentFilter(
260 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
261 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
263 mUploadFinishReceiver
= new UploadFinishReceiver();
264 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
265 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
271 public void onPause() {
274 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
275 mDownloadFinishReceiver
= null
;
277 getActivity().unregisterReceiver(mUploadFinishReceiver
);
278 mUploadFinishReceiver
= null
;
283 public void onStop() {
285 if (mMediaServiceConnection
!= null
) {
286 Log
.d(TAG
, "Unbinding from MediaService ...");
287 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
288 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
290 getActivity().unbindService(mMediaServiceConnection
);
291 mMediaServiceBinder
= null
;
292 if (mMediaController
!= null
) {
293 mMediaController
.hide();
294 mMediaController
= null
;
297 leaveTransferProgress();
302 public View
getView() {
303 return super.getView() == null ? mView
: super.getView();
308 public void onClick(View v
) {
310 case R
.id
.fdDownloadBtn
: {
311 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
312 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
313 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
314 downloaderBinder
.cancel(mAccount
, mFile
);
315 if (mFile
.isDown()) {
318 setButtonsForRemote();
321 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
322 uploaderBinder
.cancel(mAccount
, mFile
);
323 if (!mFile
.fileExists()) {
324 // TODO make something better
325 if (getActivity() instanceof FileDisplayActivity
) {
327 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
328 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
329 transaction
.commit();
330 mContainerActivity
.onFileStateChanged();
332 getActivity().finish();
335 } else if (mFile
.isDown()) {
338 setButtonsForRemote();
342 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
343 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
344 mLastRemoteOperation
.execute(wc
, this, mHandler
);
347 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
348 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
353 case R
.id
.fdKeepInSync
: {
354 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
355 mFile
.setKeepInSync(cb
.isChecked());
356 mStorageManager
.saveFile(mFile
);
358 /// register the OCFile instance in the observer service to monitor local updates;
359 /// if necessary, the file is download
360 Intent intent
= new Intent(getActivity().getApplicationContext(),
361 FileObserverService
.class);
362 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
364 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
365 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
366 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
367 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
368 getActivity().startService(intent
);
370 if (mFile
.keepInSync()) {
371 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
375 case R
.id
.fdRenameBtn
: {
376 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
377 dialog
.show(getFragmentManager(), "nameeditdialog");
380 case R
.id
.fdRemoveBtn
: {
381 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
382 R
.string
.confirmation_remove_alert
,
383 new String
[]{mFile
.getFileName()},
384 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
385 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
386 R
.string
.common_cancel
);
387 confDialog
.setOnConfirmationListener(this);
388 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
391 case R
.id
.fdOpenBtn
: {
396 Log
.e(TAG
, "Incorrect view clicked!");
399 /* else if (v.getId() == R.id.fdShareBtn) {
400 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
406 private void startVideoActivity() {
407 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
408 i
.putExtra(PreviewVideoActivity
.EXTRA_FILE
, mFile
);
409 i
.putExtra(PreviewVideoActivity
.EXTRA_ACCOUNT
, mAccount
);
414 private void bindMediaService() {
415 Log
.d(TAG
, "Binding to MediaService...");
416 if (mMediaServiceConnection
== null
) {
417 mMediaServiceConnection
= new MediaServiceConnection();
419 getActivity().bindService( new Intent(getActivity(),
421 mMediaServiceConnection
,
422 Context
.BIND_AUTO_CREATE
);
423 // follow the flow in MediaServiceConnection#onServiceConnected(...)
426 /** Defines callbacks for service binding, passed to bindService() */
427 private class MediaServiceConnection
implements ServiceConnection
{
430 public void onServiceConnected(ComponentName component
, IBinder service
) {
431 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
432 Log
.d(TAG
, "Media service connected");
433 mMediaServiceBinder
= (MediaServiceBinder
) service
;
434 if (mMediaServiceBinder
!= null
) {
435 if (mMediaController
== null
) {
436 mMediaController
= new MediaController(getSherlockActivity());
438 prepareMediaController();
440 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
443 Log
.e(TAG
, "Unexpected response from MediaService while binding");
448 private void prepareMediaController() {
449 mMediaServiceBinder
.registerMediaController(mMediaController
);
450 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
451 mMediaController
.setAnchorView(getView());
452 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
456 public void onServiceDisconnected(ComponentName component
) {
457 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
458 Log
.e(TAG
, "Media service suddenly disconnected");
459 if (mMediaController
!= null
) {
460 mMediaController
.hide();
461 mMediaController
.setMediaPlayer(null
);
462 mMediaController
= null
;
464 mMediaServiceBinder
= null
;
465 mMediaServiceConnection
= null
;
474 private void openFile() {
476 String storagePath
= mFile
.getStoragePath();
477 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
479 Intent i
= new Intent(Intent
.ACTION_VIEW
);
480 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
481 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
484 } catch (Throwable t
) {
485 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
486 boolean toastIt
= true
;
487 String mimeType
= "";
489 Intent i
= new Intent(Intent
.ACTION_VIEW
);
490 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
491 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
492 if (mimeType
!= null
) {
493 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
496 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
498 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
503 } catch (IndexOutOfBoundsException e
) {
504 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
506 } catch (ActivityNotFoundException e
) {
507 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
509 } catch (Throwable th
) {
510 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
514 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
523 public void onConfirmation(String callerTag
) {
524 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
525 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
526 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
529 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
530 mLastRemoteOperation
.execute(wc
, this, mHandler
);
532 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
533 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
539 public void onNeutral(String callerTag
) {
541 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
543 mFile
.setStoragePath(null
);
544 mStorageManager
.saveFile(mFile
);
545 updateFileDetails(mFile
, mAccount
);
550 public void onCancel(String callerTag
) {
551 Log
.d(TAG
, "REMOVAL CANCELED");
556 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
558 * @return True when the fragment was created with the empty layout.
560 public boolean isEmpty() {
561 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
568 public OCFile
getFile(){
573 * Use this method to signal this Activity that it shall update its view.
575 * @param file : An {@link OCFile}
577 public void updateFileDetails(OCFile file
, Account ocAccount
) {
579 if (ocAccount
!= null
&& (
580 mStorageManager
== null
||
581 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
583 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
585 mAccount
= ocAccount
;
586 updateFileDetails(false
);
591 * Updates the view with all relevant details about that file.
593 * TODO Remove parameter when the transferring state of files is kept in database.
595 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
597 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
598 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
599 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
602 public void updateFileDetails(boolean transferring
) {
607 setFilename(mFile
.getFileName());
608 setFiletype(mFile
.getMimetype());
609 setFilesize(mFile
.getFileLength());
610 if(ocVersionSupportsTimeCreated()){
611 setTimeCreated(mFile
.getCreationTimestamp());
614 setTimeModified(mFile
.getModificationTimestamp());
616 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
617 cb
.setChecked(mFile
.keepInSync());
619 // configure UI for depending upon local state of the file
620 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
621 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
622 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
623 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
624 setButtonsForTransferring();
626 } else if (mFile
.isDown()) {
631 // TODO load default preview image; when the local file is removed, the preview remains there
632 setButtonsForRemote();
635 getView().invalidate();
640 * Checks if the fragment is ready to show details of a OCFile
642 * @return 'True' when the fragment is ready to show details of a file
644 private boolean readyToShow() {
645 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
651 * Updates the filename in view
652 * @param filename to set
654 private void setFilename(String filename
) {
655 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
657 tv
.setText(filename
);
661 * Updates the MIME type in view
662 * @param mimetype to set
664 private void setFiletype(String mimetype
) {
665 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
667 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
668 tv
.setText(printableMimetype
);
670 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
672 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
677 * Updates the file size in view
678 * @param filesize in bytes to set
680 private void setFilesize(long filesize
) {
681 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
683 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
687 * Updates the time that the file was created in view
688 * @param milliseconds Unix time to set
690 private void setTimeCreated(long milliseconds
){
691 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
692 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
694 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
695 tv
.setVisibility(View
.VISIBLE
);
696 tvLabel
.setVisibility(View
.VISIBLE
);
701 * Updates the time that the file was last modified
702 * @param milliseconds Unix time to set
704 private void setTimeModified(long milliseconds
){
705 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
707 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
712 * Enables or disables buttons for a file being downloaded
714 private void setButtonsForTransferring() {
716 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
717 downloadButton
.setText(R
.string
.common_cancel
);
718 //downloadButton.setEnabled(false);
720 // let's protect the user from himself ;)
721 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
722 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
723 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
724 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
726 // show the progress bar for the transfer
727 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
728 progressBar
.setVisibility(View
.VISIBLE
);
729 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
730 progressText
.setVisibility(View
.VISIBLE
);
731 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
732 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
733 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
734 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
735 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
736 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
743 * Enables or disables buttons for a file locally available
745 private void setButtonsForDown() {
747 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
748 downloadButton
.setText(R
.string
.filedetails_sync_file
);
750 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
751 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
752 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
753 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
755 // hides the progress bar
756 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
757 progressBar
.setVisibility(View
.GONE
);
758 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
759 progressText
.setVisibility(View
.GONE
);
764 * Enables or disables buttons for a file not locally available
766 private void setButtonsForRemote() {
768 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
769 downloadButton
.setText(R
.string
.filedetails_download
);
771 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
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
);
779 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
780 progressText
.setVisibility(View
.GONE
);
786 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
787 * the time that the file was created. There is a chance that this will
788 * be fixed in future versions. Use this method to check if this version of
789 * ownCloud has this fix.
790 * @return True, if ownCloud the ownCloud version is supporting creation time
792 private boolean ocVersionSupportsTimeCreated(){
793 /*if(mAccount != null){
794 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
795 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
796 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
797 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
806 * Once the file download has finished -> update view
807 * @author Bartek Przybylski
809 private class DownloadFinishReceiver
extends BroadcastReceiver
{
811 public void onReceive(Context context
, Intent intent
) {
812 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
814 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
815 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
816 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
817 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
818 if (downloadWasFine
) {
819 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
821 mContainerActivity
.notifySuccessfulDownload(mFile
, intent
, downloadWasFine
);
822 getActivity().removeStickyBroadcast(intent
);
823 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
831 * Once the file upload has finished -> update view
833 * Being notified about the finish of an upload is necessary for the next sequence:
834 * 1. Upload a big file.
835 * 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
836 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
837 * 3. Click the file in the list to see its details.
838 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
840 private class UploadFinishReceiver
extends BroadcastReceiver
{
842 public void onReceive(Context context
, Intent intent
) {
843 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
845 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
846 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
847 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
848 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
849 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
852 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
854 if (renamedInUpload
) {
855 String newName
= (new File(uploadRemotePath
)).getName();
856 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
859 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
860 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
867 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
868 @SuppressWarnings("unused")
869 private class ShareRunnable
implements Runnable
{
870 private String mPath
;
872 public ShareRunnable(String path
) {
877 AccountManager am
= AccountManager
.get(getActivity());
878 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
879 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
880 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
882 Log
.d("share", "sharing for version " + ocv
.toString());
884 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
885 String APPS_PATH
= "/apps/files_sharing/";
886 String SHARE_PATH
= "ajax/share.php";
888 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
890 final String WEBDAV_SCRIPT
= "webdav.php";
891 final String WEBDAV_FILES_LOCATION
= "/files/";
893 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
894 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
895 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
897 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
898 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
900 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
902 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
903 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
904 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
905 Log
.d("share", mPath
+"");
906 formparams
.add(new BasicNameValuePair("sources",mPath
));
907 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
908 formparams
.add(new BasicNameValuePair("permissions", "0"));
909 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
913 PropFindMethod find
= new PropFindMethod(url
+"/");
914 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
915 Log
.d("sharer", ""+ url
+"/");
917 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
918 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
921 int status2
= wc
.executeMethod(find
);
923 Log
.d("sharer", "propstatus "+status2
);
925 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
926 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
928 status2
= wc
.executeMethod(get
);
930 Log
.d("sharer", "getstatus "+status2
);
931 Log
.d("sharer", "" + get
.getResponseBodyAsString());
933 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
934 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
937 status
= wc
.executeMethod(post
);
938 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
939 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
941 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
942 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
944 String resp
= post
.getResponseBodyAsString();
945 Log
.d("share", ""+post
.getURI().toString());
946 Log
.d("share", "returned status " + status
);
947 Log
.d("share", " " +resp
);
949 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
953 JSONObject jsonObject
= new JSONObject (resp
);
954 String jsonStatus
= jsonObject
.getString("status");
955 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
957 String token
= jsonObject
.getString("data");
958 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
959 Log
.d("Actions:shareFile ok", "url: " + uri
);
961 } catch (Exception e
) {
965 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
971 public void onDismiss(EditNameDialog dialog
) {
972 if (dialog
.getResult()) {
973 String newFilename
= dialog
.getNewFilename();
974 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
975 mLastRemoteOperation
= new RenameFileOperation( mFile
,
978 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
979 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
980 mLastRemoteOperation
.execute(wc
, this, mHandler
);
981 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
982 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
991 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
992 if (operation
.equals(mLastRemoteOperation
)) {
993 if (operation
instanceof RemoveFileOperation
) {
994 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
996 } else if (operation
instanceof RenameFileOperation
) {
997 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
999 } else if (operation
instanceof SynchronizeFileOperation
) {
1000 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
1006 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
1007 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1008 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1010 if (result
.isSuccess()) {
1011 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1013 if (inDisplayActivity
) {
1015 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1016 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1017 transaction
.commit();
1018 mContainerActivity
.onFileStateChanged();
1020 getActivity().finish();
1024 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1026 if (result
.isSslRecoverableException()) {
1027 // TODO show the SSL warning dialog
1032 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1033 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1034 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1036 if (result
.isSuccess()) {
1037 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1038 mContainerActivity
.onFileStateChanged();
1041 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1042 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1044 // TODO throw again the new rename dialog
1046 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1048 if (result
.isSslRecoverableException()) {
1049 // TODO show the SSL warning dialog
1055 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1056 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1057 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1059 if (!result
.isSuccess()) {
1060 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1061 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1062 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1063 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1067 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1071 if (mFile
.isDown()) {
1072 setButtonsForDown();
1075 setButtonsForRemote();
1079 if (operation
.transferWasRequested()) {
1080 setButtonsForTransferring();
1081 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1082 // checking the service to see if the file is downloading results in FALSE
1084 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1086 if (mFile
.isDown()) {
1087 setButtonsForDown();
1090 setButtonsForRemote();
1097 public void listenForTransferProgress() {
1098 if (mProgressListener
!= null
) {
1099 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1100 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1102 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1103 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1109 public void leaveTransferProgress() {
1110 if (mProgressListener
!= null
) {
1111 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1112 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1114 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1115 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1123 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1125 * @author David A. Velasco
1127 private class ProgressListener
implements OnDatatransferProgressListener
{
1128 int mLastPercent
= 0;
1129 WeakReference
<ProgressBar
> mProgressBar
= null
;
1131 ProgressListener(ProgressBar progressBar
) {
1132 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1136 public void onTransferProgress(long progressRate
) {
1137 // old method, nothing here
1141 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1142 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1143 if (percent
!= mLastPercent
) {
1144 ProgressBar pb
= mProgressBar
.get();
1146 pb
.setProgress(percent
);
1147 pb
.postInvalidate();
1150 mLastPercent
= percent
;