tiny color change
[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 Query(object):
244     rate_limit = 1.1 # 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 = now
253
254     def __init__(self):
255         pass
256
257     def _geturl(self, url):
258         log.info("%s", url)
259         Query._ratelimit()
260         try:
261             ret = simplejson.loads(curlGET(url))
262         except Exception, e:
263             return None
264         return ret
265
266     def __str__(self):
267         return "#%s" % (self.__class__.__name__)
268
269     def execute(self):
270         raise NotImplemented
271
272 class CoverFetcher(threading.Thread):
273     def __init__(self):
274         threading.Thread.__init__(self)
275         self.setDaemon(True)
276         self.cond = threading.Condition()
277         self.work = []
278
279     def _retrieve(self, url, fname):
280         f = open(fname, 'wb')
281         c = pycurl.Curl()
282         c.setopt(pycurl.FOLLOWLOCATION, 1)
283         c.setopt(pycurl.URL, str(url))
284         c.setopt(pycurl.WRITEFUNCTION, f.write)
285         try:
286             c.perform()
287         except:
288             fname = None
289         finally:
290             c.close()
291             f.close()
292         log.debug("Coverfetch: %s -> %s", url, fname)
293         return fname
294
295     def _fetch_cover(self, albumid, size):
296         try:
297             coverdir = _COVERDIR if _COVERDIR else '/tmp'
298             to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
299             if not os.path.isfile(to):
300                 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
301                 to = self._retrieve(url, to)
302             return to
303         except Exception, e:
304             return None
305
306     def _fetch_image(self, url):
307         try:
308             h = hashlib.md5(url).hexdigest()
309             coverdir = _COVERDIR if _COVERDIR else '/tmp'
310             to = os.path.join(coverdir, h+'.jpg')
311             if not os.path.isfile(to):
312                 to = self._retrieve(url, to)
313             return to
314         except Exception, e:
315             return None
316
317     def request_cover(self, albumid, size, cb):
318         self.cond.acquire()
319         self.work.insert(0, (albumid, size, cb))
320         self.cond.notify()
321         self.cond.release()
322
323     def request_images(self, urls, cb):
324         """cb([(url, image)])"""
325         self.cond.acquire()
326         self.work = [('image', url, cb) for url in urls] + self.work
327         self.cond.notify()
328         self.cond.release()
329
330     def run(self):
331         while True:
332             work = []
333             self.cond.acquire()
334             while True:
335                 work = self.work
336                 if work:
337                     self.work = []
338                     break
339                 self.cond.wait()
340             self.cond.release()
341
342             multi = len(work) > 1
343             for job in work:
344                 if job[0] == 'image':
345                     self.process_image(job[1], job[2])
346                 else:
347                     self.process_cover(*job)
348
349     def process_cover(self, albumid, size, cb):
350         cover = self._fetch_cover(albumid, size)
351         if cover:
352             cb(albumid, size, cover)
353
354     def process_image(self, url, cb):
355         image = self._fetch_image(url)
356         if image:
357             cb([(url, image)])
358
359 class CoverCache(object):
360     """
361     cache and fetch covers
362     TODO: background thread that
363     fetches and returns covers,
364     asynchronously, LIFO
365     """
366     def __init__(self):
367         self._covers = {} # (albumid, size) -> file
368         self._images = {}
369         self._fetcher = CoverFetcher()
370         self._fetcher.start()
371         if _COVERDIR and os.path.isdir(_COVERDIR):
372             self.prime_cache()
373
374     def prime_cache(self):
375         coverdir = _COVERDIR
376         covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
377
378         prev_covers = os.listdir(coverdir)
379
380         if len(prev_covers) > _CACHED_COVERS:
381             import random
382             dropn = len(prev_covers) - _CACHED_COVERS
383             todrop = random.sample(prev_covers, dropn)
384             log.warning("Deleting from cache: %s", todrop)
385             for d in todrop:
386                 m = covermatch.match(d)
387                 if m:
388                     try:
389                         os.unlink(os.path.join(coverdir, d))
390                     except OSError, e:
391                         log.exception('unlinking failed')
392
393         for fil in os.listdir(coverdir):
394             fl = os.path.join(coverdir, fil)
395             m = covermatch.match(fil)
396             if m and os.path.isfile(fl):
397                 self._covers[(int(m.group(1)), int(m.group(2)))] = fl
398
399     def fetch_cover(self, albumid, size):
400         coverdir = _COVERDIR
401         if coverdir:
402             to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
403             if not os.path.isfile(to):
404                 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
405                 urllib.urlretrieve(url, to)
406                 self._covers[(albumid, size)] = to
407             return to
408         return None
409
410     def get_cover(self, albumid, size):
411         cover = self._covers.get((albumid, size), None)
412         if not cover:
413             cover = self.fetch_cover(albumid, size)
414         return cover
415
416     def get_async(self, albumid, size, cb):
417         cover = self._covers.get((albumid, size), None)
418         if cover:
419             cb(albumid, size, cover)
420         else:
421             def cb2(albumid, size, cover):
422                 self._covers[(albumid, size)] = cover
423                 cb(albumid, size, cover)
424             self._fetcher.request_cover(albumid, size, cb2)
425
426     def get_images_async(self, url_list, cb):
427         found = []
428         lookup = []
429         for url in url_list:
430             image = self._images.get(url, None)
431             if image:
432                 found.append((url, image))
433             else:
434                 lookup.append(url)
435         if found:
436             cb(found)
437
438         if lookup:
439             def cb2(results):
440                 for url, image in results:
441                     self._images[url] = image
442                 cb(results)
443             self._fetcher.request_images(lookup, cb2)
444
445 _cover_cache = CoverCache()
446
447 def set_cache_dir(cachedir):
448     global _CACHEDIR
449     global _COVERDIR
450     _CACHEDIR = cachedir
451     _COVERDIR = os.path.join(_CACHEDIR, 'covers')
452
453     try:
454         os.makedirs(_CACHEDIR)
455     except OSError:
456         pass
457
458     try:
459         os.makedirs(_COVERDIR)
460     except OSError:
461         pass
462
463     _cover_cache.prime_cache()
464
465 def get_album_cover(albumid, size=100):
466     return _cover_cache.get_cover(albumid, size)
467
468 def get_album_cover_async(cb, albumid, size=100):
469     _cover_cache.get_async(albumid, size, cb)
470
471 def get_images_async(cb, url_list):
472     _cover_cache.get_images_async(url_list, cb)
473
474 class CustomQuery(Query):
475     def __init__(self, url):
476         Query.__init__(self)
477         self.url = url
478
479     def execute(self):
480         return self._geturl(self.url)
481
482     def __str__(self):
483         return self.url
484
485 class GetQuery(Query):
486     queries = {
487         'artist' : {
488             'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
489             'params' : 'artist_id=%d',
490             'constructor' : Artist
491             },
492         'artist_list' : {
493             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/artist/json/?',
494             'params' : 'artist_id=%s',
495             'constructor' : Album
496             },
497         'album' : {
498             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
499             'params' : 'album_id=%d',
500             'constructor' : Album
501             },
502         'album_list' : {
503             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
504             'params' : 'album_id=%s',
505             'constructor' : Album
506             },
507         'albums' : {
508             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
509             'params' : 'artist_id=%d',
510             'constructor' : [Album]
511             },
512         'track' : {
513             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
514             'params' : 'id=%d',
515             'constructor' : Track
516             },
517         'track_list' : {
518             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
519             'params' : 'id=%s',
520             'constructor' : Track
521             },
522         'tracks' : {
523             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
524             'params' : 'order=numalbum_asc&album_id=%d',
525             'constructor' : [Track]
526             },
527         'radio' : {
528             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
529             'params' : 'order=random_asc&radio_id=%d&n=16',
530             'constructor' : [Track]
531             },
532         'favorite_albums' : {
533             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
534             'params' : 'user_idstr=%s',
535             'constructor' : [Album]
536             },
537         'tag' : {
538             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
539             'params' : 'tag_id=%d&n=50&order=rating_desc',
540             'constructor' : [Track]
541             },
542         }
543
544     def __init__(self, what, ID):
545         Query.__init__(self)
546         self.ID = ID
547         info = GetQuery.queries[what]
548         self.url = info['url']
549         self.params = info['params']
550         self.constructor = info['constructor']
551
552     def construct(self, data):
553         constructor = self.constructor
554         if isinstance(constructor, list):
555             constructor = constructor[0]
556         if isinstance(data, list):
557             return [constructor(int(x['id']), json=x) for x in data]
558         else:
559             return constructor(int(data['id']), json=data)
560
561     def execute(self):
562         js = self._geturl(self.url + self.params % (self.ID))
563         if not js:
564             return None
565         return self.construct(js)
566
567     def __str__(self):
568         return self.url + self.params % (self.ID)
569
570 class SearchQuery(GetQuery):
571     def __init__(self, what, query=None, order=None, user=None, count=20):
572         GetQuery.__init__(self, what, None)
573         self.query = query
574         self.order = order
575         self.count = count
576         self.user = user
577
578     def execute(self):
579         params = {}
580         if self.query:
581             params['searchquery'] = self.query
582         if self.order:
583             params['order'] = self.order
584         if self.count:
585             params['n'] = self.count
586         if self.user:
587             params['user_idstr'] = self.user
588         js = self._geturl(self.url +  urllib.urlencode(params))
589         if not js:
590             return None
591         return self.construct(js)
592
593     def __str__(self):
594         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
595         return self.url +  urllib.urlencode(params)
596
597 class JamendoAPIException(Exception):
598     def __init__(self, url):
599         Exception.__init__(self, url)
600
601 def _update_cache(cache, new_items):
602     if not isinstance(new_items, list):
603         new_items = [new_items]
604     for item in new_items:
605         old = cache.get(item.ID)
606         if old:
607             old._set_from(item)
608         else:
609             cache[item.ID] = item
610         if isinstance(item, Artist) and item.albums:
611             for album in item.albums:
612                 _update_cache(_albums, album)
613         elif isinstance(item, Album) and item.tracks:
614             for track in item.tracks:
615                 _update_cache(_tracks, track)
616     # enforce cache limits here!
617     # also, TODO: save/load cache between sessions
618     # that will require storing a timestamp with
619     # each item, though..
620     # perhaps,
621     # artists: 1 day - changes often
622     # albums: 2-5 days - changes less often (?)
623     # tracks: 1 week - changes rarely, queried often
624
625 def get_artist(artist_id):
626     """Returns: Artist"""
627     a = _artists.get(artist_id, None)
628     if not a:
629         q = GetQuery('artist', artist_id)
630         a = q.execute()
631         if not a:
632             raise JamendoAPIException(str(q))
633         _update_cache(_artists, a)
634         if isinstance(a, list):
635             a = a[0]
636     return a
637
638 def get_artists(artist_ids):
639     """Returns: [Artist]"""
640     assert(isinstance(artist_ids, list))
641     found = []
642     lookup = []
643     for artist_id in artist_ids:
644         a = _artists.get(artist_id, None)
645         if not a:
646             lookup.append(artist_id)
647         else:
648             found.append(a)
649     if lookup:
650         q = GetQuery('artist_list', '+'.join(str(x) for x in lookup))
651         a = q.execute()
652         if not a:
653             raise JamendoAPIException(str(q))
654         _update_cache(_artists, a)
655         lookup = a
656     return found + lookup
657
658 def get_album_list(album_ids):
659     """Returns: [Album]"""
660     assert(isinstance(album_ids, list))
661     found = []
662     lookup = []
663     for album_id in album_ids:
664         a = _albums.get(album_id, None)
665         if not a:
666             lookup.append(album_id)
667         else:
668             found.append(a)
669     if lookup:
670         q = GetQuery('album_list', '+'.join(str(x) for x in lookup))
671         a = q.execute()
672         if not a:
673             raise JamendoAPIException(str(q))
674         _update_cache(_albums, a)
675         lookup = a
676     return found + lookup
677
678 def get_albums(artist_id):
679     """Returns: [Album]
680     Parameter can either be an artist_id or a list of album ids.
681     """
682     if isinstance(artist_id, list):
683         return get_album_list(artist_id)
684     a = _artists.get(artist_id, None)
685     if a and a.albums:
686         return a.albums
687
688     q = GetQuery('albums', artist_id)
689     a = q.execute()
690     if not a:
691         raise JamendoAPIException(str(q))
692     _update_cache(_albums, a)
693     return a
694
695 def get_album(album_id):
696     """Returns: Album"""
697     a = _albums.get(album_id, None)
698     if not a:
699         q = GetQuery('album', album_id)
700         a = q.execute()
701         if not a:
702             raise JamendoAPIException(str(q))
703         _update_cache(_albums, a)
704         if isinstance(a, list):
705             a = a[0]
706     return a
707
708 def get_track_list(track_ids):
709     """Returns: [Track]"""
710     assert(isinstance(track_ids, list))
711     found = []
712     lookup = []
713     for track_id in track_ids:
714         a = _tracks.get(track_id, None)
715         if not a:
716             lookup.append(track_id)
717         else:
718             found.append(a)
719     if lookup:
720         q = GetQuery('track_list', '+'.join(str(x) for x in lookup))
721         a = q.execute()
722         if not a:
723             raise JamendoAPIException(str(q))
724         _update_cache(_tracks, a)
725         lookup = a
726     return found + lookup
727
728 def get_tracks(album_id):
729     """Returns: [Track]
730     Parameter can either be an album_id or a list of track ids.
731     """
732     if isinstance(album_id, list):
733         return get_track_list(album_id)
734     a = _albums.get(album_id, None)
735     if a and a.tracks:
736         return a.tracks
737
738     q = GetQuery('tracks', album_id)
739     a = q.execute()
740     if not a:
741         raise JamendoAPIException(str(q))
742     _update_cache(_tracks, a)
743     return a
744
745 def get_track(track_id):
746     """Returns: Track"""
747     a = _tracks.get(track_id, None)
748     if not a:
749         q = GetQuery('track', track_id)
750         a = q.execute()
751         if not a:
752             raise JamendoAPIException(str(q))
753         _update_cache(_tracks, a)
754         if isinstance(a, list):
755             a = a[0]
756     return a
757
758 def get_radio_tracks(radio_id):
759     """Returns: [Track]"""
760     q = GetQuery('radio', radio_id)
761     a = q.execute()
762     if not a:
763         raise JamendoAPIException(str(q))
764     _update_cache(_tracks, a)
765     return a
766
767 #http://api.jamendo.com/get2/id+name/track/plain/?tag_id=327&n=50&order=rating_desc
768 def get_tag_tracks(tag_id):
769     """Returns: [Track]"""
770     q = GetQuery('tag', tag_id)
771     a = q.execute()
772     if not a:
773         raise JamendoAPIException(str(q))
774     _update_cache(_tracks, a)
775     return a
776
777 def search_artists(query):
778     """Returns: [Artist]"""
779     q = SearchQuery('artist', query, 'searchweight_desc')
780     a = q.execute()
781     if not a:
782         raise JamendoAPIException(str(q))
783     _update_cache(_artists, a)
784     return a
785
786 def search_albums(query):
787     """Returns: [Album]"""
788     q = SearchQuery('album', query, 'searchweight_desc')
789     a = q.execute()
790     if not a:
791         raise JamendoAPIException(str(q))
792     _update_cache(_albums, a)
793     return a
794
795 def search_tracks(query):
796     """Returns: [Track]"""
797     q = SearchQuery('track', query=query, order='searchweight_desc')
798     a = q.execute()
799     if not a:
800         raise JamendoAPIException(str(q))
801     _update_cache(_tracks, a)
802     return a
803
804 def albums_of_the_week():
805     """Returns: [Album]"""
806     q = SearchQuery('album', order='ratingweek_desc')
807     a = q.execute()
808     if not a:
809         raise JamendoAPIException(str(q))
810     _update_cache(_albums, a)
811     return a
812
813 def new_releases():
814     """Returns: [Track] (playlist)"""
815     q = SearchQuery('track', order='releasedate_desc')
816     a = q.execute()
817     if not a:
818         raise JamendoAPIException(str(q))
819     _update_cache(_tracks, a)
820     return a
821
822 def tracks_of_the_week():
823     """Returns: [Track] (playlist)"""
824     q = SearchQuery('track', order='ratingweek_desc')
825     a = q.execute()
826     if not a:
827         raise JamendoAPIException(str(q))
828     _update_cache(_tracks, a)
829     return a
830
831 def top_artists(order='rating_desc', count=20):
832     """Returns: [Artist]"""
833     q = SearchQuery('artist', order=order, count=count)
834     a = q.execute()
835     if not a:
836         raise JamendoAPIException(str(q))
837     _update_cache(_artists, a)
838     return a
839
840 def top_albums(order='rating_desc', count=20):
841     """Returns: [Album]"""
842     q = SearchQuery('album', order=order, count=count)
843     a = q.execute()
844     if not a:
845         raise JamendoAPIException(str(q))
846     _update_cache(_albums, a)
847     return a
848
849 def top_tracks(order='rating_desc', count=20):
850     """Returns: [Track]"""
851     q = SearchQuery('track', order=order, count=count)
852     a = q.execute()
853     if not a:
854         raise JamendoAPIException(str(q))
855     _update_cache(_tracks, a)
856     return a
857
858 def get_radio(radio_id):
859     """Returns: Radio"""
860     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
861     js = q.execute()
862     if not js:
863         raise JamendoAPIException(str(q))
864     if isinstance(js, list):
865         ks = js[0]
866     return Radio(radio_id, json=js)
867
868 def starred_radios():
869     """Returns: [Radio]"""
870     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
871     js = q.execute()
872     if not js:
873         raise JamendoAPIException(str(q))
874     return [Radio(int(radio['id']), json=radio) for radio in js]
875
876 def top_tags(count=50, order='rating_desc'):
877     """Returns: [Tag]"""
878     q = CustomQuery(_GET2+"id+name/tag/json?n=%d&order=%s"%(count, order))
879     js = q.execute()
880     if not js:
881         raise JamendoAPIException(str(q))
882     return [Tag(int(tag['id']), json=tag) for tag in js]
883
884 def favorite_albums(user):
885     """Returns: [Album]"""
886     q = SearchQuery('favorite_albums', user=user, count=20)
887     a = q.execute()
888     if not a:
889         raise JamendoAPIException(str(q))
890     _update_cache(_albums, a)
891     return a
892
893 ### Set loader functions for classes
894
895 def _artist_loader(self):
896     if self._needs_load():
897         artist = get_artist(self.ID)
898         artist.albums = get_albums(self.ID)
899         self._set_from(artist)
900 Artist.load = _artist_loader
901
902 def _album_loader(self):
903     if self._needs_load():
904         album = get_album(self.ID)
905         album.tracks = get_tracks(self.ID)
906         self._set_from(album)
907 Album.load = _album_loader
908
909 def _track_loader(self):
910     track = get_track(self.ID)
911     self._set_from(track)
912 Track.load = _track_loader
913
914 def _radio_loader(self):
915     radio = get_radio(self.ID)
916     self._set_from(radio)
917 Radio.load = _radio_loader