New backend: api2.py
[jamaendo] / jamaendo / api2.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', 'artist_id', 'tracks')
143
144     def _set_from(self, other):
145         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'tracks')
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         }
299 #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
300
301     def __init__(self, what, ID):
302         Query.__init__(self)
303         self.ID = ID
304         info = GetQuery.queries[what]
305         self.url = info['url']
306         self.params = info['params']
307         self.constructor = info['constructor']
308
309     def construct(self, data):
310         constructor = self.constructor
311         if isinstance(constructor, list):
312             constructor = constructor[0]
313         if isinstance(data, list):
314             return [constructor(int(x['id']), json=x) for x in data]
315         else:
316             return constructor(int(data['id']), json=data)
317
318     def execute(self):
319         js = self._geturl(self.url + self.params % (self.ID))
320         if not js:
321             return None
322         return self.construct(js)
323
324     def __str__(self):
325         return self.url + self.params % (self.ID)
326
327 class SearchQuery(GetQuery):
328     def __init__(self, what, query=None, order=None, count=10):
329         GetQuery.__init__(self, what, None)
330         self.query = query
331         self.order = order
332         self.count = count
333
334     def execute(self):
335         params = {}
336         if self.query:
337             params['searchquery'] = self.query
338         if self.order:
339             params['order'] = self.order
340         if self.count:
341             params['n'] = self.count
342         js = self._geturl(self.url +  urllib.urlencode(params))
343         if not js:
344             return None
345         return self.construct(js)
346
347     def __str__(self):
348         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
349         return self.url +  urllib.urlencode(params)
350
351 class JamendoAPIException(Exception):
352     def __init__(self, url):
353         Exception.__init__(url)
354
355 def _update_cache(cache, new_items):
356     if not isinstance(new_items, list):
357         new_items = [new_items]
358     for item in new_items:
359         old = cache.get(item.ID)
360         if old:
361             old._set_from(item)
362         else:
363             cache[item.ID] = item
364
365 def get_artist(artist_id):
366     """Returns: Artist"""
367     a = _artists.get(artist_id, None)
368     if not a:
369         q = GetQuery('artist', artist_id)
370         a = q.execute()
371         if not a:
372             raise JamendoAPIException(str(q))
373         _update_cache(_artists, a)
374     return a
375
376 def get_albums(artist_id):
377     """Returns: [Album]"""
378     q = GetQuery('albums', artist_id)
379     a = q.execute()
380     if not a:
381         raise JamendoAPIException(str(q))
382     _update_cache(_artists, a)
383     return a
384
385 def get_album(album_id):
386     """Returns: Album"""
387     a = _albums.get(album_id, None)
388     if not a:
389         q = GetQuery('album', album_id)
390         a = q.execute()
391         if not a:
392             raise JamendoAPIException(str(q))
393         _update_cache(_albums, a)
394     return a
395
396 def get_tracks(album_id):
397     """Returns: [Track]"""
398     q = GetQuery('tracks', album_id)
399     a = q.execute()
400     if not a:
401         raise JamendoAPIException(str(q))
402     _update_cache(_tracks, a)
403     return a
404
405 def get_track(track_id):
406     """Returns: Track"""
407     a = _tracks.get(track_id, None)
408     if not a:
409         q = GetQuery('track', track_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_radio_tracks(radio_id):
417     """Returns: [Track]"""
418     q = GetQuery('radio', radio_id)
419     a = q.execute()
420     if not a:
421         raise JamendoAPIException(str(q))
422     _update_cache(_tracks, a)
423     return a
424
425 def search_artists(query):
426     """Returns: [Artist]"""
427     q = SearchQuery('artist', query, 'searchweight_desc')
428     a = q.execute()
429     if not a:
430         raise JamendoAPIException(str(q))
431     _update_cache(_artists, a)
432     return a
433
434 def search_albums(query):
435     """Returns: [Album]"""
436     q = SearchQuery('album', query, 'searchweight_desc')
437     a = q.execute()
438     if not a:
439         raise JamendoAPIException(str(q))
440     _update_cache(_albums, a)
441     return a
442
443 def search_tracks(query):
444     """Returns: [Track]"""
445     q = SearchQuery('track', query=query, order='searchweight_desc')
446     a = q.execute()
447     if not a:
448         raise JamendoAPIException(str(q))
449     _update_cache(_tracks, a)
450     return a
451
452 def albums_of_the_week():
453     """Returns: [Album]"""
454     q = SearchQuery('album', order='ratingweek_desc')
455     a = q.execute()
456     if not a:
457         raise JamendoAPIException(str(q))
458     _update_cache(_albums, a)
459     return a
460
461 def new_releases():
462     """Returns: [Track] (playlist)"""
463     q = SearchQuery('track', order='releasedate_desc')
464     a = q.execute()
465     if not a:
466         raise JamendoAPIException(str(q))
467     _update_cache(_tracks, a)
468     return a
469
470 def tracks_of_the_week():
471     """Returns: [Track] (playlist)"""
472     q = SearchQuery('track', order='ratingweek_desc')
473     a = q.execute()
474     if not a:
475         raise JamendoAPIException(str(q))
476     _update_cache(_tracks, a)
477     return a
478
479 def get_radio(radio_id):
480     """Returns: Radio"""
481     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
482     js = q.execute()
483     if not js:
484         raise JamendoAPIException(str(q))
485     if isinstance(js, list):
486         return [Radio(x['id'], json=x) for x in js]
487     else:
488         return Radio(radio_id, json=js)
489
490 def starred_radios():
491     """Returns: [Radio]"""
492     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
493     js = q.execute()
494     if not js:
495         raise JamendoAPIException(str(q))
496     return [Radio(int(radio['id']), json=radio) for radio in js]
497
498 ### Set loader functions for classes
499
500 def _artist_loader(self):
501     if self._needs_load():
502         artist = get_artist(self.ID)
503         self._set_from(artist)
504 Artist.load = _artist_loader
505
506 def _album_loader(self):
507     if self._needs_load():
508         album = get_album(self.ID)
509         self._set_from(album)
510 Album.load = _album_loader
511
512 def _track_loader(self):
513     track = get_track(self.ID)
514     self._set_from(track)
515 Track.load = _track_loader
516
517 def _radio_loader(self):
518     radio = get_radio(self.ID)
519     self._set_from(radio)
520 Radio.load = _radio_loader