8bd7d91f910d834a8351bef233a9883208db8803
[jamaendo] / jamaendo / api.py
1 # An improved, structured jamendo API for the N900 with cacheing
2 # Image / cover downloads.. and more?
3 import urllib, threading, os, gzip, time, simplejson, re
4 #import util
5 #if util.platform == 'maemo':
6 #    _CACHEDIR = os.path.expanduser('''~/MyDocs/.jamaendo''')
7 #else:
8 #    _CACHEDIR = os.path.expanduser('''~/.cache/jamaendo''')
9
10 _CACHEDIR = None#'/tmp/jamaendo'
11 _COVERDIR = None#os.path.join(_CACHEDIR, 'covers')
12 _GET2 = '''http://api.jamendo.com/get2/'''
13 _MP3URL = _GET2+'stream/track/redirect/?id=%d&streamencoding=mp31'
14 _OGGURL = _GET2+'stream/track/redirect/?id=%d&streamencoding=ogg2'
15
16
17 def set_cache_dir(cachedir):
18     global _CACHEDIR
19     global _COVERDIR
20     _CACHEDIR = cachedir
21     _COVERDIR = os.path.join(_CACHEDIR, 'covers')
22
23     try:
24         os.makedirs(_CACHEDIR)
25     except OSError:
26         pass
27
28     try:
29         os.makedirs(_COVERDIR)
30     except OSError:
31         pass
32
33 # These classes can be partially constructed,
34 # and if asked for a property they don't know,
35 # makes a query internally to get the full story
36
37 _ARTIST_FIELDS = ['id', 'name', 'image']
38 _ALBUM_FIELDS = ['id', 'name', 'image', 'artist_name', 'artist_id']
39 _TRACK_FIELDS = ['id', 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration']
40 _RADIO_FIELDS = ['id', 'name', 'idstr', 'image']
41
42 class LazyQuery(object):
43     def set_from_json(self, json):
44         for key, value in json.iteritems():
45             if key == 'id':
46                 assert(self.ID == int(value))
47             else:
48                 if key.endswith('_id'):
49                     value = int(value)
50                 setattr(self, key, value)
51
52     def load(self):
53         """Not automatic for now,
54         will have to do artist.load()
55
56         This is filled in further down
57         in the file
58         """
59         raise NotImplemented
60
61     def _needs_load(self):
62         return True
63
64     def _set_from(self, other):
65         raise NotImplemented
66
67     def _needs_load_impl(self, *attrs):
68         for attr in attrs:
69             if getattr(self, attr) is None:
70                 return True
71         return False
72
73     def _set_from_impl(self, other, *attrs):
74         for attr in attrs:
75             self._set_if(other, attr)
76
77     def _set_if(self, other, attrname):
78         if getattr(self, attrname) is None and getattr(other, attrname) is not None:
79             setattr(self, attrname, getattr(other, attrname))
80
81     def __repr__(self):
82         try:
83             return u"%s(%s)"%(self.__class__.__name__,
84                               u", ".join(repr(v) for k,v in self.__dict__.iteritems() if not k.startswith('_')))
85         except UnicodeEncodeError:
86             import traceback
87             traceback.print_exc()
88             return u"%s(?)"%(self.__class__.__name__)
89
90 class Artist(LazyQuery):
91     def __init__(self, ID, json=None):
92         self.ID = int(ID)
93         self.name = None
94         self.image = None
95         self.albums = None # None means not downloaded
96         if json:
97             self.set_from_json(json)
98
99     def _needs_load(self):
100         return self._needs_load_impl('name', 'image', 'albums')
101
102     def _set_from(self, other):
103         return self._set_from_impl(other, 'name', 'image', 'albums')
104
105 class Album(LazyQuery):
106     def __init__(self, ID, json=None):
107         self.ID = int(ID)
108         self.name = None
109         self.image = None
110         self.artist_name = None
111         self.artist_id = None
112         self.tracks = None # None means not downloaded
113         if json:
114             self.set_from_json(json)
115
116     def _needs_load(self):
117         return self._needs_load_impl('name', 'image', 'artist_name', 'artist_id', 'tracks')
118
119     def _set_from(self, other):
120         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'tracks')
121
122 class Track(LazyQuery):
123     def __init__(self, ID, json=None):
124         self.ID = int(ID)
125         self.name = None
126         self.image = None
127         self.artist_name = None
128         self.album_name = None
129         self.album_id = None
130         self.numalbum = None
131         self.duration = None
132         if json:
133             self.set_from_json(json)
134
135     def mp3_url(self):
136        return _MP3URL%(self.ID)
137
138     def ogg_url(self):
139        return _OGGURL%(self.ID)
140
141     def _needs_load(self):
142         return self._needs_load_impl('name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
143
144     def _set_from(self, other):
145         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
146
147 class Radio(LazyQuery):
148     def __init__(self, ID, json=None):
149         self.ID = int(ID)
150         self.name = None
151         self.idstr = None
152         self.image = None
153         if json:
154             self.set_from_json(json)
155
156     def _needs_load(self):
157         return self._needs_load_impl('name', 'idstr', 'image')
158
159     def _set_from(self, other):
160         return self._set_from_impl(other, 'name', 'idstr', 'image')
161
162
163 _artists = {} # id -> Artist()
164 _albums = {} # id -> Album()
165 _tracks = {} # id -> Track()
166 _radios = {} # id -> Radio()
167
168
169 # cache sizes per session (TODO)
170 _CACHED_ARTISTS = 100
171 _CACHED_ALBUMS = 200
172 _CACHED_TRACKS = 500
173 _CACHED_RADIOS = 10
174
175 # TODO: cache queries?
176
177 class Query(object):
178     last_query = time.time()
179     rate_limit = 1.0 # max queries per second
180
181     @classmethod
182     def _ratelimit(cls):
183         now = time.time()
184         if now - cls.last_query < cls.rate_limit:
185             time.sleep(cls.rate_limit - (now - cls.last_query))
186         cls.last_query = now
187
188     def __init__(self):
189         pass
190
191     def _geturl(self, url):
192         print "geturl: %s" % (url)
193         f = urllib.urlopen(url)
194         ret = simplejson.load(f)
195         f.close()
196         return ret
197
198     def __str__(self):
199         return "#%s" % (self.__class__.__name__)
200
201     def execute(self):
202         raise NotImplemented
203
204 class CoverCache(object):
205     """
206     cache and fetch covers
207     TODO: background thread that
208     fetches and returns covers,
209     asynchronously, LIFO
210     """
211     def __init__(self):
212         self._covers = {} # (albumid, size) -> file
213         coverdir = _COVERDIR if _COVERDIR else '/tmp'
214         if os.path.isdir(coverdir):
215             covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
216             for fil in os.listdir(coverdir):
217                 fl = os.path.join(coverdir, fil)
218                 m = covermatch.match(fil)
219                 if m and os.path.isfile(fl):
220                     self._covers[(int(m.group(1)), int(m.group(2)))] = fl
221
222     def fetch_cover(self, albumid, size):
223         Query._ratelimit() # ratelimit cover fetching too?
224         coverdir = _COVERDIR if _COVERDIR else '/tmp'
225         to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
226         if not os.path.isfile(to):
227             url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
228             urllib.urlretrieve(url, to)
229             self._covers[(albumid, size)] = to
230         return to
231
232     def get_cover(self, albumid, size):
233         cover = self._covers.get((albumid, size), None)
234         if not cover:
235             cover = self.fetch_cover(albumid, size)
236         return cover
237
238     def get_async(self, albumid, size, cb):
239         cover = self._covers.get((albumid, size), None)
240         if cover:
241             cb(cover)
242         else:
243             # TODO
244             cover = self.fetch_cover(albumid, size)
245             cb(cover)
246
247 _cover_cache = CoverCache()
248
249 def get_album_cover(albumid, size=200):
250     return _cover_cache.get_cover(albumid, size)
251
252 def get_album_cover_async(cb, albumid, size=200):
253     _cover_cache.get_async(albumid, size, cb)
254
255 class CustomQuery(Query):
256     def __init__(self, url):
257         Query.__init__(self)
258         self.url = url
259
260     def execute(self):
261         return self._geturl(self.url)
262
263     def __str__(self):
264         return self.url
265
266 class GetQuery(Query):
267     queries = {
268         'artist' : {
269             'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
270             'params' : 'artist_id=%d',
271             'constructor' : Artist
272             },
273         'album' : {
274             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
275             'params' : 'album_id=%d',
276             'constructor' : Album
277             },
278         'albums' : {
279             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
280             'params' : 'artist_id=%d',
281             'constructor' : [Album]
282             },
283         'track' : {
284             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
285             'params' : 'id=%d',
286             'constructor' : Track
287             },
288         'tracks' : {
289             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
290             'params' : 'album_id=%d',
291             'constructor' : [Track]
292             },
293         'radio' : {
294             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
295             'params' : 'order=numradio_asc&radio_id=%d',
296             'constructor' : [Track]
297             },
298         'favorite_albums' : {
299             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
300             'params' : 'user_idstr=%s',
301             'constructor' : [Album]
302             },
303     #http://api.jamendo.com/get2/id+name+url+image+artist_name/album/jsonpretty/album_user_starred/?user_idstr=sylvinus&n=all
304     #q = SearchQuery('album', user_idstr=user)
305
306         }
307 #http://api.jamendo.com/get2/id+name+image+artist_name+album_name+album_id+numalbum+duration/track/json/radio_track_inradioplaylist+track_album+album_artist/?order=numradio_asc&radio_id=283
308
309     def __init__(self, what, ID):
310         Query.__init__(self)
311         self.ID = ID
312         info = GetQuery.queries[what]
313         self.url = info['url']
314         self.params = info['params']
315         self.constructor = info['constructor']
316
317     def construct(self, data):
318         constructor = self.constructor
319         if isinstance(constructor, list):
320             constructor = constructor[0]
321         if isinstance(data, list):
322             return [constructor(int(x['id']), json=x) for x in data]
323         else:
324             return constructor(int(data['id']), json=data)
325
326     def execute(self):
327         js = self._geturl(self.url + self.params % (self.ID))
328         if not js:
329             return None
330         return self.construct(js)
331
332     def __str__(self):
333         return self.url + self.params % (self.ID)
334
335 class SearchQuery(GetQuery):
336     def __init__(self, what, query=None, order=None, user=None, count=10):
337         GetQuery.__init__(self, what, None)
338         self.query = query
339         self.order = order
340         self.count = count
341         self.user = user
342
343     def execute(self):
344         params = {}
345         if self.query:
346             params['searchquery'] = self.query
347         if self.order:
348             params['order'] = self.order
349         if self.count:
350             params['n'] = self.count
351         if self.user:
352             params['user_idstr'] = self.user
353         js = self._geturl(self.url +  urllib.urlencode(params))
354         if not js:
355             return None
356         return self.construct(js)
357
358     def __str__(self):
359         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
360         return self.url +  urllib.urlencode(params)
361
362 class JamendoAPIException(Exception):
363     def __init__(self, url):
364         Exception.__init__(url)
365
366 def _update_cache(cache, new_items):
367     if not isinstance(new_items, list):
368         new_items = [new_items]
369     for item in new_items:
370         old = cache.get(item.ID)
371         if old:
372             old._set_from(item)
373         else:
374             cache[item.ID] = item
375
376 def get_artist(artist_id):
377     """Returns: Artist"""
378     a = _artists.get(artist_id, None)
379     if not a:
380         q = GetQuery('artist', artist_id)
381         a = q.execute()
382         if not a:
383             raise JamendoAPIException(str(q))
384         _update_cache(_artists, a)
385     return a
386
387 def get_albums(artist_id):
388     """Returns: [Album]"""
389     q = GetQuery('albums', artist_id)
390     a = q.execute()
391     if not a:
392         raise JamendoAPIException(str(q))
393     _update_cache(_artists, a)
394     return a
395
396 def get_album(album_id):
397     """Returns: Album"""
398     a = _albums.get(album_id, None)
399     if not a:
400         q = GetQuery('album', album_id)
401         a = q.execute()
402         if not a:
403             raise JamendoAPIException(str(q))
404         _update_cache(_albums, a)
405     return a
406
407 def get_tracks(album_id):
408     """Returns: [Track]"""
409     q = GetQuery('tracks', album_id)
410     a = q.execute()
411     if not a:
412         raise JamendoAPIException(str(q))
413     _update_cache(_tracks, a)
414     return a
415
416 def get_track(track_id):
417     """Returns: Track"""
418     a = _tracks.get(track_id, None)
419     if not a:
420         q = GetQuery('track', track_id)
421         a = q.execute()
422         if not a:
423             raise JamendoAPIException(str(q))
424         _update_cache(_tracks, a)
425     return a
426
427 def get_radio_tracks(radio_id):
428     """Returns: [Track]"""
429     q = GetQuery('radio', radio_id)
430     a = q.execute()
431     if not a:
432         raise JamendoAPIException(str(q))
433     _update_cache(_tracks, a)
434     return a
435
436 def search_artists(query):
437     """Returns: [Artist]"""
438     q = SearchQuery('artist', query, 'searchweight_desc')
439     a = q.execute()
440     if not a:
441         raise JamendoAPIException(str(q))
442     _update_cache(_artists, a)
443     return a
444
445 def search_albums(query):
446     """Returns: [Album]"""
447     q = SearchQuery('album', query, 'searchweight_desc')
448     a = q.execute()
449     if not a:
450         raise JamendoAPIException(str(q))
451     _update_cache(_albums, a)
452     return a
453
454 def search_tracks(query):
455     """Returns: [Track]"""
456     q = SearchQuery('track', query=query, order='searchweight_desc')
457     a = q.execute()
458     if not a:
459         raise JamendoAPIException(str(q))
460     _update_cache(_tracks, a)
461     return a
462
463 def albums_of_the_week():
464     """Returns: [Album]"""
465     q = SearchQuery('album', order='ratingweek_desc')
466     a = q.execute()
467     if not a:
468         raise JamendoAPIException(str(q))
469     _update_cache(_albums, a)
470     return a
471
472 def new_releases():
473     """Returns: [Track] (playlist)"""
474     q = SearchQuery('track', order='releasedate_desc')
475     a = q.execute()
476     if not a:
477         raise JamendoAPIException(str(q))
478     _update_cache(_tracks, a)
479     return a
480
481 def tracks_of_the_week():
482     """Returns: [Track] (playlist)"""
483     q = SearchQuery('track', order='ratingweek_desc')
484     a = q.execute()
485     if not a:
486         raise JamendoAPIException(str(q))
487     _update_cache(_tracks, a)
488     return a
489
490 def get_radio(radio_id):
491     """Returns: Radio"""
492     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
493     js = q.execute()
494     if not js:
495         raise JamendoAPIException(str(q))
496     if isinstance(js, list):
497         return [Radio(x['id'], json=x) for x in js]
498     else:
499         return Radio(radio_id, json=js)
500
501 def starred_radios():
502     """Returns: [Radio]"""
503     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
504     js = q.execute()
505     if not js:
506         raise JamendoAPIException(str(q))
507     return [Radio(int(radio['id']), json=radio) for radio in js]
508
509 def favorite_albums(user):
510     """Returns: [Album]"""
511     q = SearchQuery('favorite_albums', user=user, count=20)
512     a = q.execute()
513     if not a:
514         raise JamendoAPIException(str(q))
515     _update_cache(_albums, a)
516     return a
517
518 ### Set loader functions for classes
519
520 def _artist_loader(self):
521     if self._needs_load():
522         artist = get_artist(self.ID)
523         self._set_from(artist)
524 Artist.load = _artist_loader
525
526 def _album_loader(self):
527     if self._needs_load():
528         album = get_album(self.ID)
529         self._set_from(album)
530 Album.load = _album_loader
531
532 def _track_loader(self):
533     track = get_track(self.ID)
534     self._set_from(track)
535 Track.load = _track_loader
536
537 def _radio_loader(self):
538     radio = get_radio(self.ID)
539     self._set_from(radio)
540 Radio.load = _radio_loader