command: make Ctrl-X/Alt-X/F1 etc. translatable
[ncmpc.git] / lyrics / 30-leoslyrics.py
blob87953e81840d598fc8007c90271b4274c2ac800c
1 #!/usr/bin/python
3 # (c) 2004-2008 The Music Player Daemon Project
4 # http://www.musicpd.org/
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.
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
21 # Load lyrics from leoslyrics.com
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 try:
47 f = urlopen(url)
48 except IOError:
49 stderr.write("Failed to connect to http://api.leoslyrics.com, it seems down!\n")
50 exit(1)
51 handler = SearchContentHandler()
52 parser = make_parser()
53 parser.setContentHandler(handler)
54 try:
55 parser.parse(f)
56 except SAXException:
57 stderr.write("Failed to parse the search result!\n")
58 exit(1)
59 return handler.hid
61 class LyricsContentHandler(ContentHandler):
62 def __init__(self):
63 self.code = None
64 self.is_text = False
65 self.text = None
67 def startElement(self, name, attrs):
68 if name == 'text':
69 self.text = ''
70 self.is_text = True
71 else:
72 self.is_text = False
74 def characters(self, chars):
75 if self.is_text:
76 self.text += chars
78 def lyrics(hid):
79 query = urlencode({'auth': 'ncmpc',
80 'hid': hid})
81 url = "http://api.leoslyrics.com/api_lyrics.php?" + query
82 f = urlopen(url)
83 handler = LyricsContentHandler()
84 parser = make_parser()
85 parser.setContentHandler(handler)
86 try:
87 parser.parse(f)
88 except SAXException:
89 stderr.write("Failed to parse the lyrics!\n")
90 exit(1)
91 return handler.text
93 hid = search(argv[1], argv[2])
94 if hid is None:
95 exit(69)
96 print lyrics(hid).encode('utf-8').rstrip()