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 version 2,
7 * as published by the Free Software Foundation.
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.annotation.SuppressLint;
40 import android
.app
.Activity
;
41 import android
.content
.ActivityNotFoundException
;
42 import android
.content
.BroadcastReceiver
;
43 import android
.content
.Context
;
44 import android
.content
.Intent
;
45 import android
.content
.IntentFilter
;
46 import android
.net
.Uri
;
47 import android
.os
.Bundle
;
48 import android
.os
.Handler
;
49 import android
.support
.v4
.app
.FragmentTransaction
;
50 import android
.util
.Log
;
51 import android
.view
.LayoutInflater
;
52 import android
.view
.View
;
53 import android
.view
.View
.OnClickListener
;
54 import android
.view
.ViewGroup
;
55 import android
.webkit
.MimeTypeMap
;
56 import android
.widget
.Button
;
57 import android
.widget
.CheckBox
;
58 import android
.widget
.ImageView
;
59 import android
.widget
.ProgressBar
;
60 import android
.widget
.TextView
;
61 import android
.widget
.Toast
;
63 import android
.graphics
.Bitmap
;
64 import android
.graphics
.BitmapFactory
;
65 import android
.graphics
.BitmapFactory
.Options
;
66 import android
.graphics
.Point
;
67 import android
.net
.Uri
;
68 import android
.os
.AsyncTask
;
69 import android
.os
.Bundle
;
70 import android
.os
.Handler
;
71 import android
.support
.v4
.app
.DialogFragment
;
72 import android
.support
.v4
.app
.FragmentTransaction
;
73 import android
.util
.Log
;
74 import android
.view
.Display
;
75 import android
.view
.LayoutInflater
;
76 import android
.view
.View
;
77 import android
.view
.View
.OnClickListener
;
78 import android
.view
.ViewGroup
;
79 import android
.webkit
.MimeTypeMap
;
80 import android
.widget
.Button
;
81 import android
.widget
.CheckBox
;
82 import android
.widget
.ImageView
;
83 import android
.widget
.TextView
;
84 import android
.widget
.Toast
;
87 import com
.actionbarsherlock
.app
.SherlockFragment
;
88 import com
.owncloud
.android
.AccountUtils
;
89 import com
.owncloud
.android
.DisplayUtils
;
90 import com
.owncloud
.android
.Log_OC
;
91 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
92 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
93 import com
.owncloud
.android
.datamodel
.OCFile
;
94 import com
.owncloud
.android
.files
.services
.FileObserverService
;
95 import com
.owncloud
.android
.files
.services
.FileUploader
;
96 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
97 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
98 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
99 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
100 import com
.owncloud
.android
.operations
.RemoteOperation
;
101 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
102 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
103 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
104 import com
.owncloud
.android
.operations
.RenameFileOperation
;
105 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
106 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
107 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
108 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
109 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
110 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
111 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
113 import com
.owncloud
.android
.R
;
115 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
116 import eu
.alefzero
.webdav
.WebdavClient
;
117 import eu
.alefzero
.webdav
.WebdavUtils
;
121 * This Fragment is used to display the details about a file.
123 * @author Bartek Przybylski
124 * @author David A. Velasco
126 public class FileDetailFragment
extends SherlockFragment
implements
128 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
131 public static final String EXTRA_FILE
= "FILE";
132 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
134 private FileFragment
.ContainerActivity mContainerActivity
;
138 private OCFile mFile
;
139 private Account mAccount
;
140 private FileDataStorageManager mStorageManager
;
142 private UploadFinishReceiver mUploadFinishReceiver
;
143 public ProgressListener mProgressListener
;
145 private Handler mHandler
;
146 private RemoteOperation mLastRemoteOperation
;
148 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
149 public static final String FTAG
= "FileDetails";
150 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
154 * Creates an empty details fragment.
156 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
158 public FileDetailFragment() {
161 mStorageManager
= null
;
162 mLayout
= R
.layout
.file_details_empty
;
163 mProgressListener
= null
;
168 * Creates a details fragment.
170 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
172 * @param fileToDetail An {@link OCFile} to show in the fragment
173 * @param ocAccount An ownCloud account; needed to start downloads
175 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
176 mFile
= fileToDetail
;
177 mAccount
= ocAccount
;
178 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
179 mLayout
= R
.layout
.file_details_empty
;
180 mProgressListener
= null
;
185 public void onCreate(Bundle savedInstanceState
) {
186 super.onCreate(savedInstanceState
);
187 mHandler
= new Handler();
192 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
193 Bundle savedInstanceState
) {
194 super.onCreateView(inflater
, container
, savedInstanceState
);
196 if (savedInstanceState
!= null
) {
197 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
198 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
201 if(mFile
!= null
&& mAccount
!= null
) {
202 mLayout
= R
.layout
.file_details_fragment
;
206 view
= inflater
.inflate(mLayout
, container
, false
);
209 if (mLayout
== R
.layout
.file_details_fragment
) {
210 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
211 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
212 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
213 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
214 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
215 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
216 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
217 mProgressListener
= new ProgressListener(progressBar
);
220 updateFileDetails(false
, false
);
229 public void onAttach(Activity activity
) {
230 super.onAttach(activity
);
232 mContainerActivity
= (ContainerActivity
) activity
;
234 } catch (ClassCastException e
) {
235 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
244 public void onActivityCreated(Bundle savedInstanceState
) {
245 super.onActivityCreated(savedInstanceState
);
246 if (mAccount
!= null
) {
247 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
253 public void onSaveInstanceState(Bundle outState
) {
254 super.onSaveInstanceState(outState
);
255 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
256 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
260 public void onStart() {
262 listenForTransferProgress();
266 public void onResume() {
268 mUploadFinishReceiver
= new UploadFinishReceiver();
269 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
270 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
276 public void onPause() {
278 if (mUploadFinishReceiver
!= null
) {
279 getActivity().unregisterReceiver(mUploadFinishReceiver
);
280 mUploadFinishReceiver
= null
;
286 public void onStop() {
288 leaveTransferProgress();
293 public View
getView() {
294 return super.getView() == null ? mView
: super.getView();
298 public void onClick(View v
) {
300 case R
.id
.fdDownloadBtn
: {
301 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
302 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
303 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
304 downloaderBinder
.cancel(mAccount
, mFile
);
305 if (mFile
.isDown()) {
308 setButtonsForRemote();
311 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
312 uploaderBinder
.cancel(mAccount
, mFile
);
313 if (!mFile
.fileExists()) {
314 // TODO make something better
315 if (getActivity() instanceof FileDisplayActivity
) {
317 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
318 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
319 transaction
.commit();
320 mContainerActivity
.onFileStateChanged();
322 getActivity().finish();
325 } else if (mFile
.isDown()) {
328 setButtonsForRemote();
332 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
333 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
334 mLastRemoteOperation
.execute(wc
, this, mHandler
);
337 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
338 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
343 case R
.id
.fdKeepInSync
: {
344 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
345 mFile
.setKeepInSync(cb
.isChecked());
346 mStorageManager
.saveFile(mFile
);
348 /// register the OCFile instance in the observer service to monitor local updates;
349 /// if necessary, the file is download
350 Intent intent
= new Intent(getActivity().getApplicationContext(),
351 FileObserverService
.class);
352 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
354 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
355 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
356 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
357 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
358 getActivity().startService(intent
);
360 if (mFile
.keepInSync()) {
361 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
365 case R
.id
.fdRenameBtn
: {
366 String fileName
= mFile
.getFileName();
367 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
368 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
369 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
370 dialog
.show(getFragmentManager(), "nameeditdialog");
373 case R
.id
.fdRemoveBtn
: {
374 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
375 R
.string
.confirmation_remove_alert
,
376 new String
[]{mFile
.getFileName()},
377 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
378 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
379 R
.string
.common_cancel
);
380 confDialog
.setOnConfirmationListener(this);
381 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
384 case R
.id
.fdOpenBtn
: {
389 Log_OC
.e(TAG
, "Incorrect view clicked!");
392 /* else if (v.getId() == R.id.fdShareBtn) {
393 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
402 private void openFile() {
404 String storagePath
= mFile
.getStoragePath();
405 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
407 Intent i
= new Intent(Intent
.ACTION_VIEW
);
408 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
409 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
412 } catch (Throwable t
) {
413 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
414 boolean toastIt
= true
;
415 String mimeType
= "";
417 Intent i
= new Intent(Intent
.ACTION_VIEW
);
418 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
419 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
420 if (mimeType
!= null
) {
421 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
424 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
426 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
431 } catch (IndexOutOfBoundsException e
) {
432 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
434 } catch (ActivityNotFoundException e
) {
435 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
437 } catch (Throwable th
) {
438 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
442 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
451 public void onConfirmation(String callerTag
) {
452 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
453 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
454 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
457 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
458 mLastRemoteOperation
.execute(wc
, this, mHandler
);
460 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
461 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
467 public void onNeutral(String callerTag
) {
469 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
471 mFile
.setStoragePath(null
);
472 mStorageManager
.saveFile(mFile
);
473 updateFileDetails(mFile
, mAccount
);
478 public void onCancel(String callerTag
) {
479 Log
.d(TAG
, "REMOVAL CANCELED");
484 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
486 * @return True when the fragment was created with the empty layout.
488 public boolean isEmpty() {
489 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
496 public OCFile
getFile(){
501 * Use this method to signal this Activity that it shall update its view.
503 * @param file : An {@link OCFile}
505 public void updateFileDetails(OCFile file
, Account ocAccount
) {
507 if (ocAccount
!= null
&& (
508 mStorageManager
== null
||
509 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
511 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
513 mAccount
= ocAccount
;
514 updateFileDetails(false
, false
);
518 * Updates the view with all relevant details about that file.
520 * TODO Remove parameter when the transferring state of files is kept in database.
522 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
524 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
525 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
526 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
528 * @param refresh If 'true', try to refresh the hold file from the database
530 public void updateFileDetails(boolean transferring
, boolean refresh
) {
534 if (refresh
&& mStorageManager
!= null
) {
535 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
539 setFilename(mFile
.getFileName());
540 setFiletype(mFile
.getMimetype());
541 setFilesize(mFile
.getFileLength());
542 if(ocVersionSupportsTimeCreated()){
543 setTimeCreated(mFile
.getCreationTimestamp());
546 setTimeModified(mFile
.getModificationTimestamp());
548 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
549 cb
.setChecked(mFile
.keepInSync());
551 // configure UI for depending upon local state of the file
552 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
553 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
554 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
555 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
556 setButtonsForTransferring();
558 } else if (mFile
.isDown()) {
563 // TODO load default preview image; when the local file is removed, the preview remains there
564 setButtonsForRemote();
567 getView().invalidate();
572 * Checks if the fragment is ready to show details of a OCFile
574 * @return 'True' when the fragment is ready to show details of a file
576 private boolean readyToShow() {
577 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
582 * Updates the filename in view
583 * @param filename to set
585 private void setFilename(String filename
) {
586 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
588 tv
.setText(filename
);
592 * Updates the MIME type in view
593 * @param mimetype to set
595 private void setFiletype(String mimetype
) {
596 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
598 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
599 tv
.setText(printableMimetype
);
601 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
603 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
608 * Updates the file size in view
609 * @param filesize in bytes to set
611 private void setFilesize(long filesize
) {
612 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
614 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
618 * Updates the time that the file was created in view
619 * @param milliseconds Unix time to set
621 private void setTimeCreated(long milliseconds
){
622 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
623 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
625 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
626 tv
.setVisibility(View
.VISIBLE
);
627 tvLabel
.setVisibility(View
.VISIBLE
);
632 * Updates the time that the file was last modified
633 * @param milliseconds Unix time to set
635 private void setTimeModified(long milliseconds
){
636 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
638 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
643 * Enables or disables buttons for a file being downloaded
645 private void setButtonsForTransferring() {
647 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
648 downloadButton
.setText(R
.string
.common_cancel
);
649 //downloadButton.setEnabled(false);
651 // let's protect the user from himself ;)
652 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
653 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
654 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
655 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
657 // show the progress bar for the transfer
658 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
659 progressBar
.setVisibility(View
.VISIBLE
);
660 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
661 progressText
.setVisibility(View
.VISIBLE
);
662 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
663 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
664 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
665 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
666 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
667 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
673 * Enables or disables buttons for a file locally available
675 private void setButtonsForDown() {
677 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
678 downloadButton
.setText(R
.string
.filedetails_sync_file
);
680 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
681 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
682 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
683 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
685 // hides the progress bar
686 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
687 progressBar
.setVisibility(View
.GONE
);
688 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
689 progressText
.setVisibility(View
.GONE
);
694 * Enables or disables buttons for a file not locally available
696 private void setButtonsForRemote() {
698 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
699 downloadButton
.setText(R
.string
.filedetails_download
);
701 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
702 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
703 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
704 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
706 // hides the progress bar
707 ProgressBar progressBar
= (ProgressBar
)getView().findViewById(R
.id
.fdProgressBar
);
708 progressBar
.setVisibility(View
.GONE
);
709 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
710 progressText
.setVisibility(View
.GONE
);
716 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
717 * the time that the file was created. There is a chance that this will
718 * be fixed in future versions. Use this method to check if this version of
719 * ownCloud has this fix.
720 * @return True, if ownCloud the ownCloud version is supporting creation time
722 private boolean ocVersionSupportsTimeCreated(){
723 /*if(mAccount != null){
724 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
725 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
726 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
727 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
736 * Once the file upload has finished -> update view
738 * Being notified about the finish of an upload is necessary for the next sequence:
739 * 1. Upload a big file.
740 * 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
741 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
742 * 3. Click the file in the list to see its details.
743 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
745 private class UploadFinishReceiver
extends BroadcastReceiver
{
747 public void onReceive(Context context
, Intent intent
) {
748 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
750 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
751 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
752 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
753 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
754 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
757 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
759 if (renamedInUpload
) {
760 String newName
= (new File(uploadRemotePath
)).getName();
761 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
764 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
765 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
772 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
773 @SuppressWarnings("unused")
774 private class ShareRunnable
implements Runnable
{
775 private String mPath
;
777 public ShareRunnable(String path
) {
782 AccountManager am
= AccountManager
.get(getActivity());
783 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
784 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
785 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
787 Log
.d("share", "sharing for version " + ocv
.toString());
789 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
790 String APPS_PATH
= "/apps/files_sharing/";
791 String SHARE_PATH
= "ajax/share.php";
793 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
795 final String WEBDAV_SCRIPT
= "webdav.php";
796 final String WEBDAV_FILES_LOCATION
= "/files/";
798 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
799 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
800 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
802 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
803 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
805 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
807 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
808 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
809 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
810 Log
.d("share", mPath
+"");
811 formparams
.add(new BasicNameValuePair("sources",mPath
));
812 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
813 formparams
.add(new BasicNameValuePair("permissions", "0"));
814 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
818 PropFindMethod find
= new PropFindMethod(url
+"/");
819 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
820 Log
.d("sharer", ""+ url
+"/");
822 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
823 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
826 int status2
= wc
.executeMethod(find
);
828 Log
.d("sharer", "propstatus "+status2
);
830 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
831 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
833 status2
= wc
.executeMethod(get
);
835 Log
.d("sharer", "getstatus "+status2
);
836 Log
.d("sharer", "" + get
.getResponseBodyAsString());
838 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
839 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
842 status
= wc
.executeMethod(post
);
843 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
844 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
846 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
847 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
849 String resp
= post
.getResponseBodyAsString();
850 Log
.d("share", ""+post
.getURI().toString());
851 Log
.d("share", "returned status " + status
);
852 Log
.d("share", " " +resp
);
854 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
858 JSONObject jsonObject
= new JSONObject (resp
);
859 String jsonStatus
= jsonObject
.getString("status");
860 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
862 String token
= jsonObject
.getString("data");
863 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
864 Log
.d("Actions:shareFile ok", "url: " + uri
);
866 } catch (Exception e
) {
870 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
876 public void onDismiss(EditNameDialog dialog
) {
877 if (dialog
.getResult()) {
878 String newFilename
= dialog
.getNewFilename();
879 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
880 mLastRemoteOperation
= new RenameFileOperation( mFile
,
883 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
884 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
885 mLastRemoteOperation
.execute(wc
, this, mHandler
);
886 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
887 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
896 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
897 if (operation
.equals(mLastRemoteOperation
)) {
898 if (operation
instanceof RemoveFileOperation
) {
899 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
901 } else if (operation
instanceof RenameFileOperation
) {
902 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
904 } else if (operation
instanceof SynchronizeFileOperation
) {
905 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
911 private void onRemoveFileOperationFinish(RemoveFileOperation 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 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
918 if (inDisplayActivity
) {
920 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
921 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
922 transaction
.commit();
923 mContainerActivity
.onFileStateChanged();
925 getActivity().finish();
929 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
931 if (result
.isSslRecoverableException()) {
932 // TODO show the SSL warning dialog
937 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
938 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
939 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
941 if (result
.isSuccess()) {
942 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
943 mContainerActivity
.onFileStateChanged();
946 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
947 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
949 // TODO throw again the new rename dialog
951 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
953 if (result
.isSslRecoverableException()) {
954 // TODO show the SSL warning dialog
960 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
961 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
962 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
964 if (!result
.isSuccess()) {
965 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
966 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
967 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
968 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
972 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
976 if (mFile
.isDown()) {
980 setButtonsForRemote();
984 if (operation
.transferWasRequested()) {
985 setButtonsForTransferring();
986 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
987 // checking the service to see if the file is downloading results in FALSE
989 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
991 if (mFile
.isDown()) {
995 setButtonsForRemote();
1002 public void listenForTransferProgress() {
1003 if (mProgressListener
!= null
) {
1004 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1005 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1007 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1008 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1014 public void leaveTransferProgress() {
1015 if (mProgressListener
!= null
) {
1016 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
1017 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1019 if (mContainerActivity
.getFileUploaderBinder() != null
) {
1020 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
1028 * Helper class responsible for updating the progress bar shown for file uploading or downloading
1030 * @author David A. Velasco
1032 private class ProgressListener
implements OnDatatransferProgressListener
{
1033 int mLastPercent
= 0;
1034 WeakReference
<ProgressBar
> mProgressBar
= null
;
1036 ProgressListener(ProgressBar progressBar
) {
1037 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
1041 public void onTransferProgress(long progressRate
) {
1042 // old method, nothing here
1046 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
1047 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
1048 if (percent
!= mLastPercent
) {
1049 ProgressBar pb
= mProgressBar
.get();
1051 pb
.setProgress(percent
);
1052 pb
.postInvalidate();
1055 mLastPercent
= percent
;