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
.Context
;
43 import android
.content
.Intent
;
44 import android
.content
.IntentFilter
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.Handler
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.util
.Log
;
50 import android
.view
.LayoutInflater
;
51 import android
.view
.View
;
52 import android
.view
.View
.OnClickListener
;
53 import android
.view
.ViewGroup
;
54 import android
.webkit
.MimeTypeMap
;
55 import android
.widget
.Button
;
56 import android
.widget
.CheckBox
;
57 import android
.widget
.ImageView
;
58 import android
.widget
.ProgressBar
;
59 import android
.widget
.TextView
;
60 import android
.widget
.Toast
;
62 import com
.actionbarsherlock
.app
.SherlockFragment
;
63 import com
.owncloud
.android
.AccountUtils
;
64 import com
.owncloud
.android
.DisplayUtils
;
65 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
66 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileObserverService
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
71 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
72 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
73 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
74 import com
.owncloud
.android
.operations
.RemoteOperation
;
75 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
76 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
77 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
78 import com
.owncloud
.android
.operations
.RenameFileOperation
;
79 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
80 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
81 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
82 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
83 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
85 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
87 import com
.owncloud
.android
.R
;
89 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
90 import eu
.alefzero
.webdav
.WebdavClient
;
91 import eu
.alefzero
.webdav
.WebdavUtils
;
94 * This Fragment is used to display the details about a file.
96 * @author Bartek Przybylski
97 * @author David A. Velasco
99 public class FileDetailFragment
extends SherlockFragment
implements
101 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
104 public static final String EXTRA_FILE
= "FILE";
105 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
107 private FileFragment
.ContainerActivity mContainerActivity
;
111 private OCFile mFile
;
112 private Account mAccount
;
113 private FileDataStorageManager mStorageManager
;
115 private UploadFinishReceiver mUploadFinishReceiver
;
116 public ProgressListener mProgressListener
;
118 private Handler mHandler
;
119 private RemoteOperation mLastRemoteOperation
;
121 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
122 public static final String FTAG
= "FileDetails";
123 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
127 * Creates an empty details fragment.
129 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
131 public FileDetailFragment() {
134 mStorageManager
= null
;
135 mLayout
= R
.layout
.file_details_empty
;
136 mProgressListener
= null
;
141 * Creates a details fragment.
143 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
145 * @param fileToDetail An {@link OCFile} to show in the fragment
146 * @param ocAccount An ownCloud account; needed to start downloads
148 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
149 mFile
= fileToDetail
;
150 mAccount
= ocAccount
;
151 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
152 mLayout
= R
.layout
.file_details_empty
;
153 mProgressListener
= null
;
158 public void onCreate(Bundle savedInstanceState
) {
159 super.onCreate(savedInstanceState
);
160 mHandler
= new Handler();
165 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
166 Bundle savedInstanceState
) {
167 super.onCreateView(inflater
, container
, savedInstanceState
);
169 if (savedInstanceState
!= null
) {
170 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
171 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
174 if(mFile
!= null
&& mAccount
!= null
) {
175 mLayout
= R
.layout
.file_details_fragment
;
179 view
= inflater
.inflate(mLayout
, container
, false
);
182 if (mLayout
== R
.layout
.file_details_fragment
) {
183 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
184 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
185 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
186 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
187 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
188 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
189 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
190 mProgressListener
= new ProgressListener(progressBar
);
193 updateFileDetails(false
, false
);
202 public void onAttach(Activity activity
) {
203 super.onAttach(activity
);
205 mContainerActivity
= (ContainerActivity
) activity
;
207 } catch (ClassCastException e
) {
208 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
217 public void onActivityCreated(Bundle savedInstanceState
) {
218 super.onActivityCreated(savedInstanceState
);
219 if (mAccount
!= null
) {
220 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
226 public void onSaveInstanceState(Bundle outState
) {
227 super.onSaveInstanceState(outState
);
228 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
229 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
233 public void onStart() {
235 listenForTransferProgress();
239 public void onResume() {
241 mUploadFinishReceiver
= new UploadFinishReceiver();
242 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
243 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
249 public void onPause() {
251 if (mUploadFinishReceiver
!= null
) {
252 getActivity().unregisterReceiver(mUploadFinishReceiver
);
253 mUploadFinishReceiver
= null
;
259 public void onStop() {
261 leaveTransferProgress();
266 public View
getView() {
267 return super.getView() == null ? mView
: super.getView();
272 public void onClick(View v
) {
274 case R
.id
.fdDownloadBtn
: {
275 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
276 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
277 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
278 downloaderBinder
.cancel(mAccount
, mFile
);
279 if (mFile
.isDown()) {
282 setButtonsForRemote();
285 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
286 uploaderBinder
.cancel(mAccount
, mFile
);
287 if (!mFile
.fileExists()) {
288 // TODO make something better
289 if (getActivity() instanceof FileDisplayActivity
) {
291 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
292 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
293 transaction
.commit();
294 mContainerActivity
.onFileStateChanged();
296 getActivity().finish();
299 } else if (mFile
.isDown()) {
302 setButtonsForRemote();
306 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
307 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
308 mLastRemoteOperation
.execute(wc
, this, mHandler
);
311 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
312 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
317 case R
.id
.fdKeepInSync
: {
318 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
319 mFile
.setKeepInSync(cb
.isChecked());
320 mStorageManager
.saveFile(mFile
);
322 /// register the OCFile instance in the observer service to monitor local updates;
323 /// if necessary, the file is download
324 Intent intent
= new Intent(getActivity().getApplicationContext(),
325 FileObserverService
.class);
326 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
328 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
329 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
330 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
331 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
332 getActivity().startService(intent
);
334 if (mFile
.keepInSync()) {
335 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
339 case R
.id
.fdRenameBtn
: {
340 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
341 dialog
.show(getFragmentManager(), "nameeditdialog");
344 case R
.id
.fdRemoveBtn
: {
345 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
346 R
.string
.confirmation_remove_alert
,
347 new String
[]{mFile
.getFileName()},
348 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
349 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
350 R
.string
.common_cancel
);
351 confDialog
.setOnConfirmationListener(this);
352 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
355 case R
.id
.fdOpenBtn
: {
360 Log
.e(TAG
, "Incorrect view clicked!");
363 /* else if (v.getId() == R.id.fdShareBtn) {
364 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
373 private void openFile() {
375 String storagePath
= mFile
.getStoragePath();
376 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
378 Intent i
= new Intent(Intent
.ACTION_VIEW
);
379 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
380 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
383 } catch (Throwable t
) {
384 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
385 boolean toastIt
= true
;
386 String mimeType
= "";
388 Intent i
= new Intent(Intent
.ACTION_VIEW
);
389 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
390 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
391 if (mimeType
!= null
) {
392 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
395 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
397 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
402 } catch (IndexOutOfBoundsException e
) {
403 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
405 } catch (ActivityNotFoundException e
) {
406 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
408 } catch (Throwable th
) {
409 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
413 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
422 public void onConfirmation(String callerTag
) {
423 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
424 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
425 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
428 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
429 mLastRemoteOperation
.execute(wc
, this, mHandler
);
431 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
432 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
438 public void onNeutral(String callerTag
) {
440 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
442 mFile
.setStoragePath(null
);
443 mStorageManager
.saveFile(mFile
);
444 updateFileDetails(mFile
, mAccount
);
449 public void onCancel(String callerTag
) {
450 Log
.d(TAG
, "REMOVAL CANCELED");
455 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
457 * @return True when the fragment was created with the empty layout.
459 public boolean isEmpty() {
460 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
467 public OCFile
getFile(){
472 * Use this method to signal this Activity that it shall update its view.
474 * @param file : An {@link OCFile}
476 public void updateFileDetails(OCFile file
, Account ocAccount
) {
478 if (ocAccount
!= null
&& (
479 mStorageManager
== null
||
480 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
482 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
484 mAccount
= ocAccount
;
485 updateFileDetails(false
, false
);
490 * Updates the view with all relevant details about that file.
492 * TODO Remove parameter when the transferring state of files is kept in database.
494 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
496 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
497 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
498 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
500 * @param refresh If 'true', try to refresh the hold file from the database
502 public void updateFileDetails(boolean transferring
, boolean refresh
) {
506 if (refresh
&& mStorageManager
!= null
) {
507 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
511 setFilename(mFile
.getFileName());
512 setFiletype(mFile
.getMimetype());
513 setFilesize(mFile
.getFileLength());
514 if(ocVersionSupportsTimeCreated()){
515 setTimeCreated(mFile
.getCreationTimestamp());
518 setTimeModified(mFile
.getModificationTimestamp());
520 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
521 cb
.setChecked(mFile
.keepInSync());
523 // configure UI for depending upon local state of the file
524 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
525 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
526 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
527 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
528 setButtonsForTransferring();
530 } else if (mFile
.isDown()) {
535 // TODO load default preview image; when the local file is removed, the preview remains there
536 setButtonsForRemote();
539 getView().invalidate();
544 * Checks if the fragment is ready to show details of a OCFile
546 * @return 'True' when the fragment is ready to show details of a file
548 private boolean readyToShow() {
549 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
555 * Updates the filename in view
556 * @param filename to set
558 private void setFilename(String filename
) {
559 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
561 tv
.setText(filename
);
565 * Updates the MIME type in view
566 * @param mimetype to set
568 private void setFiletype(String mimetype
) {
569 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
571 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
572 tv
.setText(printableMimetype
);
574 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
576 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
581 * Updates the file size in view
582 * @param filesize in bytes to set
584 private void setFilesize(long filesize
) {
585 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
587 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
591 * Updates the time that the file was created in view
592 * @param milliseconds Unix time to set
594 private void setTimeCreated(long milliseconds
){
595 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
596 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
598 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
599 tv
.setVisibility(View
.VISIBLE
);
600 tvLabel
.setVisibility(View
.VISIBLE
);
605 * Updates the time that the file was last modified
606 * @param milliseconds Unix time to set
608 private void setTimeModified(long milliseconds
){
609 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
611 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
616 * Enables or disables buttons for a file being downloaded
618 private void setButtonsForTransferring() {
620 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
621 downloadButton
.setText(R
.string
.common_cancel
);
622 //downloadButton.setEnabled(false);
624 // let's protect the user from himself ;)
625 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
626 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
627 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
628 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
630 // show the progress bar for the transfer
631 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
632 progressBar
.setVisibility(View
.VISIBLE
);
633 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
634 progressText
.setVisibility(View
.VISIBLE
);
635 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
636 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
637 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
638 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
639 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
640 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
647 * Enables or disables buttons for a file locally available
649 private void setButtonsForDown() {
651 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
652 downloadButton
.setText(R
.string
.filedetails_sync_file
);
654 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
655 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
656 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
657 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
659 // hides the progress bar
660 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
661 progressBar
.setVisibility(View
.GONE
);
662 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
663 progressText
.setVisibility(View
.GONE
);
668 * Enables or disables buttons for a file not locally available
670 private void setButtonsForRemote() {
672 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
673 downloadButton
.setText(R
.string
.filedetails_download
);
675 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
676 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
677 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
678 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
680 // hides the progress bar
681 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
682 progressBar
.setVisibility(View
.GONE
);
683 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
684 progressText
.setVisibility(View
.GONE
);
690 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
691 * the time that the file was created. There is a chance that this will
692 * be fixed in future versions. Use this method to check if this version of
693 * ownCloud has this fix.
694 * @return True, if ownCloud the ownCloud version is supporting creation time
696 private boolean ocVersionSupportsTimeCreated(){
697 /*if(mAccount != null){
698 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
699 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
700 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
701 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
710 * Once the file upload has finished -> update view
712 * Being notified about the finish of an upload is necessary for the next sequence:
713 * 1. Upload a big file.
714 * 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
715 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
716 * 3. Click the file in the list to see its details.
717 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
719 private class UploadFinishReceiver
extends BroadcastReceiver
{
721 public void onReceive(Context context
, Intent intent
) {
722 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
724 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
725 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
726 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
727 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
728 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
731 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
733 if (renamedInUpload
) {
734 String newName
= (new File(uploadRemotePath
)).getName();
735 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
738 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
739 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
746 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
747 @SuppressWarnings("unused")
748 private class ShareRunnable
implements Runnable
{
749 private String mPath
;
751 public ShareRunnable(String path
) {
756 AccountManager am
= AccountManager
.get(getActivity());
757 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
758 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
759 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
761 Log
.d("share", "sharing for version " + ocv
.toString());
763 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
764 String APPS_PATH
= "/apps/files_sharing/";
765 String SHARE_PATH
= "ajax/share.php";
767 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
769 final String WEBDAV_SCRIPT
= "webdav.php";
770 final String WEBDAV_FILES_LOCATION
= "/files/";
772 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
773 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
774 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
776 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
777 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
779 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
781 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
782 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
783 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
784 Log
.d("share", mPath
+"");
785 formparams
.add(new BasicNameValuePair("sources",mPath
));
786 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
787 formparams
.add(new BasicNameValuePair("permissions", "0"));
788 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
792 PropFindMethod find
= new PropFindMethod(url
+"/");
793 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
794 Log
.d("sharer", ""+ url
+"/");
796 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
797 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
800 int status2
= wc
.executeMethod(find
);
802 Log
.d("sharer", "propstatus "+status2
);
804 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
805 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
807 status2
= wc
.executeMethod(get
);
809 Log
.d("sharer", "getstatus "+status2
);
810 Log
.d("sharer", "" + get
.getResponseBodyAsString());
812 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
813 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
816 status
= wc
.executeMethod(post
);
817 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
818 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
820 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
821 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
823 String resp
= post
.getResponseBodyAsString();
824 Log
.d("share", ""+post
.getURI().toString());
825 Log
.d("share", "returned status " + status
);
826 Log
.d("share", " " +resp
);
828 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
832 JSONObject jsonObject
= new JSONObject (resp
);
833 String jsonStatus
= jsonObject
.getString("status");
834 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
836 String token
= jsonObject
.getString("data");
837 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
838 Log
.d("Actions:shareFile ok", "url: " + uri
);
840 } catch (Exception e
) {
844 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
850 public void onDismiss(EditNameDialog dialog
) {
851 if (dialog
.getResult()) {
852 String newFilename
= dialog
.getNewFilename();
853 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
854 mLastRemoteOperation
= new RenameFileOperation( mFile
,
857 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
858 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
859 mLastRemoteOperation
.execute(wc
, this, mHandler
);
860 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
861 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
870 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
871 if (operation
.equals(mLastRemoteOperation
)) {
872 if (operation
instanceof RemoveFileOperation
) {
873 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
875 } else if (operation
instanceof RenameFileOperation
) {
876 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
878 } else if (operation
instanceof SynchronizeFileOperation
) {
879 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
885 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
886 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
887 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
889 if (result
.isSuccess()) {
890 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
892 if (inDisplayActivity
) {
894 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
895 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
896 transaction
.commit();
897 mContainerActivity
.onFileStateChanged();
899 getActivity().finish();
903 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
905 if (result
.isSslRecoverableException()) {
906 // TODO show the SSL warning dialog
911 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
912 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
913 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
915 if (result
.isSuccess()) {
916 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
917 mContainerActivity
.onFileStateChanged();
920 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
921 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
923 // TODO throw again the new rename dialog
925 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
927 if (result
.isSslRecoverableException()) {
928 // TODO show the SSL warning dialog
934 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
935 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
936 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
938 if (!result
.isSuccess()) {
939 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
940 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
941 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
942 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
946 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
950 if (mFile
.isDown()) {
954 setButtonsForRemote();
958 if (operation
.transferWasRequested()) {
959 setButtonsForTransferring();
960 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
961 // checking the service to see if the file is downloading results in FALSE
963 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
965 if (mFile
.isDown()) {
969 setButtonsForRemote();
976 public void listenForTransferProgress() {
977 if (mProgressListener
!= null
) {
978 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
979 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
981 if (mContainerActivity
.getFileUploaderBinder() != null
) {
982 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
988 public void leaveTransferProgress() {
989 if (mProgressListener
!= null
) {
990 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
991 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
993 if (mContainerActivity
.getFileUploaderBinder() != null
) {
994 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1002 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1004 * @author David A. Velasco
1006 private class ProgressListener
implements OnDatatransferProgressListener
{
1007 int mLastPercent
= 0;
1008 WeakReference
<ProgressBar
> mProgressBar
= null
;
1010 ProgressListener(ProgressBar progressBar
) {
1011 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1015 public void onTransferProgress(long progressRate
) {
1016 // old method, nothing here
1020 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1021 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1022 if (percent
!= mLastPercent
) {
1023 ProgressBar pb
= mProgressBar
.get();
1025 pb
.setProgress(percent
);
1026 pb
.postInvalidate();
1029 mLastPercent
= percent
;