Beispiel #1
0
    def _load_filesystem_plugins(self):
        # import logging
        # logging.basicConfig(level=logging.DEBUG)

        """Looks for *.yapsy-plugin files and loads them. It calls 'register' \
        method for each plugin, which in turn registers with \
        :class:`FilesystemDetector \
        <rawdisk.filesystems.detector.FilesystemDetector>`.

        Note:
            Plugin search locations:
               * $(rawdisk package location)/plugins/filesystems
               * $(home dir)/.local/share/rawdisk/plugins/filesystems
               * /usr/local/share/rawdisk/plugins/filesystems
               * /usr/share/rawdisk/plugins/filesystems
        """
        PluginManagerSingleton.setBehaviour([
            VersionedPluginManager,
        ])

        # Load the plugins from the plugin directory.
        self.manager = PluginManagerSingleton.get()
        self.manager.setPluginPlaces(self.search_path)
        self.manager.setCategoriesFilter({
            "Filesystem": IFilesystemPlugin,
        })

        # Load plugins
        self.manager.collectPlugins()

        for pluginInfo in self.manager.getPluginsOfCategory("Filesystem"):
            self.fs_plugins.append(pluginInfo)
Beispiel #2
0
    def load_filesystem_plugins(self):
        """Looks for *.yapsy-plugin files, loads them and returns a list
            of :class:`VersionedPluginInfo \
            <yapsy.VersionedPluginManager.VersionedPluginInfo>` objects

                Note:
                    Plugin search locations:
                       * $(rawdisk package location)/plugins/filesystems
                       * $(home dir)/.local/share/rawdisk/plugins/filesystems
                       * /usr/local/share/rawdisk/plugins/filesystems
                       * /usr/share/rawdisk/plugins/filesystems
                """
        self.logger.info('Loading filesystem plugins')
        search_path = self.__get_fs_plugin_search_path()
        fs_plugins = []

        PluginManagerSingleton.setBehaviour([
            VersionedPluginManager,
        ])

        # Load the plugins from the plugin directory.
        plugin_manager = PluginManagerSingleton.get()
        plugin_manager.setPluginPlaces(search_path)
        plugin_manager.setCategoriesFilter({
            "Filesystem": IFilesystemPlugin,
        })

        # Load plugins
        plugin_manager.collectPlugins()

        for pluginInfo in plugin_manager.getPluginsOfCategory("Filesystem"):
            fs_plugins.append(pluginInfo)

        return fs_plugins
Beispiel #3
0
 def botmsg(self, user, channel, task, args):
     manager = PluginManagerSingleton.get()
     if user.split("!")[0] not in manager.app.plugin_get_setting(
             "pluginAdmin", "allowedUsers") and task == "plugin":
         manager.app.msg(channel, "You're not authorised to do that!")
         return
     if task == "plugin":
         if args[0] == "rehash":
             manager.app.rehash_plugins()
             manager.app.msg(channel, "Plugins rehashed!")
         elif args[0] == "load":
             manager = PluginManagerSingleton.get()
             pname = string.join(args[1:])
             if pname in manager.app.plugin_get_setting(
                     "pluginAdmin", "disallowedPlugins"):
                 manager.app.msg(channel,
                                 "Plugin \"" + pname + "\" is protected!")
                 return
             manager.app.load_plugin(pname)
             manager.app.msg(
                 channel, "Plugin \"" + string.join(args[1:]) +
                 "\" has been loaded.")
         elif args[0] == "unload":
             manager = PluginManagerSingleton.get()
             pname = string.join(args[1:])
             if pname in manager.app.plugin_get_setting(
                     "pluginAdmin", "disallowedPlugins"):
                 manager.app.msg(channel,
                                 "Plugin \"" + pname + "\" is protected!")
                 return
             manager.app.unload_plugin(string.join(args[1:]))
             manager.app.msg(
                 channel, "Plugin \"" + string.join(args[1:]) +
                 "\" has been unloaded.")
Beispiel #4
0
    def __init__(self):
        """
        Initialize the PluginManager including:
            - plugin configuration directory
            - plugin search locations
        """
        self.config_path = save_config_path("yasibo")
        self.config_file = os.path.join(self.config_path, "plugins.conf")
        places = []
        [places.append(os.path.join(path, "yasibo", "plugins")) for path in xdg_data_dirs]
        # dev location
        places.append("%s/../plugins" % os.path.dirname(os.path.abspath(__file__)))

        PluginManagerSingleton.setBehaviour([ConfigurablePluginManager,
                                             VersionedPluginManager])
        self.manager = PluginManagerSingleton.get()
        locator = self.manager.getPluginLocator()
        locator.setPluginInfoExtension("yasibo-plugin")
        self.manager.setPluginPlaces(places)

        self.config = SafeConfigParser()
        self.config.read(self.config_file)
        self.manager.setConfigParser(self.config, self.save)

        self.manager.collectPlugins()
        log.debug("Config file: %s" % self.config_file)
Beispiel #5
0
 def botmsg(self, user, channel, task, args):
     user = user.split("!")[0]
     if task == "note" and args[0] == "send":
         manager = PluginManagerSingleton.get()
         self.add_note(args[1], "\"" + string.join(args[2:]) + "\" (from " + user + ")")
         manager.app.msg(args[1], "You have a new note! Use !note read to read it.")
         manager.app.msg(user, "Your message has been sent.")
     elif task == "note" and args[0] == "read":
         manager = PluginManagerSingleton.get()     
         _notes = manager.app.plugin_get_setting("notePlugin", "notes")
         x = None
         try:
             x = _notes[user]
             if len(x) == 0:
                 raise KeyError("x")
         except KeyError:
             manager.app.msg(user, "You don't have any messages.")
             return
         manager.app.msg(user, str(x[0]))
         _notes[user].remove(x[0])
         manager.app.msg(user, "You now have " + str(len(x)) + " messages. Use !note read to read the next one.")
         if len(x) == 0:
             _notes.pop(user, None)
         manager.app.plugin_set_setting("notePlugin", "notes", _notes)
     elif task == "note" and args[0] == "purge":
         manager = PluginManagerSingleton.get()  
         if not user in manager.app.plugin_get_setting("notePlugin", "allowedUsers"):
             return
         self.cleanup()
         manager.app.msg(user, "Notes purged.")
Beispiel #6
0
    def _init_plugin_engine(self):
        self.debug("Initializing plugin engine")
        
        places = []
        if hasattr(self, '_plugin_dir'):
            # run_local.py will pass in a plugin directory
            places.append(self._plugin_dir)
            
        for path in xdg_data_dirs:
            path = os.path.join(path, self._package, "plugins")
            places.append(path)

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])
        manager = PluginManagerSingleton.get()
        manager.application = self
        manager.setConfigParser(self._config, self.write_config)
        manager.setPluginInfoExtension("plugin")
        manager.setPluginPlaces(places)
        #manager.setCategoriesFilter({
        #    "Application" : WindowPlugin,
        #})
        manager.collectPlugins()
        
        #for info in manager.getPluginsOfCategory("Window"):
        for info in manager.getAllPlugins():
            plugin = info.plugin_object
            plugin.application = self
Beispiel #7
0
 def __init__ (self):
   """ Class initialiser """
   # Get singleton instance
   PluginManagerSingleton.setBehaviour([
       VersionedPluginManager,
   ])
   manager = PluginManagerSingleton.get()
   
   # A referrence for plugins to access the app
   manager.app = self
   
   # Set environment
   self.env = jinja2.Environment(loader=jinja2.FileSystemLoader("./template/"),
                                 **TEMPLATE_OPTIONS)
   
   # Set ArgParser
   self.parser = argparse.ArgumentParser(description='Simple Static Web Generator')
   self.parser.add_argument('--cache', dest='cache', action='store_true')
   
   # A referrence for plugins to access the env object
   # manager.env = self.env
   
   # Set plugin's directories path
   manager.setPluginPlaces(['plugins'])
   
   # Locates and Loads the plugins
   manager.collectPlugins()
Beispiel #8
0
    def __init__(self, plugin_dir=None):
        self.config = SafeConfigParser()
        config_path = save_config_path(self.APP_NAME)
        self.config_file = os.path.join(config_path, self.APP_NAME + ".conf")
        self.config.read(self.config_file)

        this_dir = os.path.abspath(os.path.dirname(__file__))
        self.plugin_dir = plugin_dir or os.path.join(this_dir,
                                                     self._default_dir)
        places = [
            self.plugin_dir,
        ]
        [
            places.append(os.path.join(path, self.APP_NAME, "evaluators"))
            for path in xdg_data_dirs
        ]

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        self.manager = PluginManagerSingleton.get()
        self.manager.setConfigParser(self.config, self.write_config)
        self.manager.setPluginInfoExtension("expr-plugin")
        self.manager.setPluginPlaces(places)
        self.manager.collectPlugins()
Beispiel #9
0
 def botmsg(self, user, channel, task, args):
     manager = PluginManagerSingleton.get()
     if user.split("!")[0] not in manager.app.plugin_get_setting("pluginAdmin", "allowedUsers") and task == "plugin" :
         manager.app.msg(channel, "You're not authorised to do that!")
         return
     if task == "plugin":
         if args[0] == "rehash":
             manager.app.rehash_plugins()
             manager.app.msg(channel, "Plugins rehashed!")
         elif args[0] == "load":
             manager = PluginManagerSingleton.get()
             pname = string.join(args[1:])
             if pname in manager.app.plugin_get_setting("pluginAdmin", "disallowedPlugins"):
                 manager.app.msg(channel, "Plugin \"" + pname + "\" is protected!")       
                 return
             manager.app.load_plugin(pname)
             manager.app.msg(channel, "Plugin \"" + string.join(args[1:]) + "\" has been loaded.")
         elif args[0] == "unload":
             manager = PluginManagerSingleton.get()
             pname = string.join(args[1:])
             if pname in manager.app.plugin_get_setting("pluginAdmin", "disallowedPlugins"):
                 manager.app.msg(channel, "Plugin \"" + pname + "\" is protected!")       
                 return
             manager.app.unload_plugin(string.join(args[1:]))
             manager.app.msg(channel, "Plugin \"" + string.join(args[1:]) + "\" has been unloaded.")
Beispiel #10
0
 def deferred_botmsg(self, user, channel, task, args):
     if task == "rep":
         user = user.split("!")[0]
         if args[0] == "give":
             manager = PluginManagerSingleton.get()
             user_stat = yield manager.app.is_user_online(args[1])
             if user_stat == False:
                 logging.warning(manager.app.is_user_online(args[1]))
                 manager.app.msg(channel, "This user doesn't appear to be here!")
                 return
             if args[1] == user:
                 manager.app.msg(channel, "You cannot give yourself rep.")
                 return
             lastRep = manager.app.plugin_get_setting("repPlugin", "lastRep")
             if user + ":" + args[1] == str(lastRep):
                 manager.app.msg(channel, "You've already given this person rep!")
                 return
             self.give_rep(args[1])
             manager.app.plugin_set_setting("repPlugin", "lastRep", user + ":" + args[1])
             manager.app.msg(channel, args[1] + " has received 1 rep from " + user)
         elif args[0] == "check":
             manager = PluginManagerSingleton.get()
             manager.app.msg(channel, args[1] + " has " + str(self.get_rep(args[1])) + " rep!")
         elif args[0] == "purge":
             manager = PluginManagerSingleton.get()
             if user in manager.app.plugin_get_setting("repPlugin", "allowedUsers"):
                 self.cleanup()
                 manager.app.msg(channel, "Rep data purged.")
Beispiel #11
0
    def _load_filesystem_plugins(self):
        """Looks for *.yapsy-plugin files and loads them. It calls 'register' \
        method for each plugin, which in turn registers with \
        :class:`FilesystemDetector \
        <rawdisk.filesystems.detector.FilesystemDetector>`.

        Note:
            Plugin search locations:
               * $(rawdisk package location)/plugins/filesystems
               * $(home dir)/.local/share/rawdisk/plugins/filesystems
               * /usr/local/share/rawdisk/plugins/filesystems
               * /usr/share/rawdisk/plugins/filesystems
        """
        PluginManagerSingleton.setBehaviour([
            VersionedPluginManager,
        ])

        # Load the plugins from the plugin directory.
        self.manager = PluginManagerSingleton.get()
        self.manager.setPluginPlaces(self.search_path)
        self.manager.setCategoriesFilter({
            "Filesystem": IFilesystemPlugin,
        })

        # Load plugins
        self.manager.collectPlugins()

        for pluginInfo in self.manager.getPluginsOfCategory("Filesystem"):
            self.fs_plugins.append(pluginInfo)
Beispiel #12
0
    def load_filesystem_plugins(self):
        """Looks for *.yapsy-plugin files, loads them and returns a list
            of :class:`VersionedPluginInfo \
            <yapsy.VersionedPluginManager.VersionedPluginInfo>` objects

                Note:
                    Plugin search locations:
                       * $(rawdisk package location)/plugins/filesystems
                       * $(home dir)/.local/share/rawdisk/plugins/filesystems
                       * /usr/local/share/rawdisk/plugins/filesystems
                       * /usr/share/rawdisk/plugins/filesystems
                """
        self.logger.info('Loading filesystem plugins')
        search_path = self.__get_fs_plugin_search_path()
        fs_plugins = []

        PluginManagerSingleton.setBehaviour([
            VersionedPluginManager,
        ])

        # Load the plugins from the plugin directory.
        plugin_manager = PluginManagerSingleton.get()
        plugin_manager.setPluginPlaces(search_path)
        plugin_manager.setCategoriesFilter({
            "Filesystem": IFilesystemPlugin,
        })

        # Load plugins
        plugin_manager.collectPlugins()

        for pluginInfo in plugin_manager.getPluginsOfCategory("Filesystem"):
            fs_plugins.append(pluginInfo)

        return fs_plugins
Beispiel #13
0
    def __init__(self, win):
        self.app = win.app
        self.parent = win

        # Build a list of directories which may contain plugins. This will
        # include the 'plugins' folder where this file resides as well as every
        # directory in xdg.BaseDirectory.xdg_data_dirs. This way users can
        # install plugins in something like ~/.local/yapsy-gtk-example/plugins
        # but your installer could also install those plugins to something like
        # /usr/share/yapsy-gtk-example/plugins. You'll see Yapsy checking each
        # of these directories if logging is set to logging.DEBUG
        xdg_data_dirs = [
            os.path.join(os.path.expanduser("~"), '.local', 'share')
        ]
        this_dir = os.path.abspath(self.app.FULL_PATH)
        plugin_dir = os.path.join(this_dir, 'data', 'plugins')
        places = [
            plugin_dir,
        ]
        for path in xdg_data_dirs:
            places.append(os.path.join(path, self.app.APP_NAME, "plugins"))

        # The singleton versino of the Yapsy plugin manager is used rather than
        # passing around a PluginManager instance. Prior to getting the
        # singleton instance, some "plugin manager decorators" are installed to:
        # 1. Automatically save active and non-active plugins to the config file
        # 2. Ensure only the newest versions of plugins are used.
        # This call to setBehaviour() must occur before getting the singleton
        # instance.

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        # Get singleton instance
        manager = PluginManagerSingleton.get()

        # I like to give the manager a reference to the application class so
        # that plugins can connect to signals and access windows through
        # the manager singleton.
        manager.app = self.app
        manager.parent = self.parent

        # Give manager the config file and a callback function to call when it
        # changes the config (eg. when a plugin is activated or deactivated).
        manager.setConfigParser(self.app.config,
                                self.app.config.write_settings)

        # Setup a file extension for plugin information files. In this it's
        # just ".plugin" but you may want to do something specific to your
        # application like ".myapp-plugin"
        manager.setPluginInfoExtension("gs-plugin")

        # Pass the manager the list of plugin directories
        manager.setPluginPlaces(places)

        # CollectPlugins is a shortcut for locatePlugins() and loadPlugins().
        manager.collectPlugins()
Beispiel #14
0
    def testActivationAndDeactivation(self):
        """
		Test if the activation/deactivaion procedures work.
		"""
        self.plugin_activate()
        PluginManagerSingleton.get().deactivatePluginByName(
            self.plugin_info.name, self.plugin_info.category)
        self.assertTrue(not self.plugin_info.plugin_object.is_activated)
Beispiel #15
0
 def _loadPlugins(self):
     PluginManagerSingleton.setBehaviour([
                 VersionedPluginManager,
     ])
     manager = PluginManagerSingleton.get()
     manager.setPluginPlaces(self.pluginDirs)
     manager.setCategoriesFilter(pluginCategories)
     manager.collectPlugins()
Beispiel #16
0
	def testActivationAndDeactivation(self):
		"""
		Test if the activation/deactivaion procedures work.
		"""
		self.plugin_activate()
		PluginManagerSingleton.get().deactivatePluginByName(self.plugin_info.name,
															self.plugin_info.category)
		self.assertTrue(not self.plugin_info.plugin_object.is_activated)
Beispiel #17
0
    def __init__(self, config: Config):
        PluginManagerSingleton.setBehaviour(
            [ConfigurablePluginManager, VersionedPluginManager]
        )

        self._plugin_manager = PluginManagerSingleton.get()
        self._plugin_manager.setPluginPlaces(config.get_plugin_paths())
        self._plugin_manager.setPluginInfoExtension("plugin")
        self._plugin_manager.setConfigParser(config.parser, config.save)
Beispiel #18
0
    def plugin_activate(self):
        """
		Activate the plugin with basic checking
		"""
        self.plugin_loading_check()
        if not self.plugin_info.plugin_object.is_activated:
            PluginManagerSingleton.get().activatePluginByName(
                self.plugin_info.name, self.plugin_info.category)
        self.assertTrue(self.plugin_info.plugin_object.is_activated)
Beispiel #19
0
	def plugin_activate(self):
		"""
		Activate the plugin with basic checking
		"""
		self.plugin_loading_check()
		if not self.plugin_info.plugin_object.is_activated:
			PluginManagerSingleton.get().activatePluginByName(self.plugin_info.name,
															  self.plugin_info.category)
		self.assertTrue(self.plugin_info.plugin_object.is_activated)
Beispiel #20
0
    def __init__(self, win):
        self.app = win.app
        self.parent = win

        # Build a list of directories which may contain plugins. This will
        # include the 'plugins' folder where this file resides as well as every
        # directory in xdg.BaseDirectory.xdg_data_dirs. This way users can
        # install plugins in something like ~/.local/yapsy-gtk-example/plugins
        # but your installer could also install those plugins to something like
        # /usr/share/yapsy-gtk-example/plugins. You'll see Yapsy checking each
        # of these directories if logging is set to logging.DEBUG
        xdg_data_dirs = [os.path.join(os.path.expanduser("~"),
                         '.local', 'share')]
        this_dir = os.path.abspath(self.app.FULL_PATH)
        plugin_dir = os.path.join(this_dir, 'data', 'plugins')
        places = [plugin_dir, ]
        for path in xdg_data_dirs:
            places.append(os.path.join(path, self.app.APP_NAME, "plugins"))

        # The singleton versino of the Yapsy plugin manager is used rather than
        # passing around a PluginManager instance. Prior to getting the
        # singleton instance, some "plugin manager decorators" are installed to:
        # 1. Automatically save active and non-active plugins to the config file
        # 2. Ensure only the newest versions of plugins are used.
        # This call to setBehaviour() must occur before getting the singleton
        # instance.

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        # Get singleton instance
        manager = PluginManagerSingleton.get()

        # I like to give the manager a reference to the application class so
        # that plugins can connect to signals and access windows through
        # the manager singleton.
        manager.app = self.app
        manager.parent = self.parent

        # Give manager the config file and a callback function to call when it
        # changes the config (eg. when a plugin is activated or deactivated).
        manager.setConfigParser(self.app.config, self.app.config.write_settings)

        # Setup a file extension for plugin information files. In this it's
        # just ".plugin" but you may want to do something specific to your
        # application like ".myapp-plugin"
        manager.setPluginInfoExtension("gs-plugin")

        # Pass the manager the list of plugin directories
        manager.setPluginPlaces(places)

        # CollectPlugins is a shortcut for locatePlugins() and loadPlugins().
        manager.collectPlugins()
Beispiel #21
0
    def create_plugin_manager(self):
        from yapsy.ConfigurablePluginManager import ConfigurablePluginManager
        from yapsy.PluginManager import PluginManagerSingleton
        from yapsy.VersionedPluginManager import VersionedPluginManager

        PluginManagerSingleton.setBehaviour([
            ConfigurablePluginManager,
            VersionedPluginManager,
        ])

        return PluginManagerSingleton.get()
Beispiel #22
0
    def __init__(self, configdir, profile=None):
        QtCore.QObject.__init__(self)

        self.firstrun = False
        PluginManagerSingleton.setBehaviour([ConfigurablePluginManager])
        self.plugmanc = PluginManagerSingleton.get()
        locator = self.plugmanc.getPluginLocator()
        locator.setPluginInfoExtension("freeseer-plugin")

        self.configdir = configdir

        if profile:
            # Use profile if specified
            self.configfile = os.path.abspath(
                os.path.join(self.configdir, "profiles", profile,
                             "plugin.conf"))
        else:
            self.configfile = os.path.abspath(
                os.path.join(self.configdir, "plugin.conf"))

        self.config = ConfigParser.ConfigParser()
        self.load()
        self.plugmanc.setConfigParser(self.config, self.save)

        # Get the path where the installed plugins are located on systems where
        # freeseer is installed.
        pluginpath = "%s/../plugins" % os.path.dirname(
            os.path.abspath(__file__))

        self.plugmanc.setPluginPlaces([
            pluginpath,
            os.path.expanduser("~/.freeseer/plugins"), "freeseer/plugins"
        ])
        self.plugmanc.setCategoriesFilter({
            "AudioInput": IAudioInput,
            "AudioMixer": IAudioMixer,
            "VideoInput": IVideoInput,
            "VideoMixer": IVideoMixer,
            "Output": IOutput
        })
        self.plugmanc.collectPlugins()

        # If config was corrupt or did not exist, reset default plugins.
        if self.firstrun:
            self.set_default_plugins()

        for plugin in self.plugmanc.getAllPlugins():
            plugin.plugin_object.set_plugman(self)

        log.debug("Plugin manager initialized.")
Beispiel #23
0
    def load(self):
        PluginManagerSingleton.setBehaviour([
            VersionedPluginManager,
            ConfigurablePluginManager,
        ])  #OnlinePluginManager
        self.manager = PluginManagerSingleton.get()

        #~ if self.installpath:
        #~ self.manager.setInstallDir(self.installpath)

        self.manager.setConfigParser(self.configparser, self.configparser.save)
        self.manager.setPluginPlaces(self.loadpathes)
        self.manager.setPluginInfoExtension(self.extension)
        self.manager.setCategoriesFilter(self.categories)
        self.manager.collectPlugins()
Beispiel #24
0
    def __init__(self, cfg):
        """
        Initialise the plugin system.
        """

        assert cfg
        self.cfg = cfg

        # Get plugin locations.
        plugin_search_path_b = self.cfg.get_config_str(
            "PluginSearchPath",
            default=b"/etc/rdiffweb/plugins")

        # Determine the search path
        searchpath = []
        # Append core plugins directory (in bytes)
        path_b = pkg_resources.resource_filename('rdiffweb', b'plugins')  # @UndefinedVariable
        searchpath.append(path_b)
        # Append user plugins directory
        plugin_locations = plugin_search_path_b.split(b',')
        searchpath.extend(plugin_locations)
        # Build the manager
        logger.debug("plugin search path [%s]" % (searchpath))

        # Create the plugin manager.
        PluginManagerSingleton.setBehaviour([FilteredPluginManager])
        self.manager = PluginManagerSingleton.get()

        # Sets plugins locations.
        plugin_locator = PluginLocator()
        self.manager.setPluginLocator(plugin_locator)
        plugin_locator.setPluginPlaces(searchpath)

        # Define categories
        self.manager.setCategoriesFilter({
            IDatabase.CATEGORY: IDatabase,
            IDeamonPlugin.CATEGORY: IDeamonPlugin,
            ILocationsPagePlugin.CATEGORY: ILocationsPagePlugin,
            IPasswordStore.CATEGORY: IPasswordStore,
            IPreferencesPanelProvider.CATEGORY: IPreferencesPanelProvider,
            IUserChangeListener.CATEGORY: IUserChangeListener,
        })

        # Set filter.
        self.manager.isPluginOk = self.is_plugin_enabled

        # Load all plugins
        self.manager.collectPlugins()
def activatedPlugins():
    """
	Activate and deactivate all the plugins.
	"""
    pm = PluginManagerSingleton.get()
    activated = []
    for pluginInfo in pm.getAllPlugins():
        try:
            pluginInfo.plugin_object.activate()
            activated.append(pluginInfo)
            log.debug('activated plugin %s', pluginInfo.name)
        except:
            log.error(('Exception activating plugin "%s". (Will not' +
                       ' deactivate.)') % pluginInfo.name,
                      exc_info=True)

    try:
        yield activated
    finally:
        for pluginInfo in activated:
            try:
                pluginInfo.plugin_object.deactivate()
            except:
                log.error('Exception deactivating plugin "%s".' %
                          pluginInfo.name,
                          exc_info=True)
Beispiel #26
0
    def __init__(self, parent):
        super(SettingsDialog,self).__init__(parent)

        pluginPaths = wx.GetApp().GetPluginPlaces()

        self.pluginsHtml.SetPage(
        """
        <html>
        <body><h3 align="center">Select Plugins</h3>
        You can add customized plugins by placing them in the following
        directories <ul><li>{}<li>{}</ul>
        <body>
        </html>
        """.format(*pluginPaths))

        self.pluginCtrlMap = {
                        STATEMENT_WRITER:self.statementWriter,
                        REGISTRY_WRITER:self.registryWriter,
                        TRANSACTION_FORMATTER:self.transactionFormatter,
                        INIT_PARSER:self.initParser
                        }

        self.app = wx.GetApp()
        manager = PluginManagerSingleton.get()

        for category, ctrl in self.pluginCtrlMap.items():
            currentSel = self.app.getPluginNameFromConfig(category)
            choices = [ p.name for p in
                    manager.getPluginsOfCategory(category) ]
            ctrl.SetItems(choices)
            try:
                i = choices.index(currentSel)
                ctrl.SetSelection(i)
            except ValueError:
                pass
Beispiel #27
0
    def __init__(self):
        self.servers = {}
        self.clients = []
        self.logger = logging.getLogger("Factory")
        self.plugman = PluginManagerSingleton.get()
        self.events = manager.manager()
        self.plugman.setPluginPlaces(["plugins"])
        self.plugman.setPluginInfoExtension("plug")
        self.plugman.collectPlugins()

        self.logger.info("Loading plugins..")
        for pluginInfo in self.plugman.getAllPlugins():
            try:
                self.plugman.activatePluginByName(pluginInfo.name)
                pluginInfo.plugin_object._add_variables(pluginInfo, self)
                pluginInfo.plugin_object.setup()
            except Exception:
                self.logger.warn("Unable to load plugin: %s v%s" % (pluginInfo.name, pluginInfo.version))
                util.output_exception(self.logger, logging.WARN)
                self.plugman.deactivatePluginByName(pluginInfo.name)
            else:
                self.logger.info("Loaded plugin: %s v%s" % (pluginInfo.name, pluginInfo.version))
                event = pluginLoadedEvent(self, pluginInfo)
                self.events.runCallback("pluginLoaded", event)
        self.logger.info("Finished loading plugins.")

        event = pluginsLoadedEvent(self)
        self.events.runCallback("pluginsLoaded", event)
Beispiel #28
0
def init_plugin_manager(category_filter=None,
                        info_ext=PLUGIN_INFO_EXT,
                        builtins_pkg=PLUGIN_BUILTINS,
                        env_var=PLUGIN_ENV_VAR):
    """
    Initialize the plugin manager and set some behaviour options
    :param category_filter:
    :param info_ext:
    :param builtins_pkg:
    :param env_var:
    :return:
    """
    global _initialized

    # default category_filter is PLUGIN_CATEGORIES_FILTER (dict)
    category_filter = PLUGIN_CATEGORIES_FILTER if category_filter is None else category_filter

    logger.debug('Initializing plugin manager..')

    manager = PluginManagerSingleton.get()

    manager.setCategoriesFilter(category_filter)
    manager.setPluginInfoExtension(info_ext)

    # save parameters used to initialize the module
    _initialized = dict(category_filter=category_filter,
                        info_ext=info_ext,
                        builtins_pkg=builtins_pkg,
                        env_var=env_var)
Beispiel #29
0
    def botmsg(self, user, channel, task, args):
        user = user.split("!")[0]
        if task == "away":
            manager = PluginManagerSingleton.get()
            if manager.app.plugin_get_setting("awayPlugin", "pmOnly") == "yes":
                channel = user
            elif channel == manager.app.nickname:
                channel = user

            if args[0] == "reason":
                reason = self.get_reason_for_away(args[1])
                manager.app.msg(
                    channel, args[1] + " is away for the following reason: " +
                    str(reason))
            elif args[0] == "set":
                reason = string.join(args[1:])
                self.add_user_as_away(user, reason)
                manager.app.msg(channel, "Your away reason has been set.")
            elif args[0] == "unset":
                self.remove_user_as_away(user)
                manager.app.msg(channel, "Your away reason has been removed.")
            elif args[0] == "purge":
                if user not in manager.app.plugin_get_setting(
                        "awayPlugin", "allowedUsers"):
                    manager.app.msg(channel,
                                    "You're not permitted to do that!")
                    return
                manager.app.plugin_set_setting("awayPlugin", "awayReasons", {})
Beispiel #30
0
    def __init__(self, **kwargs):

        IPlugin.__init__(self)
        BaseView.__init__(self, **kwargs)
        self.manager = PluginManagerSingleton.get()
        self.logger = logging.getLogger(self.__class__.__name__)
        self.enabled = False

        self.viewable = False
        self.widgetized = False
        self.use_filestore = False
        self.use_sqllog = False

        #set defaults for template paths
        # ais/plugins/name/widget.html
        # ais/plugins/name/index.html
        path_items = inspect.getfile(self.__class__).split('/')[-3:-1]
        self.path = str.join('/', path_items)
        self.view_template = self.path + '/index.html'
        self.widget_template = self.path + '/widget.html'
        self.url = "/" + self.__class__.__name__.lower() + "/"
        self.filestore = None

        try:
            getattr(self.manager, 'app')
        except Exception:
            pass
        else:
            self.app = self.manager.app
        self.logger.debug("%s Init finished", self.__class__.__name__)
Beispiel #31
0
    def create_plugin_config(self):
        # get current directory and plugin directory
        current_dir = path.abspath(path.dirname(__file__))
        plugin_dir = path.join(current_dir, 'plugins')

        # configure plugin manager
        manager = PluginManagerSingleton.get()
        manager.setPluginPlaces([plugin_dir])
        manager.collectPlugins()

        # set default value for plugin key
        self.config.get('plugins', {})

        # iterate over all plugins
        for plugin in manager.getAllPlugins():
            manager.activatePluginByName(plugin.name)

            # get the default config if the plugin if available
            if hasattr(plugin.plugin_object, 'default_config'):
                # create the default config if not already in the config
                if plugin.name.strip().lower() not in self.config['plugins']:
                    self.config['plugins'][plugin.name.strip().lower()] = plugin.plugin_object.default_config
                else:
                    # update keys
                    for k, v in plugin.plugin_object.default_config.items():
                        if k not in self.config['plugins'][plugin.name.strip().lower()]:
                            self.config['plugins'][plugin.name.strip().lower()][k] = v

        # reset plugin manager
        PluginManagerSingleton._PluginManagerSingleton__instance = None

        self.update_config()
        print('Updated default plugin config at ./config.json')
Beispiel #32
0
    def __init__(self):
        LogObject.__init__(self)
        super(MykissPlugin, self).__init__()

        # grab the application instance from the plugin manager
        manager = PluginManagerSingleton.get()
        self.application = manager.application
Beispiel #33
0
 def botmsg(self, user, channel, task, args):
     if not args:
         return  # All of our commands require arguments.
     if task == "wiki":
         manager = PluginManagerSingleton.get()
         user = user.split("!")[0]
         if user in manager.app.plugin_get_setting("wikipediaPlugin",
                                                   "blacklist"):
             manager.app.msg(channel,
                             "You're blacklisted for abuse (ha ha ha ha).")
             return
         if args[0] == "get":
             topic = string.join(args[1:])
             topic = topic.replace(" ", "_")
             url = "http://en.wikipedia.com/wiki/" + topic
             logging.debug("Checking url " + url)
             try:
                 pg = urllib2.urlopen(url)
                 soup = BeautifulSoup(pg)
                 mainText = soup.find("div", {"id": "mw-content-text"})
                 firstParagraph = mainText.find("p").text
                 asciiParagraph = firstParagraph.encode(
                     "ascii", "ignore").decode("ascii")
                 manager.app.msg(channel, str(asciiParagraph)[:250] + "...")
                 manager.app.msg(channel, "More information at " + url)
             except:
                 manager.app.msg(channel, "Search unsuccessful.")
Beispiel #34
0
 def user_joined(self, user, channel):
     user = user.split("!")[0]
     manager = PluginManagerSingleton.get()
     _notes = manager.app.plugin_get_setting("notePlugin", "notes")
     if user in _notes:
         if len(_notes[user]) > 0:
             manager.app.msg(user, "You have " + str(len(_notes[user])) + " new messages. Use !note read to read each one.")
Beispiel #35
0
  def setup_plugins(self):
    """
    discover all plugins and populate the plugin combo boxes
    setup signals so that selecting a plugin has some effect
    """
    self.prevAttentionPluginIndex = 0
    self.prevMeditationPluginIndex = 0
    self.prevEyeBlinkPluginIndex = 0
    
    #enable the following 2 lines of code to debug yapsy discovery
    #import logging
    #logging.basicConfig(level=logging.DEBUG)
 
    from yapsy.PluginManager import PluginManagerSingleton
    manager = PluginManagerSingleton.get()
    from getinstallpath import getInstallPath
    import os.path
    places = [ os.path.join(getInstallPath(), "midicontroller/plugins/scoregenerators") ]
    manager.setPluginPlaces(places)
    manager.locatePlugins()
    manager.loadPlugins()
    print "Discovered the following plugins:"
    for plugin in manager.getAllPlugins():
      n = plugin.plugin_object.name
      print n
      self.attentionPluginComboBox.addItem(n)
      self.meditationPluginComboBox.addItem(n)
      self.eyeBlinkPluginComboBox.addItem(n)

    self.attentionPluginComboBox.currentIndexChanged.connect(self.attentionPluginSelected)
    self.meditationPluginComboBox.currentIndexChanged.connect(self.meditationPluginSelected)
    self.eyeBlinkPluginComboBox.currentIndexChanged.connect(self.eyeBlinkPluginSelected)
    self.attentionPluginSelected(0)
    self.meditationPluginSelected(0)
    self.eyeBlinkPluginSelected(0)
Beispiel #36
0
def list(args):
	xh.setuputil.collectPlugins()
	pm = PluginManagerSingleton.get()
	pluginInfoStr = 'Plugins:'
	for p in pm.getAllPlugins():
		infos = ['%s (%s%s)'
			% (p.name, os.path.basename(p.path), os.path.sep)]
		if '?' not in p.version:
			infos.append('v' + p.version)
		if p.description is not None:
			infos.append(p.description)
		pluginInfoStr += '\n\t' + ' '.join(infos)
	log.info(pluginInfoStr)

	serialDevice = (xh.setuputil.FAKE_SERIAL if args.fakeSerial
			else args.serialDevice)
	nodeInfoList = listNodeIds(
		serialDevice=serialDevice,
		timeout=args.timeout)

	nodeInfoStr = 'XBees:'
	for n in nodeInfoList:
		lineStr = str(n)
		nodeInfoStr += '\n\t' + lineStr
	log.info(nodeInfoStr)
Beispiel #37
0
 def get_reason_for_away(self, user):
     manager = PluginManagerSingleton.get()
     _cur = manager.app.plugin_get_setting("awayPlugin", "awayReasons")
     try:
         return _cur[user]
     except KeyError:
         return "User is not away!"
Beispiel #38
0
 def __init__(self):
     LogObject.__init__(self)
     super(MykissPlugin, self).__init__()
     
     # grab the application instance from the plugin manager
     manager = PluginManagerSingleton.get()
     self.application = manager.application
def activatedPlugins():
	"""
	Activate and deactivate all the plugins.
	"""
	pm = PluginManagerSingleton.get()
	activated = []
	for pluginInfo in pm.getAllPlugins():
		try:
			pluginInfo.plugin_object.activate()
			activated.append(pluginInfo)
			log.debug('activated plugin %s', pluginInfo.name)
		except:
			log.error(('Exception activating plugin "%s". (Will not'
				+ ' deactivate.)') % pluginInfo.name,
				exc_info=True)

	try:
		yield activated
	finally:
		for pluginInfo in activated:
			try:
				pluginInfo.plugin_object.deactivate()
			except:
				log.error('Exception deactivating plugin "%s".'
				% pluginInfo.name, exc_info=True)
Beispiel #40
0
def check_args(parsed_args):
    """
    Function to check for inherent contradictions within parsed arguments.
    For example, batch_size < num_gpus
    Intended to raise errors prior to backend initialisation.

    :param parsed_args: parser.parse_args()
    :return: parsed_args
    """

    if parsed_args.multi_gpu > 1 and parsed_args.batch_size < parsed_args.multi_gpu:
        raise ValueError(
            "Batch size ({}) must be equal to or higher than the number of GPUs ({})".format(parsed_args.batch_size,
                                                                                             parsed_args.multi_gpu))

    if parsed_args.multi_gpu > 1 and parsed_args.snapshot:
        raise ValueError(
            "Multi GPU training ({}) and resuming from snapshots ({}) is not supported.".format(parsed_args.multi_gpu,
                                                                                                parsed_args.snapshot))

    for plugin in PluginManagerSingleton.get().getAllPlugins():
        plugin.plugin_object.check_args(parsed_args)

    if 'resnet' in parsed_args.backbone:
        from ..models.resnet import validate_backbone
    elif 'mobilenet' in parsed_args.backbone:
        from ..models.mobilenet import validate_backbone
    else:
        raise NotImplementedError('Backbone \'{}\' not implemented.'.format(parsed_args.backbone))

    validate_backbone(parsed_args.backbone)

    return parsed_args
Beispiel #41
0
    def privmsg(self, user, channel, msg):
        # The singleton allows us to access the bot's methods (such as msg)
        # via the manager.app class.
        manager = PluginManagerSingleton.get()

        # For the purposes of this example, we'll just say ping to any message.
        manager.app.msg(channel, "Ping.")
Beispiel #42
0
 def privmsg(self, user, channel, msg):
     manager = PluginManagerSingleton.get()
     if str(msg).startswith('_pypi'):
         pkg = msg[len('_pypi'):].strip()
         print('Looking up PyPi package %s' % pkg)
         try:
             resp = urlopen('https://pypi.python.org/pypi/%s' % pkg)
         except HTTPError:
             manager.app.say(channel, 'Silly %s, this package doesn\'t exist!' % user)
             return
         html = resp.read()
         soup = BeautifulSoup(html)
         section = soup.find('div', {'class': 'section'})
         if 'Index' in section.find('h1').contents[0]:
             latest = section.find('table').find('a').contents[0].lower() \
                 .replace(pkg.lower(), '').encode('ascii', 'ignore')
             all_versions = section.find('table').find_all('a')
             versions = ''
             version_count = 0
             for version in all_versions:
                 separator = ', ' if version_count != 0 else ''
                 versions += '%s%s' % (separator, version.contents[0].lower().replace(pkg.lower(), ''))
                 version_count += 1
                 if 10 == version_count:
                     break
             versions = versions.encode('ascii', 'ignore')
             manager.app.say(channel, 'Please specify a version. Latest: %s' % str(latest))
             manager.app.say(channel, 'Available versions: %s' % str(versions))
             return
         version = section.find('h1').contents[0]
         description = section.find('p').contents[0]
         manager.app.say(channel, 'Package: %s' % str(version).strip())
         manager.app.say(channel, 'Description: %s' % str(description).strip())
         manager.app.say(channel, 'URL: %s' % ('https://pypi.python.org/pypi/%s' % pkg))
Beispiel #43
0
 def get_reason_for_away(self, user):
     manager = PluginManagerSingleton.get()
     _cur = manager.app.plugin_get_setting("awayPlugin", "awayReasons")
     try:
         return _cur[user]
     except KeyError:
         return "User is not away!"
Beispiel #44
0
    def botmsg(self, user, channel, task, args):
        if not args:
            return  # All of our commands require arguments.
        if task == "man":
            manager = PluginManagerSingleton.get()
            user = user.split("!")[0]
            if user in manager.app.plugin_get_setting("manPlugin",
                                                      "blacklist"):
                manager.app.msg(channel, "You're blacklisted!")
                return
            elif channel == manager.app.nickname:
                channel = user

            if args[0] == "get":
                topic = args[1]
                url = "http://man.he.net/?topic=" + topic + "&section=all"
                pg = urllib2.urlopen(url).read()
                logging.debug(url)
                soup = BeautifulSoup(pg)
                try:
                    pre = soup.find("pre")
                    text = string.join(pre.findAll(
                        text=True)).decode("utf8").encode("ascii", "ignore")
                    manager.app.msg(channel, text[:250] + "...")
                    manager.app.msg(channel, "More information at " + str(url))
                except:
                    manager.app.msg(channel, "Search unsuccessful.")
Beispiel #45
0
  def load_state(self, filename):
    """
    get state of ui and all plugins from file, and set to the ui
    """
    try:
      with open(filename, "r") as f:
        modelstring = f.read()
    except IOError:
      return

    import json
    model = json.loads(modelstring)
    plugin_model = model['plugins']
    del model['plugins']
    self.serializer.model_to_ui(model)
    from yapsy.PluginManager import PluginManagerSingleton
    manager = PluginManagerSingleton.get()

    for plugin in manager.getAllPlugins():
      for section in SECTIONS:
        self.suspend_plugin(plugin.plugin_object, section)
      name = plugin.plugin_object.name
      if name in plugin_model:
        plugin.plugin_object.set_state_from_dict(self.MainWindow.centralWidget(),plugin_model[name])  
    self.attentionCheckBoxClicked()
    self.meditationCheckBoxClicked()
    self.eyeBlinkCheckBoxClicked()
Beispiel #46
0
    def __init__(self, profile):
        QtCore.QObject.__init__(self)

        self.profile = profile
        self.firstrun = False
        self.plugmanc = PluginManagerSingleton.get()

        locator = self.plugmanc.getPluginLocator()
        locator.setPluginInfoExtension("freeseer-plugin")

        # Get the path where the installed plugins are located on systems where
        # freeseer is installed.
        pluginpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, "plugins")

        self.plugmanc.setPluginPlaces([pluginpath, os.path.expanduser("~/.freeseer/plugins"), "freeseer/plugins"])
        self.plugmanc.setCategoriesFilter(
            {
                "AudioInput": IAudioInput,
                "AudioMixer": IAudioMixer,
                "VideoInput": IVideoInput,
                "VideoMixer": IVideoMixer,
                "Importer": IImporter,
                "Output": IOutput,
            }
        )
        self.plugmanc.collectPlugins()

        for plugin in self.plugmanc.getAllPlugins():
            plugin.plugin_object.set_plugman(self)

        log.debug("Plugin manager initialized.")
Beispiel #47
0
    def privmsg(self, user, channel, msg):
        # The singleton allows us to access the bot's methods (such as msg)
        # via the manager.app class.
        manager = PluginManagerSingleton.get()

        # For the purposes of this example, we'll just say ping to any message.
        manager.app.msg(channel, "Ping.")
Beispiel #48
0
    def __init__(self, profile):
        QtCore.QObject.__init__(self)

        self.profile = profile
        self.firstrun = False
        self.plugmanc = PluginManagerSingleton.get()

        locator = self.plugmanc.getPluginLocator()
        locator.setPluginInfoExtension("freeseer-plugin")

        # Get the path where the installed plugins are located on systems where
        # freeseer is installed.
        pluginpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, "plugins")

        self.plugmanc.setPluginPlaces([pluginpath,
                                       os.path.expanduser("~/.freeseer/plugins"),
                                       "freeseer/plugins"])
        self.plugmanc.setCategoriesFilter({
            "AudioInput": IAudioInput,
            "AudioMixer": IAudioMixer,
            "VideoInput": IVideoInput,
            "VideoMixer": IVideoMixer,
            "Importer":   IImporter,
            "Output":     IOutput})
        self.plugmanc.collectPlugins()

        for plugin in self.plugmanc.getAllPlugins():
            plugin.plugin_object.set_plugman(self)

        log.debug("Plugin manager initialized.")
Beispiel #49
0
    def load_state(self, filename):
        """
    get state of ui and all plugins from file, and set to the ui
    """
        try:
            with open(filename, "r") as f:
                modelstring = f.read()
        except IOError:
            return

        import json
        model = json.loads(modelstring)
        plugin_model = model['plugins']
        del model['plugins']
        self.serializer.model_to_ui(model)
        from yapsy.PluginManager import PluginManagerSingleton
        manager = PluginManagerSingleton.get()

        for plugin in manager.getAllPlugins():
            for section in SECTIONS:
                self.suspend_plugin(plugin.plugin_object, section)
            name = plugin.plugin_object.name
            if name in plugin_model:
                plugin.plugin_object.set_state_from_dict(
                    self.MainWindow.centralWidget(), plugin_model[name])
        self.attentionCheckBoxClicked()
        self.meditationCheckBoxClicked()
        self.eyeBlinkCheckBoxClicked()
Beispiel #50
0
    def __init__(self):
        self.allApps = {}
        self.scanner = []
        self.gui = None

        currentDir = os.path.dirname(os.path.realpath(__file__))

        plugin_dir = currentDir + "/" + "plugins"
        places = [
            plugin_dir,
        ]

        self.manager = PluginManagerSingleton.get()

        self.manager.app = self
        self.manager.setPluginInfoExtension("plugin")

        # Pass the manager the list of plugin directories
        self.manager.setPluginPlaces(places)

        # CollectPlugins is a shortcut for locatePlugins() and loadPlugins().
        self.manager.collectPlugins()

        # let's load all plugins we can find in the plugins directory
        for plugin in self.manager.getAllPlugins():
            self.activatePlugin(plugin.name)
            try:
                print(plugin.details.get("Documentation", "requires"))
            except configparser.NoOptionError:
                pass

        self.scan()
Beispiel #51
0
def get_plugin_manager():
    if get_settings().get_plugins_enabled():
        from yapsy.PluginManager import PluginManagerSingleton
        return PluginManagerSingleton.get()
    else:
        from lunchinator.log import getCoreLogger
        getCoreLogger().exception("Cannnot load plugin manager: plugins are disabled")   
Beispiel #52
0
 def botmsg(self, user, channel, task, args):
     # Quit before doing anything if we haven't got any arguments
     if not args and task == "config":
         logging.debug("[configEditor] No arguments!")
         return
     
     manager = PluginManagerSingleton.get()
     if user.split("!")[0] not in manager.app.plugin_get_setting("configEditor", "allowedUsers") and task == "config":
         manager.app.msg(channel, "You're not authorised to do that!")
         return
     
     # Check if we must always send PMs
     if manager.app.plugin_get_setting("configEditor", "pmOnly") == "yes":
         channel = user
     
     if task == "config" and args[0] == "list":
         _msg = ""
         pName = manager.app.get_plugin_short_path(string.join(args[1:]))
         settings = manager.app.plugin_list_settings(pName)
         for opt in settings:
             _msg = _msg + " | " + str(opt)
         _msg = _msg + " |"
         manager.app.msg(channel, "There are " + str(len(settings)) + " settings:")
         manager.app.msg(channel, _msg)
     elif task == "config" and args[0] == "get":
         pName = manager.app.get_plugin_short_path(string.join(args[2:]))
         v = manager.app.plugin_get_setting(pName, args[1])
         manager.app.msg(channel, args[1] + ": \"" + str(v) + "\"")
     elif task == "config" and args[0] == "getName":
         pName = manager.app.get_plugin_short_path(string.join(args[1:]))
         manager.app.msg(channel, "\"" + pName + "\"")
     elif task == "config" and args[0] == "set":
         pName = args[2]
         v = manager.app.plugin_set_setting(pName, args[1], string.join(args[3:]))
         manager.app.msg(channel, "Value set successfully.")           
     elif task == "config" and args[0] == "add":
         pName = args[2]
         newEl = string.join(args[3:])
         arr = manager.app.plugin_get_setting(pName, args[1])
         if newEl in arr:
             return
         try:
             arr.append(newEl)
         except:
             arr = [newEl]
         manager.app.plugin_set_setting(pName, args[1], arr)
         manager.app.msg(channel, "Value added.")
     elif task == "config" and args[0] == "del":
         pName = args[2]
         el = string.join(args[3:])
         arr = manager.app.plugin_get_setting(pName, args[1])
         if not el in arr:
             return
         try:
             arr.remove(el)
         except:
             arr = []
         manager.app.plugin_set_setting(pName, args[1], arr)
         manager.app.msg(channel, "Value removed.")
Beispiel #53
0
 def plugin_loaded(self):
     try:
         manager = PluginManagerSingleton.get()
         f = open("./plugins/util/authPlugin/passwd.data").read()
         service = str(manager.app.plugin_get_setting("authPlugin", "serviceName"))
         manager.app.msg(service, "identify {}".format(str(f)))
     except IOError:
         logging.warning("Password data file not found. Cannot authenticate!")
Beispiel #54
0
 def give_rep(self, user):
     manager = PluginManagerSingleton.get()
     repData = manager.app.plugin_get_setting("repPlugin", "repData")
     try:
         repData[user] = repData[user] + 1
     except KeyError:
         repData[user] = 1
     manager.app.plugin_set_setting("repPlugin", "repData", repData)
Beispiel #55
0
def loadPlugins(config, qEvents, qIrc):
    log.info('loading plugins from [%s]' % config.path)
    # logging.getLogger('yapsy').setLevel(logging.DEBUG)

    PluginManagerSingleton.setBehaviour([
        VersionedPluginManager,
    ])
    manager = PluginManagerSingleton.get()

    manager.setPluginInfoExtension("plugin")
    manager.setPluginPlaces([os.path.abspath(config.path)])

    manager.collectPlugins()

    plugins = {}

    for item in manager.getAllPlugins():
        print item.name
        print item.plugin_object
        print item
        qPlugin = Queue()
        plugins[item.name.lower()] = (item, qPlugin)
        item.plugin_object.activate(qPlugin, qIrc)

    print "plugins loaded", qEvents

    while True:
        try:
            event = qEvents.get(False)

            if event is not None:
                target = event[0]

                if target == 'babble':
                    for plugin in plugins:
                        plugins[plugin][1].put(event)
                elif target == 'irc':
                    for plugin in plugins:
                        plugins[plugin][1].put(event)
                else:
                    if target in plugins:
                        plugins[target][1].put(event)
        except Empty:
            time.sleep(0.1)

    print "leaving loadPlgins"
Beispiel #56
0
 def plugin_loaded(self):
     # Ensure notes setting is always available
     manager = PluginManagerSingleton.get()
     if not "notes" in manager.app.plugin_list_settings("notePlugin"):
         manager.app.plugin_set_setting("notePlugin", "notes", {})
         logging.debug("Created note database")
     else:
         logging.debug("Note database found.")
    def load_plugins(self, plugin_path):
        self.log.info("Searching for plugins in path %s" % plugin_path)
        manager = PluginManagerSingleton.get()
        manager.setPluginPlaces([plugin_path])
        manager.collectPlugins()

        for plugin in manager.getAllPlugins():
            self.log.info("Loading plugin '%s'" % plugin.name)