Commits

Vladimir Kolev  committed 67e6cd8

pep8 improvements and some style changes

  • Participants
  • Parent commits 1a56ea1

Comments (0)

Files changed (5)

File gsharkdown.py

 #!/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
     pygtk.require('2.0')
     import gtk
     import gobject
-except:
+except ImportError:
     print "You don't have python-gtk2 installed!"
-    sys.exit(0)
+    sys.exit(1)
 
 try:
     import pygst
     pygst.require('0.10')
     import gst
-except:
+except ImportError:
     print "You don't have python-gstreamer installed!"
-    sys.exit(0)
+    sys.exit(1)
 
 try:
     from configobj import ConfigObj
-except:
+except ImportError:
     print "You don't have python-configobj installed!"
-    sys.exit()
+    sys.exit(1)
 
-basepath = os.path.abspath(os.path.dirname(sys.argv[0]))
+BASEPATH = os.path.abspath(os.path.dirname(sys.argv[0]))
 
-config = ConfigObj("%s/data/gsharkdown.ini" % basepath)
+CONFIG = ConfigObj("%s/data/gsharkdown.ini" % BASEPATH)
 
 
 class SharkDown:
+    """
+    The main application class for gSharkDown
+    """
     results = []
     playitems = []
     downloads = []
     playing = None
 
     def __init__(self):
+        """
+        Initialise the main application window
+        """
         gobject.threads_init()
         builder = gtk.Builder()
-        builder.add_from_file('%s/data/main_window.ui' % basepath)
+        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.progressBar = builder.get_object('progressbar1')
-        self.playButton = builder.get_object('toolbutton3')
-        self.ffButton = builder.get_object('toolbutton9')
+        self.progress_bar = builder.get_object('progressbar1')
+        self.play_button = builder.get_object('toolbutton3')
+        self.ff_button = builder.get_object('toolbutton9')
         self.songinfo = builder.get_object('songinfo')
         self.songinfo.set_text("")
-        repeatButton = builder.get_object('togglebutton1')
-        repeatButton.set_active(int(config['repeat_playlist']))
-        shuffleButton = builder.get_object('togglebutton2')
-        shuffleButton.set_active(int(config['shuffle_playlist']))
+        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")
 
         # Results List definition
         self._create_play_columns()
 
         self.staticon = gtk.StatusIcon()
-        self.staticon.set_from_file("%s/data/gsharkdown_16.png" % basepath)
+        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")
         self.window.show_all()
 
     def window_close(self, widget, data=None):
-        if int(config['show_stat_icon']) == 0:
+        """
+        How to act on closing the window
+        """
+        if int(CONFIG['show_stat_icon']) == 0:
             self.window.hide_on_delete()
             self.windowstate = 0
             return True
             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)
-        quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
-        quit.connect("activate", self.quit_app)
+        quiter = gtk.ImageMenuItem(gtk.STOCK_QUIT)
+        quiter.connect("activate", self.quit_app)
 
         menu.append(about)
         menu.append(prefs)
         menu.append(gtk.SeparatorMenuItem())
-        menu.append(quit)
+        menu.append(quiter)
         menu.show_all()
 
         menu.popup(None, None, gtk.status_icon_position_menu,
                   button, time, icon)
 
     def icon_clicked(self, widget, data=None):
+        """
+        Executed on left clicking the statusicon
+        """
         if(self.windowstate == 0):
             self.window.show_all()
             self.windowstate = 1
             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)
 
     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)
 
     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,
         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]
             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['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])
             self.playitems.pop(path[0])
 
     def toggle_repeat(self, widget, data=None):
-        config['repeat_playlist'] = int(widget.get_active())
-        config.write()
+        """
+        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):
-        config['shuffle_playlist'] = int(widget.get_active())
-        config.write()
+        """
+        Toggle the configuration option for shuffleing the playlist
+        """
+        CONFIG['shuffle_playlist'] = int(widget.get_active())
+        CONFIG.write()
 
     def play_next(self, widget, data=None):
+        """
+        Plays the next item from the playlist
+        """
         if self.playing == None:
-            self.play_selected(self.playButton)
+            self.play_selected(self.play_button)
         else:
-            if int(config['shuffle_playlist']) == 0:
+            if int(CONFIG['shuffle_playlist']) == 0:
                 index = self.playing + 1
             else:
                 index = random.randint(0, len(self.playitems))
 
             if index >= len(self.playitems):
-                if int(config['repeat_playlist']) == 1:
+                if int(CONFIG['repeat_playlist']) == 1:
                     self.player.set_state(gst.STATE_NULL)
                     self.playing = None
-                    self.play_selected(self.playButton)
+                    self.play_selected(self.play_button)
                 else:
                     self.player.set_state(gst.STATE_NULL)
-                    self.playButton.set_stock_id(gtk.STOCK_MEDIA_PLAY)
+                    self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
                     self.playing = None
                     self.set_songinfos()
             else:
 
 
     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]
             dialog.destroy()
 
     def show_about(self, widget, data=None):
+        """
+        About dialog for the application
+        """
         builder = gtk.Builder()
-        builder.add_from_file('%s/data/about_dialog.ui' % basepath)
+        builder.add_from_file('%s/data/about_dialog.ui' % BASEPATH)
         about = builder.get_object('aboutdialog1')
         about.run()
         about.destroy()
 
     def edit_preferences(self, widget, data=None):
+        """
+        Preferences dialog with save and close buttons
+        """
         builder = gtk.Builder()
-        builder.add_from_file('%s/data/preferenes_dialog.ui' % basepath)
+        builder.add_from_file('%s/data/preferenes_dialog.ui' % BASEPATH)
         prefs = builder.get_object('window1')
         self.dest = builder.get_object('entry1')
-        self.dest.set_text(config['down_path'])
+        self.dest.set_text(CONFIG['down_path'])
         self.notify = builder.get_object("checkbutton1")
-        self.notify.set_active(int(config['show_stat_icon']))
+        self.notify.set_active(int(CONFIG['show_stat_icon']))
         builder.connect_signals(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,
         chooser.destroy()
 
     def save_preferences(self, widget, data=None):
-        config['down_path'] = self.dest.get_text()
-        if self.notify.get_active() == True:
-            config['show_stat_icon'] = 1
+        """
+        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
-        config.write()
+            CONFIG['show_stat_icon'] = 0
+        CONFIG.write()
         win = widget.get_window()
         win.destroy()
 
     def close_preferences(self, widget, data=None):
+        """
+        Closes the Preferences dialog discarding any changes
+        """
         win = widget.get_window()
         win.destroy()
 
     def search_grooveshark(self, widget, data=None):
+        """
+        Starts the search thread
+        """
         if widget.get_text() == "":
             pass
         else:
             search_thread.run()
 
     def play_selected(self, widget, data=None, row=None):
+        """
+        Starts the play thread
+        """
         #self.staticon.set_from_file("%s/data/gsharkdown_16_playing.png"
         #                            % basepath)
         #index = self.playlist.get_path(select[1])[0]
                 t.start()
         else:
             self.player.set_state(gst.STATE_NULL)
-            self.playButton.set_stock_id(gtk.STOCK_MEDIA_PLAY)
+            self.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
             self.set_songinfos()
             self.playing = None
 
     def set_songinfos(self, song=None):
+        """
+        Updates some labels and icons when a song is playing
+        """
         if song != None:
             self.staticon.set_from_file(
-                "%s/data/gsharkdown_16_playing.png" % basepath
+                "%s/data/gsharkdown_16_playing.png" % BASEPATH
             )
             self.staticon.set_tooltip(
                 "Playing: %s - %s" % (song['ArtistName'], song['SongName'])
                                          song['SongName'])
             )
         else:
-            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % basepath)
+            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % BASEPATH)
             self.staticon.set_tooltip(
                 "gSharkDown: GrooveShark Downloader"
             )
             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("<>:\"/\|?*"))
-            t = t_download(self, song, filename, config['down_path'])
+            t = t_download(self, song, filename, CONFIG['down_path'])
             t.start()
         else:
             pass
 
     def get_stream_url(self):
+        """
+        Not used at the momment
+        """
         pass
 
 if __name__ == "__main__":
-    app = SharkDown()
-    init_thread = t_init(app)
+    APP = SharkDown()
+    init_thread = t_init(APP)
     init_thread.run()
     gtk.main()

File lib/groove.py

 
 if sys.version_info[1] >= 6:
     import json
-else:
-    import simplejson as json
 
 _useragent = \
 """Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"""
 
 def prepToken(method):
     rnd = (''.join(random.choice(string.hexdigits) for x in range(6))).lower()
-    hashs = hashlib.sha1(method + ":" + _token + ":quitStealinMahShit:" + rnd).hexdigest()
+    hashs = hashlib.sha1(
+        method + ":" + _token + ":quitStealinMahShit:" + rnd).hexdigest()
     ret = rnd + hashs
     return ret
 
                   "Referer": _referer,
                   "Content-Type": "",
                   "Accept-Encoding": "gzip",
-                  "Cookie": "PHPSESSID=" + h["session"]
-                 })
+                  "Cookie": "PHPSESSID=" + h["session"]})
     resp = conn.getresponse().read()
     gzipfile = gzip.GzipFile(fileobj=(StringIO.StringIO(resp)))
     _token = json.JSONDecoder().decode(gzipfile.read())["result"]
                   "Referer": "http://grooveshark.com/",
                   "Content-Type": "",
                   "Accept-Encoding": "gzip",
-                  "Cookie": "PHPSESSID=" + h["session"]
-                 })
+                  "Cookie": "PHPSESSID=" + h["session"]})
     resp = conn.getresponse().read()
     gzipfile = gzip.GzipFile(fileobj=(StringIO.StringIO(resp)))
     return json.JSONDecoder().decode(gzipfile.read())["result"]["result"]
                   "Referer": _referer,
                   "Content-Type": "",
                   "Accept-Encoding": "gzip",
-                  "Cookie": "PHPSESSID=" + h["session"]
-                 })
+                  "Cookie": "PHPSESSID=" + h["session"]})
     resp = conn.getresponse().read()
     gzipfile = gzip.GzipFile(fileobj=(StringIO.StringIO(resp)))
     return json.JSONDecoder().decode(gzipfile.read())

File lib/groove.pyc

Binary file modified.

File lib/tfuncs.py

             try:
                 groove.init()
                 groove.getToken()
-                self.frame.progressBar.set_text("Ready")
+                self.frame.progress_bar.set_text("Ready")
                 p = 0
             except Exception, e:
                 if e.args[0] == 11004:
     def update_progress(self, progress, countBlocks, TotalSize, Block):
         if progress < 0.99:
             mb = 1024 ** 2
-            self.win.progressBar.pulse()
+            self.win.progress_bar.pulse()
             sizestr = "%.02f/%.02f MB" % (float(countBlocks * Block) / mb,
                                           float(TotalSize) / mb)
-            self.win.progressBar.set_text("Downloading: %s" % (sizestr))
+            self.win.progress_bar.set_text("Downloading: %s" % (sizestr))
         else:
-            self.win.progressBar.set_fraction(1.00)
-            self.win.progressBar.set_text("Downloaded!")
+            self.win.progress_bar.set_fraction(1.00)
+            self.win.progress_bar.set_text("Downloaded!")
 
 
 class t_play(threading.Thread):
     def on_stopped(self, widget=None, data=None):
         if int(config['repeat_playlist']) == 1:
             self.win.playing = None
-            self.win.play_next(self.win.ffButton)
+            self.win.play_next(self.win.ff_button)
         else:
-            self.win.playButton.set_stock_id(gtk.STOCK_MEDIA_PLAY)
+            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
             self.win.staticon.set_from_file("%s/data/gsharkdown_16.png" % basepath)
             self.win.staticon.set_tooltip("gSharkDown : Grooveshark Downloader")
 
     def update_buttons(self, state):
         if state == gst.STATE_NULL:
-            self.win.playButton.set_stock_id(gtk.STOCK_MEDIA_PLAY)
+            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_PLAY)
         else:
-            self.win.playButton.set_stock_id(gtk.STOCK_MEDIA_STOP)
+            self.win.play_button.set_stock_id(gtk.STOCK_MEDIA_STOP)
 
 
 class t_search(threading.Thread):

File lib/tfuncs.pyc

Binary file modified.