From e66ed05ef708c1eb85823a6913029f8a73d80adc Mon Sep 17 00:00:00 2001 From: magmaus3 Date: Sun, 20 Nov 2022 13:21:45 +0100 Subject: [PATCH] Hook system improvements + Allow assigning multiple hook types to a class. + Add hook types, that are executed (almost) on every occasion. --- customiwmserver/hook_system.py | 41 ++++++++++++++++---------------- customiwmserver/hooks/webhook.py | 5 ++-- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/customiwmserver/hook_system.py b/customiwmserver/hook_system.py index db88b15..f502a9b 100644 --- a/customiwmserver/hook_system.py +++ b/customiwmserver/hook_system.py @@ -11,36 +11,35 @@ class HookMan: def __new__(cls): return reduce(lambda x, y: y(x), cls.hooks, super(HookMan, cls).__new__(cls)) - def execute_hooks(self, hook_type, *args, **kwargs): + def execute_hooks(self, hook_type, isAdminAction=False, *args, **kwargs): if hook_type not in self.hooks: - return - - for hook in self.hooks[hook_type]: - print(f"Executing hook {hook.__name__}") + hook_type = None + + if isAdminAction: + admin_hooks = self.hooks["admin*"] + else: + admin_hooks = [] + + for hook in \ + (lambda: self.hooks[hook_type] if hook_type in self.hooks else [])() \ + + (lambda: self.hooks["*"] if "*" in self.hooks else [])() \ + + admin_hooks: + print(f"\tExecuting hook {hook.__name__}") try: - hook()(*args, **kwargs) + hook()(hook_type=hook_type, isAdminAction=isAdminAction, *args, **kwargs) except Exception as exc: raise HookException(exc) @classmethod def add_hook(cls, func, *args, **kwargs): """Adds a hook.""" - hook_type = func.hook_type - if hook_type in cls.hooks: - cls.hooks[hook_type] = cls.hooks[hook_type] + [func] - else: - cls.hooks[hook_type] = [func] + hook_types = func.hook_type + for hook_type in hook_types: + if hook_type in cls.hooks: + cls.hooks[hook_type] = cls.hooks[hook_type] + [func] + else: + cls.hooks[hook_type] = [func] hook = HookMan() -# @hook.add_hook -# class example_hook: -# """Example hook.""" -# hook_type = "player_login" -# -# def __call__(self, *args, **kwargs): -# print("Hook player_login,", kwargs) -# -# -hook.execute_hooks("player_login", hello="john") diff --git a/customiwmserver/hooks/webhook.py b/customiwmserver/hooks/webhook.py index 4f2680c..658ab24 100644 --- a/customiwmserver/hooks/webhook.py +++ b/customiwmserver/hooks/webhook.py @@ -11,8 +11,9 @@ hook = hook_system.hook class Login: # Different hook types are executed at different places. # In this case, the hook is executed when a user logs in. + # # Check the documentation for more hook types. - hook_type = "player_login" + hook_type = ["player_login"] - def __call__(self, *args, **kwargs): + def __call__(self, hook_type, *args, **kwargs): print("LOGIN HOOK:", args, kwargs)