diff --git a/CHANGELOG.md b/CHANGELOG.md index c4b4551..0018bc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # 更新日志 +## 0.1.3 · 2026-11-17 + +- 图片发送方式新增 Base64(默认)、本地文件(NapCat 直读)和图片链接(NapCat 下载);发送失败时记录 ERROR 并回复原文字战报,不自动切换方式。 +- 修复损坏图片缓存被反复使用的问题,发现无效缓存后自动重新生成;新图片不可用时回复文字战报。 + ## 0.1.2 · 2026-11-17 - 近期战绩新增基于 ba-dragon 模型的逐局「评分」,按分数着色,不附称号。 diff --git a/README.md b/README.md index 3a06c00..bc397b5 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,9 @@ AstrBot 原生《断箭》(Broken Arrow)战绩查询插件。以简洁排版 ## 快速开始 -1. **安装插件**:在 AstrBot 插件管理中导入 `astrbot_plugin_ba_stats_v0.1.2.zip`(或将插件目录放入 `data/plugins/` 并使用 AstrBot 的 Python 环境安装 `requirements.txt`)。 +1. **安装插件**:在 AstrBot 的插件页面通过仓库链接在线安装:`https://github.com/timeance/astrbot_plugin_BA_stats`。 2. **开启查询**:进入插件详情 → 可视化视图 → 设置中心,在「常用设置」中开启「启用在线查询」(默认关闭);API 地址通常保持默认即可。常用设置也可在 AstrBot 原生插件配置中调整。 -3. **保存重载**:保存设置后,在 AstrBot 插件页手动重载,使在线查询设置生效。 +3. **保存重载**:自定义设置中心保存后,在 AstrBot 插件页手动重载;原生插件设置保存时自动重载。 4. **绑定与查询**: - 发送 `ba search 昵称` 搜索玩家 - 发送 `ba bind stb:玩家ID` 并按提示发送 `ba select 请求码 序号` 确认绑定 @@ -65,7 +65,7 @@ ba stats @群友 ## 主要配置 -设置中心和 AstrBot 原生插件配置共用同一份设置。诊断开关保存后即时生效;其他设置保存后,请在插件页手动重载。 +自定义设置中心和 AstrBot 原生插件配置共用同一份设置。自定义设置中心保存后,诊断开关即时生效,其他设置需在插件页手动重载;原生插件设置保存时自动重载。 - **数据源接入**:在线查询开关、API 地址,无需填写客户端标识或令牌。 - **查询与命令**:默认/最大近期场数(5 / 20)、用户冷却(3 秒)、中文子命令别名开关。 @@ -74,6 +74,8 @@ ba stats @群友 - **维护与缓存**:请求间隔、并发、超时、重试及缓存容量/旧缓存回退时间,设置中心中默认折叠。 - **诊断日志**:诊断开关、日志状态和 ZIP 下载集中显示,内容默认折叠;总容量上限 30 MB,旧日志自动轮换。 +图片发送方式(`output.image_send_mode`)可选「Base64(默认)」「本地文件(NapCat 直读)」「图片链接(NapCat 下载)」。Windows 同机部署可选本地文件,NapCat 必须能访问 AstrBot 的图片路径;图片链接需要渲染器提供 NapCat 可访问的 HTTP(S) 链接,返回本地文件时不可用。图片生成或发送失败会在控制台记录 `ERROR` 并回复原文字战报,不自动切换 Base64 或重试其他发送方式。 + 排查问题时,在设置中心选择「诊断日志」并展开,开启诊断并保存后复现问题,再点击「下载诊断日志(ZIP)」。下载由宿主登录鉴权。 ## 数据与常见问题 diff --git a/_conf_schema.json b/_conf_schema.json index c9ee7f8..a78849d 100644 --- a/_conf_schema.json +++ b/_conf_schema.json @@ -78,6 +78,22 @@ "default": true, "hint": "调用 AstrBot 图文渲染服务生成战报图;渲染或图片发送未成功时,使用同一查询结果回复文字,不重复查询。" }, + "image_send_mode": { + "description": "图片发送方式", + "type": "string", + "default": "base64", + "options": [ + "base64", + "file", + "url" + ], + "labels": [ + "Base64(默认)", + "本地文件(NapCat 直读)", + "图片链接(NapCat 下载)" + ], + "hint": "本地文件需 NapCat 可读取图片路径;图片链接需渲染器返回可访问的 HTTP(S) 地址。发送失败记录 ERROR 并回复文字战报。" + }, "theme": { "description": "图片主题", "type": "string", diff --git a/diagnostics.py b/diagnostics.py index 3ab4d06..675efb8 100644 --- a/diagnostics.py +++ b/diagnostics.py @@ -32,7 +32,7 @@ "lifecycle", "command", "query", "request", "cache", "render", "send", "fallback", "quota", "export", "plugin_start", "plugin_stop", "command_start", "command_complete", "command_error", "query_complete", "image_cache", "image_render_start", "image_render_complete", "image_render_error", - "image_send_start", "image_send_complete", "image_send_error", "text_report", + "image_send_start", "image_send_complete", "image_send_error", "image_validated", "image_cache_invalid", "text_report", "text_send_start", "text_send_complete", "text_send_error", "http_start", "http_response", "http_error", }) _ACTIONS = frozenset({"help", "stats", "recent", "last", "match", "search", "bind", "binding", "unbind", "select", "cancel", "status", "quota", "cache_clear", "unknown"}) @@ -43,7 +43,8 @@ "ReadTimeout", "WriteTimeout", "PoolTimeout", "HTTPError", "HTTPStatusError", "RequestError", "ClientError", "NotConfiguredError", "AuthenticationError", "RateLimitError", "RequestTimeoutError", "UpstreamError", "NoDataError", "SchemaError", "IdentityMismatchError", "QueueFullError", "ClientClosedError", - "QuotaExceededError", + "QuotaExceededError", "ImageTransportError", "UnidentifiedImageError", "DecompressionBombError", + "DecompressionBombWarning", "ClientConnectorError", "ClientPayloadError", "ClientResponseError", "ServerTimeoutError", }) _ROUTES = frozenset({"/api/players/search", "/api/analysis/player", "/api/players/matches", "/api/match"}) _IMAGE_NAME = re.compile(r"(?:[0-9a-f]{64}|report|card|image)(?:-[0-9]{1,4})?\.(?:jpg|jpeg|png|webp|gif)\Z", re.IGNORECASE) @@ -59,6 +60,14 @@ ("failed", re.compile(r"\bfail\w*\b|失败", re.IGNORECASE)), ) _ENUMS = { + "mode": frozenset({"base64", "file", "url"}), + "stage": frozenset({"generate", "download", "validate", "cache", "send"}), + "reason": frozenset({"generation_failed", "download_failed", "validation_failed", "cache_failed", "send_failed", + "timeout", "http_status", "invalid_content_type", "invalid_image_size", "invalid_image", + "unsupported_image", "url_unavailable", "local_path_unavailable", "unsupported_mode", + "onebot_required", "invalid_target", "onebot_rejected"}), + "content_type": frozenset({"image/jpeg", "image/png", "image/gif", "image/webp", "application/octet-stream", + "text/plain", "text/html", "application/json"}), "phase": frozenset({"start", "finish", "error", "cancel", "initialize", "terminate", "enable", "disable"}), "command": _ACTIONS, "action": _ACTIONS, @@ -70,7 +79,7 @@ "image_type": frozenset({"JPEG", "JPG", "PNG", "GIF", "WEBP", "UNKNOWN", "jpeg", "jpg", "png", "gif", "webp", "unknown", "未知"}), "scope": frozenset({"global", "user", "group"}), } -_COUNTERS = frozenset({"count", "inflight", "requests", "cache_hits", "stale_hits", "bytes", "retry", "limit", "used", "remaining", "page", "image_bytes", "attempt", "rows"}) +_COUNTERS = frozenset({"count", "inflight", "requests", "cache_hits", "stale_hits", "bytes", "retry", "limit", "used", "remaining", "page", "image_bytes", "attempt", "rows", "width", "height"}) _BOOLEANS = frozenset({"configured", "closed", "force", "cached", "stale"}) @@ -94,7 +103,7 @@ def _safe_fields(fields: dict) -> dict: value = fields.get("status") if type(value) is int and 100 <= value <= 599: result["status"] = value - elif type(value) is str and value in _ERROR_CODES | {"ok", "success", "error", "failed", "fallback", "0.1.2"}: + elif type(value) is str and value in _ERROR_CODES | {"ok", "success", "error", "failed", "fallback", "0.1.2", "0.1.3"}: result["status"] = value value = fields.get("retcode") if type(value) is int and -1_000_000_000 <= value <= 1_000_000_000: @@ -121,6 +130,23 @@ def _safe_fields(fields: dict) -> dict: return result +def image_error_metadata(exc, mode, stage): + """Share the same allowlist between always-on console errors and diagnostics.""" + result = getattr(exc, "result", None) + result = result if isinstance(result, dict) else {} + cause = exc.__cause__ or exc + defaults = {"generate": "generation_failed", "download": "download_failed", "validate": "validation_failed", + "cache": "cache_failed", "send": "send_failed"} + return _safe_fields({ + "mode": mode, "stage": stage if stage == "cache" else getattr(exc, "stage", stage), + "error": type(cause).__name__, "retcode": result.get("retcode"), + "reason": getattr(exc, "reason", "timeout" if isinstance(exc, TimeoutError) else defaults.get(stage)), + "message": result.get("message") or result.get("wording"), + "status_code": getattr(exc, "status_code", None), "content_type": getattr(exc, "content_type", None), + "image_bytes": getattr(exc, "image_bytes", None), + }) + + class DiagnosticLog: """Thread-safe bounded recorder with atomic ZIP snapshots. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index f78c3e0..4a25208 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -1,16 +1,16 @@ # 验证记录 -验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.2。 +验证日期:2026-11-17(Asia/Hong_Kong)。版本:v0.1.3。 ## 本次结果 | 项目 | 结果 | | --- | --- | -| 完整离线测试 | **635 passed,25.90 秒** | +| 完整离线测试 | **695 passed,33.35 秒** | | 评分与固定上游 TypeScript 对照 | **320 个合成样本一致**;中间值误差小于 1e-12 | -| 三类战报本地渲染 | 18 组 HTML/文字、36 张 PNG;无横向溢出或外部请求 | -| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览 | -| 依赖兼容性 | `uv pip check`:21 个已安装包兼容 | +| 三类战报本地渲染 | 沿用 v0.1.2 的 18 组 HTML/文字、36 张 PNG;本轮未修改战报版式 | +| 设置中心本地交互 | 深色 390px、浅色 1100px 两组通过;4 张预览;新增发送方式保存检查 | +| 依赖兼容性 | `uv pip check`:30 个已安装包兼容 | | 完整 AstrBot 服务、真实渲染服务 | 未启动;按 v4.29.4 固定源码核对 API,使用事件与桥接桩验证 | | BATrace / QQ 实际联调 | 开发环境未调用;用户已提供候选结果和图片超时日志 | | 远端 PR / CI | 以对应 PR 的实时结果为准;本记录不表示已合并或部署 | @@ -31,26 +31,36 @@ - 独立视图 `views/settings/`,与原生配置共用 AstrBotConfig;常用、额度、维护、诊断分组。跟随宿主深浅主题,维护和诊断内容默认折叠。 - 按 schema 描述与白名单校验字段,API origin 与客户端复用同一 HTTPS 校验规则;不返回或接受旧客户端标识、令牌、全局额度字段。 -- 保存检查磁盘配置版本,冲突返回 409 并保留页面草稿。普通设置等待手动重载,页面显示待生效项;诊断开关保存后即时应用,保存不重启业务对象或中断在途请求。 +- 自定义设置中心保存检查磁盘配置版本,冲突返回 409 并保留页面草稿。普通设置等待手动重载,页面显示待生效项;诊断开关保存后即时应用,保存不重启业务对象或中断在途请求。AstrBot 原生插件设置保存时由宿主自动重载。 - API 使用 AstrBot 登录鉴权,插件额外检查用户名。未登录、已关闭、无效 JSON、非法类型/范围、保存失败及旧实例卸载有回归测试。下载不通过公开静态目录。 - 诊断仅记录允许的事件与字段:请求耗时/状态、渲染及图片发送阶段、文件类型/大小、受控错误分类等。日志上限为 `30 * 1024 * 1024` 字节,旧段自动淘汰;关闭后可下载既有日志。 - 记录器覆盖轮换、并发导出、关闭、磁盘失败及脱敏;不记录令牌、请求头、完整响应、聊天正文或图片内容。导出为 ZIP,不清空原日志。 -- 本地浏览器验证保存开关、下载路由、409 草稿保留、重新读取后保留草稿、待重载提示及固定总额度。合成桥接不替代真实宿主收发;常用设置全页预览将悬浮保存栏放到文档末尾,交互测试使用原样 CSS。 +- 本地浏览器验证保存开关、下载路由、409 草稿保留、重新读取后保留草稿、待重载提示及固定总额度;新增验证 Base64 默认值,以及 file/url 保存后等待重载。合成桥接不替代真实宿主收发;常用设置全页预览将悬浮保存栏放到文档末尾,交互测试使用原样 CSS。 -## 图片超时的已知边界 +## 图片发送与损坏缓存 用户环境为 AstrBot 4.29.4、NapCat.Core 4.18.18;其他插件能发图片。用户日志显示 OneBot `retcode=1200`、QQ `sendMsg` 确认超时。 -v0.1.1 已改为等待图片发送结果,并在未获成功确认时使用同一次查询回复文字、关闭文字自动转图。v0.1.2 增加受控诊断信息,**未证明 QQ 超时根因已修复**。本地卡片可渲染不等于实际 QQ 可接收;需在用户实例打开诊断并复现后检查日志。 +用户提供的诊断 ZIP 显示,玩家概览和单局图片缓存仅有 20 字节,随后发送超时。没有取得该缓存文件原始正文,因此不能断言具体错误响应内容。固定版本 AstrBot 的远程渲染下载路径未验证响应状态和图片内容,插件原先也只检查文件是否存在。 + +v0.1.3 共用图片下载与验证流程:检查 HTTP 状态,限制下载大小与重定向,通过 Pillow 验证并完整解码图片。缓存命中也重新验证;当前摘要的损坏图片会删除并重新生成,新产生的无效文件不会进入缓存或发送。只处理图片缓存,保留查询缓存、绑定和额度记录。 + +- Base64 为默认方式,使用 AstrBot 标准图片组件并等待发送结果;本地文件和链接方式直接调用 OneBot,分别传入 file URI 和实际 HTTP(S) URL,群聊和私聊均保留当前机器人 self_id。 +- 链接方式每次获取新地址。渲染器只返回本地路径或平台不支持对应方式时,明确报错,不伪造链接、不自动切换方式重发。 +- 生成、下载、校验或发送失败均在控制台记录 ERROR,包含方式、阶段和受控原因;诊断关闭也不会隐藏这些错误。不记录原始异常正文、签名 URL、Base64 或凭据。 +- 回归覆盖 20 字节无效文件、损坏及截断图片、旧缓存重建、错误响应不落盘、三种发送方式、群聊/私聊路由及不自动切换重发。文字回退复用同一次查询并关闭自动转图。 + +这些结果证明离线流程与坏缓存处理通过测试,**不代表已完成真实 QQ 收发验收**。仍需在用户实例安装后验证;不能将旧日志中的所有 QQ 超时都归因为相同原因。 ## 执行与证据 ```powershell -& ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v012-final --junitxml=../validation/pytest-v0.1.2.xml -# 635 passed in 25.90s +& ../.venv/Scripts/python.exe -X utf8 -m pytest -q --basetemp=../tmp/pytest-v013-portable --junitxml=../validation/pytest-v0.1.3.xml +# 695 passed in 33.35s & ../.venv/Scripts/python.exe -X utf8 -B tools/render_previews.py --screenshots -# 18 HTML/text pairs; 36 screenshots; 0 layout/network failures +# v0.1.2 记录:18 HTML/text pairs; 36 screenshots; 0 layout/network failures +# 本轮未修改战报版式,沿用对应预览,未重复运行此命令。 & ../.venv/Scripts/python.exe -X utf8 -B tools/check_settings_view.py # 2 local browser scenarios passed; 4 screenshots; no external requests @@ -70,7 +80,7 @@ uv --cache-dir ../tmp/uv-cache pip check --python ../.venv/Scripts/python.exe - AstrBot T2I:`bcc08e47274c69e5ace19bbf738b95260ce17ca7`。 - 设置中心仅参考 `anka-afk/astrbot_plugin_meme_manager` 的分组、折叠与共享配置交互,代码独立实现。 -`tools/build_delivery.py --output ../delivery/v0.1.2` 生成安装 ZIP、Gemini 文案优化 ZIP 及总交付 ZIP。安装包包含原生入口、元数据、配置、模板、设置视图、标题翻译、模型和许可;不含测试环境、个人数据库、缓存、真实凭据或参考项目源码。文案包覆盖提示、配置、HTML/JS、README、CHANGELOG,保留占位符、固定文字与许可约束。各 ZIP 用 `testzip()` 校验并附 SHA-256。 +本次通过 GitHub PR 交付,使用 AstrBot 仓库链接在线安装;不将安装 ZIP 或文案优化包作为交付物。仓库包含原生入口、元数据、配置、模板、设置视图、标题翻译、模型和许可,不提交测试环境、个人数据库、缓存、真实凭据或参考项目源码。 原 Logo 保持不变: diff --git a/image_transport.py b/image_transport.py new file mode 100644 index 0000000..3793294 --- /dev/null +++ b/image_transport.py @@ -0,0 +1,97 @@ +"""Validated render artifacts; URL downloads never use BATrace credentials.""" + +from dataclasses import dataclass, field +from io import BytesIO +from pathlib import Path +from urllib.parse import urlsplit +import warnings + +import aiohttp +from PIL import Image +from yarl import URL + + +IMAGE_SUFFIXES = {"JPEG": ".jpg", "PNG": ".png", "WEBP": ".webp", "GIF": ".gif"} +MAX_IMAGE_BYTES = 32 * 1024 * 1024 + + +class ImageTransportError(ValueError): + """Only controlled stage/reason codes may enter image error messages.""" + + def __init__(self, stage, reason, *, status_code=None, content_type=None): + super().__init__(reason) + self.stage = stage + self.reason = reason + self.status_code = status_code + self.content_type = content_type + + +@dataclass(frozen=True) +class ImageArtifact: + path: Path + image_type: str + width: int + height: int + image_bytes: int + url: str | None = field(default=None, repr=False) + + @property + def metadata(self): + return {"path": self.path.name, "image_type": self.image_type, + "width": self.width, "height": self.height, "image_bytes": self.image_bytes} + + +def validate_image(data: bytes) -> tuple[str, int, int]: + """Verify the container and decode every frame; a suffix is not evidence.""" + if not data or len(data) > MAX_IMAGE_BYTES: + raise ImageTransportError("validate", "invalid_image_size") + try: + with warnings.catch_warnings(): + warnings.simplefilter("error", Image.DecompressionBombWarning) + with Image.open(BytesIO(data)) as picture: + image_type, (width, height) = picture.format, picture.size + if image_type not in IMAGE_SUFFIXES or width <= 0 or height <= 0: + raise ImageTransportError("validate", "unsupported_image") + picture.verify() + with Image.open(BytesIO(data)) as picture: + for frame in range(getattr(picture, "n_frames", 1)): + picture.seek(frame) + picture.load() + except ImageTransportError: + raise + except Exception as exc: + raise ImageTransportError("validate", "invalid_image") from exc + return image_type, width, height + + +def is_image_url(source) -> bool: + """Accept real HTTP(S) references only; never turn a local path into a URL.""" + if not isinstance(source, str): + return False + try: + parsed = urlsplit(source) + return (parsed.scheme in {"http", "https"} and bool(parsed.hostname) + and parsed.username is None and parsed.password is None) + except ValueError: + return False + + +async def download_image(url: str, timeout: float) -> tuple[bytes, str]: + """Download once with bounded redirects/body size and no request URL logging.""" + # aiohttp does not emit httpx's INFO request line containing signed URLs. + async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout), trust_env=True) as session: + async with session.get(URL(url, encoded=True), max_redirects=5) as response: + content_type = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() + if not 200 <= response.status < 300: + raise ImageTransportError("download", "http_status", status_code=response.status, + content_type=content_type) + if content_type and not (content_type.startswith("image/") or content_type == "application/octet-stream"): + raise ImageTransportError("download", "invalid_content_type", content_type=content_type) + if response.content_length is not None and response.content_length > MAX_IMAGE_BYTES: + raise ImageTransportError("download", "invalid_image_size", content_type=content_type) + body = bytearray() + async for chunk in response.content.iter_chunked(64 * 1024): + body.extend(chunk) + if len(body) > MAX_IMAGE_BYTES: + raise ImageTransportError("download", "invalid_image_size", content_type=content_type) + return bytes(body), content_type diff --git a/main.py b/main.py index 2c6702e..4367636 100644 --- a/main.py +++ b/main.py @@ -6,7 +6,6 @@ import hashlib from pathlib import Path import re -import shutil import time from astrbot.api import AstrBotConfig @@ -17,7 +16,10 @@ from .client import BatraceClient, ClientConfig, ClientError from .commands import mention_token, parse_command -from .diagnostics import DiagnosticLog +from .diagnostics import DiagnosticLog, image_error_metadata +from .image_transport import ( + IMAGE_SUFFIXES, MAX_IMAGE_BYTES, ImageArtifact, ImageTransportError, download_image, is_image_url, validate_image, +) from .quota import GLOBAL_DAILY_LIMIT, QuotaActor from .render import Renderer from .service import Caller, StatsService @@ -153,46 +155,147 @@ async def initialize(self): await self.storage.open() self._images.mkdir(parents=True, exist_ok=True) self._prune_images() - self.diagnostics.record("plugin_start", status="0.1.2") + self.diagnostics.record("plugin_start", status="0.1.3") - async def _run(self, awaitable): + async def _run(self, awaitable, *, timed=True): if self._closed: awaitable.close() raise asyncio.CancelledError task = asyncio.create_task(awaitable) self._tasks.add(task) try: - return await asyncio.wait_for(task, self.settings.wait_timeout) + return await asyncio.wait_for(task, self.settings.wait_timeout) if timed else await task finally: self._tasks.discard(task) + def _image_files(self): + return [p for p in self._images.iterdir() + if p.is_file() and p.suffix.lower() in {*IMAGE_SUFFIXES.values(), ".jpeg"}] + def _prune_images(self): - files = sorted(self._images.glob("*.jpg"), key=lambda p: p.stat().st_mtime, reverse=True) + files = sorted(self._image_files(), key=lambda p: p.stat().st_mtime, reverse=True) for index, path in enumerate(files): if index >= 48 or time.time() - path.stat().st_mtime > 86400: path.unlink(missing_ok=True) async def _image(self, view, umo): + mode = self.settings.image_send_mode + progress = {"stage": "generate"} + try: + # Keep the timeout inside the stage-aware operation so a download + # timeout is not mislabeled as a renderer failure. + async with asyncio.timeout(self.settings.wait_timeout): + return await self._prepare_image(view, umo, mode, progress) + except ImageTransportError: + raise + except Exception as exc: + reason = {"generate": "generation_failed", "download": "download_failed", + "validate": "validation_failed", "cache": "cache_failed"}[progress["stage"]] + raise ImageTransportError(progress["stage"], "timeout" if isinstance(exc, TimeoutError) else reason) from exc + + async def _prepare_image(self, view, umo, mode, progress): html = self.renderer.template(view) - # Scope renderer endpoint/session too: different AstrBot sessions can use - # different render services. Content itself remains the same result. digest = hashlib.sha256((umo + html).encode()).hexdigest() - destination = self._images / f"{digest}.jpg" async with self._image_lock: - if destination.exists() and time.time() - destination.stat().st_mtime <= 86400: - self.diagnostics.record("image_cache", path=destination.name, image_bytes=destination.stat().st_size) - return str(destination) + progress["stage"] = "cache" + for cached in self._image_files(): + if cached.stem != digest: + continue + try: + if cached.stat().st_size > MAX_IMAGE_BYTES: + raise ImageTransportError("cache", "invalid_image_size") + data = cached.read_bytes() + image_type, width, height = await asyncio.to_thread(validate_image, data) + except (ImageTransportError, OSError) as exc: + exc.image_bytes = cached.stat().st_size if cached.exists() else None + self._log_image_failure(exc, mode, "cache") + cached.unlink(missing_ok=True) + continue + # Old releases could label PNG bytes as .jpg. Normalize the + # artifact to its decoded format without changing its bytes. + correct_path = cached.with_suffix(IMAGE_SUFFIXES[image_type]) + if cached != correct_path: + cached.replace(correct_path) + cached = correct_path + # URL mode always regenerates: signed URLs are not persisted. + if mode != "url" and time.time() - cached.stat().st_mtime <= 86400: + image = ImageArtifact(cached, image_type, width, height, len(data)) + self.diagnostics.record("image_cache", mode=mode, stage="cache", **image.metadata) + return image # Final HTML is DATA, never a second Jinja template. This preserves # literal {{...}} in nicknames after the first HTML escaping pass. + progress["stage"] = "generate" source = await self.html_render( - "{{ body | safe }}", {"body": html}, return_url=False, + "{{ body | safe }}", {"body": html}, return_url=True, options={"type": "jpeg", "quality": 85, "full_page": True, "viewport_width": 900 if view.get("kind") == "match" else 390, "device_scale_factor_level": "ultra"}, umo=umo) - if not Path(source).is_file(): - raise ValueError("渲染服务未返回本地图片。") - shutil.copyfile(source, destination) + url = source if is_image_url(source) else None + content_type = "" + if url: + progress["stage"] = "download" + try: + data, content_type = await download_image(url, self.settings.wait_timeout) + except ImageTransportError: + raise + except Exception as exc: + raise ImageTransportError("download", "download_failed") from exc + else: + if mode == "url": + raise ImageTransportError("generate", "url_unavailable") + if not isinstance(source, (str, Path)) or not Path(source).is_file(): + raise ImageTransportError("generate", "local_path_unavailable") + if Path(source).stat().st_size > MAX_IMAGE_BYTES: + raise ImageTransportError("validate", "invalid_image_size") + data = Path(source).read_bytes() + progress["stage"] = "validate" + try: + image_type, width, height = await asyncio.to_thread(validate_image, data) + except ImageTransportError as exc: + exc.image_bytes, exc.content_type = len(data), content_type + raise + progress["stage"] = "cache" + destination = self._images / f"{digest}{IMAGE_SUFFIXES[image_type]}" + temporary = destination.with_suffix(".part") + try: + temporary.write_bytes(data) + temporary.replace(destination) + finally: + temporary.unlink(missing_ok=True) + for previous in self._image_files(): + if previous.stem == digest and previous != destination: + previous.unlink(missing_ok=True) + image = ImageArtifact(destination, image_type, width, height, len(data), url) + self.diagnostics.record("image_validated", mode=mode, stage="validate", content_type=content_type, + **image.metadata) self._prune_images() - return str(destination) + return image + + async def _send_image(self, event, image): + mode = self.settings.image_send_mode + if mode == "base64": + await event.send(event.image_result(str(image.path))) + return + if mode not in {"file", "url"}: + raise ImageTransportError("send", "unsupported_mode") + if (event.get_platform_name() != "aiocqhttp" + or not callable(getattr(getattr(event, "bot", None), "call_action", None))): + raise ImageTransportError("send", "onebot_required") + if mode == "url" and not is_image_url(image.url): + raise ImageTransportError("send", "url_unavailable") + file = image.path.resolve().as_uri() if mode == "file" else image.url + group = event.get_group_id() + target = group or event.get_sender_id() + if not str(target).isascii() or not str(target).isdecimal() or int(target) <= 0: + raise ImageTransportError("send", "invalid_target") + payload = {"group_id" if group else "user_id": int(target), "self_id": event.get_self_id(), + "message": [{"type": "image", "data": {"file": file}}]} + result = await event.bot.call_action("send_group_msg" if group else "send_private_msg", **payload) + # aiocqhttp normally raises ActionFailed itself; also handle adapters + # that return an unwrapped OneBot failure envelope. + if isinstance(result, dict) and (result.get("retcode", 0) != 0 or result.get("status") == "failed"): + error = ImageTransportError("send", "onebot_rejected") + error.result = result + raise error async def _status(self): status = self.client.status() @@ -201,11 +304,11 @@ async def _status(self): "schema": "响应结构变化", "identity_mismatch": "身份校验失败", "no_data": "暂无收录", "upstream": "上游暂不可用", "queue_full": "队列已满", "not_configured": "接入未配置", "closed": "客户端已关闭", "daily_quota": "每日额度已用完"} - return (f"断箭战报 v0.1.2\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" + return (f"断箭战报 v0.1.3\n在线查询:{'已启用' if status['configured'] else '未启用或 API 地址无效'}\n" f"今日总请求:{usage['global']}/{GLOBAL_DAILY_LIMIT}(固定上限);北京时间 0 点重置\n" f"本次运行请求:{status['requests']};进行中:{status['inflight']}\n" f"API 缓存:{await self.storage.cache_count()} 条;命中:{status['cache_hits']};旧缓存:{status['stale_hits']}\n" - f"图片缓存:{len(list(self._images.glob('*.jpg')))} 张\n" + f"图片缓存:{len(self._image_files())} 张\n" f"最近错误:{labels.get(status['last_error'], '无' if not status['last_error'] else '请求失败')}\n" f"诊断模式:{'已开启' if self.settings.diagnostics_enabled else '已关闭'}") @@ -240,27 +343,21 @@ def _response_result(self, event, response, config): # Instructions must remain copyable, and At components must stay interactive. return event.chain_result(parts).use_t2i(False) - def _log_image_send_failure(self, exc, path): - result = getattr(exc, "result", None) - result = result if isinstance(result, dict) else {} - # Include only diagnostic OneBot fields, never its payload/echo/base64. - detail = str(result.get("message") or result.get("wording") or "无平台错误详情")[:512] - detail = re.sub(r"base64://\S+|https?://\S+", "[已省略]", detail) - detail = " ".join(detail.split()) - try: - image_path = Path(path) - size = image_path.stat().st_size - with image_path.open("rb") as source: - signature = source.read(8) - image_type = "JPEG" if signature.startswith(b"\xff\xd8\xff") else ( - "PNG" if signature == b"\x89PNG\r\n\x1a\n" else "未知") - except OSError: - size, image_type = "不可读取", "未知" - self.logger.warning( - "断箭战报图片发送未获成功确认(%s,retcode=%s,%s);图片=%s;格式=%s;字节数=%s。改发文字。", - type(exc).__name__, result.get("retcode", "未知"), detail, path, image_type, size) - self.diagnostics.record("image_send_error", error=type(exc).__name__, retcode=result.get("retcode"), - message=detail, path=Path(path).name, image_type=image_type, image_bytes=size) + def _log_image_failure(self, exc, mode, stage, image=None): + details = image_error_metadata(exc, mode, stage) + metadata = image.metadata if image is not None else {} + details.update(metadata) + self.logger.error( + "断箭战报图片失败 mode=%s stage=%s error=%s retcode=%s reason=%s message=%s http_status=%s type=%s bytes=%s", + details.get("mode", "unknown"), details.get("stage", stage), details.get("error", "unknown"), + details.get("retcode", "unknown"), details.get("reason", "unknown"), details.get("message", "details_omitted"), + details.get("status_code", "unknown"), details.get("image_type", "unknown"), details.get("image_bytes", "unknown")) + if stage == "send": + self.diagnostics.record("image_send_error", **details) + elif stage == "cache": + self.diagnostics.record("image_cache_invalid", **details) + else: + self.diagnostics.record("image_render_error", **details) @filter.command("ba", alias={"BA", "Ba", "bA"}) async def ba(self, event: AstrMessageEvent): @@ -290,7 +387,7 @@ async def ba(self, event: AstrMessageEvent): else: await self.client.clear_cache() async with self._image_lock: - for path in self._images.glob("*.jpg"): + for path in self._image_files(): path.unlink(missing_ok=True) yield event.plain_result("已清理 API 缓存与图片缓存;账号绑定及今日已用额度不受影响。") return @@ -308,25 +405,24 @@ async def ba(self, event: AstrMessageEvent): if send_images: stage_started = time.monotonic() try: - path = await self._run(self._image(view, event.unified_msg_origin)) + image = await self._run(self._image(view, event.unified_msg_origin), timed=False) except Exception as exc: - self.diagnostics.record("image_render_error", error=type(exc).__name__, - duration_ms=round((time.monotonic() - stage_started) * 1000)) - self.logger.warning("断箭战报图片渲染失败,已使用相同查询结果回复文字。") + self._log_image_failure(exc, self.settings.image_send_mode, "generate") else: - self.diagnostics.record("image_render_complete", kind=view.get("kind"), path=Path(path).name, + self.diagnostics.record("image_render_complete", kind=view.get("kind"), mode=self.settings.image_send_mode, + **image.metadata, duration_ms=round((time.monotonic() - stage_started) * 1000)) stage_started = time.monotonic() - self.diagnostics.record("image_send_start", path=Path(path).name) + self.diagnostics.record("image_send_start", mode=self.settings.image_send_mode, stage="send", **image.metadata) try: # Await the transport here: errors from yielded results # are otherwise swallowed later by AstrBot's pipeline. - await self._run(event.send(event.image_result(path))) + await self._run(self._send_image(event, image)) except Exception as exc: - self._log_image_send_failure(exc, path) + self._log_image_failure(exc, self.settings.image_send_mode, "send", image) send_uncertain = True else: - self.diagnostics.record("image_send_complete", path=Path(path).name, + self.diagnostics.record("image_send_complete", mode=self.settings.image_send_mode, stage="send", **image.metadata, duration_ms=round((time.monotonic() - stage_started) * 1000)) continue send_images = False diff --git a/metadata.yaml b/metadata.yaml index dc0c4f9..9f34898 100644 --- a/metadata.yaml +++ b/metadata.yaml @@ -2,7 +2,7 @@ name: astrbot_plugin_ba_stats display_name: 断箭战报 short_desc: "《断箭》战绩查询,支持逐局评分、赛前预测与图片战报。" desc: "查询《断箭》(Broken Arrow)玩家概览、近期战绩和单局战报,展示逐局评分、赛前预测、双方对比与兵种构成,支持账号绑定、群友查询及图片或文字展示。在设置中心或原生插件配置中开启在线查询后使用。" -version: "0.1.2" +version: "0.1.3" author: timeance repo: https://github.com/timeance/astrbot_plugin_BA_stats astrbot_version: ">=4.29.4" diff --git a/requirements.txt b/requirements.txt index a1575e1..5d825f3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,5 @@ httpx>=0.27,<1 aiosqlite>=0.20,<1 Jinja2>=3.1,<4 tzdata>=2024.1 +Pillow>=10.4,<14 +aiohttp>=3.9,<4 diff --git a/settings.py b/settings.py index 780a070..50d87fa 100644 --- a/settings.py +++ b/settings.py @@ -46,6 +46,7 @@ class Settings: cooldown_seconds: float = 3 chinese_aliases: bool = True image_enabled: bool = True + image_send_mode: str = "base64" theme: str = "dark" timezone: str = "Asia/Shanghai" request_interval: float = 1 @@ -77,6 +78,9 @@ def from_config(cls, config): theme = output.get("theme", "dark") if theme not in {"dark", "light"}: raise ValueError("主题必须为 dark 或 light。") + image_send_mode = output.get("image_send_mode", "base64") + if image_send_mode not in ("base64", "file", "url"): + raise ValueError("图片发送方式必须为 base64、file 或 url。") return cls( enabled=bool(access.get("enabled", False)), base_url=str(access.get("base_url", cls.base_url)).strip(), @@ -85,6 +89,7 @@ def from_config(cls, config): cooldown_seconds=bounded(query, "cooldown_seconds", 3, 0, 60), chinese_aliases=bool(query.get("chinese_aliases", True)), image_enabled=bool(output.get("image_enabled", True)), + image_send_mode=image_send_mode, theme=theme, timezone=timezone, request_interval=bounded(maintenance, "request_interval", 1, 0.1, 60), concurrency=bounded(maintenance, "concurrency", 2, 1, 5, int), diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..d8d90a8 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,20 @@ +"""Runtime configuration contracts without a live host/API.""" +import pytest + +from settings import Settings + + +def test_image_send_mode_defaults_to_base64(): + assert Settings().image_send_mode == "base64" + assert Settings.from_config({}).image_send_mode == "base64" + + +@pytest.mark.parametrize("mode", ["base64", "file", "url"]) +def test_image_send_mode_accepts_supported_values(mode): + assert Settings.from_config({"output": {"image_send_mode": mode}}).image_send_mode == mode + + +@pytest.mark.parametrize("mode", ["auto", "BASE64", "", None, False, 123, [], {}]) +def test_image_send_mode_rejects_invalid_values(mode): + with pytest.raises(ValueError, match="图片发送方式"): + Settings.from_config({"output": {"image_send_mode": mode}}) diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 0efdaa4..6c5a529 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -10,7 +10,7 @@ import pytest -from diagnostics import DiagnosticLog, MAX_TOTAL_BYTES +from diagnostics import DiagnosticLog, MAX_TOTAL_BYTES, image_error_metadata def unpack(data): @@ -26,6 +26,23 @@ def unpack(data): return contents, records +def test_image_metadata_allowlist_and_console_fields_share_redaction(tmp_path): + log = DiagnosticLog(tmp_path, enabled=True) + error = RuntimeError("base64://do-not-print https://host/?signature=secret chat text") + error.result = {"retcode": 1200, "message": "Timeout: sendMsg base64://secret https://host/?key=secret private chat"} + fields = image_error_metadata(error, "url", "send") + assert fields == {"mode": "url", "stage": "send", "error": "RuntimeError", "reason": "send_failed", + "retcode": 1200, "message": "Timeout: sendMsg"} + assert log.record("image_send_error", **fields, width=900, height=1200, content_type="image/jpeg") + assert log.record("image_validated", mode="url?secret", stage="secret", width="secret", height=True, + reason="secret", content_type="image/jpeg; secret") + contents, records = unpack(log.export_zip()) + assert "secret" not in b"".join(contents.values()).decode() + assert records[0]["width"] == 900 and records[0]["height"] == 1200 + assert records[0]["content_type"] == "image/jpeg" + assert set(records[1]) == {"timestamp", "event"} + + def test_default_disabled_switch_and_permanent_close(tmp_path): directory = tmp_path / "diagnostics" log = DiagnosticLog(directory) diff --git a/tests/test_image_transport.py b/tests/test_image_transport.py new file mode 100644 index 0000000..add060b --- /dev/null +++ b/tests/test_image_transport.py @@ -0,0 +1,83 @@ +"""Offline decoder and HTTP response contracts; no sockets are opened.""" + +from io import BytesIO + +import pytest +from PIL import Image + +import image_transport as transport + + +def picture_bytes(kind="PNG"): + stream = BytesIO() + Image.new("RGB", (12, 8), "blue").save(stream, format=kind) + return stream.getvalue() + + +@pytest.mark.parametrize("kind", ["JPEG", "PNG", "WEBP", "GIF"]) +def test_complete_image_decode_reports_actual_format_and_dimensions(kind): + assert transport.validate_image(picture_bytes(kind)) == (kind, 12, 8) + + +@pytest.mark.parametrize("body", [b"Internal Server Error"[:20], b'{"error":"timeout"} ', + b"https://bad.invalid/", b"\xff\xd8\xff" + b"x" * 17, + picture_bytes("PNG")[:-20], picture_bytes("JPEG")[:-20]]) +def test_error_bodies_and_truncated_images_are_rejected(body): + with pytest.raises(transport.ImageTransportError, match="invalid_image"): + transport.validate_image(body) + + +@pytest.mark.parametrize("status,content_type,body,reason", [ + (503, "text/plain", b"Internal Server Err ", "http_status"), + (200, "application/json", b'{"error":"timeout"}', "invalid_content_type"), + (200, "image/jpeg", b"Internal Server Err ", None), + (200, "application/octet-stream", picture_bytes(), None), +]) +async def test_http_response_is_checked_before_decoding(monkeypatch, status, content_type, body, reason): + calls = [] + + class Response: + headers = {"Content-Type": content_type} + content_length = len(body) + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + pass + + async def iter_chunked(self, size): + yield body + + response = Response() + response.status, response.content = status, response + + class Session: + def __init__(self, **kwargs): + assert kwargs["timeout"].total == 7 + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + pass + + def get(self, url, **kwargs): + calls.append((str(url), kwargs)) + return response + + monkeypatch.setattr(transport.aiohttp, "ClientSession", Session) + url = "https://render.invalid/card?signature=do%2Fnot%2Bchange" + if reason: + with pytest.raises(transport.ImageTransportError, match=reason) as caught: + await transport.download_image(url, 7) + assert caught.value.stage == "download" + else: + data, mime = await transport.download_image(url, 7) + assert data == body and mime == content_type + assert calls == [(url, {"max_redirects": 5})] + + +@pytest.mark.parametrize("source", ["/tmp/image.jpg", "file:///tmp/image.jpg", "base64://secret", "https://user:pass@host/img", "https://"]) +def test_local_or_credential_bearing_reference_is_not_a_downloadable_url(source): + assert not transport.is_image_url(source) diff --git a/tests/test_main.py b/tests/test_main.py index 868a084..b43aa5d 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -22,6 +22,7 @@ import pytest import httpx +from PIL import Image as PILImage ROOT = Path(__file__).resolve().parents[1] @@ -79,6 +80,9 @@ def get_sender_id(self): def get_platform_id(self): return self.platform + def get_platform_name(self): + return "aiocqhttp" + def get_group_id(self): return self.group @@ -237,6 +241,221 @@ async def collect(plugin, event): return [item async for item in plugin.ba(event)] +def image_bytes(image_type="JPEG"): + output = BytesIO() + PILImage.new("RGB", (12, 8), "#285080").save(output, format=image_type) + return output.getvalue() + + +def artifact(app, path, *, url=None): + return app.main.ImageArtifact(Path(path), "JPEG", 12, 8, len(image_bytes()), url) + + +@pytest.mark.parametrize("mode", ["base64", "file", "url"]) +async def test_twenty_byte_render_body_never_enters_cache_or_send(app, monkeypatch, mode, caplog): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + monkeypatch.setattr(plugin.renderer, "template", lambda view: "synthetic html") + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + render = AsyncMock(return_value="https://render.invalid/result?signature=NEVER-LOG") + download = AsyncMock(return_value=(b"Internal Server Err ", "image/jpeg")) + assert len(download.return_value[0]) == 20 + monkeypatch.setattr(plugin, "html_render", render) + monkeypatch.setattr(app.main, "download_image", download) + event = Event([Plain("/ba stats stb:001")]) + event.bot = SimpleNamespace(call_action=AsyncMock()) + replies = await collect(plugin, event) + assert len(replies) == 1 and replies[0].use_t2i_ is False + assert not event.sent + event.bot.call_action.assert_not_awaited() + render.assert_awaited_once() + download.assert_awaited_once() + assert list(plugin._images.iterdir()) == [] + assert f"mode={mode}" in caplog.text and "stage=validate" in caplog.text + assert "bytes=20" in caplog.text and "invalid_image" in caplog.text + assert "NEVER-LOG" not in caplog.text and "render.invalid" not in caplog.text + assert caplog.records[-1].levelno == logging.ERROR + assert not plugin.diagnostics.enabled + + +async def test_bad_cache_deleted_and_regenerated_once_without_touching_other_data(app, monkeypatch, tmp_path): + plugin = await app.make(images=True) + monkeypatch.setattr(plugin.renderer, "template", lambda view: "cache regression") + digest = app.main.hashlib.sha256(b"sessioncache regression").hexdigest() + bad = plugin._images / f"{digest}.jpg" + bad.write_bytes(b"Internal Server Err ") + source = tmp_path / "real.png" + source.write_bytes(image_bytes("PNG")) + render = AsyncMock(return_value=str(source)) + monkeypatch.setattr(plugin, "html_render", render) + marker = plugin.data_dir / "keep.json" + marker.write_text("keep") + await plugin.storage.put_cache("keep-api", {"ok": True}, 60) + first = await plugin._image({}, "session") + assert not bad.exists() and first.path.suffix == ".png" + assert first.path.read_bytes() == source.read_bytes() + assert (first.width, first.height, first.image_type) == (12, 8, "PNG") + assert await plugin._image({}, "session") == first + render.assert_awaited_once() + assert marker.read_text() == "keep" and await plugin.storage.cache_count() == 1 + + +async def test_valid_old_mislabeled_cache_uses_true_extension_without_rerender(app, monkeypatch): + plugin = await app.make(images=True) + monkeypatch.setattr(plugin.renderer, "template", lambda view: "old image") + digest = app.main.hashlib.sha256(b"sessionold image").hexdigest() + old = plugin._images / f"{digest}.jpg" + old.write_bytes(image_bytes("PNG")) + image = await plugin._image({}, "session") + assert image.path.suffix == ".png" and not old.exists() + assert image.path.read_bytes() == image_bytes("PNG") + + +async def test_bad_cache_and_bad_regeneration_leave_no_reusable_artifact(app, monkeypatch, tmp_path): + plugin = await app.make(images=True) + monkeypatch.setattr(plugin.renderer, "template", lambda view: "bad cache") + digest = app.main.hashlib.sha256(b"sessionbad cache").hexdigest() + (plugin._images / f"{digest}.jpg").write_bytes(b"Internal Server Err ") + source = tmp_path / "bad.jpg" + source.write_bytes(b"Internal Server Err ") + render = AsyncMock(return_value=str(source)) + monkeypatch.setattr(plugin, "html_render", render) + with pytest.raises(app.main.ImageTransportError, match="invalid_image"): + await plugin._image({}, "session") + assert not plugin._image_files() + render.assert_awaited_once() + + +async def test_url_mode_regenerates_url_each_time_but_shares_validated_disk_cache(app, monkeypatch): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": "url"}}) + monkeypatch.setattr(plugin.renderer, "template", lambda view: "url cache") + urls = ["https://render.invalid/a?signature=one", "https://render.invalid/b?signature=two"] + render = AsyncMock(side_effect=urls) + download = AsyncMock(return_value=(image_bytes("PNG"), "image/png")) + monkeypatch.setattr(plugin, "html_render", render) + monkeypatch.setattr(app.main, "download_image", download) + first = await plugin._image({}, "session") + second = await plugin._image({}, "session") + assert [first.url, second.url] == urls and first.path == second.path + assert render.await_count == download.await_count == 2 + assert all(call.kwargs["return_url"] is True for call in render.await_args_list) + assert len(plugin._image_files()) == 1 + assert "signature" not in repr(second) + plugin.settings = app.main.replace(plugin.settings, image_send_mode="base64") + cached = await plugin._image({}, "session") + assert cached.path == second.path and cached.url is None + assert render.await_count == 2 + + +async def test_url_mode_with_local_path_reports_error_and_never_sends(app, monkeypatch, tmp_path, caplog): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": "url"}}) + source = tmp_path / "local.jpg" + source.write_bytes(image_bytes()) + render = AsyncMock(return_value=str(source)) + monkeypatch.setattr(plugin, "html_render", render) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + event = Event([Plain("/ba stats stb:001")]) + event.bot = SimpleNamespace(call_action=AsyncMock()) + replies = await collect(plugin, event) + assert len(replies) == 1 and not event.sent + event.bot.call_action.assert_not_awaited() + render.assert_awaited_once() + assert "mode=url" in caplog.text and "url_unavailable" in caplog.text + assert caplog.records[-1].levelno == logging.ERROR + + +@pytest.mark.parametrize("mode", ["file", "url"]) +@pytest.mark.parametrize("group", ["123", ""]) +async def test_native_onebot_payload_and_no_standard_component_conversion(app, monkeypatch, tmp_path, mode, group): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + picture = tmp_path / "空 格 #.jpg" + picture.write_bytes(image_bytes()) + url = "https://render.invalid/result?signature=do%2Fnot%2Bchange" + image = artifact(app, picture, url=url) + event = Event([], group=group, user="456") + event.bot = SimpleNamespace(call_action=AsyncMock(return_value={"message_id": 1})) + event.image_result = lambda path: pytest.fail("native modes must not use a standard Image component") + event.send = AsyncMock(side_effect=AssertionError("native modes must not call event.send")) + await plugin._send_image(event, image) + event.bot.call_action.assert_awaited_once_with( + "send_group_msg" if group else "send_private_msg", + **{"group_id" if group else "user_id": int(group or "456"), "self_id": "999", + "message": [{"type": "image", "data": {"file": picture.resolve().as_uri() if mode == "file" else url}}]}) + event.send.assert_not_awaited() + + +@pytest.mark.parametrize("mode", ["base64", "file", "url"]) +async def test_failed_send_uses_error_and_text_without_retrying_or_switching_mode(app, monkeypatch, tmp_path, caplog, mode): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + picture = tmp_path / "report.jpg" + picture.write_bytes(image_bytes()) + render = AsyncMock(return_value=artifact(app, picture, url="https://render.invalid/image?secret=123")) + monkeypatch.setattr(plugin, "_image", render) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + error = RuntimeError("base64://raw-body https://secret.invalid/?token=leak private-chat") + error.result = {"retcode": 1200, "message": "Timeout: sendMsg base64://raw-body secret-token private-chat"} + event = Event([Plain("/ba stats stb:001")]) + event.send = AsyncMock(side_effect=error) + event.bot = SimpleNamespace(call_action=AsyncMock(side_effect=error)) + replies = await collect(plugin, event) + assert len(replies) == 1 and replies[0].use_t2i_ is False + assert event.send.await_count == (mode == "base64") + assert event.bot.call_action.await_count == (mode != "base64") + render.assert_awaited_once() + assert f"mode={mode}" in caplog.text and "stage=send" in caplog.text and "retcode=1200" in caplog.text + assert caplog.records[-1].levelno == logging.ERROR + assert not any(secret in caplog.text for secret in ("raw-body", "secret.invalid", "secret-token", "private-chat", "?secret=")) + + +@pytest.mark.parametrize("mode", ["file", "url"]) +async def test_native_modes_reject_non_onebot_platform_with_text_fallback(app, monkeypatch, caplog, mode): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + monkeypatch.setattr(plugin, "_image", AsyncMock(return_value=artifact(app, "report.jpg", url="https://render.invalid/image"))) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + event = Event([Plain("/ba stats stb:001")]) + event.get_platform_name = lambda: "discord" + event.bot = SimpleNamespace(call_action=AsyncMock()) + replies = await collect(plugin, event) + assert len(replies) == 1 and not event.sent + event.bot.call_action.assert_not_awaited() + assert "onebot_required" in caplog.text and caplog.records[-1].levelno == logging.ERROR + + +@pytest.mark.parametrize("mode", ["base64", "file", "url"]) +@pytest.mark.parametrize("stage", ["generate", "download"]) +async def test_generation_and_download_failures_log_correct_stage_without_secrets(app, monkeypatch, caplog, mode, stage): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + error = RuntimeError("https://render.invalid/?signature=private-token base64://private-data private-chat") + render = AsyncMock(side_effect=error) if stage == "generate" else AsyncMock(return_value="https://render.invalid/?signature=private-token") + monkeypatch.setattr(plugin, "html_render", render) + download = AsyncMock(side_effect=error) + monkeypatch.setattr(app.main, "download_image", download) + event = Event([Plain("/ba stats stb:001")]) + replies = await collect(plugin, event) + assert len(replies) == 1 and not event.sent + assert f"mode={mode}" in caplog.text and f"stage={stage}" in caplog.text + assert "error=RuntimeError" in caplog.text and "retcode=unknown" in caplog.text + assert caplog.records[-1].levelno == logging.ERROR + assert not any(secret in caplog.text for secret in ("render.invalid", "private-token", "private-data", "private-chat")) + assert download.await_count == (stage == "download") + assert not plugin.diagnostics.enabled + + +@pytest.mark.parametrize("mode", ["file", "url"]) +async def test_native_returned_failure_envelope_is_not_reported_as_success(app, monkeypatch, caplog, mode): + plugin = await app.make(config={"output": {"image_enabled": True, "image_send_mode": mode}}) + monkeypatch.setattr(plugin, "_image", AsyncMock(return_value=artifact(app, "report.jpg", url="https://render.invalid/image"))) + monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={"kind": "overview"}, instructions=()))) + event = Event([Plain("/ba stats stb:001")]) + event.bot = SimpleNamespace(call_action=AsyncMock(return_value={"status": "failed", "retcode": 1200, + "message": "private-data Timeout: sendMsg"})) + replies = await collect(plugin, event) + assert len(replies) == 1 and not event.sent + event.bot.call_action.assert_awaited_once() + assert "retcode=1200" in caplog.text and "onebot_rejected" in caplog.text + assert "private-data" not in caplog.text + + def test_only_framework_ba_command_is_registered(app_modules): assert len(app_modules.registered) == 1 command, options, function = app_modules.registered[0] @@ -474,7 +693,7 @@ async def test_report_delivery_failure_switches_remaining_pages_to_plain_text(ap monkeypatch.setattr(plugin.service, "execute", execute) monkeypatch.setattr(plugin.renderer, "views", lambda view: [{"kind": "recent", "page": i} for i in range(3)]) monkeypatch.setattr(plugin.renderer, "text", lambda view: f"same data page {view['page']}") - render = AsyncMock(side_effect=lambda view, umo: f"page-{view['page']}.jpg") + render = AsyncMock(side_effect=lambda view, umo: artifact(app, f"page-{view['page']}.jpg")) monkeypatch.setattr(plugin, "_image", render) event = Event([Plain("/ba stats stb:152117")]) attempted = [] @@ -500,7 +719,7 @@ async def test_cancelled_image_send_is_not_converted_to_fallback(app, monkeypatc plugin = await app.make(images=True) monkeypatch.setattr(plugin.service, "execute", AsyncMock(return_value=SimpleNamespace(text="", view={}, instructions=()))) monkeypatch.setattr(plugin.renderer, "views", lambda view: [view]) - monkeypatch.setattr(plugin, "_image", AsyncMock(return_value="synthetic.jpg")) + monkeypatch.setattr(plugin, "_image", AsyncMock(return_value=artifact(app, "synthetic.jpg"))) event = Event([Plain("/ba stats stb:001")]) event.send = AsyncMock(side_effect=asyncio.CancelledError) with pytest.raises(asyncio.CancelledError): @@ -510,9 +729,8 @@ async def test_cancelled_image_send_is_not_converted_to_fallback(app, monkeypatc async def test_image_render_uses_mobile_jpeg_contract_and_fixed_outer_template(app, monkeypatch, tmp_path): plugin = await app.make(images=True) - # Only exercise local file handoff/caching, not image validity or appearance. source = tmp_path / "synthetic-render.jpg" - source.write_bytes(b"synthetic jpeg handoff") + source.write_bytes(image_bytes()) render = AsyncMock(return_value=str(source)) monkeypatch.setattr(plugin, "html_render", render) view = { @@ -520,14 +738,14 @@ async def test_image_render_uses_mobile_jpeg_contract_and_fixed_outer_template(a "scope": "合成测试样本", "fetched_at": datetime(2026, 11, 17, tzinfo=timezone.utc), } first = await plugin._image(view, "onebot:test:group:one") - assert Path(first).suffix == ".jpg" - assert Path(first).read_bytes() == source.read_bytes() + assert first.path.suffix == ".jpg" + assert first.path.read_bytes() == source.read_bytes() assert await plugin._image(view, "onebot:test:group:one") == first render.assert_awaited_once() positional, options = render.await_args assert positional[0] == "{{ body | safe }}" assert "{{ 7 * 7 }} a b" in positional[1]["body"] - assert options["return_url"] is False + assert options["return_url"] is True assert options["umo"] == "onebot:test:group:one" assert options["options"] == { "type": "jpeg", "quality": 85, "full_page": True, @@ -692,12 +910,13 @@ def test_quota_defaults_schema_and_fixed_total_are_consistent(app_modules): async def test_image_failure_logs_onebot_details_and_image_metadata(app, tmp_path, caplog): plugin = await app.make(config={"diagnostics": {"enabled": True}}) picture = tmp_path / "report.jpg" - picture.write_bytes(b"\xff\xd8\xff" + b"synthetic-image") + picture.write_bytes(image_bytes()) error = RuntimeError("not used") error.result = {"retcode": 1200, "message": "Timeout: sendMsg base64://private-image https://secret.invalid/?token=secret", "data": "private-response", "echo": {"token": "private-echo"}} - with caplog.at_level(logging.WARNING): - plugin._log_image_send_failure(error, str(picture)) + with caplog.at_level(logging.ERROR): + plugin._log_image_failure(error, "base64", "send", artifact(app, picture)) + assert all(record.levelno == logging.ERROR for record in caplog.records) assert "retcode=1200" in caplog.text and "Timeout: sendMsg" in caplog.text assert "JPEG" in caplog.text and str(picture.stat().st_size) in caplog.text assert not any(secret in caplog.text for secret in ("private-image", "secret.invalid", "private-response", "private-echo")) diff --git a/tests/test_web_settings.py b/tests/test_web_settings.py index 8272050..a33df8b 100644 --- a/tests/test_web_settings.py +++ b/tests/test_web_settings.py @@ -59,23 +59,33 @@ def test_snapshot_is_schema_based_and_never_discloses_legacy_credentials(editor) fields = {field["path"]: field for field in snapshot["fields"]} assert fields["query.default_limit"]["value"] == 5 assert fields["output.theme"]["options"] == ["dark", "light"] + assert fields["output.image_send_mode"]["value"] == "base64" + assert fields["output.image_send_mode"]["default"] == "base64" + assert fields["output.image_send_mode"]["options"] == ["base64", "file", "url"] + assert fields["output.image_send_mode"]["labels"] == [ + "Base64(默认)", "本地文件(NapCat 直读)", "图片链接(NapCat 下载)"] assert "diagnostics.show_options" not in fields assert not snapshot["reload_required"] and not snapshot["diagnostics"]["enabled"] -def test_partial_save_retains_unmodified_values_and_applies_only_diagnostics(editor): +@pytest.mark.parametrize("image_send_mode", ["file", "url"]) +def test_partial_save_retains_unmodified_values_and_applies_only_diagnostics(editor, image_send_mode): original_settings = editor._running.copy() - result = save(editor, {"diagnostics.enabled": True, "query.default_limit": 6}) + result = save(editor, {"diagnostics.enabled": True, "query.default_limit": 6, + "output.image_send_mode": image_send_mode}) assert editor.diagnostics.enabled and result["diagnostics_applied"] assert editor._running == original_settings - assert result["pending_restart"] == ["query.default_limit"] + assert editor._running["output.image_send_mode"] == "base64" + assert result["pending_restart"] == ["query.default_limit", "output.image_send_mode"] assert "手动重载" in result["message"] assert editor.config["access"]["api_token"] == "PRIVATE_TOKEN" assert editor.config["legacy_token"] == "PRIVATE_ROOT" stored = json.loads(editor.config.config_path.read_text(encoding="utf-8-sig")) assert stored["query"]["default_limit"] == 6 assert stored["diagnostics"]["enabled"] is True - result = save(editor, {"query.default_limit": 5, "diagnostics.enabled": False}) + assert stored["output"]["image_send_mode"] == image_send_mode + result = save(editor, {"query.default_limit": 5, "diagnostics.enabled": False, + "output.image_send_mode": "base64"}) assert not result["reload_required"] and not editor.diagnostics.enabled @@ -86,6 +96,7 @@ def test_partial_save_retains_unmodified_values_and_applies_only_diagnostics(edi {"query.default_limit": 21}, {"query.cooldown_seconds": float("nan")}, {"query.cooldown_seconds": float("inf")}, {"query.cooldown_seconds": 10 ** 1000}, {"access.enabled": "true"}, {"diagnostics.enabled": 1}, {"output.theme": "auto"}, + {"output.image_send_mode": "auto"}, {"output.image_send_mode": None}, {"output.timezone": "Not/AZone"}, {"maintenance.concurrency": 6}, {"access.base_url": "http://example.invalid"}, {"access.base_url": "https://user:secret@example.invalid"}, diff --git a/tools/check_settings_view.py b/tools/check_settings_view.py index dbbe08a..37e1c4d 100644 --- a/tools/check_settings_view.py +++ b/tools/check_settings_view.py @@ -83,6 +83,9 @@ async def main(): os.environ["TMP"] = os.environ["TEMP"] = str(temporary) tempfile.tempdir = str(temporary) snapshot = fixture() + image_mode = next(field for field in snapshot["fields"] if field["path"] == "output.image_send_mode") + assert image_mode["default"] == image_mode["value"] == "base64" + assert image_mode["options"] == ["base64", "file", "url"] checks = [] async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=True) @@ -111,6 +114,10 @@ async def route(request): assert await page.locator("#diagnostics details").get_attribute("open") is None assert await page.locator("#maintenance details").get_attribute("open") is None assert await page.locator("#setting-access-client_id, #setting-access-api_token").count() == 0 + image_select = page.locator("#setting-output-image_send_mode") + assert await image_select.input_value() == "base64" + assert await image_select.locator("option").evaluate_all("options => options.map(option => option.value)") == ["base64", "file", "url"] + assert await image_select.locator("option:checked").inner_text() == "Base64(默认)" await page.evaluate("""() => { const p = document.createElement('p'); p.textContent = '合成预览 · 非运行实例'; p.className = 'muted'; document.querySelector('h1').after(p); @@ -134,6 +141,21 @@ async def route(request): assert (await page.evaluate("window.__downloads[0]")) == ["diagnostics/download", {}, "ba-stats-diagnostics.zip"] await page.screenshot(path=str(OUTPUT / f"settings-diagnostics-{theme}-{label}.png"), full_page=True) + await page.locator('[data-section="common"]').click() + for mode in ("file", "url"): + await image_select.select_option(mode) + assert not await page.locator("#save").is_disabled() + await page.locator("#save").click() + await page.wait_for_function("document.getElementById('save-status').textContent.includes('手动重载')") + post = await page.evaluate("window.__posts.at(-1)") + assert post["path"] == "settings/config" and post["payload"]["changes"] == {"output.image_send_mode": mode} + state = await page.evaluate("window.__state") + assert state["reload_required"] and state["pending_restart"] == ["output.image_send_mode"] + assert await image_select.input_value() == mode + assert await image_select.locator("..").get_attribute("data-pending") == "true" + assert "手动重载" in await page.locator("#apply-state").inner_text() + assert await page.locator("#save").is_disabled() + await page.locator('[data-section="limits"]').click() await page.locator("#setting-limits-user_daily_limit").fill("21") await page.evaluate("window.__conflict = true") @@ -154,6 +176,7 @@ async def route(request): assert dimensions["documentWidth"] <= width and not errors and not external checks.append({"theme": theme, "viewport": label, **dimensions, "passed": True, "checks": ["host theme", "default collapsed", "diagnostic save", "download route", + "image mode defaults to Base64", "file save pending restart", "url save pending restart", "conflict preserves draft", "reload preserves draft", "restart indication", "fixed global quota"], "page_errors": errors, "external_requests": external}) await context.close() diff --git a/web_settings.py b/web_settings.py index 3b2e9ed..278a97b 100644 --- a/web_settings.py +++ b/web_settings.py @@ -20,7 +20,8 @@ "access.enabled": "enabled", "access.base_url": "base_url", "query.default_limit": "default_limit", "query.max_limit": "max_limit", "query.cooldown_seconds": "cooldown_seconds", "query.chinese_aliases": "chinese_aliases", - "output.image_enabled": "image_enabled", "output.theme": "theme", "output.timezone": "timezone", + "output.image_enabled": "image_enabled", "output.image_send_mode": "image_send_mode", + "output.theme": "theme", "output.timezone": "timezone", "limits.user_daily_limit": "user_daily_limit", "limits.group_daily_limit": "group_daily_limit", **{f"maintenance.{key}": key for key in ( "request_interval", "concurrency", "queue_size", "request_timeout", "wait_timeout",