239 lines
7.3 KiB
Python
239 lines
7.3 KiB
Python
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,
|
|
}
|
|
|
|
|
|
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 跳转基地址。
|
|
核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。
|
|
Returns:
|
|
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
|
"""
|
|
for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_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 send_wecom_textcard_message(
|
|
wecom_userid: str,
|
|
title: str,
|
|
description: str,
|
|
jump_url: str,
|
|
) -> dict:
|
|
token = _get_access_token()
|
|
payload = {
|
|
'touser': wecom_userid,
|
|
'msgtype': 'textcard',
|
|
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
|
'textcard': {
|
|
'title': title[:120],
|
|
'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,
|
|
) -> dict:
|
|
"""
|
|
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
|
|
"""
|
|
trace_id = uuid.uuid4().hex
|
|
audit = _create_audit(event_type, user, title, content, trace_id)
|
|
|
|
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 user or not user.wecom_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(user.wecom_userid, title, content, final_jump_url)
|
|
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
|