3 # This file is part of Jamaendo.
4 # Copyright (c) 2010, Kristoffer Gronlund
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.
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.
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
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'
37 log = logging.getLogger(__name__)
39 class StdoutLogger(object):
40 def info(self, s, *args):
42 def debug(self, s, *args):
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
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']
58 s = StringIO.StringIO()
59 c.setopt(pycurl.FOLLOWLOCATION, 1)
60 c.setopt(pycurl.URL, url)
61 c.setopt(pycurl.WRITEFUNCTION, s.write)
69 class LazyQuery(object):
70 def set_from_json(self, json):
71 for key, value in json.iteritems():
73 assert(self.ID == int(value))
75 if key.endswith('_id'):
77 setattr(self, key, value)
80 """Not automatic for now,
81 will have to do artist.load()
83 This is filled in further down
88 def _needs_load(self):
91 def _set_from(self, other):
94 def _needs_load_impl(self, *attrs):
96 if getattr(self, attr) is None:
100 def _set_from_impl(self, other, *attrs):
102 self._set_if(other, attr)
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))
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:
114 #traceback.print_exc()
115 return u"%s(?)"%(self.__class__.__name__)
117 class Artist(LazyQuery):
118 def __init__(self, ID, json=None):
122 self.albums = None # None means not downloaded
124 self.set_from_json(json)
126 def _needs_load(self):
127 return self._needs_load_impl('name', 'albums')
129 def _set_from(self, other):
130 return self._set_from_impl(other, 'name', 'image', 'albums')
133 return {'name':self.name, 'image':self.image}
135 class Album(LazyQuery):
136 def __init__(self, ID, json=None):
140 self.artist_name = None
141 self.artist_id = None
142 self.license_url = None
143 self.tracks = None # None means not downloaded
145 self.set_from_json(json)
147 def torrent_url(self):
148 return _TORRENTURL%(self.ID)
151 def _needs_load(self):
152 return self._needs_load_impl('name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
154 def _set_from(self, other):
155 return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
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}
163 class Track(LazyQuery):
164 def __init__(self, ID, json=None):
167 self.artist_id = None
168 self.artist_name = None
169 self.album_image = None
170 self.album_name = None
175 self.set_from_json(json)
178 return _MP3URL%(self.ID)
181 return _OGGURL%(self.ID)
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}
193 def _needs_load(self):
194 return self._needs_load_impl('name', 'artist_name', 'artist_id', 'album_name', 'album_id', 'numalbum', 'duration')
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')
199 class Radio(LazyQuery):
200 def __init__(self, ID, json=None):
206 self.set_from_json(json)
208 def _needs_load(self):
209 return self._needs_load_impl('name', 'idstr', 'image')
211 def _set_from(self, other):
212 return self._set_from_impl(other, 'name', 'idstr', 'image')
214 class Tag(LazyQuery):
215 def __init__(self, ID, json=None):
219 self.set_from_json(json)
221 def _needs_load(self):
222 return self._needs_load_impl('name')
224 def _set_from(self, other):
225 return self._set_from_impl(other, 'name')
227 _artists = {} # id -> Artist()
228 _albums = {} # id -> Album()
229 _tracks = {} # id -> Track()
230 _radios = {} # id -> Radio()
233 # cache sizes per session (TODO)
234 _CACHED_ARTISTS = 100
238 # cache sizes, persistant
239 _CACHED_COVERS = 2048
241 # TODO: cache queries?
244 rate_limit = 1.1 # seconds between queries
245 last_query = time.time() - 1.5
250 if now - cls.last_query < cls.rate_limit:
251 time.sleep(cls.rate_limit - (now - cls.last_query))
257 def _geturl(self, url):
261 ret = simplejson.loads(curlGET(url))
267 return "#%s" % (self.__class__.__name__)
272 class CoverFetcher(threading.Thread):
274 threading.Thread.__init__(self)
276 self.cond = threading.Condition()
279 def _retrieve(self, url, fname):
280 BROKEN = 'http://imgjam.com/radios/default/default.100.png'
283 f = open(fname, 'wb')
285 c.setopt(pycurl.FOLLOWLOCATION, 1)
286 c.setopt(pycurl.URL, str(url))
287 c.setopt(pycurl.WRITEFUNCTION, f.write)
295 log.debug("Coverfetch: %s -> %s", url, fname)
298 def _fetch_cover(self, albumid, size):
300 coverdir = _COVERDIR if _COVERDIR else '/tmp'
301 to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
302 if not os.path.isfile(to):
303 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
304 to = self._retrieve(url, to)
309 def _fetch_image(self, url):
311 h = hashlib.md5(url).hexdigest()
312 coverdir = _COVERDIR if _COVERDIR else '/tmp'
313 to = os.path.join(coverdir, h+'.jpg')
314 if not os.path.isfile(to):
315 to = self._retrieve(url, to)
320 def request_cover(self, albumid, size, cb):
322 self.work.insert(0, (albumid, size, cb))
326 def request_images(self, urls, cb):
327 """cb([(url, image)])"""
329 self.work = [('image', url, cb) for url in urls] + self.work
345 multi = len(work) > 1
347 if job[0] == 'image':
348 self.process_image(job[1], job[2])
350 self.process_cover(*job)
352 def process_cover(self, albumid, size, cb):
353 cover = self._fetch_cover(albumid, size)
355 cb(albumid, size, cover)
357 def process_image(self, url, cb):
358 image = self._fetch_image(url)
362 class CoverCache(object):
364 cache and fetch covers
365 TODO: background thread that
366 fetches and returns covers,
370 self._covers = {} # (albumid, size) -> file
372 self._fetcher = CoverFetcher()
373 self._fetcher.start()
374 if _COVERDIR and os.path.isdir(_COVERDIR):
377 def prime_cache(self):
379 covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
381 prev_covers = os.listdir(coverdir)
383 if len(prev_covers) > _CACHED_COVERS:
385 dropn = len(prev_covers) - _CACHED_COVERS
386 todrop = random.sample(prev_covers, dropn)
387 log.warning("Deleting from cache: %s", todrop)
389 m = covermatch.match(d)
392 os.unlink(os.path.join(coverdir, d))
394 log.exception('unlinking failed')
396 for fil in os.listdir(coverdir):
397 fl = os.path.join(coverdir, fil)
398 m = covermatch.match(fil)
399 if m and os.path.isfile(fl):
400 self._covers[(int(m.group(1)), int(m.group(2)))] = fl
402 def fetch_cover(self, albumid, size):
405 to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
406 if not os.path.isfile(to):
407 url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
408 urllib.urlretrieve(url, to)
409 self._covers[(albumid, size)] = to
413 def get_cover(self, albumid, size):
414 cover = self._covers.get((albumid, size), None)
416 cover = self.fetch_cover(albumid, size)
419 def get_async(self, albumid, size, cb):
420 cover = self._covers.get((albumid, size), None)
422 cb(albumid, size, cover)
424 def cb2(albumid, size, cover):
425 self._covers[(albumid, size)] = cover
426 cb(albumid, size, cover)
427 self._fetcher.request_cover(albumid, size, cb2)
429 def get_images_async(self, url_list, cb):
433 image = self._images.get(url, None)
435 found.append((url, image))
443 for url, image in results:
444 self._images[url] = image
446 self._fetcher.request_images(lookup, cb2)
448 _cover_cache = CoverCache()
450 def set_cache_dir(cachedir):
454 _COVERDIR = os.path.join(_CACHEDIR, 'covers')
457 os.makedirs(_CACHEDIR)
462 os.makedirs(_COVERDIR)
466 _cover_cache.prime_cache()
468 def get_album_cover(albumid, size=100):
469 return _cover_cache.get_cover(albumid, size)
471 def get_album_cover_async(cb, albumid, size=100):
472 _cover_cache.get_async(albumid, size, cb)
474 def get_images_async(cb, url_list):
475 _cover_cache.get_images_async(url_list, cb)
477 class CustomQuery(Query):
478 def __init__(self, url):
483 return self._geturl(self.url)
488 class GetQuery(Query):
491 'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
492 'params' : 'artist_id=%d',
493 'constructor' : Artist
496 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/artist/json/?',
497 'params' : 'artist_id=%s',
498 'constructor' : Album
501 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
502 'params' : 'album_id=%d',
503 'constructor' : Album
506 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
507 'params' : 'album_id=%s',
508 'constructor' : Album
511 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
512 'params' : 'artist_id=%d',
513 'constructor' : [Album]
516 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
518 'constructor' : Track
521 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
523 'constructor' : Track
526 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
527 'params' : 'order=numalbum_asc&album_id=%d',
528 'constructor' : [Track]
531 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
532 'params' : 'order=random_asc&radio_id=%d&n=16',
533 'constructor' : [Track]
535 'favorite_albums' : {
536 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
537 'params' : 'user_idstr=%s',
538 'constructor' : [Album]
541 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
542 'params' : 'tag_id=%d&n=50&order=rating_desc',
543 'constructor' : [Track]
547 def __init__(self, what, ID):
550 info = GetQuery.queries[what]
551 self.url = info['url']
552 self.params = info['params']
553 self.constructor = info['constructor']
555 def construct(self, data):
556 constructor = self.constructor
557 if isinstance(constructor, list):
558 constructor = constructor[0]
559 if isinstance(data, list):
560 return [constructor(int(x['id']), json=x) for x in data]
562 return constructor(int(data['id']), json=data)
565 js = self._geturl(self.url + self.params % (self.ID))
568 return self.construct(js)
571 return self.url + self.params % (self.ID)
573 class SearchQuery(GetQuery):
574 def __init__(self, what, query=None, order=None, user=None, count=20):
575 GetQuery.__init__(self, what, None)
584 params['searchquery'] = self.query
586 params['order'] = self.order
588 params['n'] = self.count
590 params['user_idstr'] = self.user
591 js = self._geturl(self.url + urllib.urlencode(params))
594 return self.construct(js)
597 params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
598 return self.url + urllib.urlencode(params)
600 class JamendoAPIException(Exception):
601 def __init__(self, url):
602 Exception.__init__(self, url)
604 def _update_cache(cache, new_items):
605 if not isinstance(new_items, list):
606 new_items = [new_items]
607 for item in new_items:
608 old = cache.get(item.ID)
612 cache[item.ID] = item
613 if isinstance(item, Artist) and item.albums:
614 for album in item.albums:
615 _update_cache(_albums, album)
616 elif isinstance(item, Album) and item.tracks:
617 for track in item.tracks:
618 _update_cache(_tracks, track)
619 # enforce cache limits here!
620 # also, TODO: save/load cache between sessions
621 # that will require storing a timestamp with
622 # each item, though..
624 # artists: 1 day - changes often
625 # albums: 2-5 days - changes less often (?)
626 # tracks: 1 week - changes rarely, queried often
628 def get_artist(artist_id):
629 """Returns: Artist"""
630 a = _artists.get(artist_id, None)
632 q = GetQuery('artist', artist_id)
635 raise JamendoAPIException(str(q))
636 _update_cache(_artists, a)
637 if isinstance(a, list):
641 def get_artists(artist_ids):
642 """Returns: [Artist]"""
643 assert(isinstance(artist_ids, list))
646 for artist_id in artist_ids:
647 a = _artists.get(artist_id, None)
649 lookup.append(artist_id)
653 q = GetQuery('artist_list', '+'.join(str(x) for x in lookup))
656 raise JamendoAPIException(str(q))
657 _update_cache(_artists, a)
659 return found + lookup
661 def get_album_list(album_ids):
662 """Returns: [Album]"""
663 assert(isinstance(album_ids, list))
666 for album_id in album_ids:
667 a = _albums.get(album_id, None)
669 lookup.append(album_id)
673 q = GetQuery('album_list', '+'.join(str(x) for x in lookup))
676 raise JamendoAPIException(str(q))
677 _update_cache(_albums, a)
679 return found + lookup
681 def get_albums(artist_id):
683 Parameter can either be an artist_id or a list of album ids.
685 if isinstance(artist_id, list):
686 return get_album_list(artist_id)
687 a = _artists.get(artist_id, None)
691 q = GetQuery('albums', artist_id)
694 raise JamendoAPIException(str(q))
695 _update_cache(_albums, a)
698 def get_album(album_id):
700 a = _albums.get(album_id, None)
702 q = GetQuery('album', album_id)
705 raise JamendoAPIException(str(q))
706 _update_cache(_albums, a)
707 if isinstance(a, list):
711 def get_track_list(track_ids):
712 """Returns: [Track]"""
713 assert(isinstance(track_ids, list))
716 for track_id in track_ids:
717 a = _tracks.get(track_id, None)
719 lookup.append(track_id)
723 q = GetQuery('track_list', '+'.join(str(x) for x in lookup))
726 raise JamendoAPIException(str(q))
727 _update_cache(_tracks, a)
729 return found + lookup
731 def get_tracks(album_id):
733 Parameter can either be an album_id or a list of track ids.
735 if isinstance(album_id, list):
736 return get_track_list(album_id)
737 a = _albums.get(album_id, None)
741 q = GetQuery('tracks', album_id)
744 raise JamendoAPIException(str(q))
745 _update_cache(_tracks, a)
748 def get_track(track_id):
750 a = _tracks.get(track_id, None)
752 q = GetQuery('track', track_id)
755 raise JamendoAPIException(str(q))
756 _update_cache(_tracks, a)
757 if isinstance(a, list):
761 def get_radio_tracks(radio_id):
762 """Returns: [Track]"""
763 q = GetQuery('radio', radio_id)
766 raise JamendoAPIException(str(q))
767 _update_cache(_tracks, a)
770 #http://api.jamendo.com/get2/id+name/track/plain/?tag_id=327&n=50&order=rating_desc
771 def get_tag_tracks(tag_id):
772 """Returns: [Track]"""
773 q = GetQuery('tag', tag_id)
776 raise JamendoAPIException(str(q))
777 _update_cache(_tracks, a)
780 def search_artists(query):
781 """Returns: [Artist]"""
782 q = SearchQuery('artist', query, 'searchweight_desc')
785 raise JamendoAPIException(str(q))
786 _update_cache(_artists, a)
789 def search_albums(query):
790 """Returns: [Album]"""
791 q = SearchQuery('album', query, 'searchweight_desc')
794 raise JamendoAPIException(str(q))
795 _update_cache(_albums, a)
798 def search_tracks(query):
799 """Returns: [Track]"""
800 q = SearchQuery('track', query=query, order='searchweight_desc')
803 raise JamendoAPIException(str(q))
804 _update_cache(_tracks, a)
807 def albums_of_the_week():
808 """Returns: [Album]"""
809 q = SearchQuery('album', order='ratingweek_desc')
812 raise JamendoAPIException(str(q))
813 _update_cache(_albums, a)
817 """Returns: [Track] (playlist)"""
818 q = SearchQuery('track', order='releasedate_desc')
821 raise JamendoAPIException(str(q))
822 _update_cache(_tracks, a)
825 def tracks_of_the_week():
826 """Returns: [Track] (playlist)"""
827 q = SearchQuery('track', order='ratingweek_desc')
830 raise JamendoAPIException(str(q))
831 _update_cache(_tracks, a)
834 def top_artists(order='rating_desc', count=20):
835 """Returns: [Artist]"""
836 q = SearchQuery('artist', order=order, count=count)
839 raise JamendoAPIException(str(q))
840 _update_cache(_artists, a)
843 def top_albums(order='rating_desc', count=20):
844 """Returns: [Album]"""
845 q = SearchQuery('album', order=order, count=count)
848 raise JamendoAPIException(str(q))
849 _update_cache(_albums, a)
852 def top_tracks(order='rating_desc', count=20):
853 """Returns: [Track]"""
854 q = SearchQuery('track', order=order, count=count)
857 raise JamendoAPIException(str(q))
858 _update_cache(_tracks, a)
861 def get_radio(radio_id):
863 q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
866 raise JamendoAPIException(str(q))
867 if isinstance(js, list):
869 return Radio(radio_id, json=js)
871 def starred_radios():
872 """Returns: [Radio]"""
873 q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
876 raise JamendoAPIException(str(q))
877 return [Radio(int(radio['id']), json=radio) for radio in js]
879 def top_tags(count=50, order='rating_desc'):
881 q = CustomQuery(_GET2+"id+name/tag/json?n=%d&order=%s"%(count, order))
884 raise JamendoAPIException(str(q))
885 return [Tag(int(tag['id']), json=tag) for tag in js]
887 def favorite_albums(user):
888 """Returns: [Album]"""
889 q = SearchQuery('favorite_albums', user=user, count=20)
892 raise JamendoAPIException(str(q))
893 _update_cache(_albums, a)
896 ### Set loader functions for classes
898 def _artist_loader(self):
899 if self._needs_load():
900 artist = get_artist(self.ID)
901 artist.albums = get_albums(self.ID)
902 self._set_from(artist)
903 Artist.load = _artist_loader
905 def _album_loader(self):
906 if self._needs_load():
907 album = get_album(self.ID)
908 album.tracks = get_tracks(self.ID)
909 self._set_from(album)
910 Album.load = _album_loader
912 def _track_loader(self):
913 track = get_track(self.ID)
914 self._set_from(track)
915 Track.load = _track_loader
917 def _radio_loader(self):
918 radio = get_radio(self.ID)
919 self._set_from(radio)
920 Radio.load = _radio_loader