delete file after download failed, correctly send message about download fail
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / fragment / FileDetailFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18 package eu.alefzero.owncloud.ui.fragment;
19
20 import java.io.IOException;
21 import java.util.ArrayList;
22 import java.util.List;
23
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;
40
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;
69
70 import com.actionbarsherlock.app.SherlockFragment;
71
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;
81
82 /**
83 * This Fragment is used to display the details about a file.
84 *
85 * @author Bartek Przybylski
86 *
87 */
88 public class FileDetailFragment extends SherlockFragment implements
89 OnClickListener {
90
91 public static final String EXTRA_FILE = "FILE";
92 public static final String EXTRA_ACCOUNT = "ACCOUNT";
93
94 private int mLayout;
95 private View mView;
96 private OCFile mFile;
97 private Account mAccount;
98
99 private DownloadFinishReceiver mDownloadFinishReceiver;
100
101 private static final String TAG = "FileDetailFragment";
102 public static final String FTAG = "FileDetails";
103
104
105 /**
106 * Creates an empty details fragment.
107 *
108 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
109 */
110 public FileDetailFragment() {
111 mFile = null;
112 mAccount = null;
113 mLayout = R.layout.file_details_empty;
114 }
115
116
117 /**
118 * Creates a details fragment.
119 *
120 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
121 *
122 * @param fileToDetail An {@link OCFile} to show in the fragment
123 * @param ocAccount An ownCloud account; needed to start downloads
124 */
125 public FileDetailFragment(OCFile fileToDetail, Account ocAccount){
126 mFile = fileToDetail;
127 mAccount = ocAccount;
128 mLayout = R.layout.file_details_empty;
129
130 if(fileToDetail != null && ocAccount != null) {
131 mLayout = R.layout.file_details_fragment;
132 }
133 }
134
135
136 @Override
137 public View onCreateView(LayoutInflater inflater, ViewGroup container,
138 Bundle savedInstanceState) {
139 super.onCreateView(inflater, container, savedInstanceState);
140
141 if (savedInstanceState != null) {
142 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
143 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
144 }
145
146 View view = null;
147 view = inflater.inflate(mLayout, container, false);
148 mView = view;
149
150 updateFileDetails();
151 return view;
152 }
153
154
155 @Override
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");
162 }
163
164
165 @Override
166 public void onResume() {
167 super.onResume();
168 mDownloadFinishReceiver = new DownloadFinishReceiver();
169 IntentFilter filter = new IntentFilter(
170 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
171 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
172 }
173
174 @Override
175 public void onPause() {
176 super.onPause();
177 getActivity().unregisterReceiver(mDownloadFinishReceiver);
178 mDownloadFinishReceiver = null;
179 }
180
181 @Override
182 public View getView() {
183 return super.getView() == null ? mView : super.getView();
184 }
185
186 @Override
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());
195 v.setEnabled(false);
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));
204 }
205 }/* else if (v.getId() == R.id.fdShareBtn) {
206 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
207 t.start();
208 }*/
209 }
210
211
212 /**
213 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
214 *
215 * @return True when the fragment was created with the empty layout.
216 */
217 public boolean isEmpty() {
218 return mLayout == R.layout.file_details_empty;
219 }
220
221
222 /**
223 * Can be used to get the file that is currently being displayed.
224 * @return The file on the screen.
225 */
226 public OCFile getDisplayedFile(){
227 return mFile;
228 }
229
230 /**
231 * Use this method to signal this Activity that it shall update its view.
232 *
233 * @param file : An {@link OCFile}
234 */
235 public void updateFileDetails(OCFile file, Account ocAccount) {
236 mFile = file;
237 mAccount = ocAccount;
238 updateFileDetails();
239 }
240
241
242 /**
243 * Updates the view with all relevant details about that file.
244 */
245 public void updateFileDetails() {
246
247 if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
248
249 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
250 // set file details
251 setFilename(mFile.getFileName());
252 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
253 .getMimetype()));
254 setFilesize(mFile.getFileLength());
255 if(ocVersionSupportsTimeCreated()){
256 setTimeCreated(mFile.getCreationTimestamp());
257 }
258
259 setTimeModified(mFile.getModificationTimestamp());
260
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);
265
266 if (mFile.getStoragePath() != null) {
267 // Update preview
268 ImageView preview = (ImageView) getView().findViewById(R.id.fdPreview);
269 try {
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;
276 }
277 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
278 options.inMutable = false;
279 }
280
281 Bitmap bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);
282
283 if (bmp != null) {
284 int width = options.outWidth;
285 int height = options.outHeight;
286 int scale = 1;
287 boolean recycle = false;
288 if (width >= 2048 || height >= 2048) {
289 scale = (int) (Math.ceil(Math.max(height, width)/2048.));
290 options.inSampleSize = scale;
291 recycle = true;
292 }
293 Display display = getActivity().getWindowManager().getDefaultDisplay();
294 Point size = new Point();
295 int screenwidth;
296 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
297 display.getSize(size);
298 screenwidth = size.x;
299 } else {
300 screenwidth = display.getWidth();
301 }
302
303 Log.e("ASD", "W " + width + " SW " + screenwidth);
304
305 if (width > screenwidth) {
306 scale = (int) (Math.ceil(Math.max(height, width)/screenwidth));
307 options.inSampleSize = scale;
308 recycle = true;
309 }
310
311
312 if (recycle) bmp.recycle();
313 bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);
314
315 }
316 if (bmp != null) {
317 preview.setImageBitmap(bmp);
318 }
319 }
320 } catch (OutOfMemoryError e) {
321 preview.setVisibility(View.INVISIBLE);
322 Log.e(TAG, "Out of memory occured for file with size " + mFile.getFileLength());
323
324 } catch (NoSuchFieldError e) {
325 preview.setVisibility(View.INVISIBLE);
326 Log.e(TAG, "Error from access to unexisting field despite protection " + mFile.getFileLength());
327
328 } catch (Throwable t) {
329 preview.setVisibility(View.INVISIBLE);
330 Log.e(TAG, "Unexpected error while creating image preview " + mFile.getFileLength(), t);
331 }
332
333 // Change download button to open button
334 downloadButton.setText(R.string.filedetails_open);
335 downloadButton.setOnClickListener(new OnClickListener() {
336 @Override
337 public void onClick(View v) {
338 String storagePath = mFile.getStoragePath();
339 try {
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);
343 startActivity(i);
344
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 = "";
349 try {
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);
355 startActivity(i);
356 toastIt = false;
357 }
358
359 } catch (IndexOutOfBoundsException e) {
360 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
361
362 } catch (ActivityNotFoundException e) {
363 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
364
365 } catch (Throwable th) {
366 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
367
368 } finally {
369 if (toastIt) {
370 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
371 }
372 }
373
374 }
375 }
376 });
377 } else {
378 // Make download button effective
379 downloadButton.setOnClickListener(this);
380 }
381 }
382 }
383
384
385 /**
386 * Updates the filename in view
387 * @param filename to set
388 */
389 private void setFilename(String filename) {
390 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
391 if (tv != null)
392 tv.setText(filename);
393 }
394
395 /**
396 * Updates the MIME type in view
397 * @param mimetype to set
398 */
399 private void setFiletype(String mimetype) {
400 TextView tv = (TextView) getView().findViewById(R.id.fdType);
401 if (tv != null)
402 tv.setText(mimetype);
403 }
404
405 /**
406 * Updates the file size in view
407 * @param filesize in bytes to set
408 */
409 private void setFilesize(long filesize) {
410 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
411 if (tv != null)
412 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
413 }
414
415 /**
416 * Updates the time that the file was created in view
417 * @param milliseconds Unix time to set
418 */
419 private void setTimeCreated(long milliseconds){
420 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
421 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
422 if(tv != null){
423 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
424 tv.setVisibility(View.VISIBLE);
425 tvLabel.setVisibility(View.VISIBLE);
426 }
427 }
428
429 /**
430 * Updates the time that the file was last modified
431 * @param milliseconds Unix time to set
432 */
433 private void setTimeModified(long milliseconds){
434 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
435 if(tv != null){
436 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
437 }
438 }
439
440 /**
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
446 */
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) {
453 return true;
454 }
455 }*/
456 return false;
457 }
458
459 /**
460 * Once the file download has finished -> update view
461 * @author Bartek Przybylski
462 */
463 private class DownloadFinishReceiver extends BroadcastReceiver {
464 @Override
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);
468
469 if (intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false)) {
470 mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
471 updateFileDetails();
472 } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
473 Toast.makeText(context, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
474 }
475 }
476
477 }
478
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;
482
483 public ShareRunnable(String path) {
484 mPath = path;
485 }
486
487 public void run() {
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);
492
493 Log.d("share", "sharing for version " + ocv.toString());
494
495 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
496 String APPS_PATH = "/apps/files_sharing/";
497 String SHARE_PATH = "ajax/share.php";
498
499 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
500
501 final String WEBDAV_SCRIPT = "webdav.php";
502 final String WEBDAV_FILES_LOCATION = "/files/";
503
504 WebdavClient wc = new WebdavClient();
505 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
506 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
507
508 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
509 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
510
511 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
512
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)));
521
522 int status;
523 try {
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));
528
529 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
530 Log.d("sharer-h", a.getName() + ":"+a.getValue());
531 }
532
533 int status2 = wc.executeMethod(find);
534
535 Log.d("sharer", "propstatus "+status2);
536
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));
539
540 status2 = wc.executeMethod(get);
541
542 Log.d("sharer", "getstatus "+status2);
543 Log.d("sharer", "" + get.getResponseBodyAsString());
544
545 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
546 Log.d("sharer", a.getName() + ":"+a.getValue());
547 }
548
549 status = wc.executeMethod(post);
550 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
551 Log.d("sharer-h", a.getName() + ":"+a.getValue());
552 }
553 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
554 Log.d("sharer", a.getName() + ":"+a.getValue());
555 }
556 String resp = post.getResponseBodyAsString();
557 Log.d("share", ""+post.getURI().toString());
558 Log.d("share", "returned status " + status);
559 Log.d("share", " " +resp);
560
561 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
562 return;
563 }
564
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");
568
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);
572
573 } catch (HttpException e) {
574 // TODO Auto-generated catch block
575 e.printStackTrace();
576 } catch (IOException e) {
577 // TODO Auto-generated catch block
578 e.printStackTrace();
579 } catch (JSONException e) {
580 // TODO Auto-generated catch block
581 e.printStackTrace();
582 } catch (Exception e) {
583 // TODO Auto-generated catch block
584 e.printStackTrace();
585 }
586
587 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
588
589 }
590 }
591 }
592
593 }