007c92935f0767a653a85e579878d34ae96a89eb
[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 LASTFM_APIKEY = "1e1d53528c86406757a6887addef0ace"
23 BASE_LASTFM = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo"
24
25
26 BASE_MSN = "http://www.bing.com/images/search?q="
27 MSN_MEDIUM = "+filterui:imagesize-medium"
28 MSN_SMALL = "+filterui:imagesize-medium"
29 MSN_SQUARE = "+filterui:aspect-square"
30 MSN_PHOTO = "+filterui:photo-graphics"
31
32 # LastFM:
33 # http://www.lastfm.es/api/show?service=290
34 #
35 class MussorgskyAlbumArt:
36
37     def __init__ (self):
38         bus = dbus.SessionBus ()
39         handle = time.time()
40         if (pil_available):
41             self.thumbnailer = LocalThumbnailer ()
42         else:
43             try:
44                 self.thumbnailer = bus.get_object ('org.freedesktop.thumbnailer',
45                                                    '/org/freedesktop/thumbnailer/Generic')
46             except dbus.exceptions.DBusException:
47                 print "No thumbnailer available"
48                 self.thumbnailer = None
49
50     def get_album_art (self, artist, album):
51         """
52         Return a tuple (album_art, thumbnail_album_art)
53         """
54         filename = getCoverArtFileName (album)
55         thumbnail = getCoverArtThumbFileName (album)
56
57         if (os.path.exists (filename)):
58             print "Album art already there " + filename
59         else:
60             online_resource = self.__msn_images (artist, album)
61             if (online_resource):
62                 content = self.__get_url (online_resource)
63                 if (content):
64                     print "Albumart: %s " % (filename)
65                     self.__save_content_into_file (content, filename)
66                 else:
67                     return (None, None)
68             else:
69                 return (None, None)
70
71         if (os.path.exists (thumbnail)):
72             print "Thumbnail exists"
73         else:
74             if (not self.__request_thumbnail (filename)):
75                 print "Failed doing thumbnail. Probably album art is not an image!"
76                 os.remove (filename)
77                 return (None, None)
78             
79         return (filename, thumbnail)
80
81     def __last_fm (self, artist, album):
82
83         if (not libxml_available):
84             return None
85         
86         if (not album or len (album) < 1):
87             return None
88         
89         URL = BASE_LASTFM + "&api_key=" + LASTFM_APIKEY
90         if (artist and len(artist) > 1):
91             URL += "&artist=" + urllib.quote(artist)
92         if (album):
93             URL += "&album=" + urllib.quote(album)
94             
95         print "Retrieving: %s" % (URL)
96         result = self.__get_url (URL)
97         if (not result):
98             return None
99         doc = libxml2.parseDoc (result)
100         image_nodes = doc.xpathEval ("//image[@size='large']")
101         if len (image_nodes) < 1:
102             return None
103         else:
104             return image_nodes[0].content
105
106     def __msn_images (self, artist, album):
107
108         good_artist = self.__clean_string_for_search (artist)
109         good_album = self.__clean_string_for_search (album)
110
111         if (good_album and good_artist):
112             full_try = BASE_MSN + good_album + "+" + good_artist + MSN_MEDIUM + MSN_SQUARE
113             print "Retrieving (album + artist): %s" % (full_try)
114             result = self.__get_url (full_try)
115             if (result):
116                 return self.__get_first_url_from_msn_results_page (result)
117
118         if (album):
119             if (album.lower ().find ("greatest hit") != -1):
120                 print "Ignoring '%s': too generic" % (album)
121                 pass
122             else:
123                 album_try = BASE_MSN + good_album + MSN_MEDIUM + MSN_SQUARE
124                 print "Retrieving (album): %s" % (album_try)
125                 result = self.__get_url (album_try)
126                 if (result):
127                     return self.__get_first_url_from_msn_results_page (result)
128
129         if (artist):
130             artist_try = BASE_MSN + good_artist + "+CD+music"  + MSN_SMALL + MSN_SQUARE + MSN_PHOTO
131             print "Retrieving (artist CD): %s" % (artist_try)
132             result = self.__get_url (artist_try)
133             if (result):
134                 return self.__get_first_url_from_msn_results_page (result)
135             
136         return None
137
138
139     def __get_first_url_from_msn_results_page (self, page):
140         start = page.find ("furl=")
141         if (start == -1):
142             return None
143         end = page.find ("\"", start + len ("furl="))
144         return page [start + len ("furl="): end].replace ("amp;", "")
145
146     def __clean_string_for_search (self, text):
147         if (not text or len (text) < 1):
148             return None
149             
150         bad_stuff = "_:?\\-~"
151         clean = text
152         for c in bad_stuff:
153             clean = clean.replace (c, " ")
154
155         clean.replace ("/", "%2F")
156         clean = clean.replace (" CD1", "").replace(" CD2", "")
157         return urllib.quote(clean)
158
159     def __save_content_into_file (self, content, filename):
160         output = open (filename, 'w')
161         output.write (content)
162         output.close ()
163         
164     def __get_url (self, url):
165         request = urllib2.Request (url)
166         request.add_header ('User-Agent', 'Mussorgsky/0.1 Test')
167         opener = urllib2.build_opener ()
168         try:
169             return opener.open (request).read ()
170         except:
171             return None
172
173     def __request_thumbnail (self, filename):
174         if (not self.thumbnailer):
175             print "No thumbnailer available"
176             return
177         uri = "file://" + filename
178         handle = time.time ()
179         return self.thumbnailer.Queue ([uri], ["image/jpeg"], dbus.UInt32 (handle))
180             
181
182
183 class LocalThumbnailer:
184     def __init__ (self):
185         self.THUMBNAIL_SIZE = (124,124)
186
187     def Queue (self, uris, mimes, handle):
188         for i in range (0, len(uris)):
189             uri = uris[i]
190             fullCoverFileName = uri[7:]
191             if (os.path.exists (fullCoverFileName)):
192                 thumbFile = get_thumb_filename_for_path (fullCoverFileName)
193                 try:
194                     image = Image.open (fullCoverFileName)
195                 except IOError, e:
196                     print e
197                     return False
198                 image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
199                 image.save( thumbFile, "JPEG" )
200                 print "Thumbnail: " + thumbFile
201         return True
202             
203
204
205 if __name__ == "__main__":
206     import sys
207     if ( len (sys.argv) > 2):
208         artist = sys.argv[1]
209         album = sys.argv[2]
210     else:
211         print "ARTIST ALBUM"
212         sys.exit (-1)
213
214     maa = MussorgskyAlbumArt ()
215     maa.get_album_art (artist, album)