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
;
20 import java
.io
.IOException
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import org
.apache
.commons
.httpclient
.HostConfiguration
;
25 import org
.apache
.commons
.httpclient
.HttpException
;
26 import org
.apache
.commons
.httpclient
.cookie
.CookiePolicy
;
27 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
28 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
29 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
30 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
31 import org
.apache
.commons
.httpclient
.params
.HttpMethodParams
;
32 import org
.apache
.http
.HttpStatus
;
33 import org
.apache
.http
.NameValuePair
;
34 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
35 import org
.apache
.http
.message
.BasicNameValuePair
;
36 import org
.apache
.http
.protocol
.HTTP
;
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
.graphics
.Bitmap
;
49 import android
.graphics
.BitmapFactory
;
50 import android
.graphics
.BitmapFactory
.Options
;
51 import android
.graphics
.Point
;
52 import android
.graphics
.drawable
.BitmapDrawable
;
53 import android
.graphics
.drawable
.Drawable
;
54 import android
.net
.Uri
;
55 import android
.os
.Bundle
;
56 import android
.preference
.PreferenceActivity
.Header
;
57 import android
.util
.Log
;
58 import android
.view
.Display
;
59 import android
.view
.LayoutInflater
;
60 import android
.view
.View
;
61 import android
.view
.View
.OnClickListener
;
62 import android
.view
.ViewGroup
;
63 import android
.webkit
.MimeTypeMap
;
64 import android
.widget
.Button
;
65 import android
.widget
.CheckBox
;
66 import android
.widget
.ImageView
;
67 import android
.widget
.TextView
;
68 import android
.widget
.Toast
;
70 import com
.actionbarsherlock
.app
.SherlockFragment
;
72 import eu
.alefzero
.owncloud
.AccountUtils
;
73 import eu
.alefzero
.owncloud
.DisplayUtils
;
74 import eu
.alefzero
.owncloud
.R
;
75 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
76 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
77 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
78 import eu
.alefzero
.owncloud
.files
.services
.FileDownloader
;
79 import eu
.alefzero
.owncloud
.utils
.OwnCloudVersion
;
80 import eu
.alefzero
.webdav
.WebdavClient
;
83 * This Fragment is used to display the details about a file.
85 * @author Bartek Przybylski
88 public class FileDetailFragment
extends SherlockFragment
implements
91 public static final String EXTRA_FILE
= "FILE";
92 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
97 private Account mAccount
;
99 private DownloadFinishReceiver mDownloadFinishReceiver
;
101 private static final String TAG
= "FileDetailFragment";
102 public static final String FTAG
= "FileDetails";
106 * Creates an empty details fragment.
108 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
110 public FileDetailFragment() {
113 mLayout
= R
.layout
.file_details_empty
;
118 * Creates a details fragment.
120 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
122 * @param fileToDetail An {@link OCFile} to show in the fragment
123 * @param ocAccount An ownCloud account; needed to start downloads
125 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
){
126 mFile
= fileToDetail
;
127 mAccount
= ocAccount
;
128 mLayout
= R
.layout
.file_details_empty
;
130 if(fileToDetail
!= null
&& ocAccount
!= null
) {
131 mLayout
= R
.layout
.file_details_fragment
;
137 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
138 Bundle savedInstanceState
) {
139 super.onCreateView(inflater
, container
, savedInstanceState
);
141 if (savedInstanceState
!= null
) {
142 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
143 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
147 view
= inflater
.inflate(mLayout
, container
, false
);
156 public void onSaveInstanceState(Bundle outState
) {
157 Log
.i(getClass().toString(), "onSaveInstanceState() start");
158 super.onSaveInstanceState(outState
);
159 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
160 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
161 Log
.i(getClass().toString(), "onSaveInstanceState() end");
166 public void onResume() {
168 mDownloadFinishReceiver
= new DownloadFinishReceiver();
169 IntentFilter filter
= new IntentFilter(
170 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
171 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
175 public void onPause() {
177 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
178 mDownloadFinishReceiver
= null
;
182 public View
getView() {
183 return super.getView() == null ? mView
: super.getView();
187 public void onClick(View v
) {
188 if (v
.getId() == R
.id
.fdDownloadBtn
) {
189 //Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();
190 Intent i
= new Intent(getActivity(), FileDownloader
.class);
191 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
192 i
.putExtra(FileDownloader
.EXTRA_REMOTE_PATH
, mFile
.getRemotePath());
193 i
.putExtra(FileDownloader
.EXTRA_FILE_PATH
, mFile
.getURLDecodedRemotePath());
194 i
.putExtra(FileDownloader
.EXTRA_FILE_SIZE
, mFile
.getFileLength());
196 getActivity().startService(i
);
197 } else if (v
.getId() == R
.id
.fdKeepInSync
) {
198 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
199 mFile
.setKeepInSync(cb
.isChecked());
200 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
201 fdsm
.saveFile(mFile
);
202 if (mFile
.keepInSync() && !mFile
.isDownloaded()) {
203 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
205 }/* else if (v.getId() == R.id.fdShareBtn) {
206 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
213 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
215 * @return True when the fragment was created with the empty layout.
217 public boolean isEmpty() {
218 return mLayout
== R
.layout
.file_details_empty
;
223 * Can be used to get the file that is currently being displayed.
224 * @return The file on the screen.
226 public OCFile
getDisplayedFile(){
231 * Use this method to signal this Activity that it shall update its view.
233 * @param file : An {@link OCFile}
235 public void updateFileDetails(OCFile file
, Account ocAccount
) {
237 mAccount
= ocAccount
;
243 * Updates the view with all relevant details about that file.
245 public void updateFileDetails() {
247 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
249 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
251 setFilename(mFile
.getFileName());
252 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
254 setFilesize(mFile
.getFileLength());
255 if(ocVersionSupportsTimeCreated()){
256 setTimeCreated(mFile
.getCreationTimestamp());
259 setTimeModified(mFile
.getModificationTimestamp());
261 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
262 cb
.setChecked(mFile
.keepInSync());
263 cb
.setOnClickListener(this);
264 //getView().findViewById(R.id.fdShareBtn).setOnClickListener(this);
266 if (mFile
.getStoragePath() != null
) {
268 ImageView preview
= (ImageView
) getView().findViewById(R
.id
.fdPreview
);
270 if (mFile
.getMimetype().startsWith("image/")) {
271 BitmapFactory
.Options options
= new Options();
272 options
.inScaled
= true
;
273 options
.inPurgeable
= true
;
274 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
275 options
.inPreferQualityOverSpeed
= false
;
277 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
278 options
.inMutable
= false
;
281 Bitmap bmp
= BitmapFactory
.decodeFile(mFile
.getStoragePath(), options
);
284 int width
= options
.outWidth
;
285 int height
= options
.outHeight
;
287 boolean recycle
= false
;
288 if (width
>= 2048 || height
>= 2048) {
289 scale
= (int) (Math
.ceil(Math
.max(height
, width
)/2048.));
290 options
.inSampleSize
= scale
;
293 Display display
= getActivity().getWindowManager().getDefaultDisplay();
294 Point size
= new Point();
296 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
297 display
.getSize(size
);
298 screenwidth
= size
.x
;
300 screenwidth
= display
.getWidth();
303 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
305 if (width
> screenwidth
) {
306 scale
= (int) (Math
.ceil(Math
.max(height
, width
)/screenwidth
));
307 options
.inSampleSize
= scale
;
312 if (recycle
) bmp
.recycle();
313 bmp
= BitmapFactory
.decodeFile(mFile
.getStoragePath(), options
);
317 preview
.setImageBitmap(bmp
);
320 } catch (OutOfMemoryError e
) {
321 preview
.setVisibility(View
.INVISIBLE
);
322 Log
.e(TAG
, "Out of memory occured for file with size " + mFile
.getFileLength());
324 } catch (NoSuchFieldError e
) {
325 preview
.setVisibility(View
.INVISIBLE
);
326 Log
.e(TAG
, "Error from access to unexisting field despite protection " + mFile
.getFileLength());
328 } catch (Throwable t
) {
329 preview
.setVisibility(View
.INVISIBLE
);
330 Log
.e(TAG
, "Unexpected error while creating image preview " + mFile
.getFileLength(), t
);
333 // Change download button to open button
334 downloadButton
.setText(R
.string
.filedetails_open
);
335 downloadButton
.setOnClickListener(new OnClickListener() {
337 public void onClick(View v
) {
338 String storagePath
= mFile
.getStoragePath();
340 Intent i
= new Intent(Intent
.ACTION_VIEW
);
341 i
.setDataAndType(Uri
.parse("file://"+ storagePath
), mFile
.getMimetype());
342 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
345 } catch (Throwable t
) {
346 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
347 boolean toastIt
= true
;
348 String mimeType
= "";
350 Intent i
= new Intent(Intent
.ACTION_VIEW
);
351 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
352 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
353 i
.setDataAndType(Uri
.parse("file://"+mFile
.getStoragePath()), mimeType
);
354 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
359 } catch (IndexOutOfBoundsException e
) {
360 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
362 } catch (ActivityNotFoundException e
) {
363 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
365 } catch (Throwable th
) {
366 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
370 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
378 // Make download button effective
379 downloadButton
.setOnClickListener(this);
386 * Updates the filename in view
387 * @param filename to set
389 private void setFilename(String filename
) {
390 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
392 tv
.setText(filename
);
396 * Updates the MIME type in view
397 * @param mimetype to set
399 private void setFiletype(String mimetype
) {
400 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
402 tv
.setText(mimetype
);
406 * Updates the file size in view
407 * @param filesize in bytes to set
409 private void setFilesize(long filesize
) {
410 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
412 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
416 * Updates the time that the file was created in view
417 * @param milliseconds Unix time to set
419 private void setTimeCreated(long milliseconds
){
420 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
421 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
423 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
424 tv
.setVisibility(View
.VISIBLE
);
425 tvLabel
.setVisibility(View
.VISIBLE
);
430 * Updates the time that the file was last modified
431 * @param milliseconds Unix time to set
433 private void setTimeModified(long milliseconds
){
434 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
436 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
441 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
442 * the time that the file was created. There is a chance that this will
443 * be fixed in future versions. Use this method to check if this version of
444 * ownCloud has this fix.
445 * @return True, if ownCloud the ownCloud version is supporting creation time
447 private boolean ocVersionSupportsTimeCreated(){
448 /*if(mAccount != null){
449 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
450 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
451 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
452 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
460 * Once the file download has finished -> update view
461 * @author Bartek Przybylski
463 private class DownloadFinishReceiver
extends BroadcastReceiver
{
465 public void onReceive(Context context
, Intent intent
) {
466 if (getView()!=null
&& getView().findViewById(R
.id
.fdDownloadBtn
) != null
)
467 getView().findViewById(R
.id
.fdDownloadBtn
).setEnabled(true
);
469 if (intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
)) {
470 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
));
472 } else if (intent
.getAction().equals(FileDownloader
.DOWNLOAD_FINISH_MESSAGE
)) {
473 Toast
.makeText(context
, R
.string
.downloader_download_failed
, Toast
.LENGTH_SHORT
).show();
479 // this is a temporary class for sharing purposes, it need to be replacead in transfer service
480 private class ShareRunnable
implements Runnable
{
481 private String mPath
;
483 public ShareRunnable(String path
) {
488 AccountManager am
= AccountManager
.get(getActivity());
489 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
490 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
491 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
493 Log
.d("share", "sharing for version " + ocv
.toString());
495 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
496 String APPS_PATH
= "/apps/files_sharing/";
497 String SHARE_PATH
= "ajax/share.php";
499 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
501 final String WEBDAV_SCRIPT
= "webdav.php";
502 final String WEBDAV_FILES_LOCATION
= "/files/";
504 WebdavClient wc
= new WebdavClient();
505 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
506 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
508 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
509 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
511 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
513 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
514 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
515 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
516 Log
.d("share", mPath
+"");
517 formparams
.add(new BasicNameValuePair("sources",mPath
));
518 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
519 formparams
.add(new BasicNameValuePair("permissions", "0"));
520 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
524 PropFindMethod find
= new PropFindMethod(url
+"/");
525 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
526 Log
.d("sharer", ""+ url
+"/");
527 wc
.setCredentials(account
.name
.substring(0, account
.name
.lastIndexOf('@')), am
.getPassword(account
));
529 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
530 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
533 int status2
= wc
.executeMethod(find
);
535 Log
.d("sharer", "propstatus "+status2
);
537 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
538 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
540 status2
= wc
.executeMethod(get
);
542 Log
.d("sharer", "getstatus "+status2
);
543 Log
.d("sharer", "" + get
.getResponseBodyAsString());
545 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
546 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
549 status
= wc
.executeMethod(post
);
550 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
551 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
553 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
554 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
556 String resp
= post
.getResponseBodyAsString();
557 Log
.d("share", ""+post
.getURI().toString());
558 Log
.d("share", "returned status " + status
);
559 Log
.d("share", " " +resp
);
561 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
565 JSONObject jsonObject
= new JSONObject (resp
);
566 String jsonStatus
= jsonObject
.getString("status");
567 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
569 String token
= jsonObject
.getString("data");
570 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
571 Log
.d("Actions:shareFile ok", "url: " + uri
);
573 } catch (HttpException e
) {
574 // TODO Auto-generated catch block
576 } catch (IOException e
) {
577 // TODO Auto-generated catch block
579 } catch (JSONException e
) {
580 // TODO Auto-generated catch block
582 } catch (Exception e
) {
583 // TODO Auto-generated catch block
587 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {