1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.fragment
;
22 import java
.lang
.ref
.WeakReference
;
23 import java
.util
.ArrayList
;
24 import java
.util
.List
;
26 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
28 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
29 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
30 import org
.apache
.http
.HttpStatus
;
31 import org
.apache
.http
.NameValuePair
;
32 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
33 import org
.apache
.http
.message
.BasicNameValuePair
;
34 import org
.apache
.http
.protocol
.HTTP
;
35 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
36 import org
.json
.JSONObject
;
38 import android
.accounts
.Account
;
39 import android
.accounts
.AccountManager
;
40 //import android.annotation.SuppressLint;
41 import android
.app
.Activity
;
42 import android
.content
.ActivityNotFoundException
;
43 import android
.content
.BroadcastReceiver
;
44 import android
.content
.Context
;
45 import android
.content
.Intent
;
46 import android
.content
.IntentFilter
;
47 import android
.net
.Uri
;
48 import android
.os
.Bundle
;
49 import android
.os
.Handler
;
50 import android
.support
.v4
.app
.FragmentTransaction
;
51 import android
.util
.Log
;
52 import android
.view
.LayoutInflater
;
53 import android
.view
.View
;
54 import android
.view
.View
.OnClickListener
;
55 import android
.view
.ViewGroup
;
56 import android
.webkit
.MimeTypeMap
;
57 import android
.widget
.Button
;
58 import android
.widget
.CheckBox
;
59 import android
.widget
.ImageView
;
60 import android
.widget
.ProgressBar
;
61 import android
.widget
.TextView
;
62 import android
.widget
.Toast
;
64 import android
.graphics
.Bitmap
;
65 import android
.graphics
.BitmapFactory
;
66 import android
.graphics
.BitmapFactory
.Options
;
67 import android
.graphics
.Point
;
68 import android
.net
.Uri
;
69 import android
.os
.AsyncTask
;
70 import android
.os
.Bundle
;
71 import android
.os
.Handler
;
72 import android
.support
.v4
.app
.DialogFragment
;
73 import android
.support
.v4
.app
.FragmentTransaction
;
74 import android
.util
.Log
;
75 import android
.view
.Display
;
76 import android
.view
.LayoutInflater
;
77 import android
.view
.View
;
78 import android
.view
.View
.OnClickListener
;
79 import android
.view
.ViewGroup
;
80 import android
.webkit
.MimeTypeMap
;
81 import android
.widget
.Button
;
82 import android
.widget
.CheckBox
;
83 import android
.widget
.ImageView
;
84 import android
.widget
.TextView
;
85 import android
.widget
.Toast
;
88 import com
.actionbarsherlock
.app
.SherlockFragment
;
89 import com
.owncloud
.android
.AccountUtils
;
90 import com
.owncloud
.android
.DisplayUtils
;
91 import com
.owncloud
.android
.Log_OC
;
92 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
93 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
94 import com
.owncloud
.android
.datamodel
.OCFile
;
95 import com
.owncloud
.android
.files
.services
.FileObserverService
;
96 import com
.owncloud
.android
.files
.services
.FileUploader
;
97 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
98 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
99 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
100 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
101 import com
.owncloud
.android
.operations
.RemoteOperation
;
102 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
103 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
104 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
105 import com
.owncloud
.android
.operations
.RenameFileOperation
;
106 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
107 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
108 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
109 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
110 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
111 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
112 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
114 import com
.owncloud
.android
.R
;
116 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
117 import eu
.alefzero
.webdav
.WebdavClient
;
118 import eu
.alefzero
.webdav
.WebdavUtils
;
122 * This Fragment is used to display the details about a file.
124 * @author Bartek Przybylski
125 * @author David A. Velasco
127 public class FileDetailFragment
extends SherlockFragment
implements
129 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
132 public static final String EXTRA_FILE
= "FILE";
133 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
135 private FileFragment
.ContainerActivity mContainerActivity
;
139 private OCFile mFile
;
140 private Account mAccount
;
141 private FileDataStorageManager mStorageManager
;
143 private UploadFinishReceiver mUploadFinishReceiver
;
144 public ProgressListener mProgressListener
;
146 private Handler mHandler
;
147 private RemoteOperation mLastRemoteOperation
;
149 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
150 public static final String FTAG
= "FileDetails";
151 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
155 * Creates an empty details fragment.
157 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
159 public FileDetailFragment() {
162 mStorageManager
= null
;
163 mLayout
= R
.layout
.file_details_empty
;
164 mProgressListener
= null
;
169 * Creates a details fragment.
171 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
173 * @param fileToDetail An {@link OCFile} to show in the fragment
174 * @param ocAccount An ownCloud account; needed to start downloads
176 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
177 mFile
= fileToDetail
;
178 mAccount
= ocAccount
;
179 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
180 mLayout
= R
.layout
.file_details_empty
;
181 mProgressListener
= null
;
186 public void onCreate(Bundle savedInstanceState
) {
187 super.onCreate(savedInstanceState
);
188 mHandler
= new Handler();
193 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
194 Bundle savedInstanceState
) {
195 super.onCreateView(inflater
, container
, savedInstanceState
);
197 if (savedInstanceState
!= null
) {
198 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
199 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
202 if(mFile
!= null
&& mAccount
!= null
) {
203 mLayout
= R
.layout
.file_details_fragment
;
207 view
= inflater
.inflate(mLayout
, container
, false
);
210 if (mLayout
== R
.layout
.file_details_fragment
) {
211 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
212 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
213 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
214 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
215 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
216 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
217 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
218 mProgressListener
= new ProgressListener(progressBar
);
221 updateFileDetails(false
, false
);
230 public void onAttach(Activity activity
) {
231 super.onAttach(activity
);
233 mContainerActivity
= (ContainerActivity
) activity
;
235 } catch (ClassCastException e
) {
236 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
245 public void onActivityCreated(Bundle savedInstanceState
) {
246 super.onActivityCreated(savedInstanceState
);
247 if (mAccount
!= null
) {
248 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
254 public void onSaveInstanceState(Bundle outState
) {
255 super.onSaveInstanceState(outState
);
256 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
257 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
261 public void onStart() {
263 listenForTransferProgress();
267 public void onResume() {
269 mUploadFinishReceiver
= new UploadFinishReceiver();
270 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
271 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
277 public void onPause() {
279 if (mUploadFinishReceiver
!= null
) {
280 getActivity().unregisterReceiver(mUploadFinishReceiver
);
281 mUploadFinishReceiver
= null
;
287 public void onStop() {
289 leaveTransferProgress();
294 public View
getView() {
295 return super.getView() == null ? mView
: super.getView();
299 public void onClick(View v
) {
301 case R
.id
.fdDownloadBtn
: {
302 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
303 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
304 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
305 downloaderBinder
.cancel(mAccount
, mFile
);
306 if (mFile
.isDown()) {
309 setButtonsForRemote();
312 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
313 uploaderBinder
.cancel(mAccount
, mFile
);
314 if (!mFile
.fileExists()) {
315 // TODO make something better
316 if (getActivity() instanceof FileDisplayActivity
) {
318 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
319 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
320 transaction
.commit();
321 mContainerActivity
.onFileStateChanged();
323 getActivity().finish();
326 } else if (mFile
.isDown()) {
329 setButtonsForRemote();
333 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
334 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
335 mLastRemoteOperation
.execute(wc
, this, mHandler
);
338 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
339 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
344 case R
.id
.fdKeepInSync
: {
345 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
346 mFile
.setKeepInSync(cb
.isChecked());
347 mStorageManager
.saveFile(mFile
);
349 /// register the OCFile instance in the observer service to monitor local updates;
350 /// if necessary, the file is download
351 Intent intent
= new Intent(getActivity().getApplicationContext(),
352 FileObserverService
.class);
353 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
355 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
356 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
357 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
358 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
359 getActivity().startService(intent
);
361 if (mFile
.keepInSync()) {
362 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
366 case R
.id
.fdRenameBtn
: {
367 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
368 dialog
.show(getFragmentManager(), "nameeditdialog");
371 case R
.id
.fdRemoveBtn
: {
372 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
373 R
.string
.confirmation_remove_alert
,
374 new String
[]{mFile
.getFileName()},
375 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
376 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
377 R
.string
.common_cancel
);
378 confDialog
.setOnConfirmationListener(this);
379 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
382 case R
.id
.fdOpenBtn
: {
387 Log_OC
.e(TAG
, "Incorrect view clicked!");
390 /* else if (v.getId() == R.id.fdShareBtn) {
391 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
400 private void openFile() {
402 String storagePath
= mFile
.getStoragePath();
403 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
405 Intent i
= new Intent(Intent
.ACTION_VIEW
);
406 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
407 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
410 } catch (Throwable t
) {
411 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
412 boolean toastIt
= true
;
413 String mimeType
= "";
415 Intent i
= new Intent(Intent
.ACTION_VIEW
);
416 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
417 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
418 if (mimeType
!= null
) {
419 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
422 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
424 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
429 } catch (IndexOutOfBoundsException e
) {
430 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
432 } catch (ActivityNotFoundException e
) {
433 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
435 } catch (Throwable th
) {
436 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
440 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
449 public void onConfirmation(String callerTag
) {
450 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
451 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
452 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
455 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
456 mLastRemoteOperation
.execute(wc
, this, mHandler
);
458 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
459 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
465 public void onNeutral(String callerTag
) {
467 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
469 mFile
.setStoragePath(null
);
470 mStorageManager
.saveFile(mFile
);
471 updateFileDetails(mFile
, mAccount
);
476 public void onCancel(String callerTag
) {
477 Log
.d(TAG
, "REMOVAL CANCELED");
482 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
484 * @return True when the fragment was created with the empty layout.
486 public boolean isEmpty() {
487 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
494 public OCFile
getFile(){
499 * Use this method to signal this Activity that it shall update its view.
501 * @param file : An {@link OCFile}
503 public void updateFileDetails(OCFile file
, Account ocAccount
) {
505 if (ocAccount
!= null
&& (
506 mStorageManager
== null
||
507 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
509 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
511 mAccount
= ocAccount
;
512 updateFileDetails(false
, false
);
516 * Updates the view with all relevant details about that file.
518 * TODO Remove parameter when the transferring state of files is kept in database.
520 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
522 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
523 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
524 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
526 * @param refresh If 'true', try to refresh the hold file from the database
528 public void updateFileDetails(boolean transferring
, boolean refresh
) {
532 if (refresh
&& mStorageManager
!= null
) {
533 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
537 setFilename(mFile
.getFileName());
538 setFiletype(mFile
.getMimetype());
539 setFilesize(mFile
.getFileLength());
540 if(ocVersionSupportsTimeCreated()){
541 setTimeCreated(mFile
.getCreationTimestamp());
544 setTimeModified(mFile
.getModificationTimestamp());
546 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
547 cb
.setChecked(mFile
.keepInSync());
549 // configure UI for depending upon local state of the file
550 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
551 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
552 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
553 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
554 setButtonsForTransferring();
556 } else if (mFile
.isDown()) {
561 // TODO load default preview image; when the local file is removed, the preview remains there
562 setButtonsForRemote();
565 getView().invalidate();
570 * Checks if the fragment is ready to show details of a OCFile
572 * @return 'True' when the fragment is ready to show details of a file
574 private boolean readyToShow() {
575 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
580 * Updates the filename in view
581 * @param filename to set
583 private void setFilename(String filename
) {
584 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
586 tv
.setText(filename
);
590 * Updates the MIME type in view
591 * @param mimetype to set
593 private void setFiletype(String mimetype
) {
594 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
596 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
597 tv
.setText(printableMimetype
);
599 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
601 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
606 * Updates the file size in view
607 * @param filesize in bytes to set
609 private void setFilesize(long filesize
) {
610 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
612 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
616 * Updates the time that the file was created in view
617 * @param milliseconds Unix time to set
619 private void setTimeCreated(long milliseconds
){
620 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
621 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
623 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
624 tv
.setVisibility(View
.VISIBLE
);
625 tvLabel
.setVisibility(View
.VISIBLE
);
630 * Updates the time that the file was last modified
631 * @param milliseconds Unix time to set
633 private void setTimeModified(long milliseconds
){
634 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
636 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
641 * Enables or disables buttons for a file being downloaded
643 private void setButtonsForTransferring() {
645 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
646 downloadButton
.setText(R
.string
.common_cancel
);
647 //downloadButton.setEnabled(false);
649 // let's protect the user from himself ;)
650 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
651 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
652 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
653 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
655 // show the progress bar for the transfer
656 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
657 progressBar
.setVisibility(View
.VISIBLE
);
658 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
659 progressText
.setVisibility(View
.VISIBLE
);
660 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
661 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
662 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
663 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
664 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
665 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
671 * Enables or disables buttons for a file locally available
673 private void setButtonsForDown() {
675 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
676 downloadButton
.setText(R
.string
.filedetails_sync_file
);
678 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
679 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
680 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
681 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
683 // hides the progress bar
684 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
685 progressBar
.setVisibility(View
.GONE
);
686 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
687 progressText
.setVisibility(View
.GONE
);
692 * Enables or disables buttons for a file not locally available
694 private void setButtonsForRemote() {
696 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
697 downloadButton
.setText(R
.string
.filedetails_download
);
699 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
700 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
701 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
702 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
704 // hides the progress bar
705 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
706 progressBar
.setVisibility(View
.GONE
);
707 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
708 progressText
.setVisibility(View
.GONE
);
714 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
715 * the time that the file was created. There is a chance that this will
716 * be fixed in future versions. Use this method to check if this version of
717 * ownCloud has this fix.
718 * @return True, if ownCloud the ownCloud version is supporting creation time
720 private boolean ocVersionSupportsTimeCreated(){
721 /*if(mAccount != null){
722 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
723 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
724 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
725 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
734 * Once the file upload has finished -> update view
736 * Being notified about the finish of an upload is necessary for the next sequence:
737 * 1. Upload a big file.
738 * 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
739 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
740 * 3. Click the file in the list to see its details.
741 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
743 private class UploadFinishReceiver
extends BroadcastReceiver
{
745 public void onReceive(Context context
, Intent intent
) {
746 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
748 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
749 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
750 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
751 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
752 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
755 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
757 if (renamedInUpload
) {
758 String newName
= (new File(uploadRemotePath
)).getName();
759 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
762 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
763 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
770 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
771 @SuppressWarnings("unused")
772 private class ShareRunnable
implements Runnable
{
773 private String mPath
;
775 public ShareRunnable(String path
) {
780 AccountManager am
= AccountManager
.get(getActivity());
781 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
782 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
783 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
785 Log
.d("share", "sharing for version " + ocv
.toString());
787 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
788 String APPS_PATH
= "/apps/files_sharing/";
789 String SHARE_PATH
= "ajax/share.php";
791 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
793 final String WEBDAV_SCRIPT
= "webdav.php";
794 final String WEBDAV_FILES_LOCATION
= "/files/";
796 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
797 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
798 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
800 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
801 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
803 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
805 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
806 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
807 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
808 Log
.d("share", mPath
+"");
809 formparams
.add(new BasicNameValuePair("sources",mPath
));
810 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
811 formparams
.add(new BasicNameValuePair("permissions", "0"));
812 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
816 PropFindMethod find
= new PropFindMethod(url
+"/");
817 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
818 Log
.d("sharer", ""+ url
+"/");
820 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
821 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
824 int status2
= wc
.executeMethod(find
);
826 Log
.d("sharer", "propstatus "+status2
);
828 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
829 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
831 status2
= wc
.executeMethod(get
);
833 Log
.d("sharer", "getstatus "+status2
);
834 Log
.d("sharer", "" + get
.getResponseBodyAsString());
836 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
837 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
840 status
= wc
.executeMethod(post
);
841 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
842 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
844 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
845 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
847 String resp
= post
.getResponseBodyAsString();
848 Log
.d("share", ""+post
.getURI().toString());
849 Log
.d("share", "returned status " + status
);
850 Log
.d("share", " " +resp
);
852 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
856 JSONObject jsonObject
= new JSONObject (resp
);
857 String jsonStatus
= jsonObject
.getString("status");
858 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
860 String token
= jsonObject
.getString("data");
861 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
862 Log
.d("Actions:shareFile ok", "url: " + uri
);
864 } catch (Exception e
) {
868 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
874 public void onDismiss(EditNameDialog dialog
) {
875 if (dialog
.getResult()) {
876 String newFilename
= dialog
.getNewFilename();
877 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
878 mLastRemoteOperation
= new RenameFileOperation( mFile
,
881 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
882 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
883 mLastRemoteOperation
.execute(wc
, this, mHandler
);
884 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
885 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
894 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
895 if (operation
.equals(mLastRemoteOperation
)) {
896 if (operation
instanceof RemoveFileOperation
) {
897 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
899 } else if (operation
instanceof RenameFileOperation
) {
900 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
902 } else if (operation
instanceof SynchronizeFileOperation
) {
903 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
909 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
910 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
911 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
913 if (result
.isSuccess()) {
914 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
916 if (inDisplayActivity
) {
918 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
919 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
920 transaction
.commit();
921 mContainerActivity
.onFileStateChanged();
923 getActivity().finish();
927 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
929 if (result
.isSslRecoverableException()) {
930 // TODO show the SSL warning dialog
935 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
936 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
937 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
939 if (result
.isSuccess()) {
940 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
941 mContainerActivity
.onFileStateChanged();
944 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
945 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
947 // TODO throw again the new rename dialog
949 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
951 if (result
.isSslRecoverableException()) {
952 // TODO show the SSL warning dialog
958 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
959 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
960 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
962 if (!result
.isSuccess()) {
963 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
964 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
965 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
966 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
970 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
974 if (mFile
.isDown()) {
978 setButtonsForRemote();
982 if (operation
.transferWasRequested()) {
983 setButtonsForTransferring();
984 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
985 // checking the service to see if the file is downloading results in FALSE
987 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
989 if (mFile
.isDown()) {
993 setButtonsForRemote();
1000 public void listenForTransferProgress() {
1001 if (mProgressListener
!= null
) {
1002 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1003 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1005 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1006 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1012 public void leaveTransferProgress() {
1013 if (mProgressListener
!= null
) {
1014 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1015 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1017 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1018 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1026 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1028 * @author David A. Velasco
1030 private class ProgressListener
implements OnDatatransferProgressListener
{
1031 int mLastPercent
= 0;
1032 WeakReference
<ProgressBar
> mProgressBar
= null
;
1034 ProgressListener(ProgressBar progressBar
) {
1035 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1039 public void onTransferProgress(long progressRate
) {
1040 // old method, nothing here
1044 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1045 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1046 if (percent
!= mLastPercent
) {
1047 ProgressBar pb
= mProgressBar
.get();
1049 pb
.setProgress(percent
);
1050 pb
.postInvalidate();
1053 mLastPercent
= percent
;