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