Add spotify service to allow to play music from playlist (#24991)

* adding custom service to Spotify component to allow to play random playlist music

* fixing findings

* improving naming

* improving way of using required parameters
This commit is contained in:
Leandro Loureiro 2019-07-16 04:41:16 +02:00 committed by Martin Hjelmare
parent 25285ef6a7
commit dcb12a992a
2 changed files with 42 additions and 1 deletions

View File

@ -1,6 +1,7 @@
"""Support for interacting with Spotify Connect."""
from datetime import timedelta
import logging
import random
import voluptuous as vol
@ -10,7 +11,8 @@ from homeassistant.components.media_player import (
from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC, MEDIA_TYPE_PLAYLIST, SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK,
SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_VOLUME_SET)
SUPPORT_SELECT_SOURCE, SUPPORT_SHUFFLE_SET, SUPPORT_VOLUME_SET,
ATTR_MEDIA_CONTENT_ID)
from homeassistant.const import (
CONF_NAME, STATE_IDLE, STATE_PAUSED, STATE_PLAYING)
from homeassistant.core import callback
@ -35,6 +37,14 @@ DEFAULT_CACHE_PATH = '.spotify-token-cache'
DEFAULT_NAME = 'Spotify'
DOMAIN = 'spotify'
SERVICE_PLAY_PLAYLIST = 'play_playlist'
ATTR_RANDOM_SONG = 'random_song'
PLAY_PLAYLIST_SCHEMA = vol.Schema({
vol.Required(ATTR_MEDIA_CONTENT_ID): cv.string,
vol.Optional(ATTR_RANDOM_SONG, default=False): cv.boolean
})
ICON = 'mdi:spotify'
SCAN_INTERVAL = timedelta(seconds=30)
@ -90,6 +100,16 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
oauth, config.get(CONF_NAME, DEFAULT_NAME), config[CONF_ALIASES])
add_entities([player], True)
def play_playlist_service(service):
media_content_id = service.data[ATTR_MEDIA_CONTENT_ID]
random_song = service.data.get(ATTR_RANDOM_SONG)
player.play_playlist(media_content_id, random_song)
hass.services.register(
DOMAIN, SERVICE_PLAY_PLAYLIST,
play_playlist_service,
schema=PLAY_PLAYLIST_SCHEMA)
class SpotifyAuthCallbackView(HomeAssistantView):
"""Spotify Authorization Callback View."""
@ -253,6 +273,18 @@ class SpotifyMediaPlayer(MediaPlayerDevice):
return
self._player.start_playback(**kwargs)
def play_playlist(self, media_id, random_song):
"""Play random music in a playlist."""
if not media_id.startswith('spotify:playlist:'):
_LOGGER.error("media id must be spotify playlist uri")
return
kwargs = {'context_uri': media_id}
if random_song:
results = self._player.user_playlist_tracks("me", media_id)
position = random.randint(0, results['total'] - 1)
kwargs['offset'] = {'position': position}
self._player.start_playback(**kwargs)
@property
def name(self):
"""Return the name."""

View File

@ -0,0 +1,9 @@
play_playlist:
description: Play a Spotify playlist.
fields:
media_content_id:
description: Spotify URI of the playlist.
example: 'spotify:playlist:0IpRnqCHSjun48oQRX1Dy7'
random_song:
description: True to select random song at start, False to start from beginning.
example: true