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