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