ca4e51f8845154c44976e8c963c4dd4b4f0d0bd4
[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 #
12 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
13 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
14 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15 # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
16 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
23 # An improved, structured jamendo API wrapper for the N900 with cacheing
24 # Image / cover downloads.. and more?
25 from __future__ import with_statement
26 import urllib, threading, os, time, simplejson, re
27 import logging, hashlib
28 import pycurl, StringIO
29
30 _CACHEDIR = None
31 _COVERDIR = None
32 _GET2 = '''http://api.jamendo.com/get2/'''
33 _MP3URL = _GET2+'stream/track/redirect/?id=%d&streamencoding=mp31'
34 _OGGURL = _GET2+'stream/track/redirect/?id=%d&streamencoding=ogg2'
35 _TORRENTURL = _GET2+'bittorrent/file/redirect/?album_id=%d&type=archive&class=mp32'
36
37 try:
38     log = logging.getLogger(__name__)
39 except:
40     class StdoutLogger(object):
41         def info(self, s, *args):
42             print s % (args)
43         def debug(self, s, *args):
44             pass#print s % (args)
45     log = StdoutLogger()
46
47 # These classes can be partially constructed,
48 # and if asked for a property they don't know,
49 # makes a query internally to get the full story
50
51 _ARTIST_FIELDS = ['id', 'name', 'image']
52 _ALBUM_FIELDS = ['id', 'name', 'image', 'artist_name', 'artist_id', 'license_url']
53 _TRACK_FIELDS = ['id', 'name', 'album_image', 'artist_id', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration']
54 _RADIO_FIELDS = ['id', 'name', 'idstr', 'image']
55 _TAG_FIELDS = ['id', 'name']
56
57 _APILOCK = threading.Lock()
58
59 def curlGET(url):
60     c = pycurl.Curl()
61     s = StringIO.StringIO()
62     c.setopt(pycurl.FOLLOWLOCATION, 1)
63     c.setopt(pycurl.URL, url)
64     c.setopt(pycurl.WRITEFUNCTION, s.write)
65     try:
66         c.perform()
67     finally:
68         c.close()
69     s.seek(0)
70     return s.read()
71
72 class LazyQuery(object):
73     def set_from_json(self, json):
74         for key, value in json.iteritems():
75             if key == 'id':
76                 assert(self.ID == int(value))
77             else:
78                 if key.endswith('_id'):
79                     value = int(value)
80                 setattr(self, key, value)
81
82     def load(self):
83         """Not automatic for now,
84         will have to do artist.load()
85
86         This is filled in further down
87         in the file
88         """
89         raise NotImplemented
90
91     def _needs_load(self):
92         return True
93
94     def _set_from(self, other):
95         raise NotImplemented
96
97     def _needs_load_impl(self, *attrs):
98         for attr in attrs:
99             if getattr(self, attr) is None:
100                 return True
101         return False
102
103     def _set_from_impl(self, other, *attrs):
104         for attr in attrs:
105             self._set_if(other, attr)
106
107     def _set_if(self, other, attrname):
108         if getattr(self, attrname) is None and getattr(other, attrname) is not None:
109             setattr(self, attrname, getattr(other, attrname))
110
111     def __repr__(self):
112         try:
113             return u"%s(%s)"%(self.__class__.__name__,
114                               u", ".join(("%s:%s"%(k,repr(v))) for k,v in self.__dict__.iteritems() if not k.startswith('_')))
115         except UnicodeEncodeError:
116             #import traceback
117             #traceback.print_exc()
118             return u"%s(?)"%(self.__class__.__name__)
119
120 class Artist(LazyQuery):
121     def __init__(self, ID, json=None):
122         self.ID = int(ID)
123         self.name = None
124         self.image = None
125         self.albums = None # None means not downloaded
126         if json:
127             self.set_from_json(json)
128
129     def _needs_load(self):
130         return self._needs_load_impl('name', 'albums')
131
132     def _set_from(self, other):
133         return self._set_from_impl(other, 'name', 'image', 'albums')
134
135     def get_data(self):
136         return {'name':self.name, 'image':self.image}
137
138 class Album(LazyQuery):
139     def __init__(self, ID, json=None):
140         self.ID = int(ID)
141         self.name = None
142         self.image = None
143         self.artist_name = None
144         self.artist_id = None
145         self.license_url = None
146         self.tracks = None # None means not downloaded
147         if json:
148             self.set_from_json(json)
149
150     def torrent_url(self):
151         return _TORRENTURL%(self.ID)
152
153
154     def _needs_load(self):
155         return self._needs_load_impl('name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
156
157     def _set_from(self, other):
158         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
159
160     def get_data(self):
161         return {'name':self.name, 'image':self.image,
162                 'artist_name':self.artist_name,
163                 'artist_id':self.artist_id,
164                 'license_url':self.license_url}
165
166 class Track(LazyQuery):
167     def __init__(self, ID, json=None):
168         self.ID = int(ID)
169         self.name = None
170         self.artist_id = None
171         self.artist_name = None
172         self.album_image = None
173         self.album_name = None
174         self.album_id = None
175         self.numalbum = None
176         self.duration = None
177         if json:
178             self.set_from_json(json)
179
180     def mp3_url(self):
181        return _MP3URL%(self.ID)
182
183     def ogg_url(self):
184        return _OGGURL%(self.ID)
185
186     def get_data(self):
187         return {'name':self.name,
188                 'artist_id':self.artist_id,
189                 'artist_name':self.artist_name,
190                 'album_image':self.album_image,
191                 'album_name':self.album_name,
192                 'album_id':self.album_id,
193                 'numalbum':self.numalbum,
194                 'duration':self.duration}
195
196     def _needs_load(self):
197         return self._needs_load_impl('name', 'artist_name', 'artist_id', 'album_name', 'album_id', 'numalbum', 'duration')
198
199     def _set_from(self, other):
200         return self._set_from_impl(other, 'name', 'album_image', 'artist_name', 'artist_id', 'album_name', 'album_id', 'numalbum', 'duration')
201
202 class Radio(LazyQuery):
203     def __init__(self, ID, json=None):
204         self.ID = int(ID)
205         self.name = None
206         self.idstr = None
207         self.image = None
208         if json:
209             self.set_from_json(json)
210
211     def _needs_load(self):
212         return self._needs_load_impl('name', 'idstr', 'image')
213
214     def _set_from(self, other):
215         return self._set_from_impl(other, 'name', 'idstr', 'image')
216
217 class Tag(LazyQuery):
218     def __init__(self, ID, json=None):
219         self.ID = int(ID)
220         self.name = None
221         if json:
222             self.set_from_json(json)
223
224     def _needs_load(self):
225         return self._needs_load_impl('name')
226
227     def _set_from(self, other):
228         return self._set_from_impl(other, 'name')
229
230 _artists = {} # id -> Artist()
231 _albums = {} # id -> Album()
232 _tracks = {} # id -> Track()
233 _radios = {} # id -> Radio()
234
235
236 # cache sizes per session (TODO)
237 _CACHED_ARTISTS = 100
238 _CACHED_ALBUMS = 200
239 _CACHED_TRACKS = 500
240 _CACHED_RADIOS = 10
241 # cache sizes, persistant
242 _CACHED_COVERS = 2048
243
244 # TODO: cache queries?
245
246 class Ratelimit(object):
247     rate_limit = 1.0 # seconds between queries
248     last_query = time.time() - 1.5
249
250     @classmethod
251     def ratelimit(cls):
252         now = time.time()
253         if (now - cls.last_query) < cls.rate_limit:
254             time.sleep(cls.rate_limit - (now - cls.last_query))
255         cls.last_query = time.time()
256
257 _ratelimit = Ratelimit.ratelimit
258
259 class Query(object):
260     def __init__(self):
261         pass
262
263     def _geturl(self, url):
264         _ratelimit()
265         log.info("%s", url)
266         try:
267             ret = simplejson.loads(curlGET(url))
268         except Exception, e:
269             return None
270         return ret
271
272     def __str__(self):
273         return "#%s" % (self.__class__.__name__)
274
275     def execute(self):
276         raise NotImplemented
277
278 class CoverFetcher(threading.Thread):
279     def __init__(self):
280         threading.Thread.__init__(self)
281         self.setDaemon(True)
282         self.cond = threading.Condition()
283         self.work = []
284
285     def _retrieve(self, url, fname):
286         BROKEN = 'http://imgjam.com/radios/default/default.100.png'
287         if url == BROKEN:
288             return None
289         f = open(fname, 'wb')
290         c = pycurl.Curl()
291         c.setopt(pycurl.FOLLOWLOCATION, 1)
292         c.setopt(pycurl.URL, str(url))
293         c.setopt(pycurl.WRITEFUNCTION, f.write)
294         try:
295             c.perform()
296         except:
297             fname = None
298         finally:
299             c.close()
300             f.close()
301         log.debug("Coverfetch: %s -> %s", url, fname)
302         return fname
303
304     def _fetch_cover(self, albumid, size):
305         try:
306             coverdir = _COVERDIR if _COVERDIR else '/tmp'
307             to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
308             if not os.path.isfile(to):
309                 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
310                 to = self._retrieve(url, to)
311             return to
312         except Exception, e:
313             return None
314
315     def _fetch_image(self, url):
316         try:
317             h = hashlib.md5(url).hexdigest()
318             coverdir = _COVERDIR if _COVERDIR else '/tmp'
319             to = os.path.join(coverdir, h+'.jpg')
320             if not os.path.isfile(to):
321                 to = self._retrieve(url, to)
322             return to
323         except Exception, e:
324             return None
325
326     def request_cover(self, albumid, size, cb):
327         self.cond.acquire()
328         self.work.insert(0, (albumid, size, cb))
329         self.cond.notify()
330         self.cond.release()
331
332     def request_images(self, urls, cb):
333         """cb([(url, image)])"""
334         self.cond.acquire()
335         self.work = [('image', url, cb) for url in urls] + self.work
336         self.cond.notify()
337         self.cond.release()
338
339     def run(self):
340         while True:
341             work = []
342             self.cond.acquire()
343             while True:
344                 work = self.work
345                 if work:
346                     self.work = []
347                     break
348                 self.cond.wait()
349             self.cond.release()
350
351             multi = len(work) > 1
352             for job in work:
353                 if job[0] == 'image':
354                     self.process_image(job[1], job[2])
355                 else:
356                     self.process_cover(*job)
357
358     def process_cover(self, albumid, size, cb):
359         cover = self._fetch_cover(albumid, size)
360         if cover:
361             cb(albumid, size, cover)
362
363     def process_image(self, url, cb):
364         image = self._fetch_image(url)
365         if image:
366             cb([(url, image)])
367
368 class CoverCache(object):
369     """
370     cache and fetch covers
371     TODO: background thread that
372     fetches and returns covers,
373     asynchronously, LIFO
374     """
375     def __init__(self):
376         self._covers = {} # (albumid, size) -> file
377         self._images = {}
378         self._fetcher = CoverFetcher()
379         self._fetcher.start()
380         if _COVERDIR and os.path.isdir(_COVERDIR):
381             self.prime_cache()
382
383     def prime_cache(self):
384         coverdir = _COVERDIR
385         covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
386
387         prev_covers = os.listdir(coverdir)
388
389         if len(prev_covers) > _CACHED_COVERS:
390             import random
391             dropn = len(prev_covers) - _CACHED_COVERS
392             todrop = random.sample(prev_covers, dropn)
393             log.warning("Deleting from cache: %s", todrop)
394             for d in todrop:
395                 m = covermatch.match(d)
396                 if m:
397                     try:
398                         os.unlink(os.path.join(coverdir, d))
399                     except OSError, e:
400                         log.exception('unlinking failed')
401
402         for fil in os.listdir(coverdir):
403             fl = os.path.join(coverdir, fil)
404             m = covermatch.match(fil)
405             if m and os.path.isfile(fl):
406                 self._covers[(int(m.group(1)), int(m.group(2)))] = fl
407
408     def fetch_cover(self, albumid, size):
409         coverdir = _COVERDIR
410         if coverdir:
411             to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
412             if not os.path.isfile(to):
413                 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
414                 urllib.urlretrieve(url, to)
415                 self._covers[(albumid, size)] = to
416             return to
417         return None
418
419     def get_cover(self, albumid, size):
420         cover = self._covers.get((albumid, size), None)
421         if not cover:
422             cover = self.fetch_cover(albumid, size)
423         return cover
424
425     def get_async(self, albumid, size, cb):
426         cover = self._covers.get((albumid, size), None)
427         if cover:
428             cb(albumid, size, cover)
429         else:
430             def cb2(albumid, size, cover):
431                 self._covers[(albumid, size)] = cover
432                 cb(albumid, size, cover)
433             self._fetcher.request_cover(albumid, size, cb2)
434
435     def get_images_async(self, url_list, cb):
436         found = []
437         lookup = []
438         for url in url_list:
439             image = self._images.get(url, None)
440             if image:
441                 found.append((url, image))
442             else:
443                 lookup.append(url)
444         if found:
445             cb(found)
446
447         if lookup:
448             def cb2(results):
449                 for url, image in results:
450                     self._images[url] = image
451                 cb(results)
452             self._fetcher.request_images(lookup, cb2)
453
454 _cover_cache = CoverCache()
455
456 def set_cache_dir(cachedir):
457     global _CACHEDIR
458     global _COVERDIR
459     _CACHEDIR = cachedir
460     _COVERDIR = os.path.join(_CACHEDIR, 'covers')
461
462     try:
463         os.makedirs(_CACHEDIR)
464     except OSError:
465         pass
466
467     try:
468         os.makedirs(_COVERDIR)
469     except OSError:
470         pass
471
472     _cover_cache.prime_cache()
473
474 def get_album_cover(albumid, size=100):
475     with _APILOCK:
476         return _cover_cache.get_cover(albumid, size)
477
478 def get_album_cover_async(cb, albumid, size=100):
479     with _APILOCK:
480         _cover_cache.get_async(albumid, size, cb)
481
482 def get_images_async(cb, url_list):
483     with _APILOCK:
484         _cover_cache.get_images_async(url_list, cb)
485
486 class CustomQuery(Query):
487     def __init__(self, url):
488         Query.__init__(self)
489         self.url = url
490
491     def execute(self):
492         return self._geturl(self.url)
493
494     def __str__(self):
495         return self.url
496
497 class GetQuery(Query):
498     queries = {
499         'artist' : {
500             'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
501             'params' : 'artist_id=%d',
502             'constructor' : Artist
503             },
504         'artist_list' : {
505             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/artist/json/?',
506             'params' : 'artist_id=%s',
507             'constructor' : Album
508             },
509         'album' : {
510             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
511             'params' : 'album_id=%d',
512             'constructor' : Album
513             },
514         'album_list' : {
515             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
516             'params' : 'album_id=%s',
517             'constructor' : Album
518             },
519         'albums' : {
520             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
521             'params' : 'artist_id=%d',
522             'constructor' : [Album]
523             },
524         'track' : {
525             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
526             'params' : 'id=%d',
527             'constructor' : Track
528             },
529         'track_list' : {
530             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
531             'params' : 'id=%s',
532             'constructor' : Track
533             },
534         'tracks' : {
535             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
536             'params' : 'order=numalbum_asc&album_id=%d',
537             'constructor' : [Track]
538             },
539         'radio' : {
540             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
541             'params' : 'order=random_asc&radio_id=%d&n=16',
542             'constructor' : [Track]
543             },
544         'favorite_albums' : {
545             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
546             'params' : 'user_idstr=%s',
547             'constructor' : [Album]
548             },
549         'tag' : {
550             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
551             'params' : 'tag_id=%d&n=50&order=rating_desc',
552             'constructor' : [Track]
553             },
554         }
555
556     def __init__(self, what, ID):
557         Query.__init__(self)
558         self.ID = ID
559         info = GetQuery.queries[what]
560         self.url = info['url']
561         self.params = info['params']
562         self.constructor = info['constructor']
563
564     def construct(self, data):
565         constructor = self.constructor
566         if isinstance(constructor, list):
567             constructor = constructor[0]
568         if isinstance(data, list):
569             return [constructor(int(x['id']), json=x) for x in data]
570         else:
571             return constructor(int(data['id']), json=data)
572
573     def execute(self):
574         js = self._geturl(self.url + self.params % (self.ID))
575         if not js:
576             return None
577         return self.construct(js)
578
579     def __str__(self):
580         return self.url + self.params % (self.ID)
581
582 class SearchQuery(GetQuery):
583     def __init__(self, what, query=None, order=None, user=None, count=20):
584         GetQuery.__init__(self, what, None)
585         self.query = query
586         self.order = order
587         self.count = count
588         self.user = user
589
590     def execute(self):
591         params = {}
592         if self.query:
593             params['searchquery'] = self.query
594         if self.order:
595             params['order'] = self.order
596         if self.count:
597             params['n'] = self.count
598         if self.user:
599             params['user_idstr'] = self.user
600         js = self._geturl(self.url +  urllib.urlencode(params))
601         if not js:
602             return None
603         return self.construct(js)
604
605     def __str__(self):
606         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
607         return self.url +  urllib.urlencode(params)
608
609 class JamendoAPIException(Exception):
610     def __init__(self, url):
611         Exception.__init__(self, url)
612
613 def _update_cache(cache, new_items):
614     if not isinstance(new_items, list):
615         new_items = [new_items]
616     for item in new_items:
617         old = cache.get(item.ID)
618         if old:
619             old._set_from(item)
620         else:
621             cache[item.ID] = item
622         if isinstance(item, Artist) and item.albums:
623             for album in item.albums:
624                 _update_cache(_albums, album)
625         elif isinstance(item, Album) and item.tracks:
626             for track in item.tracks:
627                 _update_cache(_tracks, track)
628     # enforce cache limits here!
629     # also, TODO: save/load cache between sessions
630     # that will require storing a timestamp with
631     # each item, though..
632     # perhaps,
633     # artists: 1 day - changes often
634     # albums: 2-5 days - changes less often (?)
635     # tracks: 1 week - changes rarely, queried often
636
637 def get_artist(artist_id):
638     """Returns: Artist"""
639     with _APILOCK:
640         a = _artists.get(artist_id, None)
641         if not a:
642             q = GetQuery('artist', artist_id)
643             a = q.execute()
644             if not a:
645                 raise JamendoAPIException(str(q))
646             _update_cache(_artists, a)
647             if isinstance(a, list):
648                 a = a[0]
649         return a
650
651 def get_artists(artist_ids):
652     """Returns: [Artist]"""
653     with _APILOCK:
654         assert(isinstance(artist_ids, list))
655         found = []
656         lookup = []
657         for artist_id in artist_ids:
658             a = _artists.get(artist_id, None)
659             if not a:
660                 lookup.append(artist_id)
661             else:
662                 found.append(a)
663         if lookup:
664             q = GetQuery('artist_list', '+'.join(str(x) for x in lookup))
665             a = q.execute()
666             if not a:
667                 raise JamendoAPIException(str(q))
668             _update_cache(_artists, a)
669             lookup = a
670         return found + lookup
671
672 def get_album_list(album_ids):
673     """Returns: [Album]"""
674     with _APILOCK:
675         assert(isinstance(album_ids, list))
676         found = []
677         lookup = []
678         for album_id in album_ids:
679             a = _albums.get(album_id, None)
680             if not a:
681                 lookup.append(album_id)
682             else:
683                 found.append(a)
684         if lookup:
685             q = GetQuery('album_list', '+'.join(str(x) for x in lookup))
686             a = q.execute()
687             if not a:
688                 raise JamendoAPIException(str(q))
689             _update_cache(_albums, a)
690             lookup = a
691         return found + lookup
692
693 def get_albums(artist_id):
694     """Returns: [Album]
695     Parameter can either be an artist_id or a list of album ids.
696     """
697     with _APILOCK:
698         if isinstance(artist_id, list):
699             return get_album_list(artist_id)
700         a = _artists.get(artist_id, None)
701         if a and a.albums:
702             return a.albums
703
704         q = GetQuery('albums', artist_id)
705         a = q.execute()
706         if not a:
707             raise JamendoAPIException(str(q))
708         _update_cache(_albums, a)
709         return a
710
711 def get_album(album_id):
712     """Returns: Album"""
713     with _APILOCK:
714         a = _albums.get(album_id, None)
715         if not a:
716             q = GetQuery('album', album_id)
717             a = q.execute()
718             if not a:
719                 raise JamendoAPIException(str(q))
720             _update_cache(_albums, a)
721             if isinstance(a, list):
722                 a = a[0]
723         return a
724
725 def get_track_list(track_ids):
726     """Returns: [Track]"""
727     with _APILOCK:
728         assert(isinstance(track_ids, list))
729         found = []
730         lookup = []
731         for track_id in track_ids:
732             a = _tracks.get(track_id, None)
733             if not a:
734                 lookup.append(track_id)
735             else:
736                 found.append(a)
737         if lookup:
738             q = GetQuery('track_list', '+'.join(str(x) for x in lookup))
739             a = q.execute()
740             if not a:
741                 raise JamendoAPIException(str(q))
742             _update_cache(_tracks, a)
743             lookup = a
744         return found + lookup
745
746 def get_tracks(album_id):
747     """Returns: [Track]
748     Parameter can either be an album_id or a list of track ids.
749     """
750     with _APILOCK:
751         if isinstance(album_id, list):
752             return get_track_list(album_id)
753         a = _albums.get(album_id, None)
754         if a and a.tracks:
755             return a.tracks
756
757         q = GetQuery('tracks', album_id)
758         a = q.execute()
759         if not a:
760             raise JamendoAPIException(str(q))
761         _update_cache(_tracks, a)
762         return a
763
764 def get_track(track_id):
765     """Returns: Track"""
766     with _APILOCK:
767         a = _tracks.get(track_id, None)
768         if not a:
769             q = GetQuery('track', track_id)
770             a = q.execute()
771             if not a:
772                 raise JamendoAPIException(str(q))
773             _update_cache(_tracks, a)
774             if isinstance(a, list):
775                 a = a[0]
776         return a
777
778 def get_radio_tracks(radio_id):
779     """Returns: [Track]"""
780     with _APILOCK:
781         q = GetQuery('radio', radio_id)
782         a = q.execute()
783         if not a:
784             raise JamendoAPIException(str(q))
785         _update_cache(_tracks, a)
786         return a
787
788 #http://api.jamendo.com/get2/id+name/track/plain/?tag_id=327&n=50&order=rating_desc
789 def get_tag_tracks(tag_id):
790     """Returns: [Track]"""
791     with _APILOCK:
792         q = GetQuery('tag', tag_id)
793         a = q.execute()
794         if not a:
795             raise JamendoAPIException(str(q))
796         _update_cache(_tracks, a)
797         return a
798
799 def search_artists(query):
800     """Returns: [Artist]"""
801     with _APILOCK:
802         q = SearchQuery('artist', query, 'searchweight_desc')
803         a = q.execute()
804         if not a:
805             raise JamendoAPIException(str(q))
806         _update_cache(_artists, a)
807         return a
808
809 def search_albums(query):
810     """Returns: [Album]"""
811     with _APILOCK:
812         q = SearchQuery('album', query, 'searchweight_desc')
813         a = q.execute()
814         if not a:
815             raise JamendoAPIException(str(q))
816         _update_cache(_albums, a)
817         return a
818
819 def search_tracks(query):
820     """Returns: [Track]"""
821     with _APILOCK:
822         q = SearchQuery('track', query=query, order='searchweight_desc')
823         a = q.execute()
824         if not a:
825             raise JamendoAPIException(str(q))
826         _update_cache(_tracks, a)
827         return a
828
829 def albums_of_the_week():
830     """Returns: [Album]"""
831     with _APILOCK:
832         q = SearchQuery('album', order='ratingweek_desc')
833         a = q.execute()
834         if not a:
835             raise JamendoAPIException(str(q))
836         _update_cache(_albums, a)
837         return a
838
839 def new_releases():
840     """Returns: [Track] (playlist)"""
841     with _APILOCK:
842         q = SearchQuery('track', order='releasedate_desc')
843         a = q.execute()
844         if not a:
845             raise JamendoAPIException(str(q))
846         _update_cache(_tracks, a)
847         return a
848
849 def tracks_of_the_week():
850     """Returns: [Track] (playlist)"""
851     with _APILOCK:
852         q = SearchQuery('track', order='ratingweek_desc')
853         a = q.execute()
854         if not a:
855             raise JamendoAPIException(str(q))
856         _update_cache(_tracks, a)
857         return a
858
859 def top_artists(order='rating_desc', count=20):
860     """Returns: [Artist]"""
861     with _APILOCK:
862         q = SearchQuery('artist', order=order, count=count)
863         a = q.execute()
864         if not a:
865             raise JamendoAPIException(str(q))
866         _update_cache(_artists, a)
867         return a
868
869 def top_albums(order='rating_desc', count=20):
870     """Returns: [Album]"""
871     with _APILOCK:
872         q = SearchQuery('album', order=order, count=count)
873         a = q.execute()
874         if not a:
875             raise JamendoAPIException(str(q))
876         _update_cache(_albums, a)
877         return a
878
879 def top_tracks(order='rating_desc', count=20):
880     """Returns: [Track]"""
881     with _APILOCK:
882         q = SearchQuery('track', order=order, count=count)
883         a = q.execute()
884         if not a:
885             raise JamendoAPIException(str(q))
886         _update_cache(_tracks, a)
887         return a
888
889 def get_radio(radio_id):
890     """Returns: Radio"""
891     with _APILOCK:
892         q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
893         js = q.execute()
894         if not js:
895             raise JamendoAPIException(str(q))
896         if isinstance(js, list):
897             ks = js[0]
898         return Radio(radio_id, json=js)
899
900 def starred_radios():
901     """Returns: [Radio]"""
902     with _APILOCK:
903         q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
904         js = q.execute()
905         if not js:
906             raise JamendoAPIException(str(q))
907         return [Radio(int(radio['id']), json=radio) for radio in js]
908
909 def top_tags(count=50, order='rating_desc'):
910     """Returns: [Tag]"""
911     with _APILOCK:
912         q = CustomQuery(_GET2+"id+name/tag/json?n=%d&order=%s"%(count, order))
913         js = q.execute()
914         if not js:
915             raise JamendoAPIException(str(q))
916         return [Tag(int(tag['id']), json=tag) for tag in js]
917
918 def favorite_albums(user):
919     """Returns: [Album]"""
920     with _APILOCK:
921         q = SearchQuery('favorite_albums', user=user, count=20)
922         a = q.execute()
923         if not a:
924             raise JamendoAPIException(str(q))
925         _update_cache(_albums, a)
926         return a
927
928 ### Set loader functions for classes
929
930 def _artist_loader(self):
931     if self._needs_load():
932         artist = get_artist(self.ID)
933         artist.albums = get_albums(self.ID)
934         self._set_from(artist)
935 Artist.load = _artist_loader
936
937 def _album_loader(self):
938     if self._needs_load():
939         album = get_album(self.ID)
940         album.tracks = get_tracks(self.ID)
941         self._set_from(album)
942 Album.load = _album_loader
943
944 def _track_loader(self):
945     track = get_track(self.ID)
946     self._set_from(track)
947 Track.load = _track_loader
948
949 def _radio_loader(self):
950     radio = get_radio(self.ID)
951     self._set_from(radio)
952 Radio.load = _radio_loader