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