912aa0601cb0fcbe8d97946a1c80f0e0153aa5ec
[mussorgsky] / src / album_art.py
1 #!/usr/bin/env python2.5
2 import urllib2, urllib
3 import os
4 from album_art_spec import getCoverArtFileName, getCoverArtThumbFileName, get_thumb_filename_for_path
5 import dbus, time
6 import string
7
8 try:
9     import libxml2
10     libxml_available = True
11 except ImportError:
12     libxml_available = False
13
14 try:
15     import PIL
16     import Image
17     pil_available = True
18 except ImportError:
19     pil_available = False
20
21
22 # Set socket timeout
23 import socket
24 import urllib2
25
26 timeout = 5
27 socket.setdefaulttimeout(timeout)
28
29 LASTFM_APIKEY = "1e1d53528c86406757a6887addef0ace"
30 BASE_LASTFM = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo"
31
32
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"
38
39 CACHE_LOCATION = os.path.join (os.getenv ("HOME"), ".cache", "mussorgsky")
40 # LastFM:
41 # http://www.lastfm.es/api/show?service=290
42 #
43 class MussorgskyAlbumArt:
44
45     def __init__ (self):
46         bus = dbus.SessionBus ()
47         handle = time.time()
48
49         if (not os.path.exists (CACHE_LOCATION)):
50             os.makedirs (CACHE_LOCATION)
51             
52         if (pil_available):
53             self.thumbnailer = LocalThumbnailer ()
54         else:
55             try:
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
61
62     def get_album_art (self, artist, album, force=False):
63         """
64         Return a tuple (album_art, thumbnail_album_art)
65         """
66         filename = getCoverArtFileName (album)
67         thumbnail = getCoverArtThumbFileName (album)
68
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
73         else:
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)
78                 if (content):
79                     print "Albumart: %s " % (filename)
80                     self.__save_content_into_file (content, filename)
81                     album_art_available = True
82                     break
83
84         if (not album_art_available):
85             return (None, None)
86
87         if (os.path.exists (thumbnail) and not force):
88             print "Thumbnail exists " + thumbnail
89         else:
90             if (not self.__request_thumbnail (filename)):
91                 print "Failed doing thumbnail. Probably album art is not an image!"
92                 os.remove (filename)
93                 return (None, None)
94             
95         return (filename, thumbnail)
96
97
98     def get_alternatives (self, artist, album, no_alternatives):
99         """
100         return a list of paths of possible album arts
101         """
102         results_page = self.__msn_images (artist, album)
103         valid_images = []
104         for image_url in self.__get_url_from_msn_results_page (results_page):
105             image = self.__get_url (image_url)
106             if (image):
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):
111                     return valid_images
112         return valid_images
113
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!"
117
118         filename = getCoverArtFileName (album)
119         thumbnail = getCoverArtThumbFileName (album)
120
121         os.rename (path, filename)
122         if (not self.__request_thumbnail (filename)):
123             print "Something wrong creating the thumbnail!"
124         
125
126     def __last_fm (self, artist, album):
127
128         if (not libxml_available):
129             return None
130         
131         if (not album or len (album) < 1):
132             return None
133         
134         URL = BASE_LASTFM + "&api_key=" + LASTFM_APIKEY
135         if (artist and len(artist) > 1):
136             URL += "&artist=" + urllib.quote(artist)
137         if (album):
138             URL += "&album=" + urllib.quote(album)
139             
140         print "Retrieving: %s" % (URL)
141         result = self.__get_url (URL)
142         if (not result):
143             return None
144         doc = libxml2.parseDoc (result)
145         image_nodes = doc.xpathEval ("//image[@size='large']")
146         if len (image_nodes) < 1:
147             return None
148         else:
149             return image_nodes[0].content
150
151     def __msn_images (self, artist, album):
152
153         good_artist = self.__clean_string_for_search (artist)
154         good_album = self.__clean_string_for_search (album)
155
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)
160             return result
161
162         if (album):
163             if (album.lower ().find ("greatest hit") != -1):
164                 print "Ignoring '%s': too generic" % (album)
165                 pass
166             else:
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)
170                 return result
171             
172         if (artist):
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)
176             return result
177         
178         return None
179
180
181     def __get_url_from_msn_results_page (self, page):
182
183         if (not page):
184             return
185
186         current_option = None
187         starting_at = 0
188
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)
193             if (start == -1):
194                 yield None
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")):
199                 yield current_option
200             starting_at = end
201         yield None
202         
203
204     def __clean_string_for_search (self, text):
205         if (not text or len (text) < 1):
206             return None
207             
208         bad_stuff = "_:?\\-~"
209         clean = text
210         for c in bad_stuff:
211             clean = clean.replace (c, " ")
212
213         clean.replace ("/", "%2F")
214         clean = clean.replace (" CD1", "").replace(" CD2", "")
215         return urllib.quote(clean)
216
217     def __save_content_into_file (self, content, filename):
218         output = open (filename, 'w')
219         output.write (content)
220         output.close ()
221         
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 ()
226         try:
227             return opener.open (request).read ()
228         except:
229             return None
230
231     def __request_thumbnail (self, filename):
232         if (not self.thumbnailer):
233             print "No thumbnailer available"
234             return
235         uri = "file://" + filename
236         handle = time.time ()
237         return self.thumbnailer.Queue ([uri], ["image/jpeg"], dbus.UInt32 (handle))
238             
239
240
241 class LocalThumbnailer:
242     def __init__ (self):
243         self.THUMBNAIL_SIZE = (124,124)
244
245     def Queue (self, uris, mimes, handle):
246         for i in range (0, len(uris)):
247             uri = uris[i]
248             fullCoverFileName = uri[7:]
249             if (os.path.exists (fullCoverFileName)):
250                 thumbFile = get_thumb_filename_for_path (fullCoverFileName)
251                 try:
252                     image = Image.open (fullCoverFileName)
253                     image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
254                     image.save( thumbFile, "JPEG" )
255                     print "Thumbnail: " + thumbFile
256                 except IOError, e:
257                     print e
258                     return False
259         return True
260             
261
262
263 if __name__ == "__main__":
264     import sys
265     from optparse import OptionParser
266
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")
281
282     (options, args) = parser.parse_args ()
283     print options
284     if (not options.artist and not options.album):
285         parser.print_help ()
286         sys.exit (-1)
287
288     if (options.multiple and options.retrieve):
289         print "Multiple and retrieve are incompatible"
290         parser.print_help ()
291         sys.exit (-1)
292         
293     if options.print_paths and not options.retrieve:
294         print "Album art:", getCoverArtFileName (options.album)
295         print "Thumbnail:", getCoverArtThumbFileName (options.album)
296
297     if options.retrieve:
298         maa = MussorgskyAlbumArt ()
299         maa.get_album_art (options.artist, options.album)
300
301     if options.multiple:
302         maa = MussorgskyAlbumArt ()
303         alt = maa.get_alternatives (options.artist, options.album, 5)
304         for a in alt:
305             print a