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