Download links
[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 #     * Redistributions in binary form must reproduce the above copyright
12 #       notice, this list of conditions and the following disclaimer in the
13 #       documentation and/or other materials provided with the distribution.
14 #     * Neither the name of Jamaendo nor the
15 #       names of its contributors may be used to endorse or promote products
16 #       derived from this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
22 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 # An improved, structured jamendo API wrapper for the N900 with cacheing
30 # Image / cover downloads.. and more?
31 import urllib, threading, os, gzip, time, simplejson, re
32
33 _CACHEDIR = None
34 _COVERDIR = None
35 _GET2 = '''http://api.jamendo.com/get2/'''
36 _MP3URL = _GET2+'stream/track/redirect/?id=%d&streamencoding=mp31'
37 _OGGURL = _GET2+'stream/track/redirect/?id=%d&streamencoding=ogg2'
38 _TORRENTURL = _GET2+'bittorrent/file/redirect/?album_id=%d&type=archive&class=mp32'
39
40 def set_cache_dir(cachedir):
41     global _CACHEDIR
42     global _COVERDIR
43     _CACHEDIR = cachedir
44     _COVERDIR = os.path.join(_CACHEDIR, 'covers')
45
46     try:
47         os.makedirs(_CACHEDIR)
48     except OSError:
49         pass
50
51     try:
52         os.makedirs(_COVERDIR)
53     except OSError:
54         pass
55
56 # These classes can be partially constructed,
57 # and if asked for a property they don't know,
58 # makes a query internally to get the full story
59
60 _ARTIST_FIELDS = ['id', 'name', 'image']
61 _ALBUM_FIELDS = ['id', 'name', 'image', 'artist_name', 'artist_id', 'license_url']
62 _TRACK_FIELDS = ['id', 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration']
63 _RADIO_FIELDS = ['id', 'name', 'idstr', 'image']
64
65 class LazyQuery(object):
66     def set_from_json(self, json):
67         for key, value in json.iteritems():
68             if key == 'id':
69                 assert(self.ID == int(value))
70             else:
71                 if key.endswith('_id'):
72                     value = int(value)
73                 setattr(self, key, value)
74
75     def load(self):
76         """Not automatic for now,
77         will have to do artist.load()
78
79         This is filled in further down
80         in the file
81         """
82         raise NotImplemented
83
84     def _needs_load(self):
85         return True
86
87     def _set_from(self, other):
88         raise NotImplemented
89
90     def _needs_load_impl(self, *attrs):
91         for attr in attrs:
92             if getattr(self, attr) is None:
93                 return True
94         return False
95
96     def _set_from_impl(self, other, *attrs):
97         for attr in attrs:
98             self._set_if(other, attr)
99
100     def _set_if(self, other, attrname):
101         if getattr(self, attrname) is None and getattr(other, attrname) is not None:
102             setattr(self, attrname, getattr(other, attrname))
103
104     def __repr__(self):
105         try:
106             return u"%s(%s)"%(self.__class__.__name__,
107                               u", ".join(repr(v) for k,v in self.__dict__.iteritems() if not k.startswith('_')))
108         except UnicodeEncodeError:
109             import traceback
110             traceback.print_exc()
111             return u"%s(?)"%(self.__class__.__name__)
112
113 class Artist(LazyQuery):
114     def __init__(self, ID, json=None):
115         self.ID = int(ID)
116         self.name = None
117         self.image = None
118         self.albums = None # None means not downloaded
119         if json:
120             self.set_from_json(json)
121
122     def _needs_load(self):
123         return self._needs_load_impl('name', 'albums')
124
125     def _set_from(self, other):
126         return self._set_from_impl(other, 'name', 'image', 'albums')
127
128 class Album(LazyQuery):
129     def __init__(self, ID, json=None):
130         self.ID = int(ID)
131         self.name = None
132         self.image = None
133         self.artist_name = None
134         self.artist_id = None
135         self.license_url = None
136         self.tracks = None # None means not downloaded
137         if json:
138             self.set_from_json(json)
139
140     def torrent_url(self):
141         return _TORRENTURL%(self.ID)
142
143
144     def _needs_load(self):
145         return self._needs_load_impl('name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
146
147     def _set_from(self, other):
148         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'artist_id', 'license_url', 'tracks')
149
150 class Track(LazyQuery):
151     def __init__(self, ID, json=None):
152         self.ID = int(ID)
153         self.name = None
154         self.image = None
155         self.artist_name = None
156         self.album_name = None
157         self.album_id = None
158         self.numalbum = None
159         self.duration = None
160         if json:
161             self.set_from_json(json)
162
163     def mp3_url(self):
164        return _MP3URL%(self.ID)
165
166     def ogg_url(self):
167        return _OGGURL%(self.ID)
168
169     def _needs_load(self):
170         return self._needs_load_impl('name', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
171
172     def _set_from(self, other):
173         return self._set_from_impl(other, 'name', 'image', 'artist_name', 'album_name', 'album_id', 'numalbum', 'duration')
174
175 class Radio(LazyQuery):
176     def __init__(self, ID, json=None):
177         self.ID = int(ID)
178         self.name = None
179         self.idstr = None
180         self.image = None
181         if json:
182             self.set_from_json(json)
183
184     def _needs_load(self):
185         return self._needs_load_impl('name', 'idstr', 'image')
186
187     def _set_from(self, other):
188         return self._set_from_impl(other, 'name', 'idstr', 'image')
189
190
191 _artists = {} # id -> Artist()
192 _albums = {} # id -> Album()
193 _tracks = {} # id -> Track()
194 _radios = {} # id -> Radio()
195
196
197 # cache sizes per session (TODO)
198 _CACHED_ARTISTS = 100
199 _CACHED_ALBUMS = 200
200 _CACHED_TRACKS = 500
201 _CACHED_RADIOS = 10
202
203 # TODO: cache queries?
204
205 class Query(object):
206     rate_limit = 1.1 # seconds between queries
207     last_query = time.time() - 1.5
208
209     @classmethod
210     def _ratelimit(cls):
211         now = time.time()
212         if now - cls.last_query < cls.rate_limit:
213             time.sleep(cls.rate_limit - (now - cls.last_query))
214         cls.last_query = now
215
216     def __init__(self):
217         pass
218
219     def _geturl(self, url):
220         print "*** %s" % (url)
221         Query._ratelimit()
222         f = urllib.urlopen(url)
223         ret = simplejson.load(f)
224         f.close()
225         return ret
226
227     def __str__(self):
228         return "#%s" % (self.__class__.__name__)
229
230     def execute(self):
231         raise NotImplemented
232
233 import threading
234
235 class CoverFetcher(threading.Thread):
236     def __init__(self):
237         threading.Thread.__init__(self)
238         self.setDaemon(True)
239         self.cond = threading.Condition()
240         self.work = []
241
242     def _fetch_cover(self, albumid, size):
243         coverdir = _COVERDIR if _COVERDIR else '/tmp'
244         to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
245         if not os.path.isfile(to):
246             url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
247             urllib.urlretrieve(url, to)
248         return to
249
250     def request_cover(self, albumid, size, cb):
251         self.cond.acquire()
252         self.work.insert(0, (albumid, size, cb))
253         self.cond.notify()
254         self.cond.release()
255
256     def run(self):
257         while True:
258             work = []
259             self.cond.acquire()
260             while True:
261                 work = self.work
262                 if work:
263                     self.work = []
264                     break
265                 self.cond.wait()
266             self.cond.release()
267
268             multi = len(work) > 1
269             for albumid, size, cb in work:
270                 cover = self._fetch_cover(albumid, size)
271                 cb(albumid, size, cover)
272                 if multi:
273                     time.sleep(1.0)
274
275 class CoverCache(object):
276     """
277     cache and fetch covers
278     TODO: background thread that
279     fetches and returns covers,
280     asynchronously, LIFO
281     """
282     def __init__(self):
283         self._covers = {} # (albumid, size) -> file
284         coverdir = _COVERDIR if _COVERDIR else '/tmp'
285         if os.path.isdir(coverdir):
286             covermatch = re.compile(r'(\d+)\-(\d+)\.jpg')
287             for fil in os.listdir(coverdir):
288                 fl = os.path.join(coverdir, fil)
289                 m = covermatch.match(fil)
290                 if m and os.path.isfile(fl):
291                     self._covers[(int(m.group(1)), int(m.group(2)))] = fl
292         self._fetcher = CoverFetcher()
293         self._fetcher.start()
294
295     def fetch_cover(self, albumid, size):
296         coverdir = _COVERDIR if _COVERDIR else '/tmp'
297         to = os.path.join(coverdir, '%d-%d.jpg'%(albumid, size))
298         if not os.path.isfile(to):
299             url = _GET2+'image/album/redirect/?id=%d&imagesize=%d'%(albumid, size)
300             urllib.urlretrieve(url, to)
301             self._covers[(albumid, size)] = to
302         return to
303
304     def get_cover(self, albumid, size):
305         cover = self._covers.get((albumid, size), None)
306         if not cover:
307             cover = self.fetch_cover(albumid, size)
308         return cover
309
310     def get_async(self, albumid, size, cb):
311         cover = self._covers.get((albumid, size), None)
312         if cover:
313             cb(albumid, size, cover)
314         else:
315             self._fetcher.request_cover(albumid, size, cb)
316
317 _cover_cache = CoverCache()
318
319 def get_album_cover(albumid, size=100):
320     return _cover_cache.get_cover(albumid, size)
321
322 def get_album_cover_async(cb, albumid, size=100):
323     _cover_cache.get_async(albumid, size, cb)
324
325 class CustomQuery(Query):
326     def __init__(self, url):
327         Query.__init__(self)
328         self.url = url
329
330     def execute(self):
331         return self._geturl(self.url)
332
333     def __str__(self):
334         return self.url
335
336 class GetQuery(Query):
337     queries = {
338         'artist' : {
339             'url' : _GET2+'+'.join(_ARTIST_FIELDS)+'/artist/json/?',
340             'params' : 'artist_id=%d',
341             'constructor' : Artist
342             },
343         'album' : {
344             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
345             'params' : 'album_id=%d',
346             'constructor' : Album
347             },
348         'albums' : {
349             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/?',
350             'params' : 'artist_id=%d',
351             'constructor' : [Album]
352             },
353         'track' : {
354             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
355             'params' : 'id=%d',
356             'constructor' : Track
357             },
358         'tracks' : {
359             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/track_album+album_artist?',
360             'params' : 'order=numalbum_asc&album_id=%d',
361             'constructor' : [Track]
362             },
363         'radio' : {
364             'url' : _GET2+'+'.join(_TRACK_FIELDS)+'/track/json/radio_track_inradioplaylist+track_album+album_artist/?',
365             'params' : 'order=random_asc&radio_id=%d',
366             'constructor' : [Track]
367             },
368         'favorite_albums' : {
369             'url' : _GET2+'+'.join(_ALBUM_FIELDS)+'/album/json/album_user_starred/?',
370             'params' : 'user_idstr=%s',
371             'constructor' : [Album]
372             },
373     #http://api.jamendo.com/get2/id+name+url+image+artist_name/album/jsonpretty/album_user_starred/?user_idstr=sylvinus&n=all
374     #q = SearchQuery('album', user_idstr=user)
375
376         }
377 #http://api.jamendo.com/get2/id+name+image+artist_name+album_name+album_id+numalbum+duration/track/json/radio_track_inradioplaylist+track_album+album_artist/?order=numradio_asc&radio_id=283
378
379     def __init__(self, what, ID):
380         Query.__init__(self)
381         self.ID = ID
382         info = GetQuery.queries[what]
383         self.url = info['url']
384         self.params = info['params']
385         self.constructor = info['constructor']
386
387     def construct(self, data):
388         constructor = self.constructor
389         if isinstance(constructor, list):
390             constructor = constructor[0]
391         if isinstance(data, list):
392             return [constructor(int(x['id']), json=x) for x in data]
393         else:
394             return constructor(int(data['id']), json=data)
395
396     def execute(self):
397         js = self._geturl(self.url + self.params % (self.ID))
398         if not js:
399             return None
400         return self.construct(js)
401
402     def __str__(self):
403         return self.url + self.params % (self.ID)
404
405 class SearchQuery(GetQuery):
406     def __init__(self, what, query=None, order=None, user=None, count=10):
407         GetQuery.__init__(self, what, None)
408         self.query = query
409         self.order = order
410         self.count = count
411         self.user = user
412
413     def execute(self):
414         params = {}
415         if self.query:
416             params['searchquery'] = self.query
417         if self.order:
418             params['order'] = self.order
419         if self.count:
420             params['n'] = self.count
421         if self.user:
422             params['user_idstr'] = self.user
423         js = self._geturl(self.url +  urllib.urlencode(params))
424         if not js:
425             return None
426         return self.construct(js)
427
428     def __str__(self):
429         params = {'searchquery':self.query, 'order':self.order, 'n':self.count}
430         return self.url +  urllib.urlencode(params)
431
432 class JamendoAPIException(Exception):
433     def __init__(self, url):
434         Exception.__init__(self, url)
435
436 def _update_cache(cache, new_items):
437     if not isinstance(new_items, list):
438         new_items = [new_items]
439     for item in new_items:
440         old = cache.get(item.ID)
441         if old:
442             old._set_from(item)
443         else:
444             cache[item.ID] = item
445
446 def get_artist(artist_id):
447     """Returns: Artist"""
448     a = _artists.get(artist_id, None)
449     if not a:
450         q = GetQuery('artist', artist_id)
451         a = q.execute()
452         if not a:
453             raise JamendoAPIException(str(q))
454         _update_cache(_artists, a)
455         if isinstance(a, list):
456             a = a[0]
457     return a
458
459 def get_albums(artist_id):
460     """Returns: [Album]"""
461     q = GetQuery('albums', artist_id)
462     a = q.execute()
463     if not a:
464         raise JamendoAPIException(str(q))
465     _update_cache(_artists, a)
466     return a
467
468 def get_album(album_id):
469     """Returns: Album"""
470     a = _albums.get(album_id, None)
471     if not a:
472         q = GetQuery('album', album_id)
473         a = q.execute()
474         if not a:
475             raise JamendoAPIException(str(q))
476         _update_cache(_albums, a)
477         if isinstance(a, list):
478             a = a[0]
479     return a
480
481 def get_tracks(album_id):
482     """Returns: [Track]"""
483     q = GetQuery('tracks', album_id)
484     a = q.execute()
485     if not a:
486         raise JamendoAPIException(str(q))
487     _update_cache(_tracks, a)
488     return a
489
490 def get_track(track_id):
491     """Returns: Track"""
492     a = _tracks.get(track_id, None)
493     if not a:
494         q = GetQuery('track', track_id)
495         a = q.execute()
496         if not a:
497             raise JamendoAPIException(str(q))
498         _update_cache(_tracks, a)
499         if isinstance(a, list):
500             a = a[0]
501     return a
502
503 def get_radio_tracks(radio_id):
504     """Returns: [Track]"""
505     q = GetQuery('radio', radio_id)
506     a = q.execute()
507     if not a:
508         raise JamendoAPIException(str(q))
509     _update_cache(_tracks, a)
510     return a
511
512 def search_artists(query):
513     """Returns: [Artist]"""
514     q = SearchQuery('artist', query, 'searchweight_desc')
515     a = q.execute()
516     if not a:
517         raise JamendoAPIException(str(q))
518     _update_cache(_artists, a)
519     return a
520
521 def search_albums(query):
522     """Returns: [Album]"""
523     q = SearchQuery('album', query, 'searchweight_desc')
524     a = q.execute()
525     if not a:
526         raise JamendoAPIException(str(q))
527     _update_cache(_albums, a)
528     return a
529
530 def search_tracks(query):
531     """Returns: [Track]"""
532     q = SearchQuery('track', query=query, order='searchweight_desc')
533     a = q.execute()
534     if not a:
535         raise JamendoAPIException(str(q))
536     _update_cache(_tracks, a)
537     return a
538
539 def albums_of_the_week():
540     """Returns: [Album]"""
541     q = SearchQuery('album', order='ratingweek_desc')
542     a = q.execute()
543     if not a:
544         raise JamendoAPIException(str(q))
545     _update_cache(_albums, a)
546     return a
547
548 def new_releases():
549     """Returns: [Track] (playlist)"""
550     q = SearchQuery('track', order='releasedate_desc')
551     a = q.execute()
552     if not a:
553         raise JamendoAPIException(str(q))
554     _update_cache(_tracks, a)
555     return a
556
557 def tracks_of_the_week():
558     """Returns: [Track] (playlist)"""
559     q = SearchQuery('track', order='ratingweek_desc')
560     a = q.execute()
561     if not a:
562         raise JamendoAPIException(str(q))
563     _update_cache(_tracks, a)
564     return a
565
566 def get_radio(radio_id):
567     """Returns: Radio"""
568     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?id=%d"%(radio_id))
569     js = q.execute()
570     if not js:
571         raise JamendoAPIException(str(q))
572     if isinstance(js, list):
573         ks = js[0]
574     return Radio(radio_id, json=js)
575
576 def starred_radios():
577     """Returns: [Radio]"""
578     q = CustomQuery(_GET2+"id+name+idstr+image/radio/json?order=starred_desc")
579     js = q.execute()
580     if not js:
581         raise JamendoAPIException(str(q))
582     return [Radio(int(radio['id']), json=radio) for radio in js]
583
584 def favorite_albums(user):
585     """Returns: [Album]"""
586     q = SearchQuery('favorite_albums', user=user, count=20)
587     a = q.execute()
588     if not a:
589         raise JamendoAPIException(str(q))
590     _update_cache(_albums, a)
591     return a
592
593 ### Set loader functions for classes
594
595 def _artist_loader(self):
596     if self._needs_load():
597         artist = get_artist(self.ID)
598         self._set_from(artist)
599 Artist.load = _artist_loader
600
601 def _album_loader(self):
602     if self._needs_load():
603         album = get_album(self.ID)
604         album.tracks = get_tracks(self.ID)
605         self._set_from(album)
606 Album.load = _album_loader
607
608 def _track_loader(self):
609     track = get_track(self.ID)
610     self._set_from(track)
611 Track.load = _track_loader
612
613 def _radio_loader(self):
614     radio = get_radio(self.ID)
615     self._set_from(radio)
616 Radio.load = _radio_loader