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
.content
.ActivityNotFoundException
;
44 import android
.content
.BroadcastReceiver
;
45 import android
.content
.Context
;
46 import android
.content
.Intent
;
47 import android
.content
.IntentFilter
;
48 import android
.content
.res
.Resources
.NotFoundException
;
49 import android
.graphics
.Bitmap
;
50 import android
.graphics
.BitmapFactory
;
51 import android
.graphics
.BitmapFactory
.Options
;
52 import android
.graphics
.Point
;
53 import android
.net
.Uri
;
54 import android
.os
.AsyncTask
;
55 import android
.os
.Bundle
;
56 import android
.os
.Handler
;
57 import android
.support
.v4
.app
.FragmentTransaction
;
58 import android
.util
.Log
;
59 import android
.view
.Display
;
60 import android
.view
.LayoutInflater
;
61 import android
.view
.View
;
62 import android
.view
.View
.OnClickListener
;
63 import android
.view
.ViewGroup
;
64 import android
.view
.WindowManager
.LayoutParams
;
65 import android
.webkit
.MimeTypeMap
;
66 import android
.widget
.Button
;
67 import android
.widget
.CheckBox
;
68 import android
.widget
.ImageView
;
69 import android
.widget
.TextView
;
70 import android
.widget
.Toast
;
72 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
73 import com
.actionbarsherlock
.app
.SherlockFragment
;
75 import eu
.alefzero
.owncloud
.AccountUtils
;
76 import eu
.alefzero
.owncloud
.DisplayUtils
;
77 import eu
.alefzero
.owncloud
.R
;
78 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
79 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
80 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
81 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
82 import eu
.alefzero
.owncloud
.files
.services
.FileUploader
;
83 import eu
.alefzero
.owncloud
.ui
.activity
.FileDisplayActivity
;
84 import eu
.alefzero
.owncloud
.utils
.OwnCloudVersion
;
85 import eu
.alefzero
.webdav
.WebdavClient
;
86 import eu
.alefzero
.webdav
.WebdavUtils
;
89 * This Fragment is used to display the details about a file.
91 * @author Bartek Przybylski
94 public class FileDetailFragment
extends SherlockFragment
implements
95 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
97 public static final String EXTRA_FILE
= "FILE";
98 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
102 private OCFile mFile
;
103 private Account mAccount
;
104 private ImageView mPreview
;
106 private DownloadFinishReceiver mDownloadFinishReceiver
;
108 private static final String TAG
= "FileDetailFragment";
109 public static final String FTAG
= "FileDetails";
110 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
114 * Creates an empty details fragment.
116 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
118 public FileDetailFragment() {
121 mLayout
= R
.layout
.file_details_empty
;
126 * Creates a details fragment.
128 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
130 * @param fileToDetail An {@link OCFile} to show in the fragment
131 * @param ocAccount An ownCloud account; needed to start downloads
133 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
134 mFile
= fileToDetail
;
135 mAccount
= ocAccount
;
136 mLayout
= R
.layout
.file_details_empty
;
138 if(fileToDetail
!= null
&& ocAccount
!= null
) {
139 mLayout
= R
.layout
.file_details_fragment
;
145 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
146 Bundle savedInstanceState
) {
147 super.onCreateView(inflater
, container
, savedInstanceState
);
149 if (savedInstanceState
!= null
) {
150 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
151 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
155 view
= inflater
.inflate(mLayout
, container
, false
);
158 if (mLayout
== R
.layout
.file_details_fragment
) {
159 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
160 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
161 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
162 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
163 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
164 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
165 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
174 public void onSaveInstanceState(Bundle outState
) {
175 Log
.i(getClass().toString(), "onSaveInstanceState() start");
176 super.onSaveInstanceState(outState
);
177 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
178 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
179 Log
.i(getClass().toString(), "onSaveInstanceState() end");
184 public void onResume() {
186 mDownloadFinishReceiver
= new DownloadFinishReceiver();
187 IntentFilter filter
= new IntentFilter(
188 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
189 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
190 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
194 public void onPause() {
196 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
197 mDownloadFinishReceiver
= null
;
198 if (mPreview
!= null
) {
204 public View
getView() {
205 return super.getView() == null ? mView
: super.getView();
211 public void onClick(View v
) {
213 case R
.id
.fdDownloadBtn
: {
214 Intent i
= new Intent(getActivity(), FileDownloader
.class);
215 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
216 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
217 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getRemotePath());
218 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
221 setButtonsForDownloading();
223 getActivity().startService(i
);
226 case R
.id
.fdKeepInSync
: {
227 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
228 mFile
.setKeepInSync(cb
.isChecked());
229 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
230 fdsm
.saveFile(mFile
);
231 if (mFile
.keepInSync()) {
232 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
236 case R
.id
.fdRenameBtn
: {
237 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
238 dialog
.show(getFragmentManager(), "nameeditdialog");
239 dialog
.setOnDismissListener(this);
242 case R
.id
.fdRemoveBtn
: {
243 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(R
.string
.confirmation_remove_alert
, new String
[]{mFile
.getFileName()});
244 confDialog
.setOnConfirmationListener(this);
245 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
248 case R
.id
.fdOpenBtn
: {
249 String storagePath
= mFile
.getStoragePath();
250 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
252 Intent i
= new Intent(Intent
.ACTION_VIEW
);
253 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
254 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
257 } catch (Throwable t
) {
258 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
259 boolean toastIt
= true
;
260 String mimeType
= "";
262 Intent i
= new Intent(Intent
.ACTION_VIEW
);
263 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
264 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
265 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
266 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
271 } catch (IndexOutOfBoundsException e
) {
272 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
274 } catch (ActivityNotFoundException e
) {
275 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
277 } catch (Throwable th
) {
278 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
282 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
290 Log
.e(TAG
, "Incorrect view clicked!");
293 /* else if (v.getId() == R.id.fdShareBtn) {
294 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
301 public void onConfirmation(boolean confirmation
, String callerTag
) {
302 if (confirmation
&& callerTag
.equals(FTAG_CONFIRMATION
)) {
303 Log
.e("ASD","onConfirmation");
304 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
305 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
306 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
308 } else if (!confirmation
) Log
.d(TAG
, "REMOVAL CANCELED");
313 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
315 * @return True when the fragment was created with the empty layout.
317 public boolean isEmpty() {
318 return mLayout
== R
.layout
.file_details_empty
;
323 * Can be used to get the file that is currently being displayed.
324 * @return The file on the screen.
326 public OCFile
getDisplayedFile(){
331 * Use this method to signal this Activity that it shall update its view.
333 * @param file : An {@link OCFile}
335 public void updateFileDetails(OCFile file
, Account ocAccount
) {
337 mAccount
= ocAccount
;
343 * Updates the view with all relevant details about that file.
345 public void updateFileDetails() {
347 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
350 setFilename(mFile
.getFileName());
351 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
353 setFilesize(mFile
.getFileLength());
354 if(ocVersionSupportsTimeCreated()){
355 setTimeCreated(mFile
.getCreationTimestamp());
358 setTimeModified(mFile
.getModificationTimestamp());
360 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
361 cb
.setChecked(mFile
.keepInSync());
363 // configure UI for depending upon local state of the file
364 if (FileDownloader
.isDownloading(mAccount
, mFile
.getRemotePath())) {
365 setButtonsForDownloading();
367 } else if (mFile
.isDown()) {
369 if (mFile
.getMimetype().startsWith("image/")) {
370 BitmapLoader bl
= new BitmapLoader();
371 bl
.execute(new String
[]{mFile
.getStoragePath()});
376 // Change download button to open button
377 /*downloadButton.setText(R.string.filedetails_open);
378 downloadButton.setOnClickListener(new OnClickListener() {
380 public void onClick(View v) {
381 String storagePath = mFile.getStoragePath();
382 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
384 Intent i = new Intent(Intent.ACTION_VIEW);
385 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
386 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
389 } catch (Throwable t) {
390 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
391 boolean toastIt = true;
392 String mimeType = "";
394 Intent i = new Intent(Intent.ACTION_VIEW);
395 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
396 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
397 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
398 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
403 } catch (IndexOutOfBoundsException e) {
404 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
406 } catch (ActivityNotFoundException e) {
407 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
409 } catch (Throwable th) {
410 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
414 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
422 setButtonsForRemote();
429 * Updates the filename in view
430 * @param filename to set
432 private void setFilename(String filename
) {
433 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
435 tv
.setText(filename
);
439 * Updates the MIME type in view
440 * @param mimetype to set
442 private void setFiletype(String mimetype
) {
443 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
445 tv
.setText(mimetype
);
449 * Updates the file size in view
450 * @param filesize in bytes to set
452 private void setFilesize(long filesize
) {
453 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
455 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
459 * Updates the time that the file was created in view
460 * @param milliseconds Unix time to set
462 private void setTimeCreated(long milliseconds
){
463 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
464 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
466 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
467 tv
.setVisibility(View
.VISIBLE
);
468 tvLabel
.setVisibility(View
.VISIBLE
);
473 * Updates the time that the file was last modified
474 * @param milliseconds Unix time to set
476 private void setTimeModified(long milliseconds
){
477 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
479 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
484 * Enables or disables buttons for a file being downloaded
486 private void setButtonsForDownloading() {
488 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
489 downloadButton
.setText(R
.string
.filedetails_download_in_progress
);
490 downloadButton
.setEnabled(false
); // TODO replace it with a 'cancel download' button
492 // let's protect the user from himself ;)
493 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
494 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
495 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
500 * Enables or disables buttons for a file locally available
502 private void setButtonsForDown() {
504 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
505 downloadButton
.setText(R
.string
.filedetails_redownload
);
506 downloadButton
.setEnabled(true
);
508 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
509 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
510 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
515 * Enables or disables buttons for a file not locally available
517 private void setButtonsForRemote() {
519 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
520 downloadButton
.setText(R
.string
.filedetails_download
);
521 downloadButton
.setEnabled(true
);
523 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
524 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
525 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
531 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
532 * the time that the file was created. There is a chance that this will
533 * be fixed in future versions. Use this method to check if this version of
534 * ownCloud has this fix.
535 * @return True, if ownCloud the ownCloud version is supporting creation time
537 private boolean ocVersionSupportsTimeCreated(){
538 /*if(mAccount != null){
539 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
540 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
541 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
542 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
550 * Once the file download has finished -> update view
551 * @author Bartek Przybylski
553 private class DownloadFinishReceiver
extends BroadcastReceiver
{
555 public void onReceive(Context context
, Intent intent
) {
556 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
558 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
559 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
560 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
561 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
562 if (downloadWasFine
) {
563 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
));
565 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
571 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
572 private class ShareRunnable
implements Runnable
{
573 private String mPath
;
575 public ShareRunnable(String path
) {
580 AccountManager am
= AccountManager
.get(getActivity());
581 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
582 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
583 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
585 Log
.d("share", "sharing for version " + ocv
.toString());
587 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
588 String APPS_PATH
= "/apps/files_sharing/";
589 String SHARE_PATH
= "ajax/share.php";
591 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
593 final String WEBDAV_SCRIPT
= "webdav.php";
594 final String WEBDAV_FILES_LOCATION
= "/files/";
596 WebdavClient wc
= new WebdavClient();
597 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
598 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
600 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
601 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
603 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
605 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
606 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
607 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
608 Log
.d("share", mPath
+"");
609 formparams
.add(new BasicNameValuePair("sources",mPath
));
610 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
611 formparams
.add(new BasicNameValuePair("permissions", "0"));
612 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
616 PropFindMethod find
= new PropFindMethod(url
+"/");
617 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
618 Log
.d("sharer", ""+ url
+"/");
619 wc
.setCredentials(account
.name
.substring(0, account
.name
.lastIndexOf('@')), am
.getPassword(account
));
621 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
622 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
625 int status2
= wc
.executeMethod(find
);
627 Log
.d("sharer", "propstatus "+status2
);
629 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
630 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
632 status2
= wc
.executeMethod(get
);
634 Log
.d("sharer", "getstatus "+status2
);
635 Log
.d("sharer", "" + get
.getResponseBodyAsString());
637 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
638 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
641 status
= wc
.executeMethod(post
);
642 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
643 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
645 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
646 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
648 String resp
= post
.getResponseBodyAsString();
649 Log
.d("share", ""+post
.getURI().toString());
650 Log
.d("share", "returned status " + status
);
651 Log
.d("share", " " +resp
);
653 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
657 JSONObject jsonObject
= new JSONObject (resp
);
658 String jsonStatus
= jsonObject
.getString("status");
659 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
661 String token
= jsonObject
.getString("data");
662 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
663 Log
.d("Actions:shareFile ok", "url: " + uri
);
665 } catch (HttpException e
) {
666 // TODO Auto-generated catch block
668 } catch (IOException e
) {
669 // TODO Auto-generated catch block
671 } catch (JSONException e
) {
672 // TODO Auto-generated catch block
674 } catch (Exception e
) {
675 // TODO Auto-generated catch block
679 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
685 public void onDismiss(EditNameFragment dialog
) {
686 if (dialog
instanceof EditNameFragment
) {
687 if (((EditNameFragment
)dialog
).getResult()) {
688 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
689 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
690 if (!newFilename
.equals(mFile
.getFileName())) {
691 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
692 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
693 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
694 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
695 newFile
.setFileId(mFile
.getFileId());
696 newFile
.setFileLength(mFile
.getFileLength());
697 newFile
.setKeepInSync(mFile
.keepInSync());
698 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
699 newFile
.setMimetype(mFile
.getMimetype());
700 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
701 newFile
.setParentId(mFile
.getParentId());
702 if (mFile
.isDown()) {
703 File f
= new File(mFile
.getStoragePath());
704 Log
.e(TAG
, f
.getAbsolutePath());
705 f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)); // TODO check if fails
706 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
707 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
710 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
716 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
721 private class RenameRunnable
implements Runnable
{
727 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
735 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
736 wc
.allowSelfsignedCertificates();
737 AccountManager am
= AccountManager
.get(getSherlockActivity());
738 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
739 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
740 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
741 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
743 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
744 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
745 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
748 int status
= wc
.executeMethod(move
);
749 if (move
.succeeded()) {
750 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
751 fdsm
.removeFile(mOld
);
754 mHandler
.post(new Runnable() {
756 public void run() { updateFileDetails(mFile
, mAccount
); }
759 Log
.e("ASD", ""+move
.getQueryString());
760 Log
.d("move", "returned status " + status
);
761 } catch (HttpException e
) {
762 // TODO Auto-generated catch block
764 } catch (IOException e
) {
765 // TODO Auto-generated catch block
769 private class LocalMoveMethod
extends DavMethodBase
{
771 public LocalMoveMethod(String uri
, String dest
) {
773 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
777 public String
getName() {
782 protected boolean isSuccess(int status
) {
783 return status
== 201 || status
== 204;
789 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
791 private String mNewFilename
;
792 private boolean mResult
;
793 private FileDetailFragment mListener
;
795 static public EditNameFragment
newInstance(String filename
) {
796 EditNameFragment f
= new EditNameFragment();
797 Bundle args
= new Bundle();
798 args
.putString("filename", filename
);
799 f
.setArguments(args
);
804 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
805 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
807 String currentName
= getArguments().getString("filename");
808 if (currentName
== null
)
811 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
812 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
813 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
814 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
815 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
822 public void onClick(View view
) {
823 switch (view
.getId()) {
825 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
828 case R
.id
.cancel
: { // fallthought
830 mListener
.onDismiss(this);
835 void setOnDismissListener(FileDetailFragment listener
) {
836 mListener
= listener
;
839 public String
getNewFilename() {
843 // true if user click ok
844 public boolean getResult() {
850 private class RemoveRunnable
implements Runnable
{
852 /** Arbitrary timeout for deletion */
853 public final static int DELETION_TIMEOUT
= 5000;
856 OCFile mFileToRemove
;
859 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
860 mFileToRemove
= fileToRemove
;
866 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
867 wc
.allowSelfsignedCertificates();
868 AccountManager am
= AccountManager
.get(getSherlockActivity());
869 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
870 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
871 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
872 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
874 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
876 boolean success
= false
;
878 int status
= wc
.executeMethod(delete
, DELETION_TIMEOUT
);
879 if (delete
.succeeded()) {
880 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
881 fdsm
.removeFile(mFileToRemove
);
882 mHandler
.post(new Runnable() {
886 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
888 if (getActivity() instanceof FileDisplayActivity
) {
890 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
891 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
892 transaction
.commit();
895 getActivity().finish();
898 } catch (NotFoundException e
) {
905 Log
.e("ASD", ""+ delete
.getQueryString());
906 Log
.d("delete", "returned status " + status
);
908 } catch (HttpException e
) {
911 } catch (IOException e
) {
916 mHandler
.post(new Runnable() {
920 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
923 } catch (NotFoundException e
) {
934 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
936 protected Bitmap
doInBackground(String
... params
) {
937 Bitmap result
= null
;
938 if (params
.length
!= 1) return result
;
939 String storagePath
= params
[0];
942 BitmapFactory
.Options options
= new Options();
943 options
.inScaled
= true
;
944 options
.inPurgeable
= true
;
945 options
.inJustDecodeBounds
= true
;
946 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
947 options
.inPreferQualityOverSpeed
= false
;
949 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
950 options
.inMutable
= false
;
953 result
= BitmapFactory
.decodeFile(storagePath
, options
);
954 options
.inJustDecodeBounds
= false
;
956 int width
= options
.outWidth
;
957 int height
= options
.outHeight
;
959 boolean recycle
= false
;
960 if (width
>= 2048 || height
>= 2048) {
961 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
962 options
.inSampleSize
= scale
;
964 Display display
= getActivity().getWindowManager().getDefaultDisplay();
965 Point size
= new Point();
967 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
968 display
.getSize(size
);
969 screenwidth
= size
.x
;
971 screenwidth
= display
.getWidth();
974 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
976 if (width
> screenwidth
) {
977 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
978 options
.inSampleSize
= scale
;
981 result
= BitmapFactory
.decodeFile(storagePath
, options
);
983 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
985 } catch (OutOfMemoryError e
) {
987 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
989 } catch (NoSuchFieldError e
) {
991 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
993 } catch (Throwable t
) {
995 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1000 protected void onPostExecute(Bitmap result
) {
1001 if (result
!= null
&& mPreview
!= null
) {
1002 mPreview
.setImageBitmap(result
);