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, stderr
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 try:
51 parser.parse(f)
52 except SAXException:
53 stderr.write("Failed to parse the search result!\n")
54 exit(1)
55 return handler.hid
57 class LyricsContentHandler(ContentHandler):
58 def __init__(self):
59 self.code = None
60 self.is_text = False
61 self.text = None
63 def startElement(self, name, attrs):
64 if name == 'text':
65 self.text = ''
66 self.is_text = True
67 else:
68 self.is_text = False
70 def characters(self, chars):
71 if self.is_text:
72 self.text += chars
74 def lyrics(hid):
75 query = urlencode({'auth': 'ncmpc',
76 'hid': hid})
77 url = "http://api.leoslyrics.com/api_lyrics.php?" + query
78 f = urlopen(url)
79 handler = LyricsContentHandler()
80 parser = make_parser()
81 parser.setContentHandler(handler)
82 try:
83 parser.parse(f)
84 except SAXException:
85 stderr.write("Failed to parse the lyrics!\n")
86 exit(1)
87 return handler.text
89 hid = search(argv[1], argv[2])
90 if hid is None:
91 exit(69)
92 print lyrics(hid).encode('utf-8').rstrip()