feat: 新增通知推送功能及离线登录,优化重连逻辑
- 新增通知推送模块:支持 WebSocket 实时推送与轮询兜底,新增通知管理界面 - 新增离线登录功能:断网时凭本地 7 天授权票据自动登录或手动登录 - 优化 Electron 客户端 WebSocket 重连逻辑,避免死循环 - 调整工作流脚本,拆分重构合同相关分支逻辑 - 新增设备上报客户端版本字段,用于升级追踪与关旧依据
This commit is contained in:
@@ -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}
|
||||
Reference in New Issue
Block a user