summaryrefslogtreecommitdiff
path: root/nephilim/plugins/Lyrics.py
blob: 381009a2cd418e747b27c548e8454f64a317c90b (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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#
#    Copyright (C) 2009 Anton Khirnov <wyskas@gmail.com>
#
#    Nephilim is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Nephilim is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Nephilim.  If not, see <http://www.gnu.org/licenses/>.
#

from PyQt4        import QtGui, QtCore
from PyQt4.QtCore import QVariant

import socket
import os
import re
import urllib
from   lxml import etree

from ..plugin import Plugin
from ..       import misc

class LyricsWidget(QtGui.QWidget):
    # public, read-only
    plugin = None  # plugin
    logger = None

    # private
    __text_view = None  # text-object
    __toolbar   = None
    __label     = None
    def __init__(self, plugin):
        QtGui.QWidget.__init__(self)
        self.plugin = plugin
        self.logger = plugin.logger
        self.curLyrics = ''

        self.__label = QtGui.QLabel(self)
        self.__label.setWordWrap(True)

        # add text area
        self.__text_view = QtGui.QTextEdit(self)
        self.__text_view.setReadOnly(True)

        # add toolbar
        self.__toolbar = QtGui.QToolBar('Lyrics toolbar', self)
        self.__toolbar.setOrientation(QtCore.Qt.Vertical)

        self.__toolbar.addAction(QtGui.QIcon('gfx/refresh.png'), 'Refresh lyrics', self.plugin.refresh)
        edit = self.__toolbar.addAction(QtGui.QIcon('gfx/edit.png'), 'Edit lyrics')
        edit.setCheckable(True)
        edit.connect(edit, QtCore.SIGNAL('toggled(bool)'), self.__toggle_editable)

        self.__toolbar.addAction(QtGui.QIcon('gfx/save.png'), 'Save lyrics', self.__save_lyrics)
        self.__toolbar.addAction(QtGui.QIcon('gfx/delete.png'), 'Delete stored file', self.plugin.del_lyrics_file)

        self.setLayout(QtGui.QGridLayout())
        self.layout().setSpacing(0)
        self.layout().setMargin(0)
        self.layout().addWidget(self.__toolbar, 0, 0, -1, 1, QtCore.Qt.AlignTop)
        self.layout().addWidget(self.__label, 0, 1)
        self.layout().addWidget(self.__text_view, 1, 1)

        self.connect(self.plugin, QtCore.SIGNAL('new_lyrics_fetched'), self.set_lyrics)

    def set_lyrics(self, song, lyrics, flags = 0):
        """Set currently displayed lyrics for song. flags parameter is
           unused now."""
        if not song:
            self.__label.clear()
            return self.__text_view.clear()

        # a late thread might call this for a previous song
        if song != self.plugin.mpclient.current_song():
            return

        self.__text_view.clear()
        self.__label.setText('<b>%s</b> by <u>%s</u> on <u>%s</u>'\
                             %(song.title(), song.artist(), song.album()))
        if lyrics:
            self.logger.info('Setting new lyrics.')
            self.__text_view.insertPlainText(lyrics.decode('utf-8'))
        else:
            self.logger.info('Lyrics not found.')
            self.__text_view.insertPlainText('Lyrics not found.')

    def __save_lyrics(self):
        self.plugin.save_lyrics_file(unicode(self.__text_view.toPlainText()).encode('utf-8'))

    def __toggle_editable(self, val):
        self.__text_view.setReadOnly(not val)

class Lyrics(Plugin):
    # public, read-only
    o           = None
    """A dict of { site name : function }. Function takes a song and returns lyrics
       as a python string or None if not found."""
    sites       = {}

    # private
    DEFAULTS          = {'sites' : QtCore.QStringList(['lyricwiki', 'animelyrics']), 'lyricdir' : '$musicdir/$songdir',
                         'lyricname' : '.lyrics_nephilim_$artist_$album_$title', 'store' : True}
    __available_sites = {}
    __lyrics_dir      = None
    __lyrics_path     = None

    def __init__(self, parent, mpclient, name):
        Plugin.__init__(self, parent, mpclient, name)

        self.__available_sites['lyricwiki']   = self.__fetch_lyricwiki
        self.__available_sites['animelyrics'] = self.__fetch_animelyrics

    def _load(self):
        self.o = LyricsWidget(self)
        for site in self.__available_sites:
            if site in self.settings().value('%s/sites'%self.name).toStringList():
                self.sites[site] = self.__available_sites[site]
        self.connect(self.mpclient, QtCore.SIGNAL('song_changed'), self.refresh)
    def _unload(self):
        self.o     = None
        self.sites = []
        self.disconnect(self.mpclient, QtCore.SIGNAL('song_changed'), self.refresh)
    def info(self):
        return "Show (and fetch) the lyrics of the currently playing song."

    def _get_dock_widget(self):
        return self._create_dock(self.o)

    class FetchThread(QtCore.QThread):
        def __init__(self, parent, fetch_func, song):
            QtCore.QThread.__init__(self)
            self.setParent(parent)
            self.fetch_func = fetch_func
            self.song = song
        def run(self):
            self.fetch_func(self.song)

    def refresh(self):
        """Attempt to automatically get lyrics first from a file, then from the internet."""
        self.logger.info('Autorefreshing lyrics.')
        song = self.mpclient.current_song()
        if not song:
            self.__lyrics_dir  = ''
            self.__lyrics_path = ''
            return self.o.set_lyrics(None, None)

        (self.__lyrics_dir, self.__lyrics_path) = misc.generate_metadata_path(song,
                                                                          self.settings().value(self.name + '/lyricdir').toString(),
                                                                          self.settings().value(self.name + '/lyricname').toString())
        try:
            self.logger.info('Trying to read lyrics from file %s.'%self.__lyrics_path)
            file   = open(self.__lyrics_path, 'r')
            lyrics = file.read()
            file.close()
            if lyrics:
                return self.emit(QtCore.SIGNAL('new_lyrics_fetched'), song, lyrics)
        except IOError, e:
            self.logger.info('Error reading lyrics file: %s.'%e)


        thread = self.FetchThread(self, self.__fetch_lyrics, song)
        thread.start()

    def save_lyrics_file(self, lyrics, path = None):
        """Save lyrics to a file specified in path.
           If path is None, then a default value is used."""
        self.logger.info('Saving lyrics...')
        try:
            if path:
                file = open(path, 'w')
            else:
                file = open(self.__lyrics_path, 'w')
            file.write(lyrics)
            file.close()
            self.logger.info('Lyrics successfully saved.')
        except IOError, e:
            self.logger.error('Error writing lyrics: %s', e)

    def del_lyrics_file(self, song = None):
        """Delete a lyrics file for song. If song is not specified
           current song is used."""
        if not song:
            path = self.__lyrics_path
        else:
            path = misc.generate_metadata_path(song, self.settings().value(self.name + '/lyricdir').toString(),
                                               self.settings().value(self.name + '/lyricname').toString())

        try:
            os.remove(path)
        except IOError, e:
            self.logger.error('Error removing lyrics file %s: %s'%(path, e))

    def __fetch_lyrics(self, song):
        self.logger.info('Trying to download lyrics from internet.')
        lyrics = None
        for site in self.sites:
            self.logger.info('Trying %s.'%site)
            lyrics = self.sites[site](song)
            if lyrics:
                if self.settings().value(self.name + '/store').toBool():
                    self.save_lyrics_file(lyrics)
                return self.emit(QtCore.SIGNAL('new_lyrics_fetched'), song, lyrics)

        self.emit(QtCore.SIGNAL('new_lyrics_fetched'), song, None)

    def __fetch_lyricwiki(self, song):
        url  = 'http://lyricwiki.org/api.php?%s' %urllib.urlencode({'func':'getSong',
                   'artist':song.artist().encode('utf-8'), 'song':song.title().encode('utf-8'),
                   'fmt':'xml'})
        try:
            # get url for lyrics
            tree = etree.HTML(urllib.urlopen(url).read())
            if tree.find('.//lyrics').text == 'Not found':
                return None
            #get page with lyrics and change <br> tags to newlines
            url    = tree.find('.//url').text
            page   = re.sub('<br>|<br/>|<br />', '\n', urllib.urlopen(url).read())
            html   = etree.HTML(page)
            lyrics = ''
            for elem in html.iterfind('.//div'):
                if elem.get('class') == 'lyricbox':
                    lyrics += etree.tostring(elem, method = 'text', encoding = 'utf-8')
            return lyrics
        except (socket.error, IOError), e:
            self.logger.error('Error downloading lyrics from LyricWiki: %s.'%e)
            return None

    def __fetch_animelyrics(self, song):
        url = 'http://www.animelyrics.com/search.php?%s'%urllib.urlencode({'q':song.artist().encode('utf-8'),
                                                                           't':'performer'})
        try:
            #get url for lyrics
            self.logger.info('Searching Animelyrics: %s.'%url)
            tree   = etree.HTML(urllib.urlopen(url).read())
            url    = None
            for elem in tree.iterfind('.//a'):
                if ('href' in elem.attrib) and elem.text and (song.title() in elem.text):
                    url = 'http://www.animelyrics.com/%s'%elem.get('href')
            if not url:
                return None
            #get lyrics
            self.logger.info('Found song URL: %s.'%url)
            tree = etree.HTML(urllib.urlopen(url).read())
            ret = ''
            for elem in tree.iterfind('.//pre'):
                if elem.get('class') == 'lyrics':
                    ret += '%s\n\n'%etree.tostring(elem, method = 'text', encoding = 'utf-8')
            return ret
        except socket.error, e:
            self.logger.error('Error downloading lyrics from Animelyrics: %s.'%e)
            return None
        except AttributeError:
            # lyrics not found
            return None

    class SettingsWidgetLyrics(Plugin.SettingsWidget):
        lyricdir  = None
        lyricname = None
        store     = None

        def __init__(self, plugin):
            Plugin.SettingsWidget.__init__(self, plugin)
            self.settings().beginGroup(self.plugin.name)


            # store lyrics groupbox
            self.store = QtGui.QGroupBox('Store lyrics.')
            self.store.setToolTip('Should %s store its own copy of lyrics?'%misc.APPNAME)
            self.store.setCheckable(True)
            self.store.setChecked(self.settings().value('store').toBool())
            self.store.setLayout(QtGui.QGridLayout())

            # paths to lyrics
            self.lyricdir  = QtGui.QLineEdit(self.settings().value('lyricdir').toString())
            self.lyricdir.setToolTip('Where should %s store lyrics.\n'
                                     '$musicdir will be expanded to path to MPD music library (as set by user)\n'
                                     '$songdir will be expanded to path to the song (relative to $musicdir\n'
                                     'other tags same as in lyricname'
                                      %misc.APPNAME)
            self.lyricname = QtGui.QLineEdit(self.settings().value('lyricname').toString())
            self.lyricname.setToolTip('Filename for %s lyricsfiles.\n'
                                      'All tags supported by MPD will be expanded to their\n'
                                      'values for current song, e.g. $title, $track, $artist,\n'
                                      '$album, $genre etc.'%misc.APPNAME)
            self.store.layout().addWidget(QtGui.QLabel('Lyrics directory'), 0, 0)
            self.store.layout().addWidget(self.lyricdir, 0, 1)
            self.store.layout().addWidget(QtGui.QLabel('Lyrics filename'), 1, 0)
            self.store.layout().addWidget(self.lyricname, 1, 1)

            self.setLayout(QtGui.QVBoxLayout())
            self.layout().addWidget(self.store)

            self.settings().endGroup()

        def save_settings(self):
            self.settings().beginGroup(self.plugin.name)
            self.settings().setValue('lyricdir', QVariant(self.lyricdir.text()))
            self.settings().setValue('lyricname', QVariant(self.lyricname.text()))
            self.settings().setValue('store', QVariant(self.store.isChecked()))
            self.settings().endGroup()
            self.plugin.refresh()

    def get_settings_widget(self):
        return self.SettingsWidgetLyrics(self)