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
.ui
.activity
.FileDisplayActivity
;
83 import eu
.alefzero
.owncloud
.utils
.OwnCloudVersion
;
84 import eu
.alefzero
.webdav
.WebdavClient
;
85 import eu
.alefzero
.webdav
.WebdavUtils
;
88 * This Fragment is used to display the details about a file.
90 * @author Bartek Przybylski
93 public class FileDetailFragment
extends SherlockFragment
implements
94 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
96 public static final String EXTRA_FILE
= "FILE";
97 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
101 private OCFile mFile
;
102 private Account mAccount
;
103 private ImageView mPreview
;
105 private DownloadFinishReceiver mDownloadFinishReceiver
;
107 private static final String TAG
= "FileDetailFragment";
108 public static final String FTAG
= "FileDetails";
109 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
113 * Creates an empty details fragment.
115 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
117 public FileDetailFragment() {
120 mLayout
= R
.layout
.file_details_empty
;
125 * Creates a details fragment.
127 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
129 * @param fileToDetail An {@link OCFile} to show in the fragment
130 * @param ocAccount An ownCloud account; needed to start downloads
132 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
133 mFile
= fileToDetail
;
134 mAccount
= ocAccount
;
135 mLayout
= R
.layout
.file_details_empty
;
137 if(fileToDetail
!= null
&& ocAccount
!= null
) {
138 mLayout
= R
.layout
.file_details_fragment
;
144 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
145 Bundle savedInstanceState
) {
146 super.onCreateView(inflater
, container
, savedInstanceState
);
148 if (savedInstanceState
!= null
) {
149 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
150 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
154 view
= inflater
.inflate(mLayout
, container
, false
);
157 if (mLayout
== R
.layout
.file_details_fragment
) {
158 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
159 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
160 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
161 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
162 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
163 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
164 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
173 public void onSaveInstanceState(Bundle outState
) {
174 Log
.i(getClass().toString(), "onSaveInstanceState() start");
175 super.onSaveInstanceState(outState
);
176 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
177 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
178 Log
.i(getClass().toString(), "onSaveInstanceState() end");
183 public void onResume() {
185 mDownloadFinishReceiver
= new DownloadFinishReceiver();
186 IntentFilter filter
= new IntentFilter(
187 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
188 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
189 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
193 public void onPause() {
195 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
196 mDownloadFinishReceiver
= null
;
197 if (mPreview
!= null
) {
203 public View
getView() {
204 return super.getView() == null ? mView
: super.getView();
210 public void onClick(View v
) {
212 case R
.id
.fdDownloadBtn
: {
213 Intent i
= new Intent(getActivity(), FileDownloader
.class);
214 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
215 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
216 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getRemotePath());
217 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
220 Toast
.makeText(getActivity(), "Downloading", Toast
.LENGTH_LONG
).show();
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("to remove " + 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 (mFile
.isDownloading()) {
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
) {
557 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
558 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
559 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
560 if (downloadWasFine
) {
561 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
));
563 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
569 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
570 private class ShareRunnable
implements Runnable
{
571 private String mPath
;
573 public ShareRunnable(String path
) {
578 AccountManager am
= AccountManager
.get(getActivity());
579 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
580 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
581 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
583 Log
.d("share", "sharing for version " + ocv
.toString());
585 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
586 String APPS_PATH
= "/apps/files_sharing/";
587 String SHARE_PATH
= "ajax/share.php";
589 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
591 final String WEBDAV_SCRIPT
= "webdav.php";
592 final String WEBDAV_FILES_LOCATION
= "/files/";
594 WebdavClient wc
= new WebdavClient();
595 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
596 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
598 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
599 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
601 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
603 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
604 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
605 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
606 Log
.d("share", mPath
+"");
607 formparams
.add(new BasicNameValuePair("sources",mPath
));
608 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
609 formparams
.add(new BasicNameValuePair("permissions", "0"));
610 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
614 PropFindMethod find
= new PropFindMethod(url
+"/");
615 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
616 Log
.d("sharer", ""+ url
+"/");
617 wc
.setCredentials(account
.name
.substring(0, account
.name
.lastIndexOf('@')), am
.getPassword(account
));
619 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
620 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
623 int status2
= wc
.executeMethod(find
);
625 Log
.d("sharer", "propstatus "+status2
);
627 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
628 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
630 status2
= wc
.executeMethod(get
);
632 Log
.d("sharer", "getstatus "+status2
);
633 Log
.d("sharer", "" + get
.getResponseBodyAsString());
635 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
636 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
639 status
= wc
.executeMethod(post
);
640 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
641 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
643 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
644 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
646 String resp
= post
.getResponseBodyAsString();
647 Log
.d("share", ""+post
.getURI().toString());
648 Log
.d("share", "returned status " + status
);
649 Log
.d("share", " " +resp
);
651 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
655 JSONObject jsonObject
= new JSONObject (resp
);
656 String jsonStatus
= jsonObject
.getString("status");
657 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
659 String token
= jsonObject
.getString("data");
660 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
661 Log
.d("Actions:shareFile ok", "url: " + uri
);
663 } catch (HttpException e
) {
664 // TODO Auto-generated catch block
666 } catch (IOException e
) {
667 // TODO Auto-generated catch block
669 } catch (JSONException e
) {
670 // TODO Auto-generated catch block
672 } catch (Exception e
) {
673 // TODO Auto-generated catch block
677 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
683 public void onDismiss(EditNameFragment dialog
) {
684 if (dialog
instanceof EditNameFragment
) {
685 if (((EditNameFragment
)dialog
).getResult()) {
686 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
687 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
688 if (!newFilename
.equals(mFile
.getFileName())) {
689 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
690 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
691 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
692 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
693 newFile
.setFileId(mFile
.getFileId());
694 newFile
.setFileLength(mFile
.getFileLength());
695 newFile
.setKeepInSync(mFile
.keepInSync());
696 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
697 newFile
.setMimetype(mFile
.getMimetype());
698 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
699 newFile
.setParentId(mFile
.getParentId());
700 if (mFile
.isDown()) {
701 File f
= new File(mFile
.getStoragePath());
702 Log
.e(TAG
, f
.getAbsolutePath());
703 f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)); // TODO check if fails
704 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
705 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
708 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
714 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
719 private class RenameRunnable
implements Runnable
{
725 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
733 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
734 AccountManager am
= AccountManager
.get(getSherlockActivity());
735 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
736 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
737 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
738 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
740 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
741 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
742 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
745 int status
= wc
.executeMethod(move
);
746 if (move
.succeeded()) {
747 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
748 fdsm
.removeFile(mOld
);
751 mHandler
.post(new Runnable() {
753 public void run() { updateFileDetails(mFile
, mAccount
); }
756 Log
.e("ASD", ""+move
.getQueryString());
757 Log
.d("move", "returned status " + status
);
758 } catch (HttpException e
) {
759 // TODO Auto-generated catch block
761 } catch (IOException e
) {
762 // TODO Auto-generated catch block
766 private class LocalMoveMethod
extends DavMethodBase
{
768 public LocalMoveMethod(String uri
, String dest
) {
770 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
774 public String
getName() {
779 protected boolean isSuccess(int status
) {
780 return status
== 201 || status
== 204;
786 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
788 private String mNewFilename
;
789 private boolean mResult
;
790 private FileDetailFragment mListener
;
792 static public EditNameFragment
newInstance(String filename
) {
793 EditNameFragment f
= new EditNameFragment();
794 Bundle args
= new Bundle();
795 args
.putString("filename", filename
);
796 f
.setArguments(args
);
801 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
802 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
804 String currentName
= getArguments().getString("filename");
805 if (currentName
== null
)
808 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
809 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
810 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
811 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
812 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
819 public void onClick(View view
) {
820 switch (view
.getId()) {
822 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
825 case R
.id
.cancel
: { // fallthought
827 mListener
.onDismiss(this);
832 void setOnDismissListener(FileDetailFragment listener
) {
833 mListener
= listener
;
836 public String
getNewFilename() {
840 // true if user click ok
841 public boolean getResult() {
847 private class RemoveRunnable
implements Runnable
{
849 /** Arbitrary timeout for deletion */
850 public final static int DELETION_TIMEOUT
= 5000;
853 OCFile mFileToRemove
;
856 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
857 mFileToRemove
= fileToRemove
;
863 WebdavClient wc
= new WebdavClient(mAccount
, getSherlockActivity().getApplicationContext());
864 AccountManager am
= AccountManager
.get(getSherlockActivity());
865 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
866 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
867 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
868 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
870 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
872 boolean success
= false
;
874 int status
= wc
.executeMethod(delete
, DELETION_TIMEOUT
);
875 if (delete
.succeeded()) {
876 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
877 fdsm
.removeFile(mFileToRemove
);
878 mHandler
.post(new Runnable() {
882 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
884 if (getActivity() instanceof FileDisplayActivity
) {
886 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
887 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
888 transaction
.commit();
891 getActivity().finish();
894 } catch (NotFoundException e
) {
901 Log
.e("ASD", ""+ delete
.getQueryString());
902 Log
.d("delete", "returned status " + status
);
904 } catch (HttpException e
) {
907 } catch (IOException e
) {
912 mHandler
.post(new Runnable() {
916 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
919 } catch (NotFoundException e
) {
930 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
932 protected Bitmap
doInBackground(String
... params
) {
933 Bitmap result
= null
;
934 if (params
.length
!= 1) return result
;
935 String storagePath
= params
[0];
938 BitmapFactory
.Options options
= new Options();
939 options
.inScaled
= true
;
940 options
.inPurgeable
= true
;
941 options
.inJustDecodeBounds
= true
;
942 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
943 options
.inPreferQualityOverSpeed
= false
;
945 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
946 options
.inMutable
= false
;
949 result
= BitmapFactory
.decodeFile(storagePath
, options
);
950 options
.inJustDecodeBounds
= false
;
952 int width
= options
.outWidth
;
953 int height
= options
.outHeight
;
955 boolean recycle
= false
;
956 if (width
>= 2048 || height
>= 2048) {
957 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
958 options
.inSampleSize
= scale
;
960 Display display
= getActivity().getWindowManager().getDefaultDisplay();
961 Point size
= new Point();
963 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
964 display
.getSize(size
);
965 screenwidth
= size
.x
;
967 screenwidth
= display
.getWidth();
970 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
972 if (width
> screenwidth
) {
973 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
974 options
.inSampleSize
= scale
;
977 result
= BitmapFactory
.decodeFile(storagePath
, options
);
979 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
981 } catch (OutOfMemoryError e
) {
983 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
985 } catch (NoSuchFieldError e
) {
987 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
989 } catch (Throwable t
) {
991 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
996 protected void onPostExecute(Bitmap result
) {
997 if (result
!= null
&& mPreview
!= null
) {
998 mPreview
.setImageBitmap(result
);