1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package com
.owncloud
.android
.ui
.preview
;
19 import java
.util
.ArrayList
;
20 import java
.util
.List
;
22 import android
.accounts
.Account
;
23 import android
.app
.Activity
;
24 import android
.app
.AlertDialog
;
25 import android
.content
.ComponentName
;
26 import android
.content
.Context
;
27 import android
.content
.DialogInterface
;
28 import android
.content
.Intent
;
29 import android
.content
.ServiceConnection
;
30 import android
.content
.res
.Configuration
;
31 import android
.media
.MediaPlayer
;
32 import android
.media
.MediaPlayer
.OnCompletionListener
;
33 import android
.media
.MediaPlayer
.OnErrorListener
;
34 import android
.media
.MediaPlayer
.OnPreparedListener
;
35 import android
.os
.Build
;
36 import android
.os
.Bundle
;
37 import android
.os
.IBinder
;
38 import android
.view
.LayoutInflater
;
39 import android
.view
.MotionEvent
;
40 import android
.view
.View
;
41 import android
.view
.View
.OnTouchListener
;
42 import android
.view
.ViewGroup
;
43 import android
.widget
.ImageView
;
44 import android
.widget
.Toast
;
45 import android
.widget
.VideoView
;
47 import com
.actionbarsherlock
.view
.Menu
;
48 import com
.actionbarsherlock
.view
.MenuInflater
;
49 import com
.actionbarsherlock
.view
.MenuItem
;
50 import com
.owncloud
.android
.R
;
51 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
52 import com
.owncloud
.android
.datamodel
.OCFile
;
53 import com
.owncloud
.android
.media
.MediaControlView
;
54 import com
.owncloud
.android
.media
.MediaService
;
55 import com
.owncloud
.android
.media
.MediaServiceBinder
;
56 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
57 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
58 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
59 import com
.owncloud
.android
.utils
.Log_OC
;
63 * This fragment shows a preview of a downloaded media file (audio or video).
65 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
67 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
69 * @author David A. Velasco
71 public class PreviewMediaFragment
extends FileFragment
implements
73 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
75 public static final String EXTRA_FILE
= "FILE";
76 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
77 private static final String EXTRA_PLAY_POSITION
= "PLAY_POSITION";
78 private static final String EXTRA_PLAYING
= "PLAYING";
81 private Account mAccount
;
82 private ImageView mImagePreview
;
83 private VideoView mVideoPreview
;
84 private int mSavedPlaybackPosition
;
86 private MediaServiceBinder mMediaServiceBinder
= null
;
87 private MediaControlView mMediaController
= null
;
88 private MediaServiceConnection mMediaServiceConnection
= null
;
89 private VideoHelper mVideoHelper
;
90 private boolean mAutoplay
;
91 public boolean mPrepared
;
93 private FileFragment
.ContainerActivity mContainerActivity
;
95 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
99 * Creates a fragment to preview a file.
101 * When 'fileToDetail' or 'ocAccount' are null
103 * @param fileToDetail An {@link OCFile} to preview in the fragment
104 * @param ocAccount An ownCloud account; needed to start downloads
106 public PreviewMediaFragment(OCFile fileToDetail
, Account ocAccount
, int startPlaybackPosition
, boolean autoplay
) {
108 mAccount
= ocAccount
;
109 mSavedPlaybackPosition
= startPlaybackPosition
;
110 mAutoplay
= autoplay
;
115 * Creates an empty fragment for previews.
117 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
119 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
121 public PreviewMediaFragment() {
124 mSavedPlaybackPosition
= 0;
133 public void onCreate(Bundle savedInstanceState
) {
134 super.onCreate(savedInstanceState
);
135 setHasOptionsMenu(true
);
143 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
144 Bundle savedInstanceState
) {
145 super.onCreateView(inflater
, container
, savedInstanceState
);
146 Log_OC
.e(TAG
, "onCreateView");
149 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
151 mImagePreview
= (ImageView
)mView
.findViewById(R
.id
.image_preview
);
152 mVideoPreview
= (VideoView
)mView
.findViewById(R
.id
.video_preview
);
153 mVideoPreview
.setOnTouchListener(this);
155 mMediaController
= (MediaControlView
)mView
.findViewById(R
.id
.media_controller
);
165 public void onActivityCreated(Bundle savedInstanceState
) {
166 super.onActivityCreated(savedInstanceState
);
167 Log_OC
.e(TAG
, "onActivityCreated");
169 if (savedInstanceState
!= null
) {
170 setFile((OCFile
)savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
));
171 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
172 mSavedPlaybackPosition
= savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
173 mAutoplay
= savedInstanceState
.getBoolean(PreviewMediaFragment
.EXTRA_PLAYING
);
176 OCFile file
= getFile();
178 throw new IllegalStateException("Instanced with a NULL OCFile");
180 if (mAccount
== null
) {
181 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
183 if (!file
.isDown()) {
184 throw new IllegalStateException("There is no local file to preview");
186 if (file
.isVideo()) {
187 mVideoPreview
.setVisibility(View
.VISIBLE
);
188 mImagePreview
.setVisibility(View
.GONE
);
192 mVideoPreview
.setVisibility(View
.GONE
);
193 mImagePreview
.setVisibility(View
.VISIBLE
);
203 public void onSaveInstanceState(Bundle outState
) {
204 super.onSaveInstanceState(outState
);
205 Log_OC
.e(TAG
, "onSaveInstanceState");
207 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, getFile());
208 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
210 if (getFile().isVideo()) {
211 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
212 mAutoplay
= mVideoPreview
.isPlaying();
213 outState
.putInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
, mSavedPlaybackPosition
);
214 outState
.putBoolean(PreviewMediaFragment
.EXTRA_PLAYING
, mAutoplay
);
216 outState
.putInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
, mMediaServiceBinder
.getCurrentPosition());
217 outState
.putBoolean(PreviewMediaFragment
.EXTRA_PLAYING
, mMediaServiceBinder
.isPlaying());
223 public void onStart() {
225 Log_OC
.e(TAG
, "onStart");
227 OCFile file
= getFile();
229 if (file
.isAudio()) {
232 } else if (file
.isVideo()) {
240 private void stopAudio() {
241 Intent i
= new Intent(getSherlockActivity(), MediaService
.class);
242 i
.setAction(MediaService
.ACTION_STOP_ALL
);
243 getSherlockActivity().startService(i
);
251 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
252 super.onCreateOptionsMenu(menu
, inflater
);
254 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
255 List
<Integer
> toHide
= new ArrayList
<Integer
>();
257 MenuItem item
= null
;
258 toHide
.add(R
.id
.action_cancel_download
);
259 toHide
.add(R
.id
.action_cancel_upload
);
260 toHide
.add(R
.id
.action_download_file
);
261 toHide
.add(R
.id
.action_sync_file
);
262 toHide
.add(R
.id
.action_rename_file
); // by now
265 if (!getFile().isShareByLink()) {
266 toHide
.add(R
.id
.action_unshare_file
);
270 boolean sendEnabled
= getString(R
.string
.send_files_to_other_apps
).equalsIgnoreCase("on");
272 toHide
.add(R
.id
.action_send_file
);
275 for (int i
: toHide
) {
276 item
= menu
.findItem(i
);
278 item
.setVisible(false
);
279 item
.setEnabled(false
);
290 public void onPrepareOptionsMenu(Menu menu
) {
291 super.onPrepareOptionsMenu(menu
);
293 MenuItem item
= menu
.findItem(R
.id
.action_unshare_file
);
295 if (!getFile().isShareByLink()) {
296 item
.setVisible(false
);
297 item
.setEnabled(false
);
299 item
.setVisible(true
);
300 item
.setEnabled(true
);
309 public boolean onOptionsItemSelected(MenuItem item
) {
310 switch (item
.getItemId()) {
311 case R
.id
.action_share_file
: {
315 case R
.id
.action_unshare_file
: {
316 unshareFileWithLink();
319 case R
.id
.action_open_file_with
: {
323 case R
.id
.action_remove_file
: {
327 case R
.id
.action_see_details
: {
331 case R
.id
.action_send_file
: {
343 * Update the file of the fragment with file value
346 public void updateFile(OCFile file
){
350 private void unshareFileWithLink() {
352 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
355 private void shareFileWithLink() {
357 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
361 private void sendFile() {
363 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
367 private void seeDetails() {
369 mContainerActivity
.showDetails(getFile());
373 private void prepareVideo() {
374 // create helper to get more control on the playback
375 mVideoHelper
= new VideoHelper();
376 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
377 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
378 mVideoPreview
.setOnErrorListener(mVideoHelper
);
381 private void playVideo() {
382 // create and prepare control panel for the user
383 mMediaController
.setMediaPlayer(mVideoPreview
);
385 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
386 mVideoPreview
.setVideoPath(getFile().getStoragePath());
390 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
393 * Called when the file is ready to be played.
395 * Just starts the playback.
397 * @param mp {@link MediaPlayer} instance performing the playback.
400 public void onPrepared(MediaPlayer vp
) {
401 Log_OC
.e(TAG
, "onPrepared");
402 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
404 mVideoPreview
.start();
406 mMediaController
.setEnabled(true
);
407 mMediaController
.updatePausePlay();
413 * Called when the file is finished playing.
415 * Finishes the activity.
417 * @param mp {@link MediaPlayer} instance performing the playback.
420 public void onCompletion(MediaPlayer mp
) {
421 Log_OC
.e(TAG
, "completed");
423 mVideoPreview
.seekTo(0);
424 // next lines are necessary to work around undesired video loops
425 if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD
) {
426 mVideoPreview
.pause();
428 } else if (Build
.VERSION
.SDK_INT
== Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
429 // mVideePreview.pause() is not enough
431 mMediaController
.setEnabled(false
);
432 mVideoPreview
.stopPlayback();
434 mSavedPlaybackPosition
= 0;
435 mVideoPreview
.setVideoPath(getFile().getStoragePath());
437 } // else : called from onError()
438 mMediaController
.updatePausePlay();
443 * Called when an error in playback occurs.
445 * @param mp {@link MediaPlayer} instance performing the playback.
446 * @param what Type of error
447 * @param extra Extra code specific to the error
450 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
451 if (mVideoPreview
.getWindowToken() != null
) {
452 String message
= MediaService
.getMessageForMediaError(getSherlockActivity(), what
, extra
);
453 new AlertDialog
.Builder(getSherlockActivity())
455 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
456 new DialogInterface
.OnClickListener() {
457 public void onClick(DialogInterface dialog
, int whichButton
) {
459 VideoHelper
.this.onCompletion(null
);
462 .setCancelable(false
)
472 public void onPause() {
474 Log_OC
.e(TAG
, "onPause");
478 public void onResume() {
480 Log_OC
.e(TAG
, "onResume");
484 public void onDestroy() {
486 Log_OC
.e(TAG
, "onDestroy");
490 public void onStop() {
491 Log_OC
.e(TAG
, "onStop");
495 if (mMediaServiceConnection
!= null
) {
496 Log_OC
.d(TAG
, "Unbinding from MediaService ...");
497 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
498 mMediaServiceBinder
.unregisterMediaController(mMediaController
);
500 getSherlockActivity().unbindService(mMediaServiceConnection
);
501 mMediaServiceConnection
= null
;
502 mMediaServiceBinder
= null
;
507 public boolean onTouch(View v
, MotionEvent event
) {
508 if (event
.getAction() == MotionEvent
.ACTION_DOWN
&& v
== mVideoPreview
) {
509 startFullScreenVideo();
516 private void startFullScreenVideo() {
517 Intent i
= new Intent(getSherlockActivity(), PreviewVideoActivity
.class);
518 i
.putExtra(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
519 i
.putExtra(FileActivity
.EXTRA_FILE
, getFile());
520 i
.putExtra(PreviewVideoActivity
.EXTRA_AUTOPLAY
, mVideoPreview
.isPlaying());
521 mVideoPreview
.pause();
522 i
.putExtra(PreviewVideoActivity
.EXTRA_START_POSITION
, mVideoPreview
.getCurrentPosition());
523 startActivityForResult(i
, 0);
527 public void onConfigurationChanged (Configuration newConfig
) {
528 Log_OC
.e(TAG
, "onConfigurationChanged " + this);
532 public void onActivityResult (int requestCode
, int resultCode
, Intent data
) {
533 Log_OC
.e(TAG
, "onActivityResult " + this);
534 super.onActivityResult(requestCode
, resultCode
, data
);
535 if (resultCode
== Activity
.RESULT_OK
) {
536 mSavedPlaybackPosition
= data
.getExtras().getInt(PreviewVideoActivity
.EXTRA_START_POSITION
);
537 mAutoplay
= data
.getExtras().getBoolean(PreviewVideoActivity
.EXTRA_AUTOPLAY
);
542 private void playAudio() {
543 OCFile file
= getFile();
544 if (!mMediaServiceBinder
.isPlaying(file
)) {
545 Log_OC
.d(TAG
, "starting playback of " + file
.getStoragePath());
546 mMediaServiceBinder
.start(mAccount
, file
, mAutoplay
, mSavedPlaybackPosition
);
549 if (!mMediaServiceBinder
.isPlaying() && mAutoplay
) {
550 mMediaServiceBinder
.start();
551 mMediaController
.updatePausePlay();
557 private void bindMediaService() {
558 Log_OC
.d(TAG
, "Binding to MediaService...");
559 if (mMediaServiceConnection
== null
) {
560 mMediaServiceConnection
= new MediaServiceConnection();
562 getSherlockActivity().bindService( new Intent(getSherlockActivity(),
564 mMediaServiceConnection
,
565 Context
.BIND_AUTO_CREATE
);
566 // follow the flow in MediaServiceConnection#onServiceConnected(...)
569 /** Defines callbacks for service binding, passed to bindService() */
570 private class MediaServiceConnection
implements ServiceConnection
{
573 public void onServiceConnected(ComponentName component
, IBinder service
) {
574 if (getSherlockActivity() != null
) {
575 if (component
.equals(new ComponentName(getSherlockActivity(), MediaService
.class))) {
576 Log_OC
.d(TAG
, "Media service connected");
577 mMediaServiceBinder
= (MediaServiceBinder
) service
;
578 if (mMediaServiceBinder
!= null
) {
579 prepareMediaController();
580 playAudio(); // do not wait for the touch of nobody to play audio
582 Log_OC
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
585 Log_OC
.e(TAG
, "Unexpected response from MediaService while binding");
591 private void prepareMediaController() {
592 mMediaServiceBinder
.registerMediaController(mMediaController
);
593 if (mMediaController
!= null
) {
594 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
595 mMediaController
.setEnabled(true
);
596 mMediaController
.updatePausePlay();
601 public void onServiceDisconnected(ComponentName component
) {
602 if (component
.equals(new ComponentName(getSherlockActivity(), MediaService
.class))) {
603 Log_OC
.e(TAG
, "Media service suddenly disconnected");
604 if (mMediaController
!= null
) {
605 mMediaController
.setMediaPlayer(null
);
607 Toast
.makeText(getSherlockActivity(), "No media controller to release when disconnected from media service", Toast
.LENGTH_SHORT
).show();
609 mMediaServiceBinder
= null
;
610 mMediaServiceConnection
= null
;
618 * Opens the previewed file with an external application.
620 private void openFile() {
622 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
627 * Starts a the removal of the previewed file.
629 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
630 * depending upon the user selection in the dialog.
632 private void removeFile() {
633 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
634 R
.string
.confirmation_remove_alert
,
635 new String
[]{getFile().getFileName()},
636 R
.string
.confirmation_remove_remote_and_local
,
637 R
.string
.confirmation_remove_local
,
638 R
.string
.common_cancel
);
639 confDialog
.setOnConfirmationListener(this);
640 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
645 * Performs the removal of the previewed file, both locally and in the server.
648 public void onConfirmation(String callerTag
) {
649 OCFile file
= getFile();
650 FileDataStorageManager storageManager
= mContainerActivity
.getStorageManager();
651 if (storageManager
.getFileById(file
.getFileId()) != null
) { // check that the file is still there;
653 mContainerActivity
.getFileOperationsHelper().removeFile(file
, true
);
659 * Removes the file from local storage
662 public void onNeutral(String callerTag
) {
663 OCFile file
= getFile();
665 mContainerActivity
.getStorageManager().removeFile(file
, false
, true
); // TODO perform in background task / new thread
670 * User cancelled the removal action.
673 public void onCancel(String callerTag
) {
674 // nothing to do here
679 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
681 * @param file File to test if can be previewed.
682 * @return 'True' if the file can be handled by the fragment.
684 public static boolean canBePreviewed(OCFile file
) {
685 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
689 private void stopPreview(boolean stopAudio
) {
690 OCFile file
= getFile();
691 if (file
.isAudio() && stopAudio
) {
692 mMediaServiceBinder
.pause();
694 } else if (file
.isVideo()) {
695 mVideoPreview
.stopPlayback();
702 * Finishes the preview
704 private void finish() {
705 getSherlockActivity().onBackPressed();
709 public int getPosition() {
711 mSavedPlaybackPosition
= mVideoPreview
.getCurrentPosition();
713 Log_OC
.e(TAG
, "getting position: " + mSavedPlaybackPosition
);
714 return mSavedPlaybackPosition
;
717 public boolean isPlaying() {
719 mAutoplay
= mVideoPreview
.isPlaying();