__init__.py 16.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Thomas Amland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

18
from __future__ import unicode_literals, print_function
19

20
21
import sys
import re
22
23
import datetime
import json
24
import random
25
26
import logging
import requests
27
28
29
30
try:
    from requests.packages import urllib3
except:
    import urllib3
31
from collections import namedtuple
32
from .models import SubscriptionType, Quality
33
from .models import Artist, Album, Track, Playlist, SearchResult, Category
34
35
36
37
38
try:
    from urlparse import urljoin
except ImportError:
    from urllib.parse import urljoin

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class MLog(object):
    def __init__(self):
        self.f = sys.stderr
        self.level = 1
    def isEnabledFor(self, l):
        return True
    def debug(self, msg):
        if self.level >= 3:
            print("%s" % msg, file=self.f)
    def info(self, msg):
        if self.level >= 2:
            print("%s" % msg, file=self.f)
    def error(self, msg):
        if self.level >= 1:
            print("%s" % msg, file=self.f)

#log = logging.getLogger(__name__)
log = MLog()

# See https://github.com/arnesongit/python-tidal/ for token descs
59
class Config(object):
60
    def __init__(self, quality=Quality.high, apitoken = 'pl4Vc0hemlAXD0mN'):
61
        self.quality = quality
62
        self.api_location = 'https://api.tidalhifi.com/v1/'
63
        self.api_token = apitoken
64
        self.preview_token = "8C7kRFdkaRp0dLBp" # Token for Preview Mode
65
66
67
68

class Session(object):

    def __init__(self, config=Config()):
69
70
71
72
73
74
        """:type _config: :class:`Config`"""
        self._config = config
        self.session_id = None
        self.user = None
        self.country_code = 'US'   # Enable Trial Mode
        self.client_unique_key = None
75
76
77
78
        try:
            urllib3.disable_warnings() # Disable OpenSSL Warnings in URLLIB3
        except:
            pass
79
80

    def logout(self):
81
82
83
        self.session_id = None
        self.user = None

84
85
    def load_session(self, session_id, country_code, user_id=None,
                     subscription_type=None, unique_key=None):
86
        self.session_id = session_id
87
        self.client_unique_key = unique_key
88
        self.country_code = country_code
89
90
91
92
93
94
95
96
        if not self.country_code:
            # Set Local Country Code to enable Trial Mode 
            self.country_code = self.local_country_code()
        if user_id:
            self.user = self.init_user(user_id=user_id,
                                       subscription_type=subscription_type)
        else:
            self.user = None
97

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    def generate_client_unique_key(self):
        return format(random.getrandbits(64), '02x')

    def login(self, username, password, subscription_type=None):
        self.logout()
        if not username or not password:
            return False
        if not subscription_type:
            # Set Subscription Type corresponding to the given playback quality
            subscription_type = SubscriptionType.hifi if \
                                self._config.quality == Quality.lossless else \
                                SubscriptionType.premium
        if not self.client_unique_key:
            # Generate a random client key if no key is given
            self.client_unique_key = self.generate_client_unique_key()
113
        url = urljoin(self._config.api_location, 'login/username')
114
        headers = { "X-Tidal-Token": self._config.api_token }
115
116
117
        payload = {
            'username': username,
            'password': password,
118
            'clientUniqueKey': self.client_unique_key
119
        }
120
121
122
123
124
125
126
127
        log.debug('Using Token "%s" with clientUniqueKey "%s"' %
                  (self._config.api_token, self.client_unique_key))
        r = requests.post(url, data=payload, headers=headers)
        if not r.ok:
            try:
                msg = r.json().get('userMessage')
            except:
                msg = r.reason
128
            log.error("Tidal login: %s" % msg)
129
130
131
132
133
134
135
136
        else:
            try:
                body = r.json()
                self.session_id = body['sessionId']
                self.country_code = body['countryCode']
                self.user = self.init_user(user_id=body['userId'],
                                           subscription_type=subscription_type)
            except Exception as err:
137
                log.error('Tidal login failed. err %s %s' % (err, body))
138
139
140
141
                self.logout()

        return self.is_logged_in

142
143
144
    def get_token_and_country(self):
        return self.session_id, self.country_code
    
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    def init_user(self, user_id, subscription_type):
        return User(self, user_id=user_id, subscription_type=subscription_type)

    def local_country_code(self):
        url = urljoin(self._config.api_location, 'country/context')
        headers = { "X-Tidal-Token": self._config.api_token}
        r = requests.request('GET', url, params={'countryCode': 'WW'},
                             headers=headers)
        if not r.ok:
            return 'US'
        return r.json().get('countryCode')

    @property
    def is_logged_in(self):
        return True if self.session_id and self.country_code and self.user \
               else False
    
162
163
    def check_login(self):
        """ Returns true if current session is valid, false otherwise. """
164
        if not self.is_logged_in:
165
            return False
166
167
        self.user.subscription = self.get_user_subscription(self.user.id)
        return True if self.user.subscription != None else False
168

169
170
    def request(self, method, path, params=None, data=None, headers=None):
        request_headers = {}
171
172
173
174
175
        request_params = {
            'sessionId': self.session_id,
            'countryCode': self.country_code,
            'limit': '999',
        }
176
177
        if headers:
            request_headers.update(headers)
178
179
180
        if params:
            request_params.update(params)
        url = urljoin(self._config.api_location, path)
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
        if self.is_logged_in:
            # Request with API Session if SessionId is not given in headers parameter
            if not 'X-Tidal-SessionId' in request_headers:
                request_headers.update({'X-Tidal-SessionId': self.session_id})
        else:
            # Request with Preview-Token. Remove SessionId if given via headers parameter
            request_headers.pop('X-Tidal-SessionId', None)
            request_params.update({'token': self._config.preview_token})
        r = requests.request(method, url, params=request_params, data=data, headers=request_headers)
        log.debug("%s %s" % (method, r.request.url))
        if not r.ok:
            log.error(r.url)
            try:
                log.error(r.json().get('userMessage'))
            except:
                log.error(r.reason)
197
        r.raise_for_status()
198
199
        if r.content and log.isEnabledFor(logging.INFO):
            log.info("response: %s" % json.dumps(r.json(), indent=4))
200
201
202
203
204
        return r

    def get_user(self, user_id):
        return self._map_request('users/%s' % user_id, ret='user')

205
206
207
    def get_user_subscription(self, user_id):
        return self._map_request('users/%s/subscription' % user_id, ret='subscription')

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
    def get_user_playlists(self, user_id):
        return self._map_request('users/%s/playlists' % user_id, ret='playlists')

    def get_playlist(self, playlist_id):
        return self._map_request('playlists/%s' % playlist_id, ret='playlist')

    def get_playlist_tracks(self, playlist_id):
        return self._map_request('playlists/%s/tracks' % playlist_id, ret='tracks')

    def get_album(self, album_id):
        return self._map_request('albums/%s' % album_id, ret='album')

    def get_album_tracks(self, album_id):
        return self._map_request('albums/%s/tracks' % album_id, ret='tracks')

    def get_artist(self, artist_id):
        return self._map_request('artists/%s' % artist_id, ret='artist')

    def get_artist_albums(self, artist_id):
        return self._map_request('artists/%s/albums' % artist_id, ret='albums')

    def get_artist_albums_ep_singles(self, artist_id):
        params = {'filter': 'EPSANDSINGLES'}
        return self._map_request('artists/%s/albums' % artist_id, params, ret='albums')

    def get_artist_albums_other(self, artist_id):
        params = {'filter': 'COMPILATIONS'}
        return self._map_request('artists/%s/albums' % artist_id, params, ret='albums')

    def get_artist_top_tracks(self, artist_id):
        return self._map_request('artists/%s/toptracks' % artist_id, ret='tracks')

    def get_artist_bio(self, artist_id):
        return self.request('GET', 'artists/%s/bio' % artist_id).json()['text']

    def get_artist_similar(self, artist_id):
        return self._map_request('artists/%s/similar' % artist_id, ret='artists')

    def get_artist_radio(self, artist_id):
247
        return self._map_request('artists/%s/radio' % artist_id, params={'limit': 200}, ret='tracks')
248
249
250
251
252
253
254
255
256

    def get_featured(self):
        items = self.request('GET', 'promotions').json()['items']
        return [_parse_featured_playlist(item) for item in items if item['type'] == 'PLAYLIST']

    def get_featured_items(self, content_type, group):
        return self._map_request('/'.join(['featured', group, content_type]), ret=content_type)

    def get_moods(self):
257
        return list(map(_parse_moods, self.request('GET', 'moods').json()))
258
259
260
261
262

    def get_mood_playlists(self, mood_id):
        return self._map_request('/'.join(['moods', mood_id, 'playlists']), ret='playlists')

    def get_genres(self):
263
        return list(map(_parse_genres, self.request('GET', 'genres').json()))
264
265
266
267
268

    def get_genre_items(self, genre_id, content_type):
        return self._map_request('/'.join(['genres', genre_id, content_type]), ret=content_type)

    def get_track_radio(self, track_id):
269
        return self._map_request('tracks/%s/radio' % track_id, params={'limit': 200}, ret='tracks')
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

    def get_track(self, track_id):
        return self._map_request('tracks/%s' % track_id, ret='track')

    def _map_request(self, url, params=None, ret=None):
        json_obj = self.request('GET', url, params).json()
        parse = None
        if ret.startswith('artist'):
            parse = _parse_artist
        elif ret.startswith('album'):
            parse = _parse_album
        elif ret.startswith('track'):
            parse = _parse_track
        elif ret.startswith('user'):
            raise NotImplementedError()
        elif ret.startswith('playlist'):
            parse = _parse_playlist

        items = json_obj.get('items')
        if items is None:
            return parse(json_obj)
        elif len(items) > 0 and 'item' in items[0]:
            return list(map(parse, [item['item'] for item in items]))
        else:
            return list(map(parse, items))

    def get_media_url(self, track_id):
        params = {'soundQuality': self._config.quality}
        r = self.request('GET', 'tracks/%s/streamUrl' % track_id, params)
        return r.json()['url']

    def search(self, field, value):
        params = {
            'query': value,
304
            'limit': 200,
305
306
307
308
309
310
311
312
313
314
315
        }
        if field not in ['artist', 'album', 'playlist', 'track']:
            raise ValueError('Unknown field \'%s\'' % field)

        ret_type = field + 's'
        url = 'search/' + field + 's'
        result = self._map_request(url, params, ret=ret_type)
        return SearchResult(**{ret_type: result})


def _parse_artist(json_obj):
316
317
    artist = Artist(id=json_obj['id'], name=json_obj['name'])
    return artist
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338


def _parse_artists(json_obj):
    return list(map(_parse_artist, json_obj))


def _parse_album(json_obj, artist=None, artists=None):
    if artist is None:
        artist = _parse_artist(json_obj['artist'])
    if artists is None:
        artists = _parse_artists(json_obj['artists'])
    kwargs = {
        'id': json_obj['id'],
        'name': json_obj['title'],
        'num_tracks': json_obj.get('numberOfTracks'),
        'duration': json_obj.get('duration'),
        'artist': artist,
        'artists': artists,
    }
    if 'releaseDate' in json_obj:
        try:
339
340
            # Keep this as a string else we fail to json-reserialize it later
            kwargs['release_date'] = json_obj['releaseDate']
341
            #kwargs['release_date'] = datetime.datetime(*map(int, json_obj['releaseDate'].split('-')))
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
        except ValueError:
            pass
    return Album(**kwargs)


def _parse_featured_playlist(json_obj):
    kwargs = {
        'id': json_obj['artifactId'],
        'name': json_obj['header'],
        'description': json_obj['text'],
    }
    return Playlist(**kwargs)


def _parse_playlist(json_obj):
    kwargs = {
        'id': json_obj['uuid'],
        'name': json_obj['title'],
        'description': json_obj['description'],
        'num_tracks': int(json_obj['numberOfTracks']),
        'duration': int(json_obj['duration']),
        'is_public': json_obj['publicPlaylist'],
        #TODO 'creator': _parse_user(json_obj['creator']),
    }
    return Playlist(**kwargs)


def _parse_track(json_obj):
    artist = _parse_artist(json_obj['artist'])
    artists = _parse_artists(json_obj['artists'])
    album = _parse_album(json_obj['album'], artist, artists)
    kwargs = {
        'id': json_obj['id'],
        'name': json_obj['title'],
        'duration': json_obj['duration'],
        'track_num': json_obj['trackNumber'],
        'disc_num': json_obj['volumeNumber'],
        'popularity': json_obj['popularity'],
        'artist': artist,
        'artists': artists,
        'album': album,
        'available': bool(json_obj['streamReady']),
    }
    return Track(**kwargs)


def _parse_genres(json_obj):
    image = "http://resources.wimpmusic.com/images/%s/460x306.jpg" \
            % json_obj['image'].replace('-', '/')
    return Category(id=json_obj['path'], name=json_obj['name'], image=image)


def _parse_moods(json_obj):
    image = "http://resources.wimpmusic.com/images/%s/342x342.jpg" \
            % json_obj['image'].replace('-', '/')
    return Category(id=json_obj['path'], name=json_obj['name'], image=image)


class Favorites(object):

    def __init__(self, session, user_id):
        self._session = session
        self._base_url = 'users/%s/favorites' % user_id

    def add_artist(self, artist_id):
        return self._session.request('POST', self._base_url + '/artists', data={'artistId': artist_id}).ok

    def add_album(self, album_id):
        return self._session.request('POST', self._base_url + '/albums', data={'albumId': album_id}).ok

    def add_track(self, track_id):
        return self._session.request('POST', self._base_url + '/tracks', data={'trackId': track_id}).ok

    def remove_artist(self, artist_id):
        return self._session.request('DELETE', self._base_url + '/artists/%s' % artist_id).ok

    def remove_album(self, album_id):
        return self._session.request('DELETE', self._base_url + '/albums/%s' % album_id).ok

    def remove_track(self, track_id):
        return self._session.request('DELETE', self._base_url + '/tracks/%s' % track_id).ok

    def artists(self):
        return self._session._map_request(self._base_url + '/artists', ret='artists')

    def albums(self):
        return self._session._map_request(self._base_url + '/albums', ret='albums')

    def playlists(self):
        return self._session._map_request(self._base_url + '/playlists', ret='playlists')

    def tracks(self):
        r = self._session.request('GET', self._base_url + '/tracks')
        return [_parse_track(item['item']) for item in r.json()['items']]


class User(object):

    favorites = None

442
    def __init__(self, session, user_id, subscription_type=SubscriptionType.hifi):
443
        self._session = session
444
        self.id = user_id
445
        self.favorites = Favorites(session, self.id)
446
        
447
448
    def playlists(self):
        return self._session.get_user_playlists(self.id)