221 lines
10 KiB
Python
221 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||
|
||
后台线程发送,失败仅记日志不阻断业务。
|
||
|
||
配置项(controlplane/.env):
|
||
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import base64
|
||
import hashlib
|
||
import hmac
|
||
import json
|
||
import logging
|
||
import threading
|
||
import time
|
||
from urllib.parse import quote_plus
|
||
from urllib.request import Request, urlopen
|
||
|
||
from controlplane.core import config
|
||
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||
|
||
log = logging.getLogger(__name__)
|
||
|
||
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||
_SIGN_NAME = "37du 自动化平台"
|
||
_STATUS_COLORS = {
|
||
"info": "#0077ff", # 蓝色
|
||
"success": "#00b300", # 绿色
|
||
"warning": "#ff9900", # 橙色
|
||
"error": "#ff0000", # 红色
|
||
}
|
||
|
||
|
||
def _footer() -> str:
|
||
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||
|
||
|
||
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||
req.add_header("Content-Type", "application/json")
|
||
for k, v in (headers or {}).items():
|
||
req.add_header(k, v)
|
||
with urlopen(req, timeout=10) as resp:
|
||
return json.loads(resp.read().decode("utf-8"))
|
||
|
||
|
||
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||
"""unionid → userid(精确,无重名歧义)。"""
|
||
try:
|
||
body = _post_json(
|
||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||
{"unionid": unionid})
|
||
return ((body.get("result") or {}).get("userid")) or ""
|
||
except Exception: # noqa: BLE001
|
||
return ""
|
||
|
||
|
||
def _userid_by_name(at: str, name: str) -> str:
|
||
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||
try:
|
||
body = _post_json(
|
||
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||
headers={"x-acs-dingtalk-access-token": at})
|
||
lst = body.get("list") or []
|
||
return str(lst[0]) if lst else ""
|
||
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||
return ""
|
||
|
||
|
||
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||
status: str = "info") -> bool:
|
||
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||
text += content.strip() + "\n"
|
||
text += f"\n\n---\n\n{_footer()}"
|
||
try:
|
||
body = _post_json(
|
||
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||
{"agent_id": agent_id, "userid_list": userid,
|
||
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||
if body.get("errcode") != 0:
|
||
log.warning("钉钉工作通知被拒: %s", body)
|
||
return False
|
||
return True
|
||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||
log.warning("钉钉工作通知异常: %s", e)
|
||
return False
|
||
|
||
|
||
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||
if not agent_id:
|
||
return
|
||
try:
|
||
at = _dingtalk_topapi_token()
|
||
if not at:
|
||
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||
return
|
||
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||
if not uid and nickname:
|
||
uid = _userid_by_name(at, nickname)
|
||
if uid:
|
||
_send_work_to(
|
||
at, agent_id, uid, "账号开通通知",
|
||
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||
f"> 账号:{account}\n\n"
|
||
f"> 初始密码:{password}\n\n"
|
||
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||
status="success")
|
||
else:
|
||
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||
admin_uid = _userid_by_name(at, admin_name)
|
||
if admin_uid:
|
||
_send_work_to(
|
||
at, agent_id, admin_uid, "新账号待开通权限",
|
||
f"> 账号:{account}\n\n"
|
||
f"> 姓名:{nickname or '—'}\n\n"
|
||
f"> 来源:{source}\n\n"
|
||
"> 备注:请到管理台为该账号开通插件权限",
|
||
status="warning")
|
||
else:
|
||
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||
log.warning("钉钉建号通知异常: %s", e)
|
||
|
||
|
||
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||
unionid: str = "", source: str = "管理台") -> None:
|
||
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||
daemon=True).start()
|
||
|
||
|
||
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||
def _signed_webhook_url() -> str:
|
||
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||
if not url:
|
||
return ""
|
||
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||
if secret:
|
||
ts = str(int(time.time() * 1000))
|
||
sign = base64.b64encode(hmac.new(
|
||
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||
hashlib.sha256).digest()).decode("utf-8")
|
||
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||
return url
|
||
|
||
|
||
def _send_robot(title: str, text: str) -> None:
|
||
url = _signed_webhook_url()
|
||
if not url:
|
||
return
|
||
try:
|
||
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||
if body.get("errcode") != 0:
|
||
log.warning("钉钉群通知被拒: %s", body)
|
||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||
log.warning("钉钉群通知异常: %s", e)
|
||
|
||
|
||
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||
def _admin_names() -> list[str]:
|
||
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||
try:
|
||
from controlplane.core.db import _db
|
||
with _db() as conn:
|
||
rows = conn.execute(
|
||
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||
return []
|
||
|
||
|
||
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||
title = "内网文件服务器下线告警"
|
||
content = (
|
||
f"> 服务:{hostname or '—'}\n\n"
|
||
f"> 地址:{host}\n\n"
|
||
f"> IP:{ip or '—'}\n\n"
|
||
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||
"服务恢复后将自动解除告警")
|
||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||
at = _dingtalk_topapi_token() if agent_id else ""
|
||
sent_any = False
|
||
if at:
|
||
for name in _admin_names():
|
||
if not name:
|
||
continue
|
||
uid = _userid_by_name(at, name)
|
||
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||
sent_any = True
|
||
if not sent_any:
|
||
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||
if not sent_any:
|
||
_send_robot(title, content)
|
||
|
||
|
||
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||
last_seen: str = "") -> None:
|
||
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||
threading.Thread(target=_work_fileserver_down,
|
||
args=(host, hostname, ip, last_seen), daemon=True).start()
|