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
.FileObserverService
;
73 import com
.owncloud
.android
.files
.services
.FileUploader
;
74 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
76 import com
.owncloud
.android
.media
.MediaService
;
77 import com
.owncloud
.android
.media
.MediaServiceBinder
;
78 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
79 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
80 import com
.owncloud
.android
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
87 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
88 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
89 import com
.owncloud
.android
.ui
.activity
.PreviewVideoActivity
;
90 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
92 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
94 import com
.owncloud
.android
.R
;
96 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
97 import eu
.alefzero
.webdav
.WebdavClient
;
98 import eu
.alefzero
.webdav
.WebdavUtils
;
101 * This Fragment is used to display the details about a file.
103 * @author Bartek Przybylski
104 * @author David A. Velasco
106 public class FileDetailFragment
extends SherlockFragment
implements
108 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
111 public static final String EXTRA_FILE
= "FILE";
112 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
114 private FileFragment
.ContainerActivity mContainerActivity
;
118 private OCFile mFile
;
119 private Account mAccount
;
120 private FileDataStorageManager mStorageManager
;
122 //private DownloadFinishReceiver mDownloadFinishReceiver;
123 private UploadFinishReceiver mUploadFinishReceiver
;
124 public ProgressListener mProgressListener
;
126 private Handler mHandler
;
127 private RemoteOperation mLastRemoteOperation
;
129 private MediaServiceBinder mMediaServiceBinder
= null
;
130 private MediaController mMediaController
= null
;
131 private MediaServiceConnection mMediaServiceConnection
= null
;
133 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
134 public static final String FTAG
= "FileDetails";
135 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
139 * Creates an empty details fragment.
141 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
143 public FileDetailFragment() {
146 mStorageManager
= null
;
147 mLayout
= R
.layout
.file_details_empty
;
148 mProgressListener
= null
;
153 * Creates a details fragment.
155 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
157 * @param fileToDetail An {@link OCFile} to show in the fragment
158 * @param ocAccount An ownCloud account; needed to start downloads
160 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
161 mFile
= fileToDetail
;
162 mAccount
= ocAccount
;
163 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
164 mLayout
= R
.layout
.file_details_empty
;
165 mProgressListener
= null
;
170 public void onCreate(Bundle savedInstanceState
) {
171 super.onCreate(savedInstanceState
);
172 mHandler
= new Handler();
177 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
178 Bundle savedInstanceState
) {
179 super.onCreateView(inflater
, container
, savedInstanceState
);
181 if (savedInstanceState
!= null
) {
182 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
183 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
186 if(mFile
!= null
&& mAccount
!= null
) {
187 mLayout
= R
.layout
.file_details_fragment
;
191 view
= inflater
.inflate(mLayout
, container
, false
);
194 if (mLayout
== R
.layout
.file_details_fragment
) {
195 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
196 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
197 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
198 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
199 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
200 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
201 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
202 mProgressListener
= new ProgressListener(progressBar
);
205 updateFileDetails(false
, false
);
214 public void onAttach(Activity activity
) {
215 super.onAttach(activity
);
217 mContainerActivity
= (ContainerActivity
) activity
;
219 } catch (ClassCastException e
) {
220 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
229 public void onActivityCreated(Bundle savedInstanceState
) {
230 super.onActivityCreated(savedInstanceState
);
231 if (mAccount
!= null
) {
232 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
238 public void onSaveInstanceState(Bundle outState
) {
239 super.onSaveInstanceState(outState
);
240 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
241 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
245 public void onStart() {
247 if (mFile
!= null
&& mFile
.isAudio()) {
250 listenForTransferProgress();
254 public void onResume() {
258 mDownloadFinishReceiver = new DownloadFinishReceiver();
259 IntentFilter filter = new IntentFilter(
260 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
261 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
264 mUploadFinishReceiver
= new UploadFinishReceiver();
265 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
266 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
272 public void onPause() {
276 if (mDownloadFinishReceiver != null) {
277 getActivity().unregisterReceiver(mDownloadFinishReceiver);
278 mDownloadFinishReceiver = null;
282 if (mUploadFinishReceiver
!= null
) {
283 getActivity().unregisterReceiver(mUploadFinishReceiver
);
284 mUploadFinishReceiver
= null
;
290 public void onStop() {
292 if (mMediaServiceConnection
!= null
) {
293 Log
.d(TAG
, "Unbinding from MediaService ...");
294 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
295 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
297 getActivity().unbindService(mMediaServiceConnection
);
298 mMediaServiceBinder
= null
;
299 if (mMediaController
!= null
) {
300 mMediaController
.hide();
301 mMediaController
= null
;
304 leaveTransferProgress();
309 public View
getView() {
310 return super.getView() == null ? mView
: super.getView();
315 public void onClick(View v
) {
317 case R
.id
.fdDownloadBtn
: {
318 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
319 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
320 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
321 downloaderBinder
.cancel(mAccount
, mFile
);
322 if (mFile
.isDown()) {
325 setButtonsForRemote();
328 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
329 uploaderBinder
.cancel(mAccount
, mFile
);
330 if (!mFile
.fileExists()) {
331 // TODO make something better
332 if (getActivity() instanceof FileDisplayActivity
) {
334 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
335 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
336 transaction
.commit();
337 mContainerActivity
.onFileStateChanged();
339 getActivity().finish();
342 } else if (mFile
.isDown()) {
345 setButtonsForRemote();
349 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
350 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
351 mLastRemoteOperation
.execute(wc
, this, mHandler
);
354 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
355 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
360 case R
.id
.fdKeepInSync
: {
361 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
362 mFile
.setKeepInSync(cb
.isChecked());
363 mStorageManager
.saveFile(mFile
);
365 /// register the OCFile instance in the observer service to monitor local updates;
366 /// if necessary, the file is download
367 Intent intent
= new Intent(getActivity().getApplicationContext(),
368 FileObserverService
.class);
369 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
371 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
372 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
373 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
374 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
375 getActivity().startService(intent
);
377 if (mFile
.keepInSync()) {
378 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
382 case R
.id
.fdRenameBtn
: {
383 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
384 dialog
.show(getFragmentManager(), "nameeditdialog");
387 case R
.id
.fdRemoveBtn
: {
388 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
389 R
.string
.confirmation_remove_alert
,
390 new String
[]{mFile
.getFileName()},
391 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
392 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
393 R
.string
.common_cancel
);
394 confDialog
.setOnConfirmationListener(this);
395 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
398 case R
.id
.fdOpenBtn
: {
403 Log
.e(TAG
, "Incorrect view clicked!");
406 /* else if (v.getId() == R.id.fdShareBtn) {
407 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
413 private void startVideoActivity() {
414 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
415 i
.putExtra(PreviewVideoActivity
.EXTRA_FILE
, mFile
);
416 i
.putExtra(PreviewVideoActivity
.EXTRA_ACCOUNT
, mAccount
);
421 private void bindMediaService() {
422 Log
.d(TAG
, "Binding to MediaService...");
423 if (mMediaServiceConnection
== null
) {
424 mMediaServiceConnection
= new MediaServiceConnection();
426 getActivity().bindService( new Intent(getActivity(),
428 mMediaServiceConnection
,
429 Context
.BIND_AUTO_CREATE
);
430 // follow the flow in MediaServiceConnection#onServiceConnected(...)
433 /** Defines callbacks for service binding, passed to bindService() */
434 private class MediaServiceConnection
implements ServiceConnection
{
437 public void onServiceConnected(ComponentName component
, IBinder service
) {
438 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
439 Log
.d(TAG
, "Media service connected");
440 mMediaServiceBinder
= (MediaServiceBinder
) service
;
441 if (mMediaServiceBinder
!= null
) {
442 if (mMediaController
== null
) {
443 mMediaController
= new MediaController(getSherlockActivity());
445 prepareMediaController();
447 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
450 Log
.e(TAG
, "Unexpected response from MediaService while binding");
455 private void prepareMediaController() {
456 mMediaServiceBinder
.registerMediaController(mMediaController
);
457 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
458 mMediaController
.setAnchorView(getView());
459 mMediaController
.setEnabled(mMediaServiceBinder
.isInPlaybackState());
463 public void onServiceDisconnected(ComponentName component
) {
464 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
465 Log
.e(TAG
, "Media service suddenly disconnected");
466 if (mMediaController
!= null
) {
467 mMediaController
.hide();
468 mMediaController
.setMediaPlayer(null
);
469 mMediaController
= null
;
471 mMediaServiceBinder
= null
;
472 mMediaServiceConnection
= null
;
481 private void openFile() {
483 String storagePath
= mFile
.getStoragePath();
484 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
486 Intent i
= new Intent(Intent
.ACTION_VIEW
);
487 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
488 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
491 } catch (Throwable t
) {
492 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
493 boolean toastIt
= true
;
494 String mimeType
= "";
496 Intent i
= new Intent(Intent
.ACTION_VIEW
);
497 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
498 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
499 if (mimeType
!= null
) {
500 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
503 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
505 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
510 } catch (IndexOutOfBoundsException e
) {
511 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
513 } catch (ActivityNotFoundException e
) {
514 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
516 } catch (Throwable th
) {
517 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
521 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
530 public void onConfirmation(String callerTag
) {
531 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
532 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
533 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
536 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
537 mLastRemoteOperation
.execute(wc
, this, mHandler
);
539 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
540 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
546 public void onNeutral(String callerTag
) {
548 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
550 mFile
.setStoragePath(null
);
551 mStorageManager
.saveFile(mFile
);
552 updateFileDetails(mFile
, mAccount
);
557 public void onCancel(String callerTag
) {
558 Log
.d(TAG
, "REMOVAL CANCELED");
563 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
565 * @return True when the fragment was created with the empty layout.
567 public boolean isEmpty() {
568 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
575 public OCFile
getFile(){
580 * Use this method to signal this Activity that it shall update its view.
582 * @param file : An {@link OCFile}
584 public void updateFileDetails(OCFile file
, Account ocAccount
) {
586 if (ocAccount
!= null
&& (
587 mStorageManager
== null
||
588 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
590 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
592 mAccount
= ocAccount
;
593 updateFileDetails(false
, false
);
598 * Updates the view with all relevant details about that file.
600 * TODO Remove parameter when the transferring state of files is kept in database.
602 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
604 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
605 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
606 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
608 * @param refresh If 'true', try to refresh the hold file from the database
610 public void updateFileDetails(boolean transferring
, boolean refresh
) {
614 if (refresh
&& mStorageManager
!= null
) {
615 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
619 setFilename(mFile
.getFileName());
620 setFiletype(mFile
.getMimetype());
621 setFilesize(mFile
.getFileLength());
622 if(ocVersionSupportsTimeCreated()){
623 setTimeCreated(mFile
.getCreationTimestamp());
626 setTimeModified(mFile
.getModificationTimestamp());
628 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
629 cb
.setChecked(mFile
.keepInSync());
631 // configure UI for depending upon local state of the file
632 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
633 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
634 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
635 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
636 setButtonsForTransferring();
638 } else if (mFile
.isDown()) {
643 // TODO load default preview image; when the local file is removed, the preview remains there
644 setButtonsForRemote();
647 getView().invalidate();
652 * Checks if the fragment is ready to show details of a OCFile
654 * @return 'True' when the fragment is ready to show details of a file
656 private boolean readyToShow() {
657 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
663 * Updates the filename in view
664 * @param filename to set
666 private void setFilename(String filename
) {
667 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
669 tv
.setText(filename
);
673 * Updates the MIME type in view
674 * @param mimetype to set
676 private void setFiletype(String mimetype
) {
677 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
679 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
680 tv
.setText(printableMimetype
);
682 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
684 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
689 * Updates the file size in view
690 * @param filesize in bytes to set
692 private void setFilesize(long filesize
) {
693 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
695 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
699 * Updates the time that the file was created in view
700 * @param milliseconds Unix time to set
702 private void setTimeCreated(long milliseconds
){
703 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
704 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
706 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
707 tv
.setVisibility(View
.VISIBLE
);
708 tvLabel
.setVisibility(View
.VISIBLE
);
713 * Updates the time that the file was last modified
714 * @param milliseconds Unix time to set
716 private void setTimeModified(long milliseconds
){
717 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
719 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
724 * Enables or disables buttons for a file being downloaded
726 private void setButtonsForTransferring() {
728 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
729 downloadButton
.setText(R
.string
.common_cancel
);
730 //downloadButton.setEnabled(false);
732 // let's protect the user from himself ;)
733 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
734 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
735 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
736 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
738 // show the progress bar for the transfer
739 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
740 progressBar
.setVisibility(View
.VISIBLE
);
741 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
742 progressText
.setVisibility(View
.VISIBLE
);
743 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
744 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
745 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
746 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
747 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
748 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
755 * Enables or disables buttons for a file locally available
757 private void setButtonsForDown() {
759 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
760 downloadButton
.setText(R
.string
.filedetails_sync_file
);
762 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
763 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
764 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
765 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
767 // hides the progress bar
768 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
769 progressBar
.setVisibility(View
.GONE
);
770 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
771 progressText
.setVisibility(View
.GONE
);
776 * Enables or disables buttons for a file not locally available
778 private void setButtonsForRemote() {
780 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
781 downloadButton
.setText(R
.string
.filedetails_download
);
783 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
784 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
785 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
786 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
788 // hides the progress bar
789 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
790 progressBar
.setVisibility(View
.GONE
);
791 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
792 progressText
.setVisibility(View
.GONE
);
798 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
799 * the time that the file was created. There is a chance that this will
800 * be fixed in future versions. Use this method to check if this version of
801 * ownCloud has this fix.
802 * @return True, if ownCloud the ownCloud version is supporting creation time
804 private boolean ocVersionSupportsTimeCreated(){
805 /*if(mAccount != null){
806 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
807 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
808 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
809 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
818 * Once the file upload has finished -> update view
820 * Being notified about the finish of an upload is necessary for the next sequence:
821 * 1. Upload a big file.
822 * 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
823 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
824 * 3. Click the file in the list to see its details.
825 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
827 private class UploadFinishReceiver
extends BroadcastReceiver
{
829 public void onReceive(Context context
, Intent intent
) {
830 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
832 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
833 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
834 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
835 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
836 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
839 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
841 if (renamedInUpload
) {
842 String newName
= (new File(uploadRemotePath
)).getName();
843 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
846 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
847 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
854 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
855 @SuppressWarnings("unused")
856 private class ShareRunnable
implements Runnable
{
857 private String mPath
;
859 public ShareRunnable(String path
) {
864 AccountManager am
= AccountManager
.get(getActivity());
865 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
866 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
867 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
869 Log
.d("share", "sharing for version " + ocv
.toString());
871 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
872 String APPS_PATH
= "/apps/files_sharing/";
873 String SHARE_PATH
= "ajax/share.php";
875 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
877 final String WEBDAV_SCRIPT
= "webdav.php";
878 final String WEBDAV_FILES_LOCATION
= "/files/";
880 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
881 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
882 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
884 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
885 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
887 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
889 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
890 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
891 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
892 Log
.d("share", mPath
+"");
893 formparams
.add(new BasicNameValuePair("sources",mPath
));
894 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
895 formparams
.add(new BasicNameValuePair("permissions", "0"));
896 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
900 PropFindMethod find
= new PropFindMethod(url
+"/");
901 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
902 Log
.d("sharer", ""+ url
+"/");
904 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
905 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
908 int status2
= wc
.executeMethod(find
);
910 Log
.d("sharer", "propstatus "+status2
);
912 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
913 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
915 status2
= wc
.executeMethod(get
);
917 Log
.d("sharer", "getstatus "+status2
);
918 Log
.d("sharer", "" + get
.getResponseBodyAsString());
920 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
921 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
924 status
= wc
.executeMethod(post
);
925 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
926 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
928 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
929 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
931 String resp
= post
.getResponseBodyAsString();
932 Log
.d("share", ""+post
.getURI().toString());
933 Log
.d("share", "returned status " + status
);
934 Log
.d("share", " " +resp
);
936 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
940 JSONObject jsonObject
= new JSONObject (resp
);
941 String jsonStatus
= jsonObject
.getString("status");
942 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
944 String token
= jsonObject
.getString("data");
945 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
946 Log
.d("Actions:shareFile ok", "url: " + uri
);
948 } catch (Exception e
) {
952 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
958 public void onDismiss(EditNameDialog dialog
) {
959 if (dialog
.getResult()) {
960 String newFilename
= dialog
.getNewFilename();
961 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
962 mLastRemoteOperation
= new RenameFileOperation( mFile
,
965 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
966 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
967 mLastRemoteOperation
.execute(wc
, this, mHandler
);
968 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
969 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
978 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
979 if (operation
.equals(mLastRemoteOperation
)) {
980 if (operation
instanceof RemoveFileOperation
) {
981 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
983 } else if (operation
instanceof RenameFileOperation
) {
984 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
986 } else if (operation
instanceof SynchronizeFileOperation
) {
987 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
993 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
994 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
995 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
997 if (result
.isSuccess()) {
998 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1000 if (inDisplayActivity
) {
1002 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1003 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1004 transaction
.commit();
1005 mContainerActivity
.onFileStateChanged();
1007 getActivity().finish();
1011 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1013 if (result
.isSslRecoverableException()) {
1014 // TODO show the SSL warning dialog
1019 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1020 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1021 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1023 if (result
.isSuccess()) {
1024 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1025 mContainerActivity
.onFileStateChanged();
1028 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1029 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1031 // TODO throw again the new rename dialog
1033 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1035 if (result
.isSslRecoverableException()) {
1036 // TODO show the SSL warning dialog
1042 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1043 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1044 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1046 if (!result
.isSuccess()) {
1047 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1048 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1049 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1050 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1054 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1058 if (mFile
.isDown()) {
1059 setButtonsForDown();
1062 setButtonsForRemote();
1066 if (operation
.transferWasRequested()) {
1067 setButtonsForTransferring();
1068 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1069 // checking the service to see if the file is downloading results in FALSE
1071 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1073 if (mFile
.isDown()) {
1074 setButtonsForDown();
1077 setButtonsForRemote();
1084 public void listenForTransferProgress() {
1085 if (mProgressListener
!= null
) {
1086 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1087 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1089 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1090 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1096 public void leaveTransferProgress() {
1097 if (mProgressListener
!= null
) {
1098 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1099 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1101 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1102 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1110 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1112 * @author David A. Velasco
1114 private class ProgressListener
implements OnDatatransferProgressListener
{
1115 int mLastPercent
= 0;
1116 WeakReference
<ProgressBar
> mProgressBar
= null
;
1118 ProgressListener(ProgressBar progressBar
) {
1119 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1123 public void onTransferProgress(long progressRate
) {
1124 // old method, nothing here
1128 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1129 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1130 if (percent
!= mLastPercent
) {
1131 ProgressBar pb
= mProgressBar
.get();
1133 pb
.setProgress(percent
);
1134 pb
.postInvalidate();
1137 mLastPercent
= percent
;