2022-11-19 12:51:28 +00:00
|
|
|
from functools import reduce
|
|
|
|
|
|
|
|
|
|
|
|
class HookException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class HookMan:
|
|
|
|
hooks = {}
|
|
|
|
|
|
|
|
def __new__(cls):
|
|
|
|
return reduce(lambda x, y: y(x), cls.hooks, super(HookMan, cls).__new__(cls))
|
|
|
|
|
2022-11-20 12:21:45 +00:00
|
|
|
def execute_hooks(self, hook_type, isAdminAction=False, *args, **kwargs):
|
2022-11-19 12:51:28 +00:00
|
|
|
if hook_type not in self.hooks:
|
2022-11-20 12:21:45 +00:00
|
|
|
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__}")
|
2022-11-19 12:51:28 +00:00
|
|
|
try:
|
2022-11-20 12:21:45 +00:00
|
|
|
hook()(hook_type=hook_type, isAdminAction=isAdminAction, *args, **kwargs)
|
2022-11-19 12:51:28 +00:00
|
|
|
except Exception as exc:
|
|
|
|
raise HookException(exc)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def add_hook(cls, func, *args, **kwargs):
|
|
|
|
"""Adds a hook."""
|
2022-11-20 12:21:45 +00:00
|
|
|
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]
|
2022-11-19 12:51:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
hook = HookMan()
|
|
|
|
|