summaryrefslogtreecommitdiff
path: root/nephilim/plugins/Lyrics.py
blob: 7eae6463cd20e2cc4d80f3f5e3f337bcb46e960e (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
#
#    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 logging
import socket

from ..plugin import Plugin
from .. import misc

_available_sites = []
try:
    import LyricWiki_client
    _available_sites.append('lyricwiki')
except ImportError:
    pass

class wgLyrics(QtGui.QWidget):
    txtView     = None  # text-object
    p           = None  # plugin
    def __init__(self, p, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.p = p
        self.curLyrics = ''

        self.txtView = QtGui.QTextEdit(self)
        self.txtView.setReadOnly(True)

        self.setLayout(QtGui.QVBoxLayout())
        self.layout().setSpacing(0)
        self.layout().setMargin(0)
        self.layout().addWidget(self.txtView)

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

    def set_lyrics(self, song, lyrics):
        if not song:
            return

        if song != self.p.mpclient().current_song():
            return

        self.txtView.clear()
        if song:
            self.txtView.insertHtml('<b>%s</b>\n<br /><u>%s</u><br />'\
                    '<br />\n\n'%(song.title(), song.artist()))
        else:
            return

        if lyrics:
            self.txtView.insertPlainText(lyrics)
        else:
            self.txtView.insertPlainText('Lyrics not found.')

class Lyrics(Plugin):
    o           = None
    sites       = []
    lyrics_dir  = None
    lyrics_path = None
    DEFAULTS    = {'sites' : ['lyricwiki'], 'lyricdir' : '$musicdir/$songdir',
                   'lyricname' : '.lyrics_nephilim_$artist_$album_$title', 'store' : True}

    def _load(self):
        self.o = wgLyrics(self)
        for site in _available_sites:
            if site in self.settings().value('%s/sites'%self.name()).toStringList():
                self.sites.append(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):
        song = self.mpclient().current_song()
        if not song:
            return self.o.set_lyrics(None, None)

        (self.lyrics_dir, self.lyrics_path) = misc.generate_metadata_path(self.parent(), song,
                                                                          self.settings().value(self.name() + '/lyricdir').toString(),
                                                                          self.settings().value(self.name() + '/lyricname').toString())
        try:
            file   = open(self.lyrics_path, 'r')
            lyrics = file.read().decode('utf-8')
            file.close()
            if lyrics:
                return self.emit(QtCore.SIGNAL('new_lyrics_fetched'), song, lyrics)
        except IOError, e:
            logging.info('Error reading lyrics file: %s.'%e)


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

    def _fetch_lyrics(self, song):
        lyrics = None
        for site in self.sites:
            lyrics = eval('self.fetch_%s(song)'%site)
            if lyrics:
                try:
                    file = open(self.lyrics_path, 'w')
                    file.write(lyrics.encode('utf-8'))
                    file.close()
                except IOError, e:
                    logging.error('Error saving lyrics: %s'%e)
                return self.emit(QtCore.SIGNAL('new_lyrics_fetched'), song, lyrics)

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

    def fetch_lyricwiki(self, song):
        soap = LyricWiki_client.LyricWikiBindingSOAP("http://lyricwiki.org/server.php")
        req  = LyricWiki_client.getSongRequest()
        req.Artist = song.artist().encode('utf-8').decode('iso8859').encode('utf-8')
        req.Song   = song.title().encode('utf-8').decode('iso8859').encode('utf-8')
        try:
            result     = soap.getSong(req).Return.Lyrics.decode('utf-8').encode('iso8859').decode('utf-8')
        except socket.error, e:
            logging.error('Error downloading lyrics from LyricWiki: %s.'%e)
            return None

        return result if result != 'Not found' else 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.o.refresh()

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