1 #!/usr/bin/python
2 #
3 # (c) 2004-2008 The Music Player Daemon Project
4 # http://www.musicpd.org/
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 #
20 #
21 # Load lyrics from leoslyrics.com
22 #
24 from sys import argv, exit
25 from urllib import urlencode, urlopen
26 from xml.sax import make_parser, SAXException
27 from xml.sax.handler import ContentHandler
29 class SearchContentHandler(ContentHandler):
30 def __init__(self):
31 self.code = None
32 self.hid = None
34 def startElement(self, name, attrs):
35 if name == 'response':
36 self.code = int(attrs['code'])
37 elif name == 'result':
38 if self.hid is None or attrs['exactMatch'] == 'true':
39 self.hid = attrs['hid']
41 def search(artist, title):
42 query = urlencode({'auth': 'ncmpc',
43 'artist': artist,
44 'songtitle': title})
45 url = "http://api.leoslyrics.com/api_search.php?" + query
46 f = urlopen(url)
47 handler = SearchContentHandler()
48 parser = make_parser()
49 parser.setContentHandler(handler)
50 parser.parse(f)
51 return handler.hid
53 class LyricsContentHandler(ContentHandler):
54 def __init__(self):
55 self.code = None
56 self.is_text = False
57 self.text = None
59 def startElement(self, name, attrs):
60 if name == 'text':
61 self.text = ''
62 self.is_text = True
63 else:
64 self.is_text = False
66 def characters(self, chars):
67 if self.is_text:
68 self.text += chars
70 def lyrics(hid):
71 query = urlencode({'auth': 'ncmpc',
72 'hid': hid})
73 url = "http://api.leoslyrics.com/api_lyrics.php?" + query
74 f = urlopen(url)
75 handler = LyricsContentHandler()
76 parser = make_parser()
77 parser.setContentHandler(handler)
78 parser.parse(f)
79 return handler.text
81 hid = search(argv[1], argv[2])
82 if hid is None:
83 exit(2)
84 print lyrics(hid).encode('utf-8')