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