ad6f60474f4227732458da666fceb42c27d7ff7c
[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.File;
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.List;
24
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;
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.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;
71
72 import com.actionbarsherlock.app.SherlockDialogFragment;
73 import com.actionbarsherlock.app.SherlockFragment;
74
75 import eu.alefzero.owncloud.AccountUtils;
76 import eu.alefzero.owncloud.DisplayUtils;
77 import eu.alefzero.owncloud.R;
78 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
79 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
80 import eu.alefzero.owncloud.datamodel.OCFile;
81 import eu.alefzero.owncloud.files.services.FileDownloader;
82 import eu.alefzero.owncloud.files.services.FileUploader;
83 import eu.alefzero.owncloud.ui.activity.FileDisplayActivity;
84 import eu.alefzero.owncloud.utils.OwnCloudVersion;
85 import eu.alefzero.webdav.WebdavClient;
86 import eu.alefzero.webdav.WebdavUtils;
87
88 /**
89 * This Fragment is used to display the details about a file.
90 *
91 * @author Bartek Przybylski
92 *
93 */
94 public class FileDetailFragment extends SherlockFragment implements
95 OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
96
97 public static final String EXTRA_FILE = "FILE";
98 public static final String EXTRA_ACCOUNT = "ACCOUNT";
99
100 private int mLayout;
101 private View mView;
102 private OCFile mFile;
103 private Account mAccount;
104 private ImageView mPreview;
105
106 private DownloadFinishReceiver mDownloadFinishReceiver;
107
108 private static final String TAG = "FileDetailFragment";
109 public static final String FTAG = "FileDetails";
110 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
111
112
113 /**
114 * Creates an empty details fragment.
115 *
116 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
117 */
118 public FileDetailFragment() {
119 mFile = null;
120 mAccount = null;
121 mLayout = R.layout.file_details_empty;
122 }
123
124
125 /**
126 * Creates a details fragment.
127 *
128 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
129 *
130 * @param fileToDetail An {@link OCFile} to show in the fragment
131 * @param ocAccount An ownCloud account; needed to start downloads
132 */
133 public FileDetailFragment(OCFile fileToDetail, Account ocAccount){
134 mFile = fileToDetail;
135 mAccount = ocAccount;
136 mLayout = R.layout.file_details_empty;
137
138 if(fileToDetail != null && ocAccount != null) {
139 mLayout = R.layout.file_details_fragment;
140 }
141 }
142
143
144 @Override
145 public View onCreateView(LayoutInflater inflater, ViewGroup container,
146 Bundle savedInstanceState) {
147 super.onCreateView(inflater, container, savedInstanceState);
148
149 if (savedInstanceState != null) {
150 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
151 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
152 }
153
154 View view = null;
155 view = inflater.inflate(mLayout, container, false);
156 mView = view;
157
158 if (mLayout == R.layout.file_details_fragment) {
159 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
160 mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
161 mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
162 mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
163 mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
164 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
165 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
166 }
167
168 updateFileDetails();
169 return view;
170 }
171
172
173 @Override
174 public void onSaveInstanceState(Bundle outState) {
175 Log.i(getClass().toString(), "onSaveInstanceState() start");
176 super.onSaveInstanceState(outState);
177 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
178 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
179 Log.i(getClass().toString(), "onSaveInstanceState() end");
180 }
181
182
183 @Override
184 public void onResume() {
185 super.onResume();
186 mDownloadFinishReceiver = new DownloadFinishReceiver();
187 IntentFilter filter = new IntentFilter(
188 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
189 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
190 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
191 }
192
193 @Override
194 public void onPause() {
195 super.onPause();
196 getActivity().unregisterReceiver(mDownloadFinishReceiver);
197 mDownloadFinishReceiver = null;
198 if (mPreview != null) {
199 mPreview = null;
200 }
201 }
202
203 @Override
204 public View getView() {
205 return super.getView() == null ? mView : super.getView();
206 }
207
208
209
210 @Override
211 public void onClick(View v) {
212 switch (v.getId()) {
213 case R.id.fdDownloadBtn: {
214 Intent i = new Intent(getActivity(), FileDownloader.class);
215 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
216 i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
217 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
218 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());
219
220 // update ui
221 setButtonsForDownloading();
222
223 getActivity().startService(i);
224 break;
225 }
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));
233 }
234 break;
235 }
236 case R.id.fdRenameBtn: {
237 EditNameFragment dialog = EditNameFragment.newInstance(mFile.getFileName());
238 dialog.show(getFragmentManager(), "nameeditdialog");
239 dialog.setOnDismissListener(this);
240 break;
241 }
242 case R.id.fdRemoveBtn: {
243 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(R.string.confirmation_remove_alert, new String[]{mFile.getFileName()});
244 confDialog.setOnConfirmationListener(this);
245 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
246 break;
247 }
248 case R.id.fdOpenBtn: {
249 String storagePath = mFile.getStoragePath();
250 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
251 try {
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);
255 startActivity(i);
256
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 = "";
261 try {
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);
267 startActivity(i);
268 toastIt = false;
269 }
270
271 } catch (IndexOutOfBoundsException e) {
272 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
273
274 } catch (ActivityNotFoundException e) {
275 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
276
277 } catch (Throwable th) {
278 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
279
280 } finally {
281 if (toastIt) {
282 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
283 }
284 }
285
286 }
287 break;
288 }
289 default:
290 Log.e(TAG, "Incorrect view clicked!");
291 }
292
293 /* else if (v.getId() == R.id.fdShareBtn) {
294 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
295 t.start();
296 }*/
297 }
298
299
300 @Override
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();
307 }
308 } else if (!confirmation) Log.d(TAG, "REMOVAL CANCELED");
309 }
310
311
312 /**
313 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
314 *
315 * @return True when the fragment was created with the empty layout.
316 */
317 public boolean isEmpty() {
318 return mLayout == R.layout.file_details_empty;
319 }
320
321
322 /**
323 * Can be used to get the file that is currently being displayed.
324 * @return The file on the screen.
325 */
326 public OCFile getDisplayedFile(){
327 return mFile;
328 }
329
330 /**
331 * Use this method to signal this Activity that it shall update its view.
332 *
333 * @param file : An {@link OCFile}
334 */
335 public void updateFileDetails(OCFile file, Account ocAccount) {
336 mFile = file;
337 mAccount = ocAccount;
338 updateFileDetails();
339 }
340
341
342 /**
343 * Updates the view with all relevant details about that file.
344 */
345 public void updateFileDetails() {
346
347 if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
348
349 // set file details
350 setFilename(mFile.getFileName());
351 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
352 .getMimetype()));
353 setFilesize(mFile.getFileLength());
354 if(ocVersionSupportsTimeCreated()){
355 setTimeCreated(mFile.getCreationTimestamp());
356 }
357
358 setTimeModified(mFile.getModificationTimestamp());
359
360 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
361 cb.setChecked(mFile.keepInSync());
362
363 // configure UI for depending upon local state of the file
364 if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
365 setButtonsForDownloading();
366
367 } else if (mFile.isDown()) {
368 // Update preview
369 if (mFile.getMimetype().startsWith("image/")) {
370 BitmapLoader bl = new BitmapLoader();
371 bl.execute(new String[]{mFile.getStoragePath()});
372 }
373
374 setButtonsForDown();
375
376 // Change download button to open button
377 /*downloadButton.setText(R.string.filedetails_open);
378 downloadButton.setOnClickListener(new OnClickListener() {
379 @Override
380 public void onClick(View v) {
381 String storagePath = mFile.getStoragePath();
382 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
383 try {
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);
387 startActivity(i);
388
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 = "";
393 try {
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);
399 startActivity(i);
400 toastIt = false;
401 }
402
403 } catch (IndexOutOfBoundsException e) {
404 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
405
406 } catch (ActivityNotFoundException e) {
407 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
408
409 } catch (Throwable th) {
410 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
411
412 } finally {
413 if (toastIt) {
414 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
415 }
416 }
417
418 }
419 }
420 });*/
421 } else {
422 setButtonsForRemote();
423 }
424 }
425 }
426
427
428 /**
429 * Updates the filename in view
430 * @param filename to set
431 */
432 private void setFilename(String filename) {
433 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
434 if (tv != null)
435 tv.setText(filename);
436 }
437
438 /**
439 * Updates the MIME type in view
440 * @param mimetype to set
441 */
442 private void setFiletype(String mimetype) {
443 TextView tv = (TextView) getView().findViewById(R.id.fdType);
444 if (tv != null)
445 tv.setText(mimetype);
446 }
447
448 /**
449 * Updates the file size in view
450 * @param filesize in bytes to set
451 */
452 private void setFilesize(long filesize) {
453 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
454 if (tv != null)
455 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
456 }
457
458 /**
459 * Updates the time that the file was created in view
460 * @param milliseconds Unix time to set
461 */
462 private void setTimeCreated(long milliseconds){
463 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
464 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
465 if(tv != null){
466 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
467 tv.setVisibility(View.VISIBLE);
468 tvLabel.setVisibility(View.VISIBLE);
469 }
470 }
471
472 /**
473 * Updates the time that the file was last modified
474 * @param milliseconds Unix time to set
475 */
476 private void setTimeModified(long milliseconds){
477 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
478 if(tv != null){
479 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
480 }
481 }
482
483 /**
484 * Enables or disables buttons for a file being downloaded
485 */
486 private void setButtonsForDownloading() {
487 if (!isEmpty()) {
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
491
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);
496 }
497 }
498
499 /**
500 * Enables or disables buttons for a file locally available
501 */
502 private void setButtonsForDown() {
503 if (!isEmpty()) {
504 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
505 downloadButton.setText(R.string.filedetails_redownload);
506 downloadButton.setEnabled(true);
507
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);
511 }
512 }
513
514 /**
515 * Enables or disables buttons for a file not locally available
516 */
517 private void setButtonsForRemote() {
518 if (!isEmpty()) {
519 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
520 downloadButton.setText(R.string.filedetails_download);
521 downloadButton.setEnabled(true);
522
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);
526 }
527 }
528
529
530 /**
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
536 */
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) {
543 return true;
544 }
545 }*/
546 return false;
547 }
548
549 /**
550 * Once the file download has finished -> update view
551 * @author Bartek Przybylski
552 */
553 private class DownloadFinishReceiver extends BroadcastReceiver {
554 @Override
555 public void onReceive(Context context, Intent intent) {
556 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
557
558 if (!isEmpty() && accountName.equals(mAccount.name)) {
559 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
560 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
561 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
562 if (downloadWasFine) {
563 mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
564 }
565 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
566 }
567 }
568 }
569 }
570
571 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
572 private class ShareRunnable implements Runnable {
573 private String mPath;
574
575 public ShareRunnable(String path) {
576 mPath = path;
577 }
578
579 public void run() {
580 AccountManager am = AccountManager.get(getActivity());
581 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
582 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
583 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
584
585 Log.d("share", "sharing for version " + ocv.toString());
586
587 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
588 String APPS_PATH = "/apps/files_sharing/";
589 String SHARE_PATH = "ajax/share.php";
590
591 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
592
593 final String WEBDAV_SCRIPT = "webdav.php";
594 final String WEBDAV_FILES_LOCATION = "/files/";
595
596 WebdavClient wc = new WebdavClient();
597 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
598 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
599
600 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
601 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
602
603 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
604
605 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
606 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
607 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
608 Log.d("share", mPath+"");
609 formparams.add(new BasicNameValuePair("sources",mPath));
610 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
611 formparams.add(new BasicNameValuePair("permissions", "0"));
612 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
613
614 int status;
615 try {
616 PropFindMethod find = new PropFindMethod(url+"/");
617 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
618 Log.d("sharer", ""+ url+"/");
619 wc.setCredentials(account.name.substring(0, account.name.lastIndexOf('@')), am.getPassword(account));
620
621 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
622 Log.d("sharer-h", a.getName() + ":"+a.getValue());
623 }
624
625 int status2 = wc.executeMethod(find);
626
627 Log.d("sharer", "propstatus "+status2);
628
629 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
630 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
631
632 status2 = wc.executeMethod(get);
633
634 Log.d("sharer", "getstatus "+status2);
635 Log.d("sharer", "" + get.getResponseBodyAsString());
636
637 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
638 Log.d("sharer", a.getName() + ":"+a.getValue());
639 }
640
641 status = wc.executeMethod(post);
642 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
643 Log.d("sharer-h", a.getName() + ":"+a.getValue());
644 }
645 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
646 Log.d("sharer", a.getName() + ":"+a.getValue());
647 }
648 String resp = post.getResponseBodyAsString();
649 Log.d("share", ""+post.getURI().toString());
650 Log.d("share", "returned status " + status);
651 Log.d("share", " " +resp);
652
653 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
654 return;
655 }
656
657 JSONObject jsonObject = new JSONObject (resp);
658 String jsonStatus = jsonObject.getString("status");
659 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
660
661 String token = jsonObject.getString("data");
662 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
663 Log.d("Actions:shareFile ok", "url: " + uri);
664
665 } catch (HttpException e) {
666 // TODO Auto-generated catch block
667 e.printStackTrace();
668 } catch (IOException e) {
669 // TODO Auto-generated catch block
670 e.printStackTrace();
671 } catch (JSONException e) {
672 // TODO Auto-generated catch block
673 e.printStackTrace();
674 } catch (Exception e) {
675 // TODO Auto-generated catch block
676 e.printStackTrace();
677 }
678
679 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
680
681 }
682 }
683 }
684
685 public void onDismiss(EditNameFragment dialog) {
686 if (dialog instanceof EditNameFragment) {
687 if (((EditNameFragment)dialog).getResult()) {
688 String newFilename = ((EditNameFragment)dialog).getNewFilename();
689 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
690 if (!newFilename.equals(mFile.getFileName())) {
691 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
692 if (fdsm.getFileById(mFile.getFileId()) != null) {
693 OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename);
694 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
695 newFile.setFileId(mFile.getFileId());
696 newFile.setFileLength(mFile.getFileLength());
697 newFile.setKeepInSync(mFile.keepInSync());
698 newFile.setLastSyncDate(mFile.getLastSyncDate());
699 newFile.setMimetype(mFile.getMimetype());
700 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
701 newFile.setParentId(mFile.getParentId());
702 if (mFile.isDown()) {
703 File f = new File(mFile.getStoragePath());
704 Log.e(TAG, f.getAbsolutePath());
705 f.renameTo(new File(f.getParent() + File.separator + newFilename)); // TODO check if fails
706 Log.e(TAG, f.getParent() + File.separator + newFilename);
707 newFile.setStoragePath(f.getParent() + File.separator + newFilename);
708 }
709
710 new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start();
711
712 }
713 }
714 }
715 } else {
716 Log.e(TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());
717 }
718
719 }
720
721 private class RenameRunnable implements Runnable {
722
723 Account mAccount;
724 OCFile mOld, mNew;
725 Handler mHandler;
726
727 public RenameRunnable(OCFile oldFile, OCFile newFile, Account account, Handler handler) {
728 mOld = oldFile;
729 mNew = newFile;
730 mAccount = account;
731 mHandler = handler;
732 }
733
734 public void run() {
735 WebdavClient wc = new WebdavClient(mAccount, getSherlockActivity().getApplicationContext());
736 wc.allowSelfsignedCertificates();
737 AccountManager am = AccountManager.get(getSherlockActivity());
738 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
739 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
740 String webdav_path = AccountUtils.getWebdavPath(ocv);
741 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));
742
743 Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
744 LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),
745 Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
746
747 try {
748 int status = wc.executeMethod(move);
749 if (move.succeeded()) {
750 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
751 fdsm.removeFile(mOld);
752 fdsm.saveFile(mNew);
753 mFile = mNew;
754 mHandler.post(new Runnable() {
755 @Override
756 public void run() { updateFileDetails(mFile, mAccount); }
757 });
758 }
759 Log.e("ASD", ""+move.getQueryString());
760 Log.d("move", "returned status " + status);
761 } catch (HttpException e) {
762 // TODO Auto-generated catch block
763 e.printStackTrace();
764 } catch (IOException e) {
765 // TODO Auto-generated catch block
766 e.printStackTrace();
767 }
768 }
769 private class LocalMoveMethod extends DavMethodBase {
770
771 public LocalMoveMethod(String uri, String dest) {
772 super(uri);
773 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
774 }
775
776 @Override
777 public String getName() {
778 return "MOVE";
779 }
780
781 @Override
782 protected boolean isSuccess(int status) {
783 return status == 201 || status == 204;
784 }
785
786 }
787 }
788
789 private static class EditNameFragment extends SherlockDialogFragment implements OnClickListener {
790
791 private String mNewFilename;
792 private boolean mResult;
793 private FileDetailFragment mListener;
794
795 static public EditNameFragment newInstance(String filename) {
796 EditNameFragment f = new EditNameFragment();
797 Bundle args = new Bundle();
798 args.putString("filename", filename);
799 f.setArguments(args);
800 return f;
801 }
802
803 @Override
804 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
805 View v = inflater.inflate(R.layout.edit_box_dialog, container, false);
806
807 String currentName = getArguments().getString("filename");
808 if (currentName == null)
809 currentName = "";
810
811 ((Button)v.findViewById(R.id.cancel)).setOnClickListener(this);
812 ((Button)v.findViewById(R.id.ok)).setOnClickListener(this);
813 ((TextView)v.findViewById(R.id.user_input)).setText(currentName);
814 ((TextView)v.findViewById(R.id.user_input)).requestFocus();
815 getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
816
817 mResult = false;
818 return v;
819 }
820
821 @Override
822 public void onClick(View view) {
823 switch (view.getId()) {
824 case R.id.ok: {
825 mNewFilename = ((TextView)getView().findViewById(R.id.user_input)).getText().toString();
826 mResult = true;
827 }
828 case R.id.cancel: { // fallthought
829 dismiss();
830 mListener.onDismiss(this);
831 }
832 }
833 }
834
835 void setOnDismissListener(FileDetailFragment listener) {
836 mListener = listener;
837 }
838
839 public String getNewFilename() {
840 return mNewFilename;
841 }
842
843 // true if user click ok
844 public boolean getResult() {
845 return mResult;
846 }
847
848 }
849
850 private class RemoveRunnable implements Runnable {
851
852 /** Arbitrary timeout for deletion */
853 public final static int DELETION_TIMEOUT = 5000;
854
855 Account mAccount;
856 OCFile mFileToRemove;
857 Handler mHandler;
858
859 public RemoveRunnable(OCFile fileToRemove, Account account, Handler handler) {
860 mFileToRemove = fileToRemove;
861 mAccount = account;
862 mHandler = handler;
863 }
864
865 public void run() {
866 WebdavClient wc = new WebdavClient(mAccount, getSherlockActivity().getApplicationContext());
867 wc.allowSelfsignedCertificates();
868 AccountManager am = AccountManager.get(getSherlockActivity());
869 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
870 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
871 String webdav_path = AccountUtils.getWebdavPath(ocv);
872 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
873
874 DeleteMethod delete = new DeleteMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
875
876 boolean success = false;
877 try {
878 int status = wc.executeMethod(delete, DELETION_TIMEOUT);
879 if (delete.succeeded()) {
880 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
881 fdsm.removeFile(mFileToRemove);
882 mHandler.post(new Runnable() {
883 @Override
884 public void run() {
885 try {
886 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
887 msg.show();
888 if (getActivity() instanceof FileDisplayActivity) {
889 // double pane
890 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
891 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
892 transaction.commit();
893
894 } else {
895 getActivity().finish();
896 }
897
898 } catch (NotFoundException e) {
899 e.printStackTrace();
900 }
901 }
902 });
903 success = true;
904 }
905 Log.e("ASD", ""+ delete.getQueryString());
906 Log.d("delete", "returned status " + status);
907
908 } catch (HttpException e) {
909 e.printStackTrace();
910
911 } catch (IOException e) {
912 e.printStackTrace();
913
914 } finally {
915 if (!success) {
916 mHandler.post(new Runnable() {
917 @Override
918 public void run() {
919 try {
920 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
921 msg.show();
922
923 } catch (NotFoundException e) {
924 e.printStackTrace();
925 }
926 }
927 });
928 }
929 }
930 }
931
932 }
933
934 class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
935 @Override
936 protected Bitmap doInBackground(String... params) {
937 Bitmap result = null;
938 if (params.length != 1) return result;
939 String storagePath = params[0];
940 try {
941
942 BitmapFactory.Options options = new Options();
943 options.inScaled = true;
944 options.inPurgeable = true;
945 options.inJustDecodeBounds = true;
946 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
947 options.inPreferQualityOverSpeed = false;
948 }
949 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
950 options.inMutable = false;
951 }
952
953 result = BitmapFactory.decodeFile(storagePath, options);
954 options.inJustDecodeBounds = false;
955
956 int width = options.outWidth;
957 int height = options.outHeight;
958 int scale = 1;
959 boolean recycle = false;
960 if (width >= 2048 || height >= 2048) {
961 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
962 options.inSampleSize = scale;
963 }
964 Display display = getActivity().getWindowManager().getDefaultDisplay();
965 Point size = new Point();
966 int screenwidth;
967 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
968 display.getSize(size);
969 screenwidth = size.x;
970 } else {
971 screenwidth = display.getWidth();
972 }
973
974 Log.e("ASD", "W " + width + " SW " + screenwidth);
975
976 if (width > screenwidth) {
977 scale = (int) Math.ceil((float)width / screenwidth);
978 options.inSampleSize = scale;
979 }
980
981 result = BitmapFactory.decodeFile(storagePath, options);
982
983 Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
984
985 } catch (OutOfMemoryError e) {
986 result = null;
987 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
988
989 } catch (NoSuchFieldError e) {
990 result = null;
991 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
992
993 } catch (Throwable t) {
994 result = null;
995 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
996 }
997 return result;
998 }
999 @Override
1000 protected void onPostExecute(Bitmap result) {
1001 if (result != null && mPreview != null) {
1002 mPreview.setImageBitmap(result);
1003 }
1004 }
1005
1006 }
1007
1008
1009 }