From 17031500e95960273f2e6c005b00654b82d8c65b Mon Sep 17 00:00:00 2001 From: nikita Date: Sun, 18 Oct 2026 15:29:12 +0300 Subject: [PATCH] Added context variable builders system - Fixed subpackages missing __init__.py - Fixed mab/__init__.py containing __all__ - Filters no longer add variables to EventContext - Removed most context variables - Reorganized file tree a bit - Fixed echo_bot.py example Most examples are broken --- examples/echo_bot.py | 2 +- src/mab/__init__.py | 57 +-------- src/mab/bot/_callbacks.py | 18 ++- src/mab/context.py | 88 ------------- src/mab/context/__init__.py | 155 +++++++++++++++++++++++ src/mab/context/keys.py | 31 +++++ src/mab/context/vars/__init__.py | 0 src/mab/context/vars/message/__init__.py | 0 src/mab/context/vars/message/builders.py | 41 ++++++ src/mab/context/vars/message/types.py | 17 +++ src/mab/filters/__init__.py | 5 + src/mab/filters/base.py | 3 +- src/mab/filters/body.py | 10 -- src/mab/filters/message.py | 10 +- src/mab/filters/room.py | 3 +- src/mab/models/file.py | 50 ++++++++ src/mab/types.py | 17 --- 17 files changed, 319 insertions(+), 188 deletions(-) delete mode 100644 src/mab/context.py create mode 100644 src/mab/context/__init__.py create mode 100644 src/mab/context/keys.py create mode 100644 src/mab/context/vars/__init__.py create mode 100644 src/mab/context/vars/message/__init__.py create mode 100644 src/mab/context/vars/message/builders.py create mode 100644 src/mab/context/vars/message/types.py create mode 100644 src/mab/filters/__init__.py create mode 100644 src/mab/models/file.py diff --git a/examples/echo_bot.py b/examples/echo_bot.py index 4a71846..88cc8b5 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -15,7 +15,7 @@ from _environment import check_environment async def on_text_message(ctx: EventContext) -> None: """This callback is called when a text message arrives.""" - await ctx.bot.send.text(ctx.room, ctx[CTX_BODY]) + await ctx.bot.send.text(ctx.room, ctx[CTX_MESSAGE].body) async def main() -> None: """Application entry point""" diff --git a/src/mab/__init__.py b/src/mab/__init__.py index bda1ac2..31f7caf 100644 --- a/src/mab/__init__.py +++ b/src/mab/__init__.py @@ -1,57 +1,8 @@ -from . import bot -from . import types - -from .types import MatrixBotConfig, MessageType -from .context import * +from .types import MatrixBotConfig from .bot import MatrixBot -from .filters.base import * -from .filters.message import * -from .filters.body import * +from .context import EventContext +from .context.keys import * -__all__ = [ - # module names - "bot", - "types", - - # .types - "MatrixBotConfig", - "MessageType", - - # .context - "EventContext", - "CTX_BODY", - "CTX_MESSAGE_TYPE", - "CTX_SENDER", - "CTX_CMD_PREFIX", - "CTX_CMD_VERB", - "CTX_CMD_ARGS", - "CTX_FILE_SIZE", - "CTX_FILE_MIME", - "CTX_FILE_NAME", - - # .bot - "MatrixBot", - - # .filters.base - "BaseEventFilter", - "EventTypeFilter", - - # .filters.body - "BodyExistsFilter", - "BodyContainsFilter", - "BodyStartsWithFilter", - "BodyEndsWithFilter", - "BodyCommandFilter", - "BodyRegexFilter", - - # .filters.message - "MessageTypeFilter", - "NewMessageFilter", - "EditedMessageFilter", - "RedactedMessageFilter", - "SenderIsFilter", - "SenderIsBotFilter", - "MessageHasFile", -] \ No newline at end of file +from .filters import * \ No newline at end of file diff --git a/src/mab/bot/_callbacks.py b/src/mab/bot/_callbacks.py index 15ef831..215d5ad 100644 --- a/src/mab/bot/_callbacks.py +++ b/src/mab/bot/_callbacks.py @@ -11,7 +11,7 @@ from nio.events.room_events import Event as RoomEvent from ._storage import Storage from ..types import MatrixBotConfig -from ..context import EventContext +from ..context import EventContext, ContextVarsPopulator from ..filters.base import BaseEventFilter if TYPE_CHECKING: @@ -49,14 +49,19 @@ class Callbacks: """ if self._config is None or self._client is None: raise RuntimeError("Callbacks were not set up") + # build the event context + event_data = EventContext( + room=room, + event=event, + bot=self._matrix_bot + ) + self._context_vars_populator.sync_populate(event_data) + await self._context_vars_populator.async_populate(event_data) + + # check all filters for callback_info in self._filters: if not isinstance(callback_info, self._FilterBasedCallback): continue - event_data = EventContext( - room=room, - event=event, - bot=self._matrix_bot - ) try: if not await callback_info.filter(event_data): continue @@ -135,6 +140,7 @@ class Callbacks: self._logger = logging.getLogger("Callbacks") self._storage = storage self._matrix_bot = matrix_bot + self._context_vars_populator = ContextVarsPopulator() self._config: MatrixBotConfig | None = None self._client: AsyncClient | None = None diff --git a/src/mab/context.py b/src/mab/context.py deleted file mode 100644 index 06a6dce..0000000 --- a/src/mab/context.py +++ /dev/null @@ -1,88 +0,0 @@ -"""This module implements logic for event context""" - -from dataclasses import dataclass -from typing import Any, TYPE_CHECKING - -from .types import ContextDataKey, MessageType - -from nio import MatrixRoom, Event - -if TYPE_CHECKING: - from .bot import MatrixBot - -# -# Possible context variables -# -CTX_BODY = ContextDataKey[str]("CTX_BODY") -"""Value of `event.body`""" - -CTX_MESSAGE_TYPE = ContextDataKey[MessageType]("CTX_MESSAGE_TYPE") -"""Value of `msgtype` for the event""" - -CTX_SENDER = ContextDataKey[str]("CTX_SENDER") -"""Value of `event.sender`""" - -CTX_CMD_PREFIX = ContextDataKey[str]("CTX_CMD_PREFIX") -"""Command prefix that was used when matching""" - -CTX_CMD_VERB = ContextDataKey[str]("CTX_CMD_VERB") -"""The verb that was used to execute the command""" - -CTX_CMD_ARGS = ContextDataKey[list[str]]("CTX_CMD_ARGS") -"""Arguments that were passed with the command""" - -CTX_ROOM_ENCRYPTED = ContextDataKey[bool]("CTX_ROOM_ENCRYPTED") -"""True if the room is encrypted""" - -CTX_FILE_SIZE = ContextDataKey[int]("CTX_FILE_SIZE") -"""Size of the file attached to the message (bytes)""" - -CTX_FILE_MIME = ContextDataKey[str]("CTX_FILE_MIME") -"""Mime type of the file attached to the message""" - -CTX_FILE_NAME = ContextDataKey[str]("CTX_FILE_NAME") -"""Name of the file attached to the message""" - - -# -# EventContext implementation -# -@dataclass -class EventContext: - """The class holding information about an event that happened in the room""" - - room: MatrixRoom - """The room the event has happened in""" - - event: Event - """The event that has happened in the room""" - - bot: "MatrixBot" - """The bot that is the source of the event""" - - def __setitem__[T](self, key: ContextDataKey[T], value: T | None) -> None: - """Set a value inside the context data storage. `None` removes it""" - if not hasattr(self, "_datastore"): - self._datastore: dict[ContextDataKey, Any] = {} - if value is None: - del self._datastore[key] - else: - self._datastore[key] = value - - def __getitem__[T](self, key: ContextDataKey[T]) -> T: - """ - Get a value inside the context data storage. - - Raises RuntimeError if the value is not present. - """ - if not hasattr(self, "_datastore") or key not in self._datastore: - raise RuntimeError(f"Context does not contain {repr(key)}") - return self._datastore[key] - - def __contains__[T](self, key: ContextDataKey[T]) -> bool: - """Check if context data storage contains the value""" - if not hasattr(self, "_datastore"): - return False - if key not in self._datastore: - return False - return True \ No newline at end of file diff --git a/src/mab/context/__init__.py b/src/mab/context/__init__.py new file mode 100644 index 0000000..31a95c9 --- /dev/null +++ b/src/mab/context/__init__.py @@ -0,0 +1,155 @@ +from dataclasses import dataclass +from nio import MatrixRoom, Event +from types import ModuleType +from typing import TYPE_CHECKING, Any, Callable, Coroutine +import inspect +import importlib +import pkgutil +import traceback +import mab.context.vars +if TYPE_CHECKING: + from ..bot import MatrixBot + from .keys import _ContextDataKey + +@dataclass +class EventContext: + """The class holding information about an event that happened in the room""" + + room: MatrixRoom + """The room the event has happened in""" + + event: Event + """The event that has happened in the room""" + + bot: "MatrixBot" + """The bot that is the source of the event""" + + def __setitem__[T](self, key: _ContextDataKey[T], value: T | None) -> None: + """Set a value inside the context data storage. `None` removes it""" + if not hasattr(self, "_datastore"): + self._datastore: dict[_ContextDataKey, Any] = {} + if value is None: + del self._datastore[key] + else: + self._datastore[key] = value + + def __getitem__[T](self, key: _ContextDataKey[T]) -> T: + """ + Get a value inside the context data storage. + + Raises RuntimeError if the value is not present. + """ + if not hasattr(self, "_datastore") or key not in self._datastore: + raise RuntimeError(f"Context does not contain {repr(key)}") + return self._datastore[key] + + def __contains__[T](self, key: _ContextDataKey[T]) -> bool: + """Check if context data storage contains the value""" + if not hasattr(self, "_datastore"): + return False + if key not in self._datastore: + return False + return True + +class ContextVarsPopulator: + """This class populates context variables using dynamically detected + builders. + + What is a builder? + 1. Synchronous or asynchronous function + 2. Takes exactly one positional argument of type `EventContext` + 3. A member of module `mab.context.vars..builders` + 4. `mab.context.vars..__init__` exists + 4. Function name starts with `build_` + 5. Returns `None` + + Builders are looked for dynamically because it drastically decreases amount + of boilerplate code and makes builder definition a kind of single source of + truth. + """ + + @staticmethod + def _is_builder_signature_valid(builder) -> bool: + """Check if builder signature is valid. + + Args: + - builder - function to check + + Returns: + - True if the signature is valid + """ + params = inspect.signature(builder).parameters + if len(params) != 1: + return False + p = tuple(params.values())[0] + return p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) + + @staticmethod + def _get_builder_modules() -> list[ModuleType]: + """Get all known modules for glob `mab.context.vars.*.builders`. + Imports modules during the search.""" + walk_result = pkgutil.walk_packages( + mab.context.vars.__path__, + f"{mab.context.vars.__name__}." + ) + walk_result = [i for i in walk_result if i.name.endswith(".builders") and not i.ispkg] + builder_modules = [] + for module_info in walk_result: + builder_modules.append( + importlib.import_module(module_info.name) + ) + return builder_modules + + @staticmethod + def _get_builders_of_module(module: ModuleType) -> tuple[list, list]: + """Get all builders of the module. + + Returns: + - a tuple of: + 0. list of sync builders + 1. list of async builders + """ + predicates = [ + lambda x: inspect.isfunction(x) and not inspect.iscoroutinefunction(x), + lambda x: inspect.iscoroutinefunction(x) + ] + result = [[], []] + for i, predicate in enumerate(predicates): + members = inspect.getmembers(module, predicate) + result[i] = [m[1] for m in members if m[0].startswith("build_")] + return (result[0], result[1]) + + def __init__(self) -> None: + """Initialize the populator. Builders are looked up during this + function call.""" + self._modules = self._get_builder_modules() + self._sync_builders: list[Callable[[EventContext], None]] = [] + self._async_builders: list[Callable[[EventContext], Coroutine[None, None, None]]] = [] + for m in self._modules: + sync_builders, async_builders = self._get_builders_of_module(m) + self._sync_builders += sync_builders + self._async_builders += async_builders + + def sync_populate(self, context: EventContext) -> None: + """Populate context variables using sync builders. + + Args: + - context - context to set variables in + """ + for builder in self._sync_builders: + try: + builder(context) + except: + traceback.print_exc() + + async def async_populate(self, context: EventContext) -> None: + """Populate context variables using async builders. + + Args: + - context - context to set variables in + """ + for builder in self._async_builders: + try: + await builder(context) + except: + traceback.print_exc() \ No newline at end of file diff --git a/src/mab/context/keys.py b/src/mab/context/keys.py new file mode 100644 index 0000000..1f28bd1 --- /dev/null +++ b/src/mab/context/keys.py @@ -0,0 +1,31 @@ +# +# IMPORTS FOR VARIABLE VALUE TYPES +# +from .vars.message.types import Message + +# +# VARIABLE KEY TYPE +# +class _ContextDataKey[T]: + """ + Instances of this class represent a single possible data key that can be + stored inside EventContext. + """ + def __init__(self, name: str) -> None: + """ + Initialize a ContextDataKey + + Args: + - name - name that will be used internally + """ + self._name = name + + def __repr__(self) -> str: + return f"ContextDataKey[{type(T)}]({repr(self._name)})" + +# +# VARIABLE KEYS +# + +CTX_MESSAGE = _ContextDataKey[Message]("CTX_MESSAGE") +"""Minimum set of fields required to create a message""" \ No newline at end of file diff --git a/src/mab/context/vars/__init__.py b/src/mab/context/vars/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mab/context/vars/message/__init__.py b/src/mab/context/vars/message/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mab/context/vars/message/builders.py b/src/mab/context/vars/message/builders.py new file mode 100644 index 0000000..164bfe5 --- /dev/null +++ b/src/mab/context/vars/message/builders.py @@ -0,0 +1,41 @@ +""" +This file is dynamically analyzed when `mab` is imported. All functions with +names starting with `build_` are added to the list of so called "builders". + +Builder is a function that tries to add new context variable to the +`EventContext`. One builder can add only one context variable. + +When a matrix event arrives and it is being prepared for routing through the +filters system, it is being passed to all existing builders as their one and +only argument - `context`. + +The builder may return: +1. `None`. In this case nothing happens. The builder should return `None` if it + is unable to create new context variable. +2. `tuple[ContextDataKey[T], T]`. In this case the returned values will be used + by routing system to add a new variable to the context. The first element is + used as a key, the second element is used as a value. + +IMPORTANT: You should not modify the `context`! You should return the tuple +described above if you want to add a variable! +""" + +from ... import EventContext +from ...keys import * + +from .types import Message + +async def build_message(context: EventContext) -> None: + source = context.event.source + if "content" not in source: + return None + content: dict = source["content"] + if "body" not in content or "msgtype" not in content: + return None + res = Message( + body=content.get("body", "Missing `body`"), + format=content.get("format"), + formatted_body=content.get("formatted_body"), + msgtype=content.get("msgtype", "Missing `msgtype`") + ) + context[CTX_MESSAGE] = res \ No newline at end of file diff --git a/src/mab/context/vars/message/types.py b/src/mab/context/vars/message/types.py new file mode 100644 index 0000000..01e1103 --- /dev/null +++ b/src/mab/context/vars/message/types.py @@ -0,0 +1,17 @@ +from pydantic import BaseModel + +class Message(BaseModel): + """This model defines the most important fields of the message. Custom + fields must be accessed using raw matrix-nio event.""" + + msgtype: str + """It identifies the type of message being sent""" + + body: str + """Unformatted (or fallback) body of the message""" + + format: str | None + """Format of the formatted_body content""" + + formatted_body: str | None + """Formatted body of the message, present if `format` is not None""" \ No newline at end of file diff --git a/src/mab/filters/__init__.py b/src/mab/filters/__init__.py new file mode 100644 index 0000000..3b78b52 --- /dev/null +++ b/src/mab/filters/__init__.py @@ -0,0 +1,5 @@ +from .base import EventTypeFilter + +from .body import * +from .message import * +from .room import * \ No newline at end of file diff --git a/src/mab/filters/base.py b/src/mab/filters/base.py index b092377..64146f5 100644 --- a/src/mab/filters/base.py +++ b/src/mab/filters/base.py @@ -2,7 +2,7 @@ from abc import ABC import logging from typing import Type -from ..context import EventContext, CTX_SENDER +from ..context import EventContext class BaseEventFilter(ABC): """Base class for all message filters""" @@ -79,7 +79,6 @@ class BaseEventFilter(ABC): - True if the event satisfies this filter - False if the event does not satisfy this filter """ - context[CTX_SENDER] = context.event.sender return True class EventTypeFilter(BaseEventFilter): diff --git a/src/mab/filters/body.py b/src/mab/filters/body.py index c65b54f..1108321 100644 --- a/src/mab/filters/body.py +++ b/src/mab/filters/body.py @@ -2,12 +2,6 @@ import re import traceback from .message import NewMessageFilter from ..context import EventContext -from ..context import ( - CTX_BODY, - CTX_CMD_PREFIX, - CTX_CMD_VERB, - CTX_CMD_ARGS -) class BodyExistsFilter(NewMessageFilter): """ @@ -45,7 +39,6 @@ class BodyExistsFilter(NewMessageFilter): content = context.event.source["content"] if "filename" in content and content["filename"] == context.event.body: # type: ignore return False - context[CTX_BODY] = context.event.body # type: ignore return True class BodyContainsFilter(BodyExistsFilter): @@ -180,9 +173,6 @@ class BodyCommandFilter(BodyExistsFilter): cmd = parts[0][len(self._prefix):].lower() for verb in self._verbs: if cmd == verb: - context[CTX_CMD_PREFIX] = self._prefix - context[CTX_CMD_VERB] = verb - context[CTX_CMD_ARGS] = parts[1:] return True return False diff --git a/src/mab/filters/message.py b/src/mab/filters/message.py index 8523cae..ef46c83 100644 --- a/src/mab/filters/message.py +++ b/src/mab/filters/message.py @@ -1,11 +1,7 @@ import traceback from .base import BaseEventFilter, EventTypeFilter from ..types import MessageType -from ..context import (EventContext, - CTX_MESSAGE_TYPE, - CTX_FILE_SIZE, - CTX_FILE_MIME, - CTX_FILE_NAME) +from ..context import EventContext from nio import RedactionEvent @@ -34,7 +30,6 @@ class MessageTypeFilter(BaseEventFilter): msgtype = context.event.source["content"]["msgtype"] if not msgtype in [t.value for t in self._types]: return False - context[CTX_MESSAGE_TYPE] = MessageType(msgtype) return True class NewMessageFilter(BaseEventFilter): @@ -140,7 +135,4 @@ class MessageHasFile(BaseEventFilter): # `file` if encrypted, `url` if not encrypted if "file" not in content and "url" not in content: return False - context[CTX_FILE_NAME] = content.get("filename") or content.get("body") - context[CTX_FILE_SIZE] = content["info"].get("size") - context[CTX_FILE_MIME] = content["info"].get("mimetype") return True \ No newline at end of file diff --git a/src/mab/filters/room.py b/src/mab/filters/room.py index 12e87f0..3ffe955 100644 --- a/src/mab/filters/room.py +++ b/src/mab/filters/room.py @@ -1,6 +1,6 @@ from .base import BaseEventFilter -from ..context import EventContext, CTX_ROOM_ENCRYPTED +from ..context import EventContext class RoomEncryptedFilter(BaseEventFilter): """ @@ -13,7 +13,6 @@ class RoomEncryptedFilter(BaseEventFilter): if not await super().__call__(context): return False try: - context[CTX_ROOM_ENCRYPTED] = context.room.encrypted return context.room.encrypted except: return False \ No newline at end of file diff --git a/src/mab/models/file.py b/src/mab/models/file.py new file mode 100644 index 0000000..a3cb841 --- /dev/null +++ b/src/mab/models/file.py @@ -0,0 +1,50 @@ +from pydantic import BaseModel + + +class JwkKey(BaseModel): + """Encryption key data.""" + + alg: str + """Algorithm. Must be A256CTR.""" + + ext: bool + """Extractable. Must be true.""" + + k: str + """The key, encoded as URL-safe unpadded Base64.""" + + key_ops: list[str] + """Key operations. Must at least contain encrypt and decrypt.""" + + kty: str + """Key type. Must be oct.""" + + +class Encryption(BaseModel): + """Encryption information for files. `url` is stored in `File` model!""" + + hashes: list[str] + """A map from an algorithm name to a hash of the ciphertext.""" + + iv: list[str] + """The 128-bit unique counter block used by AES-CTR, encoded as unpadded + Base64.""" + + key: JwkKey + """A JSON Web Key object.""" + + v: str + """Version of encrypted attachments's protocol. Must be v2.""" + + +class File(BaseModel): + """This model defines both encrypted and non-encrypted file.""" + + encryption: Encryption | None + """Encryption data if encryption is used.""" + + url: str + """URL of the file. Must start with `mxc://` if encrypted.""" + + filename: str | None + """The name of the file. May be absent.""" \ No newline at end of file diff --git a/src/mab/types.py b/src/mab/types.py index d3751dd..a5d0adb 100644 --- a/src/mab/types.py +++ b/src/mab/types.py @@ -86,20 +86,3 @@ class MessageType(Enum): AUDIO = "m.audio" LOCATION = "m.location" VIDEO = "m.video" - -class ContextDataKey[T]: - """ - Instances of this class represent a single possible data key that can be - stored inside EventContext. - """ - def __init__(self, name: str) -> None: - """ - Initialize a ContextDataKey - - Args: - - name - name that will be used internally - """ - self._name = name - - def __repr__(self) -> str: - return f"ContextDataKey[{type(T)}]({repr(self._name)})" \ No newline at end of file