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
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
#!/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 dbus
import dbus.service
import dbus.glib
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
from lib.tfuncs import t_lyrics
from lib.tfuncs import t_update
import lib.guihelpers
import locale
import gettext
from gettext import gettext as _
import urllib2
import webbrowser
import pickle

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

try:
    import pynotify
    HAVE_NOTIFY = True
except ImportError:
    print "You don't have pynotify installed!"
    HAVE_NOTIFY = False

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
    HAVE_PYLAST = True
except ImportError:
    print "You need to install pylast: sudo pip install pylast"
    HAVE_PYLAST = False

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:
        if HAVE_PYLAST:
            test= CONFIG['scribbling']
        else:
            raise KeyError()
    except KeyError:
        CONFIG['scrobbling'] = 0
        CONFIG['lastuser'] = ""
        CONFIG['lastpass'] = ""
    try:
        if HAVE_NOTIFY:
            test = CONFIG['show_notification']
        else:
            raise KeyError()
    except KeyError:
        CONFIG['show_notification'] = 0
        
    try:
        test = CONFIG['quit_without_confirmation']
    except KeyError:
        CONFIG['quit_without_confirmation'] = 1
        
    try:
        test = CONFIG['startup_update_check']
    except KeyError:
        CONFIG['startup_update_check'] = 1
    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.path.join(glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC), "Grooveshark")
    if os.path.isdir(CONFIG['down_path']) == False:
        try:
            os.makedirs(CONFIG['down_path'])
        except:
            pass
    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['startup_update_check'] = 1
    CONFIG['quit_without_confirmation'] = 1
    CONFIG.write()


class SharkDown:
    """
    The main application class for gSharkDown
    """
    working = None
    playing = None
    # just to prevend scrobbeling more then once for 
    # track.
    scrobbled = 0
    # Download dictionary in form Filename : Thread
    downqueue = {}

    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('mainwindow')
        self.window.connect('delete-event', self.window_close)
        self.windowstate = 1
        self.current_song = None
        self.play_button = builder.get_object('toolbutton_play')
        self.ff_button = builder.get_object('toolbutton_play_next')
        self.prev_button = builder.get_object('toolbutton_play_previous')
        self.lyrics_button = builder.get_object('toolbutton_lyrics')
        self.songinfo = builder.get_object('songinfo')
        self.songinfo.set_text("")
        self.prefsmenu = builder.get_object('mainmenu')
        repeat_button = builder.get_object('togglebutton_repeat')
        repeat_button.set_active(int(CONFIG['repeat_playlist']))
        shuffle_button = builder.get_object('togglebutton_shuffle')
        shuffle_button.set_active(int(CONFIG['shuffle_playlist']))
        self.player = gst.element_factory_make("playbin", "player")

        # Completition configuration
        self.entry = builder.get_object('toolentry_search')
        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
        # Model: Title, Artist, Album, SongID, Song Array
        self.result = gtk.ListStore(str, str, str, str, object)
        self.result_view = builder.get_object('list_results')
        self.result_view.set_model(self.result)
        self.result_view.connect("row-activated", self.on_result_row_activated)
        self.result_view.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
        self._create_search_columns()

        # Play List definition
        # Model: Title, Artist, SongID, Song Array, Font Weight (bold on playing)
        self.playlist = gtk.ListStore(str, str, str, object, int)
        self.play_view = builder.get_object('list_playlist')
        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()
        
        # Download list definition
        # Model: File Name, SongID, Progress, Size, Thread Object
        self.downloads = gtk.ListStore(str, str, int, str, object)
        self.downloads_view = builder.get_object('list_downloads')
        self.downloads_view.set_model(self.downloads)
        self.downloads_view.hide_all()
        self._create_downloads_columns()
        self.downloads_count = builder.get_object('downloads_count')
        self.downloads_expander = builder.get_object('expander_download')
        self.update_downloads_count()
        self.downmenu = builder.get_object('downloadmenu')

        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 and HAVE_NOTIFY:
            pynotify.init("gSharkDown")
            
        # Set default directory if is empty
        if CONFIG['down_path'] == "":
            CONFIG['down_path'] = os.path.join(glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC), "Grooveshark")
        
        # Scrobbling initialisation
        self.lastfm = ""
        if int(CONFIG['scrobbling']) == 1 and HAVE_PYLAST:
            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()
        if CONFIG['update_checked'] == 0:
            self.check_for_update(None)
        else:
            if CONFIG['startup_update_check'] == 1:
                self.check_for_update(None)
        self.window.show_all()
        self.hide_download_list()
        
    def result_song(self, index):
        return self.result[index][4]
    
    def playlist_song(self, index):
        return self.playlist[index][3]

    def show_prefs_menu(self, button, data=None):
        self.prefsmenu.popup(None, None, None, 0, 0)
    
    def add_song_to_playlist(self, song):
        self.playlist.append([
            song['SongName'],
            song['ArtistName'],
            song['SongID'],
            song,
            400
        ])

    def load_saved_playlist(self, path):
        """
        Loads the saved playlist from .pkl file
        """
        file = open(path, 'rb')
        eoferror = True
        playitems = []
        
        while eoferror:
            try:
                playitems.append(pickle.load(file))
            except:
                eoferror = False

        for i in range(0, len(playitems)):
            self.add_song_to_playlist(playitems[i])
                
    def save_playlist(self, path):
        """
        Saves the playlist from the playlist treeview to 
        /home/$USER/.gsharkdown/playlist.pkl
        """
        try:
            output = open(path, 'w')
            for i in range(0, len(self.playlist)):
                pickle.dump(self.playlist_song(i), output)
            output.close()
        except:
            error = lib.guihelpers.ErrorMessage(None,
                            _("Error saving the playlist"))
            error.show_all()


    def save_as_playlist(self, widget, data=None):
        """
        Saves the playlist to .pkl file in directory
        choosen from the user
        """
        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):
        """
        Opens a usersaved playlist from .pkl file
        """
        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.stop_play()
            self.load_saved_playlist(opendlg.get_filename())
            self.play_by_index(0)
        opendlg.destroy()

    def window_close(self, widget, data=None):
        """
        Closes the main window
        """
        self.window.hide_on_delete()
        self.windowstate = 0
        return True

    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):
        """
        Checks if a new version of the application is available
        on the application website. NEVER change the VERSION file
        manually!
        """
        othertext = _("To update to the latest version ")
        othertext += _("you can visit the <a href=\"http://https://bitbucket.org/vkolev/gsharkdown/downloads\"> ")
        othertext += _("download site</a>. If you are using the latest version and whant to be")
        othertext += _("informed about new versions, just enable the option in the <b>Preferences</b> dialog.")
        markup = _("<b>New version <span fgcolor=\"red\"><i>%s</i></span> is available</b>")
        nmarkup = _("<b>You are using the latest version!</b>")
        CONFIG['update_checked'] = 1
        CONFIG.write()
        t = t_update(BASEPATH, markup, nmarkup, othertext)
        t.start()

    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.add_attribute(rendererText, 'weight', 4)
        column.set_max_width(180)
        self.play_view.append_column(column)

        column = gtk.TreeViewColumn(_("Artist"), rendererText, text=1)
        column.add_attribute(rendererText, 'weight', 4)
        column.set_max_width(100)
        self.play_view.append_column(column)

        column = gtk.TreeViewColumn(_("SongID"), rendererText, text=2)
        column.add_attribute(rendererText, 'weight', 4)
        column.set_max_width(50)
        self.play_view.append_column(column)
        
    def _create_downloads_columns(self):
        """
        Generate the TreeView columns in the main window
        for the download list items
        """
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("File name"), rendererText, text=0)
        column.set_max_width(250)
        self.downloads_view.append_column(column)
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("SongID"), rendererText, text=1)
        column.set_max_width(80)
        self.downloads_view.append_column(column)
        
        rendererProgress = gtk.CellRendererProgress()
        column = gtk.TreeViewColumn(_("Download progress"), rendererProgress, value=2)
        column.set_max_width(400)
        self.downloads_view.append_column(column)
        
        rendererText = gtk.CellRendererText()
        column = gtk.TreeViewColumn(_("Size"), rendererText, text=3)
        column.set_max_width(100)
        self.downloads_view.append_column(column)

    def quit_app(self, widget, data=None):
        """
        Confirmation dialog when exiting the application
        """
        if CONFIG['quit_without_confirmation'] == '0':
            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()
            dialog.destroy()
        else:
            response = gtk.RESPONSE_YES
        
        if response == gtk.RESPONSE_YES:
            self.save_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
            self.cancel_all_downloads()
            gtk.main_quit()

    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_rows()
        if self.result_view.get_selection().count_selected_rows() > 0:
            song = self.result_song(select[1][0])
            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_rows()
        for item in select[1]:
            song = self.result_song(item[0])
            
            self.add_song_to_playlist(song)

    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:
            next = self.playlist.iter_next(select[1])
            self.playlist.remove(select[1])
            if self.playlist.get_path(select[1])[0] == self.playing:
                self.stop_play()
            if next != None:
                self.play_view.get_selection().select_iter(next)

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

    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):
        """
        Starts playling on double click event on the playlist
        treeview.
        """
        self.play_by_index(column[0])

    def on_result_row_activated(self, path, column, data=None):
        """
        On double click in the search treeview the item is added to 
        the playlist and starts playling.
        """
        song = self.result_song(column[0])
        self.add_song_to_playlist(song)

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

            if index >= len(self.playlist):
                if int(CONFIG['repeat_playlist']) == 1:
                    self.play_by_index(0)
                else:
                    self.stop_play()
            else:
                self.play_by_index(index)

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

            if index < 0:
                if int(CONFIG['repeat_playlist']) == 1:
                    self.play_by_index(len(self.playlist) - 1)
                else:
                    self.play_by_index(0)
            else:
                self.play_by_index(index)

    def play_by_index(self, index):
        """
        Start the play by an index on playlist.
        """
        if index < 0:
            index = 0

        if index >= len(self.playlist):
            index = len(self.playlist)-1

        if index != self.playing:
            self.scrobbled = 0
            self.playing = index
            for item in self.playlist:
                item[4] = 400
            self.playlist[index][4] = 600
            self.player.set_state(gst.STATE_NULL)
            song = self.playlist_song(index)
            self.set_songinfos(song)
            t = t_play(self, song,
                       int(CONFIG['repeat_playlist']),
                      self.lastfm)
            t.start()
            
    def stop_play(self):
        """
        Stop current playing
        """
        for item in self.playlist:
            item[4] = 400
        self.player.set_state(gst.STATE_NULL)
        self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
        self.playing = None
        self.set_songinfos()

    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 first item selected from the search results.
        """
        select = self.result_view.get_selection().get_selected_rows()
        if self.result_view.get_selection().count_selected_rows() > 0:
            song = self.result_song(select[1][0])
            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.playlist_song(index);
            t = t_lyrics(self, '%s/data/lyrics_dialog.ui' % BASEPATH,
                        song['ArtistName'], song['SongName'])
            t.start()
            #lyric = lib.lyrdblib.search(song['ArtistName'],
            #                             song['SongName'])

    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('filechooserbutton1')
        self.dest.set_filename(CONFIG['down_path'])
        self.quit_without_confirmation = builder.get_object("checkbutton1")
        self.quit_without_confirmation.set_active(int(CONFIG['quit_without_confirmation']))
        self.bubble = builder.get_object("checkbutton2")
        self.startup_check = builder.get_object("checkbutton4")
        self.startup_check.set_active(int(CONFIG['startup_update_check']))
        if HAVE_NOTIFY:
            self.bubble.set_active(int(CONFIG['show_notification']))
        else:
            self.bubble.set_sensitive(False)
        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")
        if HAVE_PYLAST:
            self.scrobble.set_active(int(CONFIG['scrobbling']))
        else:
            self.scrobble.set_sensitive(False)
        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 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_filename()
        if self.quit_without_confirmation.get_active():
            CONFIG['quit_without_confirmation'] = '1'
        else:
            CONFIG['quit_without_confirmation'] = '0'

        if self.bubble.get_active():
            CONFIG['show_notification'] = 1
        else:
            CONFIG['show_notification'] = 0
            
        if self.startup_check.get_active():
            CONFIG['startup_update_check'] = 1
        else:
            CONFIG['startup_update_check'] = 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() != "":
            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.start()

    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:
                self.play_by_index(0)
        else:
            self.stop_play()

    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.current_song = song
            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.set_timeout(50)
                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 get_overwritten_filename(self, filename):
        """
        Gets the file name depending on whether user want to overwrite the file,
        not overwrite it or not save it. Returns the same filename if user want
        to overwrite, the renamed filename or None if the user cancel Download.
        """
        if os.path.exists(filename) == True:
            dialog = gtk.Dialog(_("Overwrite downloaded file?"),
                         self.window,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         (_("Cancel download"), gtk.RESPONSE_NONE,
                          _("Download and overwrite"), 0,
                          _("Download renamed"), 1))

            label = gtk.Label(_("The file '%s' already exists, maybe you are downloading a file that you downloaded before.\n\nWhat do you want to do?") % filename)
            label.set_line_wrap(True)
            dialog.vbox.pack_start(label)
            label.show()

            dialog.set_default_response(gtk.RESPONSE_NONE)
            dialog.set_resizable(False)
            dialog.set_size_request(600,175)
            response = dialog.run()
            dialog.destroy()
        else:
            response = 0
            
        if response == 1:
            i = 1
            newfilename = ""
            while i == 1 or os.path.exists(newfilename):
                i += 1
                split = os.path.splitext(filename)
                newfilename = split[0] + " (%d)" % i + split[1]
            
            return newfilename
        elif response == 0:
            return filename
        else:
            return None
    
    def download_selected(self, widget, data=None):
        """
        Starts the download thread
        """
        select = self.result_view.get_selection().get_selected_rows()
        for path in select[1]:
            song = self.result_song(path[0])

            filename = "%s - %s.mp3" % (song["ArtistName"].strip("<>:\"/\|?*"),
                                    song["SongName"].strip("<>:\"/\|?*"))
            
            filename = os.path.join(CONFIG['down_path'], filename)
            filename = self.get_overwritten_filename(filename)
            
            if filename != None:
                try:
                    tDownload = t_download(self, song, filename)
                    tDownload.start()
                except:
                    pass
            
    def update_downloads_count(self):
        """
        Update the label wich indicates the downloads count.
        """
        count = self.downloads.iter_n_children(None)
        text = gettext.ngettext("Downloading %d file", "Downloading %d files", count) % count
        self.downloads_count.set_label(text)

    def right_click_download(self, treeview, event):
        """
        Executed when the user rightclicks on selected items in the download list.
        Can handle single and multiple selection.
        """
        if event.button == 3:
            path = treeview.get_path_at_pos(int(event.x), int(event.y))
            selection = treeview.get_selection()
            rows = selection.get_selected_rows()

            if path[0] not in rows[1]:
                # Unselect if the user click the right button outside 
                # the selected items - empty field.
                selection.unselect_all()
                selection.select_path(path[0])

            # still not sure about this. The point is that there are many rows selected
            # when you click the right mouse button, but then on_cancel_download still 
            # has no idea what is selected.
            if selection.count_selected_rows() > 1:
                self.downmenu.popup(None, None, None, event.button, event.time)
                print "Selected many rows"
            else:
                self.downmenu.popup(None, None, None, event.button, event.time)
                print "Selected one row!"
    
    def cancel_download(self, path):
        """
        Cancel a download by a list path
        """
        thread = self.downloads[path[0]][4]
        thread.stop()
        # TODO: Should improve the busy waiting
        while(thread.is_alive()):
            pass
    
    def cancel_all_downloads(self):
        """
        Cancel all downloads
        """
        iter = self.downloads.get_iter_first()
        while iter != None:
            path = self.downloads.get_path(iter)
            iter = self.downloads.iter_next(iter)
            self.cancel_download(path)

    def on_cancel_download(self, menu, data=None):
        """
        Cancel the download. Have to check how to cancel the thread.
        """
        select = self.downloads_view.get_selection().get_selected_rows()
        for path in select[1]:
            self.cancel_download(path)

    def toggle_download_list(self, param):
        if self.downloads_view.get_visible():
            self.hide_download_list();
        else:
            self.show_download_list();
            
    def hide_download_list(self):
        element = self.downloads_view.get_parent().get_parent();
        element.hide()
        self.downloads_view.set_visible(False)
    
    def show_download_list(self):
        element = self.downloads_view.get_parent().get_parent();
        element.show()
        self.downloads_view.set_visible(True)

    def get_stream_url(self):
        """
        TODO: Not used at the momment, but should be implemented
        with an short url to share with friends.
        """
        pass

class SingleService(dbus.service.Object):
    """
    Class to ensure that gSharkDown is running as a single service
    and allow command line arguments to be passed to the application
    """

    def __init__(self, app):
        self.app = app
        bus_name = dbus.service.BusName('org.gsharkdown.Single',
                                       bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, '/org/gsharkdown/Single')

    @dbus.service.method(dbus_interface='org.gsharkdown.Single')
    def get_current(self):
        """
        Method to get the current playing song used in the
        commandline interface.
        """
        if self.app.current_song == None:
            return "gSharkDown is not playing"
        else:
            song = self.app.current_song['ArtistName']
            song = song + " - "
            song = song + self.app.current_song['SongName']
            return song
        
    @dbus.service.method(dbus_interface='org.gsharkdown.Single')
    def get_state(self):
        """
        Method to get the player state used in the commandline interface
        """
        if self.app.playing == None:
            return "Stopped"
        else:
            return "Playing"
        
    @dbus.service.method(dbus_interface='org.gsharkdown.Single')
    def get_info(self):
        """
        Method to get information about the current playing song
        artist, song, album, year. Used in the commandline interface
        """
        if self.app.current_song == None:
            return ""
        else:
            song = self.app.current_song
            info = "Artist: " + song['ArtistName'] + "\n"
            info += "Song:" + song['SongName'] + "\n"
            info += "Album:" + song['AlbumName'] + "\n"
            info += "Year:" + song['Year'] + "\n"
            return info
        
    @dbus.service.method(dbus_interface='org.gsharkdown.Single')
    def get_version(self):
        """
        Method to return the current version of gSharkDown.
        """
        f = open("%s/VERSION" % BASEPATH, 'r')
        version = f.read()
        f.close()
        return version
    
    @dbus.service.method(dbus_interface='org.gsharkdown.Single')
    def get_help(self):
        """
        Method to read the HELP file and display the help message
        when using the commandline interface.
        """        
        return open("%s/HELP" % BASEPATH, 'r').read()

if __name__ == "__main__":
    owner = dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER
    if dbus.SessionBus().request_name("org.gsharkdown.Single") != owner:
        """
        This is just a simple salution so gsharkdown can have a 
        commandline interface, so others programs can interract with
        the application and share some informations.
        """
        try:
            if sys.argv[1] in ["--current", "-c", "current"]:
                method = dbus.SessionBus().get_object("org.gsharkdown.Single",
                            "/org/gsharkdown/Single").get_dbus_method("get_current")
            elif sys.argv[1] in ["--state", "-s", "state"]:
                method = dbus.SessionBus().get_object("org.gsharkdown.Single",
                            "/org/gsharkdown/Single").get_dbus_method("get_state")
            elif sys.argv[1] in ["--info", "-i", "info"]:
                method = dbus.SessionBus().get_object("org.gsharkdown.Single",
                            "/org/gsharkdown/Single").get_dbus_method("get_info")
            elif sys.argv[1] in ["--version", "-v","version"]:
                method = dbus.SessionBus().get_object("org.gsharkdown.Single",
                            "/org/gsharkdown/Single").get_dbus_method("get_version")
            elif sys.argv[1] in ["--help", "-h", "help"]:
                method = dbus.SessionBus().get_object("org.gsharkdown.Single",
                            "/org/gsharkdown/Single").get_dbus_method("get_help")
            print method()
        except:
            print open("%s/HELP" % BASEPATH, 'r').read()
    else:
        app = SharkDown()
        service = SingleService(app)
        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.