More robust instant photo uploads
[pub/Android/ownCloud.git] / src / com / owncloud / android / 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 com.owncloud.android.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.annotation.SuppressLint;
44 import android.app.Activity;
45 import android.content.ActivityNotFoundException;
46 import android.content.BroadcastReceiver;
47 import android.content.Context;
48 import android.content.Intent;
49 import android.content.IntentFilter;
50 import android.content.res.Resources.NotFoundException;
51 import android.graphics.Bitmap;
52 import android.graphics.BitmapFactory;
53 import android.graphics.BitmapFactory.Options;
54 import android.graphics.Point;
55 import android.net.Uri;
56 import android.os.AsyncTask;
57 import android.os.Bundle;
58 import android.os.Handler;
59 import android.support.v4.app.FragmentTransaction;
60 import android.util.Log;
61 import android.view.Display;
62 import android.view.LayoutInflater;
63 import android.view.View;
64 import android.view.View.OnClickListener;
65 import android.view.ViewGroup;
66 import android.view.WindowManager.LayoutParams;
67 import android.webkit.MimeTypeMap;
68 import android.widget.Button;
69 import android.widget.CheckBox;
70 import android.widget.ImageView;
71 import android.widget.TextView;
72 import android.widget.Toast;
73
74 import com.actionbarsherlock.app.SherlockDialogFragment;
75 import com.actionbarsherlock.app.SherlockFragment;
76 import com.owncloud.android.AccountUtils;
77 import com.owncloud.android.DisplayUtils;
78 import com.owncloud.android.authenticator.AccountAuthenticator;
79 import com.owncloud.android.datamodel.FileDataStorageManager;
80 import com.owncloud.android.datamodel.OCFile;
81 import com.owncloud.android.files.services.FileDownloader;
82 import com.owncloud.android.files.services.FileUploader;
83 import com.owncloud.android.ui.activity.FileDetailActivity;
84 import com.owncloud.android.ui.activity.FileDisplayActivity;
85 import com.owncloud.android.utils.OwnCloudClientUtils;
86 import com.owncloud.android.utils.OwnCloudVersion;
87
88 import com.owncloud.android.R;
89 import eu.alefzero.webdav.WebdavClient;
90 import eu.alefzero.webdav.WebdavUtils;
91
92 /**
93 * This Fragment is used to display the details about a file.
94 *
95 * @author Bartek Przybylski
96 *
97 */
98 public class FileDetailFragment extends SherlockFragment implements
99 OnClickListener, ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
100
101 public static final String EXTRA_FILE = "FILE";
102 public static final String EXTRA_ACCOUNT = "ACCOUNT";
103
104 private FileDetailFragment.ContainerActivity mContainerActivity;
105
106 private int mLayout;
107 private View mView;
108 private OCFile mFile;
109 private Account mAccount;
110 private ImageView mPreview;
111
112 private DownloadFinishReceiver mDownloadFinishReceiver;
113 private UploadFinishReceiver mUploadFinishReceiver;
114
115 private static final String TAG = "FileDetailFragment";
116 public static final String FTAG = "FileDetails";
117 public static final String FTAG_CONFIRMATION = "REMOVE_CONFIRMATION_FRAGMENT";
118
119
120 /**
121 * Creates an empty details fragment.
122 *
123 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
124 */
125 public FileDetailFragment() {
126 mFile = null;
127 mAccount = null;
128 mLayout = R.layout.file_details_empty;
129 }
130
131
132 /**
133 * Creates a details fragment.
134 *
135 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
136 *
137 * @param fileToDetail An {@link OCFile} to show in the fragment
138 * @param ocAccount An ownCloud account; needed to start downloads
139 */
140 public FileDetailFragment(OCFile fileToDetail, Account ocAccount){
141 mFile = fileToDetail;
142 mAccount = ocAccount;
143 mLayout = R.layout.file_details_empty;
144
145 if(fileToDetail != null && ocAccount != null) {
146 mLayout = R.layout.file_details_fragment;
147 }
148 }
149
150
151 /**
152 * {@inheritDoc}
153 */
154 @Override
155 public void onAttach(Activity activity) {
156 super.onAttach(activity);
157 try {
158 mContainerActivity = (ContainerActivity) activity;
159 } catch (ClassCastException e) {
160 throw new ClassCastException(activity.toString() + " must implement FileListFragment.ContainerActivity");
161 }
162 }
163
164
165 @Override
166 public View onCreateView(LayoutInflater inflater, ViewGroup container,
167 Bundle savedInstanceState) {
168 super.onCreateView(inflater, container, savedInstanceState);
169
170 if (savedInstanceState != null) {
171 mFile = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
172 mAccount = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_ACCOUNT);
173 }
174
175 View view = null;
176 view = inflater.inflate(mLayout, container, false);
177 mView = view;
178
179 if (mLayout == R.layout.file_details_fragment) {
180 mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
181 mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
182 mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
183 mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
184 mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
185 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
186 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
187 }
188
189 updateFileDetails();
190 return view;
191 }
192
193
194 @Override
195 public void onSaveInstanceState(Bundle outState) {
196 Log.i(getClass().toString(), "onSaveInstanceState() start");
197 super.onSaveInstanceState(outState);
198 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mFile);
199 outState.putParcelable(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
200 Log.i(getClass().toString(), "onSaveInstanceState() end");
201 }
202
203
204 @Override
205 public void onResume() {
206 super.onResume();
207
208 mDownloadFinishReceiver = new DownloadFinishReceiver();
209 IntentFilter filter = new IntentFilter(
210 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
211 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
212
213 mUploadFinishReceiver = new UploadFinishReceiver();
214 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
215 getActivity().registerReceiver(mUploadFinishReceiver, filter);
216
217 mPreview = (ImageView)mView.findViewById(R.id.fdPreview);
218 }
219
220 @Override
221 public void onPause() {
222 super.onPause();
223
224 getActivity().unregisterReceiver(mDownloadFinishReceiver);
225 mDownloadFinishReceiver = null;
226
227 getActivity().unregisterReceiver(mUploadFinishReceiver);
228 mUploadFinishReceiver = null;
229
230 if (mPreview != null) {
231 mPreview = null;
232 }
233 }
234
235 @Override
236 public View getView() {
237 return super.getView() == null ? mView : super.getView();
238 }
239
240
241
242 @Override
243 public void onClick(View v) {
244 switch (v.getId()) {
245 case R.id.fdDownloadBtn: {
246 Intent i = new Intent(getActivity(), FileDownloader.class);
247 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
248 i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
249 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
250 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());
251
252 // update ui
253 setButtonsForTransferring();
254
255 getActivity().startService(i);
256 mContainerActivity.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
257 break;
258 }
259 case R.id.fdKeepInSync: {
260 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
261 mFile.setKeepInSync(cb.isChecked());
262 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
263 fdsm.saveFile(mFile);
264 if (mFile.keepInSync()) {
265 onClick(getView().findViewById(R.id.fdDownloadBtn));
266 } else {
267 mContainerActivity.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
268 }
269 break;
270 }
271 case R.id.fdRenameBtn: {
272 EditNameFragment dialog = EditNameFragment.newInstance(mFile.getFileName());
273 dialog.show(getFragmentManager(), "nameeditdialog");
274 dialog.setOnDismissListener(this);
275 break;
276 }
277 case R.id.fdRemoveBtn: {
278 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
279 R.string.confirmation_remove_alert,
280 new String[]{mFile.getFileName()},
281 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
282 mFile.isDown() ? R.string.confirmation_remove_local : -1,
283 R.string.common_cancel);
284 confDialog.setOnConfirmationListener(this);
285 confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
286 break;
287 }
288 case R.id.fdOpenBtn: {
289 String storagePath = mFile.getStoragePath();
290 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
291 try {
292 Intent i = new Intent(Intent.ACTION_VIEW);
293 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
294 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
295 startActivity(i);
296
297 } catch (Throwable t) {
298 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
299 boolean toastIt = true;
300 String mimeType = "";
301 try {
302 Intent i = new Intent(Intent.ACTION_VIEW);
303 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
304 if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
305 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
306 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
307 startActivity(i);
308 toastIt = false;
309 }
310
311 } catch (IndexOutOfBoundsException e) {
312 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
313
314 } catch (ActivityNotFoundException e) {
315 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
316
317 } catch (Throwable th) {
318 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
319
320 } finally {
321 if (toastIt) {
322 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
323 }
324 }
325
326 }
327 break;
328 }
329 default:
330 Log.e(TAG, "Incorrect view clicked!");
331 }
332
333 /* else if (v.getId() == R.id.fdShareBtn) {
334 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
335 t.start();
336 }*/
337 }
338
339
340 @Override
341 public void onConfirmation(String callerTag) {
342 if (callerTag.equals(FTAG_CONFIRMATION)) {
343 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
344 if (fdsm.getFileById(mFile.getFileId()) != null) {
345 new Thread(new RemoveRunnable(mFile, mAccount, new Handler())).start();
346 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
347 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
348 }
349 }
350 }
351
352 @Override
353 public void onNeutral(String callerTag) {
354 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
355 File f = null;
356 if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) {
357 f.delete();
358 mFile.setStoragePath(null);
359 fdsm.saveFile(mFile);
360 updateFileDetails(mFile, mAccount);
361 }
362 }
363
364 @Override
365 public void onCancel(String callerTag) {
366 Log.d(TAG, "REMOVAL CANCELED");
367 }
368
369
370 /**
371 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
372 *
373 * @return True when the fragment was created with the empty layout.
374 */
375 public boolean isEmpty() {
376 return mLayout == R.layout.file_details_empty;
377 }
378
379
380 /**
381 * Can be used to get the file that is currently being displayed.
382 * @return The file on the screen.
383 */
384 public OCFile getDisplayedFile(){
385 return mFile;
386 }
387
388 /**
389 * Use this method to signal this Activity that it shall update its view.
390 *
391 * @param file : An {@link OCFile}
392 */
393 public void updateFileDetails(OCFile file, Account ocAccount) {
394 mFile = file;
395 mAccount = ocAccount;
396 updateFileDetails();
397 }
398
399
400 /**
401 * Updates the view with all relevant details about that file.
402 */
403 public void updateFileDetails() {
404
405 if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {
406
407 // set file details
408 setFilename(mFile.getFileName());
409 setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile
410 .getMimetype()));
411 setFilesize(mFile.getFileLength());
412 if(ocVersionSupportsTimeCreated()){
413 setTimeCreated(mFile.getCreationTimestamp());
414 }
415
416 setTimeModified(mFile.getModificationTimestamp());
417
418 CheckBox cb = (CheckBox)getView().findViewById(R.id.fdKeepInSync);
419 cb.setChecked(mFile.keepInSync());
420
421 // configure UI for depending upon local state of the file
422 if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
423 setButtonsForTransferring();
424
425 } else if (mFile.isDown()) {
426 // Update preview
427 if (mFile.getMimetype().startsWith("image/")) {
428 BitmapLoader bl = new BitmapLoader();
429 bl.execute(new String[]{mFile.getStoragePath()});
430 }
431
432 setButtonsForDown();
433
434 } else {
435 setButtonsForRemote();
436 }
437 }
438 }
439
440
441 /**
442 * Updates the filename in view
443 * @param filename to set
444 */
445 private void setFilename(String filename) {
446 TextView tv = (TextView) getView().findViewById(R.id.fdFilename);
447 if (tv != null)
448 tv.setText(filename);
449 }
450
451 /**
452 * Updates the MIME type in view
453 * @param mimetype to set
454 */
455 private void setFiletype(String mimetype) {
456 TextView tv = (TextView) getView().findViewById(R.id.fdType);
457 if (tv != null)
458 tv.setText(mimetype);
459 }
460
461 /**
462 * Updates the file size in view
463 * @param filesize in bytes to set
464 */
465 private void setFilesize(long filesize) {
466 TextView tv = (TextView) getView().findViewById(R.id.fdSize);
467 if (tv != null)
468 tv.setText(DisplayUtils.bytesToHumanReadable(filesize));
469 }
470
471 /**
472 * Updates the time that the file was created in view
473 * @param milliseconds Unix time to set
474 */
475 private void setTimeCreated(long milliseconds){
476 TextView tv = (TextView) getView().findViewById(R.id.fdCreated);
477 TextView tvLabel = (TextView) getView().findViewById(R.id.fdCreatedLabel);
478 if(tv != null){
479 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
480 tv.setVisibility(View.VISIBLE);
481 tvLabel.setVisibility(View.VISIBLE);
482 }
483 }
484
485 /**
486 * Updates the time that the file was last modified
487 * @param milliseconds Unix time to set
488 */
489 private void setTimeModified(long milliseconds){
490 TextView tv = (TextView) getView().findViewById(R.id.fdModified);
491 if(tv != null){
492 tv.setText(DisplayUtils.unixTimeToHumanReadable(milliseconds));
493 }
494 }
495
496 /**
497 * Enables or disables buttons for a file being downloaded
498 */
499 private void setButtonsForTransferring() {
500 if (!isEmpty()) {
501 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
502 //downloadButton.setText(R.string.filedetails_download_in_progress); // ugly
503 downloadButton.setEnabled(false); // TODO replace it with a 'cancel download' button
504
505 // let's protect the user from himself ;)
506 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
507 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(false);
508 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(false);
509 }
510 }
511
512 /**
513 * Enables or disables buttons for a file locally available
514 */
515 private void setButtonsForDown() {
516 if (!isEmpty()) {
517 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
518 //downloadButton.setText(R.string.filedetails_redownload); // ugly
519 downloadButton.setEnabled(true);
520
521 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(true);
522 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
523 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
524 }
525 }
526
527 /**
528 * Enables or disables buttons for a file not locally available
529 */
530 private void setButtonsForRemote() {
531 if (!isEmpty()) {
532 Button downloadButton = (Button) getView().findViewById(R.id.fdDownloadBtn);
533 //downloadButton.setText(R.string.filedetails_download); // unnecessary
534 downloadButton.setEnabled(true);
535
536 ((Button) getView().findViewById(R.id.fdOpenBtn)).setEnabled(false);
537 ((Button) getView().findViewById(R.id.fdRenameBtn)).setEnabled(true);
538 ((Button) getView().findViewById(R.id.fdRemoveBtn)).setEnabled(true);
539 }
540 }
541
542
543 /**
544 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
545 * the time that the file was created. There is a chance that this will
546 * be fixed in future versions. Use this method to check if this version of
547 * ownCloud has this fix.
548 * @return True, if ownCloud the ownCloud version is supporting creation time
549 */
550 private boolean ocVersionSupportsTimeCreated(){
551 /*if(mAccount != null){
552 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
553 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
554 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
555 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
556 return true;
557 }
558 }*/
559 return false;
560 }
561
562
563 /**
564 * Interface to implement by any Activity that includes some instance of FileDetailFragment
565 *
566 * @author David A. Velasco
567 */
568 public interface ContainerActivity {
569
570 /**
571 * Callback method invoked when the detail fragment wants to notice its container
572 * activity about a relevant state the file shown by the fragment.
573 *
574 * Added to notify to FileDisplayActivity about the need of refresh the files list.
575 *
576 * Currently called when:
577 * - a download is started;
578 * - a rename is completed;
579 * - a deletion is completed;
580 * - the 'inSync' flag is changed;
581 */
582 public void onFileStateChanged();
583
584 }
585
586
587 /**
588 * Once the file download has finished -> update view
589 * @author Bartek Przybylski
590 */
591 private class DownloadFinishReceiver extends BroadcastReceiver {
592 @Override
593 public void onReceive(Context context, Intent intent) {
594 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
595
596 if (!isEmpty() && accountName.equals(mAccount.name)) {
597 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
598 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
599 if (mFile.getRemotePath().equals(downloadedRemotePath)) {
600 if (downloadWasFine) {
601 mFile.setStoragePath(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH)); // updates the local object without accessing the database again
602 }
603 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
604 }
605 }
606 }
607 }
608
609
610 /**
611 * Once the file upload has finished -> update view
612 *
613 * Being notified about the finish of an upload is necessary for the next sequence:
614 * 1. Upload a big file.
615 * 2. Force a synchronization; if it finished before the upload, the file in transfer will be included in the local database and in the file list
616 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
617 * 3. Click the file in the list to see its details.
618 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
619 */
620 private class UploadFinishReceiver extends BroadcastReceiver {
621 @Override
622 public void onReceive(Context context, Intent intent) {
623 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
624
625 if (!isEmpty() && accountName.equals(mAccount.name)) {
626 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
627 String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH);
628 if (mFile.getRemotePath().equals(uploadRemotePath)) {
629 if (uploadWasFine) {
630 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
631 mFile = fdsm.getFileByPath(mFile.getRemotePath());
632 }
633 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
634 }
635 }
636 }
637 }
638
639
640 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
641 private class ShareRunnable implements Runnable {
642 private String mPath;
643
644 public ShareRunnable(String path) {
645 mPath = path;
646 }
647
648 public void run() {
649 AccountManager am = AccountManager.get(getActivity());
650 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
651 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
652 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
653
654 Log.d("share", "sharing for version " + ocv.toString());
655
656 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
657 String APPS_PATH = "/apps/files_sharing/";
658 String SHARE_PATH = "ajax/share.php";
659
660 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
661
662 final String WEBDAV_SCRIPT = "webdav.php";
663 final String WEBDAV_FILES_LOCATION = "/files/";
664
665 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
666 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
667 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
668
669 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
670 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
671
672 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
673
674 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
675 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
676 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
677 Log.d("share", mPath+"");
678 formparams.add(new BasicNameValuePair("sources",mPath));
679 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
680 formparams.add(new BasicNameValuePair("permissions", "0"));
681 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
682
683 int status;
684 try {
685 PropFindMethod find = new PropFindMethod(url+"/");
686 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
687 Log.d("sharer", ""+ url+"/");
688
689 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
690 Log.d("sharer-h", a.getName() + ":"+a.getValue());
691 }
692
693 int status2 = wc.executeMethod(find);
694
695 Log.d("sharer", "propstatus "+status2);
696
697 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
698 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
699
700 status2 = wc.executeMethod(get);
701
702 Log.d("sharer", "getstatus "+status2);
703 Log.d("sharer", "" + get.getResponseBodyAsString());
704
705 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
706 Log.d("sharer", a.getName() + ":"+a.getValue());
707 }
708
709 status = wc.executeMethod(post);
710 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
711 Log.d("sharer-h", a.getName() + ":"+a.getValue());
712 }
713 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
714 Log.d("sharer", a.getName() + ":"+a.getValue());
715 }
716 String resp = post.getResponseBodyAsString();
717 Log.d("share", ""+post.getURI().toString());
718 Log.d("share", "returned status " + status);
719 Log.d("share", " " +resp);
720
721 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
722 return;
723 }
724
725 JSONObject jsonObject = new JSONObject (resp);
726 String jsonStatus = jsonObject.getString("status");
727 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
728
729 String token = jsonObject.getString("data");
730 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
731 Log.d("Actions:shareFile ok", "url: " + uri);
732
733 } catch (HttpException e) {
734 // TODO Auto-generated catch block
735 e.printStackTrace();
736 } catch (IOException e) {
737 // TODO Auto-generated catch block
738 e.printStackTrace();
739 } catch (JSONException e) {
740 // TODO Auto-generated catch block
741 e.printStackTrace();
742 } catch (Exception e) {
743 // TODO Auto-generated catch block
744 e.printStackTrace();
745 }
746
747 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
748
749 }
750 }
751 }
752
753 public void onDismiss(EditNameFragment dialog) {
754 if (dialog instanceof EditNameFragment) {
755 if (((EditNameFragment)dialog).getResult()) {
756 String newFilename = ((EditNameFragment)dialog).getNewFilename();
757 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
758 if (!newFilename.equals(mFile.getFileName())) {
759 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
760 if (fdsm.getFileById(mFile.getFileId()) != null) {
761 OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename);
762 newFile.setCreationTimestamp(mFile.getCreationTimestamp());
763 newFile.setFileId(mFile.getFileId());
764 newFile.setFileLength(mFile.getFileLength());
765 newFile.setKeepInSync(mFile.keepInSync());
766 newFile.setLastSyncDate(mFile.getLastSyncDate());
767 newFile.setMimetype(mFile.getMimetype());
768 newFile.setModificationTimestamp(mFile.getModificationTimestamp());
769 newFile.setParentId(mFile.getParentId());
770 boolean localRenameFails = false;
771 if (mFile.isDown()) {
772 File f = new File(mFile.getStoragePath());
773 Log.e(TAG, f.getAbsolutePath());
774 localRenameFails = !(f.renameTo(new File(f.getParent() + File.separator + newFilename)));
775 Log.e(TAG, f.getParent() + File.separator + newFilename);
776 newFile.setStoragePath(f.getParent() + File.separator + newFilename);
777 }
778
779 if (localRenameFails) {
780 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
781 msg.show();
782
783 } else {
784 new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start();
785 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
786 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
787 }
788
789 }
790 }
791 }
792 } else {
793 Log.e(TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName());
794 }
795
796 }
797
798 private class RenameRunnable implements Runnable {
799
800 Account mAccount;
801 OCFile mOld, mNew;
802 Handler mHandler;
803
804 public RenameRunnable(OCFile oldFile, OCFile newFile, Account account, Handler handler) {
805 mOld = oldFile;
806 mNew = newFile;
807 mAccount = account;
808 mHandler = handler;
809 }
810
811 public void run() {
812 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
813 AccountManager am = AccountManager.get(getSherlockActivity());
814 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
815 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
816 String webdav_path = AccountUtils.getWebdavPath(ocv);
817 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));
818
819 Log.e("ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
820 LocalMoveMethod move = new LocalMoveMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),
821 Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath()));
822
823 boolean success = false;
824 try {
825 int status = wc.executeMethod(move);
826 success = move.succeeded();
827 move.getResponseBodyAsString(); // exhaust response, although not interesting
828 Log.d(TAG, "Move returned status: " + status);
829
830 } catch (HttpException e) {
831 Log.e(TAG, "HTTP Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
832
833 } catch (IOException e) {
834 Log.e(TAG, "I/O Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
835
836 } catch (Exception e) {
837 Log.e(TAG, "Unexpected exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e);
838
839 } finally {
840 move.releaseConnection();
841 }
842
843 if (success) {
844 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
845 fdsm.removeFile(mOld);
846 fdsm.saveFile(mNew);
847 mFile = mNew;
848 mHandler.post(new Runnable() {
849 @Override
850 public void run() {
851 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
852 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
853 updateFileDetails(mFile, mAccount);
854 mContainerActivity.onFileStateChanged();
855 }
856 });
857
858 } else {
859 mHandler.post(new Runnable() {
860 @Override
861 public void run() {
862 // undo the local rename
863 if (mNew.isDown()) {
864 File f = new File(mNew.getStoragePath());
865 if (!f.renameTo(new File(mOld.getStoragePath()))) {
866 // the local rename undoing failed; last chance: save the new local storage path in the old file
867 mFile.setStoragePath(mNew.getStoragePath());
868 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
869 fdsm.saveFile(mFile);
870 }
871 }
872 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
873 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
874 try {
875 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
876 msg.show();
877
878 } catch (NotFoundException e) {
879 e.printStackTrace();
880 }
881 }
882 });
883 }
884 }
885 private class LocalMoveMethod extends DavMethodBase {
886
887 public LocalMoveMethod(String uri, String dest) {
888 super(uri);
889 addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest));
890 }
891
892 @Override
893 public String getName() {
894 return "MOVE";
895 }
896
897 @Override
898 protected boolean isSuccess(int status) {
899 return status == 201 || status == 204;
900 }
901
902 }
903 }
904
905 private static class EditNameFragment extends SherlockDialogFragment implements OnClickListener {
906
907 private String mNewFilename;
908 private boolean mResult;
909 private FileDetailFragment mListener;
910
911 static public EditNameFragment newInstance(String filename) {
912 EditNameFragment f = new EditNameFragment();
913 Bundle args = new Bundle();
914 args.putString("filename", filename);
915 f.setArguments(args);
916 return f;
917 }
918
919 @Override
920 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
921 View v = inflater.inflate(R.layout.edit_box_dialog, container, false);
922
923 String currentName = getArguments().getString("filename");
924 if (currentName == null)
925 currentName = "";
926
927 ((Button)v.findViewById(R.id.cancel)).setOnClickListener(this);
928 ((Button)v.findViewById(R.id.ok)).setOnClickListener(this);
929 ((TextView)v.findViewById(R.id.user_input)).setText(currentName);
930 ((TextView)v.findViewById(R.id.user_input)).requestFocus();
931 getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
932
933 mResult = false;
934 return v;
935 }
936
937 @Override
938 public void onClick(View view) {
939 switch (view.getId()) {
940 case R.id.ok: {
941 mNewFilename = ((TextView)getView().findViewById(R.id.user_input)).getText().toString();
942 mResult = true;
943 }
944 case R.id.cancel: { // fallthought
945 dismiss();
946 mListener.onDismiss(this);
947 }
948 }
949 }
950
951 void setOnDismissListener(FileDetailFragment listener) {
952 mListener = listener;
953 }
954
955 public String getNewFilename() {
956 return mNewFilename;
957 }
958
959 // true if user click ok
960 public boolean getResult() {
961 return mResult;
962 }
963
964 }
965
966 private class RemoveRunnable implements Runnable {
967
968 Account mAccount;
969 OCFile mFileToRemove;
970 Handler mHandler;
971
972 public RemoveRunnable(OCFile fileToRemove, Account account, Handler handler) {
973 mFileToRemove = fileToRemove;
974 mAccount = account;
975 mHandler = handler;
976 }
977
978 public void run() {
979 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
980 AccountManager am = AccountManager.get(getSherlockActivity());
981 String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
982 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
983 String webdav_path = AccountUtils.getWebdavPath(ocv);
984 Log.d("ASD", ""+baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
985
986 DeleteMethod delete = new DeleteMethod(baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));
987
988 boolean success = false;
989 int status = -1;
990 try {
991 status = wc.executeMethod(delete);
992 success = (delete.succeeded());
993 delete.getResponseBodyAsString(); // exhaust the response, although not interesting
994 Log.d(TAG, "Delete: returned status " + status);
995
996 } catch (HttpException e) {
997 Log.e(TAG, "HTTP Exception removing file " + mFileToRemove.getRemotePath(), e);
998
999 } catch (IOException e) {
1000 Log.e(TAG, "I/O Exception removing file " + mFileToRemove.getRemotePath(), e);
1001
1002 } catch (Exception e) {
1003 Log.e(TAG, "Unexpected exception removing file " + mFileToRemove.getRemotePath(), e);
1004
1005 } finally {
1006 delete.releaseConnection();
1007 }
1008
1009 if (success) {
1010 FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver());
1011 fdsm.removeFile(mFileToRemove);
1012 mHandler.post(new Runnable() {
1013 @Override
1014 public void run() {
1015 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1016 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1017 try {
1018 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
1019 msg.show();
1020 if (inDisplayActivity) {
1021 // double pane
1022 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
1023 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1024 transaction.commit();
1025 mContainerActivity.onFileStateChanged();
1026
1027 } else {
1028 getActivity().finish();
1029 }
1030
1031 } catch (NotFoundException e) {
1032 e.printStackTrace();
1033 }
1034 }
1035 });
1036
1037 } else {
1038 mHandler.post(new Runnable() {
1039 @Override
1040 public void run() {
1041 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1042 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1043 try {
1044 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
1045 msg.show();
1046
1047 } catch (NotFoundException e) {
1048 e.printStackTrace();
1049 }
1050 }
1051 });
1052 }
1053 }
1054
1055 }
1056
1057 class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
1058 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1059 @Override
1060 protected Bitmap doInBackground(String... params) {
1061 Bitmap result = null;
1062 if (params.length != 1) return result;
1063 String storagePath = params[0];
1064 try {
1065
1066 BitmapFactory.Options options = new Options();
1067 options.inScaled = true;
1068 options.inPurgeable = true;
1069 options.inJustDecodeBounds = true;
1070 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
1071 options.inPreferQualityOverSpeed = false;
1072 }
1073 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
1074 options.inMutable = false;
1075 }
1076
1077 result = BitmapFactory.decodeFile(storagePath, options);
1078 options.inJustDecodeBounds = false;
1079
1080 int width = options.outWidth;
1081 int height = options.outHeight;
1082 int scale = 1;
1083 if (width >= 2048 || height >= 2048) {
1084 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
1085 options.inSampleSize = scale;
1086 }
1087 Display display = getActivity().getWindowManager().getDefaultDisplay();
1088 Point size = new Point();
1089 int screenwidth;
1090 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
1091 display.getSize(size);
1092 screenwidth = size.x;
1093 } else {
1094 screenwidth = display.getWidth();
1095 }
1096
1097 Log.e("ASD", "W " + width + " SW " + screenwidth);
1098
1099 if (width > screenwidth) {
1100 scale = (int) Math.ceil((float)width / screenwidth);
1101 options.inSampleSize = scale;
1102 }
1103
1104 result = BitmapFactory.decodeFile(storagePath, options);
1105
1106 Log.e("ASD", "W " + options.outWidth + " SW " + options.outHeight);
1107
1108 } catch (OutOfMemoryError e) {
1109 result = null;
1110 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
1111
1112 } catch (NoSuchFieldError e) {
1113 result = null;
1114 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
1115
1116 } catch (Throwable t) {
1117 result = null;
1118 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
1119 }
1120 return result;
1121 }
1122 @Override
1123 protected void onPostExecute(Bitmap result) {
1124 if (result != null && mPreview != null) {
1125 mPreview.setImageBitmap(result);
1126 }
1127 }
1128
1129 }
1130
1131
1132 }