hmm, asynchronous api is nontrivial
[jamaendo] / jamaendo / api.py
1 #!/usr/bin/env python
2 #
3 # This file is part of Jamaendo.
4 # Copyright (c) 2010, Kristoffer Gronlund
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 #     * Redistributions of source code must retain the above copyright
10 #       notice, this list of conditions and the following disclaimer.
11 #     * Redistributions in binary form must reproduce the above copyright
12 #       notice, this list of conditions and the following disclaimer in the
13 #       documentation and/or other materials provided with the distribution.
14 #     * Neither the name of Jamaendo nor the
15 #       names of its contributors may be used to endorse or promote products
16 #       derived from this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
22 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 # An improved, structured jamendo API wrapper for the N900 with cacheing
30 # Image / cover downloads.. and more?
31 import urllib, threading, os, gzip, time, simplejson, re
32
33 _CACHEDIR = None
34 _COVERDIR = None
35 _GET2 = '''http://api.jamendo.com/get2/'''
36 _MP3URL = _GET2+'stream/track/redirect/?id=%d&streamencoding=mp31'
37 _OGGURL = _GET2+'stream/track/redirect/?id=%d&streamencoding=ogg2'
38
39
40 def set_cache_dir(cachedir):
41     global _CACHEDIR
42     global _COVERDIR
43     _CACHEDIR = cachedir
44     _COVERDIR = os.path.join(_CACHEDIR, 'covers')
45
46     try:
47         os.makedirs(_CACHEDIR)
48     except OSError:
49         pass
50
51     try:
52         os.makedirs(_COVERDIR)
53     except OSError:
54         pass
55
56 # These classes can be partially constructed,
57 # and if asked for a property they don't know,
58 # makes a query internally to get the full story
59
60 _ARTIST_FIELDS = ['id', 'name', 'image']
61 _ALBUM_FIELDS = ['id', 'name', 'image', 'artist_name', 'artist_id', 'license_url']
62 _TRACK_FIELDS = ['id', 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration']
63 _RADIO_FIELDS = ['id', 'name', 'idstr', 'image']
64
65 class LazyQuery(object):
66     def set_from_json(self, json):
67         for key, value in json.iteritems():
68             if key == 'id':
69                 assert(self.ID == int(value))
70             else:
71                 if key.endswith('_id'):
72                     value = int(value)
73                 setattr(self, key, value)
74
75     def load(self):
76         """Not automatic for now,
77         will have to do artist.load()
78
79         This is filled in further down
80         in the file
81         """
82         raise NotImplemented
83
84     def _needs_load(self):
85         return True
86
87     def _set_from(self, other):
88         raise NotImplemented
89
90     def _needs_load_impl(self, *attrs):
91         for attr in attrs:
92             if getattr(self, attr) is None:
93                 return True
94         return False
95
96     def _set_from_impl(self, other, *attrs):
97         for attr in attrs:
98             self._set_if(other, attr)
99
100     def _set_if(self, other, attrname):
101         if getattr(self, attrname) is None and getattr(other, attrname) is not None:
102             setattr(self, attrname, getattr(other, attrname))
103
104     def __repr__(self):
105         try:
106             return u"%s(%s)"%(self.__class__.__name__,
107                               u", ".join(repr(v) for k,v in self.__dict__.iteritems() if not k.startswith('_')))
108         except UnicodeEncodeError:
109             import traceback
110             traceback.print_exc()
111             return u"%s(?)"%(self.__class__.__name__)
112
113 class Artist(LazyQuery):
114     def __init__(self, ID, json=None):
115         self.ID = int(ID)
116         self.name = None
117         self.image = None
118         self.albums = None # None means not downloaded
119         if json:
120             self.set_from_json(json)
121
122     def _needs_load(self):
123         return self._needs_load_impl('name', 'albums')
124
125     def _set_from(self, other):
126         return self._set_from_impl(other, 'name', 'image', 'albums')
127
128 class Album(LazyQuery):
129     def __init__(self, ID, json=None):
130         self.ID = int(ID)
131         self.name = None
132         self.image = None
133         self.artist_name = None
134         self.artist_id = None
135         self.license_url = None
136         self.tracks = None # None means not downloaded
137         if json:
138             self.set_from_json(json)
139
140     def _needs_load(self):
141         return self._needs_load_impl('name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
142
143     def _set_from(self, other):
144         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
145
146 class Track(LazyQuery):
147     def __init__(self, ID, json=None):
148         self.ID = int(ID)
149         self.name = None
150         self.image = None
151         self.artist_name = None
152         self.album_name = None
153         self.album_id = None
154         self.numalbum = None
155         self.duration = None
156         if json:
157             self.set_from_json(json)
158
159     def mp3_url(self):
160        return _MP3URL%(self.ID)
161
162     def ogg_url(self):
163        return _OGGURL%(self.ID)
164
165     def _needs_load(self):
166         return self._needs_load_impl('name', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
167
168     def _set_from(self, other):
169         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
170
171 class Radio(LazyQuery):
172     def __init__(self, ID, json=None):
173         self.ID = int(ID)
174         self.name = None
175         self.idstr = None
176         self.image = None
177         if json:
178             self.set_from_json(json)
179
180     def _needs_load(self):
181         return self._needs_load_impl('name', 'idstr', 'image')
182
183     def _set_from(self, other):
184         return self._set_from_impl(other, 'name', 'idstr', 'image')
185
186
187 _artists = {} # id -> Artist()
188 _albums = {} # id -> Album()
189 _tracks = {} # id -> Track()
190 _radios = {} # id -> Radio()
191
192
193 # cache sizes per session (TODO)
194 _CACHED_ARTISTS = 100
195 _CACHED_ALBUMS = 200
196 _CACHED_TRACKS = 500
197 _CACHED_RADIOS = 10
198
199 # TODO: cache queries?
200
201 class Query(object):
202     rate_limit = 1.1 # seconds between queries
203     last_query = time.time() - 1.5
204
205     @classmethod
206     def _ratelimit(cls):
207         now = time.time()
208         if now - cls.last_query < cls.rate_limit:
209             time.sleep(cls.rate_limit - (now - cls.last_query))
210         cls.last_query = now
211
212     def __init__(self):
213         pass
214
215     def _geturl(self, url):
216         print "*** %s" % (url)
217         Query._ratelimit()
218         f = urllib.urlopen(url)
219         ret = simplejson.load(f)
220         f.close()
221         return ret
222
223     def __str__(self):
224         return "#%s" % (self.__class__.__name__)
225
226     def execute(self):
227         raise NotImplemented
228
229 import threading
230
231 class CoverFetcher(threading.Thread):
232     def __init__(self):
233         threading.Thread.__init__(self)
234         self.setDaemon(True)
235         self.cond = threading.Condition()
236         self.work = []
237
238     def _fetch_cover(self, albumid, size):
239         coverdir = _COVERDIR if _COVERDIR else '/tmp'
240         to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
241         if not os.path.isfile(to):
242             url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
243             urllib.urlretrieve(url, to)
244         return to
245
246     def request_cover(self, albumid, size, cb):
247         self.cond.acquire()
248         self.work.insert(0, (albumid, size, cb))
249         self.cond.notify()
250         self.cond.release()
251
252     def run(self):
253         while True:
254             work = []
255             self.cond.acquire()
256             while True:
257                 work = self.work
258                 if work:
259                     self.work = []
260                     break
261                 self.cond.wait()
262             self.cond.release()
263
264             for albumid, size, cb in work:
265                 cover = self._fetch_cover(albumid, size)
266                 cb(albumid, size, cover)
267
268 class CoverCache(object):
269     """
270     cache and fetch covers
271     TODO: background thread that
272     fetches and returns covers,
273     asynchronously, LIFO
274     """
275     def __init__(self):
276         self._covers = {} # (albumid, size) -> file
277         coverdir = _COVERDIR if _COVERDIR else '/tmp'
278         if os.path.isdir(coverdir):
279             covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
280             for fil in os.listdir(coverdir):
281                 fl = os.path.join(coverdir, fil)
282                 m = covermatch.match(fil)
283                 if m and os.path.isfile(fl):
284                     self._covers[(int(m.group(1)), int(m.group(2)))] = fl
285         self._fetcher = CoverFetcher()
286         self._fetcher.start()
287
288     def fetch_cover(self, albumid, size):
289         coverdir = _COVERDIR if _COVERDIR else '/tmp'
290         to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
291         if not os.path.isfile(to):
292             url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
293             urllib.urlretrieve(url, to)
294             self._covers[(albumid, size)] = to
295         return to
296
297     def get_cover(self, albumid, size):
298         cover = self._covers.get((albumid, size), None)
299         if not cover:
300             cover = self.fetch_cover(albumid, size)
301         return cover
302
303     def get_async(self, albumid, size, cb):
304         cover = self._covers.get((albumid, size), None)
305         if cover:
306             cb(cover)
307         else:
308             self._fetcher.request_cover(albumid, size, cb)
309
310 _cover_cache = CoverCache()
311
312 def get_album_cover(albumid, size=200):
313     return _cover_cache.get_cover(albumid, size)
314
315 def get_album_cover_async(cb, albumid, size=200):
316     _cover_cache.get_async(albumid, size, cb)
317
318 class CustomQuery(Query):
319     def __init__(self, url):
320         Query.__init__(self)
321         self.url = url
322
323     def execute(self):
324         return self._geturl(self.url)
325
326     def __str__(self):
327         return self.url
328
329 class GetQuery(Query):
330     queries = {
331         'artist' : {
332             'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
333             'params' : 'artist_id=%d',
334             'constructor' : Artist
335             },
336         'album' : {
337             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
338             'params' : 'album_id=%d',
339             'constructor' : Album
340             },
341         'albums' : {
342             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
343             'params' : 'artist_id=%d',
344             'constructor' : [Album]
345             },
346         'track' : {
347             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
348             'params' : 'id=%d',
349             'constructor' : Track
350             },
351         'tracks' : {
352             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
353             'params' : 'order=numalbum_asc&album_id=%d',
354             'constructor' : [Track]
355             },
356         'radio' : {
357             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
358             'params' : 'order=random_asc&radio_id=%d',
359             'constructor' : [Track]
360             },
361         'favorite_albums' : {
362             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
363             'params' : 'user_idstr=%s',
364             'constructor' : [Album]
365             },
366     #http://api.jamendo.com/get2/id+name+url+image+artist_name/album/jsonpretty/album_user_starred/?user_idstr=sylvinus&n=all
367     #q = SearchQuery('album', user_idstr=user)
368
369         }
370 #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
371
372     def __init__(self, what, ID):
373         Query.__init__(self)
374         self.ID = ID
375         info = GetQuery.queries[what]
376         self.url = info['url']
377         self.params = info['params']
378         self.constructor = info['constructor']
379
380     def construct(self, data):
381         constructor = self.constructor
382         if isinstance(constructor, list):
383             constructor = constructor[0]
384         if isinstance(data, list):
385             return [constructor(int(x['id']), json=x) for x in data]
386         else:
387             return constructor(int(data['id']), json=data)
388
389     def execute(self):
390         js = self._geturl(self.url + self.params % (self.ID))
391         if not js:
392             return None
393         return self.construct(js)
394
395     def __str__(self):
396         return self.url + self.params % (self.ID)
397
398 class SearchQuery(GetQuery):
399     def __init__(self, what, query=None, order=None, user=None, count=10):
400         GetQuery.__init__(self, what, None)
401         self.query = query
402         self.order = order
403         self.count = count
404         self.user = user
405
406     def execute(self):
407         params = {}
408         if self.query:
409             params['searchquery'] = self.query
410         if self.order:
411             params['order'] = self.order
412         if self.count:
413             params['n'] = self.count
414         if self.user:
415             params['user_idstr'] = self.user
416         js = self._geturl(self.url +  urllib.urlencode(params))
417         if not js:
418             return None
419         return self.construct(js)
420
421     def __str__(self):
422         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
423         return self.url +  urllib.urlencode(params)
424
425 class JamendoAPIException(Exception):
426     def __init__(self, url):
427         Exception.__init__(self, url)
428
429 def _update_cache(cache, new_items):
430     if not isinstance(new_items, list):
431         new_items = [new_items]
432     for item in new_items:
433         old = cache.get(item.ID)
434         if old:
435             old._set_from(item)
436         else:
437             cache[item.ID] = item
438
439 def get_artist(artist_id):
440     """Returns: Artist"""
441     a = _artists.get(artist_id, None)
442     if not a:
443         q = GetQuery('artist', artist_id)
444         a = q.execute()
445         if not a:
446             raise JamendoAPIException(str(q))
447         _update_cache(_artists, a)
448         if isinstance(a, list):
449             a = a[0]
450     return a
451
452 def get_albums(artist_id):
453     """Returns: [Album]"""
454     q = GetQuery('albums', artist_id)
455     a = q.execute()
456     if not a:
457         raise JamendoAPIException(str(q))
458     _update_cache(_artists, a)
459     return a
460
461 def get_album(album_id):
462     """Returns: Album"""
463     a = _albums.get(album_id, None)
464     if not a:
465         q = GetQuery('album', album_id)
466         a = q.execute()
467         if not a:
468             raise JamendoAPIException(str(q))
469         _update_cache(_albums, a)
470         if isinstance(a, list):
471             a = a[0]
472     return a
473
474 def get_tracks(album_id):
475     """Returns: [Track]"""
476     q = GetQuery('tracks', album_id)
477     a = q.execute()
478     if not a:
479         raise JamendoAPIException(str(q))
480     _update_cache(_tracks, a)
481     return a
482
483 def get_track(track_id):
484     """Returns: Track"""
485     a = _tracks.get(track_id, None)
486     if not a:
487         q = GetQuery('track', track_id)
488         a = q.execute()
489         if not a:
490             raise JamendoAPIException(str(q))
491         _update_cache(_tracks, a)
492         if isinstance(a, list):
493             a = a[0]
494     return a
495
496 def get_radio_tracks(radio_id):
497     """Returns: [Track]"""
498     q = GetQuery('radio', radio_id)
499     a = q.execute()
500     if not a:
501         raise JamendoAPIException(str(q))
502     _update_cache(_tracks, a)
503     return a
504
505 def search_artists(query):
506     """Returns: [Artist]"""
507     q = SearchQuery('artist', query, 'searchweight_desc')
508     a = q.execute()
509     if not a:
510         raise JamendoAPIException(str(q))
511     _update_cache(_artists, a)
512     return a
513
514 def search_albums(query):
515     """Returns: [Album]"""
516     q = SearchQuery('album', query, 'searchweight_desc')
517     a = q.execute()
518     if not a:
519         raise JamendoAPIException(str(q))
520     _update_cache(_albums, a)
521     return a
522
523 def search_tracks(query):
524     """Returns: [Track]"""
525     q = SearchQuery('track', query=query, order='searchweight_desc')
526     a = q.execute()
527     if not a:
528         raise JamendoAPIException(str(q))
529     _update_cache(_tracks, a)
530     return a
531
532 def albums_of_the_week():
533     """Returns: [Album]"""
534     q = SearchQuery('album', order='ratingweek_desc')
535     a = q.execute()
536     if not a:
537         raise JamendoAPIException(str(q))
538     _update_cache(_albums, a)
539     return a
540
541 def new_releases():
542     """Returns: [Track] (playlist)"""
543     q = SearchQuery('track', order='releasedate_desc')
544     a = q.execute()
545     if not a:
546         raise JamendoAPIException(str(q))
547     _update_cache(_tracks, a)
548     return a
549
550 def tracks_of_the_week():
551     """Returns: [Track] (playlist)"""
552     q = SearchQuery('track', order='ratingweek_desc')
553     a = q.execute()
554     if not a:
555         raise JamendoAPIException(str(q))
556     _update_cache(_tracks, a)
557     return a
558
559 def get_radio(radio_id):
560     """Returns: Radio"""
561     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
562     js = q.execute()
563     if not js:
564         raise JamendoAPIException(str(q))
565     if isinstance(js, list):
566         ks = js[0]
567     return Radio(radio_id, json=js)
568
569 def starred_radios():
570     """Returns: [Radio]"""
571     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
572     js = q.execute()
573     if not js:
574         raise JamendoAPIException(str(q))
575     return [Radio(int(radio['id']), json=radio) for radio in js]
576
577 def favorite_albums(user):
578     """Returns: [Album]"""
579     q = SearchQuery('favorite_albums', user=user, count=20)
580     a = q.execute()
581     if not a:
582         raise JamendoAPIException(str(q))
583     _update_cache(_albums, a)
584     return a
585
586 ### Set loader functions for classes
587
588 def _artist_loader(self):
589     if self._needs_load():
590         artist = get_artist(self.ID)
591         self._set_from(artist)
592 Artist.load = _artist_loader
593
594 def _album_loader(self):
595     if self._needs_load():
596         album = get_album(self.ID)
597         album.tracks = get_tracks(self.ID)
598         self._set_from(album)
599 Album.load = _album_loader
600
601 def _track_loader(self):
602     track = get_track(self.ID)
603     self._set_from(track)
604 Track.load = _track_loader
605
606 def _radio_loader(self):
607     radio = get_radio(self.ID)
608     self._set_from(radio)
609 Radio.load = _radio_loader