68 lines
3.7 KiB
Python
68 lines
3.7 KiB
Python
"""Scoped PMS delivery adapter; never changes platform-wide Feishu credentials."""
|
||
import re
|
||
from uuid import UUID
|
||
|
||
from fastapi import HTTPException
|
||
|
||
from app.modules.feishu.client import FeishuClient
|
||
from app.modules.feishu.constants import FeishuAppType
|
||
from app.modules.feishu.errors import FeishuAPIError
|
||
|
||
|
||
def dispatch_feishu(payload: dict) -> dict:
|
||
app_id = payload.get("app_id")
|
||
secret = payload.get("app_secret")
|
||
operation = payload.get("operation")
|
||
if (not isinstance(app_id, str) or not re.fullmatch(r"cli_[A-Za-z0-9_]{6,100}", app_id)
|
||
or not isinstance(secret, str) or not re.fullmatch(r"[\x21-\x7E]{8,256}", secret)
|
||
or operation not in {"check", "send"}):
|
||
raise HTTPException(400, "飞书应用参数无效")
|
||
if operation == "send":
|
||
receive_type = payload.get("receive_id_type")
|
||
target = payload.get("receive_id")
|
||
patterns = {"email": r"[^\s@<>]{1,100}@[^\s@<>]{1,100}\.[^\s@<>]{2,30}",
|
||
"open_id": r"ou_[A-Za-z0-9_]{6,100}", "user_id": r"[A-Za-z0-9_-]{1,128}"}
|
||
if receive_type not in patterns or not isinstance(target, str) or not re.fullmatch(patterns[receive_type], target):
|
||
raise HTTPException(400, "飞书接收账号无效")
|
||
text = payload.get("text")
|
||
if not isinstance(text, str) or not text.strip() or len(text.encode("utf-8")) > 28000:
|
||
raise HTTPException(400, "飞书消息内容无效或过长")
|
||
try:
|
||
request_id = str(UUID(payload.get("uuid", "")))
|
||
except (ValueError, TypeError, AttributeError):
|
||
raise HTTPException(400, "飞书发送请求编号无效") from None
|
||
|
||
client = FeishuClient()
|
||
# A separate immutable settings copy and fresh token cache for this request.
|
||
client.settings = client.settings.model_copy(update={
|
||
"feishu_app_id": app_id, "feishu_app_secret": secret,
|
||
"feishu_app_type": FeishuAppType.SELF,
|
||
"feishu_base_url": "https://open.feishu.cn/open-apis",
|
||
"feishu_default_chat_id": None, "feishu_default_tenant_key": None,
|
||
})
|
||
phase = "auth"
|
||
try:
|
||
client._get_tenant_access_token()
|
||
if operation == "check":
|
||
return {"ok": True}
|
||
phase = "send"
|
||
response = client.send_text(text, receive_id=target, receive_id_type=receive_type, uuid=request_id)
|
||
message_id = response.get("data", {}).get("message_id")
|
||
if not isinstance(message_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", message_id):
|
||
return {"ok": False, "status": "unknown", "message": "飞书未返回有效消息编号,请先核对收件情况。"}
|
||
return {"ok": True, "message_id": message_id}
|
||
except FeishuAPIError as exc:
|
||
code = str(exc.provider_code) if exc.provider_code is not None else ""
|
||
code_label = f"(错误码 {code})" if re.fullmatch(r"\d{1,12}", code) else ""
|
||
rejected = exc.provider_code is not None or (exc.http_status is not None and 400 <= exc.http_status < 500)
|
||
state = "failed" if phase == "auth" or rejected else "unknown"
|
||
if phase == "auth":
|
||
message = f"飞书凭证检查未通过{code_label},请检查 App ID、App Secret 及网络连接。"
|
||
elif rejected:
|
||
message = f"飞书拒绝发送{code_label},请检查机器人发送权限、应用可用范围和接收账号。"
|
||
else:
|
||
message = "飞书暂未确认发送结果,请先核对收件情况;安全时段内重试将沿用原请求编号。"
|
||
return {"ok": False, "status": state, "message": message}
|
||
except HTTPException:
|
||
return {"ok": False, "status": "failed" if phase == "auth" else "unknown", "message": "飞书连接未完成,请检查应用配置。"}
|