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"
39 CACHE_LOCATION = os.path.join (os.getenv ("HOME"), ".cache", "mussorgsky")
41 # http://www.lastfm.es/api/show?service=290
43 class MussorgskyAlbumArt:
46 bus = dbus.SessionBus ()
49 if (not os.path.exists (CACHE_LOCATION)):
50 os.makedirs (CACHE_LOCATION)
53 self.thumbnailer = LocalThumbnailer ()
56 self.thumbnailer = bus.get_object ('org.freedesktop.thumbnailer',
57 '/org/freedesktop/thumbnailer/Generic')
58 except dbus.exceptions.DBusException:
59 print "No thumbnailer available"
60 self.thumbnailer = None
62 def get_album_art (self, artist, album, force=False):
64 Return a tuple (album_art, thumbnail_album_art)
66 filename = getCoverArtFileName (album)
67 thumbnail = getCoverArtThumbFileName (album)
69 album_art_available = False
70 if (os.path.exists (filename) and not force):
71 print "Album art already there " + filename
72 album_art_available = True
74 results_page = self.__msn_images (artist, album)
75 for online_resource in self.__get_url_from_msn_results_page (results_page):
76 print "Choosed:", online_resource
77 content = self.__get_url (online_resource)
79 print "Albumart: %s " % (filename)
80 self.__save_content_into_file (content, filename)
81 album_art_available = True
84 if (not album_art_available):
87 if (os.path.exists (thumbnail) and not force):
88 print "Thumbnail exists " + thumbnail
90 if (not self.__request_thumbnail (filename)):
91 print "Failed doing thumbnail. Probably album art is not an image!"
95 return (filename, thumbnail)
98 def get_alternatives (self, artist, album, no_alternatives):
100 return a list of paths of possible album arts
102 results_page = self.__msn_images (artist, album)
104 for image_url in self.__get_url_from_msn_results_page (results_page):
105 image = self.__get_url (image_url)
107 image_path = os.path.join (CACHE_LOCATION, "alternative-" + str(len(valid_images)))
108 self.__save_content_into_file (image, image_path)
109 valid_images.append (image_path)
110 if (len (valid_images) > no_alternatives):
114 def save_alternative (self, artist, album, path):
115 if (not os.path.exists (path)):
116 print "**** CRITICAL **** image in path", path, "doesn't exist!"
118 filename = getCoverArtFileName (album)
119 thumbnail = getCoverArtThumbFileName (album)
121 os.rename (path, filename)
122 if (not self.__request_thumbnail (filename)):
123 print "Something wrong creating the thumbnail!"
126 def __last_fm (self, artist, album):
128 if (not libxml_available):
131 if (not album or len (album) < 1):
134 URL = BASE_LASTFM + "&api_key=" + LASTFM_APIKEY
135 if (artist and len(artist) > 1):
136 URL += "&artist=" + urllib.quote(artist)
138 URL += "&album=" + urllib.quote(album)
140 print "Retrieving: %s" % (URL)
141 result = self.__get_url (URL)
144 doc = libxml2.parseDoc (result)
145 image_nodes = doc.xpathEval ("//image[@size='large']")
146 if len (image_nodes) < 1:
149 return image_nodes[0].content
151 def __msn_images (self, artist, album):
153 good_artist = self.__clean_string_for_search (artist)
154 good_album = self.__clean_string_for_search (album)
156 if (good_album and good_artist):
157 full_try = BASE_MSN + good_album + "+" + good_artist + MSN_MEDIUM + MSN_SQUARE
158 print "Searching (album + artist): %s" % (full_try)
159 result = self.__get_url (full_try)
163 if (album.lower ().find ("greatest hit") != -1):
164 print "Ignoring '%s': too generic" % (album)
167 album_try = BASE_MSN + good_album + MSN_MEDIUM + MSN_SQUARE
168 print "Searching (album): %s" % (album_try)
169 result = self.__get_url (album_try)
173 artist_try = BASE_MSN + good_artist + "+CD+music" + MSN_SMALL + MSN_SQUARE + MSN_PHOTO
174 print "Searching (artist CD): %s" % (artist_try)
175 result = self.__get_url (artist_try)
181 def __get_url_from_msn_results_page (self, page):
186 current_option = None
189 # 500 is just a safe limit
190 for i in range (0, 500):
191 # Iterate until find a jpeg
192 start = page.find ("furl=", starting_at)
195 end = page.find ("\"", start + len ("furl="))
196 current_option = page [start + len ("furl="): end].replace ("amp;", "")
197 if (current_option.lower().endswith (".jpg") or
198 current_option.lower().endswith (".jpeg")):
204 def __clean_string_for_search (self, text):
205 if (not text or len (text) < 1):
208 bad_stuff = "_:?\\-~"
211 clean = clean.replace (c, " ")
213 clean.replace ("/", "%2F")
214 clean = clean.replace (" CD1", "").replace(" CD2", "")
215 return urllib.quote(clean)
217 def __save_content_into_file (self, content, filename):
218 output = open (filename, 'w')
219 output.write (content)
222 def __get_url (self, url):
223 request = urllib2.Request (url)
224 request.add_header ('User-Agent', 'Mussorgsky/0.1 Test')
225 opener = urllib2.build_opener ()
227 return opener.open (request).read ()
231 def __request_thumbnail (self, filename):
232 if (not self.thumbnailer):
233 print "No thumbnailer available"
235 uri = "file://" + filename
236 handle = time.time ()
237 return self.thumbnailer.Queue ([uri], ["image/jpeg"], dbus.UInt32 (handle))
241 class LocalThumbnailer:
243 self.THUMBNAIL_SIZE = (124,124)
245 def Queue (self, uris, mimes, handle):
246 for i in range (0, len(uris)):
248 fullCoverFileName = uri[7:]
249 if (os.path.exists (fullCoverFileName)):
250 thumbFile = get_thumb_filename_for_path (fullCoverFileName)
252 image = Image.open (fullCoverFileName)
253 image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
254 image.save( thumbFile, "JPEG" )
255 print "Thumbnail: " + thumbFile
263 if __name__ == "__main__":
265 from optparse import OptionParser
267 parser = OptionParser()
268 parser.add_option ("-p", "--print", dest="print_paths",
269 action="store_true", default=True,
270 help="Print the destination paths")
271 parser.add_option ("-r", "--retrieve", dest="retrieve",
272 action="store_true", default=False,
273 help="Try to retrieve the online content")
274 parser.add_option ("-m", "--multiple", dest="multiple",
275 action="store_true", default=False,
276 help="Show more than one option")
277 parser.add_option ("-a", "--artist", dest="artist", type="string",
278 help="ARTIST to look for", metavar="ARTIST")
279 parser.add_option ("-b", "--album", dest="album", type="string",
280 help="ALBUM to look for", metavar="ALBUM")
282 (options, args) = parser.parse_args ()
284 if (not options.artist and not options.album):
288 if (options.multiple and options.retrieve):
289 print "Multiple and retrieve are incompatible"
293 if options.print_paths and not options.retrieve:
294 print "Album art:", getCoverArtFileName (options.album)
295 print "Thumbnail:", getCoverArtThumbFileName (options.album)
298 maa = MussorgskyAlbumArt ()
299 maa.get_album_art (options.artist, options.album)
302 maa = MussorgskyAlbumArt ()
303 alt = maa.get_alternatives (options.artist, options.album, 5)