Commits

Damián Nohales  committed 2f82731

Some imports fixes a refactoring to use Enviroment.

  • Participants
  • Parent commits 85ae20a
  • Branches refactoring

Comments (0)

Files changed (6)

File gsharkdown.py

     print "You don't have python-configobj installed!"
     sys.exit(1)
 
+# Imports PyCurl
+try:
+    import pycurl
+except:
+    print "You don't have python-pycurl installed!"
+    sys.exit(1)
+
 # Imports pynotify
 try:
     import pynotify
 except ImportError:
     print "You need to install pylast: sudo pip install pylast"
     HAVE_PYLAST = False
+
+# Imports application indicator
+try:
+    import appindicator
+    HAVE_INDICATOR = True
+except ImportError:
+    print "You don't have python-appindicator installed!"
+    print "StautsIcon will be used instead"
+    HAVE_INDICATOR = False
     
 # Common imports
 import os
 import dbus.service
 import dbus.glib
 from lib.enviroment import env
+from lib.SingleService import SingleService
 from lib.SharkDown import SharkDown
+from lib.tfuncs import InitThread
 
 # Enviroment Initialization
 env().HAVE_NOTIFY = HAVE_NOTIFY
 env().HAVE_PYLAST = HAVE_PYLAST
+env().HAVE_INDICATOR = HAVE_INDICATOR
 env().BASEPATH = os.path.abspath(os.path.dirname(sys.argv[0]))
 env().initialize()
 

File lib/SharkDown.py

+from enviroment import env, config
 import os
 import sys
 import random
-import dbus
-import dbus.service
-import dbus.glib
-from lib.tfuncs import InitThread
-from lib.tfuncs import DownloadThread
-from lib.tfuncs import PlayThread
-from lib.tfuncs import SearchThread
-from lib.tfuncs import KeyListenerThread
-from lib.tfuncs import LyricsThread
-from lib.tfuncs import UpdateThread
-from lib.tfuncs import SongCoverThread
-from lib.enviroment import env
-import lib.guihelpers
-import locale
-import gettext
-from gettext import gettext as _
+from tfuncs import DownloadThread
+from tfuncs import PlayThread
+from tfuncs import SearchThread
+from tfuncs import KeyListenerThread
+from tfuncs import LyricsThread
+from tfuncs import UpdateThread
+from tfuncs import SongCoverThread
+import guihelpers
 import urllib2
 import webbrowser
 import pickle
 import gst
 import glib
 import gobject
-import pynotify
-import pylast
+import locale
+import gettext
+from gettext import gettext as _
+
+try:
+    import pynotify
+    import pylast
+except:
+    pass   
 
 class SharkDown:
     """
         gobject.threads_init()
         
         builder = gtk.Builder()
-        builder.set_translation_domain(APP)
-        builder.add_from_file('%s/data/main_window.ui' % BASEPATH)
+        builder.set_translation_domain(env().APP)
+        builder.add_from_file('%s/data/main_window.ui' % env().BASEPATH)
         self.window = builder.get_object('mainwindow')
         self.window.connect('delete-event', self.window_close)
         self.windowstate = 1
         self.prefsmenu = builder.get_object('mainmenu')
         self.lovebutton = builder.get_object('toolbutton3')
         repeat_button = builder.get_object('togglebutton_repeat')
-        repeat_button.set_active(int(CONFIG['repeat_playlist']))
+        repeat_button.set_active(int(config()['repeat_playlist']))
         shuffle_button = builder.get_object('togglebutton_shuffle')
-        shuffle_button.set_active(int(CONFIG['shuffle_playlist']))
+        shuffle_button.set_active(int(config()['shuffle_playlist']))
         self.player = gst.element_factory_make("playbin", "player")
 
         # Completition configuration
         completition = gtk.EntryCompletion()
         comp_store = gtk.ListStore(str)
         completition.set_model(comp_store)
-        for item in CONFIG['completition'].split("|"):
+        for item in config()['completition'].split("|"):
             comp_store.append([item])
         completition.set_minimum_key_length(1)
         completition.set_text_column(0)
         self.update_downloads_count()
         self.downmenu = builder.get_object('downloadmenu')
 
-        self.staticon = lib.guihelpers.GsharkIndicator(self)
+        self.staticon = guihelpers.GsharkIndicator(self)
 
         if os.path.exists("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME")):
             self.load_saved_playlist("%s/.gsharkdown/playlist.pkl" % os.environ.get("HOME"))
         if os.path.exists("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME")):
             self.load_downqueue_list("%s/.gsharkdown/downqueue.pkl" % os.environ.get("HOME"))
 
-        if int(CONFIG['show_notification']) == 1 and HAVE_NOTIFY:
+        if int(config()['show_notification']) == 1 and env().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")
+        if config()['down_path'] == "":
+            config()['down_path'] = env().get_default_down_path()
 
         # Scrobbling initialisation
         self.lastfm = ""
-        if int(CONFIG['scrobbling']) == 1 and HAVE_PYLAST:
+        if int(config()['scrobbling']) == 1 and env().HAVE_PYLAST:
             try:
-                self.lastfm = pylast.LastFMNetwork(api_key = LAST_KEY,
-                                          api_secret = LAST_SECRET,
-                                          username = CONFIG['lastuser'],
-                                          password_hash = CONFIG['lastpass'])
+                self.lastfm = pylast.LastFMNetwork(api_key = env().LASTFM_KEY,
+                                          api_secret = env().LASTFM_SECRET,
+                                          username = config()['lastuser'],
+                                          password_hash = config()['lastpass'])
                 self.lovebutton.set_sensitive(True)
             except pylast.WSError:
                 error = lib.guihelpers.ErrorMessage(self.window,
         builder.connect_signals(self)
         self.tlisten = KeyListenerThread(self)
         self.tlisten.start()
-        if CONFIG['update_checked'] == 0:
+        if config()['update_checked'] == 0:
             self.check_for_update(None)
         else:
-            if CONFIG['startup_update_check'] == 1:
+            if config()['startup_update_check'] == 1:
                 self.check_for_update(None)
         self.window.show_all()
 
         thread.start()
 
     def create_default_track_icon(self):
-        default = gtk.gdk.pixbuf_new_from_file("%s/data/sdefault.png" % BASEPATH)
+        default = gtk.gdk.pixbuf_new_from_file("%s/data/sdefault.png" % env().BASEPATH)
         return self.create_cornered_image(default)
 
     def create_loading_track_icon(self):
-        default = gtk.gdk.pixbuf_new_from_file("%s/data/loading.png" % BASEPATH)
+        default = gtk.gdk.pixbuf_new_from_file("%s/data/loading.png" % env().BASEPATH)
         return self.create_cornered_image(default)
 
     def create_cornered_image(self, pixbuf):
-        corners = gtk.gdk.pixbuf_new_from_file("%s/data/corners.png" % BASEPATH)
+        corners = gtk.gdk.pixbuf_new_from_file("%s/data/corners.png" % env().BASEPATH)
         corners.composite(pixbuf, 0, 0, pixbuf.props.width, pixbuf.props.height,
                           0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)
         return pixbuf
         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 = UpdateThread(BASEPATH, markup, nmarkup, othertext)
+        config()['update_checked'] = 1
+        config().write()
+        t = UpdateThread(env().BASEPATH, markup, nmarkup, othertext)
         t.start()
 
     def icon_clicked(self, widget, data = None):
         """
         Confirmation dialog when exiting the application
         """
-        if CONFIG['quit_without_confirmation'] == '0':
+        if config()['quit_without_confirmation'] == '0':
             dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                   type = gtk.MESSAGE_QUESTION,
                                   buttons = gtk.BUTTONS_YES_NO,
         Toggles the configuration option for looping trough the
         playlist
         """
-        CONFIG['repeat_playlist'] = int(widget.get_active())
-        CONFIG.write()
+        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()
+        config()['shuffle_playlist'] = int(widget.get_active())
+        config().write()
 
     def double_click_start(self, widget, path, data = None):
         """
             self.play_by_index(0)
         else:
             index = self.playlist.get_path(self.get_playing_iter())[0] + 1
-            if int(CONFIG['shuffle_playlist']) == 1:
+            if int(config()['shuffle_playlist']) == 1:
                 index = random.randint(0, len(self.playlist) - 1)
 
             if index >= len(self.playlist):
-                if int(CONFIG['repeat_playlist']) == 1:
+                if int(config()['repeat_playlist']) == 1:
                     self.play_by_index(0)
                 else:
                     self.stop_play()
             self.play_by_index(0)
         else:
             index = self.playlist.get_path(self.get_playing_iter())[0] - 1
-            if int(CONFIG['shuffle_playlist']) == 1:
+            if int(config()['shuffle_playlist']) == 1:
                 index = random.randint(0, len(self.playlist) - 1)
 
             if index < 0:
-                if int(CONFIG['repeat_playlist']) == 1:
+                if int(config()['repeat_playlist']) == 1:
                     self.play_by_index(len(self.playlist) - 1)
                 else:
                     self.play_by_index(0)
             song = self.playlist_song(index)
             self.set_songinfos(song)
             t = PlayThread(self, song,
-                       int(CONFIG['repeat_playlist']),
+                       int(config()['repeat_playlist']),
                       self.lastfm)
             t.start()
 
         Tries to retrieve lyrics for selected song from the playlist.
         """
         if self.current_song != None:
-            t = LyricsThread(self, '%s/data/lyrics_dialog.ui' % BASEPATH,
+            t = LyricsThread(self, '%s/data/lyrics_dialog.ui' % env().BASEPATH,
                             self.current_song['ArtistName'],
                             self.current_song['SongName'])
             t.start()
         About dialog for the application
         """
         builder = gtk.Builder()
-        builder.set_translation_domain(APP)
-        builder.add_from_file('%s/data/about_dialog.ui' % BASEPATH)
+        builder.set_translation_domain(env().APP)
+        builder.add_from_file('%s/data/about_dialog.ui' % env().BASEPATH)
         flattr = builder.get_object('flattrbut')
         flattr.connect("clicked", self.flattr_this)
         updbtn = builder.get_object('updatbut')
         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)
+        builder.set_translation_domain(env().APP)
+        builder.add_from_file('%s/data/preferenes_dialog.ui' % env().BASEPATH)
         self.prefs = builder.get_object('window1')
         self.dest = builder.get_object('filechooserbutton1')
-        self.dest.set_filename(CONFIG['down_path'])
+        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.quit_without_confirmation.set_active(int(config()['quit_without_confirmation']))
         self.bubble = builder.get_object("checkbutton2")
         self.speed = builder.get_object("spinbutton1")
-        self.speed.set_value(int(CONFIG['speed_limit']))
+        self.speed.set_value(int(config()['speed_limit']))
         self.file_pattern = builder.get_object("entry1")
-        self.file_pattern.set_text(CONFIG['file_pattern'])
+        self.file_pattern.set_text(config()['file_pattern'])
         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']))
+        self.startup_check.set_active(int(config()['startup_update_check']))
+        if env().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.lastuser.set_text(config()['lastuser'])
         self.lastpass = builder.get_object("entry3")
         self.lastpass.set_visibility(False)
-        self.lastpass.set_text(CONFIG['lastpass'])
+        self.lastpass.set_text(config()['lastpass'])
         self.scrobble = builder.get_object("checkbutton3")
-        if HAVE_PYLAST:
-            self.scrobble.set_active(int(CONFIG['scrobbling']))
+        if env().HAVE_PYLAST:
+            self.scrobble.set_active(int(config()['scrobbling']))
         else:
             self.scrobble.set_sensitive(False)
         self.lastuser.set_sensitive(self.scrobble.get_active())
         Saves the information from the Preferences dialog in the
         configuration file
         """
-        CONFIG['down_path'] = self.dest.get_filename()
+        config()['down_path'] = self.dest.get_filename()
         if self.quit_without_confirmation.get_active():
-            CONFIG['quit_without_confirmation'] = '1'
+            config()['quit_without_confirmation'] = '1'
         else:
-            CONFIG['quit_without_confirmation'] = '0'
+            config()['quit_without_confirmation'] = '0'
 
         if self.bubble.get_active():
-            CONFIG['show_notification'] = 1
+            config()['show_notification'] = 1
         else:
-            CONFIG['show_notification'] = 0
+            config()['show_notification'] = 0
 
         if self.startup_check.get_active():
-            CONFIG['startup_update_check'] = 1
+            config()['startup_update_check'] = 1
         else:
-            CONFIG['startup_update_check'] = 0
+            config()['startup_update_check'] = 0
 
-        CONFIG['file_pattern'] = self.file_pattern.get_text()
-        CONFIG['speed_limit'] = self.speed.get_value_as_int()
+        config()['file_pattern'] = self.file_pattern.get_text()
+        config()['speed_limit'] = self.speed.get_value_as_int()
 
         if self.scrobble.get_active():
-            CONFIG['scrobbling'] = 1
-            CONFIG['lastuser'] = self.lastuser.get_text()
-            CONFIG['lastpass'] = pylast.md5(self.lastpass.get_text())
+            config()['scrobbling'] = 1
+            config()['lastuser'] = self.lastuser.get_text()
+            config()['lastpass'] = pylast.md5(self.lastpass.get_text())
         else:
-            CONFIG['scrobbling'] = 0
+            config()['scrobbling'] = 0
             self.lovebutton.set_sensitive(False)
-        CONFIG.write()
+        config().write()
         try:
-            self.lastfm = pylast.LastFMNetwork(api_key = LAST_KEY,
-                                          api_secret = LAST_SECRET,
-                                          username = CONFIG['lastuser'],
-                                          password_hash = CONFIG['lastpass'])
+            self.lastfm = pylast.LastFMNetwork(api_key = env().LASTFM_KEY,
+                                          api_secret = env().LASTFM_SECRET,
+                                          username = config()['lastuser'],
+                                          password_hash = config()['lastpass'])
             self.lovebutton.set_sensitive(True)
         except pylast.WSError:
             lib.guihelpers.ErrorMessage(self.window,
                     _("Please check your username and password for Last.fm"))
-            CONFIG['lastuser'] = ""
-            CONFIG['lastpass'] = ""
-            CONFIG['scrobbling'] = 0
-            CONFIG.write()
+            config()['lastuser'] = ""
+            config()['lastpass'] = ""
+            config()['scrobbling'] = 0
+            config().write()
         self.prefs.destroy()
 
     def close_preferences(self, widget, data = None):
         Starts the search thread
         """
         if widget.get_text() != "":
-            if widget.get_text() in CONFIG['completition'].split("|"):
+            if widget.get_text() in config()['completition'].split("|"):
                 pass
             else:
-                compl = CONFIG['completition'] + widget.get_text() + "|"
-                CONFIG['completition'] = compl
-                CONFIG.write()
+                compl = config()['completition'] + widget.get_text() + "|"
+                config()['completition'] = compl
+                config().write()
             search_thread = SearchThread(self, widget.get_text(), "Songs")
             search_thread.start()
 
             self.staticon.change_playbutton(image)
 
             image1 = self.playlist.get_value(playing, 1)
-            play = gtk.gdk.pixbuf_new_from_file('%s/data/play.png' % BASEPATH)
+            play = gtk.gdk.pixbuf_new_from_file('%s/data/play.png' % env().BASEPATH)
             play.composite(image1, 0, 0, image1.props.width, image1.props.height,
                               0, 0, 1.0, 1.0, gtk.gdk.INTERP_HYPER, 255)
             self.playlist.set(playing, 1, image1)
                 _("<b>Playing:</b> {artist} - {title}").format(artist = glib.markup_escape_text(self.current_song['ArtistName']),
                                          title = glib.markup_escape_text(self.current_song['SongName']))
             )
-            if int(CONFIG['show_notification']) == 1:
+            if int(config()['show_notification']) == 1:
                 n = pynotify.Notification(_("Now playing"),
                     "%s - %s" % (glib.markup_escape_text(song['ArtistName']),
                                  glib.markup_escape_text(song['SongName'])),
 
             #filename = "%s - %s.mp3" % (song["ArtistName"].strip("<>:\"/\|?*"),
             #                        song["SongName"].strip("<>:\"/\|?*"))
-            pattern = CONFIG['file_pattern'] + ".mp3"
+            pattern = config()['file_pattern'] + ".mp3"
             filename = pattern.format(artist = song['ArtistName'].strip("<>:\"/\|?&*"),
                                       song = song["SongName"].strip("<>:\"/\|?&*"),
                                       album = song["AlbumName"].strip("<>:\"/\|?&*"))
             filename = filename.replace('/', '-')
-            filename = os.path.join(CONFIG['down_path'], filename)
+            filename = os.path.join(config()['down_path'], filename)
             filename = self.get_overwritten_filename(filename)
 
             if filename != None:

File lib/SingleService.py

+import dbus
+import dbus.service
+import dbus.glib
+
 class SingleService(dbus.service.Object):
     """
     Class to ensure that gSharkDown is running as a single service
         """
         Method to return the current version of gSharkDown.
         """
-        f = open("%s/VERSION" % BASEPATH, 'r')
+        f = open("%s/VERSION" % env().BASEPATH, 'r')
         version = f.read()
         f.close()
         return version
         Method to read the HELP file and display the help message
         when using the commandline interface.
         """
-        return open("%s/HELP" % BASEPATH, 'r').read()
+        return open("%s/HELP" % env().BASEPATH, 'r').read()

File lib/enviroment.py

         # Dependencies information
         self.HAVE_NOTIFY = None
         self.HAVE_PYLAST = None
+        self.HAVE_INDICATOR = None
         
         # Directory for i18n files
         self.LOCALE_DIR = None

File lib/guihelpers.py

+from enviroment import env
 import gtk
 import os
 import sys
 import locale
 import gettext
 import glib
+from gettext import gettext as _
+
 try:
     import appindicator
-    HAVE_INDICATOR = True
 except ImportError:
-    print "You don't have python-appindicator installed!"
-    print "StautsIcon will be used instead"
-    HAVE_INDICATOR = False
-
-from gettext import gettext as _
-
-BASEPATH = os.path.abspath(os.path.dirname(sys.argv[0]).replace('locale/', ''))
-
-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)
+    pass
 
 class ErrorMessage(gtk.MessageDialog):
     """
         instance parameter is the main windows class for gSharkDown,
         so we can access the gSharkDown methods.
         """
-        if HAVE_INDICATOR == True:
+        if env().HAVE_INDICATOR == True:
             if os.path.exists('/usr/share/pixmaps/gsharkdown'):
                 icons_path = '/usr/share/pixmaps/gsharkdown'
             else:
-                icons_path = "%s/_pixmaps/gsharkdown" % BASEPATH
+                icons_path = "%s/_pixmaps/gsharkdown" % env().BASEPATH
             self.ind = appindicator.Indicator("gsharkdown-client",
                                     "gsharkdown-messages",
                                     appindicator.CATEGORY_APPLICATION_STATUS,
         else:
             self.instance = instance
             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" % env().BASEPATH)
             self.staticon.connect("popup-menu", self.right_click_event)
             self.staticon.connect("activate", self.icon_clicked)
             self.staticon.set_tooltip(_("gSharkDown :: Player and Downloader"))
 
     def change_status_playing(self):
         # Method to change the gSharkDown icon when playing
-        if HAVE_INDICATOR == True:
+        if env().HAVE_INDICATOR == True:
             self.ind.set_status(appindicator.STATUS_ATTENTION)
         else:
-            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % BASEPATH)
+            self.staticon.set_from_file("%s/data/gsharkdown_16.png" % env().BASEPATH)
 
     def change_status_stopped(self):
         # Method to change the gSharkDown icon to default
         # when not playing anything.
-        if HAVE_INDICATOR == True:
+        if env().HAVE_INDICATOR == True:
             self.ind.set_status(appindicator.STATUS_ACTIVE)
         else:
             self.staticon.set_from_file(
-                "%s/data/gsharkdown_16_playing.png" % BASEPATH)
+                "%s/data/gsharkdown_16_playing.png" % env().BASEPATH)
 
     def change_playbutton(self, image):
-        if HAVE_INDICATOR == True:
+        if env().HAVE_INDICATOR == True:
             self.playbut.set_image(image)

File lib/tfuncs.py

+from enviroment import env
 import os
 import sys
 import gtk
 import gettext
 from gettext import gettext as _
 
-try:
-    import pygst
-    pygst.require('0.10')
-    import gst
-except:
-    print "You don't have python-gstreamer installed!"
-    sys.exit(0)
-
-try:
-    import pycurl
-except:
-    print "You don't have python-pycurl installed!"
-    sys.exit(0)
-
-basepath = os.path.abspath(os.path.dirname(sys.argv[0]).strip("/lib"))
-
-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)
+import pygst
+import pycurl
 
 
 class InitThread(threading.Thread):