2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
20 package com
.owncloud
.android
.ui
.preview
;
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
;
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
;
69 * This fragment shows a preview of a downloaded media file (audio or video).
71 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
72 * produce an {@link IllegalStateException}.
74 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is
75 * generated on instantiation too.
77 public class PreviewMediaFragment
extends FileFragment
implements
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";
86 private Account mAccount
;
87 private ImageView mImagePreview
;
88 private VideoView mVideoPreview
;
89 private int mSavedPlaybackPosition
;
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
;
98 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
102 * Creates a fragment to preview a file.
104 * When 'fileToDetail' or 'ocAccount' are null
106 * @param fileToDetail An {@link OCFile} to preview in the fragment
107 * @param ocAccount An ownCloud account; needed to start downloads
109 public PreviewMediaFragment(
112 int startPlaybackPosition
,
116 mAccount
= ocAccount
;
117 mSavedPlaybackPosition
= startPlaybackPosition
;
118 mAutoplay
= autoplay
;
123 * Creates an empty fragment for previews.
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).
128 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
131 public PreviewMediaFragment() {
134 mSavedPlaybackPosition
= 0;
143 public void onCreate(Bundle savedInstanceState
) {
144 super.onCreate(savedInstanceState
);
145 setHasOptionsMenu(true
);
153 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
154 Bundle savedInstanceState
) {
155 super.onCreateView(inflater
, container
, savedInstanceState
);
156 Log_OC
.e(TAG
, "onCreateView");
159 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
161 mImagePreview
= (ImageView
) mView
.findViewById(R
.id
.image_preview
);
162 mVideoPreview
= (VideoView
) mView
.findViewById(R
.id
.video_preview
);
163 mVideoPreview
.setOnTouchListener(this);
165 mMediaController
= (MediaControlView
) mView
.findViewById(R
.id
.media_controller
);
175 public void onActivityCreated(Bundle savedInstanceState
) {
176 super.onActivityCreated(savedInstanceState
);
177 Log_OC
.e(TAG
, "onActivityCreated");
179 OCFile file
= getFile();
180 if (savedInstanceState
== null
) {
182 throw new IllegalStateException("Instanced with a NULL OCFile");
184 if (mAccount
== null
) {
185 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
187 if (!file
.isDown()) {
188 throw new IllegalStateException("There is no local file to preview");
193 file
= (OCFile
) savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
);
195 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
196 mSavedPlaybackPosition
=
197 savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
198 mAutoplay
= savedInstanceState
.getBoolean(PreviewMediaFragment
.EXTRA_PLAYING
);
201 if (file
!= null
&& file
.isDown()) {
202 if (file
.isVideo()) {
203 mVideoPreview
.setVisibility(View
.VISIBLE
);
204 mImagePreview
.setVisibility(View
.GONE
);
209 mVideoPreview
.setVisibility(View
.GONE
);
210 mImagePreview
.setVisibility(View
.VISIBLE
);
211 extractAndSetCoverArt(file
);
218 * tries to read the cover art from the audio file and sets it as cover art.
220 * @param file audio file with potential cover art
222 private void extractAndSetCoverArt(OCFile file
) {
223 if (file
.isAudio()) {
225 MediaMetadataRetriever mmr
= new MediaMetadataRetriever();
226 mmr
.setDataSource(file
.getStoragePath());
227 byte[] data
= mmr
.getEmbeddedPicture();
229 Bitmap bitmap
= BitmapFactory
.decodeByteArray(data
, 0, data
.length
);
230 mImagePreview
.setImageBitmap(bitmap
); //associated cover art in bitmap
232 mImagePreview
.setImageResource(R
.drawable
.logo
);
234 } catch (Throwable t
) {
235 mImagePreview
.setImageResource(R
.drawable
.logo
);
245 public void onSaveInstanceState(Bundle outState
) {
246 super.onSaveInstanceState(outState
);
247 Log_OC
.e(TAG
, "onSaveInstanceState");
249 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, getFile());
250 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
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
);
260 PreviewMediaFragment
.EXTRA_PLAY_POSITION
,
261 mMediaServiceBinder
.getCurrentPosition());
263 PreviewMediaFragment
.EXTRA_PLAYING
, mMediaServiceBinder
.isPlaying());
269 public void onStart() {
271 Log_OC
.e(TAG
, "onStart");
273 OCFile file
= getFile();
274 if (file
!= null
&& file
.isDown()) {
275 if (file
.isAudio()) {
280 if (file
.isVideo()) {
289 private void stopAudio() {
290 Intent i
= new Intent(getActivity(), MediaService
.class);
291 i
.setAction(MediaService
.ACTION_STOP_ALL
);
292 getActivity().startService(i
);
300 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
301 super.onCreateOptionsMenu(menu
, inflater
);
302 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
310 public void onPrepareOptionsMenu(Menu menu
) {
311 super.onPrepareOptionsMenu(menu
);
313 if (mContainerActivity
.getStorageManager() != null
) {
314 FileMenuFilter mf
= new FileMenuFilter(
316 mContainerActivity
.getStorageManager().getAccount(),
323 // additional restriction for this fragment
324 // TODO allow renaming in PreviewImageFragment
325 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
327 item
.setVisible(false
);
328 item
.setEnabled(false
);
331 // additional restriction for this fragment
332 item
= menu
.findItem(R
.id
.action_move
);
334 item
.setVisible(false
);
335 item
.setEnabled(false
);
338 // additional restriction for this fragment
339 item
= menu
.findItem(R
.id
.action_copy
);
341 item
.setVisible(false
);
342 item
.setEnabled(false
);
351 public boolean onOptionsItemSelected(MenuItem item
) {
352 switch (item
.getItemId()) {
353 case R
.id
.action_share_file
: {
355 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
358 case R
.id
.action_share_with_users
: {
362 case R
.id
.action_unshare_file
: {
364 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
367 case R
.id
.action_open_file_with
: {
371 case R
.id
.action_remove_file
: {
372 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
373 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
376 case R
.id
.action_see_details
: {
380 case R
.id
.action_send_file
: {
384 case R
.id
.action_sync_file
: {
385 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
388 case R
.id
.action_favorite_file
:{
389 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), true
);
392 case R
.id
.action_unfavorite_file
:{
393 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), false
);
403 * Update the file of the fragment with file value
407 public void updateFile(OCFile file
) {
411 private void sendFile() {
413 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
417 private void seeDetails() {
419 mContainerActivity
.showDetails(getFile());
422 private void seeShareFile() {
424 mContainerActivity
.showShareFile(getFile());
427 private void prepareVideo() {
428 // create helper to get more control on the playback
429 mVideoHelper
= new VideoHelper();
430 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
431 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
432 mVideoPreview
.setOnErrorListener(mVideoHelper
);
435 @SuppressWarnings("static-access")
436 private void playVideo() {
437 // create and prepare control panel for the user
438 mMediaController
.setMediaPlayer(mVideoPreview
);
440 // load the video file in the video player ;
441 // when done, VideoHelper#onPrepared() will be called
442 Uri uri
= Uri
.parse(getFile().getStoragePath());
443 mVideoPreview
.setVideoPath(uri
.encode(getFile().getStoragePath()));
447 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
450 * Called when the file is ready to be played.
452 * Just starts the playback.
454 * @param vp {@link MediaPlayer} instance performing the playback.
457 public void onPrepared(MediaPlayer vp
) {
458 Log_OC
.e(TAG
, "onPrepared");
459 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
461 mVideoPreview
.start();
463 mMediaController
.setEnabled(true
);
464 mMediaController
.updatePausePlay();
470 * Called when the file is finished playing.
472 * Finishes the activity.
474 * @param mp {@link MediaPlayer} instance performing the playback.
477 public void onCompletion(MediaPlayer mp
) {
478 Log_OC
.e(TAG
, "completed");
480 mVideoPreview
.seekTo(0);
481 // next lines are necessary to work around undesired video loops
482 if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD
) {
483 mVideoPreview
.pause();
487 if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
488 // mVideePreview.pause() is not enough
490 mMediaController
.setEnabled(false
);
491 mVideoPreview
.stopPlayback();
493 mSavedPlaybackPosition
= 0;
494 mVideoPreview
.setVideoPath(getFile().getStoragePath());
497 } // else : called from onError()
498 mMediaController
.updatePausePlay();
503 * Called when an error in playback occurs.
505 * @param mp {@link MediaPlayer} instance performing the playback.
506 * @param what Type of error
507 * @param extra Extra code specific to the error
510 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
511 if (mVideoPreview
.getWindowToken() != null
) {
512 String message
= MediaService
.getMessageForMediaError(
513 getActivity(), what
, extra
);
514 new AlertDialog
.Builder(getActivity())
516 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
517 new DialogInterface
.OnClickListener() {
518 public void onClick(DialogInterface dialog
, int whichButton
) {
520 VideoHelper
.this.onCompletion(null
);
523 .setCancelable(false
)
533 public void onPause() {
534 Log_OC
.e(TAG
, "onPause");
539 public void onResume() {
541 Log_OC
.e(TAG
, "onResume");
545 public void onDestroy() {
546 Log_OC
.e(TAG
, "onDestroy");
551 public void onStop() {
552 Log_OC
.e(TAG
, "onStop");
555 if (mMediaServiceConnection
!= null
) {
556 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
557 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
558 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
560 getActivity().unbindService(mMediaServiceConnection
);
561 mMediaServiceConnection
= null
;
562 mMediaServiceBinder
= null
;
569 public boolean onTouch(View v
, MotionEvent event
) {
570 if (event
.getAction() == MotionEvent
.ACTION_DOWN
&& v
== mVideoPreview
) {
571 // added a margin on the left to avoid interfering with gesture to open navigation drawer
572 if (event
.getX() / Resources
.getSystem().getDisplayMetrics().density
> 24.0) {
573 startFullScreenVideo();
581 private void startFullScreenVideo() {
582 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
583 i
.putExtra(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
584 i
.putExtra(FileActivity
.EXTRA_FILE
, getFile());
585 i
.putExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, mVideoPreview
.isPlaying());
586 mVideoPreview
.pause();
587 i
.putExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, mVideoPreview
.getCurrentPosition());
588 startActivityForResult(i
, 0);
592 public void onConfigurationChanged(Configuration newConfig
) {
593 Log_OC
.e(TAG
, "onConfigurationChanged " + this);
597 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
598 Log_OC
.e(TAG
, "onActivityResult " + this);
599 super.onActivityResult(requestCode
, resultCode
, data
);
600 if (resultCode
== Activity
.RESULT_OK
) {
601 mSavedPlaybackPosition
= data
.getExtras().getInt(
602 PreviewVideoActivity
.EXTRA_START_POSITION
);
603 mAutoplay
= data
.getExtras().getBoolean(PreviewVideoActivity
.EXTRA_AUTOPLAY
);
608 private void playAudio() {
609 OCFile file
= getFile();
610 if (!mMediaServiceBinder
.isPlaying(file
)) {
611 Log_OC
.d(TAG
, "starting playback of " + file
.getStoragePath());
612 mMediaServiceBinder
.start(mAccount
, file
, mAutoplay
, mSavedPlaybackPosition
);
616 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
617 mMediaServiceBinder
.start();
618 mMediaController
.updatePausePlay();
624 private void bindMediaService() {
625 Log_OC
.d(TAG
, "Binding to MediaService...");
626 if (mMediaServiceConnection
== null
) {
627 mMediaServiceConnection
= new MediaServiceConnection();
629 getActivity().bindService( new Intent(getActivity(),
631 mMediaServiceConnection
,
632 Context
.BIND_AUTO_CREATE
);
633 // follow the flow in MediaServiceConnection#onServiceConnected(...)
636 /** Defines callbacks for service binding, passed to bindService() */
637 private class MediaServiceConnection
implements ServiceConnection
{
640 public void onServiceConnected(ComponentName component
, IBinder service
) {
641 if (getActivity() != null
) {
642 if (component
.equals(
643 new ComponentName(getActivity(), MediaService
.class))) {
644 Log_OC
.d(TAG
, "Media service connected");
645 mMediaServiceBinder
= (MediaServiceBinder
) service
;
646 if (mMediaServiceBinder
!= null
) {
647 prepareMediaController();
648 playAudio(); // do not wait for the touch of nobody to play audio
650 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
654 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
660 private void prepareMediaController() {
661 mMediaServiceBinder
.registerMediaController(mMediaController
);
662 if (mMediaController
!= null
) {
663 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
664 mMediaController
.setEnabled(true
);
665 mMediaController
.updatePausePlay();
670 public void onServiceDisconnected(ComponentName component
) {
671 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
672 Log_OC
.e(TAG
, "Media service suddenly disconnected");
673 if (mMediaController
!= null
) {
674 mMediaController
.setMediaPlayer(null
);
679 "No media controller to release when disconnected from media service",
680 Toast
.LENGTH_SHORT
).show();
682 mMediaServiceBinder
= null
;
683 mMediaServiceConnection
= null
;
690 * Opens the previewed file with an external application.
692 private void openFile() {
694 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
699 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
702 * @param file File to test if can be previewed.
703 * @return 'True' if the file can be handled by the fragment.
705 public static boolean canBePreviewed(OCFile file
) {
706 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
710 public void stopPreview(boolean stopAudio
) {
711 OCFile file
= getFile();
712 if (file
.isAudio() && stopAudio
) {
713 mMediaServiceBinder
.pause();
717 if (file
.isVideo()) {
718 mVideoPreview
.stopPlayback();
725 * Finishes the preview
727 private void finish() {
728 getActivity().onBackPressed();
732 public int getPosition() {
734 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
736 Log_OC
.e(TAG
, "getting position: " + mSavedPlaybackPosition
);
737 return mSavedPlaybackPosition
;
740 public boolean isPlaying() {
742 mAutoplay
= mVideoPreview
.isPlaying();