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