keep file in sync and initial commit for file sharing
[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 display.getSize(size);
296 int screenwidth = size.x;
297
298 Log.e("ASD", "W " + width + " SW " + screenwidth);
299
300 if (width > screenwidth) {
301 scale = (int) (Math.ceil(Math.max(height, width)/screenwidth));
302 options.inSampleSize = scale;
303 recycle = true;
304 }
305
306
307 if (recycle) bmp.recycle();
308 bmp = BitmapFactory.decodeFile(mFile.getStoragePath(), options);
309
310 }
311 if (bmp != null) {
312 preview.setImageBitmap(bmp);
313 }
314 }
315 } catch (OutOfMemoryError e) {
316 preview.setVisibility(View.INVISIBLE);
317 Log.e(TAG, "Out of memory occured for file with size " + mFile.getFileLength());
318
319 } catch (NoSuchFieldError e) {
320 preview.setVisibility(View.INVISIBLE);
321 Log.e(TAG, "Error from access to unexisting field despite protection " + mFile.getFileLength());
322
323 } catch (Throwable t) {
324 preview.setVisibility(View.INVISIBLE);
325 Log.e(TAG, "Unexpected error while creating image preview " + mFile.getFileLength(), t);
326 }
327
328 // Change download button to open button
329 downloadButton.setText(R.string.filedetails_open);
330 downloadButton.setOnClickListener(new OnClickListener() {
331 @Override
332 public void onClick(View v) {
333 String storagePath = mFile.getStoragePath();
334 try {
335 Intent i = new Intent(Intent.ACTION_VIEW);
336 i.setDataAndType(Uri.parse("file://"+ storagePath), mFile.getMimetype());
337 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
338 startActivity(i);
339
340 } catch (Throwable t) {
341 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
342 boolean toastIt = true;
343 String mimeType = "";
344 try {
345 Intent i = new Intent(Intent.ACTION_VIEW);
346 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
347 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
348 i.setDataAndType(Uri.parse("file://"+mFile.getStoragePath()), mimeType);
349 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
350 startActivity(i);
351 toastIt = false;
352 }
353
354 } catch (IndexOutOfBoundsException e) {
355 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
356
357 } catch (ActivityNotFoundException e) {
358 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
359
360 } catch (Throwable th) {
361 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
362
363 } finally {
364 if (toastIt) {
365 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
366 }
367 }
368
369 }
370 }
371 });
372 } else {
373 // Make download button effective
374 downloadButton.setOnClickListener(this);
375 }
376 }
377 }
378
379
380 /**
381 * Updates the filename in view
382 * @param filename to set
383 */
384 private void setFilename(String filename) {
385 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
386 if (tv != null)
387 tv.setText(filename);
388 }
389
390 /**
391 * Updates the MIME type in view
392 * @param mimetype to set
393 */
394 private void setFiletype(String mimetype) {
395 TextView tv = (TextView) getView().findViewById(R.id.fdType);
396 if (tv != null)
397 tv.setText(mimetype);
398 }
399
400 /**
401 * Updates the file size in view
402 * @param filesize in bytes to set
403 */
404 private void setFilesize(long filesize) {
405 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
406 if (tv != null)
407 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
408 }
409
410 /**
411 * Updates the time that the file was created in view
412 * @param milliseconds Unix time to set
413 */
414 private void setTimeCreated(long milliseconds){
415 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
416 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
417 if(tv != null){
418 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
419 tv.setVisibility(View.VISIBLE);
420 tvLabel.setVisibility(View.VISIBLE);
421 }
422 }
423
424 /**
425 * Updates the time that the file was last modified
426 * @param milliseconds Unix time to set
427 */
428 private void setTimeModified(long milliseconds){
429 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
430 if(tv != null){
431 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
432 }
433 }
434
435 /**
436 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
437 * the time that the file was created. There is a chance that this will
438 * be fixed in future versions. Use this method to check if this version of
439 * ownCloud has this fix.
440 * @return True, if ownCloud the ownCloud version is supporting creation time
441 */
442 private boolean ocVersionSupportsTimeCreated(){
443 /*if(mAccount != null){
444 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
445 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
446 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
447 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
448 return true;
449 }
450 }*/
451 return false;
452 }
453
454 /**
455 * Once the file download has finished -> update view
456 * @author Bartek Przybylski
457 */
458 private class DownloadFinishReceiver extends BroadcastReceiver {
459 @Override
460 public void onReceive(Context context, Intent intent) {
461 getView().findViewById(R.id.fdDownloadBtn).setEnabled(true);
462 if (intent.getAction().equals(FileDownloader.BAD_DOWNLOAD_MESSAGE)) {
463 Toast.makeText(context, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
464
465 } else if (intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
466 mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
467 updateFileDetails();
468 }
469 }
470
471 }
472
473 // this is a temporary class for sharing purposes, it need to be replacead in transfer service
474 private class ShareRunnable implements Runnable {
475 private String mPath;
476
477 public ShareRunnable(String path) {
478 mPath = path;
479 }
480
481 public void run() {
482 AccountManager am = AccountManager.get(getActivity());
483 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
484 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
485 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
486
487 Log.d("share", "sharing for version " + ocv.toString());
488
489 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
490 String APPS_PATH = "/apps/files_sharing/";
491 String SHARE_PATH = "ajax/share.php";
492
493 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
494
495 final String WEBDAV_SCRIPT = "webdav.php";
496 final String WEBDAV_FILES_LOCATION = "/files/";
497
498 WebdavClient wc = new WebdavClient();
499 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
500 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
501
502 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
503 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
504
505 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
506
507 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
508 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
509 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
510 Log.d("share", mPath+"");
511 formparams.add(new BasicNameValuePair("sources",mPath));
512 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
513 formparams.add(new BasicNameValuePair("permissions", "0"));
514 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
515
516 int status;
517 try {
518 PropFindMethod find = new PropFindMethod(url+"/");
519 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
520 Log.d("sharer", ""+ url+"/");
521 wc.setCredentials(account.name.substring(0, account.name.lastIndexOf('@')), am.getPassword(account));
522
523 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
524 Log.d("sharer-h", a.getName() + ":"+a.getValue());
525 }
526
527 int status2 = wc.executeMethod(find);
528
529 Log.d("sharer", "propstatus "+status2);
530
531 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
532 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
533
534 status2 = wc.executeMethod(get);
535
536 Log.d("sharer", "getstatus "+status2);
537 Log.d("sharer", "" + get.getResponseBodyAsString());
538
539 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
540 Log.d("sharer", a.getName() + ":"+a.getValue());
541 }
542
543 status = wc.executeMethod(post);
544 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
545 Log.d("sharer-h", a.getName() + ":"+a.getValue());
546 }
547 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
548 Log.d("sharer", a.getName() + ":"+a.getValue());
549 }
550 String resp = post.getResponseBodyAsString();
551 Log.d("share", ""+post.getURI().toString());
552 Log.d("share", "returned status " + status);
553 Log.d("share", " " +resp);
554
555 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
556 return;
557 }
558
559 JSONObject jsonObject = new JSONObject (resp);
560 String jsonStatus = jsonObject.getString("status");
561 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
562
563 String token = jsonObject.getString("data");
564 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
565 Log.d("Actions:shareFile ok", "url: " + uri);
566
567 } catch (HttpException e) {
568 // TODO Auto-generated catch block
569 e.printStackTrace();
570 } catch (IOException e) {
571 // TODO Auto-generated catch block
572 e.printStackTrace();
573 } catch (JSONException e) {
574 // TODO Auto-generated catch block
575 e.printStackTrace();
576 } catch (Exception e) {
577 // TODO Auto-generated catch block
578 e.printStackTrace();
579 }
580
581 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
582
583 }
584 }
585 }
586
587 }