817e8c44e702adae0cc0ae5b34e031fd4a6b7d9c
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / fragment / FilePreviewFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 2 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.lang.ref.WeakReference;
22 import java.sql.PreparedStatement;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.apache.commons.httpclient.methods.GetMethod;
27 import org.apache.commons.httpclient.methods.PostMethod;
28 import org.apache.commons.httpclient.methods.StringRequestEntity;
29 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
30 import org.apache.http.HttpStatus;
31 import org.apache.http.NameValuePair;
32 import org.apache.http.client.utils.URLEncodedUtils;
33 import org.apache.http.entity.FileEntity;
34 import org.apache.http.message.BasicNameValuePair;
35 import org.apache.http.protocol.HTTP;
36 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
37 import org.json.JSONObject;
38
39 import android.accounts.Account;
40 import android.accounts.AccountManager;
41 import android.annotation.SuppressLint;
42 import android.app.Activity;
43 import android.app.AlertDialog;
44 import android.content.ActivityNotFoundException;
45 import android.content.BroadcastReceiver;
46 import android.content.ComponentName;
47 import android.content.Context;
48 import android.content.DialogInterface;
49 import android.content.Intent;
50 import android.content.IntentFilter;
51 import android.content.ServiceConnection;
52 import android.graphics.Bitmap;
53 import android.graphics.BitmapFactory;
54 import android.graphics.BitmapFactory.Options;
55 import android.graphics.Point;
56 import android.media.MediaPlayer;
57 import android.media.MediaPlayer.OnCompletionListener;
58 import android.media.MediaPlayer.OnErrorListener;
59 import android.media.MediaPlayer.OnPreparedListener;
60 import android.net.Uri;
61 import android.os.AsyncTask;
62 import android.os.Bundle;
63 import android.os.Handler;
64 import android.os.IBinder;
65 import android.support.v4.app.DialogFragment;
66 import android.support.v4.app.FragmentTransaction;
67 import android.util.Log;
68 import android.view.Display;
69 import android.view.LayoutInflater;
70 import android.view.MotionEvent;
71 import android.view.View;
72 import android.view.View.OnClickListener;
73 import android.view.View.OnTouchListener;
74 import android.view.ViewGroup;
75 import android.webkit.MimeTypeMap;
76 import android.widget.Button;
77 import android.widget.CheckBox;
78 import android.widget.ImageView;
79 import android.widget.MediaController;
80 import android.widget.TextView;
81 import android.widget.Toast;
82 import android.widget.VideoView;
83 import android.widget.AdapterView.AdapterContextMenuInfo;
84
85 import com.actionbarsherlock.app.SherlockFragment;
86 import com.actionbarsherlock.view.Menu;
87 import com.actionbarsherlock.view.MenuInflater;
88 import com.actionbarsherlock.view.MenuItem;
89 import com.owncloud.android.AccountUtils;
90 import com.owncloud.android.DisplayUtils;
91 import com.owncloud.android.authenticator.AccountAuthenticator;
92 import com.owncloud.android.datamodel.FileDataStorageManager;
93 import com.owncloud.android.datamodel.OCFile;
94 import com.owncloud.android.files.services.FileDownloader;
95 import com.owncloud.android.files.services.FileObserverService;
96 import com.owncloud.android.files.services.FileUploader;
97 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
98 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
99 import com.owncloud.android.media.MediaService;
100 import com.owncloud.android.media.MediaServiceBinder;
101 import com.owncloud.android.network.OwnCloudClientUtils;
102 import com.owncloud.android.operations.OnRemoteOperationListener;
103 import com.owncloud.android.operations.RemoteOperation;
104 import com.owncloud.android.operations.RemoteOperationResult;
105 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
106 import com.owncloud.android.operations.RemoveFileOperation;
107 import com.owncloud.android.operations.RenameFileOperation;
108 import com.owncloud.android.operations.SynchronizeFileOperation;
109 import com.owncloud.android.ui.activity.ConflictsResolveActivity;
110 import com.owncloud.android.ui.activity.FileDetailActivity;
111 import com.owncloud.android.ui.activity.FileDisplayActivity;
112 import com.owncloud.android.ui.OnSwipeTouchListener;
113 import com.owncloud.android.ui.activity.TransferServiceGetter;
114 import com.owncloud.android.ui.activity.PreviewVideoActivity;
115 import com.owncloud.android.ui.dialog.EditNameDialog;
116 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
117 import com.owncloud.android.utils.OwnCloudVersion;
118
119 import com.owncloud.android.R;
120 import eu.alefzero.webdav.WebdavClient;
121 import eu.alefzero.webdav.WebdavUtils;
122
123 /**
124 * This fragment shows a preview of a downloaded file.
125 *
126 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
127 *
128 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
129 *
130 * @author David A. Velasco
131 */
132 public class FilePreviewFragment extends SherlockFragment implements
133 /*OnClickListener,*/ OnTouchListener , FileFragment,
134 ConfirmationDialogFragment.ConfirmationDialogFragmentListener, OnRemoteOperationListener /*, EditNameDialogListener*/ {
135
136 public static final String EXTRA_FILE = "FILE";
137 public static final String EXTRA_ACCOUNT = "ACCOUNT";
138 private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
139
140 private View mView;
141 private OCFile mFile;
142 private Account mAccount;
143 private FileDataStorageManager mStorageManager;
144 private ImageView mImagePreview;
145 public Bitmap mBitmap = null;
146 private VideoView mVideoPreview;
147 private int mSavedPlaybackPosition;
148
149 //private DownloadFinishReceiver mDownloadFinishReceiver;
150 //private UploadFinishReceiver mUploadFinishReceiver;
151
152 private Handler mHandler;
153 private RemoteOperation mLastRemoteOperation;
154
155 private MediaServiceBinder mMediaServiceBinder = null;
156 private MediaController mMediaController = null;
157 private MediaServiceConnection mMediaServiceConnection = null;
158 private VideoHelper mVideoHelper;
159
160 private static final String TAG = FilePreviewFragment.class.getSimpleName();
161
162
163 /**
164 * Creates a fragment to preview a file.
165 *
166 * When 'fileToDetail' or 'ocAccount' are null
167 *
168 * @param fileToDetail An {@link OCFile} to preview in the fragment
169 * @param ocAccount An ownCloud account; needed to start downloads
170 */
171 public FilePreviewFragment(OCFile fileToDetail, Account ocAccount) {
172 mFile = fileToDetail;
173 mAccount = ocAccount;
174 mSavedPlaybackPosition = 0;
175 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
176 }
177
178
179 /**
180 * Creates an empty fragment for previews.
181 *
182 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
183 *
184 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
185 */
186 public FilePreviewFragment() {
187 mFile = null;
188 mAccount = null;
189 mSavedPlaybackPosition = 0;
190 mStorageManager = null;
191 }
192
193
194 /**
195 * {@inheritDoc}
196 */
197 @Override
198 public void onCreate(Bundle savedInstanceState) {
199 super.onCreate(savedInstanceState);
200 mHandler = new Handler();
201 setHasOptionsMenu(true);
202 }
203
204
205 /**
206 * {@inheritDoc}
207 */
208 @Override
209 public View onCreateView(LayoutInflater inflater, ViewGroup container,
210 Bundle savedInstanceState) {
211 super.onCreateView(inflater, container, savedInstanceState);
212
213 mView = inflater.inflate(R.layout.file_preview, container, false);
214
215 //mView.findViewById(R.id.fdKeepInSync).setOnClickListener(this);
216 //mView.findViewById(R.id.fdRenameBtn).setOnClickListener(this);
217 //mView.findViewById(R.id.fdDownloadBtn).setOnClickListener(this);
218 //mView.findViewById(R.id.fdOpenBtn).setOnClickListener(this);
219 //mView.findViewById(R.id.fdRemoveBtn).setOnClickListener(this);
220 mImagePreview = (ImageView)mView.findViewById(R.id.image_preview);
221 mImagePreview.setOnTouchListener(this);
222 mVideoPreview = (VideoView)mView.findViewById(R.id.video_preview);
223
224 //updateFileDetails(false);
225 return mView;
226 }
227
228
229 /**
230 * {@inheritDoc}
231 */
232 @Override
233 public void onAttach(Activity activity) {
234 super.onAttach(activity);
235 if (!(activity instanceof FileFragment.ContainerActivity))
236 throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
237 }
238
239
240 /**
241 * {@inheritDoc}
242 */
243 @Override
244 public void onActivityCreated(Bundle savedInstanceState) {
245 super.onActivityCreated(savedInstanceState);
246
247 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
248 if (savedInstanceState != null) {
249 mFile = savedInstanceState.getParcelable(FilePreviewFragment.EXTRA_FILE);
250 mAccount = savedInstanceState.getParcelable(FilePreviewFragment.EXTRA_ACCOUNT);
251 mSavedPlaybackPosition = savedInstanceState.getInt(FilePreviewFragment.EXTRA_PLAY_POSITION);
252
253 }
254 if (mFile == null) {
255 throw new IllegalStateException("Instanced with a NULL OCFile");
256 }
257 if (mAccount == null) {
258 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
259 }
260 if (!mFile.isDown()) {
261 throw new IllegalStateException("There is no local file to preview");
262 }
263 if (mFile.isVideo()) {
264 mVideoPreview.setVisibility(View.VISIBLE);
265 mImagePreview.setVisibility(View.GONE);
266 prepareVideo();
267
268 } else {
269 mVideoPreview.setVisibility(View.GONE);
270 mImagePreview.setVisibility(View.VISIBLE);
271 }
272
273 }
274
275
276 /**
277 * {@inheritDoc}
278 */
279 @Override
280 public void onSaveInstanceState(Bundle outState) {
281 super.onSaveInstanceState(outState);
282
283 outState.putParcelable(FilePreviewFragment.EXTRA_FILE, mFile);
284 outState.putParcelable(FilePreviewFragment.EXTRA_ACCOUNT, mAccount);
285
286 if (mVideoPreview.isPlaying()) {
287 outState.putInt(FilePreviewFragment.EXTRA_PLAY_POSITION , mVideoPreview.getCurrentPosition());
288 }
289 }
290
291
292 @Override
293 public void onStart() {
294 super.onStart();
295
296 if (mFile != null) {
297 if (mFile.isAudio()) {
298 bindMediaService();
299
300 } else if (mFile.isImage()) {
301 BitmapLoader bl = new BitmapLoader(mImagePreview);
302 bl.execute(new String[]{mFile.getStoragePath()});
303
304 } else if (mFile.isVideo()) {
305 playVideo();
306 }
307 }
308 }
309
310
311 /**
312 * {@inheritDoc}
313 */
314 @Override
315 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
316 super.onCreateOptionsMenu(menu, inflater);
317
318 inflater.inflate(R.menu.file_actions_menu, menu);
319 List<Integer> toHide = new ArrayList<Integer>();
320
321 MenuItem item = null;
322 toHide.add(R.id.action_cancel_download);
323 toHide.add(R.id.action_cancel_upload);
324 toHide.add(R.id.action_download_file);
325 toHide.add(R.id.action_rename_file); // by now
326
327 for (int i : toHide) {
328 item = menu.findItem(i);
329 if (item != null) {
330 item.setVisible(false);
331 item.setEnabled(false);
332 }
333 }
334
335 }
336
337
338 /**
339 * {@inheritDoc}
340 */
341 @Override
342 public boolean onOptionsItemSelected(MenuItem item) {
343 switch (item.getItemId()) {
344 case R.id.action_open_file_with: {
345 openFile();
346 return true;
347 }
348 case R.id.action_remove_file: {
349 removeFile();
350 return true;
351 }
352 case R.id.action_see_details: {
353 seeDetails();
354 return true;
355 }
356
357 /*
358 case R.id.action_toggle_keep_in_sync: {
359 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
360 mFile.setKeepInSync(cb.isChecked());
361 mStorageManager.saveFile(mFile);
362
363 /// register the OCFile instance in the observer service to monitor local updates;
364 /// if necessary, the file is download
365 Intent intent = new Intent(getActivity().getApplicationContext(),
366 FileObserverService.class);
367 intent.putExtra(FileObserverService.KEY_FILE_CMD,
368 (cb.isChecked()?
369 FileObserverService.CMD_ADD_OBSERVED_FILE:
370 FileObserverService.CMD_DEL_OBSERVED_FILE));
371 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
372 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
373 Log.e(TAG, "starting observer service");
374 getActivity().startService(intent);
375
376 if (mFile.keepInSync()) {
377 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
378 }
379 break;
380 }*/
381 default:
382 return false;
383 }
384 }
385
386
387 private void seeDetails() {
388 stopPreview(false);
389 ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);
390 }
391
392
393 private void prepareVideo() {
394 // create helper to get more control on the playback
395 mVideoHelper = new VideoHelper();
396 mVideoPreview.setOnPreparedListener(mVideoHelper);
397 mVideoPreview.setOnCompletionListener(mVideoHelper);
398 mVideoPreview.setOnErrorListener(mVideoHelper);
399 }
400
401 private void playVideo() {
402 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
403 mVideoPreview.setVideoPath(mFile.getStoragePath());
404
405 // create and prepare control panel for the user
406 mMediaController = new MediaController(getActivity());
407 mMediaController.setMediaPlayer(mVideoPreview);
408 mMediaController.setAnchorView(mVideoPreview);
409 mVideoPreview.setMediaController(mMediaController);
410 }
411
412
413 private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
414
415 /**
416 * Called when the file is ready to be played.
417 *
418 * Just starts the playback.
419 *
420 * @param mp {@link MediaPlayer} instance performing the playback.
421 */
422 @Override
423 public void onPrepared(MediaPlayer vp) {
424 mVideoPreview.seekTo(mSavedPlaybackPosition);
425 mVideoPreview.start();
426 mMediaController.show(MediaService.MEDIA_CONTROL_SHORT_LIFE);
427 }
428
429
430 /**
431 * Called when the file is finished playing.
432 *
433 * Finishes the activity.
434 *
435 * @param mp {@link MediaPlayer} instance performing the playback.
436 */
437 @Override
438 public void onCompletion(MediaPlayer mp) {
439 // nothing, right now
440 }
441
442
443 /**
444 * Called when an error in playback occurs.
445 *
446 * @param mp {@link MediaPlayer} instance performing the playback.
447 * @param what Type of error
448 * @param extra Extra code specific to the error
449 */
450 @Override
451 public boolean onError(MediaPlayer mp, int what, int extra) {
452 Log.e(TAG, "Error in video playback, what = " + what + ", extra = " + extra);
453
454 if (mMediaController != null) {
455 mMediaController.hide();
456 }
457
458 if (mVideoPreview.getWindowToken() != null) {
459 String message = MediaService.getMessageForMediaError(getActivity(), what, extra);
460 new AlertDialog.Builder(getActivity())
461 .setMessage(message)
462 .setPositiveButton(android.R.string.VideoView_error_button,
463 new DialogInterface.OnClickListener() {
464 public void onClick(DialogInterface dialog, int whichButton) {
465 dialog.dismiss();
466 VideoHelper.this.onCompletion(null);
467 }
468 })
469 .setCancelable(false)
470 .show();
471 }
472 return true;
473 }
474
475 }
476
477
478 @Override
479 public void onResume() {
480 super.onResume();
481 /*
482 mDownloadFinishReceiver = new DownloadFinishReceiver();
483 IntentFilter filter = new IntentFilter(
484 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
485 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
486
487 mUploadFinishReceiver = new UploadFinishReceiver();
488 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
489 getActivity().registerReceiver(mUploadFinishReceiver, filter);
490 */
491
492 }
493
494
495 @Override
496 public void onPause() {
497 super.onPause();
498 /*
499 if (mVideoPreview.getVisibility() == View.VISIBLE) {
500 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
501 }*/
502 /*
503 getActivity().unregisterReceiver(mDownloadFinishReceiver);
504 mDownloadFinishReceiver = null;
505
506 getActivity().unregisterReceiver(mUploadFinishReceiver);
507 mUploadFinishReceiver = null;
508 */
509 }
510
511
512 @Override
513 public void onStop() {
514 super.onStop();
515 if (mMediaServiceConnection != null) {
516 Log.d(TAG, "Unbinding from MediaService ...");
517 if (mMediaServiceBinder != null && mMediaController != null) {
518 mMediaServiceBinder.unregisterMediaController(mMediaController);
519 }
520 getActivity().unbindService(mMediaServiceConnection);
521 mMediaServiceConnection = null;
522 mMediaServiceBinder = null;
523 if (mMediaController != null) {
524 mMediaController.hide();
525 mMediaController = null;
526 }
527 }
528 }
529
530 @Override
531 public void onDestroy() {
532 super.onDestroy();
533 if (mBitmap != null) {
534 mBitmap.recycle();
535 }
536 }
537
538 /*
539 @Override
540 public View getView() {
541 return super.getView() == null ? mView : super.getView();
542 }
543 */
544
545 /*
546 @Override
547 public void onClick(View v) {
548 switch (v.getId()) {
549 case R.id.fdDownloadBtn: {
550 FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
551 FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
552 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
553 downloaderBinder.cancel(mAccount, mFile);
554 if (mFile.isDown()) {
555 setButtonsForDown();
556 } else {
557 setButtonsForRemote();
558 }
559
560 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
561 uploaderBinder.cancel(mAccount, mFile);
562 if (!mFile.fileExists()) {
563 // TODO make something better
564 if (getActivity() instanceof FileDisplayActivity) {
565 // double pane
566 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
567 transaction.replace(R.id.file_details_container, new FilePreviewFragment(null, null), FTAG); // empty FileDetailFragment
568 transaction.commit();
569 mContainerActivity.onFileStateChanged();
570 } else {
571 getActivity().finish();
572 }
573
574 } else if (mFile.isDown()) {
575 setButtonsForDown();
576 } else {
577 setButtonsForRemote();
578 }
579
580 } else {
581 mLastRemoteOperation = new SynchronizeFileOperation(mFile, null, mStorageManager, mAccount, true, false, getActivity());
582 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
583 mLastRemoteOperation.execute(wc, this, mHandler);
584
585 // update ui
586 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
587 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
588 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
589
590 }
591 break;
592 }
593 case R.id.fdKeepInSync: {
594 CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
595 mFile.setKeepInSync(cb.isChecked());
596 mStorageManager.saveFile(mFile);
597
598 /// register the OCFile instance in the observer service to monitor local updates;
599 /// if necessary, the file is download
600 Intent intent = new Intent(getActivity().getApplicationContext(),
601 FileObserverService.class);
602 intent.putExtra(FileObserverService.KEY_FILE_CMD,
603 (cb.isChecked()?
604 FileObserverService.CMD_ADD_OBSERVED_FILE:
605 FileObserverService.CMD_DEL_OBSERVED_FILE));
606 intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
607 intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
608 Log.e(TAG, "starting observer service");
609 getActivity().startService(intent);
610
611 if (mFile.keepInSync()) {
612 onClick(getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
613 }
614 break;
615 }
616 case R.id.fdRenameBtn: {
617 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.rename_dialog_title), mFile.getFileName(), this);
618 dialog.show(getFragmentManager(), "nameeditdialog");
619 break;
620 }
621 case R.id.fdRemoveBtn: {
622 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
623 R.string.confirmation_remove_alert,
624 new String[]{mFile.getFileName()},
625 mFile.isDown() ? R.string.confirmation_remove_remote_and_local : R.string.confirmation_remove_remote,
626 mFile.isDown() ? R.string.confirmation_remove_local : -1,
627 R.string.common_cancel);
628 confDialog.setOnConfirmationListener(this);
629 mCurrentDialog = confDialog;
630 mCurrentDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
631 break;
632 }
633 case R.id.fdOpenBtn: {
634 openFile();
635 break;
636 }
637 default:
638 Log.e(TAG, "Incorrect view clicked!");
639 }
640
641 }
642 */
643
644
645 @Override
646 public boolean onTouch(View v, MotionEvent event) {
647 if (event.getAction() == MotionEvent.ACTION_DOWN) {
648 if (v == mImagePreview &&
649 mMediaServiceBinder != null && mFile.isAudio() && mMediaServiceBinder.isPlaying(mFile)) {
650 toggleMediaController(MediaService.MEDIA_CONTROL_PERMANENT);
651 return true;
652
653 } else if (v == mVideoPreview) {
654 toggleMediaController(MediaService.MEDIA_CONTROL_SHORT_LIFE);
655 return true;
656 }
657 }
658 return false;
659 }
660
661
662 private void toggleMediaController(int time) {
663 if (mMediaController.isShowing()) {
664 mMediaController.hide();
665 } else {
666 mMediaController.show(time);
667 }
668 }
669
670
671 private void playAudio() {
672 if (!mMediaServiceBinder.isPlaying(mFile)) {
673 Log.d(TAG, "starting playback of " + mFile.getStoragePath());
674 mMediaServiceBinder.start(mAccount, mFile);
675
676 } else {
677 if (!mMediaServiceBinder.isPlaying()) {
678 mMediaServiceBinder.start();
679 }
680 if (!mMediaController.isShowing() && isVisible()) {
681 mMediaController.show(MediaService.MEDIA_CONTROL_PERMANENT);
682 // TODO - fix strange bug; steps to trigger :
683 // 1. remove the "isVisible()" control
684 // 2. start the app and preview an audio file
685 // 3. exit from the app (home button, for instance) while the audio file is still being played
686 // 4. go to notification bar and click on the "ownCloud music app" notification
687 // PUM!
688 }
689 }
690 }
691
692
693 private void bindMediaService() {
694 Log.d(TAG, "Binding to MediaService...");
695 if (mMediaServiceConnection == null) {
696 mMediaServiceConnection = new MediaServiceConnection();
697 }
698 getActivity().bindService( new Intent(getActivity(),
699 MediaService.class),
700 mMediaServiceConnection,
701 Context.BIND_AUTO_CREATE);
702 // follow the flow in MediaServiceConnection#onServiceConnected(...)
703 }
704
705 /** Defines callbacks for service binding, passed to bindService() */
706 private class MediaServiceConnection implements ServiceConnection {
707
708 @Override
709 public void onServiceConnected(ComponentName component, IBinder service) {
710 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
711 Log.d(TAG, "Media service connected");
712 mMediaServiceBinder = (MediaServiceBinder) service;
713 if (mMediaServiceBinder != null) {
714 if (mMediaController == null) {
715 mMediaController = new MediaController(getSherlockActivity());
716 }
717 prepareMediaController();
718 playAudio(); // do not wait for the touch of nobody to play audio
719
720 Log.d(TAG, "Successfully bound to MediaService, MediaController ready");
721
722 } else {
723 Log.e(TAG, "Unexpected response from MediaService while binding");
724 }
725 }
726 }
727
728 private void prepareMediaController() {
729 mMediaServiceBinder.registerMediaController(mMediaController);
730 mMediaController.setMediaPlayer(mMediaServiceBinder);
731 mMediaController.setAnchorView(getView());
732 mMediaController.setEnabled(mMediaServiceBinder.isInPlaybackState());
733 }
734
735 @Override
736 public void onServiceDisconnected(ComponentName component) {
737 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
738 Log.e(TAG, "Media service suddenly disconnected");
739 if (mMediaController != null) {
740 mMediaController.hide();
741 mMediaController.setMediaPlayer(null);
742 mMediaController = null;
743 }
744 mMediaServiceBinder = null;
745 mMediaServiceConnection = null;
746 }
747 }
748 }
749
750
751
752 /**
753 * Opens the previewed file with an external application.
754 *
755 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
756 * we should get a list of available apps for MIME tpye in the server and join it with the list of
757 * available apps for the MIME type known from the file extension, to let the user choose
758 */
759 private void openFile() {
760 stopPreview(true);
761 String storagePath = mFile.getStoragePath();
762 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
763 try {
764 Intent i = new Intent(Intent.ACTION_VIEW);
765 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mFile.getMimetype());
766 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
767 startActivity(i);
768
769 } catch (Throwable t) {
770 Log.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile.getMimetype());
771 boolean toastIt = true;
772 String mimeType = "";
773 try {
774 Intent i = new Intent(Intent.ACTION_VIEW);
775 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
776 if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
777 if (mimeType != null) {
778 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
779 } else {
780 // desperate try
781 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
782 }
783 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
784 startActivity(i);
785 toastIt = false;
786 }
787
788 } catch (IndexOutOfBoundsException e) {
789 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
790
791 } catch (ActivityNotFoundException e) {
792 Log.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
793
794 } catch (Throwable th) {
795 Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);
796
797 } finally {
798 if (toastIt) {
799 Toast.makeText(getActivity(), "There is no application to handle file " + mFile.getFileName(), Toast.LENGTH_SHORT).show();
800 }
801 }
802
803 }
804 finish();
805 }
806
807 /**
808 * Starts a the removal of the previewed file.
809 *
810 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
811 * depending upon the user selection in the dialog.
812 */
813 private void removeFile() {
814 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
815 R.string.confirmation_remove_alert,
816 new String[]{mFile.getFileName()},
817 R.string.confirmation_remove_remote_and_local,
818 R.string.confirmation_remove_local,
819 R.string.common_cancel);
820 confDialog.setOnConfirmationListener(this);
821 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
822 }
823
824
825 /**
826 * Performs the removal of the previewed file, both locally and in the server.
827 */
828 @Override
829 public void onConfirmation(String callerTag) {
830 if (mStorageManager.getFileById(mFile.getFileId()) != null) { // check that the file is still there;
831 stopPreview(true);
832 mLastRemoteOperation = new RemoveFileOperation( mFile, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
833 true,
834 mStorageManager);
835 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
836 mLastRemoteOperation.execute(wc, this, mHandler);
837
838 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
839 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
840 }
841 }
842
843
844 /**
845 * Removes the file from local storage
846 */
847 @Override
848 public void onNeutral(String callerTag) {
849 // TODO this code should be made in a secondary thread,
850 if (mFile.isDown()) { // checks it is still there
851 stopPreview(true);
852 File f = new File(mFile.getStoragePath());
853 f.delete();
854 mFile.setStoragePath(null);
855 mStorageManager.saveFile(mFile);
856 finish();
857 }
858 }
859
860 /**
861 * User cancelled the removal action.
862 */
863 @Override
864 public void onCancel(String callerTag) {
865 // nothing to do here
866 }
867
868
869 /**
870 * {@inheritDoc}
871 */
872 public OCFile getFile(){
873 return mFile;
874 }
875
876 /*
877 /**
878 * Use this method to signal this Activity that it shall update its view.
879 *
880 * @param file : An {@link OCFile}
881 *-/
882 public void updateFileDetails(OCFile file, Account ocAccount) {
883 mFile = file;
884 if (ocAccount != null && (
885 mStorageManager == null ||
886 (mAccount != null && !mAccount.equals(ocAccount))
887 )) {
888 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
889 }
890 mAccount = ocAccount;
891 updateFileDetails(false);
892 }
893 */
894
895
896 /**
897 * Interface to implement by any Activity that includes some instance of FileDetailFragment
898 *
899 * @author David A. Velasco
900 */
901 public interface ContainerActivity extends TransferServiceGetter {
902
903 /**
904 * Callback method invoked when the detail fragment wants to notice its container
905 * activity about a relevant state the file shown by the fragment.
906 *
907 * Added to notify to FileDisplayActivity about the need of refresh the files list.
908 *
909 * Currently called when:
910 * - a download is started;
911 * - a rename is completed;
912 * - a deletion is completed;
913 * - the 'inSync' flag is changed;
914 */
915 public void onFileStateChanged();
916
917 }
918
919 /*
920 public void onDismiss(EditNameDialog dialog) {
921 if (dialog.getResult()) {
922 String newFilename = dialog.getNewFilename();
923 Log.d(TAG, "name edit dialog dismissed with new name " + newFilename);
924 mLastRemoteOperation = new RenameFileOperation( mFile,
925 mAccount,
926 newFilename,
927 new FileDataStorageManager(mAccount, getActivity().getContentResolver()));
928 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getSherlockActivity().getApplicationContext());
929 mLastRemoteOperation.execute(wc, this, mHandler);
930 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
931 getActivity().showDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
932 }
933 }
934 */
935
936 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
937
938 /**
939 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
940 *
941 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
942 */
943 private final WeakReference<ImageView> mImageViewRef;
944
945
946 /**
947 * Constructor.
948 *
949 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
950 */
951 public BitmapLoader(ImageView imageView) {
952 mImageViewRef = new WeakReference<ImageView>(imageView);
953 }
954
955
956 @SuppressWarnings("deprecation")
957 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
958 @Override
959 protected Bitmap doInBackground(String... params) {
960 Bitmap result = null;
961 if (params.length != 1) return result;
962 String storagePath = params[0];
963 try {
964 // set desired options that will affect the size of the bitmap
965 BitmapFactory.Options options = new Options();
966 options.inScaled = true;
967 options.inPurgeable = true;
968 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
969 options.inPreferQualityOverSpeed = false;
970 }
971 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
972 options.inMutable = false;
973 }
974 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
975 options.inJustDecodeBounds = true;
976 BitmapFactory.decodeFile(storagePath, options);
977
978 int width = options.outWidth;
979 int height = options.outHeight;
980 int scale = 1;
981 if (width >= 2048 || height >= 2048) {
982 // try to scale down the image to save memory
983 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
984 options.inSampleSize = scale;
985 }
986 Display display = getActivity().getWindowManager().getDefaultDisplay();
987 Point size = new Point();
988 int screenwidth;
989 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
990 display.getSize(size);
991 screenwidth = size.x;
992 } else {
993 screenwidth = display.getWidth();
994 }
995
996 Log.d(TAG, "image width: " + width + ", screen width: " + screenwidth);
997
998 if (width > screenwidth) {
999 // second try to scale down the image , this time depending upon the screen size; WTF...
1000 scale = (int) Math.ceil((float)width / screenwidth);
1001 options.inSampleSize = scale;
1002 }
1003
1004 // really load the bitmap
1005 options.inJustDecodeBounds = false; // the next decodeFile call will be real
1006 result = BitmapFactory.decodeFile(storagePath, options);
1007 Log.e(TAG, "loaded width: " + options.outWidth + ", loaded height: " + options.outHeight);
1008
1009 } catch (OutOfMemoryError e) {
1010 result = null;
1011 Log.e(TAG, "Out of memory occured for file with size " + storagePath);
1012
1013 } catch (NoSuchFieldError e) {
1014 result = null;
1015 Log.e(TAG, "Error from access to unexisting field despite protection " + storagePath);
1016
1017 } catch (Throwable t) {
1018 result = null;
1019 Log.e(TAG, "Unexpected error while creating image preview " + storagePath, t);
1020 }
1021 return result;
1022 }
1023
1024 @Override
1025 protected void onPostExecute(Bitmap result) {
1026 if (result != null && mImageViewRef != null) {
1027 final ImageView imageView = mImageViewRef.get();
1028 imageView.setImageBitmap(result);
1029 mBitmap = result;
1030 }
1031 }
1032
1033 }
1034
1035 /**
1036 * Helper method to test if an {@link OCFile} can be passed to a {@link FilePreviewFragment} to be previewed.
1037 *
1038 * @param file File to test if can be previewed.
1039 * @return 'True' if the file can be handled by the fragment.
1040 */
1041 public static boolean canBePreviewed(OCFile file) {
1042 return (file != null && (file.isAudio() || file.isVideo() || file.isImage()));
1043 }
1044
1045 /**
1046 * {@inheritDoc}
1047 */
1048 @Override
1049 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1050 if (operation.equals(mLastRemoteOperation)) {
1051 if (operation instanceof RemoveFileOperation) {
1052 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1053
1054 /*
1055 } else if (operation instanceof RenameFileOperation) {
1056 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1057
1058 } else if (operation instanceof SynchronizeFileOperation) {
1059 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);*/
1060 }
1061 }
1062 }
1063
1064 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1065 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1066 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1067
1068 if (result.isSuccess()) {
1069 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
1070 msg.show();
1071 finish();
1072
1073 } else {
1074 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
1075 msg.show();
1076 if (result.isSslRecoverableException()) {
1077 // TODO show the SSL warning dialog
1078 }
1079 }
1080 }
1081
1082 private void stopPreview(boolean stopAudio) {
1083 if (mMediaController != null) {
1084 mMediaController.hide();
1085 }
1086 if (mFile.isAudio() && stopAudio) {
1087 mMediaServiceBinder.pause();
1088
1089 } else if (mFile.isVideo()) {
1090 mVideoPreview.stopPlayback();
1091 }
1092 }
1093
1094
1095
1096 /**
1097 * Finishes the preview
1098 */
1099 private void finish() {
1100 Activity container = getActivity();
1101 if (container instanceof FileDisplayActivity) {
1102 // double pane
1103 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
1104 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1105 transaction.commit();
1106 ((FileFragment.ContainerActivity)container).onFileStateChanged();
1107 } else {
1108 container.finish();
1109 }
1110 }
1111
1112 /*
1113 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1114 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1115 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1116
1117 if (result.isSuccess()) {
1118 updateFileDetails(((RenameFileOperation)operation).getFile(), mAccount);
1119 mContainerActivity.onFileStateChanged();
1120
1121 } else {
1122 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1123 Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1124 msg.show();
1125 // TODO throw again the new rename dialog
1126 } else {
1127 Toast msg = Toast.makeText(getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1128 msg.show();
1129 if (result.isSslRecoverableException()) {
1130 // TODO show the SSL warning dialog
1131 }
1132 }
1133 }
1134 }
1135
1136 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1137 boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
1138 getActivity().dismissDialog((inDisplayActivity)? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT);
1139
1140 if (!result.isSuccess()) {
1141 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1142 Intent i = new Intent(getActivity(), ConflictsResolveActivity.class);
1143 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, mFile);
1144 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, mAccount);
1145 startActivity(i);
1146
1147 } else {
1148 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1149 msg.show();
1150 }
1151
1152 if (mFile.isDown()) {
1153 setButtonsForDown();
1154
1155 } else {
1156 setButtonsForRemote();
1157 }
1158
1159 } else {
1160 if (operation.transferWasRequested()) {
1161 mContainerActivity.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1162 // checking the service to see if the file is downloading results in FALSE
1163 } else {
1164 Toast msg = Toast.makeText(getActivity(), R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1165 msg.show();
1166 if (mFile.isDown()) {
1167 setButtonsForDown();
1168
1169 } else {
1170 setButtonsForRemote();
1171 }
1172 }
1173 }
1174 }
1175 */
1176
1177
1178 }