forked from davidkrantz/Colorfy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
current_spotify_playback.py
172 lines (133 loc) · 4.87 KB
/
current_spotify_playback.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
import spotipy
import spotipy.util as util
import spotipy.oauth2 as oauth2
import json
import numpy as np
from io import BytesIO
import urllib.request
from PIL import Image
class CurrentSpotifyPlayback():
"""Module for getting information about current Spotify playback.
Attributes:
auth (SpotifyOAuth): The SpotifyOAuth object to use.
refresh_token (str): Refresh token given by Spotify.
data (JSON): Current playback.
"""
def __init__(self, client_id, client_secret, redirect_uri, refresh_token):
"""Initializes the class with the current playback.
Args:
client_id (str): Client id for your Spotify application
redirect_uri (str): Redirect URI used by your Spotify
application.
refresh_token (str): Refresh token given by Spotify to
update your credentials.
"""
self.auth = oauth2.SpotifyOAuth(client_id,
client_secret,
redirect_uri)
self.refresh_token = refresh_token
self.data = self.current_playback()
def update_current_playback(self):
"""Updates the current playback."""
try:
self.data = self.current_playback()
except (CouldNotRefreshTokenException,
CouldNotFetchPlaybackException):
self.data = None
def current_playback(self):
"""Fetches the current playback.
Returns:
JSON: The current playback.
Raises:
CouldNotFetchPlaybackException: If it failed to load
current playback.
"""
token = self._refresh_token()
if token:
try:
sp = spotipy.Spotify(auth=token)
data = json.dumps(sp.current_playback())
data = json.loads(data)
except Exception:
raise CouldNotFetchPlaybackException(
'Something went wrong when' \
'fetching current playback.')
return data
def _refresh_token(self):
"""Refreshes the access token.
Returns:
str: The updated token.
Raises:
CouldNotRefreshTokenException: If it failed to refresh
the credentials token.
"""
try:
return self.auth.refresh_access_token(self.refresh_token)\
['access_token']
except Exception:
raise CouldNotRefreshTokenException('Could not refresh token.')
def connected_to_chromecast(self, name):
"""Checks if connected to a Chromecast.
Args:
name (str): Name of Chromecast
Returns:
bool: True if connected to a Chromecast, False otherwise.
"""
return self.data and self.data['device']['name'] == name
def new_song(self, old_song_id):
"""Checks if a new song is playing.
Args:
old_song_id (str): The song id given by the Spotify API.
Returns:
bool: True if new song, False otherwise.
"""
if self.data:
is_active = self.data['device']['is_active']
current_song_id = self.get_current_song_id()
return is_active and current_song_id != old_song_id
else:
return False
def get_artwork(self):
"""Returns the album artwork of the current playing song.
Returns:
ndarray: Album artwork.
Raises:
NoArtworkException: If album of current playback does
not have an artwork.
NotPlayingAnywhereExcpetion: If Spotify is not active on
any device.
"""
if self.data:
try:
url = self.data['item']['album']['images'][1]['url']
except IndexError:
raise NoArtworkException()
image_bytes = BytesIO(urllib.request.urlopen(url).read())
image = np.array(Image.open(image_bytes))
return image
else:
raise NotPlayingAnywhereException()
def get_current_song_id(self):
"""Returns the current song id.
Returns:
str: Song id.
Raises:
NotPlayingAnywhereExcpetion: If Spotify is not active on
any device.
"""
if self.data:
return self.data['item']['id']
else:
raise NotPlayingAnywhereException()
class NotPlayingAnywhereException(Exception):
"""Raises when Spotify is not active on any device."""
pass
class CouldNotRefreshTokenException(Exception):
"""Raises when token could not be refreshed"""
pass
class CouldNotFetchPlaybackException(Exception):
"""Raises when current playback could not be fetched."""
pass
class NoArtworkException(Exception):
"""Raises when the current playback has no artwork."""
pass