-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
__init__.py
349 lines (301 loc) · 11 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""main module for spotcast homeassistant utility"""
from __future__ import annotations
__version__ = "3.7.1"
import collections
import logging
import time
import homeassistant
from homeassistant.components import websocket_api
from homeassistant.const import CONF_ENTITY_ID, CONF_OFFSET, CONF_REPEAT
from homeassistant.core import callback
import homeassistant.core as ha_core
from .const import (
CONF_ACCOUNTS,
CONF_DEVICE_NAME,
CONF_FORCE_PLAYBACK,
CONF_IGNORE_FULLY_PLAYED,
CONF_RANDOM,
CONF_SHUFFLE,
CONF_SP_DC,
CONF_SP_KEY,
CONF_SPOTIFY_ACCOUNT,
CONF_SPOTIFY_DEVICE_ID,
CONF_SPOTIFY_URI,
CONF_SPOTIFY_SEARCH,
CONF_SPOTIFY_CATEGORY,
CONF_SPOTIFY_COUNTRY,
CONF_SPOTIFY_LIMIT,
CONF_START_VOL,
DOMAIN,
SCHEMA_PLAYLISTS,
SCHEMA_WS_ACCOUNTS,
SCHEMA_WS_CASTDEVICES,
SCHEMA_WS_DEVICES,
SCHEMA_WS_PLAYER,
SERVICE_START_COMMAND_SCHEMA,
SPOTCAST_CONFIG_SCHEMA,
WS_TYPE_SPOTCAST_ACCOUNTS,
WS_TYPE_SPOTCAST_CASTDEVICES,
WS_TYPE_SPOTCAST_DEVICES,
WS_TYPE_SPOTCAST_PLAYER,
WS_TYPE_SPOTCAST_PLAYLISTS,
)
from .helpers import (
async_wrap,
get_cast_devices,
get_spotify_devices,
get_spotify_install_status,
get_spotify_media_player,
is_empty_str,
get_random_playlist_from_category,
get_search_results,
is_valid_uri,
)
from .spotcast_controller import SpotcastController
CONFIG_SCHEMA = SPOTCAST_CONFIG_SCHEMA
_LOGGER = logging.getLogger(__name__)
def setup(hass: ha_core.HomeAssistant, config: collections.OrderedDict) -> bool:
"""setup method for integration with Home Assistant
Args:
hass (ha_core.HomeAssistant): the HomeAssistant object of the
server
config (collections.OrderedDict): the configuration of the
server
Returns:
bool: returns a bollean based on if the setup wroked or not
"""
# get spotify core integration status
# if return false, could indicate a bad spotify integration. Race
# condition doesn't permit us to abort setup, see #258
if not get_spotify_install_status(hass):
_LOGGER.debug(
"Spotify integration was not found, please verify integration is "
"functionnal. Could result in python error..."
)
# Setup the Spotcast service.
conf = config[DOMAIN]
sp_dc = conf[CONF_SP_DC]
sp_key = conf[CONF_SP_KEY]
accounts = conf.get(CONF_ACCOUNTS)
spotcast_controller = SpotcastController(hass, sp_dc, sp_key, accounts)
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
hass.data[DOMAIN]["controller"] = spotcast_controller
@callback
def websocket_handle_playlists(
hass: ha_core.HomeAssistant,
connection,
msg: str
):
@async_wrap
def get_playlist():
"""Handle to get playlist"""
playlist_type = msg.get("playlist_type")
country_code = msg.get("country_code")
locale = msg.get("locale", "en")
limit = msg.get("limit", 10)
account = msg.get("account", None)
_LOGGER.debug("websocket_handle_playlists msg: %s", msg)
resp = spotcast_controller.get_playlists(
account, playlist_type, country_code, locale, limit
)
connection.send_message(
websocket_api.result_message(msg["id"], resp))
hass.async_add_job(get_playlist())
@callback
def websocket_handle_devices(
hass: ha_core.HomeAssistant,
connection,
msg: str,
):
@async_wrap
def get_devices():
"""Handle to get devices. Only for default account"""
account = msg.get("account", None)
client = spotcast_controller.get_spotify_client(account)
me_resp = client._get("me") # pylint: disable=W0212
spotify_media_player = get_spotify_media_player(
hass, me_resp["id"])
resp = get_spotify_devices(spotify_media_player)
connection.send_message(
websocket_api.result_message(msg["id"], resp))
hass.async_add_job(get_devices())
@callback
def websocket_handle_player(
hass: ha_core.HomeAssistant,
connection,
msg: str,
):
@async_wrap
def get_player():
"""Handle to get player"""
account = msg.get("account", None)
_LOGGER.debug("websocket_handle_player msg: %s", msg)
client = spotcast_controller.get_spotify_client(account)
resp = client._get("me/player") # pylint: disable=W0212
connection.send_message(
websocket_api.result_message(msg["id"], resp))
hass.async_add_job(get_player())
@callback
def websocket_handle_accounts(
hass: ha_core.HomeAssistant,
connection,
msg: str,
):
"""Handle to get accounts"""
_LOGGER.debug("websocket_handle_accounts msg: %s", msg)
resp = list(accounts.keys()) if accounts is not None else []
resp.append("default")
connection.send_message(websocket_api.result_message(msg["id"], resp))
@callback
def websocket_handle_castdevices(
hass: ha_core.HomeAssistant,
connection, msg: str
):
"""Handle to get cast devices for debug purposes"""
_LOGGER.debug("websocket_handle_castdevices msg: %s", msg)
known_devices = get_cast_devices(hass)
_LOGGER.debug("%s", known_devices)
resp = [
{
"uuid": str(cast_info.cast_info.uuid),
"model_name": cast_info.cast_info.model_name,
"friendly_name": cast_info.cast_info.friendly_name,
}
for cast_info in known_devices
]
connection.send_message(websocket_api.result_message(msg["id"], resp))
def start_casting(call: ha_core.ServiceCall):
"""service called."""
uri = call.data.get(CONF_SPOTIFY_URI)
category = call.data.get(CONF_SPOTIFY_CATEGORY)
country = call.data.get(CONF_SPOTIFY_COUNTRY)
limit = call.data.get(CONF_SPOTIFY_LIMIT)
search = call.data.get(CONF_SPOTIFY_SEARCH)
random_song = call.data.get(CONF_RANDOM, False)
repeat = call.data.get(CONF_REPEAT, False)
shuffle = call.data.get(CONF_SHUFFLE, False)
start_volume = call.data.get(CONF_START_VOL)
spotify_device_id = call.data.get(CONF_SPOTIFY_DEVICE_ID)
position = call.data.get(CONF_OFFSET)
force_playback = call.data.get(CONF_FORCE_PLAYBACK)
account = call.data.get(CONF_SPOTIFY_ACCOUNT)
ignore_fully_played = call.data.get(CONF_IGNORE_FULLY_PLAYED)
device_name = call.data.get(CONF_DEVICE_NAME)
entity_id = call.data.get(CONF_ENTITY_ID)
# if no market information try to get global setting
if is_empty_str(country):
try:
country = config[DOMAIN][CONF_SPOTIFY_COUNTRY]
except KeyError:
country = None
client = spotcast_controller.get_spotify_client(account)
# verify the uri provided and clean-up if required
if not is_empty_str(uri):
# remove ? from badly formatted URI
uri = uri.split("?")[0]
if not is_valid_uri(uri):
_LOGGER.error("Invalid URI provided, aborting casting")
return
# force first two elements of uri to lowercase
uri = uri.split(":")
uri[0] = uri[0].lower()
uri[1] = uri[1].lower()
uri = ':'.join(uri)
# first, rely on spotify id given in config otherwise get one
if not spotify_device_id:
spotify_device_id = spotcast_controller.get_spotify_device_id(
account, spotify_device_id, device_name, entity_id
)
if (
is_empty_str(uri)
and is_empty_str(search)
and is_empty_str(category)
):
_LOGGER.debug("Transfering playback")
current_playback = client.current_playback()
if current_playback is not None:
_LOGGER.debug("Current_playback from spotify: %s",
current_playback)
force_playback = True
_LOGGER.debug("Force playback: %s", force_playback)
client.transfer_playback(
device_id=spotify_device_id, force_play=force_playback
)
elif category:
uri = get_random_playlist_from_category(
client, category, country, limit)
if uri is None:
_LOGGER.error("No playlist returned. Stop service call")
return None
spotcast_controller.play(
client,
spotify_device_id,
uri,
random_song,
position,
ignore_fully_played,
)
else:
if is_empty_str(uri):
# get uri from search request
uri = get_search_results(search, client, country)
spotcast_controller.play(
client,
spotify_device_id,
uri,
random_song,
position,
ignore_fully_played,
)
if start_volume <= 100:
_LOGGER.debug("Setting volume to %d", start_volume)
time.sleep(2)
client.volume(volume_percent=start_volume,
device_id=spotify_device_id)
if shuffle:
_LOGGER.debug("Turning shuffle on")
time.sleep(3)
client.shuffle(state=shuffle, device_id=spotify_device_id)
if repeat:
_LOGGER.debug("Turning repeat on")
time.sleep(3)
client.repeat(state=repeat, device_id=spotify_device_id)
# Register websocket and service
websocket_api.async_register_command(
hass=hass,
command_or_handler=WS_TYPE_SPOTCAST_PLAYLISTS,
handler=websocket_handle_playlists,
schema=SCHEMA_PLAYLISTS,
)
websocket_api.async_register_command(
hass=hass,
command_or_handler=WS_TYPE_SPOTCAST_DEVICES,
handler=websocket_handle_devices,
schema=SCHEMA_WS_DEVICES,
)
websocket_api.async_register_command(
hass=hass,
command_or_handler=WS_TYPE_SPOTCAST_PLAYER,
handler=websocket_handle_player,
schema=SCHEMA_WS_PLAYER,
)
websocket_api.async_register_command(
hass=hass,
command_or_handler=WS_TYPE_SPOTCAST_ACCOUNTS,
handler=websocket_handle_accounts,
schema=SCHEMA_WS_ACCOUNTS,
)
websocket_api.async_register_command(
hass=hass,
command_or_handler=WS_TYPE_SPOTCAST_CASTDEVICES,
handler=websocket_handle_castdevices,
schema=SCHEMA_WS_CASTDEVICES,
)
hass.services.register(
domain=DOMAIN,
service="start",
service_func=start_casting,
schema=SERVICE_START_COMMAND_SCHEMA,
)
return True