ovtk_audiencekit/plugins/PluginBase.py

118 lines
3.7 KiB
Python

from dataclasses import asdict
from abc import ABC, abstractmethod
from functools import reduce
from operator import getitem
import logging
import kdl
from core.Config import kdl_parse_config
class PluginError(Exception):
def __init__(self, source, message):
self.source = source
self.message = message
def __str__(self):
return self.message
class PluginBase(ABC):
plugins = {}
def __init__(self, chat_processes, event_queue, name, _children=None, **kwargs):
super().__init__(**kwargs)
self.chats = chat_processes
self._event_queue = event_queue
self._name = name
self.logger = logging.getLogger(f'plugin.{self._name}')
self.plugins[name] = self
if _children:
raise ValueError('Module does not accept children')
def __del__(self):
if self.plugins.get(self._name) == self:
del self.plugins[self._name]
# Base class helpers
def broadcast(self, event):
"""Send event to every active chat"""
for proc in self.chats.values():
if proc.readonly:
continue
proc.control_pipe.send(event)
@staticmethod
def _kdl_arg_formatter(text, fragment, args):
key = fragment.fragment[1:-1]
if '{' in key:
return key.format(**args).replace(r'\"', '"')
else:
try:
return reduce(getitem, key.split('.'), args)
except KeyError as e:
raise ValueError(f'{key} does not exist!') from e
def fill_context(self, actionnode, ctx):
config = asdict(kdl_parse_config)
config['valueConverters'] = {
**config['valueConverters'],
'arg': lambda text, fragment, args=ctx: self._kdl_arg_formatter(text, fragment, args),
}
config = kdl.ParseConfig(**config)
newnode = kdl.parse(str(actionnode), config).nodes[0]
return newnode
def call_plugin_from_kdl(self, node, *args, _ctx={}, **kwargs):
"""
Calls some other plugin as configured by the passed KDL node
If this was done in response to an event, pass it as event in _ctx!
"""
node = self.fill_context(node, _ctx)
target = self.plugins.get(node.name)
if target is None:
self.logger.warning(f'Could not find plugin or builtin with name {node.name}')
else:
return target._run(*node.args, *args, **node.props, _ctx=_ctx, **kwargs, _children=node.nodes)
def send_to_bus(self, event):
"""
Send an event to the event bus
WARNING: This will cause the event to be processed by other plugins - be careful not to cause an infinite loop!
"""
self._event_queue.put(event)
def _run(self, *args, **kwargs):
try:
return self.run(*args, **kwargs)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
raise e
raise PluginError(self._name, str(e)) from e
# User-defined
def tick(self, dt):
"""Called at least every half second - perform time-dependent updates here!"""
pass
def on_bus_event(self, event):
"""Called for every event from the chats"""
return event
def on_control_event(self, event):
"""
Called for events targeting this plugin name specifically.
This is normally used for other applications to communicate with this one over the websocket interface
"""
pass
@abstractmethod
def run(self, _children=None, _ctx={}, **kwargs):
"""
Run plugin action, either due to a definition in the config, or due to another plugin
"""
pass