__init__.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. """plugin-matrix-outbound-s3 — 出站媒体从 mxc:// 改走 https://s3.fmode.cn/...
  2. 为什么是插件而不是改 adapter.py:
  3. /opt/hermes 下所有文件属主 root,gateway 进程以 uid=10000(hermes) 运行,
  4. 容器内无 sudo、CapEff=0、无 docker.sock -> 目标容器里没有任何路径能写 adapter.py。
  5. /opt/data 是可写持久卷,插件在 gateway 启动时由 Hermes 加载并调用 register(ctx),
  6. 此时 gateway 里已经有 MatrixAdapter 真类,可以直接替换类方法。
  7. 副作用是:这个 PATCH 落在持久卷上,docker rm + 重建容器也不会丢。
  8. 行为(任务书任务 2):
  9. _upload_and_send 在「非 E2EE」房间不再调 self._client.upload_media(),
  10. 改为上传到 Fmode 对象存储,拿到 https://s3.fmode.cn/deliverables/... 直接写进
  11. msg_content["url"]。事件形态仍是 m.file / m.image,body=文件名,info.mimetype/size 齐全。
  12. 超限文件仍走 _media_too_large;E2EE 分支(_room_needs_encrypted_upload 为真)完全不动,
  13. 仍用 mxc(对端要从事件里派生密钥,这是另一种协议)。
  14. 上传失败返回 SendResult(success=False, error=...),绝不静默回退到 mxc。
  15. 关键:必须拿「运行时真类」(见 skill hermes-plugin-patch-runtime-class)。
  16. /opt/hermes/plugins/ 与 /opt/hermes/gateway/ 是两套独立顶层包,
  17. 按模块名 __import__("plugins.platforms.matrix.adapter") 得到的是影子类,
  18. patch 打在空气里。正确来源顺序:
  19. 1) gateway.platform_registry.platform_registry.get("matrix").adapter_factory
  20. 2) gateway.platforms.base.BasePlatformAdapter 的 __subclasses__() 里名为 MatrixAdapter 的类
  21. 3) sys.modules 里 hermes_plugins.*/gateway.* 模块的 MatrixAdapter(排除 plugins.*)
  22. 并且 bundled 平台是 deferred 注册,插件 register() 跑时真类可能还没 import,
  23. 所以再挂 pre_gateway_dispatch hook 在后续首次分发时补打。
  24. """
  25. from __future__ import annotations
  26. import logging
  27. import re
  28. from typing import Any, Dict, Optional
  29. logger = logging.getLogger(__name__)
  30. _PATCHED_CLASSES: set = set()
  31. _BACKUP: Dict[str, Any] = {}
  32. # ── 一次上传,一个 URL(2026-11-14 用户裁决)──
  33. # 交付物已经由 fmode-deliverable-hook.py 走过平台队列
  34. # (report → enqueueArtifact → pendingArtifacts → PUT → ackArtifact),
  35. # 平台签发的 publicUrl 是唯一权威地址。出站侧**绝不能再上传一次**。
  36. #
  37. # 两个入口:
  38. # 1) MediaRef.preuploaded_url —— 调用方显式带上已签发 url,直接复用。
  39. # 2) 最近 N 秒内 pushed 登记过的本地路径 —— 按 basename 认领同一个 url
  40. # (MEDIA: 行 / 显式 media 路径 都会命中这里)。
  41. PREUPLOADED_TTL_S = 1800
  42. _STATE_DIR = "/opt/data/cache/deliverable-hook"
  43. # ── 2026-11-17 并发止血(step 3):pushed[] 空时短暂二次等待 ──
  44. # 背景:transform hook 与出站 media 投递是两个线程。并发高时 hook 可能刚好落在
  45. # 「状态文件还没落盘」的窗口里,_preuploaded_lookup 立刻判负就报 no-preuploaded-url。
  46. # 这里给 hook 落盘留 1s 余量(5 × 200ms),仍为空才按现状失败。
  47. # ⚠️ 2026-11-14 裁决不变:绝不退回 mxc,只加缓冲。
  48. PREUPLOADED_RETRY_TIMES = 5
  49. PREUPLOADED_RETRY_SLEEP_S = 0.2
  50. # ── 2026-11-17 step 4:basename → 登记项 的内存索引 ──
  51. # 原实现每次 lookup 都 os.listdir + json.load 全目录(150+ 个状态文件),在 40 并发下
  52. # 等于每份附件都要读几十 MB JSON。索引按「文件 mtime_ns + 大小」做缓存键,目录里任一
  53. # 状态文件变化就整表重建(状态文件数量级是百,重建成本可忽略),未变化则 O(1)。
  54. _INDEX_CACHE: Dict[str, Any] = {"sig": None, "map": {}}
  55. def _state_signature() -> tuple:
  56. import os
  57. sig = []
  58. try:
  59. with os.scandir(_STATE_DIR) as it:
  60. for e in it:
  61. if not e.name.endswith(".json"):
  62. continue
  63. try:
  64. st = e.stat()
  65. except OSError:
  66. continue
  67. sig.append((e.name, st.st_mtime_ns, st.st_size))
  68. except OSError:
  69. return ()
  70. sig.sort()
  71. return tuple(sig)
  72. def _build_index() -> Dict[str, list]:
  73. """basename(lower) → [(ts, url, path)],只收 pushed[] 里 http 且带 path 的登记。"""
  74. import json
  75. import os
  76. out: Dict[str, list] = {}
  77. try:
  78. files = os.listdir(_STATE_DIR)
  79. except OSError:
  80. return out
  81. for fn in files:
  82. if not fn.endswith(".json"):
  83. continue
  84. try:
  85. with open(os.path.join(_STATE_DIR, fn), "r", encoding="utf-8") as fh:
  86. st = json.load(fh) or {}
  87. except Exception:
  88. continue
  89. for item in st.get("pushed") or []:
  90. if not isinstance(item, dict):
  91. continue
  92. url = item.get("url") or ""
  93. path = item.get("path") or ""
  94. if not url.startswith("http") or not path:
  95. continue
  96. try:
  97. ts = float(item.get("ts") or 0)
  98. except (TypeError, ValueError):
  99. continue
  100. name = os.path.basename(path).strip().lower()
  101. if name:
  102. out.setdefault(name, []).append((ts, url, path))
  103. return out
  104. def _index() -> Dict[str, list]:
  105. sig = _state_signature()
  106. if _INDEX_CACHE["sig"] != sig:
  107. _INDEX_CACHE["map"] = _build_index()
  108. _INDEX_CACHE["sig"] = sig
  109. logger.debug("matrix-outbound-s3: pushed 索引重建 %d 个文件名", len(_INDEX_CACHE["map"]))
  110. return _INDEX_CACHE["map"]
  111. def _preuploaded_lookup(filename: str, size: int, *, wait: bool = True) -> str:
  112. """按 basename(+size) 在最近 pushed 登记里找现成 https url;找不到返回 ""。
  113. wait=True 时最多重试 PREUPLOADED_RETRY_TIMES 次(每次 PREUPLOADED_RETRY_SLEEP_S),
  114. 给 transform hook 写状态文件留余量 —— 只缓冲,不改变匹配语义。
  115. """
  116. import os
  117. import time
  118. name = os.path.basename(filename or "").strip().lower()
  119. if not name:
  120. return ""
  121. tries = PREUPLOADED_RETRY_TIMES if wait else 1
  122. best, best_ts = "", 0.0
  123. for attempt in range(tries):
  124. now = time.time()
  125. best, best_ts = "", 0.0
  126. for ts, url, path in _index().get(name, ()):
  127. # TTL:只判「太久之前」。原写法 abs() 会把未来时间戳(时钟回拨/跨机写入)也判失效。
  128. if now - ts > PREUPLOADED_TTL_S:
  129. continue
  130. try:
  131. on_disk = os.path.getsize(path)
  132. except OSError:
  133. on_disk = -1
  134. # size 能对上才复用,避免同名不同文件串号
  135. if size and on_disk > 0 and on_disk != size:
  136. continue
  137. if ts >= best_ts:
  138. best, best_ts = url, ts
  139. if best:
  140. break
  141. if attempt + 1 < tries:
  142. time.sleep(PREUPLOADED_RETRY_SLEEP_S)
  143. if best:
  144. logger.info("matrix-outbound-s3: 复用已签发 url(不重传)%s -> %s", name, best)
  145. else:
  146. logger.warning("matrix-outbound-s3: pushed 里没有 %s 的登记(已等待 %d×%gs)",
  147. name, tries, PREUPLOADED_RETRY_SLEEP_S)
  148. return best
  149. def _registered_factory(mod: str, cls: Any) -> bool:
  150. """registry 里的 adapter_factory 是否就是这个类(真类判定)。"""
  151. try:
  152. from gateway.platform_registry import platform_registry
  153. entry = platform_registry.get("matrix")
  154. fac = getattr(entry, "adapter_factory", None) if entry else None
  155. return fac is cls
  156. except Exception:
  157. return False
  158. # ───────────────────── 取运行时真类 ─────────────────────
  159. def _candidate_classes():
  160. """按优先级产出 MatrixAdapter 真类(去重)。
  161. 事实(本机实测):真类模块路径就是 plugins.platforms.matrix.adapter,
  162. 它通过 ctx.register_platform(adapter_factory=MatrixAdapter) 注册,
  163. 所以「模块名前缀是 plugins.」并不能用来判定影子类 —— 必须用 registry 里的
  164. adapter_factory 作为权威来源,其余来源只做补充。
  165. """
  166. seen = set()
  167. def _yield(cls):
  168. if cls is None or cls in seen:
  169. return None
  170. seen.add(cls)
  171. return cls
  172. # 1) platform_registry —— 最权威,gateway 实际用它构造实例
  173. try:
  174. from gateway.platform_registry import platform_registry
  175. entry = platform_registry.get("matrix")
  176. fac = getattr(entry, "adapter_factory", None) if entry else None
  177. if isinstance(fac, type) and fac.__name__ == "MatrixAdapter":
  178. c = _yield(fac)
  179. if c:
  180. yield "platform_registry", c
  181. except Exception as exc:
  182. logger.debug("matrix-outbound-s3: platform_registry 取类失败: %s", exc)
  183. # 2) BasePlatformAdapter 子类树
  184. try:
  185. from gateway.platforms.base import BasePlatformAdapter
  186. stack = [BasePlatformAdapter]
  187. found = []
  188. while stack:
  189. node = stack.pop()
  190. try:
  191. stack.extend(node.__subclasses__())
  192. except Exception:
  193. pass
  194. if node.__name__ == "MatrixAdapter":
  195. found.append(node)
  196. for cls in found:
  197. c = _yield(cls)
  198. if c:
  199. yield "subclasses", c
  200. except Exception as exc:
  201. logger.debug("matrix-outbound-s3: __subclasses__ 取类失败: %s", exc)
  202. # 3) sys.modules 兜底(含 plugins.platforms.matrix.adapter —— 本机实测它就是真类)
  203. try:
  204. import sys as _sys
  205. for modname, mod in list(_sys.modules.items()):
  206. if mod is None:
  207. continue
  208. if not (modname.startswith("plugins.") or modname.startswith("hermes_plugins.")
  209. or modname.startswith("gateway.")):
  210. continue
  211. if "matrix" not in modname:
  212. continue
  213. cls = getattr(mod, "MatrixAdapter", None)
  214. if isinstance(cls, type) and cls.__name__ == "MatrixAdapter":
  215. c = _yield(cls)
  216. if c:
  217. yield "sys.modules:%s" % modname, c
  218. except Exception as exc:
  219. logger.debug("matrix-outbound-s3: sys.modules 扫类失败: %s", exc)
  220. # ───────────────────── 上传到对象存储(已停用)─────────────────────
  221. # 🔴 2026-11-14 用户裁决:全链路只允许一个上传点 —— fmode-deliverable-hook.py。
  222. # 本函数保留仅作回滚参考,**任何代码路径都不再调用它**;
  223. # _upload_and_send 的明文分支改为只查 pushed[],查不到即 return _fail("no-preuploaded-url")。
  224. # 恢复方式:把上面的 else 分支改回调用本函数,并恢复
  225. # MatrixAdapter._upload_media_to_object_storage = _upload_media_to_object_storage
  226. def _legacy_upload_media_to_object_storage(self, data: bytes, filename: str, content_type: str) -> str:
  227. """[已停用] 上传到 Fmode 对象存储,返回 https CDN 地址。失败抛异常(不回退 mxc)。"""
  228. import asyncio
  229. import sys as _sys
  230. if "/opt/data/scripts" not in _sys.path:
  231. _sys.path.insert(0, "/opt/data/scripts")
  232. from fmode_outbound_media import upload_bytes # 预签名 PUT + md5 回读
  233. url = asyncio.to_thread(
  234. upload_bytes, data, filename or "media.bin", content_type or "", filename or "")
  235. return str(url)
  236. # ───────────────────── 入站:只接受 https 云盘直链(2026-11-14 用户裁决)─────────────────────
  237. # 用户裁决原文:「严格禁止退回模式,只能有 s3 的模式。如果失败给出提示」。
  238. # 现状(改前):_is_allowed_media_url 对 mxc:// 一律放行 → 入站存在两条并存通道
  239. # (mxc:// 走 homeserver 中转 + https:// 直读 s3),闸门是二选一白名单。
  240. # 改后:mxc:// 一律拒绝,且必须回一条消息告诉用户,不许静默丢弃。
  241. #
  242. # 为什么改入站要包 _handle_media_message 而不是只改 _is_allowed_media_url:
  243. # _is_allowed_media_url 是模块级函数,可能被多处引用;改它会影响出站与
  244. # _fetch_http_media 的语义。_handle_media_message 是唯一的入站媒体入口
  245. # (adapter.py:2024 调用),在这里包一层最精确:拦截 + 回复 + 超限提示。
  246. _MAX_MEDIA_BYTES = 800 * 1024 * 1024
  247. def _inbound_max_bytes(self) -> int:
  248. """入站/出站共用的上限:优先 env,退回 800MB。"""
  249. import os
  250. try:
  251. return int(getattr(self, "_max_media_bytes", 0)
  252. or os.environ.get("MATRIX_MAX_MEDIA_BYTES")
  253. or _MAX_MEDIA_BYTES)
  254. except (TypeError, ValueError):
  255. return _MAX_MEDIA_BYTES
  256. async def _notify_user_blocked(self, room_id: str, text: str) -> None:
  257. """给用户回一条失败提示。绝不抛异常(提示失败不能影响主流程)。
  258. 带 ``fmode.kind=notice``:App 端据此把这条渲染成系统提示而不是正文回复。
  259. ``_send_content_event`` 只透传 msgtype/body,所以 kind 必须自己拼进 msg_content。
  260. """
  261. try:
  262. await self._send_content_event(
  263. room_id, {"msgtype": "m.text", "body": text, "fmode.kind": "notice"})
  264. logger.info("matrix-outbound-s3: 已回复用户提示: %s", text)
  265. except Exception as exc:
  266. logger.error("matrix-outbound-s3: 回复用户提示失败: %s", exc)
  267. # ───────────────────── 出站失败提示:中文,一条失败一条提示 ─────────────────────
  268. # 改前行为(两条英文提示,用户看不懂且可能重复):
  269. # 1) base._deliver_media_attachments 在 send_* 返回 success=False 后调
  270. # _notify_media_delivery_failure → "⚠️ Couldn't deliver the file attachment (x.pdf)."
  271. # 2) matrix._send_local_file 发现本地路径不存在时自己 emit_media_warning →
  272. # "⚠️ Couldn't deliver the attachment."
  273. # 改后:两条都换成中文(「未能在对话内直接发送,请使用上方已上云链接」),
  274. # 且按 (room, basename) 在同一次投递里只提示一次 —— base 那层已经发过,matrix 这层就不再重复。
  275. _NOTICED: Dict[str, float] = {}
  276. _NOTICE_DEDUP_S = 120.0
  277. _FILE_MSG_RE = re.compile(r"^\s*m\.file\s*:", re.M)
  278. def _notice_once(room_id: str, key: str) -> bool:
  279. """同一次投递只提示一次。返回 True 表示「该发」,False 表示「刚发过,跳过」。"""
  280. import time
  281. sig = "%s|%s" % (room_id, key)
  282. now = time.time()
  283. for k in [k for k, ts in _NOTICED.items() if now - ts > _NOTICE_DEDUP_S]:
  284. _NOTICED.pop(k, None)
  285. last = _NOTICED.get(sig)
  286. if last is not None and now - last <= _NOTICE_DEDUP_S:
  287. logger.info("matrix-outbound-s3: 跳过重复失败提示 %s(%ds 内已提示)", sig, int(now - last))
  288. return False
  289. _NOTICED[sig] = now
  290. return True
  291. def _delivery_failure_text(media_path: str) -> str:
  292. """中文失败提示。只用 basename —— 绝不把容器本地路径透给用户。"""
  293. import os
  294. name = os.path.basename(str(media_path or "").rstrip("/")) or "附件"
  295. return ("⚠️ 文件「%s」未能在对话内直接发送,请使用上方「已上云」链接下载。" % name)
  296. def _make_inbound_guard(orig):
  297. """包住原 _handle_media_message:mxc 拒绝 + 超限提示。"""
  298. async def _handle_media_message(self, room_id, sender, event_id, event_ts,
  299. source_content, relates_to, msgtype):
  300. body = (source_content or {}).get("body") or ""
  301. url = (source_content or {}).get("url") or ""
  302. file_content = (source_content or {}).get("file")
  303. if not url and isinstance(file_content, dict):
  304. url = file_content.get("url") or ""
  305. # 规则 1:只允许 https 云盘直链,mxc:// 一律拒绝并回复
  306. if isinstance(url, str) and url.startswith("mxc://"):
  307. logger.warning("matrix-outbound-s3: REJECT inbound mxc(附件只允许云盘直链): %s", url)
  308. await _notify_user_blocked(
  309. self, room_id,
  310. "⚠️ 收到的附件「%s」不是云盘直链(mxc:// 已停用),已拒绝接收。"
  311. "请让 App 重新发送。" % (body or "未命名"))
  312. return None
  313. # 规则 2:入站超限必须提示,不许静默丢弃
  314. info = (source_content or {}).get("info")
  315. size = 0
  316. if isinstance(info, dict):
  317. try:
  318. size = int(info.get("size") or 0)
  319. except (TypeError, ValueError):
  320. size = 0
  321. limit = _inbound_max_bytes(self)
  322. if size and size > limit:
  323. logger.warning("matrix-outbound-s3: REJECT oversized inbound: %s (%d bytes)", body, size)
  324. await _notify_user_blocked(
  325. self, room_id,
  326. "⚠️ 附件「%s」有 %.1f MB,超过 %dMB 上限,未接收。"
  327. % (body or "未命名", size / 1048576.0, limit // 1048576))
  328. return None
  329. return await orig(self, room_id, sender, event_id, event_ts,
  330. source_content, relates_to, msgtype)
  331. _handle_media_message._fmode_inbound_guard = True
  332. return _handle_media_message
  333. # ───────────────────── 打补丁 ─────────────────────
  334. def _install_patch() -> int:
  335. """把新实现挂到所有能拿到的 MatrixAdapter 真类上。返回本次新打上的类数。"""
  336. patched_now = 0
  337. for source, MatrixAdapter in _candidate_classes():
  338. if MatrixAdapter in _PATCHED_CLASSES:
  339. continue
  340. mod = getattr(MatrixAdapter, "__module__", "?")
  341. # 本机实测真类模块名就是 plugins.platforms.matrix.adapter,
  342. # 所以不能靠 "plugins." 前缀判定影子类。判定顺序:
  343. # registry 认它 -> 真类;registry 无 entry 但来自子类树 -> 真类;
  344. # 否则视为影子实例跳过。
  345. if mod.startswith("plugins.") and not (_registered_factory(mod, MatrixAdapter)
  346. or source.startswith("subclasses")):
  347. logger.debug("matrix-outbound-s3: 跳过影子类 %s.%s", mod, MatrixAdapter.__name__)
  348. continue
  349. try:
  350. SendResult = None
  351. for cand in (mod, "gateway.platforms.base", "gateway.platforms._shared"):
  352. try:
  353. m = __import__(cand, fromlist=["SendResult"])
  354. SendResult = getattr(m, "SendResult", None)
  355. if SendResult is not None:
  356. break
  357. except Exception:
  358. continue
  359. if SendResult is None:
  360. logger.warning("matrix-outbound-s3: 找不到 SendResult,跳过 %s", mod)
  361. continue
  362. _BACKUP[mod] = {
  363. "upload_and_send": MatrixAdapter.__dict__.get("_upload_and_send"),
  364. }
  365. def _fail(err):
  366. return SendResult(success=False, error=str(err))
  367. async def _upload_and_send(
  368. self, room_id: str, data: bytes, filename: str, content_type: str, msgtype: str,
  369. caption: Optional[str] = None, reply_to: Optional[str] = None,
  370. metadata: Optional[Dict[str, Any]] = None,
  371. is_voice: bool = False, voice_metadata: Optional[Dict[str, Any]] = None,
  372. ):
  373. if len(data) > _inbound_max_bytes(self):
  374. return self._media_too_large(len(data))
  375. # 🔴 2026-11-14 用户裁决:只有 s3 一条路。
  376. # E2EE 房间的 mxc 分支已删除(本项目不使用 E2EE 房间,
  377. # needs_encrypted 这条永远走不到,留着只会误导)。
  378. # 现在无论房间是否加密,都只认「已签发 https 云盘直链」。
  379. # ⚠️ 索引里有磁盘 stat,且空命中时要最多等 1s(step 3 缓冲)——
  380. # 本函数是 async def,绝不能在事件循环里同步 sleep/读盘,丢到线程里跑。
  381. import asyncio as _aio
  382. media_url = await _aio.to_thread(_preuploaded_lookup, filename, len(data))
  383. if not media_url:
  384. logger.error(
  385. "matrix-outbound-s3: FAIL outbound: 没有可用的云盘直链(filename=%s size=%d)。"
  386. "交付物必须先由 fmode-deliverable-hook.py 上传并写入 pushed[],"
  387. "本插件不再自行上传,也不回退 mxc(2026-11-14 用户裁决)。",
  388. filename, len(data))
  389. return _fail("no-preuploaded-url")
  390. msg_content: Dict[str, Any] = {
  391. "msgtype": msgtype, "body": caption or filename,
  392. "info": {"mimetype": content_type, "size": len(data)}}
  393. msg_content["url"] = media_url
  394. if is_voice: # MSC3245 native voice flag + MSC1767 audio metadata
  395. msg_content["org.matrix.msc3245.voice"] = {}
  396. audio_metadata = {
  397. k: v for k in ("duration", "waveform")
  398. if (v := (voice_metadata or {}).get(k)) is not None}
  399. if "duration" in audio_metadata:
  400. msg_content["info"]["duration"] = audio_metadata["duration"]
  401. if audio_metadata:
  402. msg_content["org.matrix.msc1767.audio"] = audio_metadata
  403. self._apply_relation_metadata(msg_content, reply_to=reply_to, metadata=metadata)
  404. return await self._send_content_event(room_id, msg_content)
  405. # 入站闸门:只收 https 云盘直链;mxc:// 与超限都回复用户(不静默)
  406. orig_inbound = getattr(MatrixAdapter, "_handle_media_message", None)
  407. if orig_inbound is not None and not getattr(orig_inbound, "_fmode_inbound_guard", False):
  408. MatrixAdapter._handle_media_message = _make_inbound_guard(orig_inbound)
  409. logger.info("matrix-outbound-s3: PATCHED _handle_media_message"
  410. "(mxc 拒绝 + 超限提示,来源=%s)", mod)
  411. elif orig_inbound is None:
  412. logger.warning("matrix-outbound-s3: %s 无 _handle_media_message,入站闸门未装", mod)
  413. MatrixAdapter._upload_and_send = _upload_and_send
  414. # ── 出站失败提示改中文(只打 Matrix 真类,不碰 BasePlatformAdapter,
  415. # 确保不影响 Discord/Slack 等其它平台)──
  416. # ① base._deliver_media_attachments 调的那条:send_* 返回 success=False 后通知用户
  417. base_notify = getattr(MatrixAdapter, "_notify_media_delivery_failure", None)
  418. if base_notify is not None and not getattr(base_notify, "_fmode_cn_notice", False):
  419. async def _notify_media_delivery_failure_cn(
  420. self, chat_id: str, media_path: str, *, is_voice: bool = False,
  421. metadata: Optional[Dict[str, Any]] = None, _orig=base_notify,
  422. ) -> None:
  423. import os as _os
  424. name = _os.path.basename(str(media_path or "")) or "附件"
  425. if not _notice_once(chat_id, name):
  426. return
  427. logger.warning("matrix-outbound-s3: 出站媒体投递失败,已中文提示: %s", name)
  428. await _notify_user_blocked(self, chat_id, _delivery_failure_text(media_path))
  429. _notify_media_delivery_failure_cn._fmode_cn_notice = True
  430. MatrixAdapter._notify_media_delivery_failure = _notify_media_delivery_failure_cn
  431. logger.info("matrix-outbound-s3: PATCHED _notify_media_delivery_failure(中文提示)")
  432. # ② matrix._send_local_file 里「路径不存在」那条独立提示(adapter.py 原文
  433. # "⚠️ Couldn't deliver the attachment."),同样换成中文,并用同一把去重锁。
  434. orig_send_local = getattr(MatrixAdapter, "_send_local_file", None)
  435. if orig_send_local is not None and not getattr(orig_send_local, "_fmode_cn_notice", False):
  436. async def _send_local_file_cn(self, room_id, file_path, msgtype, caption=None,
  437. reply_to=None, file_name=None, metadata=None,
  438. is_voice=False):
  439. from pathlib import Path as _Path
  440. p = _Path(file_path).expanduser()
  441. if not p.exists():
  442. name = file_name or _Path(str(file_path)).name or "附件"
  443. logger.warning("[%s] 出站媒体本地缺失,走中文提示: %s", self.name, file_path)
  444. if _FILE_MSG_RE.match(str(msgtype or "")) and not _notice_once(room_id, name):
  445. # base 层已经为这个名字发过提示(m.file 走 _deliver_media_attachments),
  446. # 这里不再重复,直接返回失败凭据。
  447. return SendResult(success=False, error="no-preuploaded-url")
  448. r = await self.emit_media_warning(
  449. room_id, _delivery_failure_text(str(file_path)),
  450. caption=None, reply_to=reply_to, metadata=metadata)
  451. return r if r is not None else SendResult(
  452. success=False, error=_delivery_failure_text(str(file_path)))
  453. return await orig_send_local(
  454. self, room_id, file_path, msgtype, caption, reply_to, file_name,
  455. metadata, is_voice)
  456. _send_local_file_cn._fmode_cn_notice = True
  457. MatrixAdapter._send_local_file = _send_local_file_cn
  458. logger.info("matrix-outbound-s3: PATCHED _send_local_file(缺失文件中文提示)")
  459. # 🔴 不再注入 _upload_media_to_object_storage(2026-11-14 用户裁决):
  460. # 往真类上挂一个上传函数,等于给任何调用方留了第二条上传通道。
  461. _PATCHED_CLASSES.add(MatrixAdapter)
  462. patched_now += 1
  463. logger.info(
  464. "matrix-outbound-s3: PATCHED 真类 %s.%s (来源=%s) -> _upload_and_send 只复用 pushed[] 已签发 url",
  465. mod, MatrixAdapter.__name__, source)
  466. except Exception as exc:
  467. logger.warning("matrix-outbound-s3: 打补丁失败 %s.%s: %s", mod, MatrixAdapter.__name__, exc)
  468. return patched_now
  469. def _on_pre_gateway_dispatch(**_: Any):
  470. """兜底:真类可能在插件 register() 之后才 import,首次分发时补打。"""
  471. if not _PATCHED_CLASSES:
  472. n = _install_patch()
  473. if n:
  474. logger.info("matrix-outbound-s3: 兜底 hook 补打 %d 个类", n)
  475. return None
  476. def register(ctx) -> None:
  477. n = _install_patch()
  478. if n:
  479. logger.info("plugin-matrix-outbound-s3 registered (patched=%d 类)", n)
  480. else:
  481. logger.warning("plugin-matrix-outbound-s3 register() 未拿到真类(deferred 注册),"
  482. "依赖 pre_gateway_dispatch 兜底补打")
  483. try:
  484. ctx.register_hook("pre_gateway_dispatch", _on_pre_gateway_dispatch)
  485. logger.info("plugin-matrix-outbound-s3: 已注册 pre_gateway_dispatch 兜底 hook")
  486. except Exception as exc:
  487. logger.warning("plugin-matrix-outbound-s3: 注册兜底 hook 失败: %s", exc)