319 lines
11 KiB
Python
319 lines
11 KiB
Python
"""
|
||
backend/app/services/integrations/wecom/notify.py
|
||
|
||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime, timedelta
|
||
from io import BytesIO
|
||
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
|
||
import uuid
|
||
|
||
import requests
|
||
from flask import current_app
|
||
|
||
from app import db
|
||
from app.models import User, WecomNotifyAudit
|
||
|
||
|
||
_TOKEN_CACHE = {
|
||
'token': None,
|
||
'expires_at': None,
|
||
}
|
||
|
||
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||
_TEXT_CARD_TITLE_LIMIT = 120
|
||
# 账号与权限通知不是智能体推送,标题不加来源。
|
||
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||
'password_reset',
|
||
'permission_batch_updated',
|
||
'permission_request_approved',
|
||
'permission_request_rejected',
|
||
})
|
||
|
||
|
||
def _get_enabled_events() -> set[str]:
|
||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||
if isinstance(raw, str):
|
||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||
if isinstance(raw, (list, tuple, set)):
|
||
return {str(x).strip() for x in raw if str(x).strip()}
|
||
return set()
|
||
|
||
|
||
def _get_notify_base_url() -> str:
|
||
"""
|
||
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
|
||
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
|
||
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
|
||
Returns:
|
||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||
"""
|
||
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||
raw = current_app.config.get(key)
|
||
if isinstance(raw, str) and raw.strip():
|
||
return raw.strip().rstrip('/')
|
||
return ''
|
||
|
||
|
||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||
base = _get_notify_base_url()
|
||
if not base:
|
||
return ''
|
||
base = base.rstrip('/')
|
||
if not path.startswith('/'):
|
||
path = f'/{path}'
|
||
merged = {'wecom_trace': trace_id}
|
||
if params:
|
||
merged.update({k: v for k, v in params.items() if v is not None})
|
||
return f'{base}{path}?{urlencode(merged)}'
|
||
|
||
|
||
def _get_access_token() -> str:
|
||
now = datetime.utcnow()
|
||
token = _TOKEN_CACHE.get('token')
|
||
expires_at = _TOKEN_CACHE.get('expires_at')
|
||
if token and expires_at and now < expires_at:
|
||
return token
|
||
|
||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||
secret = current_app.config.get('WECOM_SECRET')
|
||
resp = requests.get(
|
||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||
params={'corpid': corp_id, 'corpsecret': secret},
|
||
timeout=8,
|
||
)
|
||
data = resp.json()
|
||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
||
|
||
_TOKEN_CACHE['token'] = data['access_token']
|
||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||
return data['access_token']
|
||
|
||
|
||
def _create_audit(
|
||
event_type: str,
|
||
user: User,
|
||
title: str,
|
||
content: str,
|
||
trace_id: str,
|
||
) -> WecomNotifyAudit:
|
||
audit = WecomNotifyAudit(
|
||
event_type=event_type,
|
||
status='failed',
|
||
trace_id=trace_id,
|
||
user_id=user.id if user else None,
|
||
username=user.username if user else None,
|
||
wecom_userid=user.wecom_userid if user else None,
|
||
title=title,
|
||
content=content,
|
||
)
|
||
db.session.add(audit)
|
||
return audit
|
||
|
||
|
||
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
|
||
token = _get_access_token()
|
||
url = (
|
||
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
|
||
f'?access_token={token}&type=file'
|
||
)
|
||
resp = requests.post(
|
||
url,
|
||
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
|
||
timeout=30,
|
||
)
|
||
data = resp.json()
|
||
if data.get('errcode', 0) != 0 or not data.get('media_id'):
|
||
raise RuntimeError(f"WeCom media upload failed: {data}")
|
||
return data['media_id']
|
||
|
||
|
||
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||
token = _get_access_token()
|
||
payload = {
|
||
'touser': wecom_userid,
|
||
'msgtype': 'file',
|
||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||
'file': {'media_id': media_id},
|
||
'safe': 0,
|
||
}
|
||
resp = requests.post(
|
||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||
params={'access_token': token},
|
||
json=payload,
|
||
timeout=8,
|
||
)
|
||
return resp.json()
|
||
|
||
|
||
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||
"""
|
||
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||
|
||
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||
Args:
|
||
title: 业务侧传入的卡片标题。
|
||
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||
Returns:
|
||
实际发给企业微信的标题。
|
||
"""
|
||
text = (title or '').strip()
|
||
if not enabled:
|
||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||
|
||
|
||
def send_wecom_textcard_message(
|
||
wecom_userid: str,
|
||
title: str,
|
||
description: str,
|
||
jump_url: str,
|
||
*,
|
||
with_agent_source: bool = True,
|
||
) -> dict:
|
||
"""
|
||
发送企业微信文本卡片。
|
||
|
||
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||
Args:
|
||
wecom_userid: 企业微信 userid。
|
||
title: 业务标题。
|
||
description: 卡片正文。
|
||
jump_url: 点击跳转地址。
|
||
with_agent_source: 为 False 时标题不加来源。
|
||
Returns:
|
||
企业微信 message/send 的 JSON 响应。
|
||
"""
|
||
token = _get_access_token()
|
||
payload = {
|
||
'touser': wecom_userid,
|
||
'msgtype': 'textcard',
|
||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||
'textcard': {
|
||
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||
'description': (description or '')[:1024],
|
||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||
'btntxt': '查看详情',
|
||
},
|
||
'safe': 0,
|
||
}
|
||
resp = requests.post(
|
||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||
params={'access_token': token},
|
||
json=payload,
|
||
timeout=8,
|
||
)
|
||
return resp.json()
|
||
|
||
|
||
def _append_query_param(url: str, key: str, value: str) -> str:
|
||
"""
|
||
向 URL 追加单个 query 参数,保留已有参数。
|
||
@param url: 原始 URL
|
||
@param key: 参数名
|
||
@param value: 参数值
|
||
Returns:
|
||
追加参数后的 URL
|
||
"""
|
||
parsed = urlparse(url)
|
||
pairs = parse_qsl(parsed.query, keep_blank_values=True)
|
||
pairs.append((key, value))
|
||
return urlunparse(parsed._replace(query=urlencode(pairs)))
|
||
|
||
|
||
def send_wecom_event_message(
|
||
*,
|
||
event_type: str,
|
||
user: User,
|
||
title: str,
|
||
content: str,
|
||
jump_path: str = '/workspace',
|
||
jump_params: dict | None = None,
|
||
jump_url: str | None = None,
|
||
wecom_userid: str | None = None,
|
||
) -> dict:
|
||
"""
|
||
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
|
||
|
||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||
Args:
|
||
event_type: 通知事件开关名。
|
||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||
title: 卡片标题。
|
||
content: 卡片正文。
|
||
jump_path: 站内跳转路径。
|
||
jump_params: 跳转查询参数。
|
||
jump_url: 若传入则覆盖默认拼接的跳转地址。
|
||
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
|
||
Returns:
|
||
含 ok / trace_id 的发送结果字典。
|
||
"""
|
||
trace_id = uuid.uuid4().hex
|
||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
|
||
if target_userid:
|
||
audit.wecom_userid = target_userid
|
||
|
||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||
audit.error_code = 'NOTIFY_DISABLED'
|
||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||
|
||
if event_type not in _get_enabled_events():
|
||
audit.error_code = 'EVENT_DISABLED'
|
||
audit.error_message = f'event {event_type} disabled'
|
||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||
|
||
if not target_userid:
|
||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||
audit.error_message = 'user has no wecom_userid'
|
||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||
|
||
try:
|
||
if jump_url:
|
||
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
|
||
else:
|
||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||
audit.jump_url = final_jump_url
|
||
data = send_wecom_textcard_message(
|
||
target_userid,
|
||
title,
|
||
content,
|
||
final_jump_url,
|
||
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||
)
|
||
if data.get('errcode') == 0:
|
||
audit.status = 'sent'
|
||
return {'ok': True, 'trace_id': trace_id}
|
||
|
||
audit.error_code = str(data.get('errcode'))
|
||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||
except Exception as exc:
|
||
audit.error_code = 'EXCEPTION'
|
||
audit.error_message = str(exc)[:255]
|
||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||
|
||
|
||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||
if not trace_id:
|
||
return False
|
||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||
if not row:
|
||
return False
|
||
if not row.opened_at:
|
||
row.opened_at = datetime.utcnow()
|
||
return True
|