feat: 新增通知推送功能及离线登录,优化重连逻辑

- 新增通知推送模块:支持 WebSocket 实时推送与轮询兜底,新增通知管理界面
- 新增离线登录功能:断网时凭本地 7 天授权票据自动登录或手动登录
- 优化 Electron 客户端 WebSocket 重连逻辑,避免死循环
- 调整工作流脚本,拆分重构合同相关分支逻辑
- 新增设备上报客户端版本字段,用于升级追踪与关旧依据
This commit is contained in:
2026-10-13 17:46:49 +08:00
parent 816af4b960
commit 872d3dc5c8
38 changed files with 2113 additions and 388 deletions
+134 -3
View File
@@ -14,6 +14,7 @@ from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
from controlplane import config, schemas
from controlplane.apis.notifications import push_account, push_all
from controlplane.core.auth import _identity, _require_admin, _revoke_account_tokens
from controlplane.core.crypto import _hash_password
from controlplane.core.db import _audit, _db, _now
@@ -738,18 +739,40 @@ def admin_devices(page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=1000),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果。"""
"""执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果 + 客户端版本。"""
_require_admin(x_admin_token, x_api_token)
limit, offset = page_bounds(page, page_size)
with _db() as conn:
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
rows = [dict(r) for r in conn.execute(
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
" chrome_ok, last_seen, status, created_at, updated_at "
" chrome_ok, client_version, last_seen, status, created_at, updated_at "
"FROM devices ORDER BY last_seen DESC LIMIT %s OFFSET %s", (limit, offset))]
return {"items": rows, "total": total}
@router.get("/api/admin/devices/summary")
def admin_devices_summary(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""客户端升级追踪汇总:按版本统计设备数 + 按账号分组展示各设备客户端版本(关旧控制面依据)。"""
_require_admin(x_admin_token, x_api_token)
with _db() as conn:
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
by_version = [dict(r) for r in conn.execute(
"SELECT client_version AS client_version, COUNT(*) AS count "
"FROM devices GROUP BY client_version ORDER BY count DESC")]
by_account = [dict(r) for r in conn.execute(
"SELECT account, client_version, COUNT(*) AS device_count, "
" MAX(last_seen) AS last_seen "
"FROM devices GROUP BY account, client_version ORDER BY account")]
# 关联账号姓名/部门,方便按人识别
nick = {dict(r)["account"]: (dict(r)["nickname"] or "", dict(r)["dept"] or "")
for r in conn.execute("SELECT account, nickname, dept FROM accounts")}
for row in by_account:
row["nickname"], row["dept"] = nick.get(row["account"], ("", ""))
return {"total": total, "by_version": by_version, "by_account": by_account}
@router.post("/api/admin/shell-release")
async def admin_shell_release(upload: UploadFile = File(...),
version: str = Query(...),
@@ -792,4 +815,112 @@ async def admin_shell_release(upload: UploadFile = File(...),
"sha256": sha256, "notes": notes},
ensure_ascii=False, indent=2), encoding="utf-8")
_audit(login, "shell-release", filename)
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
# ==================== 通知下发管理 ====================
_NOTIF_LEVELS = {"info", "warning", "important"}
_NOTIF_TARGETS = {"all", "account"}
def _notif_expiry(iso: str):
"""ISO 时间串 → MySQL DATETIME;空串返回 None。"""
iso = (iso or "").strip()
if not iso:
return None
return iso.replace("T", " ")[:19]
@router.get("/api/admin/notifications")
def admin_notifications(page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=200),
q: str = Query(default=""),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""通知列表(分页,按 id 倒序)。"""
_require_admin(x_admin_token, x_api_token)
limit, offset = page_bounds(page, page_size)
where, args = "", []
if q.strip():
where = " WHERE (title LIKE %s OR content LIKE %s OR account LIKE %s)"
args = [f"%{q.strip()}%"] * 3
with _db() as conn:
total = count_rows(conn, "SELECT COUNT(*) AS c FROM notifications" + where, args)
rows = [dict(r) for r in conn.execute(
"SELECT id, title, content, level, target, account, created_at, expires_at, active "
"FROM notifications" + where + " ORDER BY id DESC LIMIT %s OFFSET %s",
args + [limit, offset])]
return {"items": rows, "total": total}
@router.post("/api/admin/notifications")
async def admin_notification_create(body: schemas.NotificationIn,
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""下发通知:all=全部账号 / account=指定账号;创建后即时 WebSocket 推送在线客户端。"""
login = _require_admin(x_admin_token, x_api_token)
title = (body.title or "").strip()
if not title:
raise HTTPException(400, "标题不能为空")
if body.level not in _NOTIF_LEVELS:
raise HTTPException(400, "level 仅允许 info/warning/important")
if body.target not in _NOTIF_TARGETS:
raise HTTPException(400, "target 仅允许 all/account")
if body.target == "account" and not (body.account or "").strip():
raise HTTPException(400, "target=account 时必须指定 account")
expires = _notif_expiry(body.expires_at)
with _db() as conn:
cur = conn.execute(
"INSERT INTO notifications(title, content, level, target, account, expires_at) "
"VALUES (%s,%s,%s,%s,%s,%s)",
(title, (body.content or "").strip(), body.level, body.target,
(body.account or "").strip(), expires))
nid = cur.lastrowid
conn.commit()
_audit(login, "notify-create", f"通知 #{nid} {title} → {body.target}")
payload = {"type": "notify", "notification": {
"id": nid, "title": title, "content": (body.content or "").strip(),
"level": body.level, "target": body.target, "account": (body.account or "").strip(),
"created_at": _now()}}
if body.target == "all":
pushed = await push_all(payload)
else:
pushed = await push_account((body.account or "").strip(), payload)
return {"ok": True, "id": nid, "title": title, "target": body.target,
"pushed": pushed}
@router.patch("/api/admin/notifications/{nid}")
async def admin_notification_toggle(nid: int,
active: bool = Query(...),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""启用/停用通知;启用时即时推送给在线客户端。"""
login = _require_admin(x_admin_token, x_api_token)
with _db() as conn:
row = conn.execute(
"SELECT id, title, content, level, target, account, created_at, expires_at "
"FROM notifications WHERE id = %s", (nid,)).fetchone()
conn.execute("UPDATE notifications SET active = %s WHERE id = %s", (int(active), nid))
conn.commit()
_audit(login, "notify-toggle", f"通知 #{nid} active={active}")
if active and row:
payload = {"type": "notify", "notification": dict(row)}
if row["target"] == "all":
await push_all(payload)
else:
await push_account(row["account"] or "", payload)
return {"ok": True, "id": nid, "active": active}
@router.delete("/api/admin/notifications/{nid}")
def admin_notification_delete(nid: int,
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""删除通知。"""
login = _require_admin(x_admin_token, x_api_token)
with _db() as conn:
conn.execute("DELETE FROM notifications WHERE id = %s", (nid,))
conn.commit()
_audit(login, "notify-delete", f"通知 #{nid}")
return {"ok": True, "id": nid}
+102
View File
@@ -0,0 +1,102 @@
# -*- coding: utf-8 -*-
"""客户端通知:HTTP 拉取(兜底)+ WebSocket 实时推送(管理端下发即推,秒达)。"""
from __future__ import annotations
import asyncio
from fastapi import APIRouter, Header, HTTPException, Query, WebSocket, WebSocketDisconnect
from controlplane import config
from controlplane.core.auth import _check_token, _cloud_account
from controlplane.core.db import _db
router = APIRouter(tags=["notifications"])
# WebSocket 连接注册表:account -> set[WebSocket]
# 说明:控制面单 worker 部署时进程内共享,管理端创建/停用通知时据此即时推送在线客户端;
# 即使推送失败/客户端离线,客户端 60s 轮询兜底保证最终送达。
_WS_CLIENTS: dict[str, set] = {}
@router.get("/api/notifications")
def notifications(account: str = Query(default=""),
x_api_token: str = Header(default="", alias="X-API-Token"),
authorization: str = Header(default="", alias="Authorization")) -> dict:
"""客户端拉取通知:优先云会话 token 解工号;兜底 account + X-API-Token。
返回 target=all 与 target=该账号 的启用且未过期通知(按创建时间倒序)。"""
acct = _cloud_account(authorization)
if not acct:
_check_token(x_api_token)
acct = (account or "").strip()
if not acct:
raise HTTPException(400, "缺少有效会话或 account")
with _db() as conn:
rows = conn.execute(
"""
SELECT id, title, content, level, target, account, created_at, expires_at
FROM notifications
WHERE active = 1
AND (target = 'all' OR (target = 'account' AND account = %s))
AND (expires_at IS NULL OR expires_at > NOW())
ORDER BY created_at DESC
LIMIT 50
""",
(acct,),
).fetchall()
return {"notifications": [dict(r) for r in rows]}
@router.websocket("/ws/notifications")
async def ws_notifications(websocket: WebSocket, account: str = Query(default="")):
"""客户端长连接:管理端下发通知时即时推送(秒达)。鉴权用 X-API-Token 请求头。"""
token = (websocket.headers.get("x-api-token") or "").strip()
if config.CONTROLPLANE_TOKEN and token != config.CONTROLPLANE_TOKEN:
await websocket.close(code=4401)
return
acct = (account or "").strip()
if not acct:
await websocket.close(code=4400)
return
await websocket.accept()
_WS_CLIENTS.setdefault(acct, set()).add(websocket)
try:
await websocket.send_json({"type": "hello", "account": acct})
# 保持连接:接收客户端心跳/占位帧;断开(含网络异常)自动清理
while True:
await websocket.receive_text()
except WebSocketDisconnect:
pass
except Exception: # noqa: BLE001
pass
finally:
ws_set = _WS_CLIENTS.get(acct)
if ws_set:
ws_set.discard(websocket)
if not ws_set:
_WS_CLIENTS.pop(acct, None)
async def _send_ws(ws_set: set, payload: dict) -> None:
for ws in list(ws_set):
try:
await ws.send_json(payload)
except Exception: # noqa: BLE001
ws_set.discard(ws)
async def push_all(payload: dict) -> int:
"""推送给全部在线客户端,返回目标连接数。"""
n = 0
for ws_set in _WS_CLIENTS.values():
n += len(ws_set)
await _send_ws(ws_set, payload)
return n
async def push_account(account: str, payload: dict) -> int:
"""推送给指定账号的在线客户端,返回目标连接数。"""
ws_set = _WS_CLIENTS.get(account)
if not ws_set:
return 0
await _send_ws(ws_set, payload)
return len(ws_set)
+5 -3
View File
@@ -236,17 +236,19 @@ def device_report(b: schemas.DeviceReportIn,
with _db() as conn:
conn.execute(
"INSERT INTO devices(device_id, account, hostname, os, ip, "
"chrome_installed, chrome_version, chrome_ok, last_seen, status) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
"chrome_installed, chrome_version, chrome_ok, client_version, last_seen, status) "
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE "
"account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), "
"ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), "
"chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), "
"client_version = VALUES(client_version), "
"last_seen = VALUES(last_seen), status = VALUES(status)",
(device_id, (b.account or "").strip(), (b.hostname or "").strip(),
(b.os or "").strip(), (b.ip or "").strip(),
int(bool(b.chrome_installed)), (b.chrome_version or "").strip(),
int(bool(b.chrome_ok)), _now(), int(bool(b.status))))
int(bool(b.chrome_ok)), (b.client_version or "").strip(),
_now(), int(bool(b.status))))
conn.commit()
return {"ok": True, "device_id": device_id}