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