def get_lyrics_thread(self, callback, artist, title):
        # FIXME locking...
        global ServiceProxy
        if ServiceProxy is None:
            try:
                from ZSI import ServiceProxy
                # Make sure we have the right version..
                if not hasattr(ServiceProxy, 'ServiceProxy'):
                    ServiceProxy = None
            except ImportError:
                ServiceProxy = None
        if ServiceProxy is None:
            self.call_back(
                callback,
                None,
                None,
                error=_("ZSI not found, fetching lyrics support disabled."))
            return

        # FIXME locking...
        if self.lyricServer is None:
            wsdlFile = "http://lyricwiki.org/server.php?wsdl"
            try:
                self.lyricServer = True
                timeout = socketgettimeout()
                socketsettimeout(consts.LYRIC_TIMEOUT)
                self.lyricServer = ServiceProxy.ServiceProxy(
                    wsdlFile,
                    cachedir=os.path.expanduser("~/.service_proxy_dir"))
            except:
                self.lyricServer = None
                socketsettimeout(timeout)
                error = _("Couldn't connect to LyricWiki")
                self.call_back(callback, error=error)
                return

        try:
            timeout = socketgettimeout()
            socketsettimeout(consts.LYRIC_TIMEOUT)
            lyrics = self.lyricServer.getSong(
                artist=self.lyricwiki_format(artist),
                song=self.lyricwiki_format(title))['return']["lyrics"]
            if lyrics.lower() != "not found":
                lyrics = misc.unescape_html(lyrics)
                lyrics = misc.wiki_to_html(lyrics)
                lyrics = lyrics.encode("ISO-8859-1")
                self.call_back(callback, lyrics=lyrics)
            else:
                error = _("Lyrics not found")
                self.call_back(callback, error=error)
        except:
            error = _("Fetching lyrics failed")
            self.call_back(callback, error=error)

        socketsettimeout(timeout)
    def get_lyrics_thread(self, callback, artist, title):
        # FIXME locking...
        global ServiceProxy
        if ServiceProxy is None:
            try:
                from ZSI import ServiceProxy

                # Make sure we have the right version..
                if not hasattr(ServiceProxy, "ServiceProxy"):
                    ServiceProxy = None
            except ImportError:
                ServiceProxy = None
        if ServiceProxy is None:
            self.call_back(callback, None, None, error=_("ZSI not found, fetching lyrics support disabled."))
            return

            # FIXME locking...
        if self.lyricServer is None:
            wsdlFile = "http://lyricwiki.org/server.php?wsdl"
            try:
                self.lyricServer = True
                timeout = socketgettimeout()
                socketsettimeout(consts.LYRIC_TIMEOUT)
                self.lyricServer = ServiceProxy.ServiceProxy(
                    wsdlFile, cachedir=os.path.expanduser("~/.service_proxy_dir")
                )
            except:
                self.lyricServer = None
                socketsettimeout(timeout)
                error = _("Couldn't connect to LyricWiki")
                self.call_back(callback, error=error)
                return

        try:
            timeout = socketgettimeout()
            socketsettimeout(consts.LYRIC_TIMEOUT)
            lyrics = self.lyricServer.getSong(artist=self.lyricwiki_format(artist), song=self.lyricwiki_format(title))[
                "return"
            ]["lyrics"]
            if lyrics.lower() != "not found":
                lyrics = misc.unescape_html(lyrics)
                lyrics = misc.wiki_to_html(lyrics)
                lyrics = lyrics.encode("ISO-8859-1")
                self.call_back(callback, lyrics=lyrics)
            else:
                error = _("Lyrics not found")
                self.call_back(callback, error=error)
        except:
            error = _("Fetching lyrics failed")
            self.call_back(callback, error=error)

        socketsettimeout(timeout)
Exemple #3
0
def run():
    """Main entry point of Sonata"""

    # TODO: allow to exit the application with Ctrl+C from the terminal
    # This is a fix for https://bugzilla.gnome.org/show_bug.cgi?id=622084
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # XXX insert the correct sonata package dir in sys.path

    logging.basicConfig(
        level=logging.WARNING,
        format="[%(asctime)s] [%(threadName)s] %(name)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        stream=sys.stderr)

    logger = logging.getLogger(__name__)

    try:
        import sonata
    except ImportError:
        logger.critical("Python failed to find the sonata modules.")
        logger.critical("Searched in the following directories:\n%s",
                        "\n".join(sys.path))
        logger.critical("Perhaps Sonata is improperly installed?")
        sys.exit(1)

    try:
        from sonata.version import version
    except ImportError:
        logger.critical("Python failed to find the sonata modules.")
        logger.critical("An old or incomplete installation was "
                        "found in the following directory: %s",
                        os.path.dirname(sonata.__file__))
        logger.critical("Perhaps you want to delete it?")
        sys.exit(1)

    # XXX check that version.VERSION is what this script was installed for

    ## Apply global fixes:

    if platform.system() == 'Linux':
        sys.argv[0] = "sonata"
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        PR_SET_NAME = 15
        libc.prctl(PR_SET_NAME, b"sonata", 0, 0, 0)

    ## Apply locale and translation:
    # Try to find a "good" locale directory.
    for path in [
        # This is useful when working from the source repository
        os.path.join(os.path.dirname(sonata.__file__), "share", "locale"),
        # This is useful when Sonata is installed in a special place
        os.path.join(sonata.__file__.split('/lib')[0], 'share', 'locale'),
    ]:
        if os.path.exists(path):
            locales_path = path
            break
    else:
        # This tells gettext to look at the default place for the translation
        # files.
        locales_path = None

    gettext.install('sonata', locales_path, names=["ngettext"])
    gettext.textdomain('sonata')
    gettext.bindtextdomain('sonata', locales_path)


    ## Check initial dependencies:
    try:
        import mpd
    except:
        logger.critical("Sonata requires python-mpd2. Aborting...")
        sys.exit(1)


    ## Initialize the plugin system:

    from sonata.pluginsystem import pluginsystem
    pluginsystem.find_plugins()
    pluginsystem.notify_of('enablables',
                   lambda plugin, cb: cb(True),
                   lambda plugin, cb: cb(False))


    ## Load the command line interface:

    from sonata import cli
    args = cli.Args()
    args.parse(sys.argv)

    ## Deal with GTK:

    if not args.skip_gui:
        # importing gtk does sys.setdefaultencoding("utf-8"), sets locale etc.
        from gi.repository import Gtk, Gdk
    else:
        class FakeModule:
            pass
        # make sure the ui modules aren't imported
        for m in 'gtk', 'pango', 'sonata.ui', 'sonata.breadcrumbs':
            if m in sys.modules:
                logger.warning(
                    "Module %s imported in CLI mode (it should not)", m)
            else:
                sys.modules[m] = FakeModule()


    ## Global init:

    from socket import setdefaulttimeout as socketsettimeout
    socketsettimeout(5)

    if not args.skip_gui:
        Gdk.threads_init()

    ## CLI actions:

    args.execute_cmds()

    ## Load the main application:

    from sonata import main


    def on_application_activate(application):
        Gdk.threads_enter()
        windows = application.get_windows()

        if windows:
            for window in windows:
                window.present()
        else:
            sonata = main.Base(args)
            sonata.window.set_application(application)
        Gdk.threads_leave()

    app = Gtk.Application(application_id="org.MPD.Sonata")
    app.connect("activate", on_application_activate)

    ## Load the shell
    # yo dawg, I heard you like python,
    # so I put a python shell in your python application
    # so you can debug while you run it.
    if args.start_shell:
        # the enviroment used for the shell
        scope = dict(list(globals().items()) + list(locals().items()))
        def run_shell():
            try:
                import IPython
                IPython.embed(user_ns=scope)
            except ImportError as e: # fallback if ipython is not avaible
                import code
                shell = code.InteractiveConsole(scope)
                shell.interact()
            # quit program if shell is closed,
            # This is the only way to close the program clone in this mode,
            # because we can't close the shell thread easily
            from gi.repository import Gtk
            Gtk.main_quit()
        threading.Thread(target=run_shell, name="Shell").start()

    try:
        app.run([])
    except KeyboardInterrupt:
        Gtk.main_quit()
Exemple #4
0
def run():
    """Main entry point of Sonata"""

    # TODO: allow to exit the application with Ctrl+C from the terminal
    # This is a fix for https://bugzilla.gnome.org/show_bug.cgi?id=622084
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    # XXX insert the correct sonata package dir in sys.path

    logging.basicConfig(
        level=logging.WARNING,
        format="[%(asctime)s] %(name)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        stream=sys.stderr)

    logger = logging.getLogger(__name__)

    try:
        import sonata
    except ImportError:
        logger.critical("Python failed to find the sonata modules.")
        logger.critical("Searched in the following directories:\n%s",
                        "\n".join(sys.path))
        logger.critical("Perhaps Sonata is improperly installed?")
        sys.exit(1)

    try:
        from sonata.version import version
    except ImportError:
        logger.critical("Python failed to find the sonata modules.")
        logger.critical("An old or incomplete installation was "
                        "found in the following directory: %s",
                        os.path.dirname(sonata.__file__))
        logger.critical("Perhaps you want to delete it?")
        sys.exit(1)

    # XXX check that version.VERSION is what this script was installed for

    ## Apply global fixes:

    if platform.system() == 'Linux':
        sys.argv[0] = "sonata"
        import ctypes
        libc = ctypes.CDLL('libc.so.6')
        PR_SET_NAME = 15
        libc.prctl(PR_SET_NAME, b"sonata", 0, 0, 0)

    ## Apply locale and translation:
    # Try to find a "good" locale directory.
    for path in [
        # This is useful when working from the source repository
        os.path.join(os.path.dirname(sonata.__file__), "share", "locale"),
        # This is useful when Sonata is installed in a special place
        os.path.join(sonata.__file__.split('/lib')[0], 'share', 'locale'),
    ]:
        if os.path.exists(path):
            locales_path = path
            break
    else:
        # This tells gettext to look at the default place for the translation
        # files.
        locales_path = None

    gettext.install('sonata', locales_path, names=["ngettext"])
    gettext.textdomain('sonata')
    locale.bindtextdomain('sonata', locales_path)


    ## Check initial dependencies:
    try:
        import mpd
    except:
        logger.critical("Sonata requires python-mpd. Aborting...")
        sys.exit(1)


    ## Initialize the plugin system:

    from sonata.pluginsystem import pluginsystem
    pluginsystem.find_plugins()
    pluginsystem.notify_of('enablables',
                   lambda plugin, cb: cb(True),
                   lambda plugin, cb: cb(False))


    ## Load the command line interface:

    from sonata import cli
    args = cli.Args()
    args.parse(sys.argv)

    ## Deal with GTK:

    if not args.skip_gui:
        # importing gtk does sys.setdefaultencoding("utf-8"), sets locale etc.
        from gi.repository import Gtk, Gdk
    else:
        class FakeModule:
            pass
        # make sure the ui modules aren't imported
        for m in 'gtk', 'pango', 'sonata.ui', 'sonata.breadcrumbs':
            if m in sys.modules:
                logger.warning(
                    "Module %s imported in CLI mode (it should not)", m)
            else:
                sys.modules[m] = FakeModule()


    ## Global init:

    from socket import setdefaulttimeout as socketsettimeout
    socketsettimeout(5)

    if not args.skip_gui:
        Gdk.threads_init()

    ## CLI actions:

    args.execute_cmds()

    ## Load the main application:

    from sonata import main


    def on_application_activate(application):
        windows = application.get_windows()

        if windows:
            for window in windows:
                window.present()
        else:
            sonata = main.Base(args)
            sonata.window.set_application(application)
            sonata.window.show()

    app = Gtk.Application(application_id="org.MPD.Sonata")
    app.connect("activate", on_application_activate)

    ## Load the shell
    # yo dawg, I heard you like python,
    # so I put a python shell in your python application
    # so you can debug while you run it.
    if args.start_shell:
        # the enviroment used for the shell
        scope = dict(list(globals().items()) + list(locals().items()))
        def run_shell():
            try:
                import IPython
                IPython.embed(user_ns=scope)
            except ImportError as e: # fallback if ipython is not avaible
                import code
                shell = code.InteractiveConsole(scope)
                shell.interact()
            # quit program if shell is closed,
            # This is the only way to close the program clone in this mode,
            # because we can't close the shell thread easily
            from gi.repository import Gtk
            Gtk.main_quit()
        threading.Thread(target=run_shell).start()

    try:
        app.run([])
    except KeyboardInterrupt:
        Gtk.main_quit()
Exemple #5
0
	def get_lyrics_thread(self, search_artist, search_title, filename_artist, filename_title, song_dir):
		filename_artist = misc.strip_all_slashes(filename_artist)
		filename_title = misc.strip_all_slashes(filename_title)
		filename = self.info_check_for_local_lyrics(filename_artist, filename_title, song_dir)
		search_str = misc.link_markup(_("search"), True, True, self.linkcolor)
		edit_str = misc.link_markup(_("edit"), True, True, self.linkcolor)
		if filename:
			# If the lyrics only contain "not found", delete the file and try to
			# fetch new lyrics. If there is a bug in Sonata/SZI/LyricWiki that
			# prevents lyrics from being found, storing the "not found" will
			# prevent a future release from correctly fetching the lyrics.
			f = open(filename, 'r')
			lyrics = f.read()
			f.close()
			if lyrics == _("Lyrics not found"):
				misc.remove_file(filename)
				filename = self.info_check_for_local_lyrics(filename_artist, filename_title, song_dir)
		if filename:
			# Re-use lyrics from file:
			f = open(filename, 'r')
			lyrics = f.read()
			f.close()
			# Strip artist - title line from file if it exists, since we
			# now have that information visible elsewhere.
			header = filename_artist + " - " + filename_title + "\n\n"
			if lyrics[:len(header)] == header:
				lyrics = lyrics[len(header):]
			gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist, filename_title)
			gobject.idle_add(self.info_searchlabel.set_markup, search_str)
			gobject.idle_add(self.info_editlyricslabel.set_markup, edit_str)
		else:
			# Use default filename:
			filename = self.target_lyrics_filename(filename_artist, filename_title, song_dir)
			# Fetch lyrics from lyricwiki.org
			gobject.idle_add(self.info_show_lyrics, _("Fetching lyrics..."), filename_artist, filename_title)
			if self.lyricServer is None:
				wsdlFile = "http://lyricwiki.org/server.php?wsdl"
				try:
					self.lyricServer = True
					timeout = socketgettimeout()
					socketsettimeout(consts.LYRIC_TIMEOUT)
					self.lyricServer = ServiceProxy.ServiceProxy(wsdlFile, cachedir=os.path.expanduser("~/.service_proxy_dir")) 
				except:
					socketsettimeout(timeout)
					lyrics = _("Couldn't connect to LyricWiki")
					gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist, filename_title)
					self.lyricServer = None
					gobject.idle_add(self.info_searchlabel.set_markup, search_str)
					gobject.idle_add(self.info_editlyricslabel.set_markup, edit_str)
					return
			try:
				timeout = socketgettimeout()
				socketsettimeout(consts.LYRIC_TIMEOUT)
				lyrics = self.lyricServer.getSong(artist=self.lyricwiki_format(search_artist), song=self.lyricwiki_format(search_title))['return']["lyrics"]
				if lyrics.lower() != "not found":
					lyrics = misc.unescape_html(lyrics)
					lyrics = misc.wiki_to_html(lyrics)
					lyrics = lyrics.encode("ISO-8859-1")
					gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist, filename_title)
					# Save lyrics to file:
					misc.create_dir('~/.lyrics/')
					f = open(filename, 'w')
					lyrics = misc.unescape_html(lyrics)
					try:
						f.write(lyrics.decode(self.enc).encode('utf8'))
					except:
						f.write(lyrics)
					f.close()
				else:
					lyrics = _("Lyrics not found")
					gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist, filename_title)
			except:
				lyrics = _("Fetching lyrics failed")
				gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist, filename_title)
			gobject.idle_add(self.info_searchlabel.set_markup, search_str)
			gobject.idle_add(self.info_editlyricslabel.set_markup, edit_str)
			socketsettimeout(timeout)
Exemple #6
0
        pass
    # make sure the ui modules aren't imported
    for m in 'gtk', 'pango', 'sonata.ui', 'sonata.breadcrumbs':
        if m in sys.modules:
            print "Warning: module %s imported in CLI mode" % m
        else:
            sys.modules[m] = FakeModule()
    # like gtk, set utf-8 encoding of str objects
    reload(sys) # hack access to setdefaultencoding
    sys.setdefaultencoding("utf-8")


## Global init:

from socket import setdefaulttimeout as socketsettimeout
socketsettimeout(5)

if not args.skip_gui:
    gtk.gdk.threads_init()

    # we don't use gtk.LinkButton, but gtk.AboutDialog does;
    # in gtk 2.16.0 without this, the about uri opens doubly:
    gtk.link_button_set_uri_hook(lambda *args:None)

## CLI actions:

args.execute_cmds()


## Load the main application:
Exemple #7
0
 def get_lyrics_thread(self, search_artist, search_title, filename_artist,
                       filename_title, song_dir):
     filename_artist = misc.strip_all_slashes(filename_artist)
     filename_title = misc.strip_all_slashes(filename_title)
     filename = self.info_check_for_local_lyrics(filename_artist,
                                                 filename_title, song_dir)
     search_str = misc.link_markup(_("search"), True, True, self.linkcolor)
     edit_str = misc.link_markup(_("edit"), True, True, self.linkcolor)
     if filename:
         # If the lyrics only contain "not found", delete the file and try to
         # fetch new lyrics. If there is a bug in Sonata/SZI/LyricWiki that
         # prevents lyrics from being found, storing the "not found" will
         # prevent a future release from correctly fetching the lyrics.
         f = open(filename, 'r')
         lyrics = f.read()
         f.close()
         if lyrics == _("Lyrics not found"):
             misc.remove_file(filename)
             filename = self.info_check_for_local_lyrics(
                 filename_artist, filename_title, song_dir)
     if filename:
         # Re-use lyrics from file:
         f = open(filename, 'r')
         lyrics = f.read()
         f.close()
         # Strip artist - title line from file if it exists, since we
         # now have that information visible elsewhere.
         header = filename_artist + " - " + filename_title + "\n\n"
         if lyrics[:len(header)] == header:
             lyrics = lyrics[len(header):]
         gobject.idle_add(self.info_show_lyrics, lyrics, filename_artist,
                          filename_title)
         gobject.idle_add(self.info_searchlabel.set_markup, search_str)
         gobject.idle_add(self.info_editlyricslabel.set_markup, edit_str)
     else:
         # Use default filename:
         filename = self.target_lyrics_filename(filename_artist,
                                                filename_title, song_dir)
         # Fetch lyrics from lyricwiki.org
         gobject.idle_add(self.info_show_lyrics, _("Fetching lyrics..."),
                          filename_artist, filename_title)
         if self.lyricServer is None:
             wsdlFile = "http://lyricwiki.org/server.php?wsdl"
             try:
                 self.lyricServer = True
                 timeout = socketgettimeout()
                 socketsettimeout(consts.LYRIC_TIMEOUT)
                 self.lyricServer = ServiceProxy.ServiceProxy(
                     wsdlFile,
                     cachedir=os.path.expanduser("~/.service_proxy_dir"))
             except:
                 socketsettimeout(timeout)
                 lyrics = _("Couldn't connect to LyricWiki")
                 gobject.idle_add(self.info_show_lyrics, lyrics,
                                  filename_artist, filename_title)
                 self.lyricServer = None
                 gobject.idle_add(self.info_searchlabel.set_markup,
                                  search_str)
                 gobject.idle_add(self.info_editlyricslabel.set_markup,
                                  edit_str)
                 return
         try:
             timeout = socketgettimeout()
             socketsettimeout(consts.LYRIC_TIMEOUT)
             lyrics = self.lyricServer.getSong(
                 artist=self.lyricwiki_format(search_artist),
                 song=self.lyricwiki_format(
                     search_title))['return']["lyrics"]
             if lyrics.lower() != "not found":
                 lyrics = misc.unescape_html(lyrics)
                 lyrics = misc.wiki_to_html(lyrics)
                 lyrics = lyrics.encode("ISO-8859-1")
                 gobject.idle_add(self.info_show_lyrics, lyrics,
                                  filename_artist, filename_title)
                 # Save lyrics to file:
                 misc.create_dir('~/.lyrics/')
                 f = open(filename, 'w')
                 lyrics = misc.unescape_html(lyrics)
                 try:
                     f.write(lyrics.decode(self.enc).encode('utf8'))
                 except:
                     f.write(lyrics)
                 f.close()
             else:
                 lyrics = _("Lyrics not found")
                 gobject.idle_add(self.info_show_lyrics, lyrics,
                                  filename_artist, filename_title)
         except:
             lyrics = _("Fetching lyrics failed")
             gobject.idle_add(self.info_show_lyrics, lyrics,
                              filename_artist, filename_title)
         gobject.idle_add(self.info_searchlabel.set_markup, search_str)
         gobject.idle_add(self.info_editlyricslabel.set_markup, edit_str)
         socketsettimeout(timeout)
Exemple #8
0
        pass
    # make sure the ui modules aren't imported
    for m in 'gtk', 'pango', 'sonata.ui', 'sonata.breadcrumbs':
        if m in sys.modules:
            print "Warning: module %s imported in CLI mode" % m
        else:
            sys.modules[m] = FakeModule()
    # like gtk, set utf-8 encoding of str objects
    reload(sys) # hack access to setdefaultencoding
    sys.setdefaultencoding("utf-8")


## Global init:

from socket import setdefaulttimeout as socketsettimeout
socketsettimeout(5)

if not args.skip_gui:
    gtk.gdk.threads_init()

    # we don't use gtk.LinkButton, but gtk.AboutDialog does;
    # in gtk 2.16.0 without this, the about uri opens doubly:
    gtk.link_button_set_uri_hook(lambda *args:None)

## CLI actions:

args.execute_cmds()


## Load the main application: