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 eu
.alefzero
.owncloud
.ui
.fragment
;
21 import java
.io
.IOException
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import org
.apache
.commons
.httpclient
.HttpException
;
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
.DavMethodBase
;
36 import org
.apache
.jackrabbit
.webdav
.client
.methods
.DeleteMethod
;
37 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
38 import org
.json
.JSONException
;
39 import org
.json
.JSONObject
;
41 import android
.accounts
.Account
;
42 import android
.accounts
.AccountManager
;
43 import android
.annotation
.SuppressLint
;
44 import android
.app
.Activity
;
45 import android
.content
.ActivityNotFoundException
;
46 import android
.content
.BroadcastReceiver
;
47 import android
.content
.Context
;
48 import android
.content
.Intent
;
49 import android
.content
.IntentFilter
;
50 import android
.content
.res
.Resources
.NotFoundException
;
51 import android
.graphics
.Bitmap
;
52 import android
.graphics
.BitmapFactory
;
53 import android
.graphics
.BitmapFactory
.Options
;
54 import android
.graphics
.Point
;
55 import android
.net
.Uri
;
56 import android
.os
.AsyncTask
;
57 import android
.os
.Bundle
;
58 import android
.os
.Handler
;
59 import android
.support
.v4
.app
.FragmentTransaction
;
60 import android
.util
.Log
;
61 import android
.view
.Display
;
62 import android
.view
.LayoutInflater
;
63 import android
.view
.View
;
64 import android
.view
.View
.OnClickListener
;
65 import android
.view
.ViewGroup
;
66 import android
.view
.WindowManager
.LayoutParams
;
67 import android
.webkit
.MimeTypeMap
;
68 import android
.widget
.Button
;
69 import android
.widget
.CheckBox
;
70 import android
.widget
.ImageView
;
71 import android
.widget
.TextView
;
72 import android
.widget
.Toast
;
74 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
75 import com
.actionbarsherlock
.app
.SherlockFragment
;
77 import eu
.alefzero
.owncloud
.AccountUtils
;
78 import eu
.alefzero
.owncloud
.DisplayUtils
;
79 import eu
.alefzero
.owncloud
.R
;
80 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
81 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
82 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
83 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
84 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
85 import eu
.alefzero
.owncloud
.ui
.activity
.FileDetailActivity
;
86 import eu
.alefzero
.owncloud
.ui
.activity
.FileDisplayActivity
;
87 import eu
.alefzero
.owncloud
.utils
.OwnCloudVersion
;
88 import eu
.alefzero
.webdav
.WebdavClient
;
89 import eu
.alefzero
.webdav
.WebdavUtils
;
92 * This Fragment is used to display the details about a file.
94 * @author Bartek Przybylski
97 public class FileDetailFragment
extends SherlockFragment
implements
98 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
100 public static final String EXTRA_FILE
= "FILE";
101 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
103 private FileDetailFragment
.ContainerActivity mContainerActivity
;
107 private OCFile mFile
;
108 private Account mAccount
;
109 private ImageView mPreview
;
111 private DownloadFinishReceiver mDownloadFinishReceiver
;
112 private UploadFinishReceiver mUploadFinishReceiver
;
114 private static final String TAG
= "FileDetailFragment";
115 public static final String FTAG
= "FileDetails";
116 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
120 * Creates an empty details fragment.
122 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
124 public FileDetailFragment() {
127 mLayout
= R
.layout
.file_details_empty
;
132 * Creates a details fragment.
134 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
136 * @param fileToDetail An {@link OCFile} to show in the fragment
137 * @param ocAccount An ownCloud account; needed to start downloads
139 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
140 mFile
= fileToDetail
;
141 mAccount
= ocAccount
;
142 mLayout
= R
.layout
.file_details_empty
;
144 if(fileToDetail
!= null
&& ocAccount
!= null
) {
145 mLayout
= R
.layout
.file_details_fragment
;
154 public void onAttach(Activity activity
) {
155 super.onAttach(activity
);
157 mContainerActivity
= (ContainerActivity
) activity
;
158 } catch (ClassCastException e
) {
159 throw new ClassCastException(activity
.toString() + " must implement FileListFragment.ContainerActivity");
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
);
175 view
= inflater
.inflate(mLayout
, container
, false
);
178 if (mLayout
== R
.layout
.file_details_fragment
) {
179 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
180 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
181 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
182 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
183 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
184 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
185 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
194 public void onSaveInstanceState(Bundle outState
) {
195 Log
.i(getClass().toString(), "onSaveInstanceState() start");
196 super.onSaveInstanceState(outState
);
197 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
198 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
199 Log
.i(getClass().toString(), "onSaveInstanceState() end");
204 public void onResume() {
207 mDownloadFinishReceiver
= new DownloadFinishReceiver();
208 IntentFilter filter
= new IntentFilter(
209 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
210 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
212 mUploadFinishReceiver
= new UploadFinishReceiver();
213 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
214 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
216 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
220 public void onPause() {
223 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
224 mDownloadFinishReceiver
= null
;
226 getActivity().unregisterReceiver(mUploadFinishReceiver
);
227 mUploadFinishReceiver
= null
;
229 if (mPreview
!= null
) {
235 public View
getView() {
236 return super.getView() == null ? mView
: super.getView();
242 public void onClick(View v
) {
244 case R
.id
.fdDownloadBtn
: {
245 Intent i
= new Intent(getActivity(), FileDownloader
.class);
246 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
247 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
248 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getRemotePath());
249 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
252 setButtonsForTransferring();
254 getActivity().startService(i
);
255 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
258 case R
.id
.fdKeepInSync
: {
259 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
260 mFile
.setKeepInSync(cb
.isChecked());
261 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
262 fdsm
.saveFile(mFile
);
263 if (mFile
.keepInSync()) {
264 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
266 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
270 case R
.id
.fdRenameBtn
: {
271 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
272 dialog
.show(getFragmentManager(), "nameeditdialog");
273 dialog
.setOnDismissListener(this);
276 case R
.id
.fdRemoveBtn
: {
277 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
278 R
.string
.confirmation_remove_alert
,
279 new String
[]{mFile
.getFileName()},
280 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
281 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
282 R
.string
.common_cancel
);
283 confDialog
.setOnConfirmationListener(this);
284 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
287 case R
.id
.fdOpenBtn
: {
288 String storagePath
= mFile
.getStoragePath();
289 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
291 Intent i
= new Intent(Intent
.ACTION_VIEW
);
292 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
293 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
296 } catch (Throwable t
) {
297 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
298 boolean toastIt
= true
;
299 String mimeType
= "";
301 Intent i
= new Intent(Intent
.ACTION_VIEW
);
302 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
303 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
304 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
305 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
310 } catch (IndexOutOfBoundsException e
) {
311 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
313 } catch (ActivityNotFoundException e
) {
314 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
316 } catch (Throwable th
) {
317 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
321 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
329 Log
.e(TAG
, "Incorrect view clicked!");
332 /* else if (v.getId() == R.id.fdShareBtn) {
333 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
340 public void onConfirmation(String callerTag
) {
341 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
342 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
343 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
344 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
345 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
346 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
352 public void onNeutral(String callerTag
) {
353 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
355 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
357 mFile
.setStoragePath(null
);
358 fdsm
.saveFile(mFile
);
359 updateFileDetails(mFile
, mAccount
);
364 public void onCancel(String callerTag
) {
365 Log
.d(TAG
, "REMOVAL CANCELED");
370 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
372 * @return True when the fragment was created with the empty layout.
374 public boolean isEmpty() {
375 return mLayout
== R
.layout
.file_details_empty
;
380 * Can be used to get the file that is currently being displayed.
381 * @return The file on the screen.
383 public OCFile
getDisplayedFile(){
388 * Use this method to signal this Activity that it shall update its view.
390 * @param file : An {@link OCFile}
392 public void updateFileDetails(OCFile file
, Account ocAccount
) {
394 mAccount
= ocAccount
;
400 * Updates the view with all relevant details about that file.
402 public void updateFileDetails() {
404 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
407 setFilename(mFile
.getFileName());
408 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
410 setFilesize(mFile
.getFileLength());
411 if(ocVersionSupportsTimeCreated()){
412 setTimeCreated(mFile
.getCreationTimestamp());
415 setTimeModified(mFile
.getModificationTimestamp());
417 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
418 cb
.setChecked(mFile
.keepInSync());
420 // configure UI for depending upon local state of the file
421 if (FileDownloader
.isDownloading(mAccount
, mFile
.getRemotePath()) || FileUploader
.isUploading(mAccount
, mFile
.getRemotePath())) {
422 setButtonsForTransferring();
424 } else if (mFile
.isDown()) {
426 if (mFile
.getMimetype().startsWith("image/")) {
427 BitmapLoader bl
= new BitmapLoader();
428 bl
.execute(new String
[]{mFile
.getStoragePath()});
434 setButtonsForRemote();
441 * Updates the filename in view
442 * @param filename to set
444 private void setFilename(String filename
) {
445 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
447 tv
.setText(filename
);
451 * Updates the MIME type in view
452 * @param mimetype to set
454 private void setFiletype(String mimetype
) {
455 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
457 tv
.setText(mimetype
);
461 * Updates the file size in view
462 * @param filesize in bytes to set
464 private void setFilesize(long filesize
) {
465 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
467 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
471 * Updates the time that the file was created in view
472 * @param milliseconds Unix time to set
474 private void setTimeCreated(long milliseconds
){
475 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
476 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
478 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
479 tv
.setVisibility(View
.VISIBLE
);
480 tvLabel
.setVisibility(View
.VISIBLE
);
485 * Updates the time that the file was last modified
486 * @param milliseconds Unix time to set
488 private void setTimeModified(long milliseconds
){
489 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
491 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
496 * Enables or disables buttons for a file being downloaded
498 private void setButtonsForTransferring() {
500 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
501 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
502 downloadButton
.setEnabled(false
); // TODO replace it with a 'cancel download' button
504 // let's protect the user from himself ;)
505 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
506 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
507 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
512 * Enables or disables buttons for a file locally available
514 private void setButtonsForDown() {
516 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
517 //downloadButton.setText(R.string.filedetails_redownload); // ugly
518 downloadButton
.setEnabled(true
);
520 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
521 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
522 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
527 * Enables or disables buttons for a file not locally available
529 private void setButtonsForRemote() {
531 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
532 //downloadButton.setText(R.string.filedetails_download); // unnecessary
533 downloadButton
.setEnabled(true
);
535 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
536 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
537 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
543 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
544 * the time that the file was created. There is a chance that this will
545 * be fixed in future versions. Use this method to check if this version of
546 * ownCloud has this fix.
547 * @return True, if ownCloud the ownCloud version is supporting creation time
549 private boolean ocVersionSupportsTimeCreated(){
550 /*if(mAccount != null){
551 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
552 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
553 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
554 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
563 * Interface to implement by any Activity that includes some instance of FileDetailFragment
565 * @author David A. Velasco
567 public interface ContainerActivity
{
570 * Callback method invoked when the detail fragment wants to notice its container
571 * activity about a relevant state the file shown by the fragment.
573 * Added to notify to FileDisplayActivity about the need of refresh the files list.
575 * Currently called when:
576 * - a download is started;
577 * - a rename is completed;
578 * - a deletion is completed;
579 * - the 'inSync' flag is changed;
581 public void onFileStateChanged();
587 * Once the file download has finished -> update view
588 * @author Bartek Przybylski
590 private class DownloadFinishReceiver
extends BroadcastReceiver
{
592 public void onReceive(Context context
, Intent intent
) {
593 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
595 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
596 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
597 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
598 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
599 if (downloadWasFine
) {
600 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
602 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
610 * Once the file upload has finished -> update view
612 * Being notified about the finish of an upload is necessary for the next sequence:
613 * 1. Upload a big file.
614 * 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
615 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
616 * 3. Click the file in the list to see its details.
617 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
619 private class UploadFinishReceiver
extends BroadcastReceiver
{
621 public void onReceive(Context context
, Intent intent
) {
622 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
624 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
625 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
626 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
627 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
629 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
630 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
632 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
639 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
640 private class ShareRunnable
implements Runnable
{
641 private String mPath
;
643 public ShareRunnable(String path
) {
648 AccountManager am
= AccountManager
.get(getActivity());
649 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
650 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
651 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
653 Log
.d("share", "sharing for version " + ocv
.toString());
655 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
656 String APPS_PATH
= "/apps/files_sharing/";
657 String SHARE_PATH
= "ajax/share.php";
659 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
661 final String WEBDAV_SCRIPT
= "webdav.php";
662 final String WEBDAV_FILES_LOCATION
= "/files/";
664 WebdavClient wc
= new WebdavClient();
665 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
666 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
668 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
669 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
671 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
673 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
674 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
675 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
676 Log
.d("share", mPath
+"");
677 formparams
.add(new BasicNameValuePair("sources",mPath
));
678 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
679 formparams
.add(new BasicNameValuePair("permissions", "0"));
680 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
684 PropFindMethod find
= new PropFindMethod(url
+"/");
685 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
686 Log
.d("sharer", ""+ url
+"/");
687 wc
.setCredentials(account
.name
.substring(0, account
.name
.lastIndexOf('@')), am
.getPassword(account
));
689 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
690 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
693 int status2
= wc
.executeMethod(find
);
695 Log
.d("sharer", "propstatus "+status2
);
697 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
698 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
700 status2
= wc
.executeMethod(get
);
702 Log
.d("sharer", "getstatus "+status2
);
703 Log
.d("sharer", "" + get
.getResponseBodyAsString());
705 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
706 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
709 status
= wc
.executeMethod(post
);
710 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
711 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
713 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
714 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
716 String resp
= post
.getResponseBodyAsString();
717 Log
.d("share", ""+post
.getURI().toString());
718 Log
.d("share", "returned status " + status
);
719 Log
.d("share", " " +resp
);
721 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
725 JSONObject jsonObject
= new JSONObject (resp
);
726 String jsonStatus
= jsonObject
.getString("status");
727 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
729 String token
= jsonObject
.getString("data");
730 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
731 Log
.d("Actions:shareFile ok", "url: " + uri
);
733 } catch (HttpException e
) {
734 // TODO Auto-generated catch block
736 } catch (IOException e
) {
737 // TODO Auto-generated catch block
739 } catch (JSONException e
) {
740 // TODO Auto-generated catch block
742 } catch (Exception e
) {
743 // TODO Auto-generated catch block
747 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
753 public void onDismiss(EditNameFragment dialog
) {
754 if (dialog
instanceof EditNameFragment
) {
755 if (((EditNameFragment
)dialog
).getResult()) {
756 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
757 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
758 if (!newFilename
.equals(mFile
.getFileName())) {
759 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
760 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
761 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
762 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
763 newFile
.setFileId(mFile
.getFileId());
764 newFile
.setFileLength(mFile
.getFileLength());
765 newFile
.setKeepInSync(mFile
.keepInSync());
766 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
767 newFile
.setMimetype(mFile
.getMimetype());
768 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
769 newFile
.setParentId(mFile
.getParentId());
770 boolean localRenameFails
= false
;
771 if (mFile
.isDown()) {
772 File f
= new File(mFile
.getStoragePath());
773 Log
.e(TAG
, f
.getAbsolutePath());
774 localRenameFails
= !(f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)));
775 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
776 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
779 if (localRenameFails
) {
780 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
784 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
785 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
786 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
793 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
798 private class RenameRunnable
implements Runnable
{
804 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
812 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
813 wc
.allowSelfsignedCertificates();
814 AccountManager am
= AccountManager
.get(getSherlockActivity());
815 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
816 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
817 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
818 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
820 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
821 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
822 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
824 boolean success
= false
;
826 int status
= wc
.executeMethod(move
);
827 success
= move
.succeeded();
828 Log
.d(TAG
, "Move returned status: " + status
);
830 } catch (HttpException e
) {
831 Log
.e(TAG
, "HTTP Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
833 } catch (IOException e
) {
834 Log
.e(TAG
, "I/O Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
836 } catch (Exception e
) {
837 Log
.e(TAG
, "Unexpected exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
841 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
842 fdsm
.removeFile(mOld
);
845 mHandler
.post(new Runnable() {
848 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
849 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
850 updateFileDetails(mFile
, mAccount
);
851 mContainerActivity
.onFileStateChanged();
856 mHandler
.post(new Runnable() {
859 // undo the local rename
861 File f
= new File(mNew
.getStoragePath());
862 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
863 // the local rename undoing failed; last chance: save the new local storage path in the old file
864 mFile
.setStoragePath(mNew
.getStoragePath());
865 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
866 fdsm
.saveFile(mFile
);
869 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
870 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
872 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
875 } catch (NotFoundException e
) {
882 private class LocalMoveMethod
extends DavMethodBase
{
884 public LocalMoveMethod(String uri
, String dest
) {
886 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
890 public String
getName() {
895 protected boolean isSuccess(int status
) {
896 return status
== 201 || status
== 204;
902 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
904 private String mNewFilename
;
905 private boolean mResult
;
906 private FileDetailFragment mListener
;
908 static public EditNameFragment
newInstance(String filename
) {
909 EditNameFragment f
= new EditNameFragment();
910 Bundle args
= new Bundle();
911 args
.putString("filename", filename
);
912 f
.setArguments(args
);
917 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
918 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
920 String currentName
= getArguments().getString("filename");
921 if (currentName
== null
)
924 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
925 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
926 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
927 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
928 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
935 public void onClick(View view
) {
936 switch (view
.getId()) {
938 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
941 case R
.id
.cancel
: { // fallthought
943 mListener
.onDismiss(this);
948 void setOnDismissListener(FileDetailFragment listener
) {
949 mListener
= listener
;
952 public String
getNewFilename() {
956 // true if user click ok
957 public boolean getResult() {
963 private class RemoveRunnable
implements Runnable
{
966 OCFile mFileToRemove
;
969 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
970 mFileToRemove
= fileToRemove
;
976 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
977 wc
.allowSelfsignedCertificates();
978 AccountManager am
= AccountManager
.get(getSherlockActivity());
979 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
980 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
981 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
982 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
984 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
986 boolean success
= false
;
989 status
= wc
.executeMethod(delete
);
990 success
= (delete
.succeeded());
991 Log
.d(TAG
, "Delete: returned status " + status
);
993 } catch (HttpException e
) {
994 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
996 } catch (IOException e
) {
997 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
999 } catch (Exception e
) {
1000 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1004 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1005 fdsm
.removeFile(mFileToRemove
);
1006 mHandler
.post(new Runnable() {
1009 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1010 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1012 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1014 if (inDisplayActivity
) {
1016 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1017 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1018 transaction
.commit();
1019 mContainerActivity
.onFileStateChanged();
1022 getActivity().finish();
1025 } catch (NotFoundException e
) {
1026 e
.printStackTrace();
1032 mHandler
.post(new Runnable() {
1035 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1036 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1038 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1041 } catch (NotFoundException e
) {
1042 e
.printStackTrace();
1051 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1052 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1054 protected Bitmap
doInBackground(String
... params
) {
1055 Bitmap result
= null
;
1056 if (params
.length
!= 1) return result
;
1057 String storagePath
= params
[0];
1060 BitmapFactory
.Options options
= new Options();
1061 options
.inScaled
= true
;
1062 options
.inPurgeable
= true
;
1063 options
.inJustDecodeBounds
= true
;
1064 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1065 options
.inPreferQualityOverSpeed
= false
;
1067 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1068 options
.inMutable
= false
;
1071 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1072 options
.inJustDecodeBounds
= false
;
1074 int width
= options
.outWidth
;
1075 int height
= options
.outHeight
;
1077 if (width
>= 2048 || height
>= 2048) {
1078 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1079 options
.inSampleSize
= scale
;
1081 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1082 Point size
= new Point();
1084 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1085 display
.getSize(size
);
1086 screenwidth
= size
.x
;
1088 screenwidth
= display
.getWidth();
1091 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1093 if (width
> screenwidth
) {
1094 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1095 options
.inSampleSize
= scale
;
1098 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1100 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1102 } catch (OutOfMemoryError e
) {
1104 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1106 } catch (NoSuchFieldError e
) {
1108 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1110 } catch (Throwable t
) {
1112 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1117 protected void onPostExecute(Bitmap result
) {
1118 if (result
!= null
&& mPreview
!= null
) {
1119 mPreview
.setImageBitmap(result
);