Beispiel #1
0
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)
Beispiel #2
0
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)
Beispiel #3
0
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)
    plugin_manager.load_plugins("plugins")
    plugin_manager.run_plugins()

    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()
class TestPluginManager:
    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 setup(self):
        self.plugin_manager = PluginManager(None)
        self.loop = asyncio.new_event_loop()

    def test_bad_paths(self):
        assert_raises(FileNotFoundError,
                      self.plugin_manager._load_module, self.bad_path)

    def test_load_good_plugins(self):
        self.plugin_manager.load_plugin(self.good_plugin)
        self.plugin_manager.load_plugin(self.good_plugin_package)
        self.plugin_manager.resolve_dependencies()
        assert_in("test_plugin_2",
                  self.plugin_manager.list_plugins().keys())
        assert_in("test_plugin_1",
                  self.plugin_manager.list_plugins().keys())

    def test_load_bad_plugin(self):
        with assert_raises(SyntaxError):
            self.plugin_manager.load_plugin(self.bad_plugin)
            self.plugin_manager.resolve_dependencies()

    def test_load_plugin_dir(self):
        self.plugin_manager.load_from_path(self.plugin_path)
        self.plugin_manager.resolve_dependencies()
        assert_in("test_plugin_2",
                  self.plugin_manager.list_plugins())
        assert_in("test_plugin_1",
                  self.plugin_manager.list_plugins())
        assert_in("bad_plugin",
                  self.plugin_manager.failed)

    def test_the_do_method(self):
        self.plugin_manager.load_plugin(self.good_plugin)
        self.plugin_manager.load_plugin(self.good_plugin_package)
        self.plugin_manager.resolve_dependencies()
        result = self.loop.run_until_complete(
            self.plugin_manager.do("chat_sent", b""))
        assert_equals(result, True)

    def test_dependency_check(self):
        with assert_raises(ImportError):
            self.plugin_manager.load_plugin(self.dependent_plugins / 'b.py')
            self.plugin_manager.resolve_dependencies()

    def test_dependency_resolution(self):
        self.plugin_manager.load_plugins([
            self.dependent_plugins / 'a.py',
            self.dependent_plugins / 'b.py'
        ])

        self.plugin_manager.resolve_dependencies()

    def test_circular_dependency_error(self):
        with assert_raises(ImportError):
            self.plugin_manager.load_plugin(
                self.dependent_plugins / 'circular.py')
            self.plugin_manager.resolve_dependencies()

    def test_empty_overrides(self):
        self.plugin_manager.resolve_dependencies()
        owners = self.loop.run_until_complete(
            self.plugin_manager.get_overrides())
        assert_equal(owners, set())

    def test_override(self):
        self.plugin_manager.load_plugin(
            self.plugin_path / 'test_plugin_package')
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        self.plugin_manager.resolve_dependencies()
        self.plugin_manager.activate_all()
        overrides = self.loop.run_until_complete(
            self.plugin_manager.get_overrides())
        assert_equal(overrides, {'on_chat_sent'})

    def test_override_caching(self):
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        assert_equal(self.plugin_manager._overrides, set())
        assert_equal(self.plugin_manager._override_cache, set())
        self.plugin_manager.activate_all()
        self.loop.run_until_complete(self.plugin_manager.get_overrides())
        assert_is(self.plugin_manager._override_cache,
                  self.plugin_manager._activated_plugins)
        cache = self.plugin_manager._override_cache
        self.loop.run_until_complete(self.plugin_manager.get_overrides())
        assert_is(self.plugin_manager._override_cache, cache)


    def test_activate(self):
        self.plugin_manager.load_plugin(
            self.plugin_path / 'test_plugin_package')
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        self.plugin_manager.resolve_dependencies()
        self.plugin_manager.activate_all()
        assert_equal({x.name for x in self.plugin_manager._activated_plugins},
                     {'test_plugin_1', 'test_plugin_2'})
Beispiel #5
0
from plugin_manager import PluginManager
from app import app
from config import LISTEN_PORT, DEBUG

if __name__ == "__main__":
    pm = PluginManager()
    pm.load_plugins()

    if DEBUG:
        app.jinja_env.auto_reload = True
        app.config["TEMPLATES_AUTO_RELOAD"] = True
    app.run(host="0.0.0.0", debug=DEBUG, port=LISTEN_PORT)
Beispiel #6
0
class TestPluginManager:
    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 setup(self):
        self.plugin_manager = PluginManager(None)
        self.loop = asyncio.new_event_loop()

    def test_bad_paths(self):
        assert_raises(FileNotFoundError, self.plugin_manager._load_module,
                      self.bad_path)

    def test_load_good_plugins(self):
        self.plugin_manager.load_plugin(self.good_plugin)
        self.plugin_manager.load_plugin(self.good_plugin_package)
        self.plugin_manager.resolve_dependencies()
        assert_in("test_plugin_2", self.plugin_manager.list_plugins().keys())
        assert_in("test_plugin_1", self.plugin_manager.list_plugins().keys())

    def test_load_bad_plugin(self):
        with assert_raises(SyntaxError):
            self.plugin_manager.load_plugin(self.bad_plugin)
            self.plugin_manager.resolve_dependencies()

    def test_load_plugin_dir(self):
        self.plugin_manager.load_from_path(self.plugin_path)
        self.plugin_manager.resolve_dependencies()
        assert_in("test_plugin_2", self.plugin_manager.list_plugins())
        assert_in("test_plugin_1", self.plugin_manager.list_plugins())
        assert_in("bad_plugin", self.plugin_manager.failed)

    def test_the_do_method(self):
        self.plugin_manager.load_plugin(self.good_plugin)
        self.plugin_manager.load_plugin(self.good_plugin_package)
        self.plugin_manager.resolve_dependencies()
        result = self.loop.run_until_complete(
            self.plugin_manager.do("chat_sent", b""))
        assert_equals(result, True)

    def test_dependency_check(self):
        with assert_raises(ImportError):
            self.plugin_manager.load_plugin(self.dependent_plugins / 'b.py')
            self.plugin_manager.resolve_dependencies()

    def test_dependency_resolution(self):
        self.plugin_manager.load_plugins(
            [self.dependent_plugins / 'a.py', self.dependent_plugins / 'b.py'])

        self.plugin_manager.resolve_dependencies()

    def test_circular_dependency_error(self):
        with assert_raises(ImportError):
            self.plugin_manager.load_plugin(self.dependent_plugins /
                                            'circular.py')
            self.plugin_manager.resolve_dependencies()

    def test_empty_overrides(self):
        self.plugin_manager.resolve_dependencies()
        owners = self.loop.run_until_complete(
            self.plugin_manager.get_overrides())
        assert_equal(owners, set())

    def test_override(self):
        self.plugin_manager.load_plugin(self.plugin_path /
                                        'test_plugin_package')
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        self.plugin_manager.resolve_dependencies()
        self.plugin_manager.activate_all()
        overrides = self.loop.run_until_complete(
            self.plugin_manager.get_overrides())
        assert_equal(overrides, {'on_chat_sent'})

    def test_override_caching(self):
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        assert_equal(self.plugin_manager._overrides, set())
        assert_equal(self.plugin_manager._override_cache, set())
        self.plugin_manager.activate_all()
        self.loop.run_until_complete(self.plugin_manager.get_overrides())
        assert_is(self.plugin_manager._override_cache,
                  self.plugin_manager._activated_plugins)
        cache = self.plugin_manager._override_cache
        self.loop.run_until_complete(self.plugin_manager.get_overrides())
        assert_is(self.plugin_manager._override_cache, cache)

    def test_activate(self):
        self.plugin_manager.load_plugin(self.plugin_path /
                                        'test_plugin_package')
        self.plugin_manager.load_plugin(self.plugin_path / 'test_plugin_2.py')
        self.plugin_manager.resolve_dependencies()
        self.plugin_manager.activate_all()
        assert_equal({x.name
                      for x in self.plugin_manager._activated_plugins},
                     {'test_plugin_1', 'test_plugin_2'})