yuanbao_media.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. """
  2. yuanbao_media.py — 元宝平台媒体处理:COS 上传、URL 下载(SSRF 防护)、TIM 媒体消息体。
  3. 移植自 TypeScript 版 media.ts(yuanbao-openclaw-plugin),用 httpx 替代 cos-nodejs-sdk-v5。
  4. COS 上传流程:genUploadInfo 获取临时凭证 → 临时凭证 HMAC-SHA1 签名 Authorization 头 → HTTP PUT。
  5. TIM 消息体:build_image_msg_body() → TIMImageElem,build_file_msg_body() → TIMFileElem
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import hmac
  10. import logging
  11. import os
  12. import secrets
  13. import struct
  14. import time
  15. import urllib.parse
  16. from typing import Optional, Any
  17. import httpx
  18. logger = logging.getLogger(__name__)
  19. UPLOAD_INFO_PATH = "/api/resource/genUploadInfo"
  20. DEFAULT_API_DOMAIN = "yuanbao.tencent.com"
  21. DEFAULT_MAX_SIZE_MB = 50
  22. # MIME → image_format 数字(TIM 协议字段)
  23. _MIME_TO_IMAGE_FORMAT: dict[str, int] = {
  24. "image/jpeg": 1, "image/jpg": 1, "image/gif": 2, "image/png": 3, "image/bmp": 4,
  25. "image/webp": 255, "image/heic": 255, "image/tiff": 255,
  26. }
  27. _EXT_TO_MIME: dict[str, str] = {
  28. ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp",
  29. ".bmp": "image/bmp", ".heic": "image/heic", ".tiff": "image/tiff", ".ico": "image/x-icon",
  30. ".pdf": "application/pdf",
  31. ".doc": "application/msword",
  32. ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  33. ".xls": "application/vnd.ms-excel",
  34. ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  35. ".ppt": "application/vnd.ms-powerpoint",
  36. ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  37. ".txt": "text/plain", ".zip": "application/zip", ".tar": "application/x-tar", ".gz": "application/gzip",
  38. ".mp3": "audio/mpeg", ".mp4": "video/mp4", ".wav": "audio/wav", ".ogg": "audio/ogg", ".webm": "video/webm",
  39. }
  40. _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".heic", ".tiff", ".ico"}
  41. def _ext(filename: str) -> str:
  42. return os.path.splitext(filename)[-1].lower()
  43. def guess_mime_type(filename: str) -> str:
  44. return _EXT_TO_MIME.get(_ext(filename), "application/octet-stream")
  45. def is_image(filename: str, mime_type: str = "") -> bool:
  46. """MIME 前缀或扩展名判断是否为图片。"""
  47. return mime_type.startswith("image/") or _ext(filename) in _IMAGE_EXTS
  48. def get_image_format(mime_type: str) -> int:
  49. """TIM 图片格式编号(未知 → 255)。"""
  50. return _MIME_TO_IMAGE_FORMAT.get(mime_type.lower(), 255)
  51. def md5_hex(data: bytes) -> str:
  52. return hashlib.md5(data).hexdigest()
  53. def generate_file_id() -> str:
  54. """随机文件 ID(32 位 hex)。"""
  55. return secrets.token_hex(16)
  56. # ============ 图片尺寸解析(纯 Python,无需 Pillow) ============
  57. def _wh(w: int, h: int) -> dict[str, int]:
  58. return {"width": w, "height": h}
  59. def _parse_png_size(buf: bytes) -> Optional[dict[str, int]]:
  60. if len(buf) < 24 or buf[:4] != b"\x89PNG":
  61. return None
  62. return _wh(*struct.unpack(">II", buf[16:24]))
  63. def _parse_jpeg_size(buf: bytes) -> Optional[dict[str, int]]:
  64. if len(buf) < 4 or buf[:2] != b"\xff\xd8":
  65. return None
  66. i = 2
  67. while i < len(buf) - 9:
  68. if buf[i] != 0xFF:
  69. i += 1
  70. elif buf[i + 1] in {0xC0, 0xC2}: # SOF0 / SOF2: height then width
  71. h, w = struct.unpack(">HH", buf[i + 5: i + 9])
  72. return _wh(w, h)
  73. elif i + 3 < len(buf):
  74. i += 2 + struct.unpack(">H", buf[i + 2: i + 4])[0]
  75. else:
  76. break
  77. return None
  78. def _parse_gif_size(buf: bytes) -> Optional[dict[str, int]]:
  79. if len(buf) < 10 or buf[:6] not in (b"GIF87a", b"GIF89a"):
  80. return None
  81. return _wh(*struct.unpack("<HH", buf[6:10]))
  82. def _parse_webp_size(buf: bytes) -> Optional[dict[str, int]]:
  83. if len(buf) < 16 or buf[:4] != b"RIFF" or buf[8:12] != b"WEBP":
  84. return None
  85. chunk = buf[12:16]
  86. if chunk == b"VP8 " and len(buf) >= 30 and buf[23:26] == b"\x9d\x01\x2a":
  87. w, h = struct.unpack("<HH", buf[26:30])
  88. return _wh(w & 0x3FFF, h & 0x3FFF)
  89. if chunk == b"VP8L" and len(buf) >= 25 and buf[20] == 0x2F:
  90. bits = struct.unpack("<I", buf[21:25])[0]
  91. return _wh((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)
  92. if chunk == b"VP8X" and len(buf) >= 30:
  93. return _wh(int.from_bytes(buf[24:27], "little") + 1, int.from_bytes(buf[27:30], "little") + 1)
  94. return None
  95. def parse_image_size(data: bytes) -> Optional[dict[str, int]]:
  96. """解析图片宽高(JPEG/PNG/GIF/WebP),返回 {"width", "height"} 或 None。"""
  97. return _parse_png_size(data) or _parse_jpeg_size(data) or _parse_gif_size(data) or _parse_webp_size(data)
  98. # ============ URL 下载 ============
  99. async def download_url(url: str, max_size_mb: int = DEFAULT_MAX_SIZE_MB) -> tuple[bytes, str]:
  100. """下载 URL 内容,返回 (bytes, content_type)。
  101. Raises:
  102. ValueError: 内容超过 max_size_mb,或 URL / 重定向目标被 SSRF 防护拦截
  103. httpx.HTTPError: 网络/HTTP 错误
  104. """
  105. # SSRF protection: yuanbao downloads model-supplied and inbound URLs server-side.
  106. # Reject private/internal targets up front, and re-validate every redirect hop so a
  107. # public URL can't 302 to http://169.254.169.254/.
  108. from tools.url_safety import create_ssrf_safe_async_client, is_safe_url
  109. if not is_safe_url(url):
  110. raise ValueError(f"Blocked unsafe URL (SSRF protection): {url}")
  111. async def _redirect_guard(response: httpx.Response) -> None:
  112. if response.is_redirect and response.next_request:
  113. redirect_url = str(response.next_request.url)
  114. if not is_safe_url(redirect_url):
  115. raise ValueError(f"Blocked redirect to private/internal address: {redirect_url}")
  116. max_bytes = max_size_mb * 1024 * 1024
  117. async with create_ssrf_safe_async_client(
  118. timeout=30.0, follow_redirects=True, event_hooks={"response": [_redirect_guard]},
  119. ) as client:
  120. try: # HEAD 预检大小;部分服务器不支持 HEAD,忽略
  121. head = await client.head(url)
  122. content_length = int(head.headers.get("content-length", 0) or 0)
  123. if content_length > 0 and content_length > max_bytes:
  124. raise ValueError(f"文件过大: {content_length / 1024 / 1024:.1f} MB > {max_size_mb} MB")
  125. except httpx.HTTPStatusError:
  126. pass
  127. async with client.stream("GET", url) as resp: # 流式 GET,防止超限
  128. resp.raise_for_status()
  129. content_type = resp.headers.get("content-type", "").split(";")[0].strip()
  130. chunks: list[bytes] = []
  131. downloaded = 0
  132. async for chunk in resp.aiter_bytes(65536):
  133. downloaded += len(chunk)
  134. if downloaded > max_bytes:
  135. raise ValueError(f"文件过大: 已超过 {max_size_mb} MB 限制")
  136. chunks.append(chunk)
  137. return b"".join(chunks), content_type
  138. # ============ COS 鉴权(HMAC-SHA1) ============
  139. def _hmac_sha1_hex(key: str, msg: str) -> str:
  140. return hmac.new(key.encode("utf-8"), msg.encode("utf-8"), hashlib.sha1).hexdigest()
  141. def _sorted_kv(d: dict[str, str]) -> list[tuple[str, str]]:
  142. """签名用 (小写 key, URL-encoded value) 按字典序排列"""
  143. return sorted((k.lower(), urllib.parse.quote(str(v), safe="")) for k, v in d.items())
  144. def _cos_sign(
  145. method: str, path: str, params: dict[str, str], headers: dict[str, str], secret_id: str, secret_key: str,
  146. start_time: Optional[int] = None, expire_seconds: int = 3600,
  147. ) -> str:
  148. """COS Authorization 头(q-sign-algorithm=sha1;https://cloud.tencent.com/document/product/436/7778)。
  149. method 小写、path 已 URL-encode;params / headers 的 key 会被小写;secret_* 为临时 tmpSecretId/Key;
  150. start_time 默认 now。
  151. """
  152. start = start_time or int(time.time())
  153. q_sign_time = f"{start};{start + expire_seconds}"
  154. sign_key = _hmac_sha1_hex(secret_key, q_sign_time) # SignKey = HMAC-SHA1(SecretKey, q-sign-time)
  155. sorted_params = _sorted_kv(params)
  156. sorted_headers = _sorted_kv(headers)
  157. kv = lambda pairs: "&".join(f"{k}={v}" for k, v in pairs)
  158. http_string = "\n".join([method.lower(), path, kv(sorted_params), kv(sorted_headers), ""])
  159. string_to_sign = "\n".join(["sha1", q_sign_time, hashlib.sha1(http_string.encode("utf-8")).hexdigest(), ""])
  160. return (
  161. f"q-sign-algorithm=sha1&q-ak={secret_id}&q-sign-time={q_sign_time}&q-key-time={q_sign_time}"
  162. f"&q-header-list={';'.join(k for k, _ in sorted_headers)}"
  163. f"&q-url-param-list={';'.join(k for k, _ in sorted_params)}"
  164. f"&q-signature={_hmac_sha1_hex(sign_key, string_to_sign)}"
  165. )
  166. # ============ 主要公开 API ============
  167. async def get_cos_credentials(
  168. app_key: str, api_domain: str, token: str, filename: str = "file", file_id: Optional[str] = None,
  169. bot_id: str = "", route_env: str = "",
  170. ) -> dict:
  171. """调用 genUploadInfo 获取 COS 临时密钥及上传配置。
  172. X-ID 头取 bot_id(优先)或 app_key;api_domain 如 https://bot.yuanbao.tencent.com;file_id 不传则自动生成。
  173. 返回接口 data dict:bucketName, region, location (COS key), encryptTmpSecretId, encryptTmpSecretKey,
  174. encryptToken, startTime, expiredTime, resourceUrl, resourceID(可选)。
  175. Raises RuntimeError: 接口返回非 0 code 或 bucketName/location 缺失
  176. """
  177. headers = {"Content-Type": "application/json", "X-Token": token, "X-ID": bot_id or app_key, "X-Source": "web"}
  178. if route_env:
  179. headers["X-Route-Env"] = route_env
  180. body = {"fileName": filename, "fileId": file_id if file_id is not None else generate_file_id(), "docFrom": "localDoc", "docOpenId": ""}
  181. async with httpx.AsyncClient(timeout=15.0) as client:
  182. resp = await client.post(f"{api_domain.rstrip('/')}{UPLOAD_INFO_PATH}", json=body, headers=headers)
  183. resp.raise_for_status()
  184. result: dict[str, Any] = resp.json()
  185. code = result.get("code")
  186. if code != 0 and code is not None:
  187. raise RuntimeError(f"genUploadInfo 失败: code={code}, msg={result.get('msg', '')}")
  188. data = result.get("data") or result
  189. missing = [f for f in ["bucketName", "location"] if not data.get(f)]
  190. if missing:
  191. raise RuntimeError(f"genUploadInfo 返回字段不完整: 缺少字段 {missing}")
  192. return data
  193. async def upload_to_cos(
  194. file_bytes: bytes, filename: str, content_type: str, credentials: dict, bucket: str, region: str,
  195. ) -> dict:
  196. """用临时凭证(get_cos_credentials() 返回的 dict)HMAC-SHA1 签名,httpx PUT 上传到 COS(走全球加速域名)。
  197. Returns {url, uuid (内容 MD5), size, width?, height? (仅图片)}
  198. Raises httpx.HTTPStatusError(COS 非 2xx)/ RuntimeError(credentials 字段缺失)
  199. """
  200. secret_id, secret_key, session_token, cos_key = (
  201. credentials.get(k, "") for k in ("encryptTmpSecretId", "encryptTmpSecretKey", "encryptToken", "location")
  202. )
  203. start_time: Optional[int] = credentials.get("startTime")
  204. expired_time: Optional[int] = credentials.get("expiredTime")
  205. if not secret_id or not secret_key or not cos_key:
  206. raise RuntimeError(
  207. f"COS credentials 不完整: secretId={bool(secret_id)}, secretKey={bool(secret_key)}, location={bool(cos_key)}"
  208. )
  209. cos_host = f"{bucket}.cos.accelerate.myqcloud.com"
  210. encoded_key = urllib.parse.quote(cos_key, safe="/").lstrip("/")
  211. cos_url = f"https://{cos_host}/{encoded_key}"
  212. if not content_type or content_type == "application/octet-stream":
  213. content_type = guess_mime_type(filename) if is_image(filename) else "application/octet-stream"
  214. file_size = len(file_bytes)
  215. now = int(time.time())
  216. authorization = _cos_sign(
  217. method="put", path=f"/{encoded_key}", params={},
  218. headers={"host": cos_host, "content-type": content_type, "x-cos-security-token": session_token},
  219. secret_id=secret_id, secret_key=secret_key,
  220. start_time=start_time if start_time else now,
  221. expire_seconds=(expired_time - now) if expired_time and expired_time > now else 3600,
  222. )
  223. put_headers = {"Authorization": authorization, "Content-Type": content_type, "x-cos-security-token": session_token}
  224. logger.info("COS PUT: bucket=%s region=%s key=%s size=%d mime=%s", bucket, region, cos_key, file_size, content_type)
  225. async with httpx.AsyncClient(timeout=120.0) as client:
  226. resp = await client.put(cos_url, content=file_bytes, headers=put_headers)
  227. resp.raise_for_status()
  228. result: dict[str, Any] = {"url": credentials.get("resourceUrl", "") or cos_url, "uuid": md5_hex(file_bytes), "size": file_size}
  229. if content_type.startswith("image/"):
  230. result.update(parse_image_size(file_bytes) or {})
  231. logger.info("COS 上传成功: url=%s size=%d", result["url"], file_size)
  232. return result
  233. # ============ TIM 媒体消息构建(https://cloud.tencent.com/document/product/269/2720) ============
  234. def build_image_msg_body(
  235. url: str, uuid: Optional[str] = None, filename: Optional[str] = None, size: int = 0, width: int = 0,
  236. height: int = 0, mime_type: str = "",
  237. ) -> list[dict]:
  238. """TIMImageElem 消息体(可直接放入 msg_body)。uuid 缺省依次退到 filename / URL basename / "image"。"""
  239. return [{
  240. "msg_type": "TIMImageElem",
  241. "msg_content": {
  242. "uuid": uuid or filename or _basename_from_url(url) or "image",
  243. "image_format": get_image_format(mime_type) if mime_type else 255,
  244. "image_info_array": [{"type": 1, "size": size, "width": width, "height": height, "url": url}], # type 1 = 原图
  245. },
  246. }]
  247. def build_file_msg_body(url: str, filename: str, uuid: Optional[str] = None, size: int = 0) -> list[dict]:
  248. """TIMFileElem 消息体(可直接放入 msg_body)。uuid 缺省使用 filename。"""
  249. return [{
  250. "msg_type": "TIMFileElem",
  251. "msg_content": {"uuid": uuid or filename, "file_name": filename, "file_size": size, "url": url},
  252. }]
  253. def _basename_from_url(url: str) -> str:
  254. try:
  255. return os.path.basename(urllib.parse.urlparse(url).path)
  256. except Exception:
  257. return ""