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