1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.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
.JSONObject
;
40 import android
.accounts
.Account
;
41 import android
.accounts
.AccountManager
;
42 import android
.annotation
.SuppressLint
;
43 import android
.app
.Activity
;
44 import android
.content
.ActivityNotFoundException
;
45 import android
.content
.BroadcastReceiver
;
46 import android
.content
.Context
;
47 import android
.content
.Intent
;
48 import android
.content
.IntentFilter
;
49 import android
.content
.res
.Resources
.NotFoundException
;
50 import android
.graphics
.Bitmap
;
51 import android
.graphics
.BitmapFactory
;
52 import android
.graphics
.BitmapFactory
.Options
;
53 import android
.graphics
.Point
;
54 import android
.net
.Uri
;
55 import android
.os
.AsyncTask
;
56 import android
.os
.Bundle
;
57 import android
.os
.Handler
;
58 import android
.support
.v4
.app
.FragmentTransaction
;
59 import android
.util
.Log
;
60 import android
.view
.Display
;
61 import android
.view
.LayoutInflater
;
62 import android
.view
.View
;
63 import android
.view
.View
.OnClickListener
;
64 import android
.view
.ViewGroup
;
65 import android
.view
.WindowManager
.LayoutParams
;
66 import android
.webkit
.MimeTypeMap
;
67 import android
.widget
.Button
;
68 import android
.widget
.CheckBox
;
69 import android
.widget
.ImageView
;
70 import android
.widget
.TextView
;
71 import android
.widget
.Toast
;
73 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
74 import com
.actionbarsherlock
.app
.SherlockFragment
;
75 import com
.owncloud
.android
.AccountUtils
;
76 import com
.owncloud
.android
.DisplayUtils
;
77 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
78 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
79 import com
.owncloud
.android
.datamodel
.OCFile
;
80 import com
.owncloud
.android
.files
.services
.FileDownloader
;
81 import com
.owncloud
.android
.files
.services
.FileUploader
;
82 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
83 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
84 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
85 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
87 import com
.owncloud
.android
.R
;
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)
269 Intent intent = new Intent(getActivity().getApplicationContext(),
270 FileObserverService.class);
271 intent.putExtra(FileObserverService.KEY_FILE_CMD,
273 FileObserverService.CMD_ADD_OBSERVED_FILE:
274 FileObserverService.CMD_DEL_OBSERVED_FILE));
275 intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
276 getActivity().startService(intent);
280 case R
.id
.fdRenameBtn
: {
281 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
282 dialog
.show(getFragmentManager(), "nameeditdialog");
283 dialog
.setOnDismissListener(this);
286 case R
.id
.fdRemoveBtn
: {
287 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
288 R
.string
.confirmation_remove_alert
,
289 new String
[]{mFile
.getFileName()},
290 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
291 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
292 R
.string
.common_cancel
);
293 confDialog
.setOnConfirmationListener(this);
294 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
297 case R
.id
.fdOpenBtn
: {
298 String storagePath
= mFile
.getStoragePath();
299 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
301 Intent i
= new Intent(Intent
.ACTION_VIEW
);
302 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
303 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
306 } catch (Throwable t
) {
307 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
308 boolean toastIt
= true
;
309 String mimeType
= "";
311 Intent i
= new Intent(Intent
.ACTION_VIEW
);
312 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
313 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
314 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
315 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
320 } catch (IndexOutOfBoundsException e
) {
321 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
323 } catch (ActivityNotFoundException e
) {
324 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
326 } catch (Throwable th
) {
327 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
331 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
339 Log
.e(TAG
, "Incorrect view clicked!");
342 /* else if (v.getId() == R.id.fdShareBtn) {
343 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
350 public void onConfirmation(String callerTag
) {
351 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
352 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
353 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
354 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
355 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
356 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
362 public void onNeutral(String callerTag
) {
363 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
365 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
367 mFile
.setStoragePath(null
);
368 fdsm
.saveFile(mFile
);
369 updateFileDetails(mFile
, mAccount
);
374 public void onCancel(String callerTag
) {
375 Log
.d(TAG
, "REMOVAL CANCELED");
380 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
382 * @return True when the fragment was created with the empty layout.
384 public boolean isEmpty() {
385 return mLayout
== R
.layout
.file_details_empty
;
390 * Can be used to get the file that is currently being displayed.
391 * @return The file on the screen.
393 public OCFile
getDisplayedFile(){
398 * Use this method to signal this Activity that it shall update its view.
400 * @param file : An {@link OCFile}
402 public void updateFileDetails(OCFile file
, Account ocAccount
) {
404 mAccount
= ocAccount
;
410 * Updates the view with all relevant details about that file.
412 public void updateFileDetails() {
414 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
417 setFilename(mFile
.getFileName());
418 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
420 setFilesize(mFile
.getFileLength());
421 if(ocVersionSupportsTimeCreated()){
422 setTimeCreated(mFile
.getCreationTimestamp());
425 setTimeModified(mFile
.getModificationTimestamp());
427 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
428 cb
.setChecked(mFile
.keepInSync());
430 // configure UI for depending upon local state of the file
431 if (FileDownloader
.isDownloading(mAccount
, mFile
.getRemotePath()) || FileUploader
.isUploading(mAccount
, mFile
.getRemotePath())) {
432 setButtonsForTransferring();
434 } else if (mFile
.isDown()) {
436 if (mFile
.getMimetype().startsWith("image/")) {
437 BitmapLoader bl
= new BitmapLoader();
438 bl
.execute(new String
[]{mFile
.getStoragePath()});
444 setButtonsForRemote();
451 * Updates the filename in view
452 * @param filename to set
454 private void setFilename(String filename
) {
455 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
457 tv
.setText(filename
);
461 * Updates the MIME type in view
462 * @param mimetype to set
464 private void setFiletype(String mimetype
) {
465 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
467 tv
.setText(mimetype
);
471 * Updates the file size in view
472 * @param filesize in bytes to set
474 private void setFilesize(long filesize
) {
475 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
477 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
481 * Updates the time that the file was created in view
482 * @param milliseconds Unix time to set
484 private void setTimeCreated(long milliseconds
){
485 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
486 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
488 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
489 tv
.setVisibility(View
.VISIBLE
);
490 tvLabel
.setVisibility(View
.VISIBLE
);
495 * Updates the time that the file was last modified
496 * @param milliseconds Unix time to set
498 private void setTimeModified(long milliseconds
){
499 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
501 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
506 * Enables or disables buttons for a file being downloaded
508 private void setButtonsForTransferring() {
510 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
511 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
512 downloadButton
.setEnabled(false
); // TODO replace it with a 'cancel download' button
514 // let's protect the user from himself ;)
515 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
516 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
517 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
522 * Enables or disables buttons for a file locally available
524 private void setButtonsForDown() {
526 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
527 //downloadButton.setText(R.string.filedetails_redownload); // ugly
528 downloadButton
.setEnabled(true
);
530 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
531 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
532 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
537 * Enables or disables buttons for a file not locally available
539 private void setButtonsForRemote() {
541 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
542 //downloadButton.setText(R.string.filedetails_download); // unnecessary
543 downloadButton
.setEnabled(true
);
545 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
546 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
547 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
553 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
554 * the time that the file was created. There is a chance that this will
555 * be fixed in future versions. Use this method to check if this version of
556 * ownCloud has this fix.
557 * @return True, if ownCloud the ownCloud version is supporting creation time
559 private boolean ocVersionSupportsTimeCreated(){
560 /*if(mAccount != null){
561 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
562 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
563 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
564 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
573 * Interface to implement by any Activity that includes some instance of FileDetailFragment
575 * @author David A. Velasco
577 public interface ContainerActivity
{
580 * Callback method invoked when the detail fragment wants to notice its container
581 * activity about a relevant state the file shown by the fragment.
583 * Added to notify to FileDisplayActivity about the need of refresh the files list.
585 * Currently called when:
586 * - a download is started;
587 * - a rename is completed;
588 * - a deletion is completed;
589 * - the 'inSync' flag is changed;
591 public void onFileStateChanged();
597 * Once the file download has finished -> update view
598 * @author Bartek Przybylski
600 private class DownloadFinishReceiver
extends BroadcastReceiver
{
602 public void onReceive(Context context
, Intent intent
) {
603 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
605 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
606 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
607 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
608 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
609 if (downloadWasFine
) {
610 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
612 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
620 * Once the file upload has finished -> update view
622 * Being notified about the finish of an upload is necessary for the next sequence:
623 * 1. Upload a big file.
624 * 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
625 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
626 * 3. Click the file in the list to see its details.
627 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
629 private class UploadFinishReceiver
extends BroadcastReceiver
{
631 public void onReceive(Context context
, Intent intent
) {
632 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
634 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
635 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
636 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
637 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
639 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
640 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
642 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
649 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
650 @SuppressWarnings("unused")
651 private class ShareRunnable
implements Runnable
{
652 private String mPath
;
654 public ShareRunnable(String path
) {
659 AccountManager am
= AccountManager
.get(getActivity());
660 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
661 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
662 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
664 Log
.d("share", "sharing for version " + ocv
.toString());
666 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
667 String APPS_PATH
= "/apps/files_sharing/";
668 String SHARE_PATH
= "ajax/share.php";
670 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
672 final String WEBDAV_SCRIPT
= "webdav.php";
673 final String WEBDAV_FILES_LOCATION
= "/files/";
675 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
676 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
677 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
679 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
680 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
682 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
684 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
685 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
686 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
687 Log
.d("share", mPath
+"");
688 formparams
.add(new BasicNameValuePair("sources",mPath
));
689 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
690 formparams
.add(new BasicNameValuePair("permissions", "0"));
691 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
695 PropFindMethod find
= new PropFindMethod(url
+"/");
696 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
697 Log
.d("sharer", ""+ url
+"/");
699 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
700 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
703 int status2
= wc
.executeMethod(find
);
705 Log
.d("sharer", "propstatus "+status2
);
707 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
708 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
710 status2
= wc
.executeMethod(get
);
712 Log
.d("sharer", "getstatus "+status2
);
713 Log
.d("sharer", "" + get
.getResponseBodyAsString());
715 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
716 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
719 status
= wc
.executeMethod(post
);
720 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
721 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
723 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
724 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
726 String resp
= post
.getResponseBodyAsString();
727 Log
.d("share", ""+post
.getURI().toString());
728 Log
.d("share", "returned status " + status
);
729 Log
.d("share", " " +resp
);
731 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
735 JSONObject jsonObject
= new JSONObject (resp
);
736 String jsonStatus
= jsonObject
.getString("status");
737 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
739 String token
= jsonObject
.getString("data");
740 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
741 Log
.d("Actions:shareFile ok", "url: " + uri
);
743 } catch (Exception e
) {
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
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
813 AccountManager am
= AccountManager
.get(getSherlockActivity());
814 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
815 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
816 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
817 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
819 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
820 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
821 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
823 boolean success
= false
;
825 int status
= wc
.executeMethod(move
);
826 success
= move
.succeeded();
827 move
.getResponseBodyAsString(); // exhaust response, although not interesting
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
);
840 move
.releaseConnection();
844 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
845 fdsm
.removeFile(mOld
, false
);
848 mHandler
.post(new Runnable() {
851 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
852 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
853 updateFileDetails(mFile
, mAccount
);
854 mContainerActivity
.onFileStateChanged();
859 mHandler
.post(new Runnable() {
862 // undo the local rename
864 File f
= new File(mNew
.getStoragePath());
865 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
866 // the local rename undoing failed; last chance: save the new local storage path in the old file
867 mFile
.setStoragePath(mNew
.getStoragePath());
868 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
869 fdsm
.saveFile(mFile
);
872 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
873 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
875 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
878 } catch (NotFoundException e
) {
885 private class LocalMoveMethod
extends DavMethodBase
{
887 public LocalMoveMethod(String uri
, String dest
) {
889 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
893 public String
getName() {
898 protected boolean isSuccess(int status
) {
899 return status
== 201 || status
== 204;
905 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
907 private String mNewFilename
;
908 private boolean mResult
;
909 private FileDetailFragment mListener
;
911 static public EditNameFragment
newInstance(String filename
) {
912 EditNameFragment f
= new EditNameFragment();
913 Bundle args
= new Bundle();
914 args
.putString("filename", filename
);
915 f
.setArguments(args
);
920 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
921 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
923 String currentName
= getArguments().getString("filename");
924 if (currentName
== null
)
927 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
928 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
929 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
930 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
931 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
938 public void onClick(View view
) {
939 switch (view
.getId()) {
941 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
944 case R
.id
.cancel
: { // fallthought
946 mListener
.onDismiss(this);
951 void setOnDismissListener(FileDetailFragment listener
) {
952 mListener
= listener
;
955 public String
getNewFilename() {
959 // true if user click ok
960 public boolean getResult() {
966 private class RemoveRunnable
implements Runnable
{
969 OCFile mFileToRemove
;
972 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
973 mFileToRemove
= fileToRemove
;
979 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
980 AccountManager am
= AccountManager
.get(getSherlockActivity());
981 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
982 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
983 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
984 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
986 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
988 boolean success
= false
;
991 status
= wc
.executeMethod(delete
);
992 success
= (delete
.succeeded());
993 delete
.getResponseBodyAsString(); // exhaust the response, although not interesting
994 Log
.d(TAG
, "Delete: returned status " + status
);
996 } catch (HttpException e
) {
997 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
999 } catch (IOException e
) {
1000 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1002 } catch (Exception e
) {
1003 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1006 delete
.releaseConnection();
1010 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1011 fdsm
.removeFile(mFileToRemove
, true
);
1012 mHandler
.post(new Runnable() {
1015 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1016 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1018 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1020 if (inDisplayActivity
) {
1022 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1023 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1024 transaction
.commit();
1025 mContainerActivity
.onFileStateChanged();
1028 getActivity().finish();
1031 } catch (NotFoundException e
) {
1032 e
.printStackTrace();
1038 mHandler
.post(new Runnable() {
1041 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1042 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1044 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1047 } catch (NotFoundException e
) {
1048 e
.printStackTrace();
1057 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1058 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1060 protected Bitmap
doInBackground(String
... params
) {
1061 Bitmap result
= null
;
1062 if (params
.length
!= 1) return result
;
1063 String storagePath
= params
[0];
1066 BitmapFactory
.Options options
= new Options();
1067 options
.inScaled
= true
;
1068 options
.inPurgeable
= true
;
1069 options
.inJustDecodeBounds
= true
;
1070 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1071 options
.inPreferQualityOverSpeed
= false
;
1073 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1074 options
.inMutable
= false
;
1077 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1078 options
.inJustDecodeBounds
= false
;
1080 int width
= options
.outWidth
;
1081 int height
= options
.outHeight
;
1083 if (width
>= 2048 || height
>= 2048) {
1084 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1085 options
.inSampleSize
= scale
;
1087 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1088 Point size
= new Point();
1090 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1091 display
.getSize(size
);
1092 screenwidth
= size
.x
;
1094 screenwidth
= display
.getWidth();
1097 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1099 if (width
> screenwidth
) {
1100 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1101 options
.inSampleSize
= scale
;
1104 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1106 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1108 } catch (OutOfMemoryError e
) {
1110 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1112 } catch (NoSuchFieldError e
) {
1114 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1116 } catch (Throwable t
) {
1118 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1123 protected void onPostExecute(Bitmap result
) {
1124 if (result
!= null
&& mPreview
!= null
) {
1125 mPreview
.setImageBitmap(result
);