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