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_unshare_file
: {
360 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
363 case R
.id
.action_open_file_with
: {
367 case R
.id
.action_remove_file
: {
368 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
369 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
372 case R
.id
.action_see_details
: {
376 case R
.id
.action_send_file
: {
380 case R
.id
.action_sync_file
: {
381 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
384 case R
.id
.action_favorite_file
:{
385 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), true
);
388 case R
.id
.action_unfavorite_file
:{
389 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), false
);
399 * Update the file of the fragment with file value
403 public void updateFile(OCFile file
) {
407 private void sendFile() {
409 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
413 private void seeDetails() {
415 mContainerActivity
.showDetails(getFile());
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
);
427 @SuppressWarnings("static-access")
428 private void playVideo() {
429 // create and prepare control panel for the user
430 mMediaController
.setMediaPlayer(mVideoPreview
);
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()));
439 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
442 * Called when the file is ready to be played.
444 * Just starts the playback.
446 * @param vp {@link MediaPlayer} instance performing the playback.
449 public void onPrepared(MediaPlayer vp
) {
450 Log_OC
.e(TAG
, "onPrepared");
451 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
453 mVideoPreview
.start();
455 mMediaController
.setEnabled(true
);
456 mMediaController
.updatePausePlay();
462 * Called when the file is finished playing.
464 * Finishes the activity.
466 * @param mp {@link MediaPlayer} instance performing the playback.
469 public void onCompletion(MediaPlayer mp
) {
470 Log_OC
.e(TAG
, "completed");
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();
479 if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
480 // mVideePreview.pause() is not enough
482 mMediaController
.setEnabled(false
);
483 mVideoPreview
.stopPlayback();
485 mSavedPlaybackPosition
= 0;
486 mVideoPreview
.setVideoPath(getFile().getStoragePath());
489 } // else : called from onError()
490 mMediaController
.updatePausePlay();
495 * Called when an error in playback occurs.
497 * @param mp {@link MediaPlayer} instance performing the playback.
498 * @param what Type of error
499 * @param extra Extra code specific to the error
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())
508 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
509 new DialogInterface
.OnClickListener() {
510 public void onClick(DialogInterface dialog
, int whichButton
) {
512 VideoHelper
.this.onCompletion(null
);
515 .setCancelable(false
)
525 public void onPause() {
526 Log_OC
.e(TAG
, "onPause");
531 public void onResume() {
533 Log_OC
.e(TAG
, "onResume");
537 public void onDestroy() {
538 Log_OC
.e(TAG
, "onDestroy");
543 public void onStop() {
544 Log_OC
.e(TAG
, "onStop");
547 if (mMediaServiceConnection
!= null
) {
548 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
549 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
550 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
552 getActivity().unbindService(mMediaServiceConnection
);
553 mMediaServiceConnection
= null
;
554 mMediaServiceBinder
= null
;
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();
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);
584 public void onConfigurationChanged(Configuration newConfig
) {
585 Log_OC
.e(TAG
, "onConfigurationChanged " + this);
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
);
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
);
608 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
609 mMediaServiceBinder
.start();
610 mMediaController
.updatePausePlay();
616 private void bindMediaService() {
617 Log_OC
.d(TAG
, "Binding to MediaService...");
618 if (mMediaServiceConnection
== null
) {
619 mMediaServiceConnection
= new MediaServiceConnection();
621 getActivity().bindService( new Intent(getActivity(),
623 mMediaServiceConnection
,
624 Context
.BIND_AUTO_CREATE
);
625 // follow the flow in MediaServiceConnection#onServiceConnected(...)
628 /** Defines callbacks for service binding, passed to bindService() */
629 private class MediaServiceConnection
implements ServiceConnection
{
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
642 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
646 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
652 private void prepareMediaController() {
653 mMediaServiceBinder
.registerMediaController(mMediaController
);
654 if (mMediaController
!= null
) {
655 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
656 mMediaController
.setEnabled(true
);
657 mMediaController
.updatePausePlay();
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
);
671 "No media controller to release when disconnected from media service",
672 Toast
.LENGTH_SHORT
).show();
674 mMediaServiceBinder
= null
;
675 mMediaServiceConnection
= null
;
682 * Opens the previewed file with an external application.
684 private void openFile() {
686 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
691 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
694 * @param file File to test if can be previewed.
695 * @return 'True' if the file can be handled by the fragment.
697 public static boolean canBePreviewed(OCFile file
) {
698 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
702 public void stopPreview(boolean stopAudio
) {
703 OCFile file
= getFile();
704 if (file
.isAudio() && stopAudio
) {
705 mMediaServiceBinder
.pause();
709 if (file
.isVideo()) {
710 mVideoPreview
.stopPlayback();
717 * Finishes the preview
719 private void finish() {
720 getActivity().onBackPressed();
724 public int getPosition() {
726 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
728 Log_OC
.e(TAG
, "getting position: " + mSavedPlaybackPosition
);
729 return mSavedPlaybackPosition
;
732 public boolean isPlaying() {
734 mAutoplay
= mVideoPreview
.isPlaying();