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