From 33efd5e1045fcabf2dbf41ef7a5548122f9342b3 Mon Sep 17 00:00:00 2001 From: nikita Date: Sun, 18 Oct 2026 16:22:35 +0300 Subject: [PATCH] Added CTX_FILE variable - Modified file_bot.py example to utilize CTX_FILE - Removed docstring for message builders.py - Removed mab.models namespace package --- examples/file_bot.py | 8 ++-- src/mab/context/keys.py | 8 +++- src/mab/context/vars/file/__init__.py | 0 src/mab/context/vars/file/builders.py | 24 ++++++++++++ src/mab/context/vars/file/types.py | 19 +++++++++ src/mab/context/vars/message/builders.py | 28 ++----------- src/mab/models/file.py | 50 ------------------------ 7 files changed, 57 insertions(+), 80 deletions(-) create mode 100644 src/mab/context/vars/file/__init__.py create mode 100644 src/mab/context/vars/file/builders.py create mode 100644 src/mab/context/vars/file/types.py delete mode 100644 src/mab/models/file.py diff --git a/examples/file_bot.py b/examples/file_bot.py index ce140f3..a9870e0 100644 --- a/examples/file_bot.py +++ b/examples/file_bot.py @@ -24,7 +24,7 @@ async def on_file_message(ctx: EventContext) -> None: """This callback is called when a file arrives.""" sha = hashlib.sha256() does_temp_exist = False - if ctx[CTX_FILE_SIZE] > 1_000_000: + if ctx[CTX_FILE].size > 1_000_000: await ctx.bot.send.text( ctx.room, "The file is larger than 1 MB, downloading to filesystem" @@ -45,8 +45,8 @@ async def on_file_message(ctx: EventContext) -> None: content = await ctx.bot.download.file(ctx, path=None) sha.update(content) # result - response = f"SHA256 for file `{ctx[CTX_FILE_NAME]}`" - response += f" ({ctx[CTX_FILE_SIZE]} bytes, {ctx[CTX_FILE_MIME]})" + response = f"SHA256 for file `{ctx[CTX_FILE].filename}`" + response += f" ({ctx[CTX_FILE].size} bytes, {ctx[CTX_FILE].filename})" await ctx.bot.send.file_bytes( room=ctx.room, data=sha.hexdigest().encode("utf-8"), @@ -59,7 +59,7 @@ async def on_file_message(ctx: EventContext) -> None: await ctx.bot.send.file( room=ctx.room, path="temp.tmp", - filename=ctx[CTX_FILE_NAME], + filename=ctx[CTX_FILE].filename, text="This is the file you have sent, but it was reuploaded" ) try: diff --git a/src/mab/context/keys.py b/src/mab/context/keys.py index 1f28bd1..0f396eb 100644 --- a/src/mab/context/keys.py +++ b/src/mab/context/keys.py @@ -2,6 +2,7 @@ # IMPORTS FOR VARIABLE VALUE TYPES # from .vars.message.types import Message +from .vars.file.types import File # # VARIABLE KEY TYPE @@ -28,4 +29,9 @@ class _ContextDataKey[T]: # CTX_MESSAGE = _ContextDataKey[Message]("CTX_MESSAGE") -"""Minimum set of fields required to create a message""" \ No newline at end of file +"""Minimum set of fields required to describe a message. The variable is set +when the event is a message.""" + +CTX_FILE = _ContextDataKey[File]("CTX_FILE") +"""Minimum set of fields required to describe a file. The variable is set when +you can download a file attached to the message.""" \ No newline at end of file diff --git a/src/mab/context/vars/file/__init__.py b/src/mab/context/vars/file/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mab/context/vars/file/builders.py b/src/mab/context/vars/file/builders.py new file mode 100644 index 0000000..6f69891 --- /dev/null +++ b/src/mab/context/vars/file/builders.py @@ -0,0 +1,24 @@ +from ... import EventContext +from ...keys import * + +from .types import File + +def build_file_info(context: EventContext) -> None: + # check if basic fields are missing + source = context.event.source + if "content" not in source: + return + content: dict = source["content"] + if "body" not in content or "msgtype" not in content: + return + # no file + if "url" not in content and "file" not in content: + return + # create the variable + context[CTX_FILE] = File( + is_encrypted="file" in content, + url=content.get("url") or content["file"]["url"], + filename=content.get("filename", content["body"]), + mimetype=content["info"]["mimetype"], + size=content["info"]["size"] + ) \ No newline at end of file diff --git a/src/mab/context/vars/file/types.py b/src/mab/context/vars/file/types.py new file mode 100644 index 0000000..e54bea9 --- /dev/null +++ b/src/mab/context/vars/file/types.py @@ -0,0 +1,19 @@ +from pydantic import BaseModel + +class File(BaseModel): + """This model defines both encrypted and non-encrypted file.""" + + is_encrypted: bool + """Whether the file is encrypted.""" + + url: str + """URL of the file. Must start with `mxc://` if encrypted.""" + + filename: str + """The name of the file.""" + + mimetype: str + """Mimetype of the file.""" + + size: int + """File size in bytes.""" \ No newline at end of file diff --git a/src/mab/context/vars/message/builders.py b/src/mab/context/vars/message/builders.py index 164bfe5..0bfbf99 100644 --- a/src/mab/context/vars/message/builders.py +++ b/src/mab/context/vars/message/builders.py @@ -1,37 +1,15 @@ -""" -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: +def build_message(context: EventContext) -> None: source = context.event.source if "content" not in source: - return None + return content: dict = source["content"] if "body" not in content or "msgtype" not in content: - return None + return res = Message( body=content.get("body", "Missing `body`"), format=content.get("format"), diff --git a/src/mab/models/file.py b/src/mab/models/file.py deleted file mode 100644 index a3cb841..0000000 --- a/src/mab/models/file.py +++ /dev/null @@ -1,50 +0,0 @@ -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