aboutsummaryrefslogtreecommitdiff
path: root/pandora/client.py
blob: ff27678ef34f6f031bf05453ad2e06059aeb1f59 (plain)
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
"""
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
from .ratelimit import WarningTokenBucket


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,
        rate_limiter=WarningTokenBucket,
    ):
        """Initialize an API Client

        transport
            instance of a Pandora transport
        partner_user
            partner username
        partner_password
            partner password
        device
            device type identifier
        default_audio_quality
            audio quality level, one of the *_AUDIO_QUALITY constants in the
            BaseAPIClient class
        rate_limiter
            class (not instance) implementing the pandora.ratelimit.TokenBucket
            interface. Used by various client components to handle rate
            limits with the Pandora API. The default rate limited warns when
            the rate limit has been exceeded but does not enforce the limit.
        """
        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

        # Global rate limiter for all methods, allows a call rate of 2 calls
        # per second. This limit is based on nothing but seems sane to prevent
        # runaway code from hitting Pandora too hard.
        self._api_limiter = rate_limiter(120, 1, 1)

        # Rate limiter for the get_playlist API which has a much lower
        # server-side limit than other APIs. This was determined
        # experimentally. This is applied before and in addition to the global
        # API rate limit.
        self._playlist_limiter = rate_limiter(5, 1, 1)

    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):
        self._api_limiter.consume(1)

        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

        self._playlist_limiter.consume(1)

        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
    ):
        from .models.station import Station

        kwargs = {}

        if search_token:
            kwargs = {"musicToken": search_token}
        elif artist_token:
            kwargs = {"trackToken": artist_token, "musicType": "artist"}
        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
        )