summaryrefslogtreecommitdiff
path: root/plugins/Lyrics.py
blob: 895a40139a675c0d50d6b920f140902a8ee05606 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from PyQt4 import QtGui,QtCore

import urllib2, httplib, cookielib
import socket
socket.setdefaulttimeout(8)
import re
from thread import start_new_thread
from traceback import print_exc

from misc import *
from clSettings import settings,mpdSettings
from clMonty import monty
from clPlugin import *

class ResetEvent(QtCore.QEvent):
	song=None
	def __init__(self, song=None):
		QtCore.QEvent.__init__(self,QtCore.QEvent.User)
		self.song=song
class AddHtmlEvent(QtCore.QEvent):
	html=None
	def __init__(self,html):
		QtCore.QEvent.__init__(self,QtCore.QEvent.User)
		self.html=html

LY_DEFAULT_ENGINE='http://www.google.com/search?q=lyrics+"$artist"+"$title"'
LY_DEFAULT_SITES='azlyrics.com	<br><br>.*?<br><br>(.*?)<br><br>\n'\
	'oldielyrics.com	song_in_top2.*?<br><br>(.*?)<script\n'\
	 'lyricstime.com	phone-left.gif.*?<p>(.*?)</p>\n'\

class wgLyrics(QtGui.QWidget):
	" contains the lyrics"
	txt=None
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self, parent)
		self.txt=QtGui.QTextEdit(parent)
		self.txt.setReadOnly(True)
		
		layout=QtGui.QVBoxLayout()
		layout.addWidget(self.txt)
		self.setLayout(layout)

		monty.addListener('onSongChange', self.onSongChange)
		monty.addListener('onReady', self.onReady)
		monty.addListener('onDisconnect', self.onDisconnect)
	
	def onSongChange(self, params):
		song=monty.getCurrentSong()
		try:
			song._data['file']
		except:
			self.resetTxt()
			return
		
		self.resetTxt(song)
		start_new_thread(self.fetchLyrics, (song,))
	
	def customEvent(self, event):
		if isinstance(event,ResetEvent):
			self.resetTxt(event.song)
		elif isinstance(event,AddHtmlEvent):
			self.txt.insertHtml(event.html)

	def onReady(self, params):
		self.onSongChange(None)
	
	_mutex=QtCore.QMutex()
	_fetchCnt=0
	def fetchLyrics(self, song):
		# only allow 1 instance to look lyrics!
		self._mutex.lock()
		if self._fetchCnt:
			self._mutex.unlock()
			return
		self._fetchCnt=1
		self._mutex.unlock()

		QtCore.QCoreApplication.postEvent(self, ResetEvent(song))
		
		# save the data to file!
		save_dir=settings.get('lyrics.dir', '/holy_grail')
		fInfo=QtCore.QFileInfo(save_dir)
		if fInfo.isDir():
			lyFName='%s/%s - %s.txt'%(save_dir,song.getArtist(),song.getTitle())
		else:
			lyFName=None
		# does the file exist? if yes, read that one!
		try:
			# we have it: load, and return!
			file=open(lyFName, 'r')
			QtCore.QCoreApplication.postEvent(self, AddHtmlEvent(file.read()))
			file.close()
			self._fetchCnt=0
			return
		except:
			pass

		# fetch from inet
		QtCore.QCoreApplication.postEvent(self, AddHtmlEvent('<i>Searching lyrics ...</i>'))
		
		lines=settings.get('lyrics.sites', LY_DEFAULT_SITES).split('\n')
		sites={}
		for line in lines:
			if line.strip():
				sites[line[0:line.find('\t')]]=line[line.find('\t'):].strip()
		# construct URL to search!
		url=settings.get('lyrics.engine', LY_DEFAULT_ENGINE)
		url=url.replace('$artist', song.getArtist())
		url=url.replace('$title', song.getTitle()).replace('$album', song.getAlbum())
		url=url.replace(' ', '+')
		try:
			request=urllib2.Request(url)
			request.add_header('User-Agent', 'montypc')
			opener=urllib2.build_opener()
			data=opener.open(request).read()

			# look for urls!
			regex=re.compile('<a href="(.*?)".*?>.*?<\/a>')
			urls=regex.findall(data)
			
			# look for predefined urls, which are good lyrics-sites
			finalURL=None
			finalRegex=None
			for url in urls:
				if finalURL:
					break
				for site in sites:
					if url.find(site)>=0:
						finalURL=url
						finalRegex=sites[site]
						break

			match=None
			QtCore.QCoreApplication.postEvent(self, ResetEvent(song))
			#print finalURL
			if finalURL:
				cj = cookielib.CookieJar()
				opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
				r = opener.open(finalURL)
				data=r.read()
				regex=re.compile(finalRegex, re.IGNORECASE|re.MULTILINE|re.DOTALL)
				match=regex.search(data)
			#print match
			if match:
				data=match.group(1)
				data=data.replace('<br>', '<br />')
				data=data.replace('<br />', '<br />')
				data=data.strip()
				# save for later use!
				if lyFName:
					# we can't save if the path isn't correct
					file=open(lyFName, 'w')
					file.write(data)
					file.close()
				data='%s<br /><br />(source: <a href="%s">%s</a>)'%(data,finalURL,finalURL)
			else:
				data='Lyrics not found :\'('

			QtCore.QCoreApplication.postEvent(self, AddHtmlEvent(data))

		except:
			print_exc()
			QtCore.QCoreApplication.postEvent(self, ResetEvent(song))
			QtCore.QCoreApplication.postEvent(self, AddHtmlEvent('Oh noes, an error occured while fetching lyrics!'))
		self._fetchCnt=0

	def onDisconnect(self, params):
		self.resetTxt()
	
	def resetTxt(self, song=None):
		self.txt.clear()
		if song:
			self.txt.insertHtml('<b>%s</b>\n<br /><u>%s</u><br />'\
					'<br />\n\n'%(song.getTitle(), song.getArtist()))


class pluginLyrics(Plugin):
	o=None
	def __init__(self, winMain):
		Plugin.__init__(self, winMain, 'Lyrics')
		self.o=wgLyrics(None)
	def getInfo(self):
		return "Show (and fetch) the lyrics of the currently playing song."
	
	def _getDockWidget(self):
		return self._createDock(self.o)

	def _getSettings(self):
		sites=QtGui.QTextEdit()
		sites.insertPlainText(settings.get('lyrics.sites', LY_DEFAULT_SITES))
		return [
			['lyrics.engine', 'Search engine', 'The URL that is used to search. $artist, $title and $album are replaced in the URL.', QtGui.QLineEdit(settings.get('lyrics.engine', LY_DEFAULT_ENGINE))],
			['lyrics.sites', 'Sites & regexes', 'This field contains all sites, together with the regex needed to fetch the lyrics.\nEvery line must look like this: $domain $regex-start(.*?)$regex-end\n$domain is the domain of the lyrics website, $regex-start is the regex indicating the start of the lyrics, $regex-end indicates the end. E.g. foolyrics.org <lyrics>(.*?)</lyrics>', sites],
			['lyrics.dir', 'Lyrics directory', 'Directory where lyrics should be stored and retrieved.', QtGui.QLineEdit(settings.get('lyrics.dir'))],
		]
	def afterSaveSettings(self):
		self.o.onSongChange(None)