diff --git a/app/adapters/system/attachment.py b/app/adapters/system/attachment.py new file mode 100644 index 000000000..3367c7c24 --- /dev/null +++ b/app/adapters/system/attachment.py @@ -0,0 +1,92 @@ +""" +通知图片来源读取与短期上传文件管理,不保留远程图片或二维码缓存。 +""" + +import base64 +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Optional + +from app.adapters.network.http import RequestUtils +from app.runtime.log import logger +from app.runtime.settings import get_runtime_setting + +# 统一图片输入最多读取 10 MiB;平台更严格的限制由各发送客户端处理。 +IMAGE_MAX_BYTES = 10 * 1024 * 1024 + + +def _download_image(url: str) -> Optional[bytes]: + """ + 有界读取插件提供的 HTTP(S) 图片,并始终释放流式响应。 + """ + response = RequestUtils(timeout=30).get_res(url, stream=True) + if response is None: + return None + try: + if response.status_code != 200: + return None + content = bytearray() + for chunk in response.iter_content(chunk_size=64 * 1024): + if len(content) + len(chunk) > IMAGE_MAX_BYTES: + return None + content.extend(chunk) + return bytes(content) + finally: + response.close() + + +def load_image(image: str) -> Optional[tuple[bytes, str]]: + """ + 从 URL、Base64 数据地址或本地路径读取 JPG/PNG 原图。 + + :param image: 插件明确提供的图片来源;本地路径支持展开用户目录 + :return: 原始字节和匹配内容的文件后缀;格式、大小或读取失败返回 None + """ + try: + content: Optional[bytes] + if image.startswith("data:image/"): + header, encoded = image.split(",", 1) + if not header.endswith(";base64") or len(encoded) > ((IMAGE_MAX_BYTES + 2) // 3) * 4: + return None + content = base64.b64decode(encoded, validate=True) + elif image.startswith(("https://", "http://")): + content = _download_image(image) + elif "://" not in image: + with Path(image).expanduser().open("rb") as image_file: + content = image_file.read(IMAGE_MAX_BYTES + 1) + else: + return None + if not content or not 5 < len(content) <= IMAGE_MAX_BYTES: + return None + if content.startswith(b"\x89PNG\r\n\x1a\n"): + return content, ".png" + if content.startswith(b"\xff\xd8\xff"): + return content, ".jpg" + except Exception as error: + # 不记录图片地址、Base64 或本地路径,避免泄露二维码来源中的临时凭据。 + logger.warning(f"读取通知原图失败:{type(error).__name__}") + return None + + +@contextmanager +def image_upload_file(image: str) -> Iterator[Optional[Path]]: + """ + 为仅接受文件路径的渠道提供短期原图,发送结束后清理且不删除调用方文件。 + + :param image: HTTP(S)、Base64 或本地 JPG/PNG 图片 + :yields: 位于运行时临时目录的图片副本;无法读取时为 None + """ + loaded = load_image(image) + if loaded is None: + logger.warning("通知原图不可用,仅支持不超过 10 MiB 的 JPG/PNG") + yield None + return + content, suffix = loaded + temp_root = Path(get_runtime_setting("TEMP_PATH")) + temp_root.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(prefix="message-image-", dir=temp_root) as directory: + path = Path(directory) / f"image{suffix}" + path.write_bytes(content) + yield path diff --git a/app/agent/tools/impl/send_local_file.py b/app/agent/tools/impl/send_local_file.py index 3905c578d..54f9f06fd 100644 --- a/app/agent/tools/impl/send_local_file.py +++ b/app/agent/tools/impl/send_local_file.py @@ -9,7 +9,6 @@ from pydantic import BaseModel, Field, model_validator from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag -from app.application.notification import get_notification_configs from app.runtime.log import logger from app.schemas.message import Message from app.schemas.notification import ChannelCapability, ChannelCapabilityManager @@ -122,14 +121,6 @@ class SendLocalFileTool(MoviePilotTool): ): return f"当前渠道 {channel.value} 暂不支持发送本地文件" - if channel == NotificationChannel.Wechat: - configs = await self.run_blocking("config", get_notification_configs) - if not any( - config.name == self._source and (config.config or {}).get("WECHAT_MODE", "app") != "bot" - for config in configs - ): - return "企业微信仅自建应用模式支持发送本地文件,请检查当前通知实例" - resolved_path = Path(file_path).expanduser() if not resolved_path.is_absolute(): resolved_path = resolved_path.resolve() diff --git a/app/application/messaging/attachment.py b/app/application/messaging/attachment.py new file mode 100644 index 000000000..01e47e740 --- /dev/null +++ b/app/application/messaging/attachment.py @@ -0,0 +1,61 @@ +""" +统一通知图片与附件的投递语义,拆分组合消息并显式说明渠道不具备的能力。 +""" + +from pathlib import Path + +from app.schemas.message import Message +from app.schemas.notification import ChannelCapability, ChannelCapabilityManager +from app.schemas.types import NotificationChannel + + +def notification_parts(message: Message, channel: NotificationChannel) -> list[Message]: + """ + 为单个渠道生成互不污染的图片、附件或降级文本。 + + :param message: 插件或宿主的统一消息;原对象及其路由范围保持不变 + :param channel: 当前模块渠道,由宿主查询能力,插件无需判断 + :return: 顺序投递的消息;同时有图片和文件时保留二者且说明文字只发送一次 + """ + if message.image and message.file_path: + parts = [ + message.model_copy(update={"file_path": None, "file_name": None, "voice_path": None}), + message.model_copy(update={ + "image": None, "poster": None, "native_image": False, "voice_path": None, + "title": None, "text": None, "rich_content": None, "rich_message": None, + "link": None, "buttons": None, + }), + ] + else: + parts = [message] + return [_channel_part(part, channel) for part in parts] + + +def _channel_part(message: Message, channel: NotificationChannel) -> Message: + """ + 将不受支持的附件转换为明确提示,不暴露本地路径或伪造下载链接。 + """ + if message.file_path and not ChannelCapabilityManager.supports_capability(channel, ChannelCapability.FILE_SENDING): + name = Path(message.file_name or message.file_path).name + hint = f"[附件未发送:{name};当前渠道不支持本地文件]" + return message.model_copy(update={ + "file_path": None, "file_name": None, "rich_content": None, + "text": "\n".join(part for part in (message.text, hint) if part), + }) + if message.image and message.native_image and not ChannelCapabilityManager.supports_capability( + channel, ChannelCapability.NATIVE_IMAGES, + ): + if message.image.startswith(("http://", "https://")) and ChannelCapabilityManager.supports_capability( + channel, ChannelCapability.IMAGES, + ): + return message.model_copy(update={ + "native_image": False, "link": None, + "title": message.title or (None if message.text else "图片"), + }) + hint = (f"图片:{message.image}" if message.image.startswith(("http://", "https://")) + else "[图片未发送:当前渠道不支持上传原图]") + return message.model_copy(update={ + "image": None, "native_image": False, "rich_content": None, + "text": "\n".join(part for part in (message.text, hint) if part), + }) + return message diff --git a/app/modules/__init__.py b/app/modules/__init__.py index 8c2c4f997..2fe2c7854 100644 --- a/app/modules/__init__.py +++ b/app/modules/__init__.py @@ -4,13 +4,15 @@ import threading from abc import ABCMeta, abstractmethod +from collections.abc import Iterator from pathlib import Path from typing import Any, Callable, Dict, Generic, Mapping, Optional, Protocol, Tuple, Type, TypeVar, Union +from app.application.messaging.attachment import notification_parts from app.runtime.extensions.service import ServiceConfigHelper from app.runtime.log import logger from app.runtime.reload import ConfigReloadMixin -from app.schemas.message import Message +from app.schemas.message import Message, MessageResponse from app.schemas.system import DownloaderConf, MediaServerConf, NotificationConf from app.schemas.types import ( DownloaderType, @@ -318,6 +320,43 @@ class _MessageBase(ServiceBase[TService, NotificationConf]): return {} return {conf.name: conf for conf in configs if conf.type == self._service_name and conf.enabled} + def iter_message_configs(self, message: Message) -> Iterator[tuple[NotificationConf, Message]]: + """ + 先按原通知过滤实例,再为每个实例独立适配图片与附件。 + + :param message: 保留原始接收人、通知范围和内容的统一消息 + :yields: 通过原通知规则的配置与渠道消息;附件拆分不会改写其他实例的输入 + """ + for conf in self.get_configs().values(): + if not self.check_message(message, conf.name): + continue + channel = getattr(self, "_channel", None) + if channel is None: + subtype = getattr(self, "get_subtype", lambda: None)() + channel = subtype if isinstance(subtype, NotificationChannel) else None + parts = notification_parts(message, channel) if channel is not None else [message] + for part in parts: + yield conf, part + + def _send_direct_parts( + self, message: Message, sender: Callable[[Message], Optional[MessageResponse]], + ) -> Optional[MessageResponse]: + """ + 直接发送接口也保留组合附件;后续部分绑定首条成功实例,任一失败不得当作完整成功。 + """ + channel = getattr(self, "_channel", None) or getattr(self, "get_subtype", lambda: None)() + parts = notification_parts(message, channel) if isinstance(channel, NotificationChannel) else [message] + first = None + for part in parts: + if first is not None and first.source: + part = part.model_copy(update={"source": first.source}) + response = sender(part) + if response is None or not response.success: + return None + if first is None: + first = response + return first + def check_message(self, message: Message, source: Optional[str] = None) -> bool: """ 检查消息渠道及消息类型,判断是否处理消息。 diff --git a/app/modules/apppush/__init__.py b/app/modules/apppush/__init__.py index e34bee843..9fa48e135 100644 --- a/app/modules/apppush/__init__.py +++ b/app/modules/apppush/__init__.py @@ -249,9 +249,7 @@ class AppPushModule(_ModuleBase, _MessageBase[object]): """ 仅向路由确定的不可变账号身份投递;缺少绑定绝不退回全设备广播。 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): link = message.link or "/?shotcut=message" # 外部下载或媒体链接留在消息列表中,系统通知点击始终交给本实例。 route = link if link.startswith("/") and not link.startswith("//") and "\\" not in link else "/?shotcut=message" diff --git a/app/modules/dingtalk/__init__.py b/app/modules/dingtalk/__init__.py index 63299a29e..b9430ed51 100644 --- a/app/modules/dingtalk/__init__.py +++ b/app/modules/dingtalk/__init__.py @@ -74,9 +74,7 @@ class DingTalkModule(_MessageChannelModuleBase[DingTalk]): """ 向所有匹配消息范围的钉钉配置发送普通通知。 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): client = self.get_instance(conf.name) if client: texts: Sequence[Optional[str]] = message.channel_text_chunks(NotificationChannel.DingTalk) or [message.text] diff --git a/app/modules/discord/__init__.py b/app/modules/discord/__init__.py index da2e68afc..9ed18f694 100644 --- a/app/modules/discord/__init__.py +++ b/app/modules/discord/__init__.py @@ -363,15 +363,10 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): logger.debug("[Discord] get_configs() 返回空,没有可用的 Discord 配置") return - for conf in configs.values(): + for conf, message in self.iter_message_configs(message): logger.debug( f"[Discord] 检查配置: name={conf.name}, type={conf.type}, enabled={conf.enabled}" ) - if not self.check_message(message, conf.name): - logger.debug( - f"[Discord] check_message 返回 False,跳过配置: {conf.name}" - ) - continue logger.debug(f"[Discord] check_message 通过,准备发送到: {conf.name}") targets = self.get_notification_targets(message) userid = message.userid @@ -388,7 +383,12 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): logger.debug( f"[Discord] 调用 client 发送, userid={userid}, title={message.title[:50] if message.title else None}..." ) - if message.file_path: + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, userid=userid, + original_chat_id=None if message.private_delivery else message.original_chat_id, buttons=message.buttons, + ) + elif message.file_path: result = client.send_file( file_path=message.file_path, file_name=message.file_name, @@ -621,6 +621,12 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): )) def send_direct_message(self, message: Message) -> Optional[MessageResponse]: + """ + 通过统一媒体协议发送完整通知,返回首条消息引用,任一附件失败则返回 None。 + """ + return self._send_direct_parts(message, self._send_direct_message_part) + + def _send_direct_message_part(self, message: Message) -> Optional[MessageResponse]: """ 向匹配的 Discord 通知实例直接发送文件或文本。 @@ -639,13 +645,19 @@ class DiscordModule(_MessageChannelModuleBase[Discord]): return None client: Optional[Discord] = self.get_instance(conf.name) if client: - if message.file_path: + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, userid=userid, + original_chat_id=None if message.private_delivery else message.original_chat_id, buttons=message.buttons, + ) + elif message.file_path: result = client.send_file( file_path=message.file_path, file_name=message.file_name, title=message.title, text=message.text, userid=userid, + original_chat_id=None if message.private_delivery else message.original_chat_id, ) else: result = client.send_msg( diff --git a/app/modules/discord/discord.py b/app/modules/discord/discord.py index 8f55a2257..e73011425 100644 --- a/app/modules/discord/discord.py +++ b/app/modules/discord/discord.py @@ -5,12 +5,14 @@ Discord 机器人连接、频道路由、消息卡片和输入状态生命周期 import asyncio import re import threading +from io import BytesIO from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import discord from discord import app_commands +from app.adapters.system.attachment import load_image from app.application.messaging.ingress import async_forward_message_to_host from app.domain.context import Context, MediaInfo from app.domain.metainfo import MetaInfo @@ -587,6 +589,34 @@ class Discord: logger.error(f"发送 Discord 消息失败:{err}") return False + def send_image(self, image: str, title: Optional[str] = None, text: Optional[str] = None, + userid: Optional[str] = None, original_chat_id: Optional[str] = None, + buttons: Optional[List[List[dict[str, Any]]]] = None) -> Union[bool, Tuple[bool, Optional[Dict[str, str]]]]: + """ + 上传完整原图并保留接收会话;有按钮时先发送一次说明与按钮。 + + :param image: HTTP(S)、Base64 或本地 JPG/PNG + :param title: 图片说明标题 + :param text: 图片说明正文 + :param userid: 接收用户标识 + :param original_chat_id: 优先接收的原会话标识 + :param buttons: 可选的交互按钮,随说明发送一次 + :return: 沿用文件接口的成功标记及消息引用;失败返回 False + """ + loaded = load_image(image) + if loaded is None: + return False + if buttons: + result = self.send_msg(title=title or ("" if text else "图片"), text=text, userid=userid, + original_chat_id=original_chat_id, buttons=buttons) + if not result or (isinstance(result, tuple) and not result[0]): + return False + title, text = None, None + content, suffix = loaded + # 字节由发送协程持有,入口超时也不会提前删除仍在上传的临时文件。 + return self.send_file(f"image{suffix}", title=title, text=text, userid=userid, + original_chat_id=original_chat_id, file_content=content) + def send_file( self, file_path: str, @@ -595,6 +625,7 @@ class Discord: userid: Optional[str] = None, file_name: Optional[str] = None, original_chat_id: Optional[str] = None, + file_content: Optional[bytes] = None, ) -> Union[bool, Tuple[bool, Optional[Dict[str, str]]]]: """ 在专用事件循环中上传本地文件,最多等待 30 秒。 @@ -605,6 +636,7 @@ class Discord: :param userid: 用于上下文频道路由或私聊回退的用户标识 :param file_name: 可选上传文件名,默认使用本地名称 :param original_chat_id: 优先接收文件的频道标识 + :param file_content: 原图适配器提供的字节;非空时由发送协程持有,不读取 file_path :return: 内部发送完成时返回 (成功标记, 消息标识字典或 None);入口校验、超时或调度失败返回 False """ if not self.get_state(): @@ -621,6 +653,7 @@ class Discord: userid=userid, file_name=file_name, original_chat_id=original_chat_id, + file_content=file_content, ), self._loop, ) @@ -1065,9 +1098,10 @@ class Discord: userid: Optional[str], file_name: Optional[str], original_chat_id: Optional[str], + file_content: Optional[bytes] = None, ) -> Tuple[bool, Optional[Dict[str, str]]]: """ - 在线程池检查本地文件后,上传到解析出的接收频道。 + 上传到解析出的接收频道,本地文件先检查,原图字节由当前协程持有到完成。 标题和正文合并为附言,超过 1900 字符时截断并追加省略号。 @@ -1079,7 +1113,7 @@ class Discord: return False, None local_file = Path(file_path) - if not await run_in_threadpool( + if file_content is None and not await run_in_threadpool( _is_regular_file, local_file, ): @@ -1093,7 +1127,8 @@ class Discord: try: discord_file = discord.File( - str(local_file), filename=file_name or local_file.name + BytesIO(file_content) if file_content is not None else str(local_file), + filename=file_name or local_file.name, ) sent_message = await channel.send(content=content, file=discord_file) return ( diff --git a/app/modules/feishu/feishu.py b/app/modules/feishu/feishu.py index 24a1d6204..8a8887ca2 100644 --- a/app/modules/feishu/feishu.py +++ b/app/modules/feishu/feishu.py @@ -15,6 +15,7 @@ from urllib.parse import urlparse from app.adapters.network.feishu import FeishuLongConnection from app.adapters.network.http import RequestUtils from app.adapters.network.ip import IpUtils +from app.adapters.system.attachment import image_upload_file from app.application.messaging.channel.admin import matches_channel_admin from app.application.messaging.ingress import submit_message_to_host from app.application.security.user import get_configured_user_channel_lookup @@ -1635,6 +1636,43 @@ class Feishu: ) return result + def send_image(self, image: str, title: Optional[str] = None, text: Optional[str] = None, + userid: Optional[str] = None, chat_id: Optional[str] = None, + receive_id_type: Optional[str] = None, original_message_id: Optional[str] = None, + buttons: Optional[List[List[dict[str, Any]]]] = None) -> Optional[JsonDict]: + """ + 发送独立图片消息,说明和交互按钮另发卡片,保留原消息回复目标。 + + :param image: HTTP(S)、Base64 或本地 JPG/PNG + :param title: 图片说明标题 + :param text: 图片说明正文 + :param userid: 接收用户标识 + :param chat_id: 接收会话标识 + :param receive_id_type: 沿用宿主解析的 open_id、user_id 或 chat_id + :param original_message_id: 原消息标识,非空时回复该消息 + :param buttons: 可选的交互按钮,随说明发送一次 + :return: 图片消息的发送结果;图片或说明失败时 success 为 False + """ + with image_upload_file(image) as path: + image_key = self._upload_image(path) if path is not None else None + if not image_key: + return {"success": False} + if title or text or buttons: + caption = self.send_notification( + Message(title=title or (None if text else "图片"), text=text, buttons=buttons), userid=userid, chat_id=chat_id, + receive_id_type=receive_id_type, original_message_id=original_message_id, + ) + if not caption or not caption.get("success"): + return {"success": False} + if original_message_id: + result = self._reply_message(original_message_id, "image", {"image_key": image_key}) + else: + result = self._send_with_fallback_broadcast( + "image", {"image_key": image_key}, userid=userid, chat_id=chat_id, + receive_id_type=receive_id_type, + ) + return result or {"success": False} + def send_file( self, file_path: str, diff --git a/app/modules/feishu/module.py b/app/modules/feishu/module.py index e9a4a73e1..8f20e6c46 100644 --- a/app/modules/feishu/module.py +++ b/app/modules/feishu/module.py @@ -164,27 +164,14 @@ class FeishuModule(_MessageChannelModuleBase[Feishu]): :param message: 通知内容和目标;同时有封面与文件时分别发送卡片和附件 :param kwargs: 兼容模块分发的附加参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): userid, chat_id, receive_id_type = self._resolve_message_target(message) client: Optional[Feishu] = self.get_instance(conf.name) if client: - if message.image and message.file_path: - # 普通文件无法嵌入卡片,先发送图文卡片,再单独发送附件,避免图片被 file_path 分支吞掉。 - client.send_notification( - message=message.model_copy(update={"file_path": None, "file_name": None}), - userid=userid, - chat_id=chat_id, - receive_id_type=receive_id_type, - original_message_id=str(message.original_message_id) if message.original_message_id else None, - ) - client.send_file( - file_path=message.file_path, - userid=userid, - chat_id=chat_id, - file_name=message.file_name, - receive_id_type=receive_id_type, + if message.native_image and message.image: + client.send_image( + image=message.image, title=message.title, text=message.text, userid=userid, + chat_id=chat_id, receive_id_type=receive_id_type, buttons=message.buttons, original_message_id=str(message.original_message_id) if message.original_message_id else None, ) elif message.file_path: @@ -301,9 +288,13 @@ class FeishuModule(_MessageChannelModuleBase[Feishu]): def send_direct_message(self, message: Message) -> Optional[MessageResponse]: """ - 发送消息并返回首个成功实例的消息引用。 + 通过统一媒体协议发送完整通知,返回首条消息引用,任一附件失败则返回 None。 + """ + return self._send_direct_parts(message, self._send_direct_message_part) - 封面与附件组合只以卡片发送结果决定成功,附件发送结果不影响返回值。 + def _send_direct_message_part(self, message: Message) -> Optional[MessageResponse]: + """ + 发送消息并返回首个成功实例的消息引用。 :param message: 待发送通知;plain 模式通过纯文本保留敏感字符,封面与文件分别发送 :return: 成功主消息的引用与可选流式状态;没有成功实例时返回 None @@ -315,23 +306,12 @@ class FeishuModule(_MessageChannelModuleBase[Feishu]): client: Optional[Feishu] = self.get_instance(conf.name) if not client: continue - if message.image and message.file_path: - result = client.send_notification( - message=message.model_copy(update={"file_path": None, "file_name": None}), - userid=userid, - chat_id=chat_id, - receive_id_type=receive_id_type, + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, userid=userid, + chat_id=chat_id, receive_id_type=receive_id_type, buttons=message.buttons, original_message_id=str(message.original_message_id) if message.original_message_id else None, ) - if result and result.get("success"): - client.send_file( - file_path=message.file_path, - userid=userid, - chat_id=chat_id, - file_name=message.file_name, - receive_id_type=receive_id_type, - original_message_id=str(message.original_message_id) if message.original_message_id else None, - ) elif message.file_path: result = client.send_file( file_path=message.file_path, diff --git a/app/modules/qqbot/module.py b/app/modules/qqbot/module.py index da169cd9e..43f08eb57 100644 --- a/app/modules/qqbot/module.py +++ b/app/modules/qqbot/module.py @@ -397,9 +397,7 @@ class QQBotModule(_MessageChannelModuleBase[QQBot]): """ 按通知路由发送 QQ 消息,并保留原正文作为权限不足时的回退。 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): targets = self.get_notification_targets(message) userid = message.userid if not userid and targets: diff --git a/app/modules/slack/__init__.py b/app/modules/slack/__init__.py index 6ff01c273..dfb2c5a73 100644 --- a/app/modules/slack/__init__.py +++ b/app/modules/slack/__init__.py @@ -404,9 +404,7 @@ class SlackModule(_MessageChannelModuleBase[Slack]): :param message: 提供通知范围、接收人、标题和原消息标识等信息的消息 :param kwargs: 兼容统一接口的扩展参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): targets = self.get_notification_targets(message) userid = message.userid if not userid and targets is not None: @@ -417,13 +415,19 @@ class SlackModule(_MessageChannelModuleBase[Slack]): client = self.get_instance(conf.name) if client: userid_text = str(userid) if userid is not None else None - if message.file_path: + if message.native_image and message.image: + client.send_image( + image=message.image, title=message.title, text=message.text, + userid=userid_text if message.private_delivery else message.original_chat_id or userid_text, + buttons=message.buttons, + ) + elif message.file_path: client.send_file( file_path=message.file_path, file_name=message.file_name, title=message.title, text=message.text, - userid=userid_text, + userid=userid_text if message.private_delivery else message.original_chat_id or userid_text, ) else: client.send_msg( @@ -672,6 +676,12 @@ class SlackModule(_MessageChannelModuleBase[Slack]): ) def send_direct_message(self, message: Message) -> Optional[MessageResponse]: + """ + 通过统一媒体协议发送完整通知,返回首条消息引用,任一附件失败则返回 None。 + """ + return self._send_direct_parts(message, self._send_direct_message_part) + + def _send_direct_message_part(self, message: Message) -> Optional[MessageResponse]: """ 向首个成功匹配的 Slack 实例直接发送文件或文本。 @@ -693,13 +703,19 @@ class SlackModule(_MessageChannelModuleBase[Slack]): client = self.get_instance(conf.name) if client: userid_text = str(userid) if userid is not None else None - if message.file_path: + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, + userid=userid_text if message.private_delivery else message.original_chat_id or userid_text, + buttons=message.buttons, + ) + elif message.file_path: result = client.send_file( file_path=message.file_path, file_name=message.file_name, title=message.title, text=message.text, - userid=userid_text, + userid=userid_text if message.private_delivery else message.original_chat_id or userid_text, ) else: result = client.send_msg( @@ -709,28 +725,25 @@ class SlackModule(_MessageChannelModuleBase[Slack]): formatted_text=message.channel_text(NotificationChannel.Slack), ) if result and result[0]: - # Slack 使用时间戳作为 message_id,chat_id 是频道ID - response_data = result[1] - message_id = None - channel_id = None - if hasattr(response_data, "get"): - message_id = response_data.get("ts") - channel_id = response_data.get("channel") - if not message_id and hasattr(response_data, "data"): - files = (response_data.data or {}).get("files") or [] - if files: - message_id = files[0].get("id") - shares = ( - files[0].get("shares", {}) - .get("private", {}) - ) - if shares: - channel_id = next(iter(shares.keys()), None) - return MessageResponse( - message_id=message_id, - chat_id=channel_id, - channel=NotificationChannel.Slack, - source=conf.name, - success=True, - ) + return self._direct_message_response(result[1], conf.name) return None + + @staticmethod + def _direct_message_response(response_data: Any, source: Optional[str]) -> MessageResponse: + """ + 从普通消息或文件上传响应读取引用,避免发送流程嵌套平台响应结构。 + + :param response_data: Slack 消息或文件上传结果 + :param source: 成功发送的实例名称 + :return: 保留消息或文件 ID、分享频道及实例来源的成功回执 + """ + message_id = response_data.get("ts") if hasattr(response_data, "get") else None + channel_id = response_data.get("channel") if hasattr(response_data, "get") else None + if not message_id and hasattr(response_data, "data"): + files = (response_data.data or {}).get("files") or [] + if files: + message_id = files[0].get("id") + shares = files[0].get("shares", {}).get("private", {}) + channel_id = next(iter(shares), channel_id) + return MessageResponse(message_id=message_id, chat_id=channel_id, channel=NotificationChannel.Slack, + source=source, success=True) diff --git a/app/modules/slack/slack.py b/app/modules/slack/slack.py index 88199b197..e0aad582a 100644 --- a/app/modules/slack/slack.py +++ b/app/modules/slack/slack.py @@ -13,6 +13,7 @@ from slack_bolt.adapter.socket_mode import SocketModeHandler from slack_sdk import WebClient from app.adapters.network.http import RequestUtils +from app.adapters.system.attachment import image_upload_file from app.application.messaging.ingress import forward_message_to_host from app.domain.context import Context, MediaInfo from app.domain.metainfo import MetaInfo @@ -490,6 +491,29 @@ class Slack: for index in range(0, len(content), capacity)] return batches + def send_image(self, image: str, title: Optional[str] = None, text: Optional[str] = None, + userid: Optional[str] = None, buttons: Optional[List[List[dict[str, Any]]]] = None) -> Tuple[bool, Any]: + """ + 上传完整原图,保留说明及可选的交互按钮,不依赖外部图片地址可公开访问。 + + :param image: HTTP(S)、Base64 或本地 JPG/PNG + :param title: 图片说明标题 + :param text: 图片说明正文 + :param userid: 接收用户或频道,沿用宿主解析的目标 + :param buttons: 可选的交互按钮,随说明发送一次 + :return: 沿用文件上传的成功标记和响应;原图或说明失败时返回 False 及原因 + """ + with image_upload_file(image) as path: + if path is None: + return False, "图片不可用" + if buttons: + sent, _ = self.send_msg(title=title or (None if text else "图片"), text=text, + userid=userid, buttons=buttons) + if not sent: + return False, "图片说明发送失败" + title, text = None, None + return self.send_file(str(path), title=title, text=text, userid=userid) + def send_file( self, file_path: str, diff --git a/app/modules/synologychat/__init__.py b/app/modules/synologychat/__init__.py index 642644569..c8875956e 100644 --- a/app/modules/synologychat/__init__.py +++ b/app/modules/synologychat/__init__.py @@ -382,9 +382,7 @@ class SynologyChatModule(_MessageChannelModuleBase[SynologyChat]): :param message: 提供渠道范围、接收人和标题等信息的通知消息 :param kwargs: 兼容统一通知入口的扩展参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): client = self.get_instance(conf.name) if client: texts: Sequence[Optional[str]] = message.channel_text_chunks(NotificationChannel.SynologyChat) or [message.text] diff --git a/app/modules/telegram/module.py b/app/modules/telegram/module.py index 5b0173d52..221a80e87 100644 --- a/app/modules/telegram/module.py +++ b/app/modules/telegram/module.py @@ -473,9 +473,7 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): :raises RuntimeError: 一个或多个匹配实例缺失客户端或未确认发送成功 """ failures = [] - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): targets = self.get_notification_targets(message) userid = message.userid if not userid and targets is not None: @@ -486,7 +484,15 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): client = self.get_instance(conf.name) result = None if client: - if message.file_path: + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, + userid=str(userid) if userid is not None else None, + original_chat_id=message.original_chat_id, parse_mode=message.parse_mode, + buttons=message.buttons, private_delivery=message.private_delivery, + ) + elif message.file_path: + file_options: dict[str, Any] = {"private_delivery": True} if message.private_delivery else {} result = client.send_file( file_path=message.file_path, file_name=message.file_name, @@ -495,6 +501,7 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): userid=str(userid) if userid is not None else None, original_chat_id=message.original_chat_id, parse_mode=message.parse_mode, + **file_options, ) elif message.voice_path: result = client.send_voice( @@ -730,6 +737,12 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): return client.stop_typing(chat_id=chat_id, userid=userid) def send_direct_message(self, message: Message) -> Optional[MessageResponse]: + """ + 通过统一媒体协议发送完整通知,返回首条消息引用,任一附件失败则返回 None。 + """ + return self._send_direct_parts(message, self._send_direct_message_part) + + def _send_direct_message_part(self, message: Message) -> Optional[MessageResponse]: """ 发送新消息并返回首个成功实例的消息引用。 @@ -748,7 +761,22 @@ class TelegramModule(_MessageChannelModuleBase[Telegram]): return None client = self.get_instance(conf.name) if client: - if message.voice_path: + if message.native_image and message.image: + result = client.send_image( + image=message.image, title=message.title, text=message.text, + userid=str(userid) if userid is not None else None, + original_chat_id=message.original_chat_id, parse_mode=message.parse_mode, + buttons=message.buttons, private_delivery=message.private_delivery, + ) + elif message.file_path: + result = client.send_file( + file_path=message.file_path, file_name=message.file_name, + title=message.title, text=message.text, + userid=str(userid) if userid is not None else None, + original_chat_id=message.original_chat_id, parse_mode=message.parse_mode, + private_delivery=message.private_delivery, + ) + elif message.voice_path: result = client.send_voice( voice_path=message.voice_path, userid=str(userid) if userid is not None else None, diff --git a/app/modules/telegram/telegram.py b/app/modules/telegram/telegram.py index 14ec6128d..27a413d0a 100644 --- a/app/modules/telegram/telegram.py +++ b/app/modules/telegram/telegram.py @@ -23,6 +23,7 @@ except ImportError: from telegramify_markdown.type import ContentTypes, File, Photo, Text from app.adapters.network.http import RequestUtils +from app.adapters.system.attachment import load_image from app.application.image import ImageHelper from app.application.messaging.ingress import forward_message_to_host from app.domain.context import Context, MediaInfo @@ -1265,6 +1266,44 @@ class Telegram: except Exception as cleanup_err: logger.debug(f"清理语音临时文件失败: {cleanup_err}") + def send_image(self, image: str, title: Optional[str] = None, text: Optional[str] = None, + userid: Optional[str] = None, original_chat_id: Optional[str] = None, + parse_mode: Optional[str] = None, buttons: Optional[List[List[dict[str, Any]]]] = None, + private_delivery: bool = False) -> Optional[JsonDict]: + """ + 上传统一来源的完整原图,复用长正文拆分并保留会话、话题、按钮和私聊约束。 + + :param image: HTTP(S)、Base64 或本地 JPG/PNG + :param title: 图片说明标题 + :param text: 图片说明正文 + :param userid: 接收用户标识 + :param original_chat_id: 优先接收的原会话标识 + :param parse_mode: 说明文字格式,沿用普通通知约定 + :param buttons: 图片下方的统一交互按钮 + :param private_delivery: 有用户标识时是否必须发送私聊 + :return: 图片发送结果;读取失败时 success 为 False + """ + if not self._telegram_token or not self._telegram_chat_id: + return None + chat_id = self._determine_target_chat_id(userid, original_chat_id, private_delivery=private_delivery) + if self._is_chat_rate_limited(chat_id, operation="发送"): + return {"success": False} + loaded = load_image(image) + if loaded is None: + return {"success": False} + mode = self._normalize_parse_mode(parse_mode) + caption = "\n".join(part for part in (self._format_title(title, mode), text) if part) + try: + sent = self.__send_request( + userid=chat_id, image=loaded[0], caption=caption, parse_mode=mode, + reply_markup=self._create_inline_keyboard(buttons) if buttons else None, + ) + self._remember_sent_message(sent, chat_id) + return self._sent_result(sent, chat_id) + except Exception as error: + logger.error(f"Telegram 原图发送失败:{type(error).__name__}") + return {"success": False} + def send_file( self, file_path: str, @@ -1275,6 +1314,8 @@ class Telegram: original_chat_id: Optional[str] = None, stop_typing: bool = False, parse_mode: Optional[str] = None, + buttons: Optional[List[List[dict[str, Any]]]] = None, + private_delivery: bool = False, ) -> Optional[JsonDict]: """ 根据后缀发送本地图片或普通附件,保留源文件。 @@ -1287,12 +1328,14 @@ class Telegram: :param original_chat_id: 显式原会话标识,优先于普通用户映射 :param stop_typing: 是否在操作收尾时请求停止输入状态,默认 False :param parse_mode: 消息格式,默认 MarkdownV2;支持 HTML 和 plain 纯文本 + :param buttons: 图片或附件下方的统一按钮行 + :param private_delivery: 有用户标识时是否绕过群聊映射直接投递私聊 :return: 含 success、message_id 和 chat_id 的结果;失败为 success 为 False 的字典,未配置或无输入路径返回 None """ if not self._bot or not file_path: return None - chat_id = self._determine_target_chat_id(userid, original_chat_id) + chat_id = self._determine_target_chat_id(userid, original_chat_id, private_delivery=private_delivery) parse_mode = self._normalize_parse_mode(parse_mode) local_file = Path(file_path) if not local_file.exists() or not local_file.is_file(): @@ -1314,13 +1357,16 @@ class Telegram: caption = text or "" with local_file.open("rb") as fp: + options: dict[str, Any] = self._topic_kwargs(chat_id) + if buttons: + options["reply_markup"] = self._create_inline_keyboard(buttons) if is_image: sent = self._api.send_photo( chat_id=chat_id, photo=fp, caption=self._prepare_text(caption, parse_mode), parse_mode=parse_mode if caption else None, - **self._topic_kwargs(chat_id), + **options, ) else: sent = self._api.send_document( @@ -1328,7 +1374,7 @@ class Telegram: document=(send_name, fp), caption=self._prepare_text(caption, parse_mode), parse_mode=parse_mode if caption else None, - **self._topic_kwargs(chat_id), + **options, ) self._stop_typing_if_needed(chat_id, stop_typing) return self._sent_result(sent, chat_id) @@ -2077,7 +2123,7 @@ class Telegram: def __send_request( self, userid: Optional[str] = None, - image: Optional[str] = "", + image: Optional[Union[str, bytes]] = "", caption: str = "", reply_markup: Optional[JsonDict] = None, disable_web_page_preview: Optional[bool] = None, @@ -2137,12 +2183,14 @@ class Telegram: return None @staticmethod - def __process_image(image_url: Optional[str]) -> Optional[bytes]: + def __process_image(image_url: Optional[Union[str, bytes]]) -> Optional[bytes]: """ 处理图片URL,获取图片内容。 """ if not image_url: return None + if isinstance(image_url, bytes): + return image_url image = ImageHelper().fetch_image(image_url) if not image: logger.warn(f"图片获取失败: {image_url},仅发送文本消息") diff --git a/app/modules/vocechat/__init__.py b/app/modules/vocechat/__init__.py index 1514c984c..b0b9f7b54 100644 --- a/app/modules/vocechat/__init__.py +++ b/app/modules/vocechat/__init__.py @@ -329,9 +329,7 @@ class VoceChatModule(_MessageChannelModuleBase[VoceChat]): :param message: 提供渠道范围、接收人和标题等信息的通知消息 :param kwargs: 兼容统一通知入口的扩展参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): userid = self.get_notification_userid(message, "vocechat_userid") client = self.get_instance(conf.name) if client: diff --git a/app/modules/webpush/__init__.py b/app/modules/webpush/__init__.py index 913444233..6302f8c86 100644 --- a/app/modules/webpush/__init__.py +++ b/app/modules/webpush/__init__.py @@ -85,9 +85,7 @@ class WebPushModule(_ModuleBase, _MessageBase[object]): :param message: 待发送的标题、正文、目标用户与跳转链接 :param kwargs: 为模块分发接口保留的扩展参数,本实现不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): webpush_users = (conf.config or {}).get("WEBPUSH_USERNAME") or "" if webpush_users: # 设定了接收用户时,非该用户的消息不接收 diff --git a/app/modules/wechat/__init__.py b/app/modules/wechat/__init__.py index 31f3c2005..4162cd6fe 100644 --- a/app/modules/wechat/__init__.py +++ b/app/modules/wechat/__init__.py @@ -337,24 +337,19 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): """ 向符合通知规则的实例发送文本、图文、原生图片、文件或语音。 - :param message: 通知内容及接收对象;文件优先于图片和语音,语音发送失败时回退到文本或图文 + :param message: 通知内容及接收对象;图片与文件分别保留,语音发送失败时回退到文本或图文 :param kwargs: 兼容模块分发的附加参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): userid = self.get_notification_userid(message, "wechat_userid") client = self.get_instance(conf.name) if client: text = message.channel_text(NotificationChannel.Wechat, conf.config) or message.text if message.file_path: - if isinstance(client, WeChat): - client.send_file(file_path=message.file_path, file_name=message.file_name, - title=message.title, text=text, userid=userid) - else: - logger.warning("企业微信机器人模式暂不支持发送本地文件") + client.send_file(file_path=message.file_path, file_name=message.file_name, + title=message.title, text=text, userid=userid) continue - if message.native_image and message.image and isinstance(client, WeChat): + if message.native_image and message.image: client.send_msg(title=message.title, text=text, image=message.image, userid=userid, link=message.link, native_image=True) continue diff --git a/app/modules/wechat/wechat.py b/app/modules/wechat/wechat.py index c105d4f0e..1f7c1d4e8 100644 --- a/app/modules/wechat/wechat.py +++ b/app/modules/wechat/wechat.py @@ -324,7 +324,7 @@ class WeChat: """ 读取原生图片并限制下载量,不在磁盘或图片缓存中保存二维码。 - :param image: HTTP(S) 图片地址或 JPG/PNG 的 Base64 数据地址 + :param image: HTTP(S) 图片地址、JPG/PNG 的 Base64 数据地址或本地图片路径 :return: 大于 5 字节且不超过 10 MiB 的 JPG/PNG 内容;来源、格式或大小无效返回 None """ content: Optional[bytes] @@ -340,8 +340,11 @@ class WeChat: return None elif image.startswith(("https://", "http://")): content = WeChat._download_native_image(image) + elif "://" not in image: + with Path(image).expanduser().open("rb") as image_file: + content = image_file.read(_IMAGE_MAX_BYTES + 1) else: - logger.error("企业微信原生图片仅支持 HTTP(S) 或 Base64 数据地址") + logger.error("企业微信原生图片仅支持 HTTP(S)、Base64 或本地图片路径") return None if not content or not 5 < len(content) <= _IMAGE_MAX_BYTES or WeChat._guess_mime_type(content, "") not in { diff --git a/app/modules/wechat/wechatbot.py b/app/modules/wechat/wechatbot.py index 93624ab39..8ab1512bf 100644 --- a/app/modules/wechat/wechatbot.py +++ b/app/modules/wechat/wechatbot.py @@ -10,12 +10,14 @@ import re import threading import time import uuid +from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple import websocket from Crypto.Cipher import AES from app.adapters.network.http import RequestUtils +from app.adapters.system.attachment import load_image from app.application.messaging.channel.admin import matches_channel_admin from app.application.messaging.image import build_wechat_image_url from app.application.messaging.ingress import submit_message_to_host @@ -388,13 +390,14 @@ class WeChatBot: raise RuntimeError("企业微信智能机器人未连接") self._ws_app.send(json.dumps(payload, ensure_ascii=False)) - def _send_with_ack(self, payload: Dict[str, Any]) -> bool: + def _send_with_ack(self, payload: Dict[str, Any], *, response: Optional[Dict[str, Any]] = None) -> bool: """ 等待认证后串行写入报文,并等待对应服务器确认。 认证和确认各最多等待 10 秒;等待记录在结束时清理,底层发送异常向上传播。 :param payload: 必须在 headers.req_id 中包含请求标识的协议报文 + :param response: 可选的确认结果容器,仅成功时填入,供临时素材上传读取服务端标识 :return: 收到错误码为 0 的确认时返回 True;缺少标识、认证或确认超时及服务端错误返回 False """ req_id = (payload.get("headers") or {}).get("req_id") @@ -423,6 +426,8 @@ class WeChatBot: f"企业微信智能机器人消息发送失败:{ack.get('errmsg')} ({ack.get('errcode')})" ) return False + if response is not None: + response.update(ack) return True finally: with self._acks_lock: @@ -795,7 +800,8 @@ class WeChatBot: return send_success def send_msg(self, title: Optional[str], text: Optional[str] = None, image: Optional[str] = None, - userid: Optional[str] = None, link: Optional[str] = None) -> Optional[bool]: + userid: Optional[str] = None, link: Optional[str] = None, *, + native_image: bool = False) -> Optional[bool]: """ 将通知组合成 Markdown 并发送给目标会话。 @@ -804,11 +810,111 @@ class WeChatBot: :param image: 可选封面地址 :param userid: 接收用户或 group: 群标识;为空时优先使用默认目标,否则发送给所有已互动用户 :param link: 可选跳转链接 + :param native_image: 上传 image 并发送独立原图,支持 URL、Base64 和本地 JPG/PNG,忽略详情链接 :return: 至少一个目标的全部分块发送成功时返回 True;内容为空、无目标或全部目标失败返回 False """ + if native_image and image: + loaded = load_image(image) + if loaded is None: + logger.warning("企业微信机器人原图不可用") + return False + image_bytes, suffix = loaded + return self._send_media(image_bytes, "image", f"image{suffix}", title, text, userid) content = self._build_markdown(title=title, text=text, image=image, link=link) return self._send_markdown(content=content, userid=userid) + def _media_command(self, command: str, body: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """ + 发送素材协议命令并读取成功回执的业务字段,不新增线程或绕过认证。 + """ + response: Dict[str, Any] = {} + if not self._send_with_ack({ + "cmd": command, "headers": {"req_id": self._build_req_id(command)}, "body": body, + }, response=response): + return None + value = response.get("body") + return value if isinstance(value, dict) else {} + + def _upload_media(self, content: bytes, media_type: str, filename: str) -> Optional[str]: + """ + 按官方长连接协议初始化、逐片确认并完成素材上传。 + + 每片最多 512 KiB,从 1 编号;失败片最多重试两次,未确认前不发送下一片。 + + :param content: 已校验大小的完整素材 + :param media_type: image 或 file + :param filename: 接收端文件名 + :return: 完成上传的 media_id;任一步失败或缺少必要回执字段返回 None + """ + chunk_bytes = 512 * 1024 + total_chunks = (len(content) + chunk_bytes - 1) // chunk_bytes + initialized = self._media_command("aibot_upload_media_init", { + "type": media_type, "filename": filename, "total_size": len(content), + "total_chunks": total_chunks, "md5": hashlib.md5(content).hexdigest(), + }) + upload_id = (initialized or {}).get("upload_id") + if not isinstance(upload_id, str) or not upload_id: + return None + for index in range(total_chunks): + chunk = content[index * chunk_bytes:(index + 1) * chunk_bytes] + body = {"upload_id": upload_id, "chunk_index": index + 1, + "base64_data": base64.b64encode(chunk).decode()} + if not any(self._media_command("aibot_upload_media_chunk", body) is not None for _ in range(3)): + return None + completed = self._media_command("aibot_upload_media_finish", {"upload_id": upload_id}) + media_id = (completed or {}).get("media_id") + return media_id if isinstance(media_id, str) and media_id else None + + def _send_media(self, content: bytes, media_type: str, filename: str, title: Optional[str], + text: Optional[str], userid: Optional[str]) -> bool: + """ + 一次上传素材后按现有单聊、群聊目标发送,保留附带说明且不回退裁切图文。 + """ + targets = self._resolve_targets(userid) + if not targets: + return False + media_id = self._upload_media(content, media_type, filename) + if not media_id: + return False + caption = self._build_markdown(title=title, text=text) + success = False + for target, chat_type in targets: + qualified = f"{'group' if chat_type == 2 else 'user'}:{target}" + if caption and not self._send_markdown(caption, qualified): + continue + sent = self._send_with_ack({ + "cmd": "aibot_send_msg", "headers": {"req_id": self._build_req_id("aibot_send_msg")}, + "body": {"chatid": target, "chat_type": chat_type, "msgtype": media_type, + media_type: {"media_id": media_id}}, + }) + success = success or sent + return success + + def send_file(self, file_path: str, file_name: Optional[str] = None, title: Optional[str] = None, + text: Optional[str] = None, userid: Optional[str] = None) -> bool: + """ + 通过统一附件参数发送本地文件,限制为大于 5 字节且不超过 20 MiB,保留源文件。 + + :param file_path: 插件提供的本地路径 + :param file_name: 可选展示名,默认使用源文件名 + :param title: 附件说明标题 + :param text: 附件说明正文 + :param userid: 沿用既有 user:、group: 或默认目标 + :return: 至少一个目标发送成功时返回 True + """ + try: + path = Path(file_path).expanduser() + limit = 20 * 1024 * 1024 + with path.open("rb") as file: + content = file.read(limit + 1) + if not 5 < len(content) <= limit: + logger.warning("企业微信机器人文件须大于 5 字节且不超过 20 MiB") + return False + return self._send_media(content, "file", Path(file_name or path.name).name, title, text, userid) + except Exception as error: + logger.error(f"企业微信机器人文件发送失败:{type(error).__name__}") + return False + def send_medias_msg(self, medias: List[MediaInfo], userid: Optional[str] = None) -> Optional[bool]: """ 将媒体候选顺序、评分和详情地址组合成 Markdown 列表。 diff --git a/app/modules/wechatclawbot/__init__.py b/app/modules/wechatclawbot/__init__.py index d77832ee1..fd1341647 100644 --- a/app/modules/wechatclawbot/__init__.py +++ b/app/modules/wechatclawbot/__init__.py @@ -426,9 +426,7 @@ class WechatClawBotModule(_MessageChannelModuleBase[WechatClawBot]): :param message: 通知内容与接收目标;普通文件优先,其次把语音作为文件发送 :param kwargs: 兼容模块分发的附加参数,当前不使用 """ - for conf in self.get_configs().values(): - if not self.check_message(message, conf.name): - continue + for conf, message in self.iter_message_configs(message): userid = self.get_notification_userid( message, "wechatclawbot_userid" ) @@ -457,6 +455,7 @@ class WechatClawBotModule(_MessageChannelModuleBase[WechatClawBot]): image=message.image, userid=userid, link=message.link, + native_image=message.native_image, ) def download_wechat_image_to_data_url( diff --git a/app/modules/wechatclawbot/wechatclawbot.py b/app/modules/wechatclawbot/wechatclawbot.py index 37263170d..a9e0d0e04 100644 --- a/app/modules/wechatclawbot/wechatclawbot.py +++ b/app/modules/wechatclawbot/wechatclawbot.py @@ -21,6 +21,7 @@ from Crypto.Cipher import AES from Crypto.Util.Padding import pad from app.adapters.network.http import RequestUtils +from app.adapters.system.attachment import load_image from app.application.messaging.ingress import forward_message_to_host from app.domain.context import Context, MediaInfo from app.domain.metainfo import MetaInfo @@ -2458,17 +2459,19 @@ class WechatClawBot: image: Optional[str] = None, userid: Optional[str] = None, link: Optional[str] = None, + native_image: bool = False, **kwargs: object, ) -> Optional[bool]: """ - 优先发送组合文字,只有无文字或仅有标题(无正文、链接)时才尝试发送图片。 + 默认沿用通知文字优先规则,显式原图消息保留图片及附带说明。 各目标独立发送,已发出的分块不会撤回。当前无文字且无可用图片时, 只要存在目标也会返回 True,此结果不表示实际发出消息。 :param title: 可选标题 :param text: 可选正文 - :param image: 可选远程图片或图片数据地址;有正文或链接时忽略;仅有标题时与标题一同发送 + :param image: 可选图片来源;显式原图时支持 URL、Base64 和本地 JPG/PNG + :param native_image: 是否完整发送原图及说明,忽略默认详情链接 :param userid: 显式接收用户;为空时使用默认目标,再回退到近期活跃或全部已知用户 :param link: 追加为详情文字的链接 :param kwargs: 兼容发送接口的附加参数,当前忽略 @@ -2478,20 +2481,23 @@ class WechatClawBot: if not targets: logger.warning("未找到可发送的微信 ClawBot 目标") return False - content = self._compose_text(title=title, text=text, link=link) + content = self._compose_text(title=title, text=text, link=None if native_image else link) # 当前 iLink 发送实现会把图文拆成两条消息发送。 # 为避免用户看到“同一条通知被拆成文本 + 图片”两次触达,这里约定: # 只要通知里已有正文或链接,就优先只发文本;纯图片通知才发送图片。 # 仅有标题(如 send_message 为纯图片通知补的“图片”占位标题)视为纯图片, # 图片带标题一并发送;图片加载失败时退回只发标题文字。 title_only = not text and not link - image_bytes = ( - self._load_remote_image(image) - if image and (not content or title_only) - else None - ) - if image and (not content or title_only) and not image_bytes: + image_bytes = None + if image and native_image: + loaded = load_image(image) + image_bytes = loaded[0] if loaded else None + elif image and (not content or title_only): + image_bytes = self._load_remote_image(image) + if image and (native_image or not content or title_only) and not image_bytes: logger.warning("微信 ClawBot 图片加载失败,已跳过图片") + if native_image: + return False ok = False for target in targets: context_token = self._get_context_token(target) @@ -2550,8 +2556,8 @@ class WechatClawBot: :param file_path: 本地普通文件路径;完整读入内存后发送,保留源文件 :param file_name: 普通附件显示名称;为空时使用路径文件名 - :param title: 兼容发送接口的标题,当前不发送 - :param text: 兼容发送接口的说明,当前不发送 + :param title: 可选的附件说明标题 + :param text: 可选的附件说明正文,和标题一同保留 :param userid: 显式接收用户;为空时使用默认目标,再回退到近期活跃或全部已知用户 :param kwargs: 兼容发送接口的附加参数,当前忽略 :return: 至少一个目标的全部发送步骤成功时返回 True;无目标或全部发送失败返回 False @@ -2569,8 +2575,11 @@ class WechatClawBot: ok = False for target in targets: context_token = self._get_context_token(target) - # send_file 的主语义是发送附件本体,附加文案可以丢弃,避免出现 - # “先发一段说明,再发一个文件”的重复触达体验。 + caption = self._compose_text(title=title or "", text=text) + if caption and not all(self._build_client().send_text( + to_user=target, text=chunk, context_token=context_token, + ) for chunk in self._split_content(caption)): + continue if mime_type.startswith("image/"): sent = self._build_client().send_image_png( to_user=target, diff --git a/app/schemas/message.py b/app/schemas/message.py index 4eb164987..507b2124d 100644 --- a/app/schemas/message.py +++ b/app/schemas/message.py @@ -275,10 +275,10 @@ class Message(BaseModel): title: Optional[str] = Field(default=None, description="标题") text: Optional[str] = Field(default=None, description="文本内容") image: Optional[str] = Field(default=None, description="图片") - native_image: bool = Field(default=False, description="是否发送原生图片;企业微信自建应用支持,默认沿用图文消息") + native_image: bool = Field(default=False, description="将 image 作为完整原图发送;由宿主适配渠道,不支持上传时明确降级,默认保留封面语义") poster: Optional[str] = Field(default=None, description="独立媒体海报,不使用背景图回退") voice_path: Optional[str] = Field(default=None, description="语音文件路径") - file_path: Optional[str] = Field(default=None, description="本地文件路径") + file_path: Optional[str] = Field(default=None, description="本地附件路径;宿主按渠道上传,不支持时明确提示,发送后保留源文件") file_name: Optional[str] = Field(default=None, description="发送时展示的文件名") voice_caption: Optional[str] = Field(default=None, description="语音消息附带说明文字") link: Optional[str] = Field(default=None, description="链接") diff --git a/app/schemas/notification.py b/app/schemas/notification.py index e43d8b02c..42df52ae5 100644 --- a/app/schemas/notification.py +++ b/app/schemas/notification.py @@ -60,6 +60,8 @@ class ChannelCapability(Enum): MARKDOWN = "markdown" # 支持图片 IMAGES = "images" + # 支持将完整原图上传为图片消息,独立于图文封面能力。 + NATIVE_IMAGES = "native_images" # 支持链接 LINKS = "links" # 支持原生语音输出 @@ -134,6 +136,7 @@ class ChannelCapabilityManager: ChannelCapability.MARKDOWN, ChannelCapability.RICH_TEXT, ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.AUDIO_OUTPUT, ChannelCapability.FILE_SENDING, @@ -153,6 +156,7 @@ class ChannelCapabilityManager: notification_mode_value="bot", capabilities={ ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.AUDIO_OUTPUT, ChannelCapability.MENU_COMMANDS, @@ -170,6 +174,7 @@ class ChannelCapabilityManager: ChannelCapability.MARKDOWN, ChannelCapability.RICH_TEXT, ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.AUDIO_OUTPUT, ChannelCapability.FILE_SENDING, @@ -186,6 +191,7 @@ class ChannelCapabilityManager: capabilities={ ChannelCapability.MARKDOWN, ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.FILE_SENDING, }, @@ -203,6 +209,7 @@ class ChannelCapabilityManager: ChannelCapability.MARKDOWN, ChannelCapability.RICH_TEXT, ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.MENU_COMMANDS, ChannelCapability.FILE_SENDING, @@ -227,6 +234,7 @@ class ChannelCapabilityManager: ChannelCapability.MARKDOWN, ChannelCapability.RICH_TEXT, ChannelCapability.IMAGES, + ChannelCapability.NATIVE_IMAGES, ChannelCapability.LINKS, ChannelCapability.FILE_SENDING, ChannelCapability.PROCESSING_STATUS, diff --git a/app/sdk/plugin/base.py b/app/sdk/plugin/base.py index 791e1ce14..db38a184d 100644 --- a/app/sdk/plugin/base.py +++ b/app/sdk/plugin/base.py @@ -425,21 +425,25 @@ class _PluginBase(metaclass=ABCMeta): def post_message(self, channel: Optional[NotificationChannel] = None, mtype: Optional[MessageType] = None, title: Optional[str] = None, - text: Optional[str] = None, image: Optional[str] = None, link: Optional[str] = None, + text: Optional[str] = None, image: Optional[Union[str, Path]] = None, link: Optional[str] = None, userid: Optional[str] = None, username: Optional[str] = None, + *, native_image: bool = False, file_path: Optional[Union[str, Path]] = None, file_name: Optional[str] = None, **kwargs: Any) -> None: """ 发送消息,沿用宿主通知开关和收件人路由。 - :param kwargs: 可传 rich_content 通用结构化通知;宿主按渠道能力排版,text 保留为纯文本回退。 - 传 native_image=True 可让企业微信自建应用发送完整原图,默认仍发送图文卡片。 - 传 file_path 和可选 file_name 可发送本地附件,企业微信自建应用上限为 20 MiB。 + :param native_image: 将 image 作为完整 JPG/PNG 原图发送;支持 HTTP(S)、Base64 或本地路径,无需判断渠道 + :param file_path: 本地附件路径;宿主负责渠道上传,发送后保留源文件 + :param file_name: 可选的附件展示名;为空时使用源文件名 + :param kwargs: 可传 rich_content 通用结构化通知;宿主按渠道能力排版,不支持附件的渠道明确提示 """ if not link: link = settings.MP_DOMAIN(f"#/plugins?tab=installed&id={self.__class__.__name__}") self.chain.post_message(Message( channel=channel, mtype=mtype, title=title, text=text, - image=image, link=link, userid=userid, username=username, **kwargs + image=str(image) if image is not None else None, native_image=native_image, + file_path=str(file_path) if file_path is not None else None, file_name=file_name, + link=link, userid=userid, username=username, **kwargs )) def close(self) -> None: diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index f04a179af..eb61a5ff2 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -845,13 +845,13 @@ flowchart LR ### 10.2 当前架构快照 -以下是 2026-11-19 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, +以下是 2026-11-20 核对的 `tests/fixtures/architecture/` 数据;这是源码合同快照, 不代表某个已发布镜像或正在运行的实例已经验证。 | 指标 | 当前值 | |---|---:| -| Python 模块 | 1185 | -| 内部导入边 | 10,382 | +| Python 模块 | 1187 | +| 内部导入边 | 10,406 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) | diff --git a/docs/mcp-api.md b/docs/mcp-api.md index ec3f0ed16..0542f9599 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -315,17 +315,11 @@ Web 会话沿用当前用户;无渠道调用不携带收件人,插件回执 新通知从已有媒体上下文提取海报;`image` 继续保留原有渠道图片语义。 旧通知及没有海报的通知返回 `poster: null`,客户端不应将背景图裁切成海报。 -插件通过 `post_message(image=..., native_image=True)` 可请求企业微信自建应用发送完整原图, -适用于二维码和截图。`image` 支持 HTTP(S) 或 Base64 JPG/PNG 数据地址,内容须大于 5 字节且 -不超过 10 MiB;有标题或正文时另发文本,`link`(包括插件默认详情链接)不会用于原生图片。 -下载、上传或发送失败会记录错误,不回退为图文卡片。省略开关时仍使用图文,机器人模式和其他渠道 -保持原有行为;此开关不改变通知权限与收件人路由。 - -企业微信自建应用还支持 `post_message(file_path=..., file_name=...)`,复用通用附件字段, -以 `msgtype=file` 发送大于 5 字节且不超过 20 MiB 的本地文件。`file_name` 可省略,默认使用源文件名; -有说明文字时另发文本,发送过程不删除源文件。显式附件优先于图片和语音;机器人模式暂不支持文件。 -Agent 的 `send_local_file` 也仅在企业微信自建应用实例开放该能力。微信插件端需先关注并开启接收应用消息, -应用管理端不要勾选“在微工作台中始终进入主页”;实际微信端展示仍需在用户账号上验证。 +插件统一通过 `post_message(image=..., native_image=True)` 请求发送完整 JPG/PNG 原图, +通过 `post_message(file_path=..., file_name=...)` 发送本地附件,无需判断渠道、应用模式或上传协议。 +同时提供图片和文件时保留二者,说明文字只发一次;发送后保留源文件。 +宿主按渠道选择上传图片、发送文件或行内图片;不支持的本地附件会明确提示,不能伪装为发送成功或泄露本地路径。 +省略 `native_image` 时保留现有封面通知。详见[统一图片与附件协议](message-attachments.md)。 `POST /api/v1/notification/config` 保存通知渠道时要求名称和稳定 `id` 各自唯一。 改名应保留原 `id`;复制为新的渠道实例应使用新的 `id`,避免共享登录凭据。 diff --git a/docs/message-attachments.md b/docs/message-attachments.md new file mode 100644 index 000000000..a82e4a103 --- /dev/null +++ b/docs/message-attachments.md @@ -0,0 +1,50 @@ +# 统一图片与附件协议 + +插件只调用 `_PluginBase.post_message()`,由宿主完成通知开关、接收人路由、图片获取、素材上传与平台载荷转换。 +不要在插件中根据渠道选择 `media_id`、`image_key`、机器人模式或上传 API。 + +## 插件调用 + +```python +self.post_message(title="登录二维码", text="请扫码后点击完成", image=image_source, native_image=True) +self.post_message(title="字幕附件", text="请下载查看", file_path=subtitle_path, file_name="subtitle.srt") +``` + +`channel`、`userid`、`source`、`mtype` 等既有路由参数继续适用。省略渠道时沿用用户的通知配置, +不会因为带附件而绕过通知权限或把私聊转为群发。 + +| 参数 | 统一含义 | +| --- | --- | +| `image` | 默认是原有通知封面;使用 `native_image=True` 时表示独立原图 | +| `native_image` | 默认 `False`;`True` 请求完整图片,支持上传的渠道接受 HTTP(S)、Base64 数据地址或本地 JPG/PNG | +| `file_path` | 本地附件路径,发送后保留源文件 | +| `file_name` | 可选的接收端展示名称,默认使用源文件名 | +| `title` / `text` | 图片或附件的说明,不因发送附件而忽略 | + +原图输入须大于 5 字节且不超过 10 MiB,不裁切或改写源图片字节。接收端仍可能生成自己的预览图。 +只接受路径上传的客户端使用运行时临时目录内的短期副本,上传结束即清理;不会删除调用方文件或写入图片缓存。 +图片与文件同时存在时分开发送,说明和交互按钮只随第一部分发送,不因某个渠道的文件分支而静默丢图。 + +## 当前渠道适配 + +下表描述当前宿主接入实现,不等同于平台所有 API 的能力。实际尺寸、配额、账号权限和服务端拒绝由对应客户端处理。 + +| 渠道 | `native_image=True` | `file_path` | +| --- | --- | --- | +| 企业微信自建应用 | 上传 JPG/PNG 后发送 `image`,说明另发文本 | 上传临时素材后发送 `file`,不超过 20 MiB | +| 企业微信智能机器人 | 长连接分片上传后发送 `image`,说明另发 | 长连接分片上传后发送 `file`,不超过 20 MiB | +| Telegram | 上传原图,保留会话、话题及按钮 | 复用已有附件上传 | +| 飞书 | 上传后发送独立 `image`,说明及按钮另发 | 复用已有附件上传 | +| Slack | 上传原图,不依赖外部图片地址公开访问 | 复用已有文件上传 | +| Discord | 上传原图,保留接收会话 | 复用已有附件上传 | +| 微信 ClawBot | 上传图片,并保留说明 | 复用已有附件协议,保留说明 | +| 钉钉、QQ、SynologyChat、VoceChat | HTTP(S) 图片沿用现有行内图片;本地或 Base64 来源明确提示暂不支持 | 当前宿主接入暂不支持,发送明确提示 | +| WebPush、AppPush | 保留现有系统通知行为,原图请求降级为图片链接或明确提示 | 当前宿主接入暂不支持,发送明确提示 | +| Web / WebAgent | 沿用站内消息及 Agent 回调的图片展示 | WebAgent 使用已有附件回调;普通站内通知不提供本地文件上传 | + +普通通知中的 `image` 和 `native_image=False` 保留旧行为,包括企业微信 `news` 海报卡片。 +显式原图不把插件默认详情链接变成图片点击目标。只有链接图片能力的渠道仍可能需要一个能被客户端访问的 HTTP(S) 地址。 + +文件不支持时通知中显示“附件未发送”及展示名称,不发送原始本地路径,不伪造附件下载链接。 +原图不支持上传时使用现有行内图片或图片链接;Base64 和本地路径不会作为文字发送给接收者。 +下载、上传或发送失败保留错误信息,接口入队不代表远端已经收到。离线测试与 CI 不能替代真实账号验收。 diff --git a/docs/rules/05-architecture.md b/docs/rules/05-architecture.md index 92863211f..73b27dac7 100644 --- a/docs/rules/05-architecture.md +++ b/docs/rules/05-architecture.md @@ -131,6 +131,12 @@ Entrypoints (app/api, app/command, app/monitor, app/scheduler, app/agent, app/wo - `app/modules/_base/` (`downloader.py`, `mediaserver.py`, `notification.py`) holds only shared connection, reconnect, auth and command-registration templates typed by `TService`, never per-provider business logic. +- Notification modules consume the same `Message` image/file intent through + `_MessageBase.iter_message_configs`; `application/messaging/attachment.py` + owns composition and unsupported-capability notices, while + `adapters/system/attachment.py` owns bounded image reads and short-lived + upload files. Provider protocols stay in their clients; plugins do not + select uploads, media identifiers or instance modes. - Strict file existence checks use `get_file_item_strict(storage, path)` returning `FileItemQueryResult(item=...)` (`None` means unsupported provider, whereas `item=None` proves absence and storage/query errors raise). Destructive diff --git a/skills/create-moviepilot-plugin/SKILL.md b/skills/create-moviepilot-plugin/SKILL.md index 6b4a693a9..3d74e508b 100644 --- a/skills/create-moviepilot-plugin/SKILL.md +++ b/skills/create-moviepilot-plugin/SKILL.md @@ -372,16 +372,15 @@ Use only the extension points the requested plugin actually needs: `init_plugin()` reads config; `update_config()` persists internal changes. - Data: use `save_data()`, `get_data()`, `del_data()`, and `get_data_path()`. - Notification: use `post_message()` instead of directly calling message - modules. For QR codes or screenshots sent through a WeCom custom application, - pass `image=, native_image=True`. - This uploads and sends a native image with any title/text sent separately; - the link (including the default plugin-page link) is ignored. Images must be - larger than 5 bytes and at most 10 MiB. The default remains a news card; - other channels and WeCom bot mode keep their existing behavior. - WeCom custom applications also support local attachments through - `file_path=, file_name=` (larger than - 5 bytes, at most 20 MiB). Attachments take precedence over image/voice fields; - the source file is preserved, and bot mode does not support file sending. + modules. Use the same `image=, native_image=True` call for QR codes + and screenshots on every channel; upload-capable adapters accept HTTP(S), + Base64 or local JPG/PNG (over 5 bytes, up to 10 MiB). Send attachments through + `file_path=, file_name=`. Do not branch on + channel names, WeCom modes, vendor media IDs or upload APIs. The host preserves + captions and both parts of a combined image/file message, selects the platform + protocol, and provides an explicit notice when a local attachment cannot be sent. + Source files are preserved. The default `image` cover behavior remains unchanged. + See `docs/message-attachments.md` for the maintained host capability matrix. - APIs: return route definitions from `get_api()`; default auth is `apikey` when `auth` is omitted. Vue component APIs should normally use `auth: "bear"` and be called through the `api` prop passed by the frontend. diff --git a/tests/fixtures/architecture/complexity-baseline.json b/tests/fixtures/architecture/complexity-baseline.json index f0c6b5a99..ce6c61a17 100644 --- a/tests/fixtures/architecture/complexity-baseline.json +++ b/tests/fixtures/architecture/complexity-baseline.json @@ -145,7 +145,6 @@ "app/modules/jellyfin/jellyfin.py:Jellyfin.get_movies": 6, "app/modules/qbittorrent/__init__.py:QbittorrentModule.download": 7, "app/modules/rtorrent/__init__.py:RtorrentModule.download": 6, - "app/modules/slack/__init__.py:SlackModule.send_direct_message": 6, "app/modules/slack/slack.py:Slack.send_medias_msg": 6, "app/modules/transmission/__init__.py:TransmissionModule.download": 7, "app/modules/wechat/wechat.py:WeChat.__split_content": 6, diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 82652746b..f7c25c141 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -977,8 +977,8 @@ "runtime_only": true } }, - "edge_count": 10382, - "edge_sha256": "8c9c2816006ccbb7ed004a2fa4296447f4a300cbda8755150cb4312bd4dffe27", + "edge_count": 10406, + "edge_sha256": "5157281ae12364f0d1c5ffcbbe8e7c41b5b02bf4b95b318568f3e75ab2e17c35", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -1135,6 +1135,12 @@ "app.adapters.network.webpush -> app.adapters.network.http", "app.adapters.observability.otel -> app.runtime", "app.adapters.observability.otel -> app.runtime.observability", + "app.adapters.system.attachment -> app.adapters", + "app.adapters.system.attachment -> app.adapters.network", + "app.adapters.system.attachment -> app.adapters.network.http", + "app.adapters.system.attachment -> app.runtime", + "app.adapters.system.attachment -> app.runtime.log", + "app.adapters.system.attachment -> app.runtime.settings", "app.adapters.system.backup.files -> app.runtime", "app.adapters.system.backup.files -> app.runtime.version", "app.adapters.system.code.kernel -> app.adapters", @@ -2177,8 +2183,6 @@ "app.agent.tools.impl.send_local_file -> app.agent.tools", "app.agent.tools.impl.send_local_file -> app.agent.tools.base", "app.agent.tools.impl.send_local_file -> app.agent.tools.tags", - "app.agent.tools.impl.send_local_file -> app.application", - "app.agent.tools.impl.send_local_file -> app.application.notification", "app.agent.tools.impl.send_local_file -> app.runtime", "app.agent.tools.impl.send_local_file -> app.runtime.log", "app.agent.tools.impl.send_local_file -> app.schemas", @@ -3985,6 +3989,10 @@ "app.application.messaging.agent -> app.schemas", "app.application.messaging.agent -> app.schemas.message", "app.application.messaging.agent -> app.schemas.types", + "app.application.messaging.attachment -> app.schemas", + "app.application.messaging.attachment -> app.schemas.message", + "app.application.messaging.attachment -> app.schemas.notification", + "app.application.messaging.attachment -> app.schemas.types", "app.application.messaging.channel.admin -> app.application", "app.application.messaging.channel.admin -> app.application.notification", "app.application.messaging.channel.admin -> app.application.security", @@ -7504,6 +7512,9 @@ "app.main -> app.runtime.settings", "app.main -> app.runtime.stop", "app.main -> app.runtime.topology", + "app.modules -> app.application", + "app.modules -> app.application.messaging", + "app.modules -> app.application.messaging.attachment", "app.modules -> app.runtime", "app.modules -> app.runtime.extensions", "app.modules -> app.runtime.extensions.service", @@ -7693,6 +7704,9 @@ "app.modules.discord -> app.schemas.event", "app.modules.discord -> app.schemas.message", "app.modules.discord -> app.schemas.types", + "app.modules.discord.discord -> app.adapters", + "app.modules.discord.discord -> app.adapters.system", + "app.modules.discord.discord -> app.adapters.system.attachment", "app.modules.discord.discord -> app.application", "app.modules.discord.discord -> app.application.messaging", "app.modules.discord.discord -> app.application.messaging.ingress", @@ -7800,6 +7814,8 @@ "app.modules.feishu.feishu -> app.adapters.network.feishu", "app.modules.feishu.feishu -> app.adapters.network.http", "app.modules.feishu.feishu -> app.adapters.network.ip", + "app.modules.feishu.feishu -> app.adapters.system", + "app.modules.feishu.feishu -> app.adapters.system.attachment", "app.modules.feishu.feishu -> app.application", "app.modules.feishu.feishu -> app.application.messaging", "app.modules.feishu.feishu -> app.application.messaging.channel", @@ -8800,6 +8816,8 @@ "app.modules.slack.slack -> app.adapters", "app.modules.slack.slack -> app.adapters.network", "app.modules.slack.slack -> app.adapters.network.http", + "app.modules.slack.slack -> app.adapters.system", + "app.modules.slack.slack -> app.adapters.system.attachment", "app.modules.slack.slack -> app.application", "app.modules.slack.slack -> app.application.messaging", "app.modules.slack.slack -> app.application.messaging.ingress", @@ -8882,6 +8900,8 @@ "app.modules.telegram.telegram -> app.adapters", "app.modules.telegram.telegram -> app.adapters.network", "app.modules.telegram.telegram -> app.adapters.network.http", + "app.modules.telegram.telegram -> app.adapters.system", + "app.modules.telegram.telegram -> app.adapters.system.attachment", "app.modules.telegram.telegram -> app.application", "app.modules.telegram.telegram -> app.application.image", "app.modules.telegram.telegram -> app.application.messaging", @@ -9360,6 +9380,8 @@ "app.modules.wechat.wechatbot -> app.adapters", "app.modules.wechat.wechatbot -> app.adapters.network", "app.modules.wechat.wechatbot -> app.adapters.network.http", + "app.modules.wechat.wechatbot -> app.adapters.system", + "app.modules.wechat.wechatbot -> app.adapters.system.attachment", "app.modules.wechat.wechatbot -> app.application", "app.modules.wechat.wechatbot -> app.application.messaging", "app.modules.wechat.wechatbot -> app.application.messaging.channel", @@ -9397,6 +9419,8 @@ "app.modules.wechatclawbot.wechatclawbot -> app.adapters", "app.modules.wechatclawbot.wechatclawbot -> app.adapters.network", "app.modules.wechatclawbot.wechatclawbot -> app.adapters.network.http", + "app.modules.wechatclawbot.wechatclawbot -> app.adapters.system", + "app.modules.wechatclawbot.wechatclawbot -> app.adapters.system.attachment", "app.modules.wechatclawbot.wechatclawbot -> app.application", "app.modules.wechatclawbot.wechatclawbot -> app.application.messaging", "app.modules.wechatclawbot.wechatclawbot -> app.application.messaging.ingress", @@ -11363,7 +11387,7 @@ "app.workflow.actions.transfer_file -> app.workflow", "app.workflow.actions.transfer_file -> app.workflow.actions" ], - "module_count": 1185, + "module_count": 1187, "modules": [ "app", "app.adapters", @@ -11395,6 +11419,7 @@ "app.adapters.observability", "app.adapters.observability.otel", "app.adapters.system", + "app.adapters.system.attachment", "app.adapters.system.backup", "app.adapters.system.backup.database", "app.adapters.system.backup.files", @@ -11693,6 +11718,7 @@ "app.application.mediaserver", "app.application.messaging", "app.application.messaging.agent", + "app.application.messaging.attachment", "app.application.messaging.channel", "app.application.messaging.channel.admin", "app.application.messaging.chat", diff --git a/tests/test_downloader_path_mapping.py b/tests/test_downloader_path_mapping.py index 7e0340ae0..774286b6a 100644 --- a/tests/test_downloader_path_mapping.py +++ b/tests/test_downloader_path_mapping.py @@ -115,6 +115,7 @@ def _load_downloader_base(): log_module.logger = _Logger() mixins_module.ConfigReloadMixin = _ConfigReloadMixin schema_message_module.Message = object + schema_message_module.MessageResponse = object schema_system_module.NotificationConf = object schema_system_module.MediaServerConf = object schema_system_module.DownloaderConf = object diff --git a/tests/test_notification_attachment_contract.py b/tests/test_notification_attachment_contract.py new file mode 100644 index 000000000..be7af8330 --- /dev/null +++ b/tests/test_notification_attachment_contract.py @@ -0,0 +1,450 @@ +""" +统一附件协议的插件入口、渠道适配、来源读取和实例隔离回归。 +""" + +import base64 +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from app.adapters.system import attachment +from app.application.messaging.attachment import notification_parts +from app.modules.dingtalk import DingTalkModule +from app.modules.discord import DiscordModule +from app.modules.discord.discord import Discord +from app.modules.feishu.feishu import Feishu +from app.modules.feishu.module import FeishuModule +from app.modules.qqbot.module import QQBotModule +from app.modules.slack import SlackModule +from app.modules.slack.slack import Slack +from app.modules.synologychat import SynologyChatModule +from app.modules.telegram.module import TelegramModule +from app.modules.telegram.telegram import Telegram +from app.modules.vocechat import VoceChatModule +from app.modules.wechat import WechatModule +from app.modules.wechat.wechat import WeChat +from app.modules.wechat.wechatbot import WeChatBot +from app.modules.wechatclawbot import WechatClawBotModule +from app.modules.wechatclawbot.wechatclawbot import WechatClawBot +from app.schemas.message import Message, MessageResponse +from app.schemas.notification import ChannelCapability, ChannelCapabilityManager +from app.schemas.types import NotificationChannel +from app.sdk.plugin import base as plugin_base +from app.sdk.plugin.base import _PluginBase + +_PNG = b"\x89PNG\r\n\x1a\nimage-bytes" +_DATA_URL = f"data:image/png;base64,{base64.b64encode(_PNG).decode()}" +_IMAGE_URL = "https://images.example/qr.png?token=temporary" +_UPLOAD_CHANNELS = [ + (NotificationChannel.Telegram, TelegramModule, Telegram), + (NotificationChannel.Feishu, FeishuModule, Feishu), + (NotificationChannel.Slack, SlackModule, Slack), + (NotificationChannel.Discord, DiscordModule, Discord), + (NotificationChannel.Wechat, WechatModule, WeChat), + (NotificationChannel.Wechat, WechatModule, WeChatBot), + (NotificationChannel.WechatClawBot, WechatClawBotModule, WechatClawBot), +] +_LINK_CHANNELS = [ + (NotificationChannel.DingTalk, DingTalkModule), + (NotificationChannel.QQ, QQBotModule), + (NotificationChannel.SynologyChat, SynologyChatModule), + (NotificationChannel.VoceChat, VoceChatModule), +] + + +def _module(monkeypatch: pytest.MonkeyPatch, channel, module_class, client): + """ + 保留真实通知过滤和接收人规则,替换实例目录及渠道发送边界。 + """ + module = module_class() + module._channel = channel + conf = SimpleNamespace(name="source", config={}, type=channel.name.lower(), enabled=True) + monkeypatch.setattr(module, "get_configs", lambda: {"source": conf}) + monkeypatch.setattr(module, "get_instance", lambda _: client) + monkeypatch.setattr(module, "get_instances", lambda: {"source": client}) + if isinstance(module, FeishuModule): + monkeypatch.setattr(module, "_resolve_message_target", lambda _: ("member", "chat", "open_id")) + return module + + +@pytest.mark.parametrize("channel,module_class,client_class", _UPLOAD_CHANNELS) +def test_same_plugin_image_payload_is_adapted_by_host( + monkeypatch: pytest.MonkeyPatch, channel, module_class, client_class, +) -> None: + """ + 插件使用同一组参数,不判断渠道或企微模式,原图、说明及目标均由宿主转交。 + """ + client = client_class.__new__(client_class) + send_image = Mock(return_value={"success": True}) + send_msg = Mock(return_value=True) + monkeypatch.setattr(client, "send_image", send_image, raising=False) + monkeypatch.setattr(client, "send_msg", send_msg, raising=False) + module = _module(monkeypatch, channel, module_class, client) + monkeypatch.setattr(plugin_base, "settings", SimpleNamespace(MP_DOMAIN=lambda path: f"https://mp.example/{path}")) + plugin = SimpleNamespace(chain=Mock()) + _PluginBase.post_message( + plugin, channel=channel, userid="member", title="扫码", text="二维码说明", + image=_DATA_URL, native_image=True, + ) + message = plugin.chain.post_message.call_args.args[0] + + module.post_message(message) + + sent = send_msg if client_class in {WeChat, WeChatBot, WechatClawBot} else send_image + assert sent.call_count == 1 + payload = sent.call_args.kwargs + assert payload["image"] == _DATA_URL + assert payload["title"] == "扫码" + assert payload["text"] == "二维码说明" + assert payload["userid"] == "member" + if sent is send_msg: + assert payload["native_image"] is True + else: + assert "link" not in payload + assert message.image == _DATA_URL + assert message.native_image is True + + +@pytest.mark.parametrize("channel,module_class,client_class", _UPLOAD_CHANNELS) +def test_same_plugin_file_payload_preserves_attachment_and_caption( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, channel, module_class, client_class, +) -> None: + """ + 所有已声明文件能力的模块都转交相同附件字段,不再丢弃说明或要求插件识别模式。 + """ + path = tmp_path / "source.txt" + path.write_text("attachment-content") + client = client_class.__new__(client_class) + send_file = Mock(return_value={"success": True}) + monkeypatch.setattr(client, "send_file", send_file) + module = _module(monkeypatch, channel, module_class, client) + + module.post_message(Message(channel=channel, userid="member", title="附件", text="请下载", + file_path=str(path), file_name="report.txt")) + + assert send_file.call_count == 1 + payload = send_file.call_args.kwargs + assert {key: payload[key] for key in ("file_path", "file_name", "title", "text", "userid")} == { + "file_path": str(path), "file_name": "report.txt", "title": "附件", "text": "请下载", "userid": "member", + } + assert path.read_text() == "attachment-content" + + +@pytest.mark.parametrize("channel,module_class", _LINK_CHANNELS) +def test_url_image_uses_existing_inline_format_and_files_get_explicit_notice( + monkeypatch: pytest.MonkeyPatch, channel, module_class, +) -> None: + """ + 仅支持图片链接的接入沿用行内图片;不支持文件时明确提示,不能泄露本地绝对路径。 + """ + send = Mock(return_value=True) + module = _module(monkeypatch, channel, module_class, SimpleNamespace(send_msg=send)) + message = Message(channel=channel, userid="123", title="说明", image=_IMAGE_URL, native_image=True, + file_path="/private/secret/report.txt", file_name="附件.txt") + + module.post_message(message) + + assert send.call_count == 2 + image_payload, file_payload = [call.kwargs for call in send.call_args_list] + assert image_payload["image"] == _IMAGE_URL + assert "附件未发送" in file_payload["text"] + assert "附件.txt" in file_payload["text"] + assert "/private/secret" not in str(send.call_args_list) + assert "base64" not in str(send.call_args_list) + + +@pytest.mark.parametrize("channel,module_class", _LINK_CHANNELS) +@pytest.mark.parametrize("image", [_DATA_URL, "/private/secret/image.png"]) +def test_link_only_channels_do_not_leak_local_or_encoded_image_source( + monkeypatch, channel, module_class, image, +) -> None: + """ + 仅支持图片链接的渠道不能把本地路径或 Base64 当作通知正文、封面 URL 泄露给用户。 + """ + sent = Mock(return_value=True) + module = _module(monkeypatch, channel, module_class, SimpleNamespace(send_msg=sent)) + + module.post_message(Message(channel=channel, userid="123", image=image, native_image=True)) + + assert sent.call_count == 1 + assert sent.call_args.kwargs["image"] is None + assert "图片未发送" in sent.call_args.kwargs["text"] + assert image not in str(sent.call_args_list) + + +@pytest.mark.parametrize("channel", list(NotificationChannel)) +def test_combined_message_is_split_without_mutation_or_lost_routing(channel) -> None: + """ + 每个渠道均从原消息独立适配组合内容,保留用户、来源和隔离路由,只发送一次说明。 + """ + original = Message(channel=channel, source="source", userid="member", title="说明", text="正文", + image=_IMAGE_URL, native_image=True, file_path="/private/report.txt", file_name="report.txt") + original.set_notification_route_scope("user") + before = original.model_dump() + + parts = notification_parts(original, channel) + + assert len(parts) == 2 + assert all(part.userid == "member" and part.source == "source" for part in parts) + assert all(part.notification_route_scope == "user" for part in parts) + assert parts[0].title == "说明" + assert parts[1].title is None + assert "正文" not in (parts[1].text or "") + assert original.model_dump() == before + assert original.notification_route_scope == "user" + + +def test_filtered_instance_never_processes_local_attachment(monkeypatch: pytest.MonkeyPatch) -> None: + """ + 先按消息来源过滤,再适配附件,不对其他实例执行发送或图片读取。 + """ + client = SimpleNamespace(send_msg=Mock(), send_file=Mock()) + module = _module(monkeypatch, NotificationChannel.Wechat, WechatModule, client) + message = Message(channel=NotificationChannel.Wechat, source="other", userid="member", + image="/private/not-for-this-instance.png", native_image=True) + + module.post_message(message) + + client.send_msg.assert_not_called() + client.send_file.assert_not_called() + + +@pytest.mark.parametrize("source_kind", ["http", "data", "local"]) +def test_common_image_source_reads_original_bytes_and_releases_temp_file( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source_kind: str, +) -> None: + """ + URL、Base64 和本地原图使用同一内容,短期文件位于运行配置目录并在发送后清理。 + """ + original = tmp_path / "original.png" + original.write_bytes(_PNG) + response = Mock(status_code=200) + response.iter_content.return_value = [_PNG[:8], _PNG[8:]] + requests = Mock() + requests.return_value.get_res.return_value = response + monkeypatch.setattr(attachment, "RequestUtils", requests) + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path / "upload") + source = {"http": _IMAGE_URL, "data": _DATA_URL, "local": str(original)}[source_kind] + + with attachment.image_upload_file(source) as path: + assert path is not None and path.read_bytes() == _PNG + assert path.parent.parent == tmp_path / "upload" + assert not path.exists() + assert original.read_bytes() == _PNG + if source_kind == "http": + response.close.assert_called_once_with() + else: + requests.assert_not_called() + + +@pytest.mark.parametrize("source", ["data:image/png;base64,!!!", "data:image/png,plain", "file:///private/a.png", + "data:image/gif;base64,R0lGODlhZ2lm", "missing.png"]) +def test_bad_image_source_is_rejected_without_temp_artifact(monkeypatch, tmp_path, source) -> None: + """ + 无效来源不会被当成可上传图片,也不产生缓存或临时副本。 + """ + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + + with attachment.image_upload_file(source) as path: + assert path is None + assert not list(tmp_path.iterdir()) + + +def test_oversized_http_stream_stops_and_closes_response(monkeypatch) -> None: + """ + 下载超限时不继续消费流,并释放连接。 + """ + monkeypatch.setattr(attachment, "IMAGE_MAX_BYTES", 8) + response = Mock(status_code=200) + chunks = iter([b"123456789", b"must-not-read"]) + response.iter_content.return_value = chunks + requests = Mock() + requests.return_value.get_res.return_value = response + monkeypatch.setattr(attachment, "RequestUtils", requests) + + assert attachment.load_image(_IMAGE_URL) is None + assert next(chunks) == b"must-not-read" + response.close.assert_called_once_with() + + +@pytest.mark.parametrize("failure", ["http", "empty", "stream"]) +def test_failed_remote_image_is_not_uploaded_and_response_is_released(monkeypatch, failure) -> None: + """ + HTTP 拒绝、无响应和中途读取失败均返回不可用结果,并释放已取得的响应。 + """ + response = None if failure == "empty" else Mock(status_code=404 if failure == "http" else 200) + if failure == "stream": + response.iter_content.side_effect = OSError("stream failed") + requests = Mock() + requests.return_value.get_res.return_value = response + monkeypatch.setattr(attachment, "RequestUtils", requests) + + assert attachment.load_image(_IMAGE_URL) is None + if response is not None: + response.close.assert_called_once_with() + + +def test_image_temporary_copy_is_cleaned_when_sender_raises(monkeypatch, tmp_path) -> None: + """ + 上传边界抛异常时仍清理短期图片,不能把二维码副本留在临时目录。 + """ + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + with pytest.raises(RuntimeError): + with attachment.image_upload_file(_DATA_URL) as path: + assert path.exists() + raise RuntimeError("sender failed") + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize("client_class", [Slack, Discord]) +def test_native_image_clients_upload_bytes_and_preserve_caption(monkeypatch, tmp_path, client_class) -> None: + """ + 各客户端从统一图片来源生成上传文件,发送边界读取相同原始字节和说明。 + """ + client = client_class.__new__(client_class) + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + captured = {} + + def upload(file_path, **kwargs): + """ + 在客户端同步上传时读取短期文件,随后由来源适配器负责清理。 + """ + path = None if "file_content" in kwargs else Path(file_path) + captured.update(kwargs, content=kwargs.get("file_content") if path is None else path.read_bytes(), path=path) + return {"success": True} if client_class is Telegram else (True, {}) + + monkeypatch.setattr(client, "send_file", upload) + + result = client.send_image(image=_DATA_URL, title="扫码", text="请扫描", userid="member") + + assert result + assert captured["content"] == _PNG + assert captured["title"] == "扫码" and captured["text"] == "请扫描" + assert captured["userid"] == "member" + assert captured["path"] is None or not captured["path"].exists() + + +@pytest.mark.parametrize("client_class", [Slack, Discord]) +@pytest.mark.parametrize("caption_succeeds", [False, True]) +def test_native_image_buttons_preserve_caption_and_failure_result( + monkeypatch, tmp_path, client_class, caption_succeeds, +) -> None: + """ + 原图有按钮时只发送一次说明;说明失败后不再上传发送图片,且总会清理短期文件。 + """ + client = client_class.__new__(client_class) + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + caption = Mock(return_value=(caption_succeeds, {})) + upload = Mock(return_value=(True, {})) + monkeypatch.setattr(client, "send_msg", caption) + monkeypatch.setattr(client, "send_file", upload) + + result = client.send_image(_DATA_URL, title="扫码", text="说明", userid="member", + buttons=[[{"text": "完成", "callback_data": "done"}]]) + + assert bool(result and (result[0] if isinstance(result, tuple) else result)) is caption_succeeds + assert caption.call_count == 1 + assert upload.called is caption_succeeds + if caption_succeeds: + assert upload.call_args.kwargs["title"] is None + assert upload.call_args.kwargs["text"] is None + assert not list(tmp_path.iterdir()) + + +def test_telegram_native_image_preserves_long_caption_and_raw_bytes(monkeypatch) -> None: + """ + Telegram 原图沿用长正文发送通路,不能因附件标题上限截断说明。 + """ + client = Telegram.__new__(Telegram) + client._telegram_token = "token" + client._telegram_chat_id = "chat" + monkeypatch.setattr(client, "_determine_target_chat_id", lambda *_args, **_kwargs: "chat") + monkeypatch.setattr(client, "_is_chat_rate_limited", lambda *_args, **_kwargs: False) + sent = Mock(return_value={"message_id": 1}) + monkeypatch.setattr(client, "_Telegram__send_request", sent) + monkeypatch.setattr(client, "_remember_sent_message", Mock()) + text = "说明" * 2000 + + assert client.send_image(_DATA_URL, title="图片", text=text, parse_mode="plain")["success"] is True + assert sent.call_args.kwargs["image"] == _PNG + assert text in sent.call_args.kwargs["caption"] + assert Telegram._Telegram__process_image(_PNG) == _PNG + + +@pytest.mark.parametrize("channel,module_class,client_class", _UPLOAD_CHANNELS) +def test_uploaded_media_capabilities_match_existing_clients(channel, module_class, client_class) -> None: + """ + 已声明可上传原图的渠道也具备文件发送接口,不向插件暴露模式特判。 + """ + assert ChannelCapabilityManager.supports_capability(channel, ChannelCapability.NATIVE_IMAGES) + assert ChannelCapabilityManager.supports_capability(channel, ChannelCapability.FILE_SENDING) + assert callable(client_class.send_file) + + +@pytest.mark.parametrize("module_class", [TelegramModule, FeishuModule, SlackModule, DiscordModule]) +@pytest.mark.parametrize("second_succeeds", [False, True]) +def test_direct_message_delivers_all_parts_on_same_instance( + monkeypatch, module_class, second_succeeds, +) -> None: + """ + 直接发送接口也保留组合图片和文件,后续投递锁定首个实例,第二部分失败不得返回完整成功。 + """ + module = module_class() + receipt = MessageResponse(success=True, source="chosen", message_id="image") + sender = Mock(side_effect=[receipt, MessageResponse(success=True, source="chosen") if second_succeeds else None]) + monkeypatch.setattr(module, "_send_direct_message_part", sender) + original = Message(userid="member", image=_IMAGE_URL, native_image=True, file_path="/private/report.txt") + + result = module.send_direct_message(original) + + assert (result is receipt) is second_succeeds + assert sender.call_count == 2 + assert sender.call_args_list[1].args[0].source == "chosen" + assert original.source is None + + +def test_feishu_native_image_uses_image_message_and_preserves_reply(monkeypatch, tmp_path) -> None: + """ + 飞书上传图片后使用独立 image 消息,说明和按钮只发送一次并回复原消息。 + """ + client = Feishu.__new__(Feishu) + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + monkeypatch.setattr(client, "_upload_image", lambda _: "image-key") + caption = Mock(return_value={"success": True}) + reply = Mock(return_value={"success": True, "message_id": "image-message"}) + monkeypatch.setattr(client, "send_notification", caption) + monkeypatch.setattr(client, "_reply_message", reply) + + result = client.send_image(image=_DATA_URL, title="二维码", text="说明", userid="member", + original_message_id="original", buttons=[[{"text": "完成", "callback_data": "done"}]]) + + assert result["success"] is True + assert caption.call_count == 1 + assert caption.call_args.args[0].buttons + reply.assert_called_once_with("original", "image", {"image_key": "image-key"}) + assert not list(tmp_path.iterdir()) + + +@pytest.mark.parametrize("failure", [None, "upload", "caption"]) +def test_feishu_native_image_broadcast_reports_failures(monkeypatch, tmp_path, failure) -> None: + """ + 飞书无原消息时保持广播路由,上传或说明失败则不发送图片且返回失败。 + """ + client = Feishu.__new__(Feishu) + monkeypatch.setattr(attachment, "get_runtime_setting", lambda _: tmp_path) + monkeypatch.setattr(client, "_upload_image", lambda _: None if failure == "upload" else "key") + caption = Mock(return_value={"success": failure != "caption"}) + deliver = Mock(return_value={"success": True}) + monkeypatch.setattr(client, "send_notification", caption) + monkeypatch.setattr(client, "_send_with_fallback_broadcast", deliver) + + result = client.send_image(_DATA_URL, title="说明" if failure else None, userid="member") + + assert result["success"] is (failure is None) + assert deliver.called is (failure is None) + if failure is None: + assert deliver.call_args.args == ("image", {"image_key": "key"}) + caption.assert_not_called() + assert not list(tmp_path.iterdir()) diff --git a/tests/test_wechat_bot_media.py b/tests/test_wechat_bot_media.py new file mode 100644 index 000000000..271efeffb --- /dev/null +++ b/tests/test_wechat_bot_media.py @@ -0,0 +1,160 @@ +""" +企业微信机器人长连接媒体上传与统一图片、文件发送协议回归。 +""" + +import base64 +import threading +from unittest.mock import Mock + +import pytest + +from app.modules.wechat.wechatbot import WeChatBot + + +@pytest.fixture +def bot(monkeypatch: pytest.MonkeyPatch) -> tuple[WeChatBot, list[dict]]: + """ + 用同步服务器回执替身驱动真实认证等待与确认关联,不创建连接或后台线程。 + """ + client = WeChatBot.__new__(WeChatBot) + client._authenticated = threading.Event() + client._authenticated.set() + client._acks_lock = threading.Lock() + client._send_lock = threading.Lock() + client._pending_acks = {} + client._known_targets = set() + client._default_chat_id = "user:member" + client._config_name = "test-bot" + recorded = [] + + def send(payload): + """ + 模拟上传初始化、分片和完成确认,分片确认允许没有 body。 + """ + recorded.append(payload) + body = {"aibot_upload_media_init": {"upload_id": "upload"}, + "aibot_upload_media_finish": {"media_id": "media"}}.get(payload["cmd"]) + ack = {"errcode": 0, **({"body": body} if body else {})} + client._resolve_ack(payload["headers"]["req_id"], ack) + + monkeypatch.setattr(client, "_send_raw", send) + return client, recorded + + +@pytest.mark.parametrize("userid,chat_type,target", [("user:member", 1, "member"), ("group:chat", 2, "chat")]) +def test_bot_file_upload_waits_for_each_ack_and_preserves_target(bot, tmp_path, userid, chat_type, target) -> None: + """ + 上传按 init、所有分片、finish 排序,随后独立发送说明与文件,并保留群聊或私聊目标。 + """ + client, frames = bot + path = tmp_path / "attachment.txt" + content = b"a" * (512 * 1024 + 17) + path.write_bytes(content) + + assert client.send_file(str(path), file_name="report.txt", title="附件", text="说明", userid=userid) is True + + assert [frame["cmd"] for frame in frames] == [ + "aibot_upload_media_init", "aibot_upload_media_chunk", "aibot_upload_media_chunk", + "aibot_upload_media_finish", "aibot_send_msg", "aibot_send_msg", + ] + assert frames[0]["body"]["filename"] == "report.txt" + assert frames[0]["body"]["total_chunks"] == 2 + chunks = frames[1:3] + assert [frame["body"]["chunk_index"] for frame in chunks] == [1, 2] + assert b"".join(base64.b64decode(frame["body"]["base64_data"]) for frame in chunks) == content + assert "说明" in frames[-2]["body"]["markdown"]["content"] + assert frames[-1]["body"] == {"chatid": target, "chat_type": chat_type, "msgtype": "file", + "file": {"media_id": "media"}} + assert path.read_bytes() == content + assert client._pending_acks == {} + + +def test_bot_native_image_uploads_original_png_without_default_link(bot) -> None: + """ + 机器人模式同样接受 native_image,无需插件判断应用模式,且不把默认详情链接嵌入图片。 + """ + client, frames = bot + content = b"\x89PNG\r\n\x1a\noriginal-png" + image = f"data:image/png;base64,{base64.b64encode(content).decode()}" + + assert client.send_msg(title="扫码", text="说明", image=image, native_image=True, + link="https://mp.example/#/plugins?id=test") is True + + assert frames[0]["body"]["type"] == "image" + assert base64.b64decode(frames[1]["body"]["base64_data"]) == content + assert frames[-1]["body"]["image"] == {"media_id": "media"} + assert "#/plugins" not in str(frames[-2:]) + + +def test_failed_chunk_is_retried_then_stops_without_sending_later_parts(bot, monkeypatch) -> None: + """ + 失败分片耗尽两次重试后停止,不能发送下一片、完成命令或消息。 + """ + client, _ = bot + command = Mock(side_effect=[{"upload_id": "upload"}, None, None, None]) + monkeypatch.setattr(client, "_media_command", command) + + assert client._upload_media(b"a" * (512 * 1024 + 1), "file", "report.txt") is None + assert [call.args[0] for call in command.call_args_list] == [ + "aibot_upload_media_init", "aibot_upload_media_chunk", "aibot_upload_media_chunk", "aibot_upload_media_chunk", + ] + assert all(call.args[1]["chunk_index"] == 1 for call in command.call_args_list[1:]) + + +@pytest.mark.parametrize("initialized,completed", [({}, {}), ({"upload_id": "upload"}, {}), + ({"upload_id": "upload"}, {"media_id": 12})]) +def test_missing_upload_identifiers_cannot_become_send_success(bot, monkeypatch, initialized, completed) -> None: + """ + 初始化或完成回执缺少合法标识时不发送媒体消息。 + """ + client, frames = bot + + def command(name, _body): + """ + 仅提供指定阶段的外部响应,验证必要标识的类型和空值边界。 + """ + return initialized if name.endswith("init") else completed if name.endswith("finish") else {} + + monkeypatch.setattr(client, "_media_command", command) + assert client._send_media(b"content", "file", "x.txt", None, None, None) is False + assert not frames + + +@pytest.mark.parametrize("size", [0, 5, 20 * 1024 * 1024 + 1]) +def test_bot_rejects_invalid_file_size_before_protocol_upload(bot, tmp_path, size) -> None: + """ + 机器人与自建应用使用相同的文件大小边界,拒绝后保留源文件。 + """ + client, frames = bot + path = tmp_path / "invalid.txt" + with path.open("wb") as file: + file.truncate(size) + + assert client.send_file(str(path)) is False + assert not frames + assert path.stat().st_size == size + + +def test_bot_does_not_upload_without_recipient(bot, monkeypatch) -> None: + """ + 缺少默认或已知接收人时不上传素材,更不能回退为全员通知。 + """ + client, frames = bot + client._default_chat_id = None + upload = Mock() + monkeypatch.setattr(client, "_upload_media", upload) + + assert client._send_media(b"content", "file", "x.txt", None, None, None) is False + upload.assert_not_called() + assert not frames + + +def test_bot_does_not_send_media_after_caption_rejection(bot, monkeypatch) -> None: + """ + 附带说明被服务器拒绝时不得继续发送文件或返回完整成功。 + """ + client, frames = bot + monkeypatch.setattr(client, "_send_markdown", lambda *_args: False) + + assert client._send_media(b"content", "file", "x.txt", "标题", "说明", None) is False + assert frames[-1]["cmd"] == "aibot_upload_media_finish" diff --git a/tests/test_wechat_file_message.py b/tests/test_wechat_file_message.py index 1e479fc3a..44e363a6c 100644 --- a/tests/test_wechat_file_message.py +++ b/tests/test_wechat_file_message.py @@ -10,7 +10,6 @@ from unittest.mock import AsyncMock, Mock import pytest -from app.agent.tools.impl import send_local_file as file_tool from app.agent.tools.impl.send_local_file import SendLocalFileTool from app.modules.wechat import WechatModule from app.modules.wechat import wechat as wechat_client @@ -225,64 +224,57 @@ def test_file_notification_keeps_instance_and_channel_filters( http.post.assert_not_called() -def test_bot_does_not_silently_replace_file_with_text( +def test_bot_receives_same_file_request_as_application( attachment: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """ - 机器人模式拒绝文件发送,不将未送出的附件伪装为普通文本通知。 + 机器人模式通过统一参数发送文件,不能将附件替换成普通文本。 """ bot = WeChatBot.__new__(WeChatBot) send = Mock() + send_file = Mock(return_value=True) monkeypatch.setattr(bot, "send_msg", send) + monkeypatch.setattr(bot, "send_file", send_file) _module(monkeypatch, bot).post_message(Message(file_path=str(attachment), title="附件", userid="member-1")) send.assert_not_called() + send_file.assert_called_once_with(file_path=str(attachment), file_name=None, title="附件", text=None, userid="member-1") -@pytest.mark.parametrize("mode, source_exists, accepted", [ - ("app", True, True), (None, True, True), ("bot", True, False), ("app", False, False), -]) -def test_agent_file_sending_checks_actual_wechat_mode( - attachment: Path, monkeypatch: pytest.MonkeyPatch, mode: str | None, source_exists: bool, accepted: bool, +@pytest.mark.parametrize("channel", [NotificationChannel.Wechat, NotificationChannel.Telegram, + NotificationChannel.Feishu, NotificationChannel.Slack, NotificationChannel.Discord]) +def test_agent_file_sending_uses_common_channel_capability( + attachment: Path, monkeypatch: pytest.MonkeyPatch, channel: NotificationChannel, ) -> None: """ - Agent 只向当前存在的自建应用实例发送附件,默认模式兼容旧配置。 + Agent 只查询通用附件能力,具体模式及发送协议交给宿主渠道模块。 """ - config = {"WECHAT_MODE": mode} if mode else {} - conf = SimpleNamespace(name="wechat-test", config=config) - monkeypatch.setattr(file_tool, "get_notification_configs", lambda: [conf] if source_exists else []) send = AsyncMock() monkeypatch.setattr(SendLocalFileTool, "send_message", send) tool = SendLocalFileTool(session_id="file-test", user_id="member-1") - tool.set_message_attr(channel=NotificationChannel.Wechat.value, source="wechat-test", username="member") + tool.set_message_attr(channel=channel.value, source="source", username="member") result = asyncio.run(tool.run(str(attachment), file_name="download.srt")) - assert ChannelCapabilityManager.supports_capability(NotificationChannel.Wechat, ChannelCapability.FILE_SENDING) - assert bool(send.await_count) is accepted - if accepted: - assert result == "本地附件已发送" - assert send.await_args.args[0].file_path == str(attachment) - assert send.await_args.args[0].file_name == "download.srt" - assert send.await_args.args[0].userid == "member-1" - else: - assert "仅自建应用" in result + assert ChannelCapabilityManager.supports_capability(channel, ChannelCapability.FILE_SENDING) + assert result == "本地附件已发送" + assert send.await_count == 1 + assert send.await_args.args[0].file_path == str(attachment) + assert send.await_args.args[0].file_name == "download.srt" + assert send.await_args.args[0].userid == "member-1" -def test_other_file_channels_do_not_require_wechat_configuration( +def test_unsupported_file_channel_returns_reason_without_sending( attachment: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: """ - 现有附件渠道不读取企业微信实例配置,保持原有文件发送能力。 + 未声明文件能力时不伪造成功回执,明确返回原因。 """ - config_lookup = Mock(side_effect=AssertionError("其他渠道不应查询企业微信配置")) - monkeypatch.setattr(file_tool, "get_notification_configs", config_lookup) send = AsyncMock() monkeypatch.setattr(SendLocalFileTool, "send_message", send) tool = SendLocalFileTool(session_id="file-test", user_id="member-1") - tool.set_message_attr(channel=NotificationChannel.Telegram.value, source="telegram-test", username="member") + tool.set_message_attr(channel=NotificationChannel.DingTalk.value, source="dingtalk-test", username="member") - assert asyncio.run(tool.run(str(attachment))) == "本地附件已发送" - config_lookup.assert_not_called() - send.assert_awaited_once() + assert "暂不支持" in asyncio.run(tool.run(str(attachment))) + send.assert_not_awaited() diff --git a/tests/test_wechat_native_image.py b/tests/test_wechat_native_image.py index fe8ca425c..5bc58aac9 100644 --- a/tests/test_wechat_native_image.py +++ b/tests/test_wechat_native_image.py @@ -313,11 +313,11 @@ def test_plugin_native_image_survives_default_link_and_message_roundtrip( @pytest.mark.parametrize("native_image", [False, True]) -def test_bot_mode_does_not_receive_app_only_keyword( +def test_bot_mode_receives_same_native_image_request( monkeypatch: pytest.MonkeyPatch, native_image: bool, ) -> None: """ - 机器人模式继续使用原有发送参数,不接收仅自建应用支持的开关。 + 机器人模式与自建应用使用同一原图开关,未启用时仍沿用旧通知参数。 """ bot = WeChatBot.__new__(WeChatBot) send = Mock() @@ -327,8 +327,11 @@ def test_bot_mode_does_not_receive_app_only_keyword( module.post_message(message) - send.assert_called_once_with(title="标题", text=None, image=_IMAGE_URL, - userid="member-1", link="https://detail.example") + expected = {"title": "标题", "text": None, "image": _IMAGE_URL, + "userid": "member-1", "link": "https://detail.example"} + if native_image: + expected["native_image"] = True + send.assert_called_once_with(**expected) def test_native_image_respects_notification_filter( diff --git a/tests/test_wechatclawbot.py b/tests/test_wechatclawbot.py index 82046107a..dfa6f89b2 100644 --- a/tests/test_wechatclawbot.py +++ b/tests/test_wechatclawbot.py @@ -597,7 +597,7 @@ def test_wechatclawbot_send_file_prefers_image_when_image_file_has_caption(): ) assert result - mock_client.send_text.assert_not_called() + mock_client.send_text.assert_called_once_with(to_user="wxid_user_1", text="图片标题\n\n图片说明", context_token=None) mock_client.send_image_png.assert_called_once_with( to_user="wxid_user_1", image_bytes=b"\x89PNG\r\n\x1a\nfake-png", @@ -630,7 +630,7 @@ def test_wechatclawbot_send_file_prefers_file_when_generic_file_has_caption(): ) assert result - mock_client.send_text.assert_not_called() + mock_client.send_text.assert_called_once_with(to_user="wxid_user_1", text="文件标题\n\n文件说明", context_token=None) mock_client.send_file_bytes.assert_called_once_with( to_user="wxid_user_1", file_bytes=b"plain-text",