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