def __init__(self, *args, **kwargs): discord.Client.__init__(self, *args, **kwargs) self.redis_url = kwargs.get('redis_url') self.db = Db(self.redis_url) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = []
def startup(config_path=DEFAULT_SETTINGS_FILE): #init logging config = ConfigParser.ConfigParser() config.read(config_path) setup_logging(config) #load the config file and start the listener, daemon logging.debug('reading setting from: %s' % config_path) #Load the plugin manager to get a handle to the plugins. _plugin_manager = PluginManager(config) locator = _plugin_manager.get_resource_locator() datastore = _plugin_manager.get_datastore() driver = _plugin_manager.get_driver() _registrar = Registrar(datastore, driver) #should the listener be started? start_server = config.getboolean('DEFAULT', 'start_server') if start_server: server.set_registrar(registrar) Thread.start(server.start()) #start looking for backends and updating the driver #THIS CALL WILL NOT RETURN daemon.start(_registrar, locator, config)
def startup(config_path=DEFAULT_SETTINGS_FILE): #init logging setup_logging() #load the config file and start the listener, daemon logging.debug("init starting up") config = ConfigParser.ConfigParser() logging.debug('reading setting from: %s' % config_path) config.read(config_path) #Load the plugin manager to get a handle to the plugins. _plugin_manager = PluginManager(config) locator = _plugin_manager.get_resource_locator() datastore = _plugin_manager.get_datastore() driver = _plugin_manager.get_driver() _registrar = Registrar(datastore, driver) #should the listener be started? start_server = config.getboolean('DEFAULT', 'start_server') if start_server: server.set_registrar(registrar) Thread.start(server.start()) #start looking for backends and updating the driver #THIS CALL WILL NOT RETURN daemon.start(_registrar, locator, config)
def test_prepare( self, mock_config, mock_path, mock_sys, mock_load_plugins ): mock_factory = Mock() mock_path.child.return_value = Mock(path='test child') mock_config.return_value = Mock( plugin_path='test path', config={ 'initial_plugins': 'test initial plugins' } ) pm = PluginManager(mock_factory) pm.prepare() mock_path.child.assert_called_with('test path') mock_sys.path.append.assert_called_with('test child') self.assertEqual(mock_load_plugins.call_count, 2) mock_load_plugins.assert_has_calls( [ call( [ 'core.admin_commands_plugin', 'core.colored_names', 'core.command_plugin', 'core.player_manager_plugin', 'core.starbound_config_manager' ] ), call('test initial plugins') ] )
def main(): # Read config config = ConfigParser() config.readfp(open(os.path.dirname(os.path.abspath(__file__)) + "/smtpd.cfg.default")) config.read(["smtpd.cfg",]) # Configure the logger logging.basicConfig(level=getattr(logging, config["logging"]["log_level"].upper()), format='%(levelname)s: %(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') loop = asyncio.get_event_loop() # Init plugin manager plugin_manager = PluginManager(loop) logger.info("Starting smtpd on {}:{}".format(config["smtpd"]["host"], config["smtpd"]["port"])) cont = CustomIdentController( MailHandler(loop, config, plugin_manager), loop=loop, ident_hostname=config["smtpd"]["hostname"], ident=config["smtpd"]["ident"], hostname=config["smtpd"]["host"], port=config["smtpd"]["port"]) cont.start() # Ugly but whatever, wait until the controller thread finishes (wtf why do they start a thread) threads = threading.enumerate() for thread in threads: if not threading.current_thread() == thread: thread.join() plugin_manager.stop_plugins()
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def get_input_plugins_config(): """Append all configs of the input plugins.""" config = "" plugin_manager = PluginManager(PLUGINS_FILE) input_plugins = plugin_manager.get_input_plugins() for app, conf in input_plugins.items(): config += conf + "\n\n\n" return config
def get_tags_config(): """Returns a list of all the tags (applications).""" plugin_manager = PluginManager(PLUGINS_FILE) tags = plugin_manager.get_tags() tags_config = "" for tag in tags: line = " {} = '{}_cpu'\n".format(tag, tag) tags_config += line return tags_config
def __init__(self): self.plugin_path = path / 'tests' / 'test_plugins' self.good_plugin = self.plugin_path / 'test_plugin_2.py' self.good_plugin_package = self.plugin_path / 'test_plugin_package' self.bad_plugin = self.plugin_path / 'bad_plugin' self.bad_path = self.plugin_path / 'bad_path.py' self.dependent_plugins = self.plugin_path / "dependent_plugins" self.plugin_manager = PluginManager(None) self.loop = None
def __init__(self, context=None, completekey='tab', stdin=sys.stdin, stdout=sys.stdout, logger=None): cmd.Cmd.__init__(self, completekey, stdin, stdout) self.plugin_mgr = PluginManager() self.ctx = context self.use_rawinput = 1 self.ioqueue = [] self.stdout = OutputWrapper(stdout, logger=logger) self.stdin = InputWrapper(stdin, logger=logger) self.stderr = OutputWrapper(sys.stderr, level=logging.ERROR, logger=logger)
def build_plugin_manager(): directories = ["jarviscli/plugins", "custom"] directories = _rel_path_fix(directories) plugin_manager = PluginManager() for directory in directories: plugin_manager.add_directory(directory) return plugin_manager
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.redis_url = kwargs.get('redis_url') self.mongo_url = kwargs.get('mongo_url') self.dd_agent_url = kwargs.get('dd_agent_url') self.db = Db(self.redis_url, self.mongo_url, self.loop) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = [] self.stats = DDAgent(self.dd_agent_url)
def __init__(self, config): self.terminated = False # Flag used to stop the service self.config = config # Create plugin instances and add them to manager so that they get control periodically # Note: plugins should be derived from class Plugin and implement update() function self.pluginManager = PluginManager() self.udpServer = UDPServer(config.scpHost, config.scpPort, self.onRequestReceived) self.pluginManager.add(self.udpServer)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = [] self.__name__ = APP_NAME self.__version__ = APP_VERSION self.__author__ = APP_AUTHOR self.__copyright__ = "Copyright (c){} {}".format( '2016-2020', self.__author__)
def __init__(self, prefix, token, cwd): Client.__init__(self) self.prefix = prefix self.token = token self.cwd = cwd self.plugin_manager = PluginManager(self, '%s/plugins' % self.cwd) self.plugin_manager.load_plugins() user_agent = get_resource(self.cwd, 'user_agent') self.client_session = ClientSession(headers={'User-Agent': user_agent})
class JoyManager(): def __init__(self): self.pre_status = None self.history = StatusHistory(max_length=10) self.controller_type = rospy.get_param('~controller_type', 'xbox') self.plugins = rospy.get_param('~plugins', []) self.current_plugin_index = 0 if self.controller_type == 'xbox': self.JoyStatus = XBoxStatus elif self.controller_type == 'ps3': self.JoyStatus = PS3Status elif self.controller_type == 'ps3wired': self.JoyStatus = PS3WiredStatus elif self.controller_type == 'auto': s = rospy.Subscriber('/joy', Joy, autoJoyDetect) while not rospy.is_shutdown(): if AUTO_DETECTED_CLASS: self.JoyStatus = AUTO_DETECTED_CLASS s.unregister() break else: rospy.sleep(1) self.plugin_manager = PluginManager('jsk_teleop_joy') self.loadPlugins() def loadPlugins(self): self.plugin_manager.loadPlugins() self.plugin_instances = self.plugin_manager.loadPluginInstances(self.plugins) def nextPlugin(self): rospy.loginfo('switching to next plugin') self.current_plugin_index = self.current_plugin_index + 1 if len(self.plugin_instances) == self.current_plugin_index: self.current_plugin_index = 0 self.current_plugin.disable() self.current_plugin = self.plugin_instances[self.current_plugin_index] self.current_plugin.enable() def start(self): if len(self.plugin_instances) == 0: rospy.logfatal('no valid plugins are loaded') return self.current_plugin = self.plugin_instances[0] self.current_plugin.enable() self.joy_subscriber = rospy.Subscriber('/joy', Joy, self.joyCB) def joyCB(self, msg): status = self.JoyStatus(msg) if self.pre_status and status.select and not self.pre_status.select: self.nextPlugin() else: self.current_plugin.joyCB(status, self.history) self.pre_status = status self.history.add(status)
def test_installed_plugins(self, mock_config, mock_path, mock_sys): mock_child = Mock(path='test child') mock_child.globChildren.return_value = [ Mock(basename=lambda: 'plugin'), Mock(basename=lambda: None), Mock(basename=lambda: 'core') ] mock_path.child.return_value = mock_child pm = PluginManager(Mock()) result = pm.installed_plugins() self.assertListEqual(result, ['plugin'])
def startup(): #load the config file and start the listener, daemon config = ConfigParser.ConfigParser() config.read('C:\dev\projects\elasticd\conf\settings.cfg') logging.debug("init starting up") p_manager = PluginManager(config) datastore = p_manager.get_datastore() registrar = Registrar(datastore) server.set_registrar(registrar) server.start()
class StarryPyServerFactory(ServerFactory): """ Factory which creates `StarryPyServerProtocol` instances. """ protocol = StarryPyServerProtocol def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager() self.plugin_manager.activate_plugins() def stopFactory(self): """ Called when the factory is stopped. Saves the configuration. :return: None """ self.config.save() def broadcast(self, text, channel=1, world='', name=''): """ Convenience method to send a broadcasted message to all clients on the server. :param text: Message text :param channel: Channel to broadcast on. 0 is global, 1 is planet. :param world: World :param name: The name to prepend before the message, format is <name> :return: None """ for p in self.protocols.itervalues(): try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.", exc_info=True) def buildProtocol(self, address): """ Builds the protocol to a given address. :rtype : Protocol """ logger.debug("Building protocol to address %s", address) p = ServerFactory.buildProtocol(self, address) return p
def test_map_plugin_packets(self, mock_config, mock_path, mock_sys): mock_plugin = Mock() mock_plugin.name = 'Test' mock_plugin.overridden_packets = { 1: { 'on': 'add me on 1', 'after': 'add me after 1' } } mock_plugin2 = Mock() mock_plugin2.name = 'Test2' mock_plugin2.overridden_packets = { 2: { 'on': 'add me on 2' }, 3: { 'after': 'add me after 2' } } pm = PluginManager(Mock()) pm.map_plugin_packets(mock_plugin) self.assertDictEqual( pm.packets, { 1: { 'on': {'Test': (mock_plugin, 'add me on 1')}, 'after': {'Test': (mock_plugin, 'add me after 1')} } } ) pm.map_plugin_packets(mock_plugin2) self.assertDictEqual( pm.packets, { 1: { 'on': {'Test': (mock_plugin, 'add me on 1')}, 'after': {'Test': (mock_plugin, 'add me after 1')} }, 2: { 'on': {'Test2': (mock_plugin2, 'add me on 2')} }, 3: { 'after': {'Test2': (mock_plugin2, 'add me after 2')} } } )
def start_qq( no_gui=False, new_user=False, debug=False, vpath="./v.jpg", smart_qq_refer="http://d1.web2.qq.com/proxy.html?v=20030916001&callback=1&id=2", cookie_file="cookie.data", plugin_setting={ "plugin_root": "./plugins", "plugins": [ "pluginmanage", "test1" ], "timers": [ "timer_weather" ] }, dbhandler='sqlite:///message-record.db', ): bot = QQBot(vpath, smart_qq_refer, cookie_file) # update the modules and enbale utf-8 decoding. reload(sys) sys.setdefaultencoding("utf-8") # set the mode for logger. if debug: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) # login bot.login(no_gui) # initialze the handler handler = SuperHandler(dbhandle=dbhandler, workers=5) handler.update_group_list(bot) logger.info("Update group list...") # dbhandler = DBHandler() # initialize the plugin manager plmanager = PluginManager(plugin_setting["plugin_root"]) timermanager = PluginManager(plugin_setting["plugin_root"]) # load the plugins for plugin_name in plugin_setting["plugins"]: # plmanager.add_plugin(plugin_name) try: plmanager.add_plugin(plugin_name) except Exception, e: print(e) logger.error("Failed to load plugin: %s" % plugin_name)
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} try: self.plugin_manager = PluginManager(factory=self) except FatalPluginError: logger.critical("Shutting Down.") sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time)
class Bot(Client): def __init__(self, prefix, token, cwd): Client.__init__(self) self.prefix = prefix self.token = token self.cwd = cwd self.plugin_manager = PluginManager(self, '%s/plugins' % self.cwd) self.plugin_manager.load_plugins() user_agent = get_resource(self.cwd, 'user_agent') self.client_session = ClientSession(headers={'User-Agent': user_agent}) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.plugin_manager.unload_plugins() self.client_session.close() self.close() @coroutine async def on_message(self, message_object): message = split_nospace(message_object.content, ' ') if not message or len(message[0]) < 2: return if not message[0][0] == self.prefix: return command = message[0][1:] arguments = None if len(message) > 1: arguments = ' '.join(message[1:]) return_value = await self.plugin_manager.execute_message( command, arguments, message_object) if return_value: try: await self.delete_message(message_object) except errors.NotFound: pass def run_bot(self): self.run(self.token)
def create_menubar(self): menubar = QMenuBar() file_menu = menubar.addMenu('&File') file_menu.addAction('&New', self.new_script).setShortcut(QKeySequence.New) file_menu.addAction('Save As...', self.save_script_as).setShortcut( QKeySequence.SaveAs) file_menu.addAction('&Open', self.open_script).setShortcut(QKeySequence.Open) file_menu.addAction('&Save', self.save_script).setShortcut(QKeySequence.Save) file_menu.addAction('&Quit', self.close) # Script actions script_menu = menubar.addMenu('&Script') script_menu.addAction('&Evaluate', self.plugin_handler.evaluate_current_script) script_menu.addAction('&Copy Hex', self.script_editor.copy_hex) # Settings and tool toggling tools_menu = menubar.addMenu('&Tools') tools_menu.addAction('&Settings', self.show_settings_dialog) tools_menu.addAction('&Plugin Manager', lambda: PluginManager(self).exec_()) tools_menu.addSeparator() self.plugin_handler.create_menu(tools_menu) help_menu = menubar.addMenu('&Help') help_menu.addAction('&About', self.do_about) help_menu.addAction('&Quick Tips', self.do_quick_tips) self.setMenuBar(menubar)
def __init__(self, plugin_package="jsk_teleop_joy"): self.state = self.STATE_INITIALIZATION self.pre_status = None self.history = StatusHistory(max_length=10) self.menu_pub = rospy.Publisher("/overlay_menu", OverlayMenu) self.controller_type = rospy.get_param('~controller_type', 'auto') self.plugins = rospy.get_param('~plugins', {}) self.current_plugin_index = 0 self.selecting_plugin_index = 0 #you can specify the limit of the rate via ~diagnostic_period self.diagnostic_updater = DiagnosticUpdater() self.diagnostic_updater.setHardwareID("teleop_manager") self.diagnostic_updater.add("State", self.stateDiagnostic) self.diagnostic_updater.add("Plugin Status", self.pluginStatusDiagnostic) #self.diagnostic_updater.add("Joy Input", self.joyInputDiagnostic) self.diagnostic_updater.update() if self.controller_type == 'xbox': self.JoyStatus = XBoxStatus elif self.controller_type == 'ps3': self.JoyStatus = PS3Status elif self.controller_type == 'ps3wired': self.JoyStatus = PS3WiredStatus elif self.controller_type == 'ipega': self.JoyStatus = IpegaStatus elif self.controller_type == 'auto': s = rospy.Subscriber('/joy', Joy, autoJoyDetect) self.state = self.STATE_WAIT_FOR_JOY error_message_published = False r = rospy.Rate(1) while not rospy.is_shutdown(): self.diagnostic_updater.update() if AUTO_DETECTED_CLASS == "UNKNOWN": if not error_message_published: rospy.logfatal("unknown joy type") error_message_published = True r.sleep() elif AUTO_DETECTED_CLASS: self.JoyStatus = AUTO_DETECTED_CLASS s.unregister() break else: r.sleep() self.diagnostic_updater.update() self.plugin_manager = PluginManager(plugin_package) self.loadPlugins()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.redis_url = kwargs.get('redis_url') self.mongo_url = kwargs.get('mongo_url') self.dd_agent_url = kwargs.get('dd_agent_url') self.sentry_dsn = kwargs.get('sentry_dsn') self.db = Db(self.redis_url, self.mongo_url, self.loop) self.plugin_manager = PluginManager(self) self.plugin_manager.load_all() self.last_messages = [] self.stats = DDAgent(self.dd_agent_url) self.voice_sessions_ids = dict() if self.shard_id is not None: self.shard = [self.shard_id, self.shard_count] else: self.shard = [0, 1]
def test_get_plugin_name_from_file(self): mock_f = Mock() mock_f.isdir.return_value = True mock_f.basename.return_value = 'test base' result = PluginManager.get_plugin_name_from_file(mock_f) self.assertEqual(result, 'test base') self.assertTrue(mock_f.isdir.called) self.assertTrue(mock_f.basename.called) mock_f = Mock() mock_f.isdir.return_value = False result = PluginManager.get_plugin_name_from_file(mock_f) self.assertIsNone(result) self.assertTrue(mock_f.isdir.called) self.assertFalse(mock_f.basename.called)
class ServerFactory: def __init__(self): try: self.protocols = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config( path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.Task(self.plugin_manager.get_overrides()) except Exception as e: print("Exception encountered during server startup.") print(e) loop.stop() sys.exit() def remove(self, protocol): self.protocols.remove(protocol) def __call__(self, reader, writer): server = StarryPyServer(reader, writer, factory=self) self.protocols.append(server) print(self.protocols)
class ServerFactory: def __init__(self): try: self.protocols = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config(path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.Task(self.plugin_manager.get_overrides()) except Exception as e: print("Exception encountered during server startup.") print(e) loop.stop() sys.exit() def remove(self, protocol): self.protocols.remove(protocol) def __call__(self, reader, writer): server = StarryPyServer(reader, writer, factory=self) self.protocols.append(server) print(self.protocols)
def __init__(self): try: self.protocols = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config(path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.Task(self.plugin_manager.get_overrides()) except Exception as e: print("Exception encountered during server startup.") print(e) loop.stop() sys.exit()
def _plugin_manager_default(self): """ Trait initializer. """ # Do the import here to emphasize the fact that this is just the # default implementation and that the application developer is free # to override it! from plugin_manager import PluginManager return PluginManager(application=self)
def main(): # Handle command line inputs p = argparse.ArgumentParser( description= "Reads logs in the Apache Combined Log Format and the Common Log Format." ) p.add_argument('-f', help='Tail the log file.', dest='tail', action='store_true') p.add_argument('-l', help='Path to logfile.', dest='file') p.add_argument('-v', help='Enable verbose.', dest='verbose', action='store_true') p.add_argument('-p', help='Arguments for the plugins. Splitted with spaces', dest='plugs', nargs='+') p.add_argument('-s', help='Silent. Superseedes -v and disables logging.', dest='silent', action='store_true') p.set_defaults(verbose=False, silent=False, file='/tmp/access.log', tail=False, plugs=[]) args = p.parse_args() logger_to_stdout() if args.verbose: set_verbose() if args.silent: set_silent() manager = PluginManager() manager.load_plugins(args.plugs) parser.tail(args.file, manager, tail=args.tail)
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager(factory=self) try: self.plugin_manager.prepare() except FatalPluginError: logger.critical('Shutting Down.') sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time) logger.debug( 'Factory created, endpoint of port %d', self.config.bind_port )
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager() self.plugin_manager.activate_plugins()
def __init__(self): try: self.connections = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config(path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager, factory=self) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.ensure_future(self.plugin_manager.get_overrides()) except Exception as err: logger.exception("Error during server startup.", exc_info=True) loop.stop() sys.exit()
def test_deactivate_plugins( self, mock_config, mock_path, mock_sys, mock_reversed, mock_de_map ): mock_reversed.side_effect = reversed pm = PluginManager(Mock()) pm.load_order = [1] pm.plugins = { 1: Mock(name='1'), } pm.deactivate_plugins() mock_reversed.assert_called_with([1]) self.assertTrue(pm.plugins[1].deactivate.called) mock_de_map.assert_called_with(pm.plugins[1])
def __init__(self, config): """ Sets up initial bot data and the PluginManager which loads inital plugins. ... Parameters ---------- config: Config Configuration object containing data found within the bot's configuration file. """ self.logger = logging.getLogger('bot_log') self.directory = config.bot_dir self.base_url = "https://api.telegram.org/bot"+config.token+"/" self.sleep_interval = config.sleep_interval self.username = json.loads(requests.get(self.base_url + "getMe").text)["result"]["username"] self.plugin_manager = PluginManager(config, self) print(self.plugin_manager.list_commands()) print(self.plugin_manager.list_listeners())
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager(factory=self) self.plugin_manager.activate_plugins() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time)
class KeyLoggerDaemon: """ A basic implementation of a python key logger stores logged keys per-window per-date in a json format Considerations: - PyHook isn't great and can miss keystrokes - Can cause a noticeable slow down on older machines - Window may not always be identifiable - All keystrokes are returned in uppercase (may be able to fix this with ASCII repr) - commas, brackets, hashes etc are returned as Oem_nameOfPunctuation (may be able to fix this with ASCII repr) """ def __init__(self): self.__hook = hook = pyHook.HookManager() hook.KeyDown = self.__write_event hook.HookKeyboard() self.plugin = PluginManager().plugin def __write_event(self, event: pyHook.KeyboardEvent): """ keyboard press callback, process each key press as necessary. then writes the data out to target plugin """ # print(event.WindowName, event.Key, chr(int(event.Ascii))) # debug print(event.Key) key = chr(int(event.Ascii)) if key == '\x00': key = event.Key self.plugin.write(datetime.now(), event.WindowName, key) return True # required by hook manager @staticmethod def watch(): """ Starts the hook event loop """ pythoncom.PumpMessages()
def test_de_map_plugin_packets(self, mock_config, mock_path, mock_sys): mock_plugin = Mock() mock_plugin.name = 'Test' pm = PluginManager(Mock()) pm.packets = { 1: { 'on': { 'Test': 'remove me' }, 'after': { 'Test2': 'test' } }, 2: { 'on': { 'Test': 'remove me', 'Test3': 'test' }, 'after': { 'Test': 'remove me' }, } } pm.de_map_plugin_packets(mock_plugin) self.assertDictEqual( pm.packets, { 1: { 'on': {}, 'after': { 'Test2': 'test' } }, 2: { 'on': { 'Test3': 'test' }, 'after': {}, } })
def test_de_map_plugin_packets(self, mock_config, mock_path, mock_sys): mock_plugin = Mock() mock_plugin.name = 'Test' pm = PluginManager(Mock()) pm.packets = { 1: { 'on': { 'Test': 'remove me' }, 'after': {'Test2': 'test'} }, 2: { 'on': { 'Test': 'remove me', 'Test3': 'test' }, 'after': { 'Test': 'remove me' }, } } pm.de_map_plugin_packets(mock_plugin) self.assertDictEqual( pm.packets, { 1: { 'on': {}, 'after': {'Test2': 'test'} }, 2: { 'on': { 'Test3': 'test' }, 'after': {}, } } )
def test_prepare(self, mock_config, mock_path, mock_sys, mock_load_plugins): mock_factory = Mock() mock_path.child.return_value = Mock(path='test child') mock_config.return_value = Mock( plugin_path='test path', config={'initial_plugins': 'test initial plugins'}) pm = PluginManager(mock_factory) pm.prepare() mock_path.child.assert_called_with('test path') mock_sys.path.append.assert_called_with('test child') self.assertEqual(mock_load_plugins.call_count, 2) mock_load_plugins.assert_has_calls([ call([ 'core.admin_commands_plugin', 'core.colored_names', 'core.command_plugin', 'core.player_manager_plugin', 'core.starbound_config_manager' ]), call('test initial plugins') ])
def test_map_plugin_packets(self, mock_config, mock_path, mock_sys): mock_plugin = Mock() mock_plugin.name = 'Test' mock_plugin.overridden_packets = { 1: { 'on': 'add me on 1', 'after': 'add me after 1' } } mock_plugin2 = Mock() mock_plugin2.name = 'Test2' mock_plugin2.overridden_packets = { 2: { 'on': 'add me on 2' }, 3: { 'after': 'add me after 2' } } pm = PluginManager(Mock()) pm.map_plugin_packets(mock_plugin) self.assertDictEqual( pm.packets, { 1: { 'on': { 'Test': (mock_plugin, 'add me on 1') }, 'after': { 'Test': (mock_plugin, 'add me after 1') } } }) pm.map_plugin_packets(mock_plugin2) self.assertDictEqual( pm.packets, { 1: { 'on': { 'Test': (mock_plugin, 'add me on 1') }, 'after': { 'Test': (mock_plugin, 'add me after 1') } }, 2: { 'on': { 'Test2': (mock_plugin2, 'add me on 2') } }, 3: { 'after': { 'Test2': (mock_plugin2, 'add me after 2') } } })
def main(): # create the Application app = QtWidgets.QApplication(sys.argv) # create the event loop event_loop = QEventLoop(app) asyncio.set_event_loop(event_loop) # Create the Gui main_window = MainWindow() # plugins to include different websites (and listeners?) plugin_manager = PluginManager() plugin_manager.register_main_window(main_window) # User Settings settings_manager = SettingsManager() settings_manager.register_main_window(main_window) settings_manager.register_plugin_manager(plugin_manager) # listeners handeled separatly for now listener_interface = pluginmanager.PluginInterface() listener_interface.collect_plugins(plugins) listener_list = listener_interface.get_instances() # flake8: noqa # main_window.central_widget.message_area.listeners = listener_list main_window.show() try: event_loop.run_forever() except KeyboardInterrupt: pass app.deleteLater() plugin_manager.terminate_plugins() event_loop.close() sys.exit()
def startup(config_path=DEFAULT_SETTINGS_FILE): ''' Load the config file and start the listener, daemon ''' logging.debug('Init starting up') config = ConfigParser.ConfigParser() logging.debug('Reading setting from: %s' % config_path) config.read(config_path) ''' Load the plugin manager to get a handle to the plugins. ''' plugin_manager = PluginManager(config) _locator = plugin_manager.get_resource_locator() _datastore = plugin_manager.get_datastore() _driver = plugin_manager.get_driver() _registrar = Registrar(_datastore, _driver) ''' Should the listener be started? ''' start_server = config.getboolean('DEFAULT', 'start_server') if start_server: server.set_registrar(registrar) thread.start(server.start()) ''' Start looking for backends and updating the driver ''' ''' THIS CALL WILL NOT RETURN ''' daemon.start(_registrar, _locator, config)
def main(): cfg = SafeConfigParser() cfg.read('mysql_db.cfg') plugin_manager = PluginManager() connection = MySQLdb.connect(user=cfg.get('main', 'user'), passwd=cfg.get('main', 'passwd'), host=cfg.get('main', 'host')) env_vars = plugin_manager.call_method('generate', keywords=['provider'], args={'connection': connection}) plugin_manager.call_method('process', keywords=['consumer'], args={'connection': connection, 'env_vars': env_vars}) plugin_manager.call_method('report')
def __init__(self): try: self.protocols = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config( path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.Task(self.plugin_manager.get_overrides()) except Exception as e: print("Exception encountered during server startup.") print(e) loop.stop() sys.exit()
def __init__(self): try: self.connections = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config( path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager, factory=self) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.ensure_future(self.plugin_manager.get_overrides()) except Exception as err: logger.exception("Error during server startup.", exc_info=True) loop.stop() sys.exit()
class ServerFactory: def __init__(self): try: self.protocols = [] self.configuration_manager = ConfigurationManager() self.configuration_manager.load_config( path / 'config' / 'config.json', default=True) self.plugin_manager = PluginManager(self.configuration_manager, factory=self) self.plugin_manager.load_from_path( path / self.configuration_manager.config.plugin_path) self.plugin_manager.resolve_dependencies() self.plugin_manager.activate_all() asyncio.Task(self.plugin_manager.get_overrides()) except Exception as e: logger.exception("Error during server startup.", exc_info=True) loop.stop() sys.exit() @asyncio.coroutine def broadcast(self, messages, *, world="", name="", channel=0, client_id=0): for protocol in self.protocols: try: yield from protocol.send_message(messages, world=world, name=name, channel=channel, client_id=client_id) except ConnectionError: continue def remove(self, protocol): self.protocols.remove(protocol) def __call__(self, reader, writer): server = StarryPyServer(reader, writer, factory=self) self.protocols.append(server) def kill_all(self): for protocol in self.protocols: protocol.die()
def __init__(self, api_cls, parent = None): super(MainWindow, self).__init__() self.api=api_cls me = self.api.get_account_settings() self.mystatus = self.api.show_user(screen_name=me['screen_name']) self.myid = self.mystatus['id'] self.status_array = [] self.buttoncount = 0 self.init_menu() self.plugin_mng = PluginManager('./plugin', ['on_status']) self.plugin = {} for cls_name in self.plugin_mng.get_plugin_names(): #インスタンスを生成 self.plugin[cls_name] = self.plugin_mng.plugin_dict[cls_name](self) self.initUI() self.streamer = MyStreamer(self, CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET) self.streamer_thread = StreamerThread(streamer=self.streamer, on_finished=self.streamer.disconnect) self.streamer_thread.start() init_status = self.api.get_home_timeline(count=20) for status in init_status[::-1]: self.status_received(status)
def __init__(self): self.pre_status = None self.history = StatusHistory(max_length=10) self.controller_type = rospy.get_param('~controller_type', 'xbox') self.plugins = rospy.get_param('~plugins', []) self.current_plugin_index = 0 if self.controller_type == 'xbox': self.JoyStatus = XBoxStatus elif self.controller_type == 'ps3': self.JoyStatus = PS3Status elif self.controller_type == 'ps3wired': self.JoyStatus = PS3WiredStatus elif self.controller_type == 'auto': s = rospy.Subscriber('/joy', Joy, autoJoyDetect) while not rospy.is_shutdown(): if AUTO_DETECTED_CLASS: self.JoyStatus = AUTO_DETECTED_CLASS s.unregister() break else: rospy.sleep(1) self.plugin_manager = PluginManager('jsk_teleop_joy') self.loadPlugins()