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
.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
;
76 import com
.owncloud
.android
.AccountUtils
;
77 import com
.owncloud
.android
.DisplayUtils
;
78 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
79 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
80 import com
.owncloud
.android
.datamodel
.OCFile
;
81 import com
.owncloud
.android
.files
.services
.FileDownloader
;
82 import com
.owncloud
.android
.files
.services
.FileObserverService
;
83 import com
.owncloud
.android
.files
.services
.FileUploader
;
84 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
85 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
86 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
87 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
89 import com
.owncloud
.android
.R
;
90 import eu
.alefzero
.webdav
.WebdavClient
;
91 import eu
.alefzero
.webdav
.WebdavUtils
;
94 * This Fragment is used to display the details about a file.
96 * @author Bartek Przybylski
99 public class FileDetailFragment
extends SherlockFragment
implements
100 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
102 public static final String EXTRA_FILE
= "FILE";
103 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
105 private FileDetailFragment
.ContainerActivity mContainerActivity
;
109 private OCFile mFile
;
110 private Account mAccount
;
111 private ImageView mPreview
;
113 private DownloadFinishReceiver mDownloadFinishReceiver
;
114 private UploadFinishReceiver mUploadFinishReceiver
;
116 private static final String TAG
= "FileDetailFragment";
117 public static final String FTAG
= "FileDetails";
118 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
122 * Creates an empty details fragment.
124 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
126 public FileDetailFragment() {
129 mLayout
= R
.layout
.file_details_empty
;
134 * Creates a details fragment.
136 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
138 * @param fileToDetail An {@link OCFile} to show in the fragment
139 * @param ocAccount An ownCloud account; needed to start downloads
141 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
142 mFile
= fileToDetail
;
143 mAccount
= ocAccount
;
144 mLayout
= R
.layout
.file_details_empty
;
146 if(fileToDetail
!= null
&& ocAccount
!= null
) {
147 mLayout
= R
.layout
.file_details_fragment
;
156 public void onAttach(Activity activity
) {
157 super.onAttach(activity
);
159 mContainerActivity
= (ContainerActivity
) activity
;
160 } catch (ClassCastException e
) {
161 throw new ClassCastException(activity
.toString() + " must implement FileListFragment.ContainerActivity");
167 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
168 Bundle savedInstanceState
) {
169 super.onCreateView(inflater
, container
, savedInstanceState
);
171 if (savedInstanceState
!= null
) {
172 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
173 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
177 view
= inflater
.inflate(mLayout
, container
, false
);
180 if (mLayout
== R
.layout
.file_details_fragment
) {
181 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
182 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
183 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
184 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
185 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
186 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
187 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
196 public void onSaveInstanceState(Bundle outState
) {
197 Log
.i(getClass().toString(), "onSaveInstanceState() start");
198 super.onSaveInstanceState(outState
);
199 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
200 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
201 Log
.i(getClass().toString(), "onSaveInstanceState() end");
206 public void onResume() {
209 mDownloadFinishReceiver
= new DownloadFinishReceiver();
210 IntentFilter filter
= new IntentFilter(
211 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
212 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
214 mUploadFinishReceiver
= new UploadFinishReceiver();
215 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
216 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
218 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
222 public void onPause() {
225 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
226 mDownloadFinishReceiver
= null
;
228 getActivity().unregisterReceiver(mUploadFinishReceiver
);
229 mUploadFinishReceiver
= null
;
231 if (mPreview
!= null
) {
237 public View
getView() {
238 return super.getView() == null ? mView
: super.getView();
244 public void onClick(View v
) {
246 case R
.id
.fdDownloadBtn
: {
247 Intent i
= new Intent(getActivity(), FileDownloader
.class);
248 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
249 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
250 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getRemotePath());
251 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
254 setButtonsForTransferring();
256 getActivity().startService(i
);
257 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
260 case R
.id
.fdKeepInSync
: {
261 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
262 mFile
.setKeepInSync(cb
.isChecked());
263 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
264 fdsm
.saveFile(mFile
);
265 if (mFile
.keepInSync()) {
266 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
268 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
271 Intent intent = new Intent(getActivity().getApplicationContext(),
272 FileObserverService.class);
273 intent.putExtra(FileObserverService.KEY_FILE_CMD,
275 FileObserverService.CMD_ADD_OBSERVED_FILE:
276 FileObserverService.CMD_DEL_OBSERVED_FILE));
277 intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
278 getActivity().startService(intent);
282 case R
.id
.fdRenameBtn
: {
283 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
284 dialog
.show(getFragmentManager(), "nameeditdialog");
285 dialog
.setOnDismissListener(this);
288 case R
.id
.fdRemoveBtn
: {
289 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
290 R
.string
.confirmation_remove_alert
,
291 new String
[]{mFile
.getFileName()},
292 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
293 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
294 R
.string
.common_cancel
);
295 confDialog
.setOnConfirmationListener(this);
296 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
299 case R
.id
.fdOpenBtn
: {
300 String storagePath
= mFile
.getStoragePath();
301 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
303 Intent i
= new Intent(Intent
.ACTION_VIEW
);
304 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
305 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
308 } catch (Throwable t
) {
309 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
310 boolean toastIt
= true
;
311 String mimeType
= "";
313 Intent i
= new Intent(Intent
.ACTION_VIEW
);
314 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
315 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
316 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
317 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
322 } catch (IndexOutOfBoundsException e
) {
323 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
325 } catch (ActivityNotFoundException e
) {
326 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
328 } catch (Throwable th
) {
329 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
333 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
341 Log
.e(TAG
, "Incorrect view clicked!");
344 /* else if (v.getId() == R.id.fdShareBtn) {
345 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
352 public void onConfirmation(String callerTag
) {
353 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
354 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
355 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
356 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
357 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
358 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
364 public void onNeutral(String callerTag
) {
365 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
367 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
369 mFile
.setStoragePath(null
);
370 fdsm
.saveFile(mFile
);
371 updateFileDetails(mFile
, mAccount
);
376 public void onCancel(String callerTag
) {
377 Log
.d(TAG
, "REMOVAL CANCELED");
382 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
384 * @return True when the fragment was created with the empty layout.
386 public boolean isEmpty() {
387 return mLayout
== R
.layout
.file_details_empty
;
392 * Can be used to get the file that is currently being displayed.
393 * @return The file on the screen.
395 public OCFile
getDisplayedFile(){
400 * Use this method to signal this Activity that it shall update its view.
402 * @param file : An {@link OCFile}
404 public void updateFileDetails(OCFile file
, Account ocAccount
) {
406 mAccount
= ocAccount
;
412 * Updates the view with all relevant details about that file.
414 public void updateFileDetails() {
416 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
419 setFilename(mFile
.getFileName());
420 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
422 setFilesize(mFile
.getFileLength());
423 if(ocVersionSupportsTimeCreated()){
424 setTimeCreated(mFile
.getCreationTimestamp());
427 setTimeModified(mFile
.getModificationTimestamp());
429 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
430 cb
.setChecked(mFile
.keepInSync());
432 // configure UI for depending upon local state of the file
433 if (FileDownloader
.isDownloading(mAccount
, mFile
.getRemotePath()) || FileUploader
.isUploading(mAccount
, mFile
.getRemotePath())) {
434 setButtonsForTransferring();
436 } else if (mFile
.isDown()) {
438 if (mFile
.getMimetype().startsWith("image/")) {
439 BitmapLoader bl
= new BitmapLoader();
440 bl
.execute(new String
[]{mFile
.getStoragePath()});
446 setButtonsForRemote();
453 * Updates the filename in view
454 * @param filename to set
456 private void setFilename(String filename
) {
457 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
459 tv
.setText(filename
);
463 * Updates the MIME type in view
464 * @param mimetype to set
466 private void setFiletype(String mimetype
) {
467 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
469 tv
.setText(mimetype
);
473 * Updates the file size in view
474 * @param filesize in bytes to set
476 private void setFilesize(long filesize
) {
477 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
479 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
483 * Updates the time that the file was created in view
484 * @param milliseconds Unix time to set
486 private void setTimeCreated(long milliseconds
){
487 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
488 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
490 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
491 tv
.setVisibility(View
.VISIBLE
);
492 tvLabel
.setVisibility(View
.VISIBLE
);
497 * Updates the time that the file was last modified
498 * @param milliseconds Unix time to set
500 private void setTimeModified(long milliseconds
){
501 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
503 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
508 * Enables or disables buttons for a file being downloaded
510 private void setButtonsForTransferring() {
512 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
513 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
514 downloadButton
.setEnabled(false
); // TODO replace it with a 'cancel download' button
516 // let's protect the user from himself ;)
517 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
518 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
519 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
524 * Enables or disables buttons for a file locally available
526 private void setButtonsForDown() {
528 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
529 //downloadButton.setText(R.string.filedetails_redownload); // ugly
530 downloadButton
.setEnabled(true
);
532 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
533 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
534 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
539 * Enables or disables buttons for a file not locally available
541 private void setButtonsForRemote() {
543 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
544 //downloadButton.setText(R.string.filedetails_download); // unnecessary
545 downloadButton
.setEnabled(true
);
547 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
548 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
549 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
555 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
556 * the time that the file was created. There is a chance that this will
557 * be fixed in future versions. Use this method to check if this version of
558 * ownCloud has this fix.
559 * @return True, if ownCloud the ownCloud version is supporting creation time
561 private boolean ocVersionSupportsTimeCreated(){
562 /*if(mAccount != null){
563 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
564 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
565 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
566 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
575 * Interface to implement by any Activity that includes some instance of FileDetailFragment
577 * @author David A. Velasco
579 public interface ContainerActivity
{
582 * Callback method invoked when the detail fragment wants to notice its container
583 * activity about a relevant state the file shown by the fragment.
585 * Added to notify to FileDisplayActivity about the need of refresh the files list.
587 * Currently called when:
588 * - a download is started;
589 * - a rename is completed;
590 * - a deletion is completed;
591 * - the 'inSync' flag is changed;
593 public void onFileStateChanged();
599 * Once the file download has finished -> update view
600 * @author Bartek Przybylski
602 private class DownloadFinishReceiver
extends BroadcastReceiver
{
604 public void onReceive(Context context
, Intent intent
) {
605 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
607 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
608 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
609 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
610 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
611 if (downloadWasFine
) {
612 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
614 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
622 * Once the file upload has finished -> update view
624 * Being notified about the finish of an upload is necessary for the next sequence:
625 * 1. Upload a big file.
626 * 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
627 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
628 * 3. Click the file in the list to see its details.
629 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
631 private class UploadFinishReceiver
extends BroadcastReceiver
{
633 public void onReceive(Context context
, Intent intent
) {
634 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
636 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
637 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
638 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
639 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
641 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
642 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
644 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
651 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
652 private class ShareRunnable
implements Runnable
{
653 private String mPath
;
655 public ShareRunnable(String path
) {
660 AccountManager am
= AccountManager
.get(getActivity());
661 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
662 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
663 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
665 Log
.d("share", "sharing for version " + ocv
.toString());
667 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
668 String APPS_PATH
= "/apps/files_sharing/";
669 String SHARE_PATH
= "ajax/share.php";
671 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
673 final String WEBDAV_SCRIPT
= "webdav.php";
674 final String WEBDAV_FILES_LOCATION
= "/files/";
676 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
677 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
678 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
680 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
681 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
683 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
685 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
686 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
687 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
688 Log
.d("share", mPath
+"");
689 formparams
.add(new BasicNameValuePair("sources",mPath
));
690 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
691 formparams
.add(new BasicNameValuePair("permissions", "0"));
692 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
696 PropFindMethod find
= new PropFindMethod(url
+"/");
697 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
698 Log
.d("sharer", ""+ url
+"/");
700 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
701 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
704 int status2
= wc
.executeMethod(find
);
706 Log
.d("sharer", "propstatus "+status2
);
708 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
709 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
711 status2
= wc
.executeMethod(get
);
713 Log
.d("sharer", "getstatus "+status2
);
714 Log
.d("sharer", "" + get
.getResponseBodyAsString());
716 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
717 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
720 status
= wc
.executeMethod(post
);
721 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
722 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
724 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
725 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
727 String resp
= post
.getResponseBodyAsString();
728 Log
.d("share", ""+post
.getURI().toString());
729 Log
.d("share", "returned status " + status
);
730 Log
.d("share", " " +resp
);
732 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
736 JSONObject jsonObject
= new JSONObject (resp
);
737 String jsonStatus
= jsonObject
.getString("status");
738 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
740 String token
= jsonObject
.getString("data");
741 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
742 Log
.d("Actions:shareFile ok", "url: " + uri
);
744 } catch (HttpException e
) {
745 // TODO Auto-generated catch block
747 } catch (IOException e
) {
748 // TODO Auto-generated catch block
750 } catch (JSONException e
) {
751 // TODO Auto-generated catch block
753 } catch (Exception e
) {
754 // TODO Auto-generated catch block
758 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
764 public void onDismiss(EditNameFragment dialog
) {
765 if (dialog
instanceof EditNameFragment
) {
766 if (((EditNameFragment
)dialog
).getResult()) {
767 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
768 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
769 if (!newFilename
.equals(mFile
.getFileName())) {
770 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
771 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
772 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
773 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
774 newFile
.setFileId(mFile
.getFileId());
775 newFile
.setFileLength(mFile
.getFileLength());
776 newFile
.setKeepInSync(mFile
.keepInSync());
777 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
778 newFile
.setMimetype(mFile
.getMimetype());
779 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
780 newFile
.setParentId(mFile
.getParentId());
781 boolean localRenameFails
= false
;
782 if (mFile
.isDown()) {
783 File f
= new File(mFile
.getStoragePath());
784 Log
.e(TAG
, f
.getAbsolutePath());
785 localRenameFails
= !(f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)));
786 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
787 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
790 if (localRenameFails
) {
791 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
795 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
796 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
797 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
804 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
809 private class RenameRunnable
implements Runnable
{
815 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
823 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
824 AccountManager am
= AccountManager
.get(getSherlockActivity());
825 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
826 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
827 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
828 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
830 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
831 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
832 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
834 boolean success
= false
;
836 int status
= wc
.executeMethod(move
);
837 success
= move
.succeeded();
838 move
.getResponseBodyAsString(); // exhaust response, although not interesting
839 Log
.d(TAG
, "Move returned status: " + status
);
841 } catch (HttpException e
) {
842 Log
.e(TAG
, "HTTP Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
844 } catch (IOException e
) {
845 Log
.e(TAG
, "I/O Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
847 } catch (Exception e
) {
848 Log
.e(TAG
, "Unexpected exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
851 move
.releaseConnection();
855 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
856 fdsm
.removeFile(mOld
, false
);
859 mHandler
.post(new Runnable() {
862 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
863 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
864 updateFileDetails(mFile
, mAccount
);
865 mContainerActivity
.onFileStateChanged();
870 mHandler
.post(new Runnable() {
873 // undo the local rename
875 File f
= new File(mNew
.getStoragePath());
876 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
877 // the local rename undoing failed; last chance: save the new local storage path in the old file
878 mFile
.setStoragePath(mNew
.getStoragePath());
879 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
880 fdsm
.saveFile(mFile
);
883 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
884 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
886 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
889 } catch (NotFoundException e
) {
896 private class LocalMoveMethod
extends DavMethodBase
{
898 public LocalMoveMethod(String uri
, String dest
) {
900 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
904 public String
getName() {
909 protected boolean isSuccess(int status
) {
910 return status
== 201 || status
== 204;
916 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
918 private String mNewFilename
;
919 private boolean mResult
;
920 private FileDetailFragment mListener
;
922 static public EditNameFragment
newInstance(String filename
) {
923 EditNameFragment f
= new EditNameFragment();
924 Bundle args
= new Bundle();
925 args
.putString("filename", filename
);
926 f
.setArguments(args
);
931 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
932 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
934 String currentName
= getArguments().getString("filename");
935 if (currentName
== null
)
938 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
939 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
940 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
941 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
942 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
949 public void onClick(View view
) {
950 switch (view
.getId()) {
952 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
955 case R
.id
.cancel
: { // fallthought
957 mListener
.onDismiss(this);
962 void setOnDismissListener(FileDetailFragment listener
) {
963 mListener
= listener
;
966 public String
getNewFilename() {
970 // true if user click ok
971 public boolean getResult() {
977 private class RemoveRunnable
implements Runnable
{
980 OCFile mFileToRemove
;
983 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
984 mFileToRemove
= fileToRemove
;
990 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
991 AccountManager am
= AccountManager
.get(getSherlockActivity());
992 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
993 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
994 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
995 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
997 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
999 boolean success
= false
;
1002 status
= wc
.executeMethod(delete
);
1003 success
= (delete
.succeeded());
1004 delete
.getResponseBodyAsString(); // exhaust the response, although not interesting
1005 Log
.d(TAG
, "Delete: returned status " + status
);
1007 } catch (HttpException e
) {
1008 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1010 } catch (IOException e
) {
1011 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1013 } catch (Exception e
) {
1014 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1017 delete
.releaseConnection();
1021 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1022 fdsm
.removeFile(mFileToRemove
, true
);
1023 mHandler
.post(new Runnable() {
1026 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1027 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1029 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1031 if (inDisplayActivity
) {
1033 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1034 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1035 transaction
.commit();
1036 mContainerActivity
.onFileStateChanged();
1039 getActivity().finish();
1042 } catch (NotFoundException e
) {
1043 e
.printStackTrace();
1049 mHandler
.post(new Runnable() {
1052 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1053 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1055 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1058 } catch (NotFoundException e
) {
1059 e
.printStackTrace();
1068 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1069 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1071 protected Bitmap
doInBackground(String
... params
) {
1072 Bitmap result
= null
;
1073 if (params
.length
!= 1) return result
;
1074 String storagePath
= params
[0];
1077 BitmapFactory
.Options options
= new Options();
1078 options
.inScaled
= true
;
1079 options
.inPurgeable
= true
;
1080 options
.inJustDecodeBounds
= true
;
1081 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1082 options
.inPreferQualityOverSpeed
= false
;
1084 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1085 options
.inMutable
= false
;
1088 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1089 options
.inJustDecodeBounds
= false
;
1091 int width
= options
.outWidth
;
1092 int height
= options
.outHeight
;
1094 if (width
>= 2048 || height
>= 2048) {
1095 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1096 options
.inSampleSize
= scale
;
1098 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1099 Point size
= new Point();
1101 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1102 display
.getSize(size
);
1103 screenwidth
= size
.x
;
1105 screenwidth
= display
.getWidth();
1108 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1110 if (width
> screenwidth
) {
1111 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1112 options
.inSampleSize
= scale
;
1115 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1117 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1119 } catch (OutOfMemoryError e
) {
1121 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1123 } catch (NoSuchFieldError e
) {
1125 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1127 } catch (Throwable t
) {
1129 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1134 protected void onPostExecute(Bitmap result
) {
1135 if (result
!= null
&& mPreview
!= null
) {
1136 mPreview
.setImageBitmap(result
);