Merge branch 'master' of github.com:owncloud/android into setAsWallpaper
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewMediaFragment.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20 package com.owncloud.android.ui.preview;
21
22 import android.accounts.Account;
23 import android.app.Activity;
24 import android.graphics.Bitmap;
25 import android.graphics.BitmapFactory;
26 import android.media.MediaMetadataRetriever;
27 import android.support.v7.app.AlertDialog;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.ServiceConnection;
33 import android.content.res.Configuration;
34 import android.content.res.Resources;
35 import android.media.MediaPlayer;
36 import android.media.MediaPlayer.OnCompletionListener;
37 import android.media.MediaPlayer.OnErrorListener;
38 import android.media.MediaPlayer.OnPreparedListener;
39 import android.net.Uri;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.IBinder;
43 import android.view.LayoutInflater;
44 import android.view.Menu;
45 import android.view.MenuInflater;
46 import android.view.MenuItem;
47 import android.view.MotionEvent;
48 import android.view.View;
49 import android.view.View.OnTouchListener;
50 import android.view.ViewGroup;
51 import android.widget.ImageView;
52 import android.widget.Toast;
53 import android.widget.VideoView;
54
55 import com.owncloud.android.R;
56 import com.owncloud.android.datamodel.OCFile;
57 import com.owncloud.android.files.FileMenuFilter;
58 import com.owncloud.android.lib.common.utils.Log_OC;
59 import com.owncloud.android.media.MediaControlView;
60 import com.owncloud.android.media.MediaService;
61 import com.owncloud.android.media.MediaServiceBinder;
62 import com.owncloud.android.ui.activity.FileActivity;
63 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
64 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
65 import com.owncloud.android.ui.fragment.FileFragment;
66
67
68 /**
69 * This fragment shows a preview of a downloaded media file (audio or video).
70 *
71 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
72 * produce an {@link IllegalStateException}.
73 *
74 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is
75 * generated on instantiation too.
76 */
77 public class PreviewMediaFragment extends FileFragment implements
78 OnTouchListener {
79
80 public static final String EXTRA_FILE = "FILE";
81 public static final String EXTRA_ACCOUNT = "ACCOUNT";
82 private static final String EXTRA_PLAY_POSITION = "PLAY_POSITION";
83 private static final String EXTRA_PLAYING = "PLAYING";
84
85 private View mView;
86 private Account mAccount;
87 private ImageView mImagePreview;
88 private VideoView mVideoPreview;
89 private int mSavedPlaybackPosition;
90
91 private MediaServiceBinder mMediaServiceBinder = null;
92 private MediaControlView mMediaController = null;
93 private MediaServiceConnection mMediaServiceConnection = null;
94 private VideoHelper mVideoHelper;
95 private boolean mAutoplay;
96 public boolean mPrepared;
97
98 private static final String TAG = PreviewMediaFragment.class.getSimpleName();
99
100
101 /**
102 * Creates a fragment to preview a file.
103 * <p/>
104 * When 'fileToDetail' or 'ocAccount' are null
105 *
106 * @param fileToDetail An {@link OCFile} to preview in the fragment
107 * @param ocAccount An ownCloud account; needed to start downloads
108 */
109 public PreviewMediaFragment(
110 OCFile fileToDetail,
111 Account ocAccount,
112 int startPlaybackPosition,
113 boolean autoplay) {
114
115 super(fileToDetail);
116 mAccount = ocAccount;
117 mSavedPlaybackPosition = startPlaybackPosition;
118 mAutoplay = autoplay;
119 }
120
121
122 /**
123 * Creates an empty fragment for previews.
124 * <p/>
125 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
126 * (for instance, when the device is turned a aside).
127 * <p/>
128 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
129 * construction
130 */
131 public PreviewMediaFragment() {
132 super();
133 mAccount = null;
134 mSavedPlaybackPosition = 0;
135 mAutoplay = true;
136 }
137
138
139 /**
140 * {@inheritDoc}
141 */
142 @Override
143 public void onCreate(Bundle savedInstanceState) {
144 super.onCreate(savedInstanceState);
145 setHasOptionsMenu(true);
146 }
147
148
149 /**
150 * {@inheritDoc}
151 */
152 @Override
153 public View onCreateView(LayoutInflater inflater, ViewGroup container,
154 Bundle savedInstanceState) {
155 super.onCreateView(inflater, container, savedInstanceState);
156 Log_OC.e(TAG, "onCreateView");
157
158
159 mView = inflater.inflate(R.layout.file_preview, container, false);
160
161 mImagePreview = (ImageView) mView.findViewById(R.id.image_preview);
162 mVideoPreview = (VideoView) mView.findViewById(R.id.video_preview);
163 mVideoPreview.setOnTouchListener(this);
164
165 mMediaController = (MediaControlView) mView.findViewById(R.id.media_controller);
166
167 return mView;
168 }
169
170
171 /**
172 * {@inheritDoc}
173 */
174 @Override
175 public void onActivityCreated(Bundle savedInstanceState) {
176 super.onActivityCreated(savedInstanceState);
177 Log_OC.e(TAG, "onActivityCreated");
178
179 OCFile file = getFile();
180 if (savedInstanceState == null) {
181 if (file == null) {
182 throw new IllegalStateException("Instanced with a NULL OCFile");
183 }
184 if (mAccount == null) {
185 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
186 }
187 if (!file.isDown()) {
188 throw new IllegalStateException("There is no local file to preview");
189 }
190
191 }
192 else {
193 file = (OCFile) savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_FILE);
194 setFile(file);
195 mAccount = savedInstanceState.getParcelable(PreviewMediaFragment.EXTRA_ACCOUNT);
196 mSavedPlaybackPosition =
197 savedInstanceState.getInt(PreviewMediaFragment.EXTRA_PLAY_POSITION);
198 mAutoplay = savedInstanceState.getBoolean(PreviewMediaFragment.EXTRA_PLAYING);
199
200 }
201 if (file != null && file.isDown()) {
202 if (file.isVideo()) {
203 mVideoPreview.setVisibility(View.VISIBLE);
204 mImagePreview.setVisibility(View.GONE);
205 prepareVideo();
206
207 }
208 else {
209 mVideoPreview.setVisibility(View.GONE);
210 mImagePreview.setVisibility(View.VISIBLE);
211 extractAndSetCoverArt(file);
212 }
213 }
214
215 }
216
217 /**
218 * tries to read the cover art from the audio file and sets it as cover art.
219 *
220 * @param file audio file with potential cover art
221 */
222 private void extractAndSetCoverArt(OCFile file) {
223 if (file.isAudio()) {
224 try {
225 MediaMetadataRetriever mmr = new MediaMetadataRetriever();
226 mmr.setDataSource(file.getStoragePath());
227 byte[] data = mmr.getEmbeddedPicture();
228 if (data != null) {
229 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
230 mImagePreview.setImageBitmap(bitmap); //associated cover art in bitmap
231 } else {
232 mImagePreview.setImageResource(R.drawable.logo);
233 }
234 } catch (Throwable t) {
235 mImagePreview.setImageResource(R.drawable.logo);
236 }
237 }
238 }
239
240
241 /**
242 * {@inheritDoc}
243 */
244 @Override
245 public void onSaveInstanceState(Bundle outState) {
246 super.onSaveInstanceState(outState);
247 Log_OC.e(TAG, "onSaveInstanceState");
248
249 outState.putParcelable(PreviewMediaFragment.EXTRA_FILE, getFile());
250 outState.putParcelable(PreviewMediaFragment.EXTRA_ACCOUNT, mAccount);
251
252 if (getFile().isVideo()) {
253 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
254 mAutoplay = mVideoPreview.isPlaying();
255 outState.putInt(PreviewMediaFragment.EXTRA_PLAY_POSITION, mSavedPlaybackPosition);
256 outState.putBoolean(PreviewMediaFragment.EXTRA_PLAYING, mAutoplay);
257 }
258 else {
259 outState.putInt(
260 PreviewMediaFragment.EXTRA_PLAY_POSITION,
261 mMediaServiceBinder.getCurrentPosition());
262 outState.putBoolean(
263 PreviewMediaFragment.EXTRA_PLAYING, mMediaServiceBinder.isPlaying());
264 }
265 }
266
267
268 @Override
269 public void onStart() {
270 super.onStart();
271 Log_OC.e(TAG, "onStart");
272
273 OCFile file = getFile();
274 if (file != null && file.isDown()) {
275 if (file.isAudio()) {
276 bindMediaService();
277
278 }
279 else {
280 if (file.isVideo()) {
281 stopAudio();
282 playVideo();
283 }
284 }
285 }
286 }
287
288
289 private void stopAudio() {
290 Intent i = new Intent(getActivity(), MediaService.class);
291 i.setAction(MediaService.ACTION_STOP_ALL);
292 getActivity().startService(i);
293 }
294
295
296 /**
297 * {@inheritDoc}
298 */
299 @Override
300 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
301 super.onCreateOptionsMenu(menu, inflater);
302 inflater.inflate(R.menu.file_actions_menu, menu);
303 }
304
305
306 /**
307 * {@inheritDoc}
308 */
309 @Override
310 public void onPrepareOptionsMenu(Menu menu) {
311 super.onPrepareOptionsMenu(menu);
312
313 if (mContainerActivity.getStorageManager() != null) {
314 FileMenuFilter mf = new FileMenuFilter(
315 getFile(),
316 mContainerActivity.getStorageManager().getAccount(),
317 mContainerActivity,
318 getActivity()
319 );
320 mf.filter(menu);
321 }
322
323 // additional restriction for this fragment
324 // TODO allow renaming in PreviewImageFragment
325 MenuItem item = menu.findItem(R.id.action_rename_file);
326 if (item != null) {
327 item.setVisible(false);
328 item.setEnabled(false);
329 }
330
331 // additional restriction for this fragment
332 item = menu.findItem(R.id.action_move);
333 if (item != null) {
334 item.setVisible(false);
335 item.setEnabled(false);
336 }
337
338 // additional restriction for this fragment
339 item = menu.findItem(R.id.action_copy);
340 if (item != null) {
341 item.setVisible(false);
342 item.setEnabled(false);
343 }
344 }
345
346
347 /**
348 * {@inheritDoc}
349 */
350 @Override
351 public boolean onOptionsItemSelected(MenuItem item) {
352 switch (item.getItemId()) {
353 case R.id.action_share_file: {
354 stopPreview(false);
355 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
356 return true;
357 }
358 case R.id.action_unshare_file: {
359 stopPreview(false);
360 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
361 return true;
362 }
363 case R.id.action_open_file_with: {
364 openFile();
365 return true;
366 }
367 case R.id.action_remove_file: {
368 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
369 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
370 return true;
371 }
372 case R.id.action_see_details: {
373 seeDetails();
374 return true;
375 }
376 case R.id.action_send_file: {
377 sendFile();
378 return true;
379 }
380 case R.id.action_sync_file: {
381 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
382 return true;
383 }
384 case R.id.action_favorite_file:{
385 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), true);
386 return true;
387 }
388 case R.id.action_unfavorite_file:{
389 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), false);
390 return true;
391 }
392 default:
393 return false;
394 }
395 }
396
397
398 /**
399 * Update the file of the fragment with file value
400 *
401 * @param file
402 */
403 public void updateFile(OCFile file) {
404 setFile(file);
405 }
406
407 private void sendFile() {
408 stopPreview(false);
409 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
410
411 }
412
413 private void seeDetails() {
414 stopPreview(false);
415 mContainerActivity.showDetails(getFile());
416 }
417
418
419 private void prepareVideo() {
420 // create helper to get more control on the playback
421 mVideoHelper = new VideoHelper();
422 mVideoPreview.setOnPreparedListener(mVideoHelper);
423 mVideoPreview.setOnCompletionListener(mVideoHelper);
424 mVideoPreview.setOnErrorListener(mVideoHelper);
425 }
426
427 @SuppressWarnings("static-access")
428 private void playVideo() {
429 // create and prepare control panel for the user
430 mMediaController.setMediaPlayer(mVideoPreview);
431
432 // load the video file in the video player ;
433 // when done, VideoHelper#onPrepared() will be called
434 Uri uri = Uri.parse(getFile().getStoragePath());
435 mVideoPreview.setVideoPath(uri.encode(getFile().getStoragePath()));
436 }
437
438
439 private class VideoHelper implements OnCompletionListener, OnPreparedListener, OnErrorListener {
440
441 /**
442 * Called when the file is ready to be played.
443 * <p/>
444 * Just starts the playback.
445 *
446 * @param vp {@link MediaPlayer} instance performing the playback.
447 */
448 @Override
449 public void onPrepared(MediaPlayer vp) {
450 Log_OC.e(TAG, "onPrepared");
451 mVideoPreview.seekTo(mSavedPlaybackPosition);
452 if (mAutoplay) {
453 mVideoPreview.start();
454 }
455 mMediaController.setEnabled(true);
456 mMediaController.updatePausePlay();
457 mPrepared = true;
458 }
459
460
461 /**
462 * Called when the file is finished playing.
463 * <p/>
464 * Finishes the activity.
465 *
466 * @param mp {@link MediaPlayer} instance performing the playback.
467 */
468 @Override
469 public void onCompletion(MediaPlayer mp) {
470 Log_OC.e(TAG, "completed");
471 if (mp != null) {
472 mVideoPreview.seekTo(0);
473 // next lines are necessary to work around undesired video loops
474 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD) {
475 mVideoPreview.pause();
476
477 }
478 else {
479 if (Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1) {
480 // mVideePreview.pause() is not enough
481
482 mMediaController.setEnabled(false);
483 mVideoPreview.stopPlayback();
484 mAutoplay = false;
485 mSavedPlaybackPosition = 0;
486 mVideoPreview.setVideoPath(getFile().getStoragePath());
487 }
488 }
489 } // else : called from onError()
490 mMediaController.updatePausePlay();
491 }
492
493
494 /**
495 * Called when an error in playback occurs.
496 *
497 * @param mp {@link MediaPlayer} instance performing the playback.
498 * @param what Type of error
499 * @param extra Extra code specific to the error
500 */
501 @Override
502 public boolean onError(MediaPlayer mp, int what, int extra) {
503 if (mVideoPreview.getWindowToken() != null) {
504 String message = MediaService.getMessageForMediaError(
505 getActivity(), what, extra);
506 new AlertDialog.Builder(getActivity())
507 .setMessage(message)
508 .setPositiveButton(android.R.string.VideoView_error_button,
509 new DialogInterface.OnClickListener() {
510 public void onClick(DialogInterface dialog, int whichButton) {
511 dialog.dismiss();
512 VideoHelper.this.onCompletion(null);
513 }
514 })
515 .setCancelable(false)
516 .show();
517 }
518 return true;
519 }
520
521 }
522
523
524 @Override
525 public void onPause() {
526 Log_OC.e(TAG, "onPause");
527 super.onPause();
528 }
529
530 @Override
531 public void onResume() {
532 super.onResume();
533 Log_OC.e(TAG, "onResume");
534 }
535
536 @Override
537 public void onDestroy() {
538 Log_OC.e(TAG, "onDestroy");
539 super.onDestroy();
540 }
541
542 @Override
543 public void onStop() {
544 Log_OC.e(TAG, "onStop");
545
546 mPrepared = false;
547 if (mMediaServiceConnection != null) {
548 Log_OC.d(TAG, "Unbinding from MediaService ...");
549 if (mMediaServiceBinder != null && mMediaController != null) {
550 mMediaServiceBinder.unregisterMediaController(mMediaController);
551 }
552 getActivity().unbindService(mMediaServiceConnection);
553 mMediaServiceConnection = null;
554 mMediaServiceBinder = null;
555 }
556
557 super.onStop();
558 }
559
560 @Override
561 public boolean onTouch(View v, MotionEvent event) {
562 if (event.getAction() == MotionEvent.ACTION_DOWN && v == mVideoPreview) {
563 // added a margin on the left to avoid interfering with gesture to open navigation drawer
564 if (event.getX() / Resources.getSystem().getDisplayMetrics().density > 24.0) {
565 startFullScreenVideo();
566 }
567 return true;
568 }
569 return false;
570 }
571
572
573 private void startFullScreenVideo() {
574 Intent i = new Intent(getActivity(), PreviewVideoActivity.class);
575 i.putExtra(FileActivity.EXTRA_ACCOUNT, mAccount);
576 i.putExtra(FileActivity.EXTRA_FILE, getFile());
577 i.putExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, mVideoPreview.isPlaying());
578 mVideoPreview.pause();
579 i.putExtra(PreviewVideoActivity.EXTRA_START_POSITION, mVideoPreview.getCurrentPosition());
580 startActivityForResult(i, 0);
581 }
582
583 @Override
584 public void onConfigurationChanged(Configuration newConfig) {
585 Log_OC.e(TAG, "onConfigurationChanged " + this);
586 }
587
588 @Override
589 public void onActivityResult(int requestCode, int resultCode, Intent data) {
590 Log_OC.e(TAG, "onActivityResult " + this);
591 super.onActivityResult(requestCode, resultCode, data);
592 if (resultCode == Activity.RESULT_OK) {
593 mSavedPlaybackPosition = data.getExtras().getInt(
594 PreviewVideoActivity.EXTRA_START_POSITION);
595 mAutoplay = data.getExtras().getBoolean(PreviewVideoActivity.EXTRA_AUTOPLAY);
596 }
597 }
598
599
600 private void playAudio() {
601 OCFile file = getFile();
602 if (!mMediaServiceBinder.isPlaying(file)) {
603 Log_OC.d(TAG, "starting playback of " + file.getStoragePath());
604 mMediaServiceBinder.start(mAccount, file, mAutoplay, mSavedPlaybackPosition);
605
606 }
607 else {
608 if (!mMediaServiceBinder.isPlaying() && mAutoplay) {
609 mMediaServiceBinder.start();
610 mMediaController.updatePausePlay();
611 }
612 }
613 }
614
615
616 private void bindMediaService() {
617 Log_OC.d(TAG, "Binding to MediaService...");
618 if (mMediaServiceConnection == null) {
619 mMediaServiceConnection = new MediaServiceConnection();
620 }
621 getActivity().bindService( new Intent(getActivity(),
622 MediaService.class),
623 mMediaServiceConnection,
624 Context.BIND_AUTO_CREATE);
625 // follow the flow in MediaServiceConnection#onServiceConnected(...)
626 }
627
628 /** Defines callbacks for service binding, passed to bindService() */
629 private class MediaServiceConnection implements ServiceConnection {
630
631 @Override
632 public void onServiceConnected(ComponentName component, IBinder service) {
633 if (getActivity() != null) {
634 if (component.equals(
635 new ComponentName(getActivity(), MediaService.class))) {
636 Log_OC.d(TAG, "Media service connected");
637 mMediaServiceBinder = (MediaServiceBinder) service;
638 if (mMediaServiceBinder != null) {
639 prepareMediaController();
640 playAudio(); // do not wait for the touch of nobody to play audio
641
642 Log_OC.d(TAG, "Successfully bound to MediaService, MediaController ready");
643
644 }
645 else {
646 Log_OC.e(TAG, "Unexpected response from MediaService while binding");
647 }
648 }
649 }
650 }
651
652 private void prepareMediaController() {
653 mMediaServiceBinder.registerMediaController(mMediaController);
654 if (mMediaController != null) {
655 mMediaController.setMediaPlayer(mMediaServiceBinder);
656 mMediaController.setEnabled(true);
657 mMediaController.updatePausePlay();
658 }
659 }
660
661 @Override
662 public void onServiceDisconnected(ComponentName component) {
663 if (component.equals(new ComponentName(getActivity(), MediaService.class))) {
664 Log_OC.e(TAG, "Media service suddenly disconnected");
665 if (mMediaController != null) {
666 mMediaController.setMediaPlayer(null);
667 }
668 else {
669 Toast.makeText(
670 getActivity(),
671 "No media controller to release when disconnected from media service",
672 Toast.LENGTH_SHORT).show();
673 }
674 mMediaServiceBinder = null;
675 mMediaServiceConnection = null;
676 }
677 }
678 }
679
680
681 /**
682 * Opens the previewed file with an external application.
683 */
684 private void openFile() {
685 stopPreview(true);
686 mContainerActivity.getFileOperationsHelper().openFile(getFile());
687 finish();
688 }
689
690 /**
691 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
692 * to be previewed.
693 *
694 * @param file File to test if can be previewed.
695 * @return 'True' if the file can be handled by the fragment.
696 */
697 public static boolean canBePreviewed(OCFile file) {
698 return (file != null && (file.isAudio() || file.isVideo()));
699 }
700
701
702 public void stopPreview(boolean stopAudio) {
703 OCFile file = getFile();
704 if (file.isAudio() && stopAudio) {
705 mMediaServiceBinder.pause();
706
707 }
708 else {
709 if (file.isVideo()) {
710 mVideoPreview.stopPlayback();
711 }
712 }
713 }
714
715
716 /**
717 * Finishes the preview
718 */
719 private void finish() {
720 getActivity().onBackPressed();
721 }
722
723
724 public int getPosition() {
725 if (mPrepared) {
726 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
727 }
728 Log_OC.e(TAG, "getting position: " + mSavedPlaybackPosition);
729 return mSavedPlaybackPosition;
730 }
731
732 public boolean isPlaying() {
733 if (mPrepared) {
734 mAutoplay = mVideoPreview.isPlaying();
735 }
736 return mAutoplay;
737 }
738
739 }