From 2e91b88faef118fb6829ab2cdb5dd02e9cef4e9c Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Mon, 3 Aug 2026 16:32:48 +0800 Subject: [PATCH] Initial source archive --- __init__.py | 0 _conf_schema.json | 18 +++ keyboards.py | 96 +++++++++++ main.py | 398 ++++++++++++++++++++++++++++++++++++++++++++++ metadata.yaml | 5 + qq_bridge.py | 110 +++++++++++++ registry.py | 130 +++++++++++++++ 7 files changed, 757 insertions(+) create mode 100644 __init__.py create mode 100644 _conf_schema.json create mode 100644 keyboards.py create mode 100644 main.py create mode 100644 metadata.yaml create mode 100644 qq_bridge.py create mode 100644 registry.py diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/_conf_schema.json b/_conf_schema.json new file mode 100644 index 0000000..a4f3dc1 --- /dev/null +++ b/_conf_schema.json @@ -0,0 +1,18 @@ +{ + "enable": { + "description": "启用按钮网关", + "type": "bool", + "default": true, + "hint": "关闭后 send_buttons 一律返回 False,调用方自行回退文本流程" + }, + "qq_platform_id": { + "description": "QQ 官方机器人平台 ID", + "type": "string", + "default": "default_1905122299" + }, + "telegram_platform_id": { + "description": "Telegram 平台 ID", + "type": "string", + "default": "telegram" + } +} diff --git a/keyboards.py b/keyboards.py new file mode 100644 index 0000000..eb36261 --- /dev/null +++ b/keyboards.py @@ -0,0 +1,96 @@ +"""Platform-specific keyboard payloads built from one platform-neutral button spec. + +Callers describe buttons once; this module renders them for whichever platform the window +belongs to. The wire format for a click is always `bg::` — at most 59 bytes, which +clears Telegram's 64-byte callback_data limit (the tighter of the two) and QQ's 100. +""" +from __future__ import annotations + +import re +from typing import Any + +BUTTON_DATA_RE = re.compile(r"^bg:(?P[a-z][a-z0-9_-]{0,15}):(?Pg1\.[A-Za-z0-9_-]{12}\.[0-9a-f]{24})$") + +# Telegram is the tighter limit; enforce it everywhere so a spec that works on one platform +# works on both. +MAX_DATA_BYTES = 64 + + +def encode(action: str, ref: str) -> str: + data = f"bg:{action}:{ref}" + if len(data.encode("utf-8")) > MAX_DATA_BYTES: + raise ValueError(f"按钮数据超长({len(data.encode('utf-8'))} > {MAX_DATA_BYTES})") + return data + + +def decode(value: Any) -> tuple[str, str]: + match = BUTTON_DATA_RE.fullmatch(str(value or "")) + if not match: + raise ValueError("无法识别的按钮数据") + return match.group("action"), match.group("ref") + + +def build_qq_keyboard( + buttons: list[dict[str, Any]], + ref: str, + *, + allowed_user_id: str | None, + per_row: int = 2, +) -> dict[str, Any]: + """action.type=1 keyboard (native Interaction callbacks). + + permission.type=2 with specify_user_ids makes QQ itself reject clicks from anyone else, so + a forged click never reaches us. click_limit=1 matches the registry's single-use default. + """ + if not buttons: + raise ValueError("按钮列表不能为空") + permission: dict[str, Any] = {"type": 2, "specify_role_ids": [], "specify_user_ids": []} + if allowed_user_id: + permission["specify_user_ids"] = [str(allowed_user_id)] + else: + permission = {"type": 0} # anyone in the conversation + + rows: list[dict[str, Any]] = [] + for start in range(0, len(buttons), per_row): + row_buttons = [] + for index, spec in enumerate(buttons[start:start + per_row], start=start): + action = str(spec["action"]) + row_buttons.append({ + "id": f"bg_{index}_{action}", + "render_data": { + "label": str(spec["label"])[:20], + "visited_label": str(spec.get("visited_label") or spec["label"])[:20], + "style": int(spec.get("style", 1)), + }, + "action": { + "type": 1, + "permission": permission, + "click_limit": 1, + "data": encode(action, ref), + }, + }) + rows.append({"buttons": row_buttons}) + return {"content": {"rows": rows}} + + +def build_qq_c2c_payload(text: str, keyboard: dict[str, Any]) -> dict[str, Any]: + """QQ only renders a keyboard alongside markdown; msg_type=0 drops it *silently*.""" + text = str(text or "").strip() + if not text or len(text) > 4000: + raise ValueError("markdown 文本无效") + if not keyboard.get("content", {}).get("rows"): + raise ValueError("keyboard 内容无效") + return {"msg_type": 2, "markdown": {"content": text}, "keyboard": keyboard} + + +def build_telegram_markup(buttons: list[dict[str, Any]], ref: str, *, per_row: int = 2): + """Lazily imported so the gateway still loads when python-telegram-bot is absent.""" + from telegram import InlineKeyboardButton, InlineKeyboardMarkup # noqa: PLC0415 + + rows = [] + for start in range(0, len(buttons), per_row): + rows.append([ + InlineKeyboardButton(str(spec["label"])[:30], callback_data=encode(str(spec["action"]), ref)) + for spec in buttons[start:start + per_row] + ]) + return InlineKeyboardMarkup(rows) diff --git a/main.py b/main.py new file mode 100644 index 0000000..473d962 --- /dev/null +++ b/main.py @@ -0,0 +1,398 @@ +"""Shared interactive-button gateway. + +Any plugin that wants buttons calls this one instead of patching botpy itself: + + gw = context.get_registered_star("astrbot_plugin_button_gateway").star_cls + await gw.send_buttons( + event, + "确认重启照片服务?", + [{"label": "批准", "action": "approve", "style": 1}, + {"label": "取消", "action": "cancel", "style": 0}], + owner="astrbot_plugin_nas_ops", + handler="on_button", + payload={"plan_id": "..."}, + allowed_user_id=event.get_sender_id(), + ) + +and exposes: + + async def on_button(action: str, payload: dict, identity: dict) -> tuple[bool, str] + +returning (ok, 回复文案). The gateway maps that onto the platform's ACK semantics and sends the +reply, so callers never touch QQ interaction codes. + +Why a gateway at all: the QQ INTERACTION intent and `on_interaction_create` are process-wide +class attributes, so only one component can own them. Two plugins patching independently +silently clobber each other. +""" +from __future__ import annotations + +import asyncio +import contextlib +import contextvars +import random +from typing import Any + +from astrbot.api import AstrBotConfig, logger +from astrbot.api.event import AstrMessageEvent, filter +from astrbot.api.star import Context, Star, register + +from . import keyboards, qq_bridge +from .registry import ButtonRegistry + +# QQ interaction result codes. +ACK_OK = 0 +ACK_FAILED = 1 +ACK_REPEATED = 3 +ACK_FORBIDDEN = 4 + +_REASON_ACK = { + "expired": ACK_FAILED, + "invalid_ref": ACK_FAILED, + "unknown_action": ACK_FAILED, + "forbidden": ACK_FORBIDDEN, + "already_consumed": ACK_REPEATED, +} +_REASON_TEXT = { + "expired": "这个按钮已经失效了,请重新发起。", + "invalid_ref": "按钮数据无法识别。", + "unknown_action": "按钮数据无法识别。", + "forbidden": "这个按钮不是给你的。", + "already_consumed": "这一项刚才已经处理过了。", +} + +# Set for the duration of a click so a handler can answer with a *new* card without holding an +# AstrMessageEvent. QQ rejects unsolicited pushes, so the interaction's event_id has to ride +# along — that is why this is context rather than something the handler could reconstruct. +_ACTIVE_CALLBACK: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar( + "button_gateway_active_callback", default=None +) + + +@register( + "astrbot_plugin_button_gateway", + "local", + "跨插件共享的交互按钮网关:独占 QQ Interaction 入口,按短引用路由回调", + "0.1.0", +) +class ButtonGatewayPlugin(Star): + def __init__(self, context: Context, config: AstrBotConfig): + super().__init__(context) + self.context = context + self.registry = ButtonRegistry() + self.qq_platform_id = str(config.get("qq_platform_id") or "default_1905122299") + self.telegram_platform_id = str(config.get("telegram_platform_id") or "telegram") + self.enabled = bool(config.get("enable", True)) + self._bridge_installed = False + self._telegram_application: Any = None + self._watch_task: asyncio.Task | None = None + + # ──── lifecycle ──── + + async def initialize(self): + if not self.enabled: + logger.info("按钮网关已禁用") + return + self._bridge_installed = qq_bridge.install(self._dispatch_qq) + if self._bridge_installed: + logger.info("按钮网关:QQ Interaction 入口已接管") + else: + logger.warning("按钮网关:QQ Interaction 入口接管失败,将只能发命令型按钮") + self._watch_task = asyncio.create_task(self._watch_platforms()) + + async def terminate(self): + if self._watch_task: + self._watch_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await self._watch_task + qq_bridge.uninstall() + self._bridge_installed = False + + async def _watch_platforms(self) -> None: + """Attach the Telegram callback handler once its Application exists, and report intent.""" + while True: + try: + platform = self.context.get_platform_inst(self.telegram_platform_id) + application = getattr(platform, "application", None) if platform else None + if application is not None and application is not self._telegram_application: + from telegram.ext import CallbackQueryHandler # noqa: PLC0415 + + application.add_handler( + CallbackQueryHandler(self._dispatch_telegram, pattern=r"^bg:"), + group=-25, + ) + self._telegram_application = application + logger.info("按钮网关:Telegram 回调处理器已注册") + except Exception as exc: + logger.warning("按钮网关:Telegram 处理器注册失败 %s", type(exc).__name__) + + try: + platform = self.context.get_platform_inst(self.qq_platform_id) + client = getattr(platform, "client", None) if platform else None + if client is not None and not qq_bridge.intent_enabled(client): + logger.warning("按钮网关:QQ INTERACTION intent 未启用,需重启 AstrBot 后生效") + except Exception as exc: + logger.warning("按钮网关:QQ intent 检查失败 %s", type(exc).__name__) + + await asyncio.sleep(5) + + # ──── public API ──── + + async def send_buttons( + self, + event: AstrMessageEvent, + text: str, + buttons: list[dict[str, Any]], + *, + owner: str, + handler: str, + payload: dict[str, Any] | None = None, + allowed_user_id: str | None = None, + ttl_seconds: int = 600, + single_use: bool = True, + ) -> bool: + """Send a button card. Returns False when the window cannot render buttons. + + A False return is not an error — callers should fall back to their text flow. + """ + if not self.enabled: + return False + actions = tuple(str(b["action"]) for b in buttons) + ref = self.registry.issue( + owner=owner, + handler=handler, + payload=payload or {}, + actions=actions, + allowed_user_id=allowed_user_id, + ttl_seconds=ttl_seconds, + single_use=single_use, + ) + try: + platform = str(getattr(getattr(event, "platform_meta", None), "name", "") or "").lower() + if platform == "qq_official": + ok = await self._send_qq(event, text, buttons, ref, allowed_user_id) + elif platform == "telegram": + ok = await self._send_telegram(event, text, buttons, ref) + else: + ok = False + except Exception as exc: + logger.warning("按钮网关:发送失败 %s: %s", type(exc).__name__, exc) + ok = False + if not ok: + self.registry.revoke(ref) + return ok + + async def send_buttons_to( + self, + identity: dict[str, str], + text: str, + buttons: list[dict[str, Any]], + *, + owner: str, + handler: str, + payload: dict[str, Any] | None = None, + ttl_seconds: int = 600, + single_use: bool = True, + ) -> bool: + """Send a card from inside a button callback, where there is no AstrMessageEvent. + + Enables multi-step flows — check, then offer what passed; pick a target, then confirm. + Only valid while handling a click: QQ refuses unsolicited pushes, so this reuses the + interaction's event_id, which exists only for that window. + """ + if not self.enabled: + return False + ctx = _ACTIVE_CALLBACK.get() + if ctx is None: + logger.warning("按钮网关:send_buttons_to 只能在按钮回调期间调用") + return False + + user_id = str(identity.get("user_id") or ctx.get("user_id") or "") + actions = tuple(str(b["action"]) for b in buttons) + ref = self.registry.issue( + owner=owner, handler=handler, payload=payload or {}, actions=actions, + allowed_user_id=user_id or None, ttl_seconds=ttl_seconds, single_use=single_use, + ) + try: + if ctx["platform"] == "qq_official": + keyboard = keyboards.build_qq_keyboard(buttons, ref, allowed_user_id=user_id or None) + message = keyboards.build_qq_c2c_payload(text, keyboard) + kwargs: dict[str, Any] = {"openid": user_id, "msg_seq": random.randint(1, 10000), **message} + if ctx.get("event_id"): + kwargs["event_id"] = ctx["event_id"] + await ctx["client"].api.post_c2c_message(**kwargs) + return True + if ctx["platform"] == "telegram": + markup = keyboards.build_telegram_markup(buttons, ref) + await ctx["query"].message.reply_text(text, reply_markup=markup) + return True + except Exception as exc: + logger.warning("按钮网关:回调内发送卡片失败 %s: %s", type(exc).__name__, exc) + self.registry.revoke(ref) + return False + + def revoke(self, ref: str) -> bool: + return self.registry.revoke(ref) + + # ──── senders ──── + + async def _send_qq(self, event, text, buttons, ref, allowed_user_id) -> bool: + if not hasattr(event, "post_c2c_message"): + return False + if str(getattr(getattr(event, "message_obj", None), "group_id", "") or "").strip(): + return False # group buttons need a different API surface; not supported yet + keyboard = keyboards.build_qq_keyboard(buttons, ref, allowed_user_id=allowed_user_id) + message = keyboards.build_qq_c2c_payload(text, keyboard) + source = getattr(getattr(event, "message_obj", None), "raw_message", None) + msg_id = str(getattr(source, "id", "") or getattr(getattr(event, "message_obj", None), "message_id", "") or "") + result = await event.post_c2c_message( + openid=str(event.get_sender_id()), + msg_id=msg_id or None, + msg_seq=random.randint(1, 10000), + **message, + ) + return result is not None + + async def _send_telegram(self, event, text, buttons, ref) -> bool: + client = getattr(event, "client", None) + if client is None: + return False + markup = keyboards.build_telegram_markup(buttons, ref) + await client.send_message(chat_id=str(event.get_sender_id()), text=text, reply_markup=markup) + return True + + # ──── dispatch ──── + + async def _invoke_owner(self, entry, action: str, identity: dict[str, str]) -> tuple[bool, str]: + meta = self.context.get_registered_star(entry.owner) + target = getattr(meta, "star_cls", None) if meta else None + if target is None: + logger.warning("按钮网关:找不到注册插件 %s", entry.owner) + return False, "处理该按钮的插件当前不可用。" + func = getattr(target, entry.handler, None) + if func is None: + logger.warning("按钮网关:%s 缺少 handler %s", entry.owner, entry.handler) + return False, "处理该按钮的插件当前不可用。" + result = await func(action, dict(entry.payload), dict(identity)) + if isinstance(result, tuple) and len(result) == 2: + return bool(result[0]), str(result[1]) + return True, str(result or "处理完成") + + async def _dispatch_qq(self, client: Any, interaction: Any) -> bool: + resolved = getattr(getattr(interaction, "data", None), "resolved", None) + raw = getattr(resolved, "button_data", "") + try: + action, ref = keyboards.decode(raw) + except ValueError: + return False # not ours — let the previous handler try + + interaction_id = str(getattr(interaction, "id", "") or "") + user_id = str(getattr(interaction, "user_openid", "") or "") + # bot_instance is part of the identity tuple downstream controllers key on, so it must + # travel with the callback rather than be re-derived by each caller. + identity = { + "platform": "qq_official", + "bot_instance": self.qq_platform_id, + "user_id": user_id, + "chat_id": str(getattr(interaction, "group_openid", "") or "") or user_id, + } + + entry, reason = self.registry.claim(ref, action, user_id) + if reason != "ok": + await self._qq_ack(client, interaction_id, _REASON_ACK.get(reason, ACK_FAILED)) + await self._qq_reply(client, interaction, user_id, _REASON_TEXT.get(reason, "处理失败。")) + return True + + token = _ACTIVE_CALLBACK.set({ + "platform": "qq_official", + "client": client, + "user_id": user_id, + "event_id": str(getattr(interaction, "event_id", "") or ""), + }) + try: + ok, reply = await self._invoke_owner(entry, action, identity) + except Exception: + logger.exception("按钮网关:插件 %s 处理按钮失败", entry.owner) + ok, reply = False, "处理时出错,请查看日志。" + finally: + _ACTIVE_CALLBACK.reset(token) + + await self._qq_ack(client, interaction_id, ACK_OK if ok else ACK_FAILED) + if reply: + await self._qq_reply(client, interaction, user_id, reply) + return True + + async def _dispatch_telegram(self, update, _context) -> None: + query = getattr(update, "callback_query", None) + if query is None: + return + try: + action, ref = keyboards.decode(query.data) + except ValueError: + return + user_id = str(getattr(getattr(query, "from_user", None), "id", "") or "") + identity = { + "platform": "telegram", + "bot_instance": self.telegram_platform_id, + "user_id": user_id, + "chat_id": user_id, + } + + entry, reason = self.registry.claim(ref, action, user_id) + if reason != "ok": + await query.answer(_REASON_TEXT.get(reason, "处理失败。"), show_alert=True) + return + token = _ACTIVE_CALLBACK.set({"platform": "telegram", "query": query, "user_id": user_id}) + try: + ok, reply = await self._invoke_owner(entry, action, identity) + except Exception: + logger.exception("按钮网关:插件 %s 处理按钮失败", entry.owner) + ok, reply = False, "处理时出错,请查看日志。" + finally: + _ACTIVE_CALLBACK.reset(token) + await query.answer("已处理" if ok else "处理失败") + if reply: + with contextlib.suppress(Exception): + await query.edit_message_text(reply[:3800]) + + @staticmethod + async def _qq_ack(client: Any, interaction_id: str, code: int) -> None: + if not interaction_id: + return + try: + await client.api.on_interaction_result(interaction_id, int(code)) + except Exception as exc: + logger.warning("按钮网关:QQ ACK 失败 %s", type(exc).__name__) + + @staticmethod + async def _qq_reply(client: Any, interaction: Any, user_id: str, text: str) -> None: + kwargs: dict[str, Any] = { + "openid": user_id, + "msg_type": 0, + "content": str(text or "处理完成")[:1800], + "msg_seq": random.randint(1, 10000), + } + event_id = str(getattr(interaction, "event_id", "") or "") + if event_id: + kwargs["event_id"] = event_id + try: + await client.api.post_c2c_message(**kwargs) + except Exception as exc: + logger.warning("按钮网关:QQ 结果消息发送失败 %s", type(exc).__name__) + + # ──── diagnostics ──── + + @filter.command("btngw") + @filter.permission_type(filter.PermissionType.ADMIN) + async def cmd_status(self, event: AstrMessageEvent): + """查看按钮网关状态。""" + self.registry.purge() + platform = self.context.get_platform_inst(self.qq_platform_id) + client = getattr(platform, "client", None) if platform else None + yield event.plain_result( + "按钮网关状态\n" + f"QQ 入口接管:{'是' if self._bridge_installed else '否'}\n" + f"QQ INTERACTION intent:{'已启用' if client is not None and qq_bridge.intent_enabled(client) else '未启用/未连接'}\n" + f"Telegram 处理器:{'已注册' if self._telegram_application is not None else '未注册'}\n" + f"待处理引用:{len(self.registry)}" + ) diff --git a/metadata.yaml b/metadata.yaml new file mode 100644 index 0000000..08ba7db --- /dev/null +++ b/metadata.yaml @@ -0,0 +1,5 @@ +name: astrbot_plugin_button_gateway +desc: "跨插件共享的交互按钮网关:独占 QQ Interaction 入口,按短引用把点击路由回发起插件;同时支持 Telegram inline keyboard。" +version: v0.1.0 +author: local +repo: "" diff --git a/qq_bridge.py b/qq_bridge.py new file mode 100644 index 0000000..63b6f14 --- /dev/null +++ b/qq_bridge.py @@ -0,0 +1,110 @@ +"""Own the single QQ Interaction entry point on behalf of every plugin. + +AstrBot builds its QQ client from botpy's `botClient`, and native (action.type=1) buttons only +arrive if the INTERACTION intent is set at construction time and `on_interaction_create` is +overridden on the class. Both are process-wide, so exactly one component may own them — +several plugins patching independently silently clobber each other. + +This module is that owner. Differences from a per-plugin patch: + +* install is idempotent and records the *original* attributes so uninstall genuinely restores + them (a patch that only clears an "active plugin" slot leaves wrappers stacked forever); +* unrecognised references fall through to whatever handler was installed before us, so a + plugin that still carries its own bridge keeps working while it migrates. +""" +from __future__ import annotations + +import logging +from typing import Any, Awaitable, Callable + +logger = logging.getLogger(__name__) + +QQ_INTERACTION_INTENT = 1 << 26 + +_ORIG_INIT = "_btngw_original_init" +_ORIG_HANDLER = "_btngw_original_interaction_handler" +_DISPATCH = "_btngw_dispatch" +_INSTALLED = "_btngw_installed" + + +def _bot_client() -> Any | None: + try: + from astrbot.core.platform.sources.qqofficial.qqofficial_platform_adapter import ( # noqa: PLC0415 + botClient, + ) + except (ImportError, AttributeError): + return None + return botClient + + +def install(dispatch: Callable[[Any, Any], Awaitable[bool]]) -> bool: + """Take over the interaction entry point. + + `dispatch(client, interaction)` must return True when it handled the interaction and False + to let the previously installed handler have it. + """ + bot_client = _bot_client() + if bot_client is None: + return False + + if not hasattr(bot_client, _ORIG_INIT): + setattr(bot_client, _ORIG_INIT, bot_client.__init__) + if not hasattr(bot_client, _ORIG_HANDLER): + setattr(bot_client, _ORIG_HANDLER, getattr(bot_client, "on_interaction_create", None)) + + setattr(bot_client, _DISPATCH, dispatch) + + if getattr(bot_client, _INSTALLED, False): + # Already wrapped; swapping the dispatch above is enough. + return True + + original_init = getattr(bot_client, _ORIG_INIT) + + def patched_init(client: Any, *args: Any, **kwargs: Any) -> None: + original_init(client, *args, **kwargs) + client.intents = int(getattr(client, "intents", 0)) | QQ_INTERACTION_INTENT + + async def on_interaction_create(client: Any, interaction: Any) -> None: + handler = getattr(bot_client, _DISPATCH, None) + if handler is not None: + try: + if await handler(client, interaction): + return + except Exception: + logger.exception("按钮网关处理 QQ Interaction 失败") + return + fallback = getattr(bot_client, _ORIG_HANDLER, None) + if fallback is not None: + await fallback(client, interaction) + + bot_client.__init__ = patched_init + bot_client.on_interaction_create = on_interaction_create + setattr(bot_client, _INSTALLED, True) + return True + + +def uninstall() -> None: + """Restore botpy to its pre-gateway state, unlike a slot-clearing teardown.""" + bot_client = _bot_client() + if bot_client is None or not getattr(bot_client, _INSTALLED, False): + return + if hasattr(bot_client, _ORIG_INIT): + bot_client.__init__ = getattr(bot_client, _ORIG_INIT) + delattr(bot_client, _ORIG_INIT) + if hasattr(bot_client, _ORIG_HANDLER): + original = getattr(bot_client, _ORIG_HANDLER) + if original is not None: + bot_client.on_interaction_create = original + else: + try: + del bot_client.on_interaction_create + except AttributeError: + pass + delattr(bot_client, _ORIG_HANDLER) + for attr in (_DISPATCH, _INSTALLED): + if hasattr(bot_client, attr): + delattr(bot_client, attr) + + +def intent_enabled(client: Any) -> bool: + return bool(int(getattr(client, "intents", 0)) & QQ_INTERACTION_INTENT) diff --git a/registry.py b/registry.py new file mode 100644 index 0000000..5ad7112 --- /dev/null +++ b/registry.py @@ -0,0 +1,130 @@ +"""Short-reference registry for interactive buttons. + +QQ caps a button's action.data at 100 bytes and Telegram caps callback_data at 64, so the real +callback payload can never travel inside the button itself. The gateway hands out an opaque +short reference instead and keeps the payload here. + +A reference is single-use by default and pinned to one user, mirroring the guarantees the QQ +protocol already offers (click_limit / specify_user_ids) so behaviour stays consistent on +platforms that do not enforce them. + +References live in memory only: after a restart every outstanding button reports "已失效", +which is the safe direction — a stale approval must never silently succeed. +""" +from __future__ import annotations + +import re +import secrets +import time +from dataclasses import dataclass, field +from typing import Any + +# g1.<12 chars>.<24 hex> -> 39 bytes. With the "bg::" prefix the worst case stays +# under Telegram's 64-byte callback_data limit, which is the tighter of the two platforms. +REF_RE = re.compile(r"^g1\.[A-Za-z0-9_-]{12}\.[0-9a-f]{24}$") +ACTION_RE = re.compile(r"^[a-z][a-z0-9_-]{0,15}$") + +DEFAULT_TTL_SECONDS = 600 +MAX_ENTRIES = 512 + + +@dataclass +class Entry: + ref: str + owner: str + handler: str + payload: dict[str, Any] + allowed_user_id: str | None + expires_at: float + single_use: bool = True + consumed: bool = False + actions: tuple[str, ...] = field(default_factory=tuple) + + +class ButtonRegistry: + def __init__(self, *, clock=time.monotonic) -> None: + self._entries: dict[str, Entry] = {} + self._clock = clock + + @staticmethod + def new_ref() -> str: + return f"g1.{secrets.token_urlsafe(9)[:12]}.{secrets.token_hex(12)}" + + def issue( + self, + *, + owner: str, + handler: str, + payload: dict[str, Any], + actions: tuple[str, ...], + allowed_user_id: str | None = None, + ttl_seconds: int = DEFAULT_TTL_SECONDS, + single_use: bool = True, + ) -> str: + if not owner or not handler: + raise ValueError("owner 与 handler 不能为空") + if not actions: + raise ValueError("至少要有一个 action") + for action in actions: + if not ACTION_RE.fullmatch(action): + raise ValueError(f"非法 action: {action!r}") + ttl = max(30, min(int(ttl_seconds), 24 * 3600)) + + self.purge() + if len(self._entries) >= MAX_ENTRIES: + # Drop the entry closest to expiry rather than refusing service. + oldest = min(self._entries.values(), key=lambda e: e.expires_at) + self._entries.pop(oldest.ref, None) + + ref = self.new_ref() + self._entries[ref] = Entry( + ref=ref, + owner=owner, + handler=handler, + payload=dict(payload or {}), + allowed_user_id=str(allowed_user_id) if allowed_user_id else None, + expires_at=self._clock() + ttl, + single_use=bool(single_use), + actions=tuple(actions), + ) + return ref + + def purge(self) -> int: + now = self._clock() + stale = [ref for ref, e in self._entries.items() if e.expires_at <= now] + for ref in stale: + self._entries.pop(ref, None) + return len(stale) + + def peek(self, ref: str) -> Entry | None: + entry = self._entries.get(ref) + if entry is None: + return None + if entry.expires_at <= self._clock(): + self._entries.pop(ref, None) + return None + return entry + + def claim(self, ref: str, action: str, user_id: str | None) -> tuple[Entry | None, str]: + """Validate a click. Returns (entry, reason); entry is None when the click is rejected.""" + if not REF_RE.fullmatch(str(ref or "")): + return None, "invalid_ref" + entry = self.peek(ref) + if entry is None: + return None, "expired" + if action not in entry.actions: + return None, "unknown_action" + if entry.allowed_user_id and str(user_id or "") != entry.allowed_user_id: + return None, "forbidden" + if entry.consumed: + return entry, "already_consumed" + if entry.single_use: + entry.consumed = True + self._entries.pop(ref, None) + return entry, "ok" + + def revoke(self, ref: str) -> bool: + return self._entries.pop(ref, None) is not None + + def __len__(self) -> int: + return len(self._entries)