This repository has been archived by the owner on Nov 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caster.py
661 lines (516 loc) · 18.2 KB
/
caster.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
import pychromecast
from pychromecast.controllers.media import ( # noqa: F401
MEDIA_PLAYER_STATE_PLAYING,
MEDIA_PLAYER_STATE_PAUSED,
MEDIA_PLAYER_STATE_BUFFERING,
MEDIA_PLAYER_STATE_IDLE,
MEDIA_PLAYER_STATE_UNKNOWN,
STREAM_TYPE_UNKNOWN,
STREAM_TYPE_BUFFERED,
STREAM_TYPE_LIVE
)
from pychromecast.controllers.spotify import SpotifyController
from mimetypes import MimeTypes
import logging
import threading
from datetime import datetime, timedelta
from util import formatTimeDelta
import os
import spotipy
import spotify_token
from time import time
logging.getLogger('pychromecast').setLevel(logging.WARN)
logger = logging.getLogger(__name__)
onError = lambda error: None # noqa: E731
deviceHosts = []
deviceHostScanTimer = None
_spotifyClient = None
DEVICE_HOST_SCAN_TIMEOUT = 15.0 # in seconds
CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL = 900.0 # in seconds
WAIT_FOR_PLAYBACK_TIMEOUT = 10.0 # in seconds
SPOTIFY_OAUTH_TOKENS_CACHE_PATH = os.path.join(
os.path.dirname(__file__), '.spotify-tokens')
SPOTIFY_OAUTH_SCOPE = ','.join((
'user-read-playback-state',
'user-modify-playback-state',
'user-read-currently-playing',
))
SPOTIFY_OAUTH_REDIRECT_SERVER_PORT = 5000
class DeviceNotFoundError(Exception):
pass
class SpotifyOAuthCredentialsError(Exception):
pass
class SpotifyPlaybackError(Exception):
pass
class DeviceStatusListener:
def __init__(self, device, callback):
self.device = device
self.callback = callback
def new_cast_status(self, status):
logger.debug('Device "{}" got new device status: {}'.format(
self.device.name,
status
))
self.callback(self.device, status)
class DeviceMediaStatusListener:
def __init__(self, device, callback):
self.device = device
self.callback = callback
self.lastPlayerState = None
def new_media_status(self, status):
logger.debug('Device "{}" got new media status: {}'.format(
self.device.name,
status
))
if self.lastPlayerState and \
self.lastPlayerState == status.player_state:
return
self.lastPlayerState = status.player_state
self.callback(self.device, status)
def setup(logLevel=None, errorHandler=None):
global onError
if logLevel:
logger.setLevel(logLevel)
logger.info('Setting up...')
if errorHandler:
onError = errorHandler
_setupSpotifyClient()
if not scanForDeviceHosts():
logger.error('Setup completed with failing scanner')
else:
logger.info('Setup completed')
def scanForDeviceHosts():
'''
Returns: Bool Whether scanner returned any device hosts or not
'''
global deviceHosts, deviceHostScanTimer
# cancel currently running scanner, if any
cancelDeviceHostScanner()
logger.debug('Scanning for device hosts...')
startTime = datetime.utcnow()
deviceHosts = pychromecast.discover_chromecasts(
timeout=DEVICE_HOST_SCAN_TIMEOUT
)
formattedScanTime = formatTimeDelta(datetime.utcnow() - startTime)
formattedNextScanTimestamp = (
datetime.utcnow() +
timedelta(seconds=CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL)
).isoformat()
gotAcceptableSetOfHosts = deviceHosts is not None and len(deviceHosts) > 0
if not gotAcceptableSetOfHosts:
logger.error(
'Device host scan completed with no hosts found after {}. '
'Scheduling next scan for {}.'.format(
formattedScanTime,
formattedNextScanTimestamp
)
)
cancelDeviceHostScanner()
onError(
Exception('Device host scan completed with no device(s) found.')
)
else:
logger.info(
'Device scan completed with {} device(s) found after {}. '
'Scheduling next scan for {}.'.format(
len(deviceHosts),
formattedScanTime,
formattedNextScanTimestamp
)
)
# continue to scan every N seconds
deviceHostScanTimer = threading.Timer(
CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL,
scanForDeviceHosts
)
deviceHostScanTimer.daemon = True
deviceHostScanTimer.start()
return gotAcceptableSetOfHosts
def cancelDeviceHostScanner():
global deviceHostScanTimer
if deviceHostScanTimer is not None and deviceHostScanTimer.is_alive():
logger.debug('Canceling device host scanner')
deviceHostScanTimer.cancel()
deviceHostScanTimer = None
def getDevice(deviceName, calledFromSelf=False):
if not calledFromSelf:
logger.debug('Getting device "{}"'.format(deviceName))
try:
host = next(i for i in deviceHosts if i[-1] == deviceName)
device = pychromecast.Chromecast(host[0], host[1])
except StopIteration:
if not calledFromSelf:
logger.warning(
'Device "{}" not found - trigger new device scan'.format(
deviceName
)
)
scanForDeviceHosts()
return getDevice(deviceName, calledFromSelf=True)
else:
logger.warning(
'Device "{}" not found (tried scanning anew)'.format(
deviceName
)
)
raise DeviceNotFoundError(
'Device "{}" not found'.format(deviceName)
)
# start worker thread and wait for cast device to be ready
logger.debug('Device "{}" found, connecting...'.format(deviceName))
device.wait()
logger.debug('Connected to "{}"'.format(deviceName))
return device
def stop(device, disconnectFromDevice=False):
if not device:
return
logger.info('Stopping playback on "{}"'.format(device.name))
try:
_pauseSpotify()
except (Exception, SpotifyPlaybackError):
logger.exception('Failed to pause Spotify playback')
try:
device.media_controller.stop()
except pychromecast.error.ControllerNotRegistered as e:
logger.error('Failed to stop: {}'.format(e))
onError(e)
return
if disconnectFromDevice:
logger.info(
'Playback stopped on "{}" - disconnecting..'.format(device.name)
)
device.disconnect(blocking=False)
def quit(device, disconnectFromDevice=False):
if not device:
return
logger.info('Closing Chromecast application on "{}"'.format(device.name))
try:
if device.app_id:
device.quit_app()
else:
logger.info(
' - no Chromecast application active '
'on "{}"!'.format(device.name)
)
except pychromecast.error.ControllerNotRegistered as e:
logger.error('Failed to quit: {}'.format(e))
onError(e)
return
if disconnectFromDevice:
logger.info('Disconnecting from "{}"'.format(device.name))
device.disconnect(blocking=False)
def setVolume(device, volume, callback=None, disconnectFromDevice=False):
if not device:
return
logger.info(
'Setting volume to {}% on "{}"'.format(
volume * 100,
device.name
)
)
try:
device.set_volume(volume)
except pychromecast.error.ControllerNotRegistered as e:
logger.error('Failed to set volume: {}'.format(e))
onError(e)
return
if callback is not None:
logger.info(
'Volume set on "{}" - disconnecting...'.format(device.name)
)
device.disconnect()
if disconnectFromDevice:
logger.info(
'Volume set on "{}" - disconnecting...'.format(device.name)
)
device.disconnect()
def isPlaying(device):
if not device:
return False
try:
return isSpotifyPlaying(device) or \
device.media_controller.status.player_is_playing
except pychromecast.error.ControllerNotRegistered as e:
logger.error('Failed to get `isPlaying`: {}'.format(e))
onError(e)
return False
def isSpotifyPlaying(device):
if not device:
return False
if not _spotifyClient:
return False
try:
playbackStatus = _spotifyClient.current_playback()
except spotipy.client.SpotifyException:
logger.exception(
'Error: Failed to get current Spotify playback status'
' - got Spotify error'
)
return False
if not playbackStatus:
return False
if playbackStatus.get('is_playing') and \
playbackStatus.get('device', {}).get('name') != device.name:
logger.warning(
'isSpotifyPlaying: Spotify playback status indicates '
'a device ({}) currently playing but with different '
'device name from the one specified ({}) - considering '
'playback status as "not playing"'.format(
playbackStatus.get('device', {}).get('name'),
device.name
)
)
return False
return playbackStatus.get('is_playing', False)
def isPaused(device):
if not device:
return False
try:
return device.media_controller.status.player_is_paused
except pychromecast.error.ControllerNotRegistered as e:
logger.error('Failed to get `isPaused`: {}'.format(e))
onError(e)
return False
def isSpotifyUri(uri):
return uri.startswith('spotify:')
def isSpotifyPlaylistUri(uri):
return isSpotifyUri(uri) and uri.startswith('spotify:playlist:')
def isSpotifyTrackUri(uri):
return isSpotifyUri(uri) and uri.startswith('spotify:track:')
def _getSpotifyAvailableDevices(calledFromSelf=False):
if not _spotifyClient:
raise Exception('Spotify client is not set up')
try:
devices = _spotifyClient.devices().get('devices', [])
except spotipy.client.SpotifyException:
if calledFromSelf:
logger.exception(
'Error: Failed to get Spotify devices (second attempt)'
' - got Spotify error'
)
else:
logger.exception(
'Error: Failed to get Spotify devices'
' - got Spotify error'
)
devices = []
if not devices:
if not calledFromSelf:
logger.warning(
'No available Spotify devices found '
'- trying once more'
)
return _getSpotifyAvailableDevices(calledFromSelf=True)
else:
logger.warning(
'No available Spotify devices found after second attempt'
)
return devices
def _getSpotifyDeviceId(filters):
'''
:param filters: dict
'''
availableSpotifyDevices = _getSpotifyAvailableDevices()
logger.debug('Available Spotify devices: {}'.format(
availableSpotifyDevices))
filteredSpotifyDevices = []
for device in availableSpotifyDevices:
passedFilters = True
for key in filters.keys():
if not (key in device.keys()):
passedFilters = False
break
if device[key] != filters[key]:
passedFilters = False
break
if passedFilters:
filteredSpotifyDevices.append(device)
try:
deviceId = filteredSpotifyDevices[0]['id']
except IndexError:
deviceId = None
return deviceId, availableSpotifyDevices
def _setupSpotifyClient():
global _spotifyClient
logger.info('Setting up Spotify client...')
try:
oAuthClientId = os.environ['SPOTIFY_OAUTH_CLIENT_ID']
oAuthClientSecret = os.environ['SPOTIFY_OAUTH_CLIENT_SECRET']
except KeyError:
raise SpotifyOAuthCredentialsError(
'Missing Spotify OAuth app credentials in env vars '
'`SPOTIFY_OAUTH_CLIENT_ID` and/or `SPOTIFY_OAUTH_CLIENT_ID`')
_spotifyClient = spotipy.Spotify(
auth_manager=spotipy.oauth2.SpotifyOAuth(
client_id=oAuthClientId,
client_secret=oAuthClientSecret,
scope=SPOTIFY_OAUTH_SCOPE,
redirect_uri='http://localhost:{}/redirect'.format(
SPOTIFY_OAUTH_REDIRECT_SERVER_PORT),
cache_path=SPOTIFY_OAUTH_TOKENS_CACHE_PATH # ,
# show_dialog=True
)
)
try:
_spotifyClient.auth_manager.get_access_token()
logger.info('Spotify client successfully set up')
except Exception:
raise SpotifyOAuthCredentialsError(
'Failed to get initial Spotify access token')
if logger.level == logging.DEBUG:
spotipy.trace = True
spotipy.trace_out = True
return _spotifyClient
def _getSpotifyChromecastController():
try:
spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME']
spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD']
except KeyError:
raise SpotifyPlaybackError(
'Missing Spotify user credentials in env vars '
'`SPOTIFY_USER_USERNAME` and/or `SPOTIFY_USER_PASSWORD`')
(spotifyControllerAccessToken,
spotifyControllerExpiresAt) = spotify_token.start_session(
spotifyUserUsername, spotifyUserPassword)
spotifyControllerExpiresIn = spotifyControllerExpiresAt - int(time())
return SpotifyController(
spotifyControllerAccessToken,
spotifyControllerExpiresIn
)
def _playSpotifyUri(device=None, uri=None):
logger.debug('Playing Spotify URI...')
# launch the Spotify app on the device we want to cast to
try:
controller = _getSpotifyChromecastController()
device.register_handler(controller)
controller.launch_app()
except pychromecast.error.LaunchError as e:
raise SpotifyPlaybackError(
'Failed to launch Spotify controller: {}'.format(e)
)
if not controller.is_launched and not controller.credential_error:
raise SpotifyPlaybackError(
'Failed to launch Spotify controller due to timeout'
)
if not controller.is_launched and controller.credential_error:
raise SpotifyPlaybackError(
'Failed to launch Spotify controller due to credential error'
)
spotifyDeviceId, availableSpotifyDevices = _getSpotifyDeviceId(
filters={'id': controller.device})
if not spotifyDeviceId:
logger.error(
'Device with ID "{}" is unknown to Spotify. '
'Available devices: {}'.format(
controller.device,
availableSpotifyDevices
)
)
raise SpotifyPlaybackError(
'Device with ID "{}" is unknown to Spotify'.format(
controller.device
)
)
# start playback
try:
if isSpotifyPlaylistUri(uri):
# offset = {'position': 0}
# if isSpotifyPlaylistUri(uri) and randomizedPlaylistStart:
# playlistId = uri.split('spotify:playlist:', False)[0]
# playlistItemCount = len(_spotifyClient.user_playlist_tracks(
# playlist_id=playlistId)['items'])
# offset = {'position': randint(0, playlistItemCount-1)}
# # need to enable repeat to ensure items after
# # the offset position will get played
# _spotifyClient.repeat('context', device_id=spotifyDeviceId)
_spotifyClient.start_playback(
device_id=spotifyDeviceId,
context_uri=uri # ,
# offset=offset
)
elif isSpotifyTrackUri(uri):
_spotifyClient.start_playback(
device_id=spotifyDeviceId,
uris=[uri]
)
else:
_spotifyClient.start_playback(
device_id=spotifyDeviceId,
context_uri=uri
)
except spotipy.client.SpotifyException:
logger.exception(
'Error: Failed to start Spotify playback'
' - got Spotify error'
)
raise SpotifyPlaybackError('Could not start playback')
def _pauseSpotify():
if not _spotifyClient:
raise Exception('Spotify client is not set up')
spotifyDeviceId, availableSpotifyDevices = _getSpotifyDeviceId(
filters={'is_active': True})
if not spotifyDeviceId:
logger.debug(
'Can\'t pause Spotify playback - '
'Spotify returned no active devices'
)
return
try:
_spotifyClient.pause_playback(device_id=spotifyDeviceId)
except spotipy.client.SpotifyException:
logger.exception(
'Error: Failed to pause Spotify playback'
' - got Spotify error'
)
def play(data, device=None):
'''
:param data: dict
:param device
'''
if data is None:
data = {}
if not data['media'].get('args'):
data['media']['args'] = {}
########################
# set up media data structure
mediaArgs = dict(data['media']['args'])
if not isSpotifyUri(data['media']['uri']):
try:
mimeType = MimeTypes().guess_type(data['media']['uri'])[0]
mediaArgs['content_type'] = mimeType
except IndexError:
raise Exception(
'Failed to look up mime type for media uri "{}"'.format(
data['media']['uri']
)
)
if not mediaArgs.get('content_type'):
raise Exception(
'Failed to look up mime type for media uri "{}"'.format(
data['media']['uri']
)
)
########################
if data.get('volume') is not None:
setVolume(device, data['volume'])
logger.info('Starting playback on "{}"'.format(device.name))
logger.debug('Playing:\n - uri: {}\n - args: {}'.format(
data['media']['uri'], mediaArgs))
mc = device.media_controller
if isSpotifyUri(data['media']['uri']):
_playSpotifyUri(
device=device,
uri=data['media']['uri']
)
else:
mc.play_media(data['media']['uri'], **mediaArgs)
mc.block_until_active()
return device
def addDeviceStatusListener(device, callback):
device.media_controller.register_status_listener(
DeviceStatusListener(device, callback)
)
def addDevicePlayerStatusListener(device, callback):
device.media_controller.register_status_listener(
DeviceMediaStatusListener(device, callback)
)