From 3a81afdc9241207181b2e2636f9521fcbdd8b63c Mon Sep 17 00:00:00 2001 From: Bryan Schumaker Date: Tue, 26 Oct 2010 22:44:09 -0400 Subject: [PATCH] last.fm for album art Whenever a new song is loaded, we check the cache for album art. If we don't have art yet, then we place a request to the last.fm to find an image. --- libsaria/__init__.py | 3 ++ libsaria/lastfm.py | 68 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 libsaria/lastfm.py diff --git a/libsaria/__init__.py b/libsaria/__init__.py index 2c778b3c..83017aa0 100644 --- a/libsaria/__init__.py +++ b/libsaria/__init__.py @@ -23,6 +23,7 @@ cache = Cache() plugin = None music = None +lastfm = None # Initialize helpful variables @@ -30,10 +31,12 @@ def init(): global vars global prefs global music + global lastfm vars = Map() prefs = Map("preferences") import music + import lastfm event.start("POSTINIT") diff --git a/libsaria/lastfm.py b/libsaria/lastfm.py new file mode 100644 index 00000000..58cad943 --- /dev/null +++ b/libsaria/lastfm.py @@ -0,0 +1,68 @@ +# Bryan Schumaker (10/24/2010) + +import libsaria +import web +import xm + +cache = libsaria.cache +pref_attr = xm.find_preferred_attribute + +pref_sizes = ["extralarge", "large", "medium", "small"] + +APIROOT = "http://ws.audioscrobbler.com/2.0/" +APIKEY = "2c76f85a6704efd74b5a358821284ef9" +SECRET = "3a6012bfb627b60a884cf33fc044885c" + + +class LastFmRequest(dict): + def __init__(self, method): + self.method = method + + def print_file(self, file): + for line in file: + print line.strip() + file.seek(0) + + def place(self, printfile=False): + url = web.Url(APIROOT + "?method=" + self.method) + url["api_key"] = APIKEY + for param in self: + url[param] = self[param] + file = url.open() + if printfile==True: + self.print_file(file) + doc = xm.parse( file ) + lfm = xm.child(doc) + if xm.attributes(lfm)["status"] == "ok": + return xm.child(lfm) + else: + return None + +def lfm_cache_album(file, artist, album): + req = LastFmRequest("album.getInfo") + req["album"] = album + req["artist"] = artist + doc = req.place() + node = pref_attr(doc, "image", "size", pref_sizes) + node = xm.child(node) + if node == None: + return + try: + url = web.Url(node.data) + for line in url.open(): + file.write(line) + return True + except: + pass + return False + +def get_artwork(filepath): + id = libsaria.collection.lib_find_id(filepath) + if id == None: + return + artist = libsaria.collection.lib_get_attr(id, "artist") + album = libsaria.collection.lib_get_attr(id, "album") + cached = cache[artist] + file = cached.get("%s.jpg" % album, lfm_cache_album, artist, album) + libsaria.event.start("POSTGETART", file) +libsaria.event.invite("POSTLOAD", get_artwork, True)