Source

gSharkDown / gsharkdown.py

  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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
#!/usr/bin/env python
#-*- encoding: utf-8 -*-

"""
Desktop application for downloading and playing songs provided
by the grooveshark.com service
"""

import os
import sys
import random
import time
from lib.tfuncs import t_init
from lib.tfuncs import t_download
from lib.tfuncs import t_play
from lib.tfuncs import t_search
from lib.tfuncs import t_key_listener
import lib.lyrdblib
import locale
import gettext
from gettext import gettext as _
import urllib2
import webbrowser
import pickle

try:
    import pygtk
    pygtk.require('2.0')
    import gtk
    import gobject
except ImportError:
    print "You don't have python-gtk2 installed!"
    sys.exit(1)

try:
    import pynotify
except ImportError:
    print "You don't have pynotify installed!"
    sys.exit(1)

try:
    import pygst
    pygst.require('0.10')
    import gst
except ImportError:
    print "You don't have python-gstreamer installed!"
    sys.exit(1)

try:
    import pylast
except ImportError:
    print "You need to install pylast: sudo pip install pylast"
    sys.exit(1)

try:
    from configobj import ConfigObj
except ImportError:
    print "You don't have python-configobj installed!"
    sys.exit(1)

BASEPATH = os.path.abspath(os.path.dirname(sys.argv[0]))

APP = 'gsharkdown'
if os.path.exists("locale"):
    DIR = "%s/locale" % BASEPATH
else:
    DIR = os.path.join(sys.prefix, 'share', 'locale')

try:
    locale.setlocale(locale.LC_ALL, '')
except locale.Error:
    locale.setlocale(locale.LC_ALL, 'en_US.utf8')
locale.bindtextdomain(APP, DIR)
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
gettext.install(APP, localedir=DIR, unicode=True)

LAST_KEY = "51fd71dc8939360b25a1029e556258a4"
LAST_SECRET = "cf35dd38f998ca4d3af4adbe59ae23f7"

if os.path.exists("%s/.gsharkdown/gsharkdown.ini" % os.environ.get("HOME")):
    CONFIG = ConfigObj("%s/.gsharkdown/gsharkdown.ini" % os.environ.get("HOME"))
    try:
        test = CONFIG['scrobbling']
    except KeyError:
        CONFIG['scrobbling'] = 0
        CONFIG['lastuser'] = ""
        CONFIG['lastpass'] = ""
        CONFIG.write()
else:
    try:
        os.mkdir("%s/.gsharkdown/" % os.environ.get("HOME"))
    except:
        pass
    CONFIG = ConfigObj("%s/.gsharkdown/gsharkdown.ini" % os.environ.get("HOME"))
    CONFIG['down_path'] = os.environ.get("HOME") + "/Music"
    CONFIG['show_stat_icon'] = 0
    CONFIG['repeat_playlist'] = 1
    CONFIG['shuffle_playlist'] = 0
    CONFIG['show_notification'] = 0
    CONFIG['update_checked'] = 0
    CONFIG['completition'] = ""
    CONFIG['scrobbling'] = 0
    CONFIG['lastuser'] = ""
    CONFIG['lastpass'] = ""
    CONFIG.write()


class SharkDown:
    """
    The main application class for gSharkDown
    """
    results = []
    playitems = []
    downloads = []
    working = None
    playing = None

    def __init__(self):
        """
        Initialise the main application window
        """
        gobject.threads_init()
        builder = gtk.Builder()
        builder.set_translation_domain(APP)
        builder.add_from_file('%s/data/main_window.ui' % BASEPATH)
        self.window = builder.get_object('window1')
        self.window.connect('delete-event', self.window_close)
        self.windowstate = 1
        self.progress_bar = builder.get_object('progressbar1')
        self.play_button = builder.get_object('toolbutton3')
        self.ff_button = builder.get_object('toolbutton9')
        self.prev_button = builder.get_object('toolbutton14')
        self.songinfo = builder.get_object('songinfo')
        self.songinfo.set_text("")
        repeat_button = builder.get_object('togglebutton1')
        repeat_button.set_active(int(CONFIG['repeat_playlist']))
        shuffle_button = builder.get_object('togglebutton2')
        shuffle_button.set_active(int(CONFIG['shuffle_playlist']))
        self.player = gst.element_factory_make("playbin", "player")

        # Completition configuration
        self.entry = builder.get_object('entry1')
        completition = gtk.EntryCompletion()
        comp_store = gtk.ListStore(str)
        completition.set_model(comp_store)
        for item in CONFIG['completition'].split("|"):
            comp_store.append([item])
        completition.set_minimum_key_length(1)
        completition.set_text_column(0)
        self.entry.set_completion(completition)
        # Results List definition
        self.result = gtk.ListStore(str, str, str, str)
        self.result_view = builder.get_object('treeview1')
        self.result_view.set_model(self.result)
        self.result_view.connect("row-activated", self.add_and_play_result)
        self._create_search_columns()

        # Play List definition
        self.playlist = gtk.ListStore(str, str, str)
        self.play_view = builder.get_object('treeview2')
        self.play_view.set_model(self.playlist)
        #self.play_view.connect('row-activated', self.double_click_start)
        self._create_play_columns()
        self.selector = self.play_view.get_selection()

        self.staticon = gtk.StatusIcon()
        self.staticon.set_from_file("%s/data/gsharkdown_16.png" % BASEPATH)
        self.staticon.connect("popup-menu", self.right_click_event)
        self.staticon.connect("activate", self.icon_clicked)
        self.staticon.set_tooltip(_("gSharkDown : Download from Grooveshark"))

        if os.path.exists("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME")):
            self.load_saved_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
        else:
            print "Playlist not found"

        if int(CONFIG['show_notification']) == 1:
            pynotify.init("gSharkDown")
        
        # Scrobbling initialisation
        self.lastfm = ""
        if int(CONFIG['scrobbling']) == 1:
            self.lastfm = pylast.LastFMNetwork(api_key=LAST_KEY,
                                          api_secret=LAST_SECRET,
                                          username=CONFIG['lastuser'],
                                          password_hash=CONFIG['lastpass'])

        builder.connect_signals(self)
        self.tlisten = t_key_listener(self)
        self.tlisten.start()
        self.check_for_update(None)
        self.window.show_all()

    def load_saved_playlist(self, path):
        file = open(path, 'rb')
        eoferror = True
        while eoferror:
            try:
                self.playitems.append(pickle.load(file))
            except:
                eoferror = False

        for i in range(0, len(self.playitems)):
            self.playlist.append([
                self.playitems[i]['SongName'],
                self.playitems[i]['ArtistName'],
                self.playitems[i]['SongID']
                ])
    def save_playlist(self, path):
        try:
            output = open(path, 'w')
            for i in range(0, len(self.playitems)):
                pickle.dump(self.playitems[i], output)
            output.close()
        except:
            self.show_error(_("Error saving the playlist"))


    def save_as_playlist(self, widget, data=None):
        savedlg = gtk.FileChooserDialog(_("Save playlist to file"),
                                       None,
                                       gtk.FILE_CHOOSER_ACTION_SAVE,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        response = savedlg.run()

        if response == gtk.RESPONSE_OK:
            filename = savedlg.get_filename()
            if filename[-4:] != ".pkl":
                filename += ".pkl"
            self.save_playlist(filename)
        savedlg.destroy()

    def open_saved_playlist(self, widget, data=None):
        opendlg = gtk.FileChooserDialog(_("Select Playlist to open"),
                                       None,
                                       gtk.FILE_CHOOSER_ACTION_OPEN,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        openfilter = gtk.FileFilter()
        openfilter.set_name(_('Playlist files'))
        openfilter.add_pattern("*.pkl")

        opendlg.add_filter(openfilter)

        response = opendlg.run()

        if response == gtk.RESPONSE_OK:
            self.playlist.clear()
            self.playitems = []
            self.playing = None
            self.load_saved_playlist(opendlg.get_filename())
        opendlg.destroy()

    def window_close(self, widget, data=None):
        """
        How to act on closing the window
        """
        if int(CONFIG['show_stat_icon']) == 0:
            self.window.hide_on_delete()
            self.windowstate = 0
            return True
        else:
            gtk.main_quit()

    def right_click_event(self, icon, button, time):
        """
        Handler for right clicking on the statusicon
        """
        menu = gtk.Menu()

        about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about.connect("activate", self.show_about)
        prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        prefs.connect("activate", self.edit_preferences)
        playbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PLAY)
        playbut.connect("activate", self.play_selected)
        prebut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_PREVIOUS)
        prebut.connect("activate", self.play_previous)
        ffbut = gtk.ImageMenuItem(gtk.STOCK_MEDIA_NEXT)
        ffbut.connect("activate", self.play_next)

        updimg = gtk.Image()
        updimg.set_from_icon_name('system-software-update',
                                 gtk.ICON_SIZE_MENU)
        updbut = gtk.ImageMenuItem(_("Check for update"))
        updbut.set_image(updimg)
        updbut.connect("activate", self.check_for_update)
        quiter = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        quiter.connect("activate", self.quit_app)

        menu.append(prebut)
        menu.append(playbut)
        menu.append(ffbut)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(about)
        menu.append(updbut)
        menu.append(prefs)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(quiter)
        menu.show_all()

        menu.popup(None, None, gtk.status_icon_position_menu,
                  button, time, icon)

    def check_for_update(self, widget, data=None):
        local = open('%s/VERSION' % BASEPATH, 'r')
        localversion = local.read().replace("\n", "")
        checkurl = 'http://bitbucket.org/vkolev/gsharkdown/raw/tip/VERSION'
        remote = urllib2.urlopen(checkurl)
        remoteversion = remote.read().replace("\n", "")
        if remoteversion > localversion:
            CONFIG['update_checked'] = 0
            CONFIG.write()
            upddiag = gtk.MessageDialog(None,
                                       gtk.DIALOG_DESTROY_WITH_PARENT,
                                       gtk.MESSAGE_INFO)
            upddiag.set_title(_("New update"))
            othertext = _("To update to the latest version click on the button ")
            othertext += _("'Update'\nand download it. After that you can ")
            othertext += _("remove the old one and install the new gSharkDown")
            markup = _("<b>New version <i>%s</i> is available</b>")
            upddiag.set_markup(markup % remoteversion)
            upddiag.format_secondary_text(othertext)
            upddiag.add_buttons(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL,
                                gtk.STOCK_EXECUTE, gtk.RESPONSE_OK)
            if upddiag.run() == gtk.RESPONSE_OK:
                downurl = "http://bitbucket.org/vkolev/gsharkdown/downloads"
                webbrowser.open(downurl)
            upddiag.destroy()
        else:
            if int(CONFIG['update_checked']) == 1:
                pass
            else:
                upddiag = gtk.MessageDialog(None,
                                       gtk.DIALOG_DESTROY_WITH_PARENT,
                                       gtk.MESSAGE_INFO)
                upddiag.set_title(_("No updates"))
                othertext = _("Congratulations!\n")
                markup = _("<b>You are using the latest version!</b>")
                upddiag.set_markup(markup)
                upddiag.format_secondary_text(othertext)
                upddiag.add_buttons(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL,
                               gtk.STOCK_OK, gtk.RESPONSE_OK)
                CONFIG['update_checked'] = 1
                CONFIG.write()
                upddiag.run()
                upddiag.destroy()

    def icon_clicked(self, widget, data=None):
        """
        Executed on left clicking the statusicon
        """
        if(self.windowstate == 0):
            self.window.show_all()
            self.windowstate = 1
        else:
            self.window.hide_on_delete()
            self.windowstate = 0
            return True

    def _create_search_columns(self):
        """
        Generate the TreeView columns in the main window
        for the search results
        """
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Title"), rendererText, text=0)
        column.set_max_width(180)
        self.result_view.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Artist"), rendererText, text=1)
        column.set_max_width(100)
        self.result_view.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Album"), rendererText, text=2)
        column.set_max_width(150)
        self.result_view.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("SongID"), rendererText, text=3)
        column.set_max_width(50)
        self.result_view.append_column(column)

    def _create_play_columns(self):
        """
        Generate the TreeView columns in the main window
        for the playlist items
        """
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Title"), rendererText, text=0)
        column.set_max_width(180)
        self.play_view.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Artist"), rendererText, text=1)
        column.set_max_width(100)
        self.play_view.append_column(column)

        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("SongID"), rendererText, text=2)
        column.set_max_width(50)
        self.play_view.append_column(column)

    def quit_app(self, widget, data=None):
        """
        Confirmation dialog when exiting the application
        """
        dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                  type=gtk.MESSAGE_QUESTION,
                                  buttons=gtk.BUTTONS_YES_NO,
                                  message_format=_("Are you sure to quit?"))
        dialog.set_title(_("Quit?"))
        response = dialog.run()
        if response == gtk.RESPONSE_YES:
            self.save_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
            gtk.main_quit()
        dialog.destroy()

    def copy_song(self, widget, data=None):
        """
        Copy the selected song name from the results list in the
        GNOME Clipboard
        """
        select = self.result_view.get_selection().get_selected()
        if select[1] != None:
            index = self.result.get_path(select[1])[0]
            song = self.results[index]
            copystring = "%s - %s" % (song['ArtistName'], song['SongName'])
            clipboard = gtk.clipboard_get()
            clipboard.set_text(copystring)
            clipboard.store()

    def add_to_playlist(self, widget, data=None):
        """
        Adds selected item from the results to the playlist
        """
        select = self.result_view.get_selection().get_selected()
        if select[1] != None:
            index = self.result.get_path(select[1])[0]
            song = self.results[index]
            self.playitems.append(song)
            self.playlist.append([song['SongName'],
                                  song['ArtistName'],
                                  song['SongID']])

    def remove_from_playlist(self, widget, data=None):
        """
        Removes an item from the playlist and the playitems list
        """
        select = self.play_view.get_selection().get_selected()
        if select[1] != None:
            path = self.playlist.get_path(select[1])
            seliter = self.playlist.get_iter(path)
            self.playlist.remove(seliter)
            self.playitems.pop(path[0])

    def clear_playlist(self, widget, data=None):
        """
        Removes all items from the playlist
        """
        self.playlist.clear()
        self.playitems = []
        self.playing = None

    def toggle_repeat(self, widget, data=None):
        """
        Toggles the configuration option for looping trough the
        playlist
        """
        CONFIG['repeat_playlist'] = int(widget.get_active())
        CONFIG.write()

    def toggle_shuffle(self, widget, data=None):
        """
        Toggle the configuration option for shuffleing the playlist
        """
        CONFIG['shuffle_playlist'] = int(widget.get_active())
        CONFIG.write()

    def double_click_start(self, path, column, data=None):
        self.player.set_state(gst.STATE_NULL)
        self.play_button.set_stock_id(gtk.STOCK_MEDIA_STOP)
        song = self.playitems[column[0]]
        self.set_songinfos(song)
        t = t_play(self, song, int(CONFIG['repeat_playlist']), self.lastfm)
        t.start()

    def add_and_play_result(self, path, column, data=None):
        song = self.results[column[0]]
        self.playitems.append(song)
        self.playlist.append([song['SongName'],
                            song['ArtistName'],
                            song['SongID']])
        if self.playing == None:
            self.playing = len(self.playitems) - 2
        self.play_next(self.ff_button)

    def play_next(self, widget, data=None):
        """
        Plays the next item from the playlist
        """
        if self.playing == None:
            self.play_selected(self.play_button)
        else:
            index = self.playing + 1
            if int(CONFIG['shuffle_playlist']) == 1:
                index = random.randint(0, len(self.playitems))

            if index >= len(self.playitems):
                if int(CONFIG['repeat_playlist']) == 1:
                    self.player.set_state(gst.STATE_NULL)
                    self.playing = None
                    self.play_selected(self.play_button)
                else:
                    self.player.set_state(gst.STATE_NULL)
                    self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
                    self.playing = None
                    self.set_songinfos()
            else:
                self.playing = index
                self.player.set_state(gst.STATE_NULL)
                song = self.playitems[index]
                self.set_songinfos(song)
                t = t_play(self, song,
                           int(CONFIG['repeat_playlist']),
                           self.lastfm)
                t.start()

    def play_previous(self, widget, data=None):
        """
        Plays the previous song from the playlist
        """
        if self.playing == None:
            self.play_selected(self.play_button)
        else:
            index = self.playing - 1
            if int(CONFIG['shuffle_playlist']) == 1:
                index = random.randint(0, len(self.playitems))

            if index < 0:
                if int(CONFIG['repeat_playlist']) == 1:
                    self.playing = len(self.playitems) - 1
                    self.player.set_state(gst.STATE_NULL)
                    song = self.playitems[len(self.playitems) - 1]
                    self.set_songinfos(song)
                    t = t_play(self, song,
                               int(CONFIG['repeat_playlist']),
                              self.lastfm)
                    t.start()
                else:
                    self.player.set_state(gst.STATE_NULL)
                    self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
                    self.playing = None
                    self.set_songinfos()
            else:
                self.playing = index
                self.player.set_state(gst.STATE_NULL)
                song = self.playitems[index]
                self.set_songinfos(song)
                t = t_play(self, song,
                           int(CONFIG['repeat_playlist']),
                          self.lastfm)
                t.start()

    def on_volume_change(self, widget, data=0.5):
        """
        Volume change handler
        """
        self.player.set_property("volume", float(data))
        return True

    def show_info(self, widget, data=None):
        """
        Song infromation dialog for item selected from the search results
        """
        select = self.result_view.get_selection().get_selected()
        if select[1] != None:
            index = self.result.get_path(select[1])[0]
            song = self.results[index]
            dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
                                      0, gtk.BUTTONS_OK,)
            dialog.set_title(_("Song Information - {songid}").format(songid=song['SongID']))
            _filename = _("<b>Filename:</b> {artist} - {title}.mp3\n").format(artist=song['ArtistName'],
                                                       title=song['SongName'])
            _artist = _("<b>Artist:</b> {artist}\n").format(artist=song['ArtistName'])
            _title = _("<b>Title:</b> {title}\n").format(title=song['SongName'])
            _duration = "%.2f" % (float(song['EstimateDuration']) / 60)
            _duration = _("<b>Duration:</b> {mins}:{secs} min\n").format(mins=_duration.split(".")[0],
                                                      secs=_duration.split(".")[1])
            _album = _("<b>Album:</b> {album}\n").format(album=song['AlbumName'])
            _year = _("<b>Year:</b> {year}\n").format(year=song['Year'])
            info = _filename + _artist + _title + _duration + _album + _year
            image = gtk.Image()
            try:
                url = "http://beta.grooveshark.com/static/amazonart/s%s"
                response = urllib2.urlopen(url % song['CoverArtFilename'])
                loader = gtk.gdk.PixbufLoader()
                loader.write(response.read())
                loader.close()
                image.set_from_pixbuf(loader.get_pixbuf())
                dialog.set_image(image)
            except:
                pass
            dialog.set_markup(info)
            dialog.show_all()
            dialog.run()
            dialog.destroy()

    def get_lyrics(self, widget, data=None):
        """
        Tries to retrieve lyrics for selected song from the playlist
        """
        select = self.play_view.get_selection().get_selected()
        if select[1] != None:
            index = self.playlist.get_path(select[1])[0]
            song = self.playitems[index]
            lyric = lib.lyrdblib.search(song['ArtistName'],
                                         song['SongName'])
            if "ERROR" in lyric:
                self.show_error(lyric)
            else:
                builder = gtk.Builder()
                builder.set_translation_domain(APP)
                builder.add_from_file('%s/data/lyrics_dialog.ui' % BASEPATH)
                lyrics = builder.get_object('dialog1')
                songlabel = builder.get_object('label2')
                songlabel.set_text(song['ArtistName'] + " - " + song['SongName'])
                lyric_view = builder.get_object('textview1')
                lyric_buff = lyric_view.get_buffer()
                lyric_buff.set_text(lyric)
                lyrics.add_buttons(gtk.STOCK_OK, gtk.RESPONSE_OK)
                lyrics.run()
                lyrics.destroy()

    def show_about(self, widget, data=None):
        """
        About dialog for the application
        """
        builder = gtk.Builder()
        builder.set_translation_domain(APP)
        builder.add_from_file('%s/data/about_dialog.ui' % BASEPATH)
        flattr = builder.get_object('flattrbut')
        flattr.connect("clicked", self.flattr_this)
        updbtn = builder.get_object('updatbut')
        updbtn.connect("clicked", self.check_for_update)
        about = builder.get_object('aboutdialog1')
        about.run()
        about.destroy()

    def flattr_this(self, widget, data=None):
        """
        Opens the flattr page for gSharkDown
        """
        webbrowser.open("http://flattr.com/thing/275401/gSharkDown")

    def edit_preferences(self, widget, data=None):
        """
        Preferences dialog with save and close buttons
        """
        builder = gtk.Builder()
        builder.set_translation_domain(APP)
        builder.add_from_file('%s/data/preferenes_dialog.ui' % BASEPATH)
        self.prefs = builder.get_object('window1')
        self.dest = builder.get_object('entry1')
        if CONFIG['down_path'] == "":
            self.dest.set_text(os.environ.get('HOME') + "/Music")
        else:
            self.dest.set_text(CONFIG['down_path'])
        self.notify = builder.get_object("checkbutton1")
        self.notify.set_active(int(CONFIG['show_stat_icon']))
        self.bubble = builder.get_object("checkbutton2")
        self.bubble.set_active(int(CONFIG['show_notification']))
        self.lastuser = builder.get_object("entry2")
        self.lastuser.set_text(CONFIG['lastuser'])
        self.lastpass = builder.get_object("entry3")
        self.lastpass.set_visibility(False)
        self.lastpass.set_text(CONFIG['lastpass'])
        self.scrobble = builder.get_object("checkbutton3")
        self.scrobble.set_active(int(CONFIG['scrobbling']))
        self.lastuser.set_sensitive(self.scrobble.get_active())
        self.lastpass.set_sensitive(self.scrobble.get_active())
        builder.connect_signals(self)
        self.prefs.show_all()

    def select_destination(self, widget, data=None):
        """
        Handler for the Select button from the Preferences dialog
        """
        chooser = gtk.FileChooserDialog(_("Select destination directory"),
                                       None,
                                        gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        response = chooser.run()
        if response == gtk.RESPONSE_ACCEPT:
            self.dest.set_text(chooser.get_filename())
        else:
            chooser.destroy()
        chooser.destroy()

    def on_scrobble_toggle(self, widget, data=None):
        self.lastuser.set_sensitive(widget.get_active())
        self.lastpass.set_sensitive(widget.get_active())

    def save_preferences(self, widget, data=None):
        """
        Saves the information from the Preferences dialog in the
        configuration file
        """
        CONFIG['down_path'] = self.dest.get_text()
        if self.notify.get_active():
            CONFIG['show_stat_icon'] = 1
        else:
            CONFIG['show_stat_icon'] = 0

        if self.bubble.get_active():
            CONFIG['show_notification'] = 1
        else:
            CONFIG['show_notification'] = 0

        if self.scrobble.get_active():
            CONFIG['scrobbling'] = 1
            CONFIG['lastuser'] = self.lastuser.get_text()
            CONFIG['lastpass'] = pylast.md5(self.lastpass.get_text())
            self.lastfm = pylast.LastFMNetwork(api_key=LAST_KEY,
                                          api_secret=LAST_SECRET,
                                          username=CONFIG['lastuser'],
                                          password_hash=CONFIG['lastpass'])

        else:
            CONFIG['scrobbling'] = 0
        CONFIG.write()
        self.prefs.destroy()

    def close_preferences(self, widget, data=None):
        """
        Closes the Preferences dialog discarding any changes
        """
        self.prefs.destroy()

    def search_grooveshark(self, widget, data=None):
        """
        Starts the search thread
        """
        if widget.get_text() == "":
            pass
        else:
            if widget.get_text() in CONFIG['completition'].split("|"):
                pass
            else:
                compl = CONFIG['completition'] + widget.get_text() + "|"
                CONFIG['completition'] = compl
                CONFIG.write()
            search_thread = t_search(self, widget.get_text(), "Songs")
            search_thread.run()

    def play_selected(self, widget, data=None, row=None):
        """
        Starts the play thread
        """
        if self.playing == None:
            if self.playlist.iter_n_children(None) <= 0:
                pass
            else:
                song = self.playitems[0]
                self.set_songinfos(song)
                self.playing = 0
                t = t_play(self, song, int(CONFIG['repeat_playlist']),
                          self.lastfm)
                t.start()
        else:
            self.player.set_state(gst.STATE_NULL)
            self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
            self.playing = None
            self.set_songinfos()

    def set_songinfos(self, song=None):
        """
        Updates some labels and icons when a song is playing
        """
        if song != None:
            if self.playing == None:
                self.playing = 0
            treerow = self.playlist.iter_nth_child(None, self.playing)
            self.selector.select_iter(treerow)
            self.staticon.set_from_file(
                "%s/data/gsharkdown_16_playing.png" % BASEPATH
            )
            self.staticon.set_tooltip(
                _("Playing: {artist} - {title}").format(artist=song['ArtistName'],
                                                        title=song['SongName'])
            )
            self.songinfo.set_markup(
                _("<b>Playing:</b> {artist} - {title}").format(artist=song['ArtistName'],
                                         title=song['SongName'])
            )
            if int(CONFIG['show_notification']) == 1:
                n = pynotify.Notification(_("Now playing"),
                    "%s - %s" % (song['ArtistName'], song['SongName']),
                    "audio-x-generic")
                n.show()
        else:
            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % BASEPATH)
            self.staticon.set_tooltip(
                _("gSharkDown: GrooveShark Downloader")
            )
            self.selector.unselect_all()
            self.songinfo.set_markup("")

    def download_selected(self, widget, data=None):
        """
        Starts the download thread
        """
        select = self.result_view.get_selection().get_selected()
        if select[1] != None:
            index = self.result.get_path(select[1])[0]
            song = self.results[index]
            filename = "%s - %s.mp3" % (song["ArtistName"].strip("<>:\"/\|?*"),
                                    song["SongName"].strip("<>:\"/\|?*"))
            if CONFIG['down_path'] == "":
                CONFIG['down_path'] = os.environ.get("HOME") + "/Music"
            t = t_download(self, song, filename, CONFIG['down_path'])
            t.start()
        else:
            pass

    def show_error(self, error):
        """
        Displays an error message when error with groove.py
        """
        dialog = gtk.MessageDialog(None,
                                  gtk.DIALOG_DESTROY_WITH_PARENT,
                                  gtk.MESSAGE_ERROR,
                                  gtk.BUTTONS_CLOSE, error)
        dialog.run()
        dialog.destroy()

    def get_stream_url(self):
        """
        Not used at the momment
        """
        pass

if __name__ == "__main__":
    app = SharkDown()
    init_thread = t_init(app)
    init_thread.run()
    gtk.main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.