1 #!/usr/bin/env python2.5
4 from album_art_spec import getCoverArtFileName, getCoverArtThumbFileName, get_thumb_filename_for_path
10 libxml_available = True
12 libxml_available = False
27 socket.setdefaulttimeout(timeout)
29 LASTFM_APIKEY = "1e1d53528c86406757a6887addef0ace"
30 BASE_LASTFM = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo"
33 BASE_MSN = "http://www.bing.com/images/search?q="
34 MSN_MEDIUM = "+filterui:imagesize-medium"
35 MSN_SMALL = "+filterui:imagesize-medium"
36 MSN_SQUARE = "+filterui:aspect-square"
37 MSN_PHOTO = "+filterui:photo-graphics"
40 # http://www.lastfm.es/api/show?service=290
42 class MussorgskyAlbumArt:
45 bus = dbus.SessionBus ()
48 self.thumbnailer = LocalThumbnailer ()
51 self.thumbnailer = bus.get_object ('org.freedesktop.thumbnailer',
52 '/org/freedesktop/thumbnailer/Generic')
53 except dbus.exceptions.DBusException:
54 print "No thumbnailer available"
55 self.thumbnailer = None
57 def get_album_art (self, artist, album, force=False):
59 Return a tuple (album_art, thumbnail_album_art)
61 filename = getCoverArtFileName (album)
62 thumbnail = getCoverArtThumbFileName (album)
64 if (os.path.exists (filename) and not force):
65 print "Album art already there " + filename
67 online_resource = self.__msn_images (artist, album)
69 print "Choosed:", online_resource
70 content = self.__get_url (online_resource)
72 print "Albumart: %s " % (filename)
73 self.__save_content_into_file (content, filename)
79 if (os.path.exists (thumbnail) and not force):
80 print "Thumbnail exists " + thumbnail
82 if (not self.__request_thumbnail (filename)):
83 print "Failed doing thumbnail. Probably album art is not an image!"
87 return (filename, thumbnail)
89 def __last_fm (self, artist, album):
91 if (not libxml_available):
94 if (not album or len (album) < 1):
97 URL = BASE_LASTFM + "&api_key=" + LASTFM_APIKEY
98 if (artist and len(artist) > 1):
99 URL += "&artist=" + urllib.quote(artist)
101 URL += "&album=" + urllib.quote(album)
103 print "Retrieving: %s" % (URL)
104 result = self.__get_url (URL)
107 doc = libxml2.parseDoc (result)
108 image_nodes = doc.xpathEval ("//image[@size='large']")
109 if len (image_nodes) < 1:
112 return image_nodes[0].content
114 def __msn_images (self, artist, album):
116 good_artist = self.__clean_string_for_search (artist)
117 good_album = self.__clean_string_for_search (album)
119 if (good_album and good_artist):
120 full_try = BASE_MSN + good_album + "+" + good_artist + MSN_MEDIUM + MSN_SQUARE
121 print "Searching (album + artist): %s" % (full_try)
122 result = self.__get_url (full_try)
124 return self.__get_first_url_from_msn_results_page (result)
127 if (album.lower ().find ("greatest hit") != -1):
128 print "Ignoring '%s': too generic" % (album)
131 album_try = BASE_MSN + good_album + MSN_MEDIUM + MSN_SQUARE
132 print "Searching (album): %s" % (album_try)
133 result = self.__get_url (album_try)
135 return self.__get_first_url_from_msn_results_page (result)
138 artist_try = BASE_MSN + good_artist + "+CD+music" + MSN_SMALL + MSN_SQUARE + MSN_PHOTO
139 print "Searching (artist CD): %s" % (artist_try)
140 result = self.__get_url (artist_try)
142 return self.__get_first_url_from_msn_results_page (result)
147 def __get_first_url_from_msn_results_page (self, page):
149 current_option = None
153 while (security_limit > 0):
154 # Iterate until find a jpeg
155 start = page.find ("furl=", starting_at)
158 end = page.find ("\"", start + len ("furl="))
159 current_option = page [start + len ("furl="): end].replace ("amp;", "")
160 if (current_option.lower().endswith (".jpg") or
161 current_option.lower().endswith (".jpeg")):
162 return current_option
169 def __clean_string_for_search (self, text):
170 if (not text or len (text) < 1):
173 bad_stuff = "_:?\\-~"
176 clean = clean.replace (c, " ")
178 clean.replace ("/", "%2F")
179 clean = clean.replace (" CD1", "").replace(" CD2", "")
180 return urllib.quote(clean)
182 def __save_content_into_file (self, content, filename):
183 output = open (filename, 'w')
184 output.write (content)
187 def __get_url (self, url):
188 request = urllib2.Request (url)
189 request.add_header ('User-Agent', 'Mussorgsky/0.1 Test')
190 opener = urllib2.build_opener ()
192 return opener.open (request).read ()
196 def __request_thumbnail (self, filename):
197 if (not self.thumbnailer):
198 print "No thumbnailer available"
200 uri = "file://" + filename
201 handle = time.time ()
202 return self.thumbnailer.Queue ([uri], ["image/jpeg"], dbus.UInt32 (handle))
206 class LocalThumbnailer:
208 self.THUMBNAIL_SIZE = (124,124)
210 def Queue (self, uris, mimes, handle):
211 for i in range (0, len(uris)):
213 fullCoverFileName = uri[7:]
214 if (os.path.exists (fullCoverFileName)):
215 thumbFile = get_thumb_filename_for_path (fullCoverFileName)
217 image = Image.open (fullCoverFileName)
218 image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
219 image.save( thumbFile, "JPEG" )
220 print "Thumbnail: " + thumbFile
228 if __name__ == "__main__":
230 from optparse import OptionParser
232 parser = OptionParser()
233 parser.add_option ("-p", "--print", dest="print_paths",
234 action="store_true", default=True,
235 help="Print the destination paths")
236 parser.add_option ("-r", "--retrieve", dest="retrieve",
237 action="store_true", default=False,
238 help="Try to retrieve the online content")
239 parser.add_option ("-a", "--artist", dest="artist", type="string",
240 help="ARTIST to look for", metavar="ARTIST")
241 parser.add_option ("-b", "--album", dest="album", type="string",
242 help="ALBUM to look for", metavar="ALBUM")
244 (options, args) = parser.parse_args ()
246 if (not options.artist and not options.album):
250 if options.print_paths and not options.retrieve:
251 print "Album art:", getCoverArtFileName (options.album)
252 print "Thumbnail:", getCoverArtThumbFileName (options.album)
256 maa = MussorgskyAlbumArt ()
257 maa.get_album_art (options.artist, options.album)