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 f = open(fname, 'wb')
282 c.setopt(pycurl.FOLLOWLOCATION, 1)
283 c.setopt(pycurl.URL, str(url))
284 c.setopt(pycurl.WRITEFUNCTION, f.write)
292 log.debug("Coverfetch: %s -> %s", url, fname)
295 def _fetch_cover(self, albumid, size):
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)
306 def _fetch_image(self, url):
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)
317 def request_cover(self, albumid, size, cb):
319 self.work.insert(0, (albumid, size, cb))
323 def request_images(self, urls, cb):
324 """cb([(url, image)])"""
326 self.work = [('image', url, cb) for url in urls] + self.work
342 multi = len(work) > 1
344 if job[0] == 'image':
345 self.process_image(job[1], job[2])
347 self.process_cover(*job)
349 def process_cover(self, albumid, size, cb):
350 cover = self._fetch_cover(albumid, size)
352 cb(albumid, size, cover)
354 def process_image(self, url, cb):
355 image = self._fetch_image(url)
359 class CoverCache(object):
361 cache and fetch covers
362 TODO: background thread that
363 fetches and returns covers,
367 self._covers = {} # (albumid, size) -> file
369 self._fetcher = CoverFetcher()
370 self._fetcher.start()
371 if _COVERDIR and os.path.isdir(_COVERDIR):
374 def prime_cache(self):
376 covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
378 prev_covers = os.listdir(coverdir)
380 if len(prev_covers) > _CACHED_COVERS:
382 dropn = len(prev_covers) - _CACHED_COVERS
383 todrop = random.sample(prev_covers, dropn)
384 log.warning("Deleting from cache: %s", todrop)
386 m = covermatch.match(d)
389 os.unlink(os.path.join(coverdir, d))
391 log.exception('unlinking failed')
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
399 def fetch_cover(self, albumid, size):
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
410 def get_cover(self, albumid, size):
411 cover = self._covers.get((albumid, size), None)
413 cover = self.fetch_cover(albumid, size)
416 def get_async(self, albumid, size, cb):
417 cover = self._covers.get((albumid, size), None)
419 cb(albumid, size, cover)
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)
426 def get_images_async(self, url_list, cb):
430 image = self._images.get(url, None)
432 found.append((url, image))
440 for url, image in results:
441 self._images[url] = image
443 self._fetcher.request_images(lookup, cb2)
445 _cover_cache = CoverCache()
447 def set_cache_dir(cachedir):
451 _COVERDIR = os.path.join(_CACHEDIR, 'covers')
454 os.makedirs(_CACHEDIR)
459 os.makedirs(_COVERDIR)
463 _cover_cache.prime_cache()
465 def get_album_cover(albumid, size=100):
466 return _cover_cache.get_cover(albumid, size)
468 def get_album_cover_async(cb, albumid, size=100):
469 _cover_cache.get_async(albumid, size, cb)
471 def get_images_async(cb, url_list):
472 _cover_cache.get_images_async(url_list, cb)
474 class CustomQuery(Query):
475 def __init__(self, url):
480 return self._geturl(self.url)
485 class GetQuery(Query):
488 'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
489 'params' : 'artist_id=%d',
490 'constructor' : Artist
493 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/artist/json/?',
494 'params' : 'artist_id=%s',
495 'constructor' : Album
498 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
499 'params' : 'album_id=%d',
500 'constructor' : Album
503 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
504 'params' : 'album_id=%s',
505 'constructor' : Album
508 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
509 'params' : 'artist_id=%d',
510 'constructor' : [Album]
513 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
515 'constructor' : Track
518 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
520 'constructor' : Track
523 'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
524 'params' : 'order=numalbum_asc&album_id=%d',
525 'constructor' : [Track]
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]
532 'favorite_albums' : {
533 'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
534 'params' : 'user_idstr=%s',
535 'constructor' : [Album]
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]
544 def __init__(self, what, ID):
547 info = GetQuery.queries[what]
548 self.url = info['url']
549 self.params = info['params']
550 self.constructor = info['constructor']
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]
559 return constructor(int(data['id']), json=data)
562 js = self._geturl(self.url + self.params % (self.ID))
565 return self.construct(js)
568 return self.url + self.params % (self.ID)
570 class SearchQuery(GetQuery):
571 def __init__(self, what, query=None, order=None, user=None, count=20):
572 GetQuery.__init__(self, what, None)
581 params['searchquery'] = self.query
583 params['order'] = self.order
585 params['n'] = self.count
587 params['user_idstr'] = self.user
588 js = self._geturl(self.url + urllib.urlencode(params))
591 return self.construct(js)
594 params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
595 return self.url + urllib.urlencode(params)
597 class JamendoAPIException(Exception):
598 def __init__(self, url):
599 Exception.__init__(self, url)
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)
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..
621 # artists: 1 day - changes often
622 # albums: 2-5 days - changes less often (?)
623 # tracks: 1 week - changes rarely, queried often
625 def get_artist(artist_id):
626 """Returns: Artist"""
627 a = _artists.get(artist_id, None)
629 q = GetQuery('artist', artist_id)
632 raise JamendoAPIException(str(q))
633 _update_cache(_artists, a)
634 if isinstance(a, list):
638 def get_artists(artist_ids):
639 """Returns: [Artist]"""
640 assert(isinstance(artist_ids, list))
643 for artist_id in artist_ids:
644 a = _artists.get(artist_id, None)
646 lookup.append(artist_id)
650 q = GetQuery('artist_list', '+'.join(str(x) for x in lookup))
653 raise JamendoAPIException(str(q))
654 _update_cache(_artists, a)
656 return found + lookup
658 def get_album_list(album_ids):
659 """Returns: [Album]"""
660 assert(isinstance(album_ids, list))
663 for album_id in album_ids:
664 a = _albums.get(album_id, None)
666 lookup.append(album_id)
670 q = GetQuery('album_list', '+'.join(str(x) for x in lookup))
673 raise JamendoAPIException(str(q))
674 _update_cache(_albums, a)
676 return found + lookup
678 def get_albums(artist_id):
680 Parameter can either be an artist_id or a list of album ids.
682 if isinstance(artist_id, list):
683 return get_album_list(artist_id)
684 a = _artists.get(artist_id, None)
688 q = GetQuery('albums', artist_id)
691 raise JamendoAPIException(str(q))
692 _update_cache(_albums, a)
695 def get_album(album_id):
697 a = _albums.get(album_id, None)
699 q = GetQuery('album', album_id)
702 raise JamendoAPIException(str(q))
703 _update_cache(_albums, a)
704 if isinstance(a, list):
708 def get_track_list(track_ids):
709 """Returns: [Track]"""
710 assert(isinstance(track_ids, list))
713 for track_id in track_ids:
714 a = _tracks.get(track_id, None)
716 lookup.append(track_id)
720 q = GetQuery('track_list', '+'.join(str(x) for x in lookup))
723 raise JamendoAPIException(str(q))
724 _update_cache(_tracks, a)
726 return found + lookup
728 def get_tracks(album_id):
730 Parameter can either be an album_id or a list of track ids.
732 if isinstance(album_id, list):
733 return get_track_list(album_id)
734 a = _albums.get(album_id, None)
738 q = GetQuery('tracks', album_id)
741 raise JamendoAPIException(str(q))
742 _update_cache(_tracks, a)
745 def get_track(track_id):
747 a = _tracks.get(track_id, None)
749 q = GetQuery('track', track_id)
752 raise JamendoAPIException(str(q))
753 _update_cache(_tracks, a)
754 if isinstance(a, list):
758 def get_radio_tracks(radio_id):
759 """Returns: [Track]"""
760 q = GetQuery('radio', radio_id)
763 raise JamendoAPIException(str(q))
764 _update_cache(_tracks, a)
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)
773 raise JamendoAPIException(str(q))
774 _update_cache(_tracks, a)
777 def search_artists(query):
778 """Returns: [Artist]"""
779 q = SearchQuery('artist', query, 'searchweight_desc')
782 raise JamendoAPIException(str(q))
783 _update_cache(_artists, a)
786 def search_albums(query):
787 """Returns: [Album]"""
788 q = SearchQuery('album', query, 'searchweight_desc')
791 raise JamendoAPIException(str(q))
792 _update_cache(_albums, a)
795 def search_tracks(query):
796 """Returns: [Track]"""
797 q = SearchQuery('track', query=query, order='searchweight_desc')
800 raise JamendoAPIException(str(q))
801 _update_cache(_tracks, a)
804 def albums_of_the_week():
805 """Returns: [Album]"""
806 q = SearchQuery('album', order='ratingweek_desc')
809 raise JamendoAPIException(str(q))
810 _update_cache(_albums, a)
814 """Returns: [Track] (playlist)"""
815 q = SearchQuery('track', order='releasedate_desc')
818 raise JamendoAPIException(str(q))
819 _update_cache(_tracks, a)
822 def tracks_of_the_week():
823 """Returns: [Track] (playlist)"""
824 q = SearchQuery('track', order='ratingweek_desc')
827 raise JamendoAPIException(str(q))
828 _update_cache(_tracks, a)
831 def top_artists(order='rating_desc', count=20):
832 """Returns: [Artist]"""
833 q = SearchQuery('artist', order=order, count=count)
836 raise JamendoAPIException(str(q))
837 _update_cache(_artists, a)
840 def top_albums(order='rating_desc', count=20):
841 """Returns: [Album]"""
842 q = SearchQuery('album', order=order, count=count)
845 raise JamendoAPIException(str(q))
846 _update_cache(_albums, a)
849 def top_tracks(order='rating_desc', count=20):
850 """Returns: [Track]"""
851 q = SearchQuery('track', order=order, count=count)
854 raise JamendoAPIException(str(q))
855 _update_cache(_tracks, a)
858 def get_radio(radio_id):
860 q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
863 raise JamendoAPIException(str(q))
864 if isinstance(js, list):
866 return Radio(radio_id, json=js)
868 def starred_radios():
869 """Returns: [Radio]"""
870 q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
873 raise JamendoAPIException(str(q))
874 return [Radio(int(radio['id']), json=radio) for radio in js]
876 def top_tags(count=50, order='rating_desc'):
878 q = CustomQuery(_GET2+"id+name/tag/json?n=%d&order=%s"%(count, order))
881 raise JamendoAPIException(str(q))
882 return [Tag(int(tag['id']), json=tag) for tag in js]
884 def favorite_albums(user):
885 """Returns: [Album]"""
886 q = SearchQuery('favorite_albums', user=user, count=20)
889 raise JamendoAPIException(str(q))
890 _update_cache(_albums, a)
893 ### Set loader functions for classes
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
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
909 def _track_loader(self):
910 track = get_track(self.ID)
911 self._set_from(track)
912 Track.load = _track_loader
914 def _radio_loader(self):
915 radio = get_radio(self.ID)
916 self._set_from(radio)
917 Radio.load = _radio_loader