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 as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.preview
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import android
.accounts
.Account
;
25 import android
.app
.Activity
;
26 import android
.app
.AlertDialog
;
27 import android
.content
.ActivityNotFoundException
;
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
.media
.MediaPlayer
;
34 import android
.media
.MediaPlayer
.OnCompletionListener
;
35 import android
.media
.MediaPlayer
.OnErrorListener
;
36 import android
.media
.MediaPlayer
.OnPreparedListener
;
37 import android
.net
.Uri
;
38 import android
.os
.Bundle
;
39 import android
.os
.Handler
;
40 import android
.os
.IBinder
;
41 import android
.support
.v4
.app
.FragmentTransaction
;
42 import android
.util
.Log
;
43 import android
.view
.LayoutInflater
;
44 import android
.view
.MotionEvent
;
45 import android
.view
.View
;
46 import android
.view
.View
.OnTouchListener
;
47 import android
.view
.ViewGroup
;
48 import android
.webkit
.MimeTypeMap
;
49 import android
.widget
.ImageView
;
50 import android
.widget
.MediaController
;
51 import android
.widget
.Toast
;
52 import android
.widget
.VideoView
;
54 import com
.actionbarsherlock
.app
.SherlockFragment
;
55 import com
.actionbarsherlock
.view
.Menu
;
56 import com
.actionbarsherlock
.view
.MenuInflater
;
57 import com
.actionbarsherlock
.view
.MenuItem
;
58 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
59 import com
.owncloud
.android
.datamodel
.OCFile
;
60 import com
.owncloud
.android
.media
.MediaControlView
;
61 import com
.owncloud
.android
.media
.MediaService
;
62 import com
.owncloud
.android
.media
.MediaServiceBinder
;
63 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
64 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
65 import com
.owncloud
.android
.operations
.RemoteOperation
;
66 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
67 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
68 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
69 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
70 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
71 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
72 import com
.owncloud
.android
.ui
.fragment
.FileDetailFragment
;
73 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
75 import com
.owncloud
.android
.R
;
76 import eu
.alefzero
.webdav
.WebdavClient
;
77 import eu
.alefzero
.webdav
.WebdavUtils
;
80 * This fragment shows a preview of a downloaded media file (audio or video).
82 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
84 * By now, if the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
86 * @author David A. Velasco
88 public class PreviewMediaFragment
extends SherlockFragment
implements
89 OnTouchListener
, FileFragment
,
90 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
{
92 public static final String EXTRA_FILE
= "FILE";
93 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
94 private static final String EXTRA_PLAY_POSITION
= "PLAY_POSITION";
98 private Account mAccount
;
99 private FileDataStorageManager mStorageManager
;
100 private ImageView mImagePreview
;
101 private VideoView mVideoPreview
;
102 private int mSavedPlaybackPosition
;
104 private Handler mHandler
;
105 private RemoteOperation mLastRemoteOperation
;
107 private MediaServiceBinder mMediaServiceBinder
= null
;
108 //private MediaController mMediaController = null;
109 private MediaControlView mMediaController
= null
;
110 private MediaServiceConnection mMediaServiceConnection
= null
;
111 private VideoHelper mVideoHelper
;
113 private static final String TAG
= PreviewMediaFragment
.class.getSimpleName();
117 * Creates a fragment to preview a file.
119 * When 'fileToDetail' or 'ocAccount' are null
121 * @param fileToDetail An {@link OCFile} to preview in the fragment
122 * @param ocAccount An ownCloud account; needed to start downloads
124 public PreviewMediaFragment(OCFile fileToDetail
, Account ocAccount
) {
125 mFile
= fileToDetail
;
126 mAccount
= ocAccount
;
127 mSavedPlaybackPosition
= 0;
128 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
133 * Creates an empty fragment for previews.
135 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
137 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
139 public PreviewMediaFragment() {
142 mSavedPlaybackPosition
= 0;
143 mStorageManager
= null
;
151 public void onCreate(Bundle savedInstanceState
) {
152 super.onCreate(savedInstanceState
);
153 mHandler
= new Handler();
154 setHasOptionsMenu(true
);
162 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
163 Bundle savedInstanceState
) {
164 super.onCreateView(inflater
, container
, savedInstanceState
);
166 mView
= inflater
.inflate(R
.layout
.file_preview
, container
, false
);
168 mImagePreview
= (ImageView
)mView
.findViewById(R
.id
.image_preview
);
169 mImagePreview
.setOnTouchListener(this);
170 mVideoPreview
= (VideoView
)mView
.findViewById(R
.id
.video_preview
);
172 mMediaController
= (MediaControlView
)mView
.findViewById(R
.id
.media_controller
);
174 //updateFileDetails(false);
183 public void onAttach(Activity activity
) {
184 super.onAttach(activity
);
185 if (!(activity
instanceof FileFragment
.ContainerActivity
))
186 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
194 public void onActivityCreated(Bundle savedInstanceState
) {
195 super.onActivityCreated(savedInstanceState
);
197 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
198 if (savedInstanceState
!= null
) {
199 mFile
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_FILE
);
200 mAccount
= savedInstanceState
.getParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
);
201 mSavedPlaybackPosition
= savedInstanceState
.getInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
);
205 throw new IllegalStateException("Instanced with a NULL OCFile");
207 if (mAccount
== null
) {
208 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
210 if (!mFile
.isDown()) {
211 throw new IllegalStateException("There is no local file to preview");
213 if (mFile
.isVideo()) {
214 mVideoPreview
.setVisibility(View
.VISIBLE
);
215 mImagePreview
.setVisibility(View
.GONE
);
219 mVideoPreview
.setVisibility(View
.GONE
);
220 mImagePreview
.setVisibility(View
.VISIBLE
);
230 public void onSaveInstanceState(Bundle outState
) {
231 super.onSaveInstanceState(outState
);
233 outState
.putParcelable(PreviewMediaFragment
.EXTRA_FILE
, mFile
);
234 outState
.putParcelable(PreviewMediaFragment
.EXTRA_ACCOUNT
, mAccount
);
236 if (mVideoPreview
.isPlaying()) {
237 outState
.putInt(PreviewMediaFragment
.EXTRA_PLAY_POSITION
, mVideoPreview
.getCurrentPosition());
243 public void onStart() {
247 if (mFile
.isAudio()) {
250 } else if (mFile
.isVideo()) {
258 private void stopAudio() {
259 Intent i
= new Intent(getSherlockActivity(), MediaService
.class);
260 i
.setAction(MediaService
.ACTION_STOP_ALL
);
261 getSherlockActivity().startService(i
);
269 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
270 super.onCreateOptionsMenu(menu
, inflater
);
272 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
273 List
<Integer
> toHide
= new ArrayList
<Integer
>();
275 MenuItem item
= null
;
276 toHide
.add(R
.id
.action_cancel_download
);
277 toHide
.add(R
.id
.action_cancel_upload
);
278 toHide
.add(R
.id
.action_download_file
);
279 toHide
.add(R
.id
.action_rename_file
); // by now
281 for (int i
: toHide
) {
282 item
= menu
.findItem(i
);
284 item
.setVisible(false
);
285 item
.setEnabled(false
);
296 public boolean onOptionsItemSelected(MenuItem item
) {
297 switch (item
.getItemId()) {
298 case R
.id
.action_open_file_with
: {
302 case R
.id
.action_remove_file
: {
306 case R
.id
.action_see_details
: {
317 private void seeDetails() {
319 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
323 private void prepareVideo() {
324 // create helper to get more control on the playback
325 mVideoHelper
= new VideoHelper();
326 mVideoPreview
.setOnPreparedListener(mVideoHelper
);
327 mVideoPreview
.setOnCompletionListener(mVideoHelper
);
328 mVideoPreview
.setOnErrorListener(mVideoHelper
);
331 private void playVideo() {
332 // create and prepare control panel for the user
333 mMediaController
.setMediaPlayer(mVideoPreview
);
335 // load the video file in the video player ; when done, VideoHelper#onPrepared() will be called
336 mVideoPreview
.setVideoPath(mFile
.getStoragePath());
338 //mVideoPreview.setMediaController(mMediaController);
342 private class VideoHelper
implements OnCompletionListener
, OnPreparedListener
, OnErrorListener
{
345 * Called when the file is ready to be played.
347 * Just starts the playback.
349 * @param mp {@link MediaPlayer} instance performing the playback.
352 public void onPrepared(MediaPlayer vp
) {
353 mVideoPreview
.seekTo(mSavedPlaybackPosition
);
354 mVideoPreview
.start();
355 mMediaController
.setEnabled(true
);
356 mMediaController
.updatePausePlay();
357 //mMediaController.show(MediaService.MEDIA_CONTROL_SHORT_LIFE);
362 * Called when the file is finished playing.
364 * Finishes the activity.
366 * @param mp {@link MediaPlayer} instance performing the playback.
369 public void onCompletion(MediaPlayer mp
) {
370 // nothing, right now
375 * Called when an error in playback occurs.
377 * @param mp {@link MediaPlayer} instance performing the playback.
378 * @param what Type of error
379 * @param extra Extra code specific to the error
382 public boolean onError(MediaPlayer mp
, int what
, int extra
) {
383 Log
.e(TAG
, "Error in video playback, what = " + what
+ ", extra = " + extra
);
386 if (mMediaController != null) {
387 mMediaController.hide();
391 if (mVideoPreview
.getWindowToken() != null
) {
392 String message
= MediaService
.getMessageForMediaError(getActivity(), what
, extra
);
393 new AlertDialog
.Builder(getActivity())
395 .setPositiveButton(android
.R
.string
.VideoView_error_button
,
396 new DialogInterface
.OnClickListener() {
397 public void onClick(DialogInterface dialog
, int whichButton
) {
399 VideoHelper
.this.onCompletion(null
);
402 .setCancelable(false
)
412 public void onResume() {
418 public void onPause() {
424 public void onStop() {
426 if (mMediaServiceConnection
!= null
) {
427 Log
.d(TAG
, "Unbinding from MediaService ...");
428 if (mMediaServiceBinder
!= null
&& mMediaController
!= null
) {
429 //mMediaServiceBinder.unregisterMediaController(mMediaController);
431 getActivity().unbindService(mMediaServiceConnection
);
432 mMediaServiceConnection
= null
;
433 mMediaServiceBinder
= null
;
435 if (mMediaController != null) {
436 mMediaController.hide();
437 mMediaController = null;
444 public void onDestroy() {
450 public boolean onTouch(View v
, MotionEvent event
) {
451 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
452 if (v
== mImagePreview
&&
453 mMediaServiceBinder
!= null
&& mFile
.isAudio() && mMediaServiceBinder
.isPlaying(mFile
)) {
454 toggleMediaController(MediaService
.MEDIA_CONTROL_PERMANENT
);
457 } else if (v
== mVideoPreview
) {
458 toggleMediaController(MediaService
.MEDIA_CONTROL_SHORT_LIFE
);
466 private void toggleMediaController(int time
) {
468 if (mMediaController.isShowing()) {
469 mMediaController.hide();
471 mMediaController.show(time);
477 private void playAudio() {
478 if (!mMediaServiceBinder
.isPlaying(mFile
)) {
479 Log
.d(TAG
, "starting playback of " + mFile
.getStoragePath());
480 mMediaServiceBinder
.start(mAccount
, mFile
);
483 if (!mMediaServiceBinder
.isPlaying()) {
484 mMediaServiceBinder
.start();
487 if (!mMediaController.isShowing() && isVisible()) {
488 //mMediaController.show(MediaService.MEDIA_CONTROL_PERMANENT);
489 // TODO - fix strange bug; steps to trigger :
490 // 1. remove the "isVisible()" control
491 // 2. start the app and preview an audio file
492 // 3. exit from the app (home button, for instance) while the audio file is still being played
493 // 4. go to notification bar and click on the "ownCloud music app" notification
501 private void bindMediaService() {
502 Log
.d(TAG
, "Binding to MediaService...");
503 if (mMediaServiceConnection
== null
) {
504 mMediaServiceConnection
= new MediaServiceConnection();
506 getActivity().bindService( new Intent(getActivity(),
508 mMediaServiceConnection
,
509 Context
.BIND_AUTO_CREATE
);
510 // follow the flow in MediaServiceConnection#onServiceConnected(...)
513 /** Defines callbacks for service binding, passed to bindService() */
514 private class MediaServiceConnection
implements ServiceConnection
{
517 public void onServiceConnected(ComponentName component
, IBinder service
) {
518 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
519 Log
.d(TAG
, "Media service connected");
520 mMediaServiceBinder
= (MediaServiceBinder
) service
;
521 if (mMediaServiceBinder
!= null
) {
523 if (mMediaController == null) {
524 mMediaController = new MediaController(getSherlockActivity());
527 prepareMediaController();
528 playAudio(); // do not wait for the touch of nobody to play audio
530 Log
.d(TAG
, "Successfully bound to MediaService, MediaController ready");
533 Log
.e(TAG
, "Unexpected response from MediaService while binding");
538 private void prepareMediaController() {
539 //mMediaServiceBinder.registerMediaController(mMediaController);
540 if (mMediaController
!= null
) {
541 mMediaController
.setMediaPlayer(mMediaServiceBinder
);
542 mMediaController
.setEnabled(true
);
543 mMediaController
.updatePausePlay();
548 public void onServiceDisconnected(ComponentName component
) {
549 if (component
.equals(new ComponentName(getActivity(), MediaService
.class))) {
550 Log
.e(TAG
, "Media service suddenly disconnected");
551 if (mMediaController
!= null
) {
552 //mMediaController.hide();
553 mMediaController
.setMediaPlayer(null
);
554 //mMediaController = null;
556 Toast
.makeText(getActivity(), "No media controller to release when disconnected from media service", Toast
.LENGTH_SHORT
).show();
558 mMediaServiceBinder
= null
;
559 mMediaServiceConnection
= null
;
567 * Opens the previewed file with an external application.
569 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
570 * we should get a list of available apps for MIME tpye in the server and join it with the list of
571 * available apps for the MIME type known from the file extension, to let the user choose
573 private void openFile() {
575 String storagePath
= mFile
.getStoragePath();
576 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
578 Intent i
= new Intent(Intent
.ACTION_VIEW
);
579 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
580 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
583 } catch (Throwable t
) {
584 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
585 boolean toastIt
= true
;
586 String mimeType
= "";
588 Intent i
= new Intent(Intent
.ACTION_VIEW
);
589 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
590 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
591 if (mimeType
!= null
) {
592 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
595 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
597 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
602 } catch (IndexOutOfBoundsException e
) {
603 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
605 } catch (ActivityNotFoundException e
) {
606 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
608 } catch (Throwable th
) {
609 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
613 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
622 * Starts a the removal of the previewed file.
624 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
625 * depending upon the user selection in the dialog.
627 private void removeFile() {
628 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
629 R
.string
.confirmation_remove_alert
,
630 new String
[]{mFile
.getFileName()},
631 R
.string
.confirmation_remove_remote_and_local
,
632 R
.string
.confirmation_remove_local
,
633 R
.string
.common_cancel
);
634 confDialog
.setOnConfirmationListener(this);
635 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
640 * Performs the removal of the previewed file, both locally and in the server.
643 public void onConfirmation(String callerTag
) {
644 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
646 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
649 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
650 mLastRemoteOperation
.execute(wc
, this, mHandler
);
652 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
653 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
659 * Removes the file from local storage
662 public void onNeutral(String callerTag
) {
663 // TODO this code should be made in a secondary thread,
664 if (mFile
.isDown()) { // checks it is still there
666 File f
= new File(mFile
.getStoragePath());
668 mFile
.setStoragePath(null
);
669 mStorageManager
.saveFile(mFile
);
675 * User cancelled the removal action.
678 public void onCancel(String callerTag
) {
679 // nothing to do here
686 public OCFile
getFile(){
692 * Use this method to signal this Activity that it shall update its view.
694 * @param file : An {@link OCFile}
696 public void updateFileDetails(OCFile file, Account ocAccount) {
698 if (ocAccount != null && (
699 mStorageManager == null ||
700 (mAccount != null && !mAccount.equals(ocAccount))
702 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
704 mAccount = ocAccount;
705 updateFileDetails(false);
711 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewMediaFragment} to be previewed.
713 * @param file File to test if can be previewed.
714 * @return 'True' if the file can be handled by the fragment.
716 public static boolean canBePreviewed(OCFile file
) {
717 return (file
!= null
&& (file
.isAudio() || file
.isVideo()));
724 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
725 if (operation
.equals(mLastRemoteOperation
)) {
726 if (operation
instanceof RemoveFileOperation
) {
727 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
732 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
733 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
734 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
736 if (result
.isSuccess()) {
737 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
742 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
744 if (result
.isSslRecoverableException()) {
745 // TODO show the SSL warning dialog
750 private void stopPreview(boolean stopAudio
) {
751 if (mMediaController
!= null
) {
752 //mMediaController.hide();
754 if (mFile
.isAudio() && stopAudio
) {
755 mMediaServiceBinder
.pause();
757 } else if (mFile
.isVideo()) {
758 mVideoPreview
.stopPlayback();
765 * Finishes the preview
767 private void finish() {
768 Activity container
= getActivity();
769 if (container
instanceof FileDisplayActivity
) {
771 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
772 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FileDetailFragment
.FTAG
); // empty FileDetailFragment
773 transaction
.commit();
774 ((FileFragment
.ContainerActivity
)container
).onFileStateChanged();