from __future__ import annotations from datetime import datetime, timedelta from io import BytesIO from urllib.parse import urlencode 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 _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str: base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or '' 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 (current_app.config.get('WECOM_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 send_wecom_event_message( *, event_type: str, user: User, title: str, content: str, jump_path: str = '/workspace', jump_params: dict | None = None, ) -> dict: 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: jump_url = _build_jump_url(jump_path, trace_id, jump_params) audit.jump_url = jump_url data = send_wecom_textcard_message(user.wecom_userid, title, content, 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