Source

lyrcl-rhythmbox / __init__.py

Full commit
  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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# -*- Mode: python; coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
#
# Copyright (C) 2011 Rhys Adams
# Based on official Lyrics plugin, Copyright (C) 2006 Jonathan Matthew
#                                  Copyright (C) 2007 James Livingston
#                                  Copyright (C) 2007 Sirio Bolaños Puchet
#
# This program 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, or (at your option)
# any later version.
#
# The Rhythmbox authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distributed together with GStreamer
# and Rhythmbox. This permission is above and beyond the permissions granted
# by the GPL license by which Rhythmbox is covered. If you modify this code
# you may extend this exception to your version of the code, but you are not
# obligated to do so. If you do not wish to do so, delete this exception
# statement from your version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.
#

from __future__ import with_statement

import os, re, urllib, webbrowser
import gtk, gio
#import gconf
import rhythmdb, rb

import LyricsParse
from cachedProperty import cachedProperty

ui_str = """
<ui>
  <menubar name="MenuBar">
    <menu name="ViewMenu" action="View">
      <menuitem name="LyrclViewSongLyrics" action="LyrclViewSongLyrics"/>
    </menu>
  </menubar>
  <toolbar name="ToolBar">
    <toolitem name="LyrclViewSidebar" action="LyrclViewSidebar" />
  </toolbar>
</ui>
"""

#LYRIC_TITLE_STRIP=["\(live[^\)]*\)", "\(acoustic[^\)]*\)", "\([^\)]*mix\)", "\([^\)]*version\)", "\([^\)]*edit\)", "\(feat[^\)]*\)"]
LYRIC_TITLE_REPLACE=[("/", "-"), (" & ", " and ")]
LYRIC_ARTIST_REPLACE=[("/", "-"), (" & ", " and ")]
STREAM_SONG_TITLE='rb:stream-song-title'

#gconf_keys = {'folder': '/apps/rhythmbox/plugins/lyrcl/folder'}

class CurrentSong(object):
    def __init__(self, db):
        self.db = db
        self.clear()

    def clear(self):
        self.entry = None
        del self.artist_title
        del self.cache_path
        self.lyrics = None # Only !None if acquired valid lyrics

    def refresh(self, entry):
        self.clear()
        self.entry = entry
        if self.artist and self.title:
            print "Determined song is \"%s\" by \"%s\"." % (self.title, self.artist)
            print "Cache path is \"%s\"." % self.cache_path

    artist = property(lambda self: self.artist_title[0])
    title = property(lambda self: self.artist_title[1])

    @cachedProperty
    def artist_title(self):
        artist = self.db.entry_get(self.entry, rhythmdb.PROP_ARTIST)
        title = self.db.entry_get(self.entry, rhythmdb.PROP_TITLE)
        if artist and title:
            return artist, title
        else:
            print "Couldn't determine artist/title from db: examining stream title..."
            stream_song_title = self.db.entry_request_extra_metadata(self.entry, STREAM_SONG_TITLE)
            details = stream_song_title.split('-')
            if len(details) > 1:
                return details[0].strip(), details[1].strip()
            else:
                details = stream_song_title.split('(')
                if len(details) > 1:
                    return details[1].strip(') '), details[0].strip()
                else:
                    print "I can't figure out what the artist/title is. ;_;"
                    return None, None

    @cachedProperty
    def cache_path(self):
        # Can't determine the path without an artist and title
        if not self.artist or not self.title:
            return None

        # convert to lowercase
        artist = self.artist.lower()
        title = self.title.lower()

        # replace ampersands and the like
        for exp in LYRIC_ARTIST_REPLACE:
            artist = re.sub(exp[0], exp[1], artist)
        for exp in LYRIC_TITLE_REPLACE:
            title = re.sub(exp[0], exp[1], title)

        # compress spaces
        title = title.strip()
        artist = artist.strip()

        lyrics_folder = os.path.expanduser(os.path.join(rb.user_cache_dir(), "lyrcl"))
        if not os.path.exists(lyrics_folder):
            os.mkdir(lyrics_folder)

        artist_folder = os.path.join(lyrics_folder, artist[:128])
        if not os.path.exists(artist_folder):
            os.mkdir(artist_folder)

        cache_path = os.path.join(artist_folder, title[:128] + '.lyric')
        return cache_path

    def __lyric_callback_file(self, text): # came from cache file
        if text != None:
            # I'm forced to trust a file request (via rb.Loader().get_url()) to be fast
            # enough not to back-up when using the Next and Previous buttons on the    
            # Properties dialog, because the request won't pass extra stuff back AFAIK.
            # I have yet to see a request slow enough to cause problems.
            self.lyrics = text
            self.callback(self.lyrics)
        else:   # shouldn't happen; only when cache file not found (BAD!)
            # this means that a request was made after a refresh() call but before the cache
            # path was generated, which is stupidly unlikely.
            print "Couldn't find cache file. THIS SHOULD NOT HAPPEN."

    def __lyric_callback_web(self, text): # came from web; format is (lyrics, entry)
        if text[1] == self.entry: # request is for current entry
            if text[0]:
                self.lyrics = text[0]

                with open(self.cache_path, 'w') as f:
                    f.write(self.lyrics)
            else: # if lyrics is None, Parse couldn't find the lyrics from the web
                self.lyrics = None

            print "Got from web. Calling back..."
            self.callback(self.lyrics)
        else:
            print "Ignoring old web lyrics request."

    def det_lyrics(self, callback, force_refresh=False):
        print "Obtaining lyrics for %s by %s..." % (self.title, self.artist)
        self.callback = callback

        if not self.artist or not self.title:
            self.lyrics = None
            print "Calling back with error..."
            callback(self.lyrics)
        elif not force_refresh and os.path.exists(self.cache_path):
            l = rb.Loader()
            l.get_url(self.cache_path, self.__lyric_callback_file)
        else:
            parser = LyricsParse.Parser(self.artist, self.title, self.entry)
            parser.get_lyrics(self.__lyric_callback_web)

class LyricsShowyThing(object):
    '''
    Template. Subclass and define self.c_song and self.buffer
    Make sure prep_buttons is called.
    '''

    def __init__(self):
        self.has_lyrics = False

    def __got_lyrics(self, lyrics):
        if lyrics:
            self.edit.props.label = '_Edit'
            self.edit.props.sensitive = True
            self.buffer.props.text = lyrics
            self.has_lyrics = True
        elif self.c_song.artist and self.c_song.title:
            self.edit.props.label = '_Add'
            self.edit.props.sensitive = True
            self.buffer.props.text = 'Lyrics not found.'
            self.has_lyrics = False
        else:
            self.edit.props.label = '_Edit'
            self.edit.props.sensitive = False
            self.buffer.props.text = 'Could not determine artist and title.'
            self.has_lyrics = False

    def get_lyrics(self, force_refresh=False):
        self.edit.props.sensitive = False
        self.buffer.props.text = _('Searching for lyrics...')
        self.c_song.det_lyrics(self.__got_lyrics, force_refresh=force_refresh)

    def edit_callback(self, widget):
        u = urllib.quote
        if self.has_lyrics:
            webbrowser.open_new('http://www.lyrcl.org/edit/%s:%s' % (
                u(self.c_song.artist), u(self.c_song.title)))
        else:
            webbrowser.open_new('http://www.lyrcl.org/add?artist=%s&song=%s' % (
                u(self.c_song.artist), u(self.c_song.title)))

    def create_lyrics_view(self):
        tview = gtk.TextView()
        tview.props.wrap_mode = gtk.WRAP_WORD
        tview.props.editable = False
        tview.props.left_margin = 6

        tview.props.width_request = 0
        tview.props.height_request = 0
        sw = gtk.ScrolledWindow()
        sw.add(tview)
        sw.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC
        sw.props.hscrollbar_policy = gtk.POLICY_NEVER
        sw.props.shadow_type = gtk.SHADOW_IN

        vbox = gtk.VBox(spacing=12)
        vbox.pack_start(sw, expand=True)
        
        return vbox, tview.get_buffer()

    def prep_buttons(self):       
        self.edit = gtk.Button('_Edit')
        self.edit.props.sensitive = False
        self.edit.connect('clicked', self.edit_callback)

        self.discard = gtk.Button(_("_Search again"))
        self.discard.connect('clicked', lambda w: self.get_lyrics(force_refresh=True))

        hbox = gtk.HButtonBox()
        hbox.props.spacing = 6
        hbox.props.layout_style = gtk.BUTTONBOX_END
        
        hbox.add(self.edit)
        hbox.add(self.discard)
        
        return hbox

class LyricPane(LyricsShowyThing):
    def __init__(self, db, song_info):
        super(self.__class__, self).__init__()
        self.song_info_property = song_info.get_property
        self.c_song = CurrentSong(db)

        hbox = self.prep_buttons()
        view, self.buffer = self.create_lyrics_view()
        view.pack_start(hbox, expand=False, fill=False, padding=6)
        view.props.spacing = 2

        view.show_all()
        
        self.page_num = song_info.append_page("lyrcl", view)
        self.visible = False

        song_info.connect('notify::current-entry', self.entry_changed)
        nb = view.get_parent()
        nb.connect('switch-page', self.switch_page_cb)

    def entry_changed(self, pspec, duh):
        self.c_song.clear()
        if self.visible:
            self.c_song.refresh(self.song_info_property("current-entry"))
            self.get_lyrics()

    def switch_page_cb(self, notebook, page, page_num):
        if page_num == self.page_num:
            self.visible = True
        else:
            self.visible = False

        if not self.c_song.lyrics and self.visible: # check if already have lyrics
            if not self.c_song.entry:
                self.c_song.refresh(self.song_info_property("current-entry"))
            self.get_lyrics()

class LyricWindow(gtk.Window, LyricsShowyThing):
    def __init__(self, db):    
        super(self.__class__, self).__init__()
        self.props.border_width = 12
        
        self.c_song = CurrentSong(db)

        close = gtk.Button(stock=gtk.STOCK_CLOSE)
        close.connect('clicked', lambda w: self.destroy())

        view, self.buffer = self.create_lyrics_view()
        hbox = self.prep_buttons()
        hbox.add(close)
        view.pack_start(hbox, expand=False)

        self.add(view)

        self.props.default_width = 400
        self.props.default_height = 300
        self.show_all()

    def song_changed(self, entry):
        self.c_song.refresh(entry)
        self.props.title = 'lyrcl // ' + self.c_song.artist + ': ' + self.c_song.title
        self.get_lyrics()

class LyricSidebar(LyricsShowyThing):
    def __init__(self, db, shell, playing_entry):
        super(self.__class__, self).__init__()

        self.shell = shell
        self.visible = False
        self.last_looked_for = None
        self.c_song = CurrentSong(db)
        
        buttons = self.prep_buttons()
        buttons.props.spacing = 2
        buttons.props.layout_style = gtk.BUTTONBOX_SPREAD
        self.edit.props.relief = gtk.RELIEF_NONE
        self.discard.props.relief = gtk.RELIEF_NONE
        self.discard.props.sensitive = False

        self.vbox, self.buffer = self.create_lyrics_view()
        self.vbox.pack_start(buttons, expand=False, fill=True)
        self.vbox.props.spacing = 0

        self.vbox.props.width_request = 300
        self.vbox.props.height_request = -1
        self.vbox.show_all()
        
        if playing_entry:
            self.song_changed(playing_entry)

    def get_lyrics(self, *args, **kwargs):
        self.last_looked_for = self.c_song.entry
        return super(self.__class__, self).get_lyrics(*args, **kwargs)

    def song_changed(self, entry):
        self.discard.props.sensitive = True
        self.c_song.refresh(entry)
        if self.visible:
            self.get_lyrics()

    def toggle_visibility(self):
        if self.visible:
            self.shell.remove_widget(self.vbox, rb.SHELL_UI_LOCATION_RIGHT_SIDEBAR)
            self.visible = False
        else:
            self.shell.add_widget(self.vbox, rb.SHELL_UI_LOCATION_RIGHT_SIDEBAR, expand=True)
            self.visible = True
            if self.c_song.entry not in [None, self.last_looked_for]:
                self.get_lyrics()

    def destroy(self):
        self.vbox.destroy()

class LyricsDisplayPlugin(rb.Plugin):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.window = None
        self.sidebar = None

    def activate(self, shell):
        self.action = gtk.Action('LyrclViewSongLyrics', _('Song L_yrics'),
                      _('Display lyrics for the playing song'),
                      None)
        self.activate_id = self.action.connect('activate', self.show_song_lyrics, shell)
        
        self.sidebar_action = gtk.ToggleAction('LyrclViewSidebar', _('Lyrics Sidebar'),
            _('Show/hide the lyrics sidebar'), None)
        self.sidebar_action.props.gicon = gio.FileIcon(gio.File(self.find_file('icon.svg')))
        self.sidebar_action.connect('activate', self.toggle_sidebar, shell)
        
        self.action_group = gtk.ActionGroup('LyrclPluginActions')
        self.action_group.add_action_with_accel(self.action, "<control>L")
        self.action_group.add_action(self.sidebar_action)
        
        uim = shell.get_ui_manager()
        uim.insert_action_group(self.action_group, 0)
        self.ui_id = uim.add_ui_from_string(ui_str)
        uim.ensure_update()

        self.db = shell.get_property("db")

        sp = shell.get_player()
        self.playing_entry = sp.get_playing_entry

        self.ppc_id = sp.connect('playing-song-property-changed', self.playing_property_changed)
        self.pec_id = sp.connect('playing-song-changed', self.playing_entry_changed)
        self.playing_entry_changed(sp, self.playing_entry())

        self.csi_id = shell.connect('create_song_info', self.create_song_info)

    def deactivate(self, shell):
        uim = shell.get_ui_manager()
        uim.remove_ui(self.ui_id)
        uim.remove_action_group(self.action_group)

        self.action_group = None
        self.action = None
        self.sidebar_action = None

        sp = shell.get_player()
        sp.disconnect(self.ppc_id)
        sp.disconnect(self.pec_id)
        shell.disconnect(self.csi_id)

        if self.window is not None:
            self.window.destroy()
            self.window = None

        if self.sidebar is not None:
            self.sidebar.destroy()
            self.sidebar = None

    def song_changed(self, entry):
        if self.window is not None:
            self.window.song_changed(entry)
        if self.sidebar is not None:
            self.sidebar.song_changed(entry)

    def playing_property_changed(self, player, uri, prop, old_val, new_val):
        if (prop == STREAM_SONG_TITLE):
            self.song_changed(self.playing_entry())
    
    def playing_entry_changed(self, sp, entry):
        if entry is not None:
            self.action.props.sensitive = True
            self.song_changed(entry)
        else:
            self.action.props.sensitive = False

    def show_song_lyrics(self, action, shell):
        if self.window is not None:
            self.window.destroy()
            self.window = None

        entry = self.playing_entry()

        if entry is not None:
            self.window = LyricWindow(self.db)
            self.window.connect("destroy", self.window_deleted)
            self.song_changed(entry)

    def window_deleted(self, window):
        print "lyrics window destroyed"
        self.window = None
    
    def create_song_info(self, shell, song_info, is_multiple):
        if is_multiple is False:
            LyricPane(self.db, song_info)

    def toggle_sidebar(self, action, shell):
        if self.sidebar is None:
            self.sidebar = LyricSidebar(self.db, shell, self.playing_entry())
        self.sidebar.toggle_visibility()