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