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