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
.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
;
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
;
67 * This fragment shows a preview of a downloaded media file (audio or video).
69 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will
70 * produce an {@link IllegalStateException}.
72 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is
73 * generated on instantiation too.
75 public class PreviewMediaFragment
extends FileFragment
implements
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";
84 private Account mAccount
;
85 private ImageView mImagePreview
;
86 private VideoView mVideoPreview
;
87 private int mSavedPlaybackPosition
;
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
;
96 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
100 * Creates a fragment to preview a file.
102 * When 'fileToDetail' or 'ocAccount' are null
104 * @param fileToDetail An {@link OCFile} to preview in the fragment
105 * @param ocAccount An ownCloud account; needed to start downloads
107 public PreviewMediaFragment(
110 int startPlaybackPosition
,
114 mAccount
= ocAccount
;
115 mSavedPlaybackPosition
= startPlaybackPosition
;
116 mAutoplay
= autoplay
;
121 * Creates an empty fragment for previews.
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).
126 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
129 public PreviewMediaFragment() {
132 mSavedPlaybackPosition
= 0;
141 public void onCreate(Bundle savedInstanceState
) {
142 super.onCreate(savedInstanceState
);
143 setHasOptionsMenu(true
);
151 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
152 Bundle savedInstanceState
) {
153 super.onCreateView(inflater
, container
, savedInstanceState
);
154 Log_OC
.v(TAG
, "onCreateView");
157 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
159 mImagePreview
= (ImageView
) mView
.findViewById(R
.id
.image_preview
);
160 mVideoPreview
= (VideoView
) mView
.findViewById(R
.id
.video_preview
);
161 mVideoPreview
.setOnTouchListener(this);
163 mMediaController
= (MediaControlView
) mView
.findViewById(R
.id
.media_controller
);
173 public void onActivityCreated(Bundle savedInstanceState
) {
174 super.onActivityCreated(savedInstanceState
);
175 Log_OC
.v(TAG
, "onActivityCreated");
177 OCFile file
= getFile();
178 if (savedInstanceState
== null
) {
180 throw new IllegalStateException("Instanced with a NULL OCFile");
182 if (mAccount
== null
) {
183 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
185 if (!file
.isDown()) {
186 throw new IllegalStateException("There is no local file to preview");
191 file
= (OCFile
) savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
);
193 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
194 mSavedPlaybackPosition
=
195 savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
196 mAutoplay
= savedInstanceState
.getBoolean(PreviewMediaFragment
.EXTRA_PLAYING
);
199 if (file
!= null
&& file
.isDown()) {
200 if (file
.isVideo()) {
201 mVideoPreview
.setVisibility(View
.VISIBLE
);
202 mImagePreview
.setVisibility(View
.GONE
);
207 mVideoPreview
.setVisibility(View
.GONE
);
208 mImagePreview
.setVisibility(View
.VISIBLE
);
209 extractAndSetCoverArt(file
);
216 * tries to read the cover art from the audio file and sets it as cover art.
218 * @param file audio file with potential cover art
220 private void extractAndSetCoverArt(OCFile file
) {
221 if (file
.isAudio()) {
223 MediaMetadataRetriever mmr
= new MediaMetadataRetriever();
224 mmr
.setDataSource(file
.getStoragePath());
225 byte[] data
= mmr
.getEmbeddedPicture();
227 Bitmap bitmap
= BitmapFactory
.decodeByteArray(data
, 0, data
.length
);
228 mImagePreview
.setImageBitmap(bitmap
); //associated cover art in bitmap
230 mImagePreview
.setImageResource(R
.drawable
.logo
);
232 } catch (Throwable t
) {
233 mImagePreview
.setImageResource(R
.drawable
.logo
);
243 public void onSaveInstanceState(Bundle outState
) {
244 super.onSaveInstanceState(outState
);
245 Log_OC
.v(TAG
, "onSaveInstanceState");
247 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, getFile());
248 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
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
);
258 PreviewMediaFragment
.EXTRA_PLAY_POSITION
,
259 mMediaServiceBinder
.getCurrentPosition());
261 PreviewMediaFragment
.EXTRA_PLAYING
, mMediaServiceBinder
.isPlaying());
267 public void onStart() {
269 Log_OC
.v(TAG
, "onStart");
271 OCFile file
= getFile();
272 if (file
!= null
&& file
.isDown()) {
273 if (file
.isAudio()) {
278 if (file
.isVideo()) {
287 private void stopAudio() {
288 Intent i
= new Intent(getActivity(), MediaService
.class);
289 i
.setAction(MediaService
.ACTION_STOP_ALL
);
290 getActivity().startService(i
);
298 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
299 super.onCreateOptionsMenu(menu
, inflater
);
300 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
308 public void onPrepareOptionsMenu(Menu menu
) {
309 super.onPrepareOptionsMenu(menu
);
311 if (mContainerActivity
.getStorageManager() != null
) {
312 FileMenuFilter mf
= new FileMenuFilter(
314 mContainerActivity
.getStorageManager().getAccount(),
321 // additional restriction for this fragment
322 // TODO allow renaming in PreviewImageFragment
323 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
325 item
.setVisible(false
);
326 item
.setEnabled(false
);
329 // additional restriction for this fragment
330 item
= menu
.findItem(R
.id
.action_move
);
332 item
.setVisible(false
);
333 item
.setEnabled(false
);
336 // additional restriction for this fragment
337 item
= menu
.findItem(R
.id
.action_copy
);
339 item
.setVisible(false
);
340 item
.setEnabled(false
);
349 public boolean onOptionsItemSelected(MenuItem item
) {
350 switch (item
.getItemId()) {
351 case R
.id
.action_share_file
: {
353 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
356 case R
.id
.action_share_with_users
: {
360 case R
.id
.action_unshare_file
: {
362 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
365 case R
.id
.action_open_file_with
: {
369 case R
.id
.action_remove_file
: {
370 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
371 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
374 case R
.id
.action_see_details
: {
378 case R
.id
.action_send_file
: {
382 case R
.id
.action_sync_file
: {
383 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
386 case R
.id
.action_favorite_file
:{
387 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), true
);
390 case R
.id
.action_unfavorite_file
:{
391 mContainerActivity
.getFileOperationsHelper().toggleFavorite(getFile(), false
);
401 * Update the file of the fragment with file value
403 * @param file Replaces the held file with a new one
405 public void updateFile(OCFile file
) {
409 private void sendFile() {
411 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
415 private void seeDetails() {
417 mContainerActivity
.showDetails(getFile());
420 private void seeShareFile() {
422 mContainerActivity
.getFileOperationsHelper().showShareFile(getFile());
425 private void prepareVideo() {
426 // create helper to get more control on the playback
427 mVideoHelper
= new VideoHelper();
428 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
429 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
430 mVideoPreview
.setOnErrorListener(mVideoHelper
);
433 @SuppressWarnings("static-access")
434 private void playVideo() {
435 // create and prepare control panel for the user
436 mMediaController
.setMediaPlayer(mVideoPreview
);
438 // load the video file in the video player ;
439 // when done, VideoHelper#onPrepared() will be called
440 mVideoPreview
.setVideoURI(getFile().getStorageUri());
444 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
447 * Called when the file is ready to be played.
449 * Just starts the playback.
451 * @param vp {@link MediaPlayer} instance performing the playback.
454 public void onPrepared(MediaPlayer vp
) {
455 Log_OC
.v(TAG
, "onPrepared");
456 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
458 mVideoPreview
.start();
460 mMediaController
.setEnabled(true
);
461 mMediaController
.updatePausePlay();
467 * Called when the file is finished playing.
469 * Finishes the activity.
471 * @param mp {@link MediaPlayer} instance performing the playback.
474 public void onCompletion(MediaPlayer mp
) {
475 Log_OC
.v(TAG
, "completed");
477 mVideoPreview
.seekTo(0);
478 } // else : called from onError()
479 mMediaController
.updatePausePlay();
484 * Called when an error in playback occurs.
486 * @param mp {@link MediaPlayer} instance performing the playback.
487 * @param what Type of error
488 * @param extra Extra code specific to the error
491 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
492 Log_OC
.e(TAG
, "Error in video playback, what = " + what
+ ", extra = " + extra
);
493 if (mVideoPreview
.getWindowToken() != null
) {
494 String message
= MediaService
.getMessageForMediaError(
495 getActivity(), what
, extra
);
496 new AlertDialog
.Builder(getActivity())
498 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
499 new DialogInterface
.OnClickListener() {
500 public void onClick(DialogInterface dialog
, int whichButton
) {
502 VideoHelper
.this.onCompletion(null
);
505 .setCancelable(false
)
515 public void onPause() {
516 Log_OC
.v(TAG
, "onPause");
521 public void onResume() {
523 Log_OC
.v(TAG
, "onResume");
527 public void onDestroy() {
528 Log_OC
.v(TAG
, "onDestroy");
533 public void onStop() {
534 Log_OC
.v(TAG
, "onStop");
537 if (mMediaServiceConnection
!= null
) {
538 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
539 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
540 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
542 getActivity().unbindService(mMediaServiceConnection
);
543 mMediaServiceConnection
= null
;
544 mMediaServiceBinder
= null
;
551 public boolean onTouch(View v
, MotionEvent event
) {
552 if (event
.getAction() == MotionEvent
.ACTION_DOWN
&& v
== mVideoPreview
) {
553 // added a margin on the left to avoid interfering with gesture to open navigation drawer
554 if (event
.getX() / Resources
.getSystem().getDisplayMetrics().density
> 24.0) {
555 startFullScreenVideo();
563 private void startFullScreenVideo() {
564 Intent i
= new Intent(getActivity(), PreviewVideoActivity
.class);
565 i
.putExtra(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
566 i
.putExtra(FileActivity
.EXTRA_FILE
, getFile());
567 i
.putExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, mVideoPreview
.isPlaying());
568 mVideoPreview
.pause();
569 i
.putExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, mVideoPreview
.getCurrentPosition());
570 startActivityForResult(i
, 0);
574 public void onConfigurationChanged(Configuration newConfig
) {
575 Log_OC
.v(TAG
, "onConfigurationChanged " + this);
579 public void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
580 Log_OC
.v(TAG
, "onActivityResult " + this);
581 super.onActivityResult(requestCode
, resultCode
, data
);
582 if (resultCode
== Activity
.RESULT_OK
) {
583 mSavedPlaybackPosition
= data
.getExtras().getInt(
584 PreviewVideoActivity
.EXTRA_START_POSITION
);
585 mAutoplay
= data
.getExtras().getBoolean(PreviewVideoActivity
.EXTRA_AUTOPLAY
);
590 private void playAudio() {
591 OCFile file
= getFile();
592 if (!mMediaServiceBinder
.isPlaying(file
)) {
593 Log_OC
.d(TAG
, "starting playback of " + file
.getStoragePath());
594 mMediaServiceBinder
.start(mAccount
, file
, mAutoplay
, mSavedPlaybackPosition
);
598 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
599 mMediaServiceBinder
.start();
600 mMediaController
.updatePausePlay();
606 private void bindMediaService() {
607 Log_OC
.d(TAG
, "Binding to MediaService...");
608 if (mMediaServiceConnection
== null
) {
609 mMediaServiceConnection
= new MediaServiceConnection();
611 getActivity().bindService( new Intent(getActivity(),
613 mMediaServiceConnection
,
614 Context
.BIND_AUTO_CREATE
);
615 // follow the flow in MediaServiceConnection#onServiceConnected(...)
618 /** Defines callbacks for service binding, passed to bindService() */
619 private class MediaServiceConnection
implements ServiceConnection
{
622 public void onServiceConnected(ComponentName component
, IBinder service
) {
623 if (getActivity() != null
) {
624 if (component
.equals(
625 new ComponentName(getActivity(), MediaService
.class))) {
626 Log_OC
.d(TAG
, "Media service connected");
627 mMediaServiceBinder
= (MediaServiceBinder
) service
;
628 if (mMediaServiceBinder
!= null
) {
629 prepareMediaController();
630 playAudio(); // do not wait for the touch of nobody to play audio
632 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
636 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
642 private void prepareMediaController() {
643 mMediaServiceBinder
.registerMediaController(mMediaController
);
644 if (mMediaController
!= null
) {
645 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
646 mMediaController
.setEnabled(true
);
647 mMediaController
.updatePausePlay();
652 public void onServiceDisconnected(ComponentName component
) {
653 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
654 Log_OC
.w(TAG
, "Media service suddenly disconnected");
655 if (mMediaController
!= null
) {
656 mMediaController
.setMediaPlayer(null
);
661 "No media controller to release when disconnected from media service",
662 Toast
.LENGTH_SHORT
).show();
664 mMediaServiceBinder
= null
;
665 mMediaServiceConnection
= null
;
672 * Opens the previewed file with an external application.
674 private void openFile() {
676 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
681 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment}
684 * @param file File to test if can be previewed.
685 * @return 'True' if the file can be handled by the fragment.
687 public static boolean canBePreviewed(OCFile file
) {
688 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
692 public void stopPreview(boolean stopAudio
) {
693 OCFile file
= getFile();
694 if (file
.isAudio() && stopAudio
) {
695 mMediaServiceBinder
.pause();
699 if (file
.isVideo()) {
700 mVideoPreview
.stopPlayback();
707 * Finishes the preview
709 private void finish() {
710 getActivity().onBackPressed();
714 public int getPosition() {
716 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
718 Log_OC
.v(TAG
, "getting position: " + mSavedPlaybackPosition
);
719 return mSavedPlaybackPosition
;
722 public boolean isPlaying() {
724 mAutoplay
= mVideoPreview
.isPlaying();