refactor(backend): dify, minio等迁移到integration,清除无效文件

This commit is contained in:
sophie committed 2026-09-21 09:24:45 +08:00
1 parent 7fe7a39384
commit faa554ade4
90 files changed
+7540 -9649

No files matched your search

@@ -1,2 +1,97 @@
"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。"""
from app.services import wecom_crypto # noqa: F401
"""
backend/app/services/integrations/wecom/crypto.py
用途:企业微信回调加解密工具(兼容 WXBizMsgCrypt 布局)。
依赖:pycryptodome AES。
逻辑:user/auth 企微回调验签、解密 Encrypt 字段时调用。
"""
from __future__ import annotations
import base64
import hashlib
import random
import struct
from typing import Optional
from Crypto.Cipher import AES
def sha1_hex(parts: list[str]) -> str:
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
pad_len = block_size - (len(data) % block_size)
return data + bytes([pad_len] * pad_len)
def _pkcs7_unpad(data: bytes) -> bytes:
if not data:
return data
pad_len = data[-1]
if pad_len < 1 or pad_len > 32:
raise ValueError('invalid pkcs7 padding')
if data[-pad_len:] != bytes([pad_len] * pad_len):
raise ValueError('invalid pkcs7 padding tail')
return data[:-pad_len]
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
raw = (encoding_aes_key_b64 or '').strip()
key = base64.b64decode(raw + '=')
if len(key) != 32:
raise ValueError('EncodingAESKey must decode to 32 bytes')
return key
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
"""
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
"""
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
msg_bytes = plain_text.encode('utf-8')
pack = (
random_bytes
+ struct.pack('>I', len(msg_bytes))
+ msg_bytes
+ corp_id.encode('utf-8')
)
padded = _pkcs7_pad(pack, 32)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(padded)
return base64.b64encode(encrypted).decode('ascii')
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
cipher_bytes = base64.b64decode(cipher_b64)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
plain_padded = cipher.decrypt(cipher_bytes)
plain = _pkcs7_unpad(plain_padded)
content = plain[16:]
if len(content) < 4:
raise ValueError('decrypted payload too short')
xml_len = struct.unpack('>I', content[:4])[0]
xml_bytes = content[4:4 + xml_len]
tail = content[4 + xml_len:]
if tail.decode('utf-8', errors='strict') != corp_id:
raise ValueError('corp_id mismatch after decrypt')
return xml_bytes.decode('utf-8')
def extract_encrypt_field(xml_body: str) -> Optional[str]:
if not xml_body:
return None
import re
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
if m:
return m.group(1).strip()
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
if m2:
return m2.group(1).strip()
return None
@@ -1,2 +1,244 @@
"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。"""
from app.services import wecom_directory_sync # noqa: F401
"""
backend/app/services/integrations/wecom/directory_sync.py
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
依赖:Flask current_app、SQLAlchemy db、wecom.notify._get_access_token、User 模型。
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
"""
from __future__ import annotations
from typing import Any
import requests
from flask import current_app
from app import db
from app.models import User
from app.services.integrations.wecom.notify import _get_access_token
_PREVIEW_LIMIT = 20
def _clean_str(value) -> str | None:
"""裁剪字符串类取值;空串视为 None。"""
if value is None:
return None
text = str(value).strip()
return text or None
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
"""
从企微成员 extattr.attrs 中读取指定扩展字段。
@param wecom_user: user/list 返回的成员 dict
@param key: 扩展属性名
Returns:
字段文本或 None
"""
extattr = wecom_user.get('extattr') or {}
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
if not isinstance(attrs, list):
return None
for attr in attrs:
if not isinstance(attr, dict):
continue
if _clean_str(attr.get('name')) != key:
continue
raw = attr.get('value')
if isinstance(raw, dict):
raw = raw.get('text') or raw.get('web') or raw.get('value')
return _clean_str(raw)
return None
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
"""
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
"""
userid = _clean_str(wecom_user.get('userid'))
source = _clean_str(employee_id_source) or 'userid'
if source == 'userid':
return userid
if source.startswith('extattr:'):
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
return _clean_str(wecom_user.get(source))
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
"""
拉取企业微信部门列表。
Raises:
RuntimeError: API 失败
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
params={'access_token': access_token},
timeout=15,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'department/list failed: {data}')
departments = data.get('department') or []
if not isinstance(departments, list):
return []
return [item for item in departments if isinstance(item, dict)]
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
"""
拉取指定部门(含子部门)成员简要列表。
@param department_id: 企微部门 ID
Returns:
user/list 返回的 userlist
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
params={
'access_token': access_token,
'department_id': department_id,
'fetch_child': 1,
},
timeout=30,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
userlist = data.get('userlist') or []
if not isinstance(userlist, list):
return []
return [item for item in userlist if isinstance(item, dict)]
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
"""
汇总多个部门成员,按 wecom_userid 去重。
Returns:
key=userid, value=成员 dict
"""
merged: dict[str, dict[str, Any]] = {}
for dept_id in department_ids:
for user in fetch_wecom_users_in_department(access_token, dept_id):
userid = _clean_str(user.get('userid'))
if userid:
merged[userid] = user
return merged
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
"""
执行工号 → wecom_userid 同步。
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
@param department_id: 指定根部门 ID;None 时使用全部部门
Returns:
统计摘要 dict(含 conflicts、pending_updates 预览)
"""
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
token = _get_access_token()
if department_id is not None:
department_ids = [department_id]
else:
departments = fetch_wecom_departments(token)
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
if not department_ids:
department_ids = [1]
wecom_users = collect_wecom_users(token, department_ids)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': employee_id_source,
'department_ids': department_ids,
'wecom_users': len(wecom_users),
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
for wecom_user in wecom_users.values():
wecom_userid = _clean_str(wecom_user.get('userid'))
wecom_unionid = _clean_str(wecom_user.get('unionid'))
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
if not employee_id:
summary['wecom_without_employee_id'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
)
continue
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
if not local_user:
summary['local_missing'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': _clean_str(wecom_user.get('name')),
}
)
if apply:
local_user.wecom_userid = wecom_userid
if wecom_unionid:
local_user.wecom_unionid = wecom_unionid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
@@ -1,2 +1,264 @@
"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。"""
from app.services import wecom_notify # noqa: F401
"""
backend/app/services/integrations/wecom/notify.py
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
"""
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 跳转基地址(用户点击入口,须为浏览器可访问的 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 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,
wecom_userid: str | None = None,
) -> dict:
"""
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
作为 wecom_userid,因为该 id 同时是企业微信 userid。
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)
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