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