-
Notifications
You must be signed in to change notification settings - Fork 19
/
client.py
Latest commit
324 lines (254 loc) · 9.65 KB
/
client.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
"""
Pandora API Client
This module contains the top level API client that is responsible for calling
the API and returing the results in model format. There is a base API client
that is useful for lower level programming such as calling methods that aren't
directly supported by the higher level API client.
The high level API client is what most clients should use and provides API
calls that map directly to the Pandora API and return model objects with
mappings from the raw JSON structures to Python objects.
For simplicity use a client builder from pandora.clientbuilder to create an
instance of a client.
"""
from. import errors
class BaseAPIClient:
"""Base Pandora API Client
The base API client has lower level methods that are composed together to
provide higher level functionality.
"""
LOW_AUDIO_QUALITY = "lowQuality"
MED_AUDIO_QUALITY = "mediumQuality"
HIGH_AUDIO_QUALITY = "highQuality"
ALL_QUALITIES = [LOW_AUDIO_QUALITY, MED_AUDIO_QUALITY, HIGH_AUDIO_QUALITY]
def __init__(
self,
transport,
partner_user,
partner_password,
device,
default_audio_quality=MED_AUDIO_QUALITY,
):
self.transport = transport
self.partner_user = partner_user
self.partner_password = partner_password
self.device = device
self.default_audio_quality = default_audio_quality
self.username = None
self.password = None
def _partner_login(self):
partner = self.transport(
"auth.partnerLogin",
username=self.partner_user,
password=self.partner_password,
deviceModel=self.device,
version=self.transport.API_VERSION,
)
self.transport.set_partner(partner)
return partner
def login(self, username, password):
self.username = username
self.password = password
return self._authenticate()
def _authenticate(self):
self._partner_login()
try:
user = self.transport(
"auth.userLogin",
loginType= "user",
username=self.username,
password=self.password,
includePandoraOneInfo=True,
includeSubscriptionExpiration=True,
returnCapped=True,
includeAdAttributes=True,
includeAdvertiserAttributes=True,
xplatformAdCapable=True,
)
except errors.InvalidPartnerLogin:
raise errors.InvalidUserLogin()
self.transport.set_user(user)
return user
@classmethod
def get_qualities(cls, start_at, return_all_if_invalid=True):
try:
idx = cls.ALL_QUALITIES.index(start_at)
return cls.ALL_QUALITIES[: idx + 1]
except ValueError:
if return_all_if_invalid:
return cls.ALL_QUALITIES[:]
else:
return []
def __call__(self, method, **kwargs):
try:
return self.transport(method, **kwargs)
except errors.InvalidAuthToken:
self._authenticate()
return self.transport(method, **kwargs)
class APIClient(BaseAPIClient):
"""High Level Pandora API Client
The high level API client implements the entire functional API for Pandora.
This is what clients should actually use.
"""
def get_station_list(self):
from.models.station import StationList
return StationList.from_json(
self, self( "user.getStationList", includeStationArtUrl=True)
)
def get_station_list_checksum(self):
return self( "user.getStationListChecksum" )[ "checksum" ]
def get_playlist(self, station_token, additional_urls=None):
from.models.playlist import Playlist
if additional_urls is None:
additional_urls = []
if isinstance(additional_urls, str):
raise TypeError( "Additional urls should be a list" )
urls = [getattr(url, "value", url) for url in additional_urls]
resp = self(
"station.getPlaylist",
stationToken=station_token,
includeTrackLength=True,
xplatformAdCapable=True,
audioAdPodCapable=True,
additionalAudioUrl= ",".join(urls),
)
for item in resp[ "items" ]:
item[ "_paramAdditionalUrls" ] = additional_urls
playlist = Playlist.from_json(self, resp)
for i, track in enumerate(playlist):
if track.is_ad:
track = self.get_ad_item(station_token, track.ad_token)
playlist[i] = track
return playlist
def get_bookmarks(self):
from.models.bookmark import BookmarkList
return BookmarkList.from_json(self, self( "user.getBookmarks" ))
def get_station(self, station_token):
from.models.station import Station
return Station.from_json(
self,
self(
"station.getStation",
stationToken=station_token,
includeExtendedAttributes=True,
),
)
def add_artist_bookmark(self, track_token):
return self( "bookmark.addArtistBookmark", trackToken=track_token)
def add_song_bookmark(self, track_token):
return self( "bookmark.addSongBookmark", trackToken=track_token)
def delete_song_bookmark(self, bookmark_token):
return self(
"bookmark.deleteSongBookmark", bookmarkToken=bookmark_token
)
def delete_artist_bookmark(self, bookmark_token):
return self(
"bookmark.deleteArtistBookmark", bookmarkToken=bookmark_token
)
def search(
self,
search_text,
include_near_matches=False,
include_genre_stations=False,
):
from.models.search import SearchResult
return SearchResult.from_json(
self,
self(
"music.search",
searchText=search_text,
includeNearMatches=include_near_matches,
includeGenreStations=include_genre_stations,
),
)
def add_feedback(self, track_token, positive):
return self(
"station.addFeedback", trackToken=track_token, isPositive=positive
)
def add_music(self, music_token, station_token):
return self(
"station.addMusic",
musicToken=music_token,
stationToken=station_token,
)
def create_station(
self,
search_token=None,
artist_token=None,
track_token=None,
song_token=None,
):
from.models.station import Station
kwargs = {}
if search_token:
kwargs = { "musicToken": search_token}
elif artist_token:
kwargs = { "musicToken": artist_token, "musicType": "artist" }
elif song_token:
kwargs = { "musicToken": song_token, "musicType": "song" }
elif track_token:
kwargs = { "trackToken": track_token, "musicType": "song" }
else:
raise KeyError( "Must pass a type of token" )
return Station.from_json(self, self( "station.createStation", **kwargs))
def delete_feedback(self, feedback_id):
return self( "station.deleteFeedback", feedbackId=feedback_id)
def delete_music(self, seed_id):
return self( "station.deleteMusic", seedId=seed_id)
def delete_station(self, station_token):
return self( "station.deleteStation", stationToken=station_token)
def get_genre_stations(self):
from.models.station import GenreStationList
genre_stations = GenreStationList.from_json(
self, self( "station.getGenreStations" )
)
genre_stations.checksum = self.get_genre_stations_checksum()
return genre_stations
def get_genre_stations_checksum(self):
return self( "station.getGenreStationsChecksum" )[ "checksum" ]
def rename_station(self, station_token, name):
return self(
"station.renameStation",
stationToken=station_token,
stationName=name,
)
def explain_track(self, track_token):
return self( "track.explainTrack", trackToken=track_token)
def set_quick_mix(self, *args):
return self( "user.setQuickMix", quickMixStationIds=args)
def sleep_song(self, track_token):
return self( "user.sleepSong", trackToken=track_token)
def share_station(self, station_id, station_token, *emails):
return self(
"station.shareStation",
stationId=station_id,
stationToken=station_token,
emails=emails,
)
def transform_shared_station(self, station_token):
return self(
"station.transformSharedStation", stationToken=station_token
)
def share_music(self, music_token, *emails):
return self(
"music.shareMusic", musicToken=music_token, email=emails[0]
)
def get_ad_item(self, station_id, ad_token):
from.models.ad import AdItem
if not station_id:
msg = "The 'station_id' param must be defined, got: '{}'"
raise errors.ParameterMissing(msg.format(station_id))
ad_item = AdItem.from_json(self, self.get_ad_metadata(ad_token))
ad_item.station_id = station_id
ad_item.ad_token = ad_token
return ad_item
def get_ad_metadata(self, ad_token):
return self(
"ad.getAdMetadata",
adToken=ad_token,
returnAdTrackingTokens=True,
supportAudioAds=True,
)
def register_ad(self, station_id, tokens):
return self(
"ad.registerAd", stationId=station_id, adTrackingTokens=tokens
)