refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane —— 内网插件控制面(中心机)包。
|
||||
|
||||
业务领域实现已归入 core 子包。本 `__init__` 作为 facade 再导出 core 内各模块,
|
||||
以兼容 `from controlplane import X` 的既有用法。
|
||||
"""
|
||||
from controlplane.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
crypto,
|
||||
db,
|
||||
dingtalk,
|
||||
pkgutil,
|
||||
schemas,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 路由子包:按领域组织 APIRouter,由 app.py 底层组装。"""
|
||||
@@ -0,0 +1,541 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""管理侧路由(写操作,需正确 token):账号 CRUD / 插件上传与维护 / 授权 / 看板 / 审计 / 运行记录。
|
||||
|
||||
所有写操作均以 `_require_admin`(X-API-Token + X-Admin-Token 管理员票据)把关。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _require_admin
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.pkgutil import (
|
||||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||
_validate_pkg_zip, _version_key,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@router.get("/api/admin/accounts")
|
||||
def admin_accounts(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:
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
|
||||
"FROM accounts ORDER BY account")]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/account")
|
||||
def admin_account_create(a: schemas.AccountCreateIn,
|
||||
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)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
if exists:
|
||||
raise HTTPException(400, f"账号 {account} 已存在")
|
||||
_hex, _salt = _hash_password(a.password)
|
||||
with _db() as conn:
|
||||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||||
(a.nickname or "").strip()))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/update")
|
||||
def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
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)
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
if a.dept is not None:
|
||||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||||
((a.dept or "").strip(), account))
|
||||
if a.nickname is not None:
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
((a.nickname or "").strip(), account))
|
||||
if a.is_admin is not None:
|
||||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||||
if a.is_admin:
|
||||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||||
else:
|
||||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||||
(account, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/reset_pwd")
|
||||
def admin_account_reset(r: schemas.AccountResetIn,
|
||||
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)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
_hex, _salt = _hash_password(r.new_password)
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@router.post("/api/admin/account/delete")
|
||||
def admin_account_delete(d: schemas.AccountDelIn,
|
||||
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)
|
||||
account = d.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 必填")
|
||||
if account == login:
|
||||
raise HTTPException(400, "不能删除当前登录的账号")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
# ==================== 授权 / 插件维护 ====================
|
||||
@router.post("/api/admin/account_plugins")
|
||||
def admin_grant(g: schemas.GrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
if not account or not plugin_id:
|
||||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||||
(account, plugin_id))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"VALUES (?, ?, ?, ?) "
|
||||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"can_download={g.can_download},can_run={g.can_run}")
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
@router.post("/api/admin/account_platforms")
|
||||
def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
platform_id = g.platform_id.strip()
|
||||
if not account or not platform_id:
|
||||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||||
with _db() as conn:
|
||||
if g.granted:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||||
(account, platform_id))
|
||||
else:
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
@router.post("/api/admin/pkg")
|
||||
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
plugin_id: str = Query(...), name: str = Query(...),
|
||||
version: str = Query(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
if not plugin_id or not version:
|
||||
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||||
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||||
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = config.PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
|
||||
# manifest 为插件契约权威来源:plugin.json 内 id 与路径 plugin_id 不一致时拒绝,
|
||||
# 否则以 manifest.metadata 覆盖 name/category/icon/description 并整份入库。
|
||||
manifest = _extract_manifest(content)
|
||||
if manifest:
|
||||
mid = str((manifest.get("id") or "")).strip()
|
||||
if mid and mid != plugin_id:
|
||||
raise HTTPException(400, f"plugin.json 内 id「{mid}」与路径 plugin_id「{plugin_id}」不一致")
|
||||
name = str(manifest.get("name") or name).strip() or plugin_id
|
||||
manifest_json = json.dumps(manifest, ensure_ascii=False) if manifest else "{}"
|
||||
|
||||
target.write_bytes(content)
|
||||
pkg_sha256 = hashlib.sha256(content).hexdigest() # 供部署端装包后防篡改校验
|
||||
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||||
"name = excluded.name, manifest = excluded.manifest"
|
||||
+ (", description = excluded.description" if manifest else "")
|
||||
+ (", category = excluded.category" if manifest else "")
|
||||
+ (", icon = excluded.icon" if manifest else ""),
|
||||
(plugin_id, name, version,
|
||||
(manifest or {}).get("description", ""),
|
||||
(manifest or {}).get("category", ""),
|
||||
(manifest or {}).get("icon", ""),
|
||||
manifest_json))
|
||||
conn.execute(
|
||||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||||
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||||
stale_files = _prune_versions(conn, plugin_id)
|
||||
conn.commit()
|
||||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||||
try:
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@router.post("/api/admin/plugin/delete")
|
||||
def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
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)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||||
files = [dict(r)["filename"] for r in conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||||
conn.commit()
|
||||
for fn in files:
|
||||
try:
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return {"ok": True, "plugin_id": plugin_id}
|
||||
|
||||
|
||||
@router.post("/api/admin/plugin/patch")
|
||||
def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
plugin_id: str = Query(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""更新插件元信息/状态/强制更新配置。
|
||||
|
||||
status: published=正常 / disabled=禁用(停止发布) / revoked=下架(拒绝运行)。
|
||||
force_min_version + force_deadline 组合开启强制更新(deadline 已过联线拒启旧版);
|
||||
clear_force=True 清除强制更新;仅给其一且未 clear 则报 400。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
pid = plugin_id.strip()
|
||||
if not pid:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
fields = []
|
||||
vals = []
|
||||
if d.name is not None and d.name.strip():
|
||||
fields.append("name = ?"); vals.append(d.name.strip())
|
||||
if d.description:
|
||||
fields.append("description = ?"); vals.append(d.description.strip())
|
||||
if d.category:
|
||||
fields.append("category = ?"); vals.append(d.category.strip())
|
||||
if d.icon:
|
||||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||||
if d.status in ("published", "disabled", "revoked"):
|
||||
fields.append("status = ?"); vals.append(d.status)
|
||||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||||
if d.force_min_version and d.force_deadline:
|
||||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||||
elif d.clear_force:
|
||||
fields.append("force_min_version = NULL")
|
||||
fields.append("force_deadline = NULL")
|
||||
if not fields:
|
||||
return {"ok": True} # 无更新项
|
||||
vals.append(pid)
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
|
||||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(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:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||
" force_min_version, force_deadline, manifest "
|
||||
"FROM plugins ORDER BY id")]
|
||||
for p in plugins:
|
||||
m = _load_manifest(p.pop("manifest"))
|
||||
p["manifest"] = m
|
||||
p["capabilities"] = m.get("capabilities") or []
|
||||
p["permissions"] = m.get("permissions") or {}
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||||
"WHERE plugin_id = ?", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||||
"WHERE account = ?", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
|
||||
|
||||
@router.get("/api/admin/stats")
|
||||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""数据看板:账号/插件规模 + 运行统计(次数/时长/成败)+ 近 14 天趋势 + 排行。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
users = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM accounts) AS total, "
|
||||
"(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, "
|
||||
"(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone())
|
||||
plugins = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM plugins) AS total, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, "
|
||||
"(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone())
|
||||
runs = dict(conn.execute(
|
||||
"SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, "
|
||||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, "
|
||||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, "
|
||||
"(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, "
|
||||
"(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, "
|
||||
"(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone())
|
||||
|
||||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||||
trend_rows = conn.execute(
|
||||
"SELECT substr(at,1,10) AS day, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||||
).fetchall()
|
||||
trend_map = {r["day"]: r for r in trend_rows}
|
||||
trend = []
|
||||
day = datetime.now() - timedelta(days=13)
|
||||
for _i in range(14):
|
||||
key = day.strftime("%Y-%m-%d")
|
||||
r = trend_map.get(key)
|
||||
trend.append({"day": key[5:], "runs": int(r["runs"] or 0) if r else 0,
|
||||
"success": int(r["success"] or 0) if r else 0,
|
||||
"failed": int(r["failed"] or 0) if r else 0})
|
||||
day = day + timedelta(days=1)
|
||||
|
||||
# 插件排行:按执行次数(以 status='start' 为一次完整触发)
|
||||
top_plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id AS pluginId, "
|
||||
" COUNT(*) AS runs, "
|
||||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS triggered, "
|
||||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed, "
|
||||
" COALESCE(SUM(duration_sec),0) AS durationSec "
|
||||
"FROM runtime_reports GROUP BY plugin_id "
|
||||
"ORDER BY triggered DESC LIMIT 8")]
|
||||
pnames = {dict(r)["id"]: dict(r)["name"] for r in conn.execute(
|
||||
"SELECT id, name FROM plugins")}
|
||||
for tp in top_plugins:
|
||||
tp["name"] = pnames.get(tp["pluginId"]) or tp["pluginId"]
|
||||
tp["runs"] = int(tp["triggered"] or 0)
|
||||
|
||||
# 活跃用户排行
|
||||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
# 最近运行列表
|
||||
recent = [dict(r) for r in conn.execute(
|
||||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||||
"FROM runtime_reports WHERE status <> 'start' "
|
||||
"ORDER BY id DESC LIMIT 20")]
|
||||
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
for tu in top_users:
|
||||
tu["nickname"] = nick.get(tu["account"], "")
|
||||
for rc in recent:
|
||||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||||
|
||||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||||
return {
|
||||
"users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0),
|
||||
"authorized": int(users["authorized"] or 0)},
|
||||
"plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0),
|
||||
"disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)},
|
||||
"runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0),
|
||||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||||
"recent": recent, "today": now_day,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, 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:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, 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:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
async def admin_shell_release(upload: UploadFile = File(...),
|
||||
version: str = Query(...),
|
||||
notes: str = Query(default=""),
|
||||
sha256: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""发布执行机壳子新版安装包:存到 shell/ + 写 version.json(管理员)。
|
||||
|
||||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
version = version.strip()
|
||||
if not version:
|
||||
raise HTTPException(400, "version 不能为空")
|
||||
if not _SAFE_NAME_RE.match(version):
|
||||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"setup-37du-host-{version}.exe"
|
||||
content = await upload.read()
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
if not sha256:
|
||||
sha256 = hashlib.sha256(content).hexdigest()
|
||||
(config.SHELL_DIR / filename).write_bytes(content)
|
||||
(config.SHELL_DIR / "version.json").write_text(
|
||||
json.dumps({"version": version, "filename": filename,
|
||||
"sha256": sha256, "notes": notes},
|
||||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_audit("", "shell-release", filename)
|
||||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""账号登录与身份路由:当前账号信息 / 可授权平台 / 账号密码登录 / 自助改密 / 员工端扫码换 token。
|
||||
|
||||
- 管理写操作(改他人账号/插件)统一走 apis.admin(_require_admin);
|
||||
- 此处为"自助/登录"类只读或本账号操作。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_account_lookup, _auth_fail, _auth_gate, _check_token,
|
||||
_resolve_login, _require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
from controlplane.core.dingtalk import _dingtalk_userinfo
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_CONTROLPLANE_PLATFORMS = [
|
||||
{"id": "hr", "label": "HR 系统"},
|
||||
{"id": "oa", "label": "OA 系统"},
|
||||
] # 需与 webhost/backend/auth.py `_LABELS` 保持一致;新增平台时两侧同步
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""查询当前账号信息:管理员标识 + 部门 + 昵称。"""
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname FROM accounts WHERE account = ?", (account,)).fetchone()
|
||||
return {"account": account,
|
||||
"is_admin": bool(row and row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
@router.get("/api/admin/platforms")
|
||||
def admin_platforms(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""可授权平台列表(只读,替代授权页写死 hr/oa)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
return {"platforms": _CONTROLPLANE_PLATFORMS}
|
||||
|
||||
|
||||
@router.post("/api/admin/auth")
|
||||
def admin_auth(a: schemas.AuthIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""统一账户登录:所有账号均可登录(需密码正确);是否管理员由 is_admin 决定。"""
|
||||
_check_token(x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
_auth_gate(account)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, is_admin, dept, must_change_pwd FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if not row or not _verify_password(a.password, row["salt"], row["password_hash"]):
|
||||
_auth_fail(account)
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(p: schemas.PwdIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT password_hash, salt, must_change_pwd FROM accounts WHERE account = ?",
|
||||
(login,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "账号不存在")
|
||||
# 首次登录(must_change_pwd=1,钉钉自动建号的默认密码)允许免旧密码直接改密
|
||||
if not row["must_change_pwd"] and (
|
||||
not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"])):
|
||||
raise HTTPException(401, "原密码错误")
|
||||
_hex, _salt = _hash_password(p.new_password)
|
||||
with _db() as conn:
|
||||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ?, must_change_pwd = 0 "
|
||||
"WHERE account = ?", (_hex, _salt, login))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": login}
|
||||
|
||||
|
||||
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
|
||||
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 只验证不建号
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600
|
||||
_cloud_tokens: dict = {}
|
||||
_cloud_lock = threading.Lock()
|
||||
|
||||
|
||||
@router.post("/auth/exchange")
|
||||
def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(只验证不建号)。"""
|
||||
code = (d.code or "").strip()
|
||||
if not code:
|
||||
raise HTTPException(400, "缺少 code")
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
info = _dingtalk_userinfo(code)
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
acct = _auth_account_lookup(account)
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
# 惰性清理过期云端会话,防内存无限增长
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": acct["nickname"] or (info.get("nickname") or "")}
|
||||
return {"token": token,
|
||||
"account": account, "nickname": acct["nickname"] or (info.get("nickname") or ""),
|
||||
"exists": bool(acct["exists"]), "is_admin": False}
|
||||
@@ -0,0 +1,127 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉扫码路由:找建账号 / OAuth 扫码页 + 回调 / 内嵌二维码(DDLogin)。
|
||||
|
||||
- 账号建立/鉴权统一走 /api/admin/dingtalk/auth(find-or-create,仅底座 X-API-Token 可调);
|
||||
- /scan→/cb 与 /sns 仅为可信扫码入口,仅换取身份不建号(建号仍由 auth 把关)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _check_token, _sign_admin_token
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _db
|
||||
from controlplane.core.dingtalk import _dingtalk_sns_userinfo, _dingtalk_userinfo
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/auth")
|
||||
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""钉钉扫码身份 → 找建统一账号(仅底座 X-API-Token 可调)。
|
||||
|
||||
返回 {ok, account, nickname, is_admin, created, must_change_pwd, token}。
|
||||
created=True 表示本次新建;must_change_pwd=True 表示当前为默认密码,前端须提示改密。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
account = d.account.strip()
|
||||
if not account or not account.isprintable() or re.search(r"[\s]", account):
|
||||
raise HTTPException(400, "工号不能为空且不可包含空白字符")
|
||||
nickname = (d.nickname or "").strip()
|
||||
ding_uid = (d.dingtalk_uid or "").strip()
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account, is_admin, must_change_pwd, nickname FROM accounts WHERE account = ?",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||||
if nickname and nickname != (row["nickname"] or ""):
|
||||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account,
|
||||
"nickname": nickname or (row["nickname"] or ""),
|
||||
"is_admin": bool(row["is_admin"]),
|
||||
"created": False, "must_change_pwd": bool(row["must_change_pwd"]),
|
||||
"token": _sign_admin_token(account)}
|
||||
# 不存在:自动建号(空壳),初始密码取覆盖值或默认值,强制改密
|
||||
pwd = (d.password.strip() if d.password else config.DINGTALK_DEFAULT_PASSWORD)
|
||||
if len(pwd) < 6:
|
||||
raise HTTPException(400, "初始密码至少 6 位")
|
||||
_hex, _salt = _hash_password(pwd)
|
||||
conn.execute(
|
||||
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||||
"dingtalk_uid, must_change_pwd) VALUES (?, ?, ?, 0, '', ?, ?, 1)",
|
||||
(account, _hex, _salt, nickname, ding_uid))
|
||||
conn.commit()
|
||||
return {"ok": True, "account": account, "nickname": nickname,
|
||||
"is_admin": False, "created": True, "must_change_pwd": True,
|
||||
"token": _sign_admin_token(account)}
|
||||
|
||||
|
||||
# ==================== 钉钉真实扫码(OAuth):扫码页 + 回调换取身份 ====================
|
||||
# 流程:部署机扫码按钮 → 本机 /api/admin/dingtalk/scan → 跳钉钉登录页(redirect_uri=本中心机回调)
|
||||
# → 用户扫码确认 → 钉钉回调 /api/admin/dingtalk/cb?code → 换 token 拉工号/姓名 →
|
||||
# 302 回部署机(state 中带回的 back)携带身份 → 部署机静默建会话。
|
||||
@router.get("/api/admin/dingtalk/scan")
|
||||
def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳地址")) -> RedirectResponse:
|
||||
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb",
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": back})
|
||||
return RedirectResponse(login_url)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||
if not (state.startswith("http://") or state.startswith("https://")):
|
||||
raise HTTPException(400, "非法回跳地址")
|
||||
info = _dingtalk_userinfo(code)
|
||||
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||
"unionid": info["unionid"] or ""})
|
||||
sep = "&" if "?" in state else "?"
|
||||
return RedirectResponse(f"{state}{sep}{qs}")
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/sns")
|
||||
def dingtalk_sns(d: schemas.SnsIn) -> dict:
|
||||
"""内嵌二维码扫码换取身份:loginTmpCode → 工号/姓名/unionid。
|
||||
|
||||
与 /scan→/cb 同为可信扫码入口,仅换取身份(不建号),故与链接授权链路一致不强制 X-API-Token;
|
||||
账号创建仍由 /api/admin/dingtalk(find-or-create, _check_token)把关。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
return _dingtalk_sns_userinfo(d.code.strip())
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留,内嵌不直接跳转)")) -> dict:
|
||||
"""构造内嵌二维码(DDLogin)所需的 goto:登录页在本页内渲染二维码,不弹新窗口。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(503, "未配置中心机回调域名(DINGTALK_CALLBACK)")
|
||||
auth_url = ("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=%s"
|
||||
"&response_type=code&scope=snsapi_login&state=%s&redirect_uri=%s") % (
|
||||
config.DINGTALK_APP_KEY, secrets.token_hex(8),
|
||||
quote(f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb"))
|
||||
return {"goto": quote(auth_url)}
|
||||
@@ -0,0 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""基础元信息路由:健康检查。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": config.DB_PATH.name}
|
||||
@@ -0,0 +1,277 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""客户端(部署端)拉取接口:插件清单 / 平台白名单 / 版本清单 / 包下载 / 离线票据 / 运行上报。
|
||||
|
||||
权限隔离 + 插件分发 + 版本比对,客户端只经本接口获取能力,不直连数据库。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from controlplane import config, crypto, schemas
|
||||
from controlplane.core.auth import _check_token, _cloud_account
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.pkgutil import _load_manifest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/plugins", response_model=dict)
|
||||
def plugins(account: str = Query(default="", description="账号(旧底座按此传)"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
authorization: str = Header(default="", alias="Authorization")) -> dict:
|
||||
"""按账号返回可用插件清单(权限隔离):无权限的账号返回空列表。
|
||||
|
||||
§2.2:优先用云端会话 token(Authorization: Bearer <token>)解出工号,不再明文传 account;
|
||||
兜底兼容旧底座 `account?` + X-API-Token 的调用方式。
|
||||
"""
|
||||
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 p.id, p.name, p.latest_version AS version
|
||||
FROM plugins p
|
||||
JOIN account_plugins ap ON ap.plugin_id = p.id
|
||||
WHERE ap.account = ?
|
||||
ORDER BY p.id
|
||||
""",
|
||||
(acct,),
|
||||
).fetchall()
|
||||
return {"account": acct, "plugins": [schemas.PluginOut(**dict(r)).model_dump() for r in rows]}
|
||||
|
||||
|
||||
@router.get("/api/platforms/allowed", response_model=dict)
|
||||
def platforms_allowed(account: str = Query(default="", description="账号(旧底座按此传)"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
authorization: str = Header(default="", alias="Authorization")) -> dict:
|
||||
"""按账号返回可登录平台白名单(与插件权限同模式)。支持云端会话 token 或旧底座 account 两种身份来源。"""
|
||||
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 platform_id FROM account_platforms WHERE account = ? ORDER BY platform_id",
|
||||
(acct,),
|
||||
).fetchall()
|
||||
return {"account": acct, "allowed": [dict(r)["platform_id"] for r in rows]}
|
||||
|
||||
|
||||
@router.get("/api/manifest")
|
||||
def manifest(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全量插件版本清单:客户端据此比对是否需要拉新包。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT p.id, p.name, p.latest_version AS version, pv.uploaded_at,
|
||||
p.status, p.category, pv.sha256 AS pkg_sha256, p.manifest
|
||||
FROM plugins p
|
||||
LEFT JOIN plugin_versions pv ON pv.plugin_id = p.id AND pv.version = p.latest_version
|
||||
ORDER BY p.id
|
||||
"""
|
||||
).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
m = _load_manifest(item.pop("manifest"))
|
||||
item["manifest"] = m
|
||||
item["capabilities"] = m.get("capabilities") or []
|
||||
item["permissions"] = m.get("permissions") or {}
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
item["field_count"] = len(props)
|
||||
out.append(item)
|
||||
return {"plugins": out, "generated_at": _now()}
|
||||
|
||||
|
||||
@router.get("/api/pkg/{plugin_id}/{version}")
|
||||
def pkg(plugin_id: str, version: str,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""下载指定版本插件包。包文件存磁盘,DB 记 filename 索引。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(plugin_id, version),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
path = config.PKG_DIR / row["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||||
_audit("", "download", f"{plugin_id}@{version}")
|
||||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
# ==================== 产品化:客户端(部署端)拉取接口 ====================
|
||||
@router.get("/api/me/pubkey")
|
||||
def me_pubkey() -> dict:
|
||||
"""下发中心机公钥(PEM 文本),部署端首次联网时缓存用于离线验签。"""
|
||||
return {"pub": crypto._pubkey_pem().decode("ascii"), "algo": "ed25519"}
|
||||
|
||||
|
||||
@router.get("/api/me/license")
|
||||
def me_license(account: str = Query(...), device: str = Query(default=""),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""签发离线授权票据:基于当前账号的插件级授权(can_run)快照,Ed25519 签名。
|
||||
|
||||
票据无硬过期——部署端离线时凭缓存副本持续可用(符合"不联网一直能用")。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
if not account.strip():
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT g.plugin_id, g.can_download, g.can_run, p.name, p.status, p.latest_version
|
||||
FROM plugin_grants g
|
||||
JOIN plugins p ON p.id = g.plugin_id
|
||||
WHERE g.account = ?
|
||||
""",
|
||||
(account.strip(),),
|
||||
).fetchall()
|
||||
plugins = [{"pluginId": r["plugin_id"], "name": r["name"],
|
||||
"canDownload": bool(r["can_download"]), "canRun": bool(r["can_run"]),
|
||||
"status": r["status"], "latestVersion": r["latest_version"]}
|
||||
for r in rows]
|
||||
blob = crypto._sign_blob({"userId": account.strip(), "deviceId": device or "",
|
||||
"issuedAt": _now(), "plugins": plugins})
|
||||
return {"ticket": blob, "plugins": plugins, "issuedAt": _now()}
|
||||
|
||||
|
||||
@router.get("/api/me/control-list")
|
||||
def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""签发管控清单:下架(revoke)/禁用(disable)/强制更新(force-update)聚合,Ed25519 签名。"""
|
||||
_check_token(x_api_token)
|
||||
revoked = []
|
||||
disabled = []
|
||||
forced = []
|
||||
with _db() as conn:
|
||||
for r in conn.execute(
|
||||
"SELECT id, name, status, force_min_version, force_deadline FROM plugins"):
|
||||
pid = r["id"]
|
||||
if r["status"] == "revoked":
|
||||
revoked.append(pid)
|
||||
elif r["status"] == "disabled":
|
||||
disabled.append(pid)
|
||||
if r["force_min_version"] and r["force_deadline"]:
|
||||
forced.append({"pluginId": pid, "minVersion": r["force_min_version"],
|
||||
"deadline": r["force_deadline"]})
|
||||
payload = {"revokedPlugins": revoked, "disabledPlugins": disabled,
|
||||
"forcedUpdates": forced, "updatedAt": _now()}
|
||||
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||
|
||||
|
||||
# 一次性下载票据(内存态,兑换后失效)
|
||||
_DL_TICKETS: dict = {}
|
||||
|
||||
|
||||
@router.get("/api/plugins/{plugin_id}/versions/{version}/download-ticket")
|
||||
def download_ticket(plugin_id: str, version: str,
|
||||
account: str = Query(...),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""签发一次性下载票据:校验账号对该插件的 can_download 授权后签发,票据仅可换一次。"""
|
||||
_check_token(x_api_token)
|
||||
if not account.strip():
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT can_download FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||||
(account.strip(), plugin_id)).fetchone()
|
||||
ver = conn.execute(
|
||||
"SELECT filename, sha256 FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(plugin_id, version)).fetchone()
|
||||
if not ver:
|
||||
raise HTTPException(404, f"未找到插件包 {plugin_id}@{version}")
|
||||
if not row or not row["can_download"]:
|
||||
raise HTTPException(403, "无该插件的下载授权")
|
||||
path = config.PKG_DIR / ver["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{ver['filename']}")
|
||||
# 票据内含可下载文件名与校验值;用一次性 nonce 存内存,兑换后失效
|
||||
nonce = secrets.token_hex(16)
|
||||
_DL_TICKETS[nonce] = {"filename": ver["filename"], "sha256": ver["sha256"] or "",
|
||||
"used": False}
|
||||
url = f"/api/download/{nonce}"
|
||||
return {"ticket": nonce, "url": url, "filename": ver["filename"],
|
||||
"sha256": ver["sha256"] or "", "expiresAt": _now()}
|
||||
|
||||
|
||||
@router.get("/api/download/{ticket}")
|
||||
def download(ticket: str, x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""兑换下载票据:一次性有效,兑换即作废并写审计。"""
|
||||
_check_token(x_api_token)
|
||||
item = _DL_TICKETS.get(ticket)
|
||||
if not item or item["used"]:
|
||||
raise HTTPException(404, "下载票据无效或已使用")
|
||||
item["used"] = True
|
||||
path = config.PKG_DIR / item["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{item['filename']}")
|
||||
_audit("", "download-ticket", item["filename"])
|
||||
return FileResponse(path, filename=item["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/api/runtime/report")
|
||||
def runtime_report(b: schemas.RuntimeReportIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""接收部署端运行上报(启动/完成/失败/离线补报),统一落库。"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO runtime_reports(account, device_id, plugin_id, version, status, msg, duration_sec, at) "
|
||||
"VALUES (?,?,?,?,?,?,?,?)",
|
||||
(b.account, b.device_id, b.plugin_id, b.version, b.status, b.msg, b.duration_sec, _now()))
|
||||
conn.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ==================== 壳子(执行机主程序)自动更新 ====================
|
||||
# shell/version.json 约定:{"version": "1.0.0", "filename": "setup-37du-host-1.0.0.exe",
|
||||
# "sha256": "<可选,安装包校验值>", "notes": "<可选,更新说明>"}
|
||||
|
||||
|
||||
def _shell_meta() -> dict:
|
||||
"""读 shell/version.json;缺失/非法返回空 dict。"""
|
||||
vf = config.SHELL_DIR / "version.json"
|
||||
if not vf.is_file():
|
||||
return {}
|
||||
try:
|
||||
d = json.loads(vf.read_text(encoding="utf-8"))
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
@router.get("/api/shell/version")
|
||||
def shell_version(x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""壳子版本清单:执行端启动时比对,判断是否需要自动下载升级包。"""
|
||||
_check_token(x_api_token)
|
||||
m = _shell_meta()
|
||||
if not m.get("version"):
|
||||
return {"available": False, "version": ""}
|
||||
return {"available": True, "version": str(m["version"]),
|
||||
"filename": m.get("filename", ""), "sha256": m.get("sha256", ""),
|
||||
"notes": m.get("notes", "")}
|
||||
|
||||
|
||||
@router.get("/api/shell/pkg")
|
||||
def shell_pkg(x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""下载壳子安装包(setup.exe),供执行端静默升级。"""
|
||||
_check_token(x_api_token)
|
||||
m = _shell_meta()
|
||||
fn = m.get("filename", "")
|
||||
path = config.SHELL_DIR / fn if fn else None
|
||||
if not path or not path.exists():
|
||||
raise HTTPException(404, "壳子安装包缺失,请联系管理员")
|
||||
return FileResponse(path, filename=path.name, media_type="application/octet-stream")
|
||||
@@ -0,0 +1,91 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网插件控制面(中心机)入口(组装层)。
|
||||
|
||||
业务逻辑已按领域拆到 sibling 模块,本文件仅承担:lifespan 初始化、创建 app、
|
||||
装配各领域路由、挂载前端产物、uvicorn 启动。
|
||||
- config.py 配置/路径/密钥 - db.py 数据层(建表/种子/审计)
|
||||
- crypto.py 口令哈希/Ed25519 - auth.py 鉴权(凭证/票据/防爆破/云端会话)
|
||||
- dingtalk.py 钉钉官方接口 - pkgutil.py 插件包校验/解析/版本
|
||||
- schemas.py 请求体模型 - apis/ 路由子包(meta/plugins/auth/dingtalk/admin)
|
||||
|
||||
DB:controlplane.db(同目录)。包文件:packages/。可选:CONTROLPLANE_TOKEN 非空时客户端须带
|
||||
X-API-Token 请求头。
|
||||
|
||||
运行(本地 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.app # 首次自动建表 + 种子 + 生成示例包
|
||||
uvicorn controlplane.app:app --port 8800
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from controlplane import config
|
||||
from controlplane.core.db import _init_db, _seed
|
||||
from controlplane.apis import admin as api_admin
|
||||
from controlplane.apis import auth as api_auth
|
||||
from controlplane.apis import dingtalk as api_dingtalk
|
||||
from controlplane.apis import meta as api_meta
|
||||
from controlplane.apis import plugins as api_plugins
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
_init_db()
|
||||
_seed()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du 内网插件控制面", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
||||
allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_plugins.router)
|
||||
app.include_router(api_auth.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_admin.router)
|
||||
|
||||
|
||||
# ==================== 挂载控制面前端产物 ====================
|
||||
# 源码模式 => config.DIST(controlplane/frontend/dist);exe 模式 => _MEIPASS/frontend/dist(打进 exe)
|
||||
if config.DIST.is_dir():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
# PyInstaller --noconsole 下 sys.stdout/stderr 可能为 None,
|
||||
# uvicorn 默认 DefaultFormatter 会调用 isatty() 导致启动崩溃,故自定义日志配置绕开颜色检测。
|
||||
LOG_CONFIG = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
"default": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||
"access": {"format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s"},
|
||||
},
|
||||
"handlers": {
|
||||
"default": {"class": "logging.StreamHandler", "formatter": "default"},
|
||||
"access": {"class": "logging.StreamHandler", "formatter": "access"},
|
||||
},
|
||||
"loggers": {
|
||||
"uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||
"uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False},
|
||||
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
|
||||
},
|
||||
}
|
||||
if getattr(sys, "frozen", False):
|
||||
if sys.stdout is None:
|
||||
sys.stdout = open(os.devnull, "w")
|
||||
if sys.stderr is None:
|
||||
sys.stderr = open(os.devnull, "w")
|
||||
|
||||
print(f"[controlplane] http://0.0.0.0:{config.CONTROLPLANE_PORT} sqlite={config.DB_PATH.name}")
|
||||
uvicorn.run(app, host="0.0.0.0", port=config.CONTROLPLANE_PORT,
|
||||
log_config=LOG_CONFIG, log_level="info")
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 领域逻辑核心(core)包:配置/数据/密码学/鉴权/插件包/钉钉/模型。"""
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机鉴权:内部凭证校验 + 管理员签名票据 + 登录防爆破 + 云端会话 token。
|
||||
|
||||
分层关系:
|
||||
- 内部凭证 X-API-Token:底座→统一后端的调用凭证(TOKEN 为空则内网可信,不强制)。
|
||||
- 管理员票据 X-Admin-Token:登录后签发的签名票据(签名密钥见 config._admin_secret),
|
||||
是唯一可信的管理员身份(不再信任可伪造的 X-Admin-User 明文)。
|
||||
- 云端会话 token:员工端扫码登录后持有的短期 token,调 /api/plugins 等作身份(§2.2)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.db import _db
|
||||
|
||||
|
||||
# ==================== 内部凭证 ====================
|
||||
def _check_token(x_api_token: str = "") -> None:
|
||||
"""底座→统一后端的内部调用凭证校验。TOKEN 空则不要求(内网可信场景)。"""
|
||||
if config.CONTROLPLANE_TOKEN and x_api_token != config.CONTROLPLANE_TOKEN:
|
||||
raise HTTPException(401, "鉴权失败:无效或缺失 X-API-Token")
|
||||
|
||||
|
||||
# ==================== 管理员签名票据 ====================
|
||||
def _sign_admin_token(account: str) -> str:
|
||||
"""签发带过期时间的签名票据:<base64url(json)>.<hmac_sig>,内含账号,防篡改/防伪造。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + config._ADMIN_TOKEN_TTL},
|
||||
separators=(",", ":")).encode()).decode().rstrip("=")
|
||||
sig = hmac.new(config._admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||
hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
def _verify_admin_token(tok: str) -> str:
|
||||
"""还原票据中的账号;签名无效或过期抛 ValueError。"""
|
||||
if "." not in tok:
|
||||
raise ValueError("invalid token")
|
||||
payload, sig = tok.rsplit(".", 1)
|
||||
expect = hmac.new(config._admin_secret().encode("utf-8"), payload.encode("utf-8"),
|
||||
hashlib.sha256).hexdigest()
|
||||
if not secrets.compare_digest(expect, sig):
|
||||
raise ValueError("bad signature")
|
||||
pad = "=" * (-len(payload) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(payload + pad))
|
||||
if int(data.get("e", 0)) < int(time.time()):
|
||||
raise ValueError("expired")
|
||||
return str(data.get("a", "") or "")
|
||||
|
||||
|
||||
def _require_admin(x_admin_token: str = "", x_api_token: str = "") -> str:
|
||||
"""管理操作:校验内部凭证(X-API-Token) + 登录票据(X-Admin-Token)对应账号 is_admin=1。返回账号。"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not account:
|
||||
raise HTTPException(401, "缺少有效登录态")
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM accounts WHERE account = ? AND is_admin = 1", (account,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(403, f"账号 {account} 无管理权限")
|
||||
return account
|
||||
|
||||
|
||||
def _resolve_login(x_admin_token: str = "", x_api_token: str = "",
|
||||
x_admin_user: str = "") -> str:
|
||||
"""解析请求身份(用户自助操作用,管理写操作仍走 _require_admin)。
|
||||
|
||||
1. 优先验签名票据 X-Admin-Token(控制台直连场景);
|
||||
2. 兜底接受底座正向代理注入的 X-Admin-User,但仅当 CONTROLPLANE_TOKEN 非空且
|
||||
请求携带匹配的 X-API-Token 时成立(防伪造;TOKEN 为空时拒绝,fail-closed)。
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
try:
|
||||
account = _verify_admin_token(x_admin_token)
|
||||
if account:
|
||||
return account
|
||||
except Exception:
|
||||
pass
|
||||
if (x_admin_user.strip() and config.CONTROLPLANE_TOKEN
|
||||
and x_api_token == config.CONTROLPLANE_TOKEN):
|
||||
return x_admin_user.strip()
|
||||
raise ValueError("no identity")
|
||||
|
||||
|
||||
# ==================== 登录防爆破(进程内计数,失败锁定退避) ====================
|
||||
_AUTH_FAILS: dict = {} # account -> [连续失败次数, 锁定截止时间戳]
|
||||
_AUTH_FAIL_LIMIT = 5 # 连续失败 N 次后锁定
|
||||
_AUTH_LOCK_SECS = 300 # 锁定 5 分钟
|
||||
|
||||
|
||||
def _auth_gate(account: str) -> None:
|
||||
fails, locked_until = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
if locked_until > time.time():
|
||||
raise HTTPException(429, f"失败次数过多,账号已临时锁定,请 {int(locked_until - time.time())} 秒后重试")
|
||||
|
||||
|
||||
def _auth_fail(account: str) -> None:
|
||||
fails, _ = _AUTH_FAILS.get(account, (0, 0.0))
|
||||
fails += 1
|
||||
if fails >= _AUTH_FAIL_LIMIT:
|
||||
_AUTH_FAILS[account] = (0, time.time() + _AUTH_LOCK_SECS)
|
||||
else:
|
||||
_AUTH_FAILS[account] = (fails, 0.0)
|
||||
|
||||
|
||||
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600 # 云端会话 token 有效期(秒,7 天)
|
||||
_cloud_tokens: dict = {} # token -> {exp, account, nickname};壳持此调云端 API
|
||||
_cloud_lock = threading.Lock()
|
||||
|
||||
|
||||
def _auth_account_lookup(account: str) -> dict:
|
||||
"""仅查询统一账号是否存在(登录链路不建号,建号只在管理员入口 /api/admin/dingtalk/auth)。
|
||||
|
||||
返回 {"exists": bool, "nickname": 账号记录昵称或空},绝不 INSERT accounts。
|
||||
"""
|
||||
if not account.strip():
|
||||
return {"exists": False, "nickname": ""}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname FROM accounts WHERE account = ?", (account.strip(),)).fetchone()
|
||||
return {"exists": bool(row), "nickname": (row["nickname"] if row else "") or ""}
|
||||
|
||||
|
||||
def _cloud_account(bearer: str) -> str:
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。"""
|
||||
token = (bearer or "").strip()
|
||||
if token.lower().startswith("bearer "):
|
||||
token = token[7:].strip()
|
||||
if not token:
|
||||
return ""
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
rec = _cloud_tokens.get(token)
|
||||
if rec and rec["exp"] >= now:
|
||||
return rec["account"]
|
||||
if rec: # 过期顺手清理,防内存无限增长
|
||||
_cloud_tokens.pop(token, None)
|
||||
return ""
|
||||
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机(控制面)配置:路径定位 + 本模块 env 加载 + 固化常量。
|
||||
|
||||
路径定位兼容两种运行形态(统一落到持久目录,禁止用 PyInstaller 临时解压目录,重启会丢数据):
|
||||
- 源码:uvicorn controlplane.app:app → APP_DIR = controlplane/
|
||||
- 打包:PyInstaller --onefile exe → APP_DIR = exe 同目录(db/packages/.admin_secret 持久可写)
|
||||
|
||||
env 专属:只读 controlplane/.env(或 exe 同目录 .env),环境变量优先、不覆盖已存在值。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_base() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent
|
||||
|
||||
|
||||
APP_DIR = _app_base()
|
||||
DB_PATH = APP_DIR / "controlplane.db"
|
||||
PKG_DIR = APP_DIR / "packages"
|
||||
# 壳子(执行机主程序)更新源:version.json + setup 安装包,供执行端自动下载升级
|
||||
SHELL_DIR = APP_DIR / "shell"
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读本模块专属 env。UTF-8、'#'注释/'空行'跳过;已存在的环境变量不覆盖。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
_k, _v = _k.strip(), _v.strip()
|
||||
if _k and _k not in os.environ:
|
||||
os.environ[_k] = _v
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# 内部凭证(底座→统一后端的调用凭证)。为空则不强制(内网可信场景)。
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
CONTROLPLANE_PORT = int(os.getenv("CONTROLPLANE_PORT", "8800"))
|
||||
# 钉钉扫码自动建号的初始密码;新号无插件权限、仅空壳,首次登录须改密。
|
||||
DINGTALK_DEFAULT_PASSWORD = os.getenv("DINGTALK_DEFAULT_PASSWORD", "123456")
|
||||
# 钉钉开放平台应用(真实扫码;未配置则钉钉扫码入口自动隐藏,仅保留账号密码登录)。
|
||||
# 同一套 KEY/SECRET 即可:扫码换 unionid/昵称 → gettoken 企业内部 token
|
||||
# → getbyunionid 取 userid → v2/user/get 取 job_number(工号),无需第二组凭证。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "")
|
||||
DINGTALK_APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "")
|
||||
# 钉钉扫码回调地址。网页扫码是"浏览器重定向"(非钉钉服务器回访),故可直接用内网 IP/域名,
|
||||
# 只要与用户实际访问地址、钉钉后台登记的回调域名一致即可。留空禁用扫码。
|
||||
DINGTALK_CALLBACK = os.getenv("DINGTALK_CALLBACK", "").rstrip("/")
|
||||
|
||||
# 管理台会话票据签名密钥:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > 首次随机生成并
|
||||
# 持久化到 .admin_secret(保证重启不回退,杜绝凭用户名 X-Admin-User 直接伪造身份)。
|
||||
_ADMIN_SECRET_CANDIDATE = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
_ADMIN_SECRET_FALLBACK: str = ""
|
||||
_ADMIN_TOKEN_TTL = 12 * 3600 # 票据有效期 12h
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
if _ADMIN_SECRET_CANDIDATE:
|
||||
return _ADMIN_SECRET_CANDIDATE
|
||||
global _ADMIN_SECRET_FALLBACK
|
||||
if _ADMIN_SECRET_FALLBACK:
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
_ADMIN_SECRET_FALLBACK = _f.read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
_ADMIN_SECRET_FALLBACK = secrets.token_hex(32)
|
||||
_f.write_text(_ADMIN_SECRET_FALLBACK, encoding="utf-8")
|
||||
return _ADMIN_SECRET_FALLBACK
|
||||
|
||||
|
||||
# 前端产物目录:源码 controlplane/frontend/dist;打包 _MEIPASS/frontend/dist(打进 exe)
|
||||
DIST = Path(getattr(sys, "_MEIPASS", APP_DIR)) / "frontend" / "dist"
|
||||
@@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机密码学:标准库口令哈希 + Ed25519 签名。
|
||||
|
||||
- 口令哈希:pbkdf2_hmac(sha256, 120_000 轮),盐随机 + 常数时间比较。
|
||||
- 签名:中心机私钥签名一切下发给部署端的可执行数据(license/control-list/download-ticket),
|
||||
部署端用缓存的公钥离线验签,保证离线环境下数据可信、防篡改、防伪造。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||
|
||||
from controlplane.core import config
|
||||
|
||||
_ITER = 120_000
|
||||
|
||||
|
||||
def _hash_password(pwd: str, salt: str = "") -> tuple[str, str]:
|
||||
salt = salt or secrets.token_hex(8)
|
||||
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), salt.encode("utf-8"), _ITER)
|
||||
return dk.hex(), salt
|
||||
|
||||
|
||||
def _verify_password(pwd: str, salt: str, hexdigest: str) -> bool:
|
||||
dk = hashlib.pbkdf2_hmac("sha256", pwd.encode("utf-8"), salt.encode("utf-8"), _ITER)
|
||||
return secrets.compare_digest(dk.hex(), hexdigest)
|
||||
|
||||
|
||||
# ==================== 产品化:Ed25519 密钥 + 签名票据 ====================
|
||||
# 密钥持久化到 APP_DIR/keys(重启复用,不回退)。
|
||||
_KEY_DIR = config.APP_DIR / "keys"
|
||||
_PRIV_PATH = _KEY_DIR / "center_key.priv"
|
||||
_PUB_PATH = _KEY_DIR / "center_key.pub"
|
||||
|
||||
|
||||
def _load_or_create_keypair() -> dict:
|
||||
"""首次启动生成并持久化 Ed25519 私钥/公钥(PEM),重启复用。"""
|
||||
_KEY_DIR.mkdir(exist_ok=True)
|
||||
if _PRIV_PATH.is_file() and _PUB_PATH.is_file():
|
||||
_priv = serialization.load_pem_private_key(_PRIV_PATH.read_bytes(), password=None)
|
||||
_pub = serialization.load_pem_public_key(_PUB_PATH.read_bytes())
|
||||
else:
|
||||
_priv = Ed25519PrivateKey.generate()
|
||||
_pub = _priv.public_key()
|
||||
_PRIV_PATH.write_bytes(_priv.private_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
_PUB_PATH.write_bytes(_pub.public_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo))
|
||||
return {"priv": _priv, "pub": _pub}
|
||||
|
||||
|
||||
_KEYS = _load_or_create_keypair()
|
||||
|
||||
|
||||
def _pubkey_pem() -> bytes:
|
||||
"""中心机公钥 PEM(下发给部署端缓存用于离线验签)。"""
|
||||
return _KEYS["pub"].public_bytes(
|
||||
serialization.Encoding.PEM,
|
||||
serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
|
||||
|
||||
def _sign_blob(payload: dict) -> str:
|
||||
"""签名打包:{base64url(json)}.{base64url(ed25519sig)}。signature=bin(64B) 后 base64url。"""
|
||||
canon = json.dumps(payload, ensure_ascii=False, separators=(",", ":"),
|
||||
sort_keys=True).encode("utf-8")
|
||||
sig = _KEYS["priv"].sign(canon)
|
||||
return (f"{base64.urlsafe_b64encode(canon).decode().rstrip('=')}."
|
||||
f"{base64.urlsafe_b64encode(sig).decode().rstrip('=')}")
|
||||
|
||||
|
||||
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
"""验签并返回 payload;签名非法/结构错误抛 ValueError。"""
|
||||
if "." not in blob:
|
||||
raise ValueError("bad blob")
|
||||
b64, sig64 = blob.rsplit(".", 1)
|
||||
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
@@ -0,0 +1,168 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机数据层:SQLite 访问 + 建表 + 种子 + 审计 + 常用时间戳。
|
||||
|
||||
数据访问统一收敛到 `_db()` 连接(commit+close 收口),路由只在本层之上组合读写。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.crypto import _hash_password
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _db():
|
||||
"""打开连接并在退出时 commit + close(统一收口,避免长运行服务累积连接)。
|
||||
|
||||
sqlite3 原生 with 语义只 commit 不 close,这里补 close;异常时不 commit 等价于回滚。
|
||||
"""
|
||||
conn = sqlite3.connect(config.DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _ensure_col(conn: sqlite3.Connection, table: str, col: str, ddl: str) -> None:
|
||||
"""幂等给表补列:列已存在则忽略(sqlite 无 ADD COLUMN IF NOT EXISTS)。"""
|
||||
cols = {r["name"] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
|
||||
if col not in cols:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}")
|
||||
|
||||
|
||||
def _init_db() -> None:
|
||||
"""建表(幂等)。基础表 + 产品化扩展表(插件授权/审计/运行上报),并兼容旧库补列。"""
|
||||
with _db() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
latest_version TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
plugin_id TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
uploaded_at TEXT NOT NULL,
|
||||
PRIMARY KEY (plugin_id, version)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
PRIMARY KEY (account, platform_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
account TEXT PRIMARY KEY,
|
||||
password_hash TEXT NOT NULL,
|
||||
salt TEXT NOT NULL,
|
||||
is_admin INTEGER DEFAULT 0,
|
||||
dept TEXT DEFAULT '',
|
||||
nickname TEXT DEFAULT '',
|
||||
dingtalk_uid TEXT DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS plugin_grants (
|
||||
account TEXT NOT NULL,
|
||||
plugin_id TEXT NOT NULL,
|
||||
can_download INTEGER DEFAULT 1,
|
||||
can_run INTEGER DEFAULT 1,
|
||||
PRIMARY KEY (account, plugin_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
action TEXT NOT NULL,
|
||||
target TEXT DEFAULT '',
|
||||
detail TEXT DEFAULT '',
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
account TEXT DEFAULT '',
|
||||
device_id TEXT DEFAULT '',
|
||||
plugin_id TEXT DEFAULT '',
|
||||
version TEXT DEFAULT '',
|
||||
status TEXT DEFAULT '',
|
||||
msg TEXT DEFAULT '',
|
||||
duration_sec INTEGER DEFAULT 0,
|
||||
at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
# 幂等补齐旧表可能缺失的可选列(sqlite ALTER 不支持 ADD COLUMN IF NOT EXISTS)
|
||||
_ensure_col(conn, "plugins", "description", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "category", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "icon", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "status", "TEXT DEFAULT 'published'")
|
||||
_ensure_col(conn, "plugins", "force_min_version", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "force_deadline", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "plugins", "manifest", "TEXT DEFAULT '{}'")
|
||||
_ensure_col(conn, "plugin_versions", "sha256", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "runtime_reports", "duration_sec", "INTEGER DEFAULT 0")
|
||||
_ensure_col(conn, "accounts", "nickname", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "dingtalk_uid", "TEXT DEFAULT ''")
|
||||
_ensure_col(conn, "accounts", "must_change_pwd", "INTEGER DEFAULT 0")
|
||||
# 回填:老库 account_plugins 已有授权但 plugin_grants 为空,则按"全权限"补录,
|
||||
# 保证离线票据 license 不会漏掉存量授权(can_download=1, can_run=1)。
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||||
"SELECT ap.account, ap.plugin_id, 1, 1 FROM account_plugins ap "
|
||||
"LEFT JOIN plugin_grants g ON g.account = ap.account AND g.plugin_id = ap.plugin_id "
|
||||
"WHERE g.account IS NULL"
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _seed() -> None:
|
||||
"""首次启动写入插件种子 + 默认管理员(puddy),并生成示例包。
|
||||
|
||||
不再种子 demo 普通账号(alice/bob 曾带弱口令入生产库),普通账号一律由管理员建号。
|
||||
"""
|
||||
config.PKG_DIR.mkdir(exist_ok=True)
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugins(id, name, latest_version) VALUES (?, ?, ?)",
|
||||
("seal_check", "考勤月报封存检查", "1.0.0"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO plugin_versions(plugin_id, version, filename, uploaded_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
("seal_check", "1.0.0", "seal_check_v1.0.0.zip", _now()),
|
||||
)
|
||||
# 默认管理员:仅作首次引导,生产环境建号后应立即改密
|
||||
for _acc, _dept in (("puddy", "IT"),):
|
||||
_hex, _salt = _hash_password("123456")
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO accounts(account, password_hash, salt, is_admin, dept) "
|
||||
"VALUES (?, ?, ?, ?, ?)", (_acc, _hex, _salt, 1, _dept))
|
||||
conn.commit()
|
||||
pkg = config.PKG_DIR / "seal_check_v1.0.0.zip"
|
||||
if not pkg.exists():
|
||||
pkg.write_bytes(b"# placeholder controlplane package v1.0.0\n")
|
||||
|
||||
|
||||
def _audit(account: str, action: str, target: str = "", detail: str = "") -> None:
|
||||
"""写入一条审计日志(下载/授权/管控/上报等关键操作);审计失败不阻断主流程。"""
|
||||
try:
|
||||
with _db() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO audit_logs(account, action, target, detail, at) VALUES (?,?,?,?,?)",
|
||||
(account or "", action, target or "", detail or "", _now()))
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
@@ -0,0 +1,145 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机钉钉官方接口封装:OAuth 扫码换身份 + 内嵌二维码(DDLogin)+ 工号解析。
|
||||
|
||||
与 webhost 扫码登录共用一套凭证语义:DINGTALK_APP_KEY/SECRET 即可完成
|
||||
扫码换 unionid/昵称 → gettoken 企业内部 token → getbyunionid 取 userid → v2/user/get 取工号。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from controlplane.core import config
|
||||
|
||||
|
||||
def _dingtalk_get_json(url: str, headers: dict | None = None) -> dict:
|
||||
req = Request(url, method="GET")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
try:
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except OSError as _e:
|
||||
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
|
||||
|
||||
|
||||
def _dingtalk_post_json(url: str, payload: dict) -> dict:
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except OSError as _e:
|
||||
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
|
||||
|
||||
|
||||
# 企业内部 token 缓存(gettoken 的 access_token 有 TTL,缓存到临近过期)
|
||||
_DINGTALK_TOPAPI = {"at": "", "exp": 0.0}
|
||||
|
||||
|
||||
def _dingtalk_topapi_token() -> str:
|
||||
"""获取企业内部应用 access_token(取工号链路用)。复用 DINGTALK_APP_KEY/SECRET。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
return ""
|
||||
now = time.time()
|
||||
if _DINGTALK_TOPAPI["at"] and _DINGTALK_TOPAPI["exp"] > now + 60:
|
||||
return _DINGTALK_TOPAPI["at"]
|
||||
try:
|
||||
info = _dingtalk_get_json(
|
||||
"https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s"
|
||||
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
|
||||
at = info.get("access_token", "")
|
||||
if not at:
|
||||
return ""
|
||||
_DINGTALK_TOPAPI["at"] = at
|
||||
_DINGTALK_TOPAPI["exp"] = now + int(info.get("expires_in", 7200))
|
||||
return at
|
||||
except Exception: # noqa: BLE001 取企业内部 token 失败不阻断扫码登录
|
||||
return ""
|
||||
|
||||
|
||||
def _dingtalk_userinfo(auth_code: str) -> dict:
|
||||
"""用钉钉扫码回调的 authCode 换取当前钉钉用户工号/姓名/unionid。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
# Step1: authCode -> accessToken -> unionid + nick
|
||||
tok = _dingtalk_post_json(
|
||||
"https://api.dingtalk.com/v1.0/oauth2/userAccessToken",
|
||||
{"clientId": config.DINGTALK_APP_KEY, "clientSecret": config.DINGTALK_APP_SECRET,
|
||||
"code": auth_code, "grantType": "authorization_code"})
|
||||
at = tok.get("accessToken")
|
||||
if not at:
|
||||
raise HTTPException(401, "钉钉授权码无效或已过期,请重新扫码")
|
||||
me = _dingtalk_get_json(
|
||||
"https://api.dingtalk.com/v1.0/contact/users/me",
|
||||
{"x-acs-dingtalk-access-token": at})
|
||||
unionid = me.get("unionId") or me.get("unionid") or ""
|
||||
nickname = me.get("nick") or ""
|
||||
account = me.get("jobNumber") or me.get("userId") or unionid
|
||||
# Step2/3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
|
||||
top_at = _dingtalk_topapi_token()
|
||||
if top_at and unionid:
|
||||
try:
|
||||
byunion = _dingtalk_post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
|
||||
{"unionid": unionid})
|
||||
ures = byunion.get("result") or {}
|
||||
userid = ures.get("userid") or ures.get("userId") or ""
|
||||
if userid:
|
||||
ud = _dingtalk_post_json(
|
||||
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
|
||||
{"userid": userid})
|
||||
res = ud.get("result") or {}
|
||||
job = res.get("job_number") or res.get("jobNumber") or ""
|
||||
nickname = nickname or res.get("name") or ""
|
||||
account = job or userid or account
|
||||
except Exception: # noqa: BLE001 取工号失败不阻断登录,回退已得字段
|
||||
pass
|
||||
return {"account": account, "nickname": nickname, "unionid": unionid}
|
||||
|
||||
|
||||
def _dingtalk_sns_userinfo(login_tmp_code: str) -> dict:
|
||||
"""内嵌二维码扫码(钉钉 DDLogin):loginTmpCode → sns unionid/nick → 企业内部取工号。
|
||||
|
||||
与 _dingtalk_userinfo 的区别仅在于换码入口:OAuth 用 userAccessToken(code),
|
||||
内嵌二维码用 sns/gettoken + sns/getuserinfo_bycode(loginTmpCode)。取工号链路共用。
|
||||
"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
# Step1: loginTmpCode -> sns access_token
|
||||
tok = _dingtalk_get_json(
|
||||
"https://oapi.dingtalk.com/sns/gettoken?access_key=%s&access_secret=%s"
|
||||
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
|
||||
at = tok.get("access_token")
|
||||
if not at:
|
||||
raise HTTPException(401, "钉钉扫码码无效或已过期,请重新扫码")
|
||||
# Step2: sns access_token -> unionid + nick
|
||||
info = _dingtalk_post_json(
|
||||
"https://oapi.dingtalk.com/sns/getuserinfo_bycode?access_token=%s" % at,
|
||||
{"tmp_auth_code": login_tmp_code})
|
||||
ui = info.get("user_info") or info.get("userInfo") or info
|
||||
unionid = ui.get("unionid") or ui.get("unionId") or ""
|
||||
nickname = ui.get("nick") or ""
|
||||
# Step3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
|
||||
account = unionid
|
||||
top_at = _dingtalk_topapi_token()
|
||||
if top_at and unionid:
|
||||
try:
|
||||
byunion = _dingtalk_post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
|
||||
{"unionid": unionid})
|
||||
ures = byunion.get("result") or {}
|
||||
userid = ures.get("userid") or ures.get("userId") or ""
|
||||
if userid:
|
||||
ud = _dingtalk_post_json(
|
||||
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
|
||||
{"userid": userid})
|
||||
res = ud.get("result") or {}
|
||||
job = res.get("job_number") or res.get("jobNumber") or ""
|
||||
account = job or userid or account
|
||||
except Exception: # noqa: BLE001 取工号失败不阻断,回退已得字段
|
||||
pass
|
||||
return {"account": account, "nickname": nickname, "unionid": unionid}
|
||||
@@ -0,0 +1,93 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机插件包工具:ZIP 完整性校验、manifest 解析、版本保留裁剪、版本比较。
|
||||
|
||||
纯计算/解析逻辑,不触碰文件系统与 DB(文件落盘/删除由路由层按返回结果执行)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
# 插件包约束:大小上限 / 必含文件 / 保留版本数 / 安全文件名
|
||||
_PKG_MAX_BYTES = 200 * 1024 * 1024
|
||||
# webhost 执行端插件为 __init__.py 注册风格,故仅强制 plugin.json(manifest 契约);
|
||||
# main.py 仅作为通用入口可选,不再必含。
|
||||
_PKG_REQUIRED_FILES = ("plugin.json",)
|
||||
_KEEP_VERSIONS = 3
|
||||
_SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
||||
|
||||
|
||||
def _load_manifest(raw: str) -> dict:
|
||||
"""读取存储的插件 manifest(异常安全,回空 dict)。"""
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
d = json.loads(raw)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def _validate_pkg_zip(content: bytes) -> None:
|
||||
"""插件包完整性校验:体积上限 + ZIP 结构 + 必含文件 + plugin.json 可解析。"""
|
||||
if len(content) > _PKG_MAX_BYTES:
|
||||
raise HTTPException(400, f"插件包超过大小上限({_PKG_MAX_BYTES // 1024 // 1024}MB)")
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
raise HTTPException(400, "上传内容不是有效的 ZIP 包")
|
||||
with zf:
|
||||
if zf.testzip() is not None:
|
||||
raise HTTPException(400, "ZIP 包校验失败(存在损坏条目)")
|
||||
names = set(zf.namelist())
|
||||
missing = [f for f in _PKG_REQUIRED_FILES if f not in names]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
400, f"插件包缺少必需文件:{', '.join(missing)}(包根目录需含 plugin.json / main.py / requirements.txt)")
|
||||
try:
|
||||
json.loads(zf.read("plugin.json").decode("utf-8"))
|
||||
except Exception:
|
||||
raise HTTPException(400, "plugin.json 不是合法 JSON")
|
||||
|
||||
|
||||
def _extract_manifest(content: bytes) -> dict | None:
|
||||
"""从插件包读取 plugin.json 并解析为 manifest(存在且合法才返回)。
|
||||
|
||||
作为插件契约的权威来源:元数据 + JSON-Schema 表单 + capabilities/permissions。
|
||||
缺文件或解析失败返回 None,交由上层决定是否拒绝。
|
||||
"""
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
with zf:
|
||||
raw = zf.read("plugin.json").decode("utf-8")
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return data
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _prune_versions(conn, plugin_id: str) -> list:
|
||||
"""仅保留最近 _KEEP_VERSIONS 个版本,返回待清理的磁盘文件名列表(调用方负责删文件)。"""
|
||||
rows = conn.execute(
|
||||
"SELECT version, filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,)).fetchall()
|
||||
stale = sorted(rows, key=lambda r: _version_key(r["version"]), reverse=True)[_KEEP_VERSIONS:]
|
||||
for r in stale:
|
||||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ? AND version = ?",
|
||||
(plugin_id, r["version"]))
|
||||
return [r["filename"] for r in stale]
|
||||
|
||||
|
||||
def _version_key(v: str):
|
||||
"""版本比较键:数字段转 (1, int),非数字段转 (0, str),保证段间可比较(1.0.0-beta 不触发 int/str 类型错误)。"""
|
||||
def to_key(s):
|
||||
try:
|
||||
return (1, int(s))
|
||||
except ValueError:
|
||||
return (0, str(s).lower())
|
||||
return tuple(to_key(x) for x in str(v).split("."))
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""中心机请求体模型(Pydantic),路由层统一复用。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class PluginOut(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
version: str
|
||||
|
||||
|
||||
class RuntimeReportIn(BaseModel):
|
||||
account: str = ""
|
||||
device_id: str = ""
|
||||
plugin_id: str = ""
|
||||
version: str = ""
|
||||
status: str = ""
|
||||
msg: str = ""
|
||||
duration_sec: int = 0
|
||||
|
||||
|
||||
class AuthIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class DingTalkIn(BaseModel):
|
||||
account: str # 工号(作为统一账号)
|
||||
nickname: str = ""
|
||||
dingtalk_uid: str = ""
|
||||
password: str = "" # 可选:覆盖默认初始密码(一般留空走 DINGTALK_DEFAULT_PASSWORD)
|
||||
|
||||
|
||||
class SnsIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后前端拿到的 loginTmpCode
|
||||
|
||||
|
||||
class AuthExchangeIn(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
class AccountCreateIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
dept: str = ""
|
||||
nickname: str = ""
|
||||
is_admin: bool = False
|
||||
|
||||
|
||||
class AccountUpdateIn(BaseModel):
|
||||
account: str
|
||||
dept: str | None = None
|
||||
nickname: str | None = None
|
||||
is_admin: bool | None = None
|
||||
|
||||
|
||||
class AccountResetIn(BaseModel):
|
||||
account: str
|
||||
new_password: str
|
||||
|
||||
|
||||
class AccountDelIn(BaseModel):
|
||||
account: str
|
||||
|
||||
|
||||
class GrantIn(BaseModel):
|
||||
account: str
|
||||
plugin_id: str
|
||||
granted: bool
|
||||
can_download: bool = True # 可选:插件级下载授权(默认授予)
|
||||
can_run: bool = True # 可选:插件级运行授权(默认授予)
|
||||
|
||||
|
||||
class PlatformGrantIn(BaseModel):
|
||||
account: str
|
||||
platform_id: str
|
||||
granted: bool
|
||||
|
||||
|
||||
class PluginDelIn(BaseModel):
|
||||
plugin_id: str
|
||||
|
||||
|
||||
class PluginPatchIn(BaseModel):
|
||||
name: str = ""
|
||||
description: str = ""
|
||||
category: str = ""
|
||||
icon: str = ""
|
||||
status: str = "" # 空=不改;published / disabled / revoked
|
||||
force_min_version: str = "" # 与 deadline 成对生效;二者齐全=开启,否则看 clear_force
|
||||
force_deadline: str = "" # ISO 时间串
|
||||
clear_force: bool = False # True = 清除强制更新配置
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"filename": "setup-37du-host-1.0.0.exe",
|
||||
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||
"notes": "初始版本"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 内网插件控制面</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1743
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "37du-controlplane-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"naive-ui": "^2.45.3",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
<template>
|
||||
<n-config-provider :theme-overrides="themeOverrides" :locale="zhCN" :date-locale="dateZhCN">
|
||||
<LoginPage v-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="console" v-else>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>中心机 · 控制面</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<n-dropdown trigger="click" :options="acctOptions" @select="onCommand">
|
||||
<div class="acct">
|
||||
<span class="avatar">{{ initial }}</span>
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<n-tag v-if="store.isAdmin" size="small" round :bordered="false" type="primary" class="admin-tag">管理员</n-tag>
|
||||
<n-icon class="caret" :size="13"><ArrowDown /></n-icon>
|
||||
</div>
|
||||
</n-dropdown>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<aside class="aside">
|
||||
<div class="aside-inner">
|
||||
<n-menu class="menu" :value="activeKey" :options="menuOptions" :root-indent="0" @update:value="onMenu" />
|
||||
</div>
|
||||
<div class="aside-foot">
|
||||
<span>37du 自动化</span>
|
||||
<span class="ver">v0.1.0</span>
|
||||
</div>
|
||||
</aside>
|
||||
<main class="main">
|
||||
<component :is="viewComp" :key="route" />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<PasswordDialog v-model="pwdOpen" />
|
||||
</n-config-provider>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ArrowDown } from '@element-plus/icons-vue'
|
||||
import { themeOverrides, zhCN, dateZhCN, message } from './naive'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import PasswordDialog from './components/PasswordDialog.vue'
|
||||
import OverviewView from './views/OverviewView.vue'
|
||||
import PluginManageView from './views/PluginManageView.vue'
|
||||
import AccountManageView from './views/AccountManageView.vue'
|
||||
import GrantManageView from './views/GrantManageView.vue'
|
||||
import StatsView from './views/StatsView.vue'
|
||||
import AuditView from './views/AuditView.vue'
|
||||
import { store, clearSession } from './store'
|
||||
import { adminMe } from './api'
|
||||
|
||||
const menuOptions = [
|
||||
{ label: '概览', key: 'overview' },
|
||||
{ label: '数据看板', key: 'stats' },
|
||||
{ label: '插件管理', key: 'plugins' },
|
||||
{ label: '账号管理', key: 'accounts' },
|
||||
{ label: '权限授权', key: 'grants' },
|
||||
{ label: '审计报表', key: 'audit' },
|
||||
]
|
||||
const acctOptions = [
|
||||
{ label: '修改密码', key: 'pwd' },
|
||||
{ type: 'divider', key: 'd1' },
|
||||
{ label: '退出登录', key: 'logout' },
|
||||
]
|
||||
|
||||
// 轻量 hash 路由:StaticFiles(html=True) 下刷新安全,零后端改动
|
||||
const KEY = {
|
||||
'#/overview': 'overview',
|
||||
'#/stats': 'stats',
|
||||
'#/plugins': 'plugins',
|
||||
'#/accounts': 'accounts',
|
||||
'#/grants': 'grants',
|
||||
'#/audit': 'audit',
|
||||
}
|
||||
const VIEWS = {
|
||||
'#/overview': OverviewView,
|
||||
'#/stats': StatsView,
|
||||
'#/plugins': PluginManageView,
|
||||
'#/accounts': AccountManageView,
|
||||
'#/grants': GrantManageView,
|
||||
'#/audit': AuditView,
|
||||
}
|
||||
const route = ref(VIEWS[location.hash] ? location.hash : '#/overview')
|
||||
window.addEventListener('hashchange', () => {
|
||||
if (VIEWS[location.hash]) route.value = location.hash
|
||||
})
|
||||
const viewComp = computed(() => VIEWS[route.value] || OverviewView)
|
||||
const activeKey = computed(() => KEY[route.value] || 'overview')
|
||||
|
||||
function onMenu(key) {
|
||||
const h = '#/' + key
|
||||
location.hash = h
|
||||
route.value = h
|
||||
}
|
||||
|
||||
const initial = computed(() => (store.current || '')[0]?.toUpperCase() || '?')
|
||||
|
||||
const pwdOpen = ref(false)
|
||||
function onCommand(cmd) {
|
||||
if (cmd === 'pwd') pwdOpen.value = true
|
||||
else if (cmd === 'logout') {
|
||||
clearSession()
|
||||
message.success('已退出登录')
|
||||
}
|
||||
}
|
||||
|
||||
function onLogin() {
|
||||
route.value = '#/overview'
|
||||
location.hash = '#/overview'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 已本地标记登录时,校验登录票据仍有效且为管理员(票据过期/权限变更后回登录页)
|
||||
if (!store.current) return
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account || !me.is_admin) clearSession()
|
||||
else store.isAdmin = true
|
||||
} catch (_) { /* 后端 down:保持本地态 */ }
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.console { height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* ---------- 顶栏:磨砂玻璃 ---------- */
|
||||
.topbar {
|
||||
height: 64px; flex-shrink: 0;
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 0 24px;
|
||||
background: rgba(255, 255, 255, .72);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border-bottom: 1px solid var(--cp-border);
|
||||
position: relative; z-index: 20;
|
||||
}
|
||||
.topbar::after {
|
||||
content: ''; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(59, 108, 255, .35), rgba(34, 199, 232, .35), transparent);
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 12px; }
|
||||
.logo {
|
||||
width: 38px; height: 38px; border-radius: 12px;
|
||||
display: grid; place-items: center; position: relative;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
color: #fff; font-size: 14px; font-weight: 800; letter-spacing: .5px;
|
||||
box-shadow: 0 6px 16px -6px rgba(59, 108, 255, .6);
|
||||
}
|
||||
.logo::after { content: ''; position: absolute; inset: 2px; border-radius: 10px; border: 1px solid rgba(255, 255, 255, .28); }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; color: var(--cp-ink); letter-spacing: .2px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--cp-ink-3); letter-spacing: .4px; }
|
||||
.spacer { flex: 1; }
|
||||
|
||||
.acct {
|
||||
display: flex; align-items: center; gap: 9px; cursor: pointer;
|
||||
padding: 6px 10px; border-radius: 12px; transition: background .18s;
|
||||
}
|
||||
.acct:hover { background: rgba(59, 108, 255, .07); }
|
||||
.avatar {
|
||||
width: 30px; height: 30px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
color: #fff; font-size: 13px; font-weight: 700;
|
||||
}
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--cp-ink); }
|
||||
.admin-tag { margin-left: 2px; }
|
||||
.caret { color: var(--cp-ink-3); }
|
||||
|
||||
/* ---------- 主体:悬浮侧栏 + 内容区 ---------- */
|
||||
.body { flex: 1; display: flex; gap: 18px; padding: 18px 24px 24px; min-height: 0; }
|
||||
.aside {
|
||||
width: 208px; flex-shrink: 0;
|
||||
display: flex; flex-direction: column;
|
||||
background: rgba(255, 255, 255, .78);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
padding: 14px 10px;
|
||||
}
|
||||
.aside-inner { flex: 1; }
|
||||
.aside-foot {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 12px 12px 4px; margin-top: 8px;
|
||||
border-top: 1px dashed var(--cp-border);
|
||||
font-size: 11px; color: var(--cp-ink-3);
|
||||
}
|
||||
.main { flex: 1; min-width: 0; overflow: auto; padding: 4px 4px 8px; }
|
||||
|
||||
/* 页面切换过渡:轻微上浮淡入 */
|
||||
.view-fade-enter-active { transition: opacity .22s ease, transform .22s ease; }
|
||||
.view-fade-leave-active { transition: opacity .12s ease; }
|
||||
.view-fade-enter-from { opacity: 0; transform: translateY(8px); }
|
||||
.view-fade-leave-to { opacity: 0; }
|
||||
|
||||
/* ---------- 侧栏菜单:干净的标准导航,配色由 naive 主题统一控制 ---------- */
|
||||
.menu { padding: 2px; }
|
||||
.menu :deep(.n-menu-item) { margin-bottom: 4px; }
|
||||
.menu :deep(.n-menu-item-content) {
|
||||
/* 无图标时 naive 给 `padding-left:0` 的内联样式,需 !important 压过,
|
||||
否则文字贴左边界、跑出圆角底色区域 */
|
||||
padding-left: 16px !important;
|
||||
padding-right: 16px !important;
|
||||
border-radius: 10px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,116 @@
|
||||
// 与 FastAPI 后端交互,控制面前端直连 /api/*
|
||||
import { store } from './store.js'
|
||||
|
||||
async function req(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// 管理接口无状态鉴权:携带登录后签发的签名票据(X-Admin-Token),后端验票解得当前账号
|
||||
function adminHeaders(extra = {}) {
|
||||
return { 'X-Admin-Token': store.token || '', ...extra }
|
||||
}
|
||||
|
||||
export async function adminLogin(account, password) {
|
||||
return req('/api/admin/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ account, password })
|
||||
})
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return req('/api/admin/password', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminMe() {
|
||||
return req('/api/admin/me', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminOverview() {
|
||||
return req('/api/admin/overview', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminPlatforms() {
|
||||
return req('/api/admin/platforms', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminGrant(body) {
|
||||
return req('/api/admin/account_plugins', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminPlatformGrant(body) {
|
||||
return req('/api/admin/account_platforms', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccounts() {
|
||||
return req('/api/admin/accounts', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminAccountCreate(body) {
|
||||
return req('/api/admin/account', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountUpdate(body) {
|
||||
return req('/api/admin/account/update', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountReset(body) {
|
||||
return req('/api/admin/account/reset_pwd', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAccountDelete(body) {
|
||||
return req('/api/admin/account/delete', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminPluginDelete(body) {
|
||||
return req('/api/admin/plugin/delete', {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminPluginPatch(pluginId, body) {
|
||||
const qs = new URLSearchParams({ plugin_id: pluginId })
|
||||
return req('/api/admin/plugin/patch?' + qs.toString(), {
|
||||
method: 'POST',
|
||||
headers: adminHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(body)
|
||||
})
|
||||
}
|
||||
export async function adminAudit(limit = 300) {
|
||||
return req('/api/admin/audit?limit=' + limit, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminReports(limit = 300) {
|
||||
return req('/api/admin/reports?limit=' + limit, { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminStats() {
|
||||
return req('/api/admin/stats', { headers: adminHeaders() })
|
||||
}
|
||||
export async function adminUpload(pluginId, name, version, file) {
|
||||
const fd = new FormData()
|
||||
fd.append('upload', file)
|
||||
const qs = new URLSearchParams({ plugin_id: pluginId, name, version })
|
||||
return req('/api/admin/pkg?' + qs.toString(), { method: 'POST', headers: adminHeaders(), body: fd })
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<div class="card">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<h1>{{ appName }}</h1>
|
||||
<p>中心机统一账户登录</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<n-form class="form" label-placement="top" @keydown.enter.prevent="doLogin">
|
||||
<n-form-item label="账号">
|
||||
<n-input
|
||||
v-model:value="account"
|
||||
placeholder="请输入账号"
|
||||
autocomplete="username"
|
||||
size="large"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><User /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-form-item label="密码">
|
||||
<n-input
|
||||
v-model:value="password"
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
autocomplete="current-password"
|
||||
size="large"
|
||||
show-password-on="click"
|
||||
@keyup.enter="doLogin"
|
||||
>
|
||||
<template #prefix><n-icon><Lock /></n-icon></template>
|
||||
</n-input>
|
||||
</n-form-item>
|
||||
<n-button type="primary" size="large" block class="primary" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '登录中…' : '登 录' }}
|
||||
</n-button>
|
||||
</n-form>
|
||||
|
||||
<div class="foot">内网管理面 · 请使用管理员账号登录</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { User, Lock } from '@element-plus/icons-vue'
|
||||
import { adminLogin } from '../api'
|
||||
import { store } from '../store.js'
|
||||
import { message } from '../naive'
|
||||
|
||||
const props = defineProps({ appName: { type: String, default: '37du 自动化工作台' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
async function doLogin() {
|
||||
if (busy.value) return
|
||||
const acct = account.value.trim()
|
||||
if (!acct || !password.value) { message.warning('请输入账号与密码'); return }
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminLogin(acct, password.value)
|
||||
if (!r.ok) throw new Error('登录失败')
|
||||
if (!r.is_admin) { throw new Error('该账号无管理权限') }
|
||||
store.current = acct
|
||||
store.token = r.token || ''
|
||||
store.isAdmin = true
|
||||
try { localStorage.setItem('cp_account', acct); localStorage.setItem('cp_token', store.token) } catch (_) {}
|
||||
message.success(`欢迎,${acct}`)
|
||||
emit('ok', r)
|
||||
} catch (e) {
|
||||
message.error(e.message || String(e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
background: linear-gradient(180deg, #f7f8fa 0%, #eef0f4 100%);
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
.card {
|
||||
width: 380px;
|
||||
box-sizing: border-box;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--cp-border, #e5e7ec);
|
||||
border-radius: 16px;
|
||||
padding: 34px 32px 28px;
|
||||
box-shadow: 0 16px 40px -24px rgba(30, 42, 76, .25);
|
||||
}
|
||||
|
||||
.brand { display: flex; align-items: center; gap: 14px; margin-bottom: 28px; }
|
||||
.logo {
|
||||
width: 42px; height: 42px; border-radius: 12px; flex: none;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff 0%, #22c7e8 130%);
|
||||
color: #fff; font-size: 15px; font-weight: 800; letter-spacing: .4px;
|
||||
box-shadow: 0 8px 18px -8px rgba(59, 108, 255, .55);
|
||||
}
|
||||
.brand-meta h1 { margin: 0; font-size: 17px; font-weight: 700; color: var(--cp-ink, #1c2433); letter-spacing: .2px; }
|
||||
.brand-meta p { margin: 3px 0 0; font-size: 12px; color: var(--cp-ink-3, #8a93a6); }
|
||||
|
||||
.form :deep(.n-form-item) { margin-bottom: 20px; }
|
||||
.form :deep(.n-form-item-label) { font-size: 12.5px; font-weight: 600; color: var(--cp-ink-2, #4a5270); padding-bottom: 6px; }
|
||||
.form :deep(.n-input) { border-radius: 8px; }
|
||||
.form :deep(.n-input__inner) { font-size: 14px; }
|
||||
|
||||
.primary.n-button--primary-type { height: 44px; border-radius: 8px; font-size: 14px; letter-spacing: .1em; }
|
||||
|
||||
.foot { margin-top: 20px; text-align: center; font-size: 11.5px; color: var(--cp-ink-3, #8a93a6); }
|
||||
</style>
|
||||
@@ -0,0 +1,70 @@
|
||||
<template>
|
||||
<n-modal v-model:show="visible" preset="card" title="修改密码" :style="{ width: '420px' }" :bordered="false" @after-leave="reset">
|
||||
<n-alert v-if="store.current" type="info" :bordered="false" class="acct-tip">当前账号:{{ store.current }}</n-alert>
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="原密码" path="oldPwd">
|
||||
<n-input v-model:value="form.oldPwd" type="password" show-password-on="click" placeholder="请输入原密码" />
|
||||
</n-form-item>
|
||||
<n-form-item label="新密码" path="newPwd">
|
||||
<n-input v-model:value="form.newPwd" type="password" show-password-on="click" placeholder="至少 6 位,不与原密码相同" />
|
||||
</n-form-item>
|
||||
<n-form-item label="确认新密码" path="newPwd2">
|
||||
<n-input v-model:value="form.newPwd2" type="password" show-password-on="click" placeholder="再次输入新密码" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="visible = false">取消</n-button>
|
||||
<n-button type="primary" :loading="busy" @click="submit">保存</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-modal>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref } from 'vue'
|
||||
import { store } from '../store'
|
||||
import { adminPassword } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const visible = defineModel({ type: Boolean, default: false })
|
||||
const formRef = ref()
|
||||
const busy = ref(false)
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
|
||||
const rules = {
|
||||
oldPwd: { required: true, message: '请输入原密码' },
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码' },
|
||||
{ min: 6, message: '新密码至少 6 位' },
|
||||
{ validator: (_r, v) => (v && v === form.oldPwd ? new Error('新密码不能与原密码相同') : true), message: '新密码不能与原密码相同' },
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码' },
|
||||
{ validator: (_r, v) => (v !== form.newPwd ? new Error('两次输入的密码不一致') : true), message: '两次输入的密码不一致' },
|
||||
],
|
||||
}
|
||||
|
||||
function reset() {
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
formRef.value?.restoreValidation()
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
busy.value = true
|
||||
try {
|
||||
await adminPassword({ account: store.current, old_password: form.oldPwd, new_password: form.newPwd })
|
||||
message.success('密码已修改,下次登录请使用新密码')
|
||||
visible.value = false
|
||||
} catch (e) {
|
||||
message.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.acct-tip { margin-bottom: 14px; }
|
||||
</style>
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createApp } from 'vue'
|
||||
import naive from 'naive-ui'
|
||||
// 图标沿用 @element-plus/icons-vue(纯 SVG 组件,与 UI 框架解耦)
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
const app = createApp(App)
|
||||
// 全量注册图标,模板中可直接用图标名,概览页卡片动态渲染需要
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(naive).mount('#app')
|
||||
@@ -0,0 +1,62 @@
|
||||
// Naive UI 主题与离散式反馈(message/dialog 无需 Provider 包裹即可调用)
|
||||
import { createDiscreteApi, zhCN, dateZhCN } from 'naive-ui'
|
||||
|
||||
export const themeOverrides = {
|
||||
common: {
|
||||
primaryColor: '#3b6cff',
|
||||
primaryColorHover: '#5e84ff',
|
||||
primaryColorPressed: '#2f56d6',
|
||||
primaryColorSuppl: '#4c79ff',
|
||||
infoColor: '#3b6cff',
|
||||
successColor: '#22b07a',
|
||||
warningColor: '#eab308',
|
||||
errorColor: '#e5484d',
|
||||
borderRadius: '10px',
|
||||
borderRadiusSmall: '8px',
|
||||
fontFamily:
|
||||
'"HarmonyOS Sans SC","Microsoft YaHei UI","PingFang SC",-apple-system,"Segoe UI",sans-serif',
|
||||
},
|
||||
Card: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
Button: {
|
||||
borderRadiusMedium: '10px',
|
||||
borderRadiusLarge: '12px',
|
||||
},
|
||||
Menu: {
|
||||
itemHeight: '46px',
|
||||
itemBorderRadius: '10px',
|
||||
itemTextColor: '#3a4660',
|
||||
itemTextColorHover: '#3b6cff',
|
||||
itemTextColorActive: '#3b6cff',
|
||||
itemTextColorActiveHover: '#2f56d6',
|
||||
itemColorHover: 'rgba(31, 45, 80, .05)',
|
||||
itemColorActive: 'rgba(59, 108, 255, .10)',
|
||||
itemColorActiveHover: 'rgba(59, 108, 255, .15)',
|
||||
iconColor: '#7b8aa8',
|
||||
iconColorHover: '#3b6cff',
|
||||
iconColorActive: '#3b6cff',
|
||||
iconColorActiveHover: '#2f56d6',
|
||||
},
|
||||
DataTable: {
|
||||
thColor: '#f5f8fe',
|
||||
thTextColor: '#5b6b8c',
|
||||
thFontWeight: '600',
|
||||
tdColor: 'transparent',
|
||||
tdColorHover: 'rgba(59,108,255,.06)',
|
||||
borderColor: 'rgba(88,113,183,.10)',
|
||||
borderRadius: '12px',
|
||||
},
|
||||
Dialog: {
|
||||
borderRadius: '16px',
|
||||
},
|
||||
}
|
||||
|
||||
export const { message, dialog, notification } = createDiscreteApi(
|
||||
['message', 'dialog', 'notification'],
|
||||
{
|
||||
configProviderProps: { themeOverrides, locale: zhCN, dateLocale: dateZhCN },
|
||||
}
|
||||
)
|
||||
|
||||
export { zhCN, dateZhCN }
|
||||
@@ -0,0 +1,40 @@
|
||||
import { reactive, ref } from 'vue'
|
||||
import { adminOverview } from './api'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '37du 内网插件控制面',
|
||||
isAdmin: false,
|
||||
current: _get('cp_account'),
|
||||
token: _get('cp_token'),
|
||||
})
|
||||
|
||||
// 概览数据缓存:各管理页共用一份 adminOverview 结果,避免切页重复拉取
|
||||
export const overview = ref(null)
|
||||
export const overviewBusy = ref(false)
|
||||
|
||||
export async function loadOverview(force = false) {
|
||||
if (overview.value && !force) return overview.value
|
||||
overviewBusy.value = true
|
||||
try {
|
||||
overview.value = await adminOverview()
|
||||
return overview.value
|
||||
} finally {
|
||||
overviewBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
export function resetOverview() {
|
||||
overview.value = null
|
||||
}
|
||||
|
||||
function _get(key) {
|
||||
try { return localStorage.getItem(key) || '' } catch (_) { return '' }
|
||||
}
|
||||
|
||||
export function clearSession() {
|
||||
store.current = ''
|
||||
store.token = ''
|
||||
store.isAdmin = false
|
||||
resetOverview()
|
||||
try { localStorage.removeItem('cp_account'); localStorage.removeItem('cp_token') } catch (_) {}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/* ============ 37du 内网插件控制面 全局基础样式(组件由 Naive UI 提供) ============ */
|
||||
:root {
|
||||
/* 设计令牌:文字 / 边框 / 表面 / 品牌色 / 投影 */
|
||||
--cp-ink: #141c33;
|
||||
--cp-ink-2: #5b6b8c;
|
||||
--cp-ink-3: #94a3c4;
|
||||
--cp-border: rgba(88, 113, 183, .14);
|
||||
--cp-surface: rgba(255, 255, 255, .82);
|
||||
--cp-blue: #3b6cff;
|
||||
--cp-cyan: #22c7e8;
|
||||
--cp-violet: #8b5cf6;
|
||||
--cp-card-shadow: 0 10px 30px -14px rgba(43, 64, 132, .20);
|
||||
--cp-card-shadow-hover: 0 18px 44px -18px rgba(59, 108, 255, .30);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "HarmonyOS Sans SC", "Microsoft YaHei UI", "PingFang SC", -apple-system, "Segoe UI", sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--cp-ink);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
background-color: #eaf0fb;
|
||||
/* 浅色极光画布:三层低透明光晕 + 渐变底 */
|
||||
background-image:
|
||||
radial-gradient(1100px 520px at 88% -10%, rgba(59, 108, 255, .14), transparent 60%),
|
||||
radial-gradient(900px 480px at -8% 108%, rgba(34, 199, 232, .12), transparent 55%),
|
||||
radial-gradient(760px 420px at 55% 118%, rgba(139, 92, 246, .10), transparent 60%),
|
||||
linear-gradient(180deg, #f4f7fd 0%, #e9eefb 100%);
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
::selection { background: rgba(59, 108, 255, .18); }
|
||||
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #c8d2e8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #b3c0de; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* ---------- Naive 组件统一质感 ---------- */
|
||||
.n-card {
|
||||
--n-border-color: var(--cp-border);
|
||||
--n-color: rgba(255, 255, 255, .82);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
}
|
||||
.n-data-table {
|
||||
--n-border-color: rgba(88, 113, 183, .10);
|
||||
}
|
||||
|
||||
/* ---------- 共享页面工具类 ---------- */
|
||||
.page { max-width: 1280px; margin: 0 auto; }
|
||||
.page-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 18px; }
|
||||
.page-head h3 { margin: 0 0 6px; font-size: 20px; font-weight: 700; letter-spacing: .2px; color: var(--cp-ink); display: flex; align-items: center; gap: 10px; }
|
||||
.page-head h3 .badge {
|
||||
font-size: 11px; font-weight: 600; color: var(--cp-blue); letter-spacing: .6px;
|
||||
background: rgba(59, 108, 255, .10); border: 1px solid rgba(59, 108, 255, .18);
|
||||
padding: 2px 9px; border-radius: 20px;
|
||||
}
|
||||
.page-head p { margin: 0; font-size: 12.5px; color: var(--cp-ink-3); }
|
||||
.block { margin-bottom: 16px; }
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.who { color: var(--cp-blue); font-weight: 600; }
|
||||
|
||||
/* 卡片标题前的小渐变竖条 */
|
||||
.card-title { font-size: 15px; font-weight: 700; color: var(--cp-ink); display: flex; align-items: center; gap: 8px; }
|
||||
.card-title::before { content: ''; width: 4px; height: 14px; border-radius: 3px; background: linear-gradient(180deg, #3b6cff, #22c7e8); }
|
||||
|
||||
/* 表格单元格通用 */
|
||||
.cell-strong { font-weight: 700; color: var(--cp-ink); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
|
||||
/* ---------- 动效 ---------- */
|
||||
@keyframes cp-rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: none; } }
|
||||
.cp-rise { animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both; }
|
||||
@@ -0,0 +1,240 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>账号管理 <span class="badge">Accounts</span></h3>
|
||||
<p>建号 · 部门 / 管理员维护 · 密码重置(不能操作自己的账号)</p>
|
||||
</div>
|
||||
<n-space :size="10">
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
<n-button type="primary" @click="openCreate">
|
||||
<template #icon><n-icon><Plus /></n-icon></template>新建账号
|
||||
</n-button>
|
||||
</n-space>
|
||||
</div>
|
||||
|
||||
<n-card class="cp-rise" :bordered="false">
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="accounts"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.account"
|
||||
:single-line="false"
|
||||
/>
|
||||
</n-card>
|
||||
|
||||
<!-- 新建账号 -->
|
||||
<n-modal v-model:show="createOpen" preset="card" title="新建账号" :style="{ width: '420px' }" :bordered="false" @after-leave="resetCreate">
|
||||
<n-form ref="formRef" :model="form" :rules="rules" label-placement="top">
|
||||
<n-form-item label="账号" path="account">
|
||||
<n-input v-model:value="form.account" placeholder="登录账号" />
|
||||
</n-form-item>
|
||||
<n-form-item label="昵称">
|
||||
<n-input v-model:value="form.nickname" placeholder="真实姓名,方便识别(可填钉钉名)" />
|
||||
</n-form-item>
|
||||
<n-form-item label="初始密码" path="password">
|
||||
<n-input v-model:value="form.password" type="password" show-password-on="click" placeholder="至少 6 位" />
|
||||
</n-form-item>
|
||||
<n-form-item label="部门">
|
||||
<n-input v-model:value="form.dept" placeholder="如 财务部 / IT" />
|
||||
</n-form-item>
|
||||
<n-form-item label="管理员">
|
||||
<n-switch v-model:value="form.is_admin" />
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="createOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="creating" @click="createAccount">建号</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-modal>
|
||||
|
||||
<!-- 重置密码 -->
|
||||
<n-modal v-model:show="resetOpen" preset="card" title="重置密码" :style="{ width: '400px' }" :bordered="false">
|
||||
<n-alert v-if="resetTarget" type="info" :bordered="false" style="margin-bottom: 14px">
|
||||
为账号 <b>{{ resetTarget }}</b> 设置新密码(至少 6 位)
|
||||
</n-alert>
|
||||
<n-input v-model:value="resetPwdVal" type="password" show-password-on="click" placeholder="新密码(至少 6 位)" @keydown.enter="confirmReset" />
|
||||
<template #footer>
|
||||
<n-space justify="end">
|
||||
<n-button @click="resetOpen = false">取消</n-button>
|
||||
<n-button type="primary" :loading="resetting" @click="confirmReset">确认重置</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</n-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NInput, NSwitch, NTag } from 'naive-ui'
|
||||
import { Refresh, Plus } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminAccountCreate, adminAccountUpdate, adminAccountReset, adminAccountDelete } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
|
||||
const current = computed(() => store.current || '')
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
|
||||
// ---------- 部门 / 昵称 行内编辑 ----------
|
||||
const editing = ref('') // 正在编辑的账号
|
||||
const editField = ref('') // 'dept' | 'nickname'
|
||||
const editDraft = ref('')
|
||||
function startEdit(row, field) {
|
||||
if (row.account === current.value) return
|
||||
editing.value = row.account
|
||||
editField.value = field
|
||||
editDraft.value = row[field] || ''
|
||||
}
|
||||
async function saveEdit(row) {
|
||||
if (editing.value !== row.account) return
|
||||
const field = editField.value
|
||||
editing.value = ''
|
||||
const val = (editDraft.value || '').trim()
|
||||
if (val === (row[field] || '')) return
|
||||
try {
|
||||
await adminAccountUpdate({ account: row.account, [field]: val })
|
||||
message.success(`已更新 ${row.account} 的${field === 'nickname' ? '昵称' : '部门'}`)
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
function inlineInput(row, field) {
|
||||
if (row.account === editing.value && editField.value === field) {
|
||||
return h(NInput, {
|
||||
value: editDraft.value,
|
||||
size: 'small',
|
||||
style: 'width: 140px',
|
||||
onUpdateValue: v => (editDraft.value = v),
|
||||
onKeyup: (e) => { if (e.key === 'Enter') saveEdit(row) },
|
||||
onBlur: () => saveEdit(row),
|
||||
})
|
||||
}
|
||||
return h('span', { class: 'dept', onClick: () => startEdit(row, field) },
|
||||
row[field] || '—')
|
||||
}
|
||||
async function toggleAdmin(row) {
|
||||
try { await adminAccountUpdate({ account: row.account, is_admin: !row.is_admin }); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
}
|
||||
|
||||
function renderTags(list, kind) {
|
||||
if (!list || !list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(t => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: kind === 'platform' ? 'success' : 'primary',
|
||||
}, { default: () => t })))
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: '账号', key: 'account', width: 140, render: r => h('b', { class: 'cell-strong' }, r.account) },
|
||||
{ title: '昵称', key: 'nickname', width: 150, render: r => inlineInput(r, 'nickname') },
|
||||
{
|
||||
title: '部门', key: 'dept', width: 160,
|
||||
render: (row) => inlineInput(row, 'dept'),
|
||||
},
|
||||
{
|
||||
title: '管理员', key: 'is_admin', width: 100,
|
||||
render: (row) => h(NSwitch, {
|
||||
value: !!row.is_admin,
|
||||
disabled: row.account === current.value,
|
||||
onUpdateValue: () => toggleAdmin(row),
|
||||
}),
|
||||
},
|
||||
{ title: '已授权插件', key: 'plugins', minWidth: 180, render: r => renderTags(r.plugins, 'plugin') },
|
||||
{ title: '已授权平台', key: 'platforms', minWidth: 140, render: r => renderTags(r.platforms, 'platform') },
|
||||
{
|
||||
title: '操作', key: 'actions', width: 170,
|
||||
render: (row) => h('div', { class: 'ops' }, [
|
||||
h(NButton, { text: true, type: 'primary', onClick: () => resetPwd(row) }, { default: () => '重置密码' }),
|
||||
h(NButton, {
|
||||
text: true, type: 'error',
|
||||
disabled: row.account === current.value,
|
||||
onClick: () => delAccount(row),
|
||||
}, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
|
||||
// ---------- 新建账号 ----------
|
||||
const createOpen = ref(false)
|
||||
const creating = ref(false)
|
||||
const formRef = ref()
|
||||
const form = reactive({ account: '', password: '', dept: '', nickname: '', is_admin: false })
|
||||
const rules = {
|
||||
account: { required: true, message: '请输入账号' },
|
||||
password: [
|
||||
{ required: true, message: '请输入初始密码' },
|
||||
{ min: 6, message: '密码至少 6 位' },
|
||||
],
|
||||
}
|
||||
function openCreate() { createOpen.value = true }
|
||||
function resetCreate() {
|
||||
form.account = form.password = form.dept = form.nickname = ''
|
||||
form.is_admin = false
|
||||
formRef.value?.restoreValidation()
|
||||
}
|
||||
async function createAccount() {
|
||||
try { await formRef.value.validate() } catch (_) { return }
|
||||
creating.value = true
|
||||
try {
|
||||
await adminAccountCreate({ ...form, account: form.account.trim() })
|
||||
message.success(`已建号 ${form.account.trim()}`)
|
||||
createOpen.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('建号失败:' + (e.message || e)) }
|
||||
finally { creating.value = false }
|
||||
}
|
||||
|
||||
// ---------- 重置密码 ----------
|
||||
const resetOpen = ref(false)
|
||||
const resetTarget = ref('')
|
||||
const resetPwdVal = ref('')
|
||||
const resetting = ref(false)
|
||||
function resetPwd(row) {
|
||||
resetTarget.value = row.account
|
||||
resetPwdVal.value = ''
|
||||
resetOpen.value = true
|
||||
}
|
||||
async function confirmReset() {
|
||||
const p = resetPwdVal.value
|
||||
if (p.length < 6) { message.warning('密码至少 6 位'); return }
|
||||
resetting.value = true
|
||||
try {
|
||||
await adminAccountReset({ account: resetTarget.value, new_password: p })
|
||||
message.success(`已重置 ${resetTarget.value} 密码`)
|
||||
resetOpen.value = false
|
||||
} catch (e) { message.error(e.message || e) }
|
||||
finally { resetting.value = false }
|
||||
}
|
||||
|
||||
function delAccount(row) {
|
||||
dialog.warning({
|
||||
title: '删除账号',
|
||||
content: `确认删除账号 ${row.account}?其插件授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminAccountDelete({ account: row.account }); message.success(`已删除 ${row.account}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dept { cursor: pointer; border-bottom: 1px dashed transparent; transition: border-color .15s; }
|
||||
.dept:hover { color: var(--cp-blue); border-bottom-color: rgba(59, 108, 255, .4); }
|
||||
</style>
|
||||
|
||||
<!-- 列 render 中由 naive-ui 动态渲染的节点不继承 scoped scopeId,须用全局样式 -->
|
||||
<style>
|
||||
.ops { display: flex; align-items: center; gap: 16px; }
|
||||
.ops .n-button { padding: 0 4px; }
|
||||
</style>
|
||||
@@ -0,0 +1,108 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>审计与运行报表 <span class="badge">Audit</span></h3>
|
||||
<p>操作审计 · 部署端运行上报记录(最新在前)</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
</div>
|
||||
|
||||
<n-tabs type="line" class="block cp-rise" :value="tab" @update:value="v => tab = v" justify-content="space-evenly">
|
||||
<n-tab-pane name="audit" tab="操作审计">
|
||||
<n-data-table :columns="auditCols" :data="audits" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="report" tab="运行上报">
|
||||
<n-data-table :columns="reportCols" :data="reports" size="small" :loading="busy" :row-key="r => r.id" :single-line="false" />
|
||||
</n-tab-pane>
|
||||
</n-tabs>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { adminAudit, adminReports } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const tab = ref('audit')
|
||||
const busy = ref(false)
|
||||
const audits = ref([])
|
||||
const reports = ref([])
|
||||
|
||||
const DETAIL_LABEL = {
|
||||
grant: '授权', 'revoke-grant': '撤销授权', 'plugin-patch': '更新插件',
|
||||
'download-ticket': '下载', 'upload-pkg': '上传', 'account-create': '建号',
|
||||
'account-update': '改号', 'account-reset': '重置密码', 'account-delete': '删除',
|
||||
'platform-grant': '平台授权', login: '登录',
|
||||
}
|
||||
function actTag(a) {
|
||||
const map = { grant: 'info', 'revoke-grant': 'error', 'plugin-patch': 'warning',
|
||||
'download-ticket': 'success', 'upload-pkg': 'success', login: 'info', }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[a] || 'default', round: true },
|
||||
{ default: () => DETAIL_LABEL[a] || a })
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!r.account && !nn) return h('span', { class: 'dim' }, '—')
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
}
|
||||
function statusTag(s) {
|
||||
const map = { start: 'info', running: 'info', done: 'success', error: 'error' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => s || '—' })
|
||||
}
|
||||
|
||||
const auditCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '操作', key: 'action', width: 130, render: r => actTag(r.action) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '对象', key: 'target', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '详情', key: 'detail', minWidth: 220, ellipsis: { tooltip: true } },
|
||||
]
|
||||
const reportCols = [
|
||||
{ title: '时间', key: 'at', width: 170 },
|
||||
{ title: '状态', key: 'status', width: 100, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 130, render: r => acctCell(r) },
|
||||
{ title: '设备', key: 'device_id', width: 110, render: r => r.device_id || h('span', { class: 'dim' }, '—') },
|
||||
{ title: '插件', key: 'plugin_id', width: 140, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'duration_sec', width: 90, render: r => typeof r.duration_sec === 'number' ? fmtDur(r.duration_sec) : '—' },
|
||||
{ title: '消息', key: 'msg', minWidth: 200, ellipsis: { tooltip: true } },
|
||||
]
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
const m = Math.floor(sec / 60), s = sec % 60
|
||||
if (m < 60) return `${m}m${s ? s + 's' : ''}`
|
||||
return `${Math.floor(m / 60)}h${m % 60}m`
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const [a, r] = await Promise.all([adminAudit(), adminReports()])
|
||||
audits.value = a.auditlogs || []
|
||||
reports.value = r.reports || []
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
<style>
|
||||
.acct { line-height: 1.25; }
|
||||
.acct .ann { font-size: 13px; color: var(--cp-ink-1); }
|
||||
.acct .anick { font-size: 11px; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>权限授权 <span class="badge">Grants</span></h3>
|
||||
<p>按账号勾选可用插件与可登录平台,保存时仅提交差异项</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<n-form inline>
|
||||
<n-form-item label="选择账号">
|
||||
<n-select
|
||||
v-model:value="account"
|
||||
:options="accountOptions"
|
||||
placeholder="选择账号…"
|
||||
style="width: 240px"
|
||||
filterable
|
||||
clearable
|
||||
/>
|
||||
</n-form-item>
|
||||
<n-form-item v-if="account">
|
||||
<span class="sel-hint">{{ account }} · 已授权 {{ grantedIds.length }} 个插件 / {{ platChecked.length }} 个平台</span>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</n-card>
|
||||
|
||||
<template v-if="account">
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>插件授权</b>
|
||||
<n-button type="primary" size="small" :loading="saving" @click="saveGrant">保存插件授权</n-button>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="grantedIds" v-if="plugins.length">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="p in plugins" :key="p.id" :value="p.id" class="ck">
|
||||
<span class="ck-main">
|
||||
<span>{{ p.id }}<span class="dim">({{ p.name }})</span></span>
|
||||
<span class="ck-sub" v-if="grantState[p.id]?.granted">
|
||||
<n-switch size="small" :value="grantState[p.id].canRun"
|
||||
@update:value="v => setGrant(p.id, { canRun: v })">
|
||||
<template #checked>可运行</template>
|
||||
<template #unchecked>禁运行</template>
|
||||
</n-switch>
|
||||
<n-switch size="small" :value="grantState[p.id].canDownload"
|
||||
@update:value="v => setGrant(p.id, { canDownload: v })">
|
||||
<template #checked>可下载</template>
|
||||
<template #unchecked>禁下载</template>
|
||||
</n-switch>
|
||||
</span>
|
||||
</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
<n-empty v-else description="暂无插件,请先在「插件管理」上传" size="small" />
|
||||
</n-card>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header>
|
||||
<div class="card-head">
|
||||
<b>平台授权</b>
|
||||
<n-button type="primary" size="small" :loading="savingPlat" @click="savePlat">保存平台授权</n-button>
|
||||
</div>
|
||||
</template>
|
||||
<n-checkbox-group v-model:value="platChecked">
|
||||
<div class="ck-grid">
|
||||
<n-checkbox v-for="pf in PLATFORM_OPTS" :key="pf.id" :value="pf.id" class="ck">
|
||||
{{ pf.label }}<span class="dim">({{ pf.id }})</span>
|
||||
</n-checkbox>
|
||||
</div>
|
||||
</n-checkbox-group>
|
||||
</n-card>
|
||||
</template>
|
||||
|
||||
<n-empty v-else description="先在上方选择一个账号" class="no-acc cp-rise" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminGrant, adminPlatformGrant, adminPlatforms } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const PLATFORM_OPTS = ref([])
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const accounts = computed(() => overview.value?.accounts || [])
|
||||
const accountOptions = computed(() => accounts.value.map(a => ({
|
||||
label: a.dept ? `${a.account} · ${a.dept}` : a.account,
|
||||
value: a.account,
|
||||
})))
|
||||
|
||||
const account = ref('')
|
||||
const grantedIds = ref([])
|
||||
const grantState = ref({}) // plugin_id -> { granted, canRun, canDownload }
|
||||
const platChecked = ref([])
|
||||
const saving = ref(false)
|
||||
const savingPlat = ref(false)
|
||||
let heldGrantState = {} // 已保存快照,用于差异比对
|
||||
let heldPlatforms = new Set()
|
||||
|
||||
function setGrant(pid, patch) {
|
||||
grantState.value[pid] = { ...grantState.value[pid], ...patch }
|
||||
grantState.value = { ...grantState.value }
|
||||
}
|
||||
|
||||
// 选中账号即自动载入其现有授权
|
||||
watch(account, (acc) => {
|
||||
const a = accounts.value.find(x => x.account === acc)
|
||||
const state = {}
|
||||
;(a?.plugins || []).forEach(pid => {
|
||||
const g = a?.grants?.[pid] || {}
|
||||
state[pid] = { granted: true, canRun: g.canRun !== false, canDownload: g.canDownload !== false }
|
||||
})
|
||||
heldGrantState = JSON.parse(JSON.stringify(state))
|
||||
grantState.value = JSON.parse(JSON.stringify(state))
|
||||
grantedIds.value = [...(a?.plugins || [])]
|
||||
heldPlatforms = new Set(a?.platforms || [])
|
||||
platChecked.value = [...heldPlatforms]
|
||||
})
|
||||
|
||||
// 勾选/取消勾选插件时同步 granted 状态
|
||||
watch(grantedIds, (ids) => {
|
||||
const state = { ...grantState.value }
|
||||
ids.forEach(pid => {
|
||||
if (!state[pid]) state[pid] = { granted: true, canRun: true, canDownload: true }
|
||||
else state[pid].granted = true
|
||||
})
|
||||
Object.keys(state).forEach(pid => {
|
||||
if (!ids.includes(pid)) state[pid].granted = false
|
||||
})
|
||||
grantState.value = state
|
||||
})
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
// 拉取可授权平台列表(后端只读接口,替代写死 hr/oa)
|
||||
async function loadPlatforms() {
|
||||
try {
|
||||
const r = await adminPlatforms()
|
||||
PLATFORM_OPTS.value = (r.platforms || []).map(p => ({ id: p.id, label: p.label }))
|
||||
} catch (e) { message.error('平台列表读取失败:' + (e.message || e)) }
|
||||
}
|
||||
|
||||
async function saveGrant() {
|
||||
const acc = account.value; if (!acc) return
|
||||
saving.value = true
|
||||
try {
|
||||
const want = {}
|
||||
Object.entries(grantState.value).forEach(([pid, s]) => {
|
||||
if (s.granted) want[pid] = s
|
||||
})
|
||||
const allPids = [...new Set([...Object.keys(want), ...Object.keys(heldGrantState)])]
|
||||
const diff = allPids.filter(pid => {
|
||||
const w = want[pid]; const h = heldGrantState[pid]
|
||||
if (!!w !== !!h) return true
|
||||
if (w && h) return w.canRun !== h.canRun || w.canDownload !== h.canDownload
|
||||
return false
|
||||
})
|
||||
if (!diff.length) { message.info('插件授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pid => adminGrant({
|
||||
account: acc, plugin_id: pid, granted: !!want[pid],
|
||||
can_run: want[pid]?.canRun !== false, can_download: want[pid]?.canDownload !== false,
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`插件授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项插件授权`)
|
||||
heldGrantState = JSON.parse(JSON.stringify(grantState.value))
|
||||
await refresh()
|
||||
} finally { saving.value = false }
|
||||
}
|
||||
async function savePlat() {
|
||||
const acc = account.value; if (!acc) return
|
||||
savingPlat.value = true
|
||||
try {
|
||||
const want = new Set(platChecked.value)
|
||||
const diff = [...new Set([...want, ...heldPlatforms])].filter(pf => want.has(pf) !== heldPlatforms.has(pf))
|
||||
if (!diff.length) { message.info('平台授权无需变更'); return }
|
||||
const results = await Promise.allSettled(diff.map(pf => adminPlatformGrant({
|
||||
account: acc, platform_id: pf, granted: want.has(pf),
|
||||
})))
|
||||
const failed = results.filter(r => r.status === 'rejected')
|
||||
failed.forEach(r => message.error(r.reason?.message || String(r.reason)))
|
||||
if (failed.length) { message.warning(`平台授权:${diff.length - failed.length} 项成功,${failed.length} 项失败`); return }
|
||||
message.success(`已更新 ${diff.length} 项平台授权`)
|
||||
heldPlatforms = new Set(platChecked.value)
|
||||
await refresh()
|
||||
} finally { savingPlat.value = false }
|
||||
}
|
||||
onMounted(() => { refresh(); loadPlatforms() })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; }
|
||||
.sel-hint { font-size: 12px; color: var(--cp-ink-2); }
|
||||
.no-acc { margin-top: 60px; }
|
||||
|
||||
/* 授权项:卡片式勾选 */
|
||||
.ck-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 10px; }
|
||||
.ck-main { display: flex; flex-direction: column; gap: 8px; min-width: 0; line-height: 1.2; }
|
||||
.ck-sub { display: flex; align-items: center; gap: 10px; }
|
||||
:deep(.n-checkbox) {
|
||||
display: flex; align-items: center; margin: 0;
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, .65);
|
||||
transition: border-color .18s, background .18s, box-shadow .18s;
|
||||
}
|
||||
:deep(.n-checkbox:hover) { border-color: rgba(59, 108, 255, .4); }
|
||||
:deep(.n-checkbox.n-checkbox--checked) {
|
||||
border-color: rgba(59, 108, 255, .45);
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .08), rgba(34, 199, 232, .06));
|
||||
box-shadow: 0 8px 18px -10px rgba(59, 108, 255, .35);
|
||||
}
|
||||
:deep(.n-checkbox .n-checkbox__label) { padding-left: 4px; flex: 1; min-width: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,112 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>概览 <span class="badge">Dashboard</span></h3>
|
||||
<p>中心机 · 插件分发与账号权限 · 当前账号 <b class="who">{{ store.current }}</b></p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
</div>
|
||||
|
||||
<div class="stat-grid" v-if="ov">
|
||||
<div class="stat-card" v-for="(s, i) in stats" :key="s.label" :style="{ animationDelay: i * 60 + 'ms' }">
|
||||
<div class="stat-ic" :style="{ background: s.bg, color: s.color }">
|
||||
<n-icon :size="20"><component :is="s.icon" /></n-icon>
|
||||
</div>
|
||||
<div class="stat-meta">
|
||||
<div class="stat-num" :class="{ sm: s.small }">{{ s.value }}</div>
|
||||
<div class="stat-label">{{ s.label }}</div>
|
||||
</div>
|
||||
<span class="stat-glow" :style="{ background: s.color }"></span>
|
||||
</div>
|
||||
</div>
|
||||
<n-skeleton v-else-if="overviewBusy" text :repeat="3" style="margin-top: 20px" />
|
||||
|
||||
<div class="tip-card cp-rise">
|
||||
<div class="tip-ic"><n-icon :size="18"><InfoFilled /></n-icon></div>
|
||||
<div class="tip-body">
|
||||
<b>使用说明</b>
|
||||
<p>「插件管理」上传与发布插件包(每插件保留最近 3 个版本);「账号管理」建号与账号维护;「权限授权」按账号勾选可用的插件与平台。部署机(webhost)仅在启动与手动刷新时拉取插件,授权变更后需在部署机刷新生效。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { Refresh, InfoFilled } from '@element-plus/icons-vue'
|
||||
import { store, overview, overviewBusy, loadOverview } from '../store'
|
||||
import { message } from '../naive'
|
||||
|
||||
const ov = computed(() => overview.value)
|
||||
const stats = computed(() => {
|
||||
const plugins = ov.value?.plugins || []
|
||||
return [
|
||||
{ label: '插件', value: plugins.length, icon: 'Box', color: '#3b6cff', bg: 'linear-gradient(135deg,#eef2ff,#dbe6ff)' },
|
||||
{ label: '版本总数', value: plugins.reduce((n, p) => n + (p.versions?.length || 0), 0), icon: 'Collection', color: '#7c5cff', bg: 'linear-gradient(135deg,#f2edff,#e6dcff)' },
|
||||
{ label: '账号', value: (ov.value?.accounts || []).length, icon: 'User', color: '#12a4d8', bg: 'linear-gradient(135deg,#e7f6fb,#d3effa)' },
|
||||
{ label: '管理员', value: (ov.value?.admins || []).length, icon: 'UserFilled', color: '#22b07a', bg: 'linear-gradient(135deg,#e6f7f0,#d2f1e4)' },
|
||||
{ label: '最近上传', value: latest(), icon: 'UploadFilled', color: '#d99a1b', bg: 'linear-gradient(135deg,#fbf3e2,#f6e8c8)', small: true },
|
||||
]
|
||||
})
|
||||
function latest() {
|
||||
const all = (ov.value?.plugins || []).flatMap(p => p.versions || []).map(v => v.uploaded_at).filter(Boolean)
|
||||
if (!all.length) return '—'
|
||||
// ISO 时间转友好格式:2026-09-10T12:51:33 → 2026-09-10 12:51
|
||||
return all.sort().at(-1).replace('T', ' ').slice(0, 16)
|
||||
}
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
.stat-card {
|
||||
position: relative; overflow: hidden;
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
background: var(--cp-surface);
|
||||
border: 1px solid var(--cp-border);
|
||||
border-radius: 18px;
|
||||
padding: 18px;
|
||||
box-shadow: var(--cp-card-shadow);
|
||||
transition: transform .22s ease, box-shadow .22s ease;
|
||||
animation: cp-rise .5s cubic-bezier(.22, .61, .36, 1) both;
|
||||
}
|
||||
.stat-card:hover { transform: translateY(-4px); box-shadow: var(--cp-card-shadow-hover); }
|
||||
.stat-ic {
|
||||
width: 46px; height: 46px; border-radius: 14px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .6);
|
||||
}
|
||||
.stat-meta { min-width: 0; }
|
||||
.stat-num { font-size: 26px; font-weight: 800; letter-spacing: .3px; line-height: 1.15; color: var(--cp-ink); font-variant-numeric: tabular-nums; }
|
||||
.stat-num.sm { font-size: 13px; font-weight: 600; word-break: break-all; line-height: 1.4; }
|
||||
.stat-label { font-size: 12px; color: var(--cp-ink-3); margin-top: 3px; }
|
||||
.stat-glow { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; border-radius: 0 6px 6px 0; opacity: .9; }
|
||||
|
||||
.tip-card {
|
||||
margin-top: 18px;
|
||||
display: flex; gap: 14px;
|
||||
background: linear-gradient(135deg, rgba(59, 108, 255, .06), rgba(34, 199, 232, .05)), rgba(255, 255, 255, .7);
|
||||
border: 1px solid rgba(59, 108, 255, .16);
|
||||
border-radius: 16px;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.tip-ic {
|
||||
width: 38px; height: 38px; border-radius: 12px; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
background: linear-gradient(135deg, #3b6cff, #22c7e8);
|
||||
color: #fff;
|
||||
box-shadow: 0 6px 14px -6px rgba(59, 108, 255, .55);
|
||||
}
|
||||
.tip-body b { display: block; font-size: 14px; color: var(--cp-ink); margin-bottom: 4px; }
|
||||
.tip-body p { margin: 0; font-size: 12.5px; line-height: 1.7; color: var(--cp-ink-2); }
|
||||
</style>
|
||||
@@ -0,0 +1,241 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>插件管理 <span class="badge">Plugins</span></h3>
|
||||
<p>上传发布插件包 · 每插件保留最近 3 个版本,超出自动清理</p>
|
||||
</div>
|
||||
<n-button :loading="overviewBusy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
</div>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">上传插件包</span></template>
|
||||
<n-form inline>
|
||||
<n-form-item label="插件 ID">
|
||||
<n-input v-model:value="pid" placeholder="如 seal_check" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="pname" placeholder="插件显示名" style="width: 150px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="版本">
|
||||
<n-input v-model:value="pver" placeholder="如 1.1.0" style="width: 110px" />
|
||||
</n-form-item>
|
||||
<n-form-item label="包文件">
|
||||
<n-space align="center" :size="8">
|
||||
<n-upload :default-upload="false" :show-file-list="false" accept=".zip" @change="onFileChange">
|
||||
<n-button :type="pfile ? 'info' : 'default'">
|
||||
<template #icon><n-icon><UploadFilled /></n-icon></template>
|
||||
{{ pfile ? '重新选择' : '选择 ZIP 包' }}
|
||||
</n-button>
|
||||
</n-upload>
|
||||
<n-tag v-if="pfile" size="small" round type="info" :bordered="false">{{ pfile.name }}</n-tag>
|
||||
</n-space>
|
||||
</n-form-item>
|
||||
<n-form-item>
|
||||
<n-button type="primary" :loading="uploading" @click="upload">
|
||||
<template #icon v-if="!uploading"><n-icon><UploadFilled /></n-icon></template>上传发布
|
||||
</n-button>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<div class="hint">包根目录需含 plugin.json / main.py / requirements.txt,ZIP 完整性校验通过才会发布。</div>
|
||||
</n-card>
|
||||
|
||||
<n-card class="block cp-rise" :bordered="false">
|
||||
<template #header><span class="card-title">插件列表</span></template>
|
||||
<n-data-table
|
||||
:columns="columns"
|
||||
:data="plugins"
|
||||
:loading="overviewBusy"
|
||||
:row-key="r => r.id"
|
||||
:single-line="false"
|
||||
:row-props="rowProps"
|
||||
/>
|
||||
</n-card>
|
||||
|
||||
<n-modal v-model:show="editShow" preset="card" :bordered="false" style="width: 560px" :title="`编辑插件 · ${edit.pid}`">
|
||||
<n-form label-placement="top">
|
||||
<n-form-item label="名称">
|
||||
<n-input v-model:value="edit.name" placeholder="插件显示名" />
|
||||
</n-form-item>
|
||||
<n-form-item label="分类">
|
||||
<n-input v-model:value="edit.category" placeholder="如 薪酬 / 考勤 / 社保" />
|
||||
</n-form-item>
|
||||
<n-form-item label="描述">
|
||||
<n-input v-model:value="edit.description" type="textarea" :rows="2" placeholder="插件用途说明" />
|
||||
</n-form-item>
|
||||
<n-form-item label="状态">
|
||||
<n-radio-group v-model:value="edit.status">
|
||||
<n-radio-button value="published">正常发布</n-radio-button>
|
||||
<n-radio-button value="disabled">禁用(停止分发)</n-radio-button>
|
||||
<n-radio-button value="revoked">下架(禁止运行)</n-radio-button>
|
||||
</n-radio-group>
|
||||
</n-form-item>
|
||||
<n-form-item label="强制更新(留空表示不强制)" :show-feedback="false">
|
||||
<div class="force-row">
|
||||
<n-input v-model:value="edit.force_min" placeholder="最低版本,如 1.2.0" style="width: 180px" />
|
||||
<n-input v-model:value="edit.force_dl" type="datetime-local" placeholder="截止时间" style="width: 200px" />
|
||||
<span class="hint">到达截止时间后,未升级到该版本的部署机会被禁止启动</span>
|
||||
</div>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
<template #footer>
|
||||
<div class="modal-foot">
|
||||
<n-button @click="editShow = false">取消</n-button>
|
||||
<n-button type="primary" :loading="saving" @click="saveEdit">保存</n-button>
|
||||
</div>
|
||||
</template>
|
||||
</n-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, h, onMounted, reactive, ref } from 'vue'
|
||||
import { NButton, NTag } from 'naive-ui'
|
||||
import { Refresh, UploadFilled } from '@element-plus/icons-vue'
|
||||
import { overview, overviewBusy, loadOverview } from '../store'
|
||||
import { adminUpload, adminPluginDelete, adminPluginPatch } from '../api'
|
||||
import { message, dialog } from '../naive'
|
||||
|
||||
const plugins = computed(() => overview.value?.plugins || [])
|
||||
const pid = ref(''); const pname = ref(''); const pver = ref(''); const pfile = ref(null)
|
||||
const uploading = ref(false)
|
||||
|
||||
// 状态徽标文案与配色
|
||||
const STATUS_META = {
|
||||
published: { label: '正常', type: 'success' },
|
||||
disabled: { label: '禁用', type: 'warning' },
|
||||
revoked: { label: '已下架', type: 'error' },
|
||||
}
|
||||
function renderStatus(row) {
|
||||
const s = STATUS_META[row.status] || { label: row.status || '—', type: 'default' }
|
||||
return h(NTag, { size: 'small', round: true, bordered: false, type: s.type }, { default: () => s.label })
|
||||
}
|
||||
|
||||
function onFileChange(e) {
|
||||
pfile.value = e?.file?.file || null
|
||||
}
|
||||
|
||||
function renderVersions(row) {
|
||||
const list = row.versions || []
|
||||
if (!list.length) return h('span', { class: 'dim' }, '—')
|
||||
return h('div', { class: 'tags' }, list.map(v => h(NTag, {
|
||||
size: 'small', round: true, bordered: false,
|
||||
type: v.version === row.latest_version ? 'primary' : 'default',
|
||||
}, { default: () => v.version })))
|
||||
}
|
||||
|
||||
// —— 编辑弹窗状态 ——
|
||||
const editShow = ref(false)
|
||||
const saving = ref(false)
|
||||
const edit = reactive({ pid: '', name: '', category: '', description: '', status: 'published', force_min: '', force_dl: '' })
|
||||
function openEdit(row) {
|
||||
edit.pid = row.id
|
||||
edit.name = row.name || ''
|
||||
edit.category = row.category || ''
|
||||
edit.description = row.description || ''
|
||||
edit.status = row.status || 'published'
|
||||
edit.force_min = row.force_min_version || ''
|
||||
edit.force_dl = toLocalInput(row.force_deadline)
|
||||
editShow.value = true
|
||||
}
|
||||
// ISO 时间 → datetime-local 输入框可识别的本地格式
|
||||
function toLocalInput(iso) {
|
||||
if (!iso) return ''
|
||||
const d = new Date(iso.endsWith('Z') ? iso : iso + 'Z')
|
||||
return isNaN(d) ? '' : `${String(d.getFullYear()).padStart(4, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||
}
|
||||
async function saveEdit() {
|
||||
if (!edit.pid) return
|
||||
saving.value = true
|
||||
try {
|
||||
const body = { name: edit.name, category: edit.category, description: edit.description, status: edit.status }
|
||||
// 强制更新:min 与 deadline 均填则成对下发;否则清除强制更新
|
||||
body.force_min_version = edit.force_min || null
|
||||
body.force_deadline = edit.force_dl ? new Date(edit.force_dl).toISOString() : null
|
||||
body.clear_force = !(edit.force_min && edit.force_dl)
|
||||
await adminPluginPatch(edit.pid, body)
|
||||
message.success(`已更新插件 ${edit.pid}`)
|
||||
editShow.value = false
|
||||
await refresh()
|
||||
} catch (e) { message.error('保存失败:' + (e.message || e)) }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
|
||||
const columns = computed(() => [
|
||||
{ title: '插件 ID', key: 'id', width: 150, render: r => h('b', { class: 'cell-strong' }, r.id) },
|
||||
{ title: '名称', key: 'name', width: 130, ellipsis: { tooltip: true } },
|
||||
{ title: '分类', key: 'category', width: 90, render: r => r.category ? h(NTag, { size: 'small', bordered: false, type: 'info' }, { default: () => r.category }) : h('span', { class: 'dim' }, '—') },
|
||||
{
|
||||
title: '能力 / 表单', key: 'caps', minWidth: 130,
|
||||
render: r => h('div', { class: 'tags' }, [
|
||||
...(r.capabilities?.length ? r.capabilities.map(c => h(NTag, { size: 'small', bordered: false, type: 'default' }, { default: () => c })) : [h('span', { class: 'dim' }, '—')]),
|
||||
h(NTag, { size: 'small', bordered: false, type: 'info', style: 'margin-left:2px' }, { default: () => `${r.field_count || 0} 字段` }),
|
||||
]),
|
||||
},
|
||||
{ title: '状态', key: 'status', width: 80, render: renderStatus },
|
||||
{ title: '最新版', key: 'latest_version', width: 90 },
|
||||
{ title: '版本历史', key: 'versions', minWidth: 200, render: renderVersions },
|
||||
{
|
||||
title: '授权账号', key: 'accounts', minWidth: 130,
|
||||
render: r => (r.accounts?.length ? r.accounts.join('、') : h('span', { class: 'dim' }, '—')),
|
||||
ellipsis: { tooltip: true },
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'actions', width: 120,
|
||||
render: r => h('div', { class: 'row-acts' }, [
|
||||
h(NButton, { size: 'small', text: true, type: 'primary', onClick: () => openEdit(r) }, { default: () => '编辑' }),
|
||||
h(NButton, { size: 'small', text: true, type: 'error', onClick: () => delPlugin(r) }, { default: () => '删除' }),
|
||||
]),
|
||||
},
|
||||
])
|
||||
function rowProps() {
|
||||
return { style: 'cursor:default' }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try { await loadOverview(true) } catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
}
|
||||
async function upload() {
|
||||
if (!pid.value || !pver.value || !pfile.value) { message.warning('请填写插件 ID / 版本并选择 ZIP 包'); return }
|
||||
uploading.value = true
|
||||
try {
|
||||
await adminUpload(pid.value, pname.value || pid.value, pver.value, pfile.value)
|
||||
message.success(`已发布 ${pid.value}@${pver.value}`)
|
||||
pid.value = ''; pname.value = ''; pver.value = ''; pfile.value = null
|
||||
await refresh()
|
||||
} catch (e) { message.error('上传失败:' + (e.message || e)) }
|
||||
finally { uploading.value = false }
|
||||
}
|
||||
function delPlugin(p) {
|
||||
dialog.warning({
|
||||
title: '删除插件',
|
||||
content: `确认删除插件 ${p.id}?其全部版本与授权将一并清除`,
|
||||
positiveText: '删除',
|
||||
negativeText: '取消',
|
||||
onPositiveClick: async () => {
|
||||
try { await adminPluginDelete({ plugin_id: p.id }); message.success(`已删除插件 ${p.id}`); await refresh() }
|
||||
catch (e) { message.error(e.message || e) }
|
||||
},
|
||||
})
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.hint { font-size: 12px; color: var(--cp-ink-3); margin-top: 4px; }
|
||||
.force-row { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
||||
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; }
|
||||
</style>
|
||||
|
||||
<!-- 以下类用于 n-data-table 列 render 中由 naive-ui 作用域动态渲染的节点,
|
||||
它们不继承本组件 scoped scopeId,必须用全局(非 scoped)样式才生效。 -->
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
.cell-strong { font-weight: 600; color: var(--cp-ink-1); }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.row-acts { display: flex; align-items: center; gap: 14px; white-space: nowrap; }
|
||||
.row-acts .n-button { --n-padding: 0; }
|
||||
.row-acts .n-button + .n-button { margin-left: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,176 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head cp-rise">
|
||||
<div>
|
||||
<h3>运行统计 <span class="badge">Stats</span></h3>
|
||||
<p>账号 · 插件规模 · 执行次数/时长/成败 · 近 14 天趋势</p>
|
||||
</div>
|
||||
<n-button :loading="busy" @click="refresh">
|
||||
<template #icon><n-icon><Refresh /></n-icon></template>刷新
|
||||
</n-button>
|
||||
</div>
|
||||
|
||||
<template v-if="st">
|
||||
<!-- 指标卡 -->
|
||||
<div class="kpis cp-rise">
|
||||
<div class="kpi"><span class="num" style="color:var(--cp-blue)">{{ st.users.total }}</span><span class="lab">用户总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.plugins.total }}</span><span class="lab">插件总数</span></div>
|
||||
<div class="kpi"><span class="num">{{ st.runs.total }}</span><span class="lab">累计执行</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#34a853">{{ st.runs.success }}</span><span class="lab">成功</span></div>
|
||||
<div class="kpi"><span class="num" style="color:#e5484d">{{ st.runs.failed }}</span><span class="lab">失败</span></div>
|
||||
<div class="kpi"><span class="num">{{ fmtDur(st.runs.durationSec) }}</span><span class="lab">总运行时长</span></div>
|
||||
</div>
|
||||
|
||||
<div class="grid cp-rise">
|
||||
<!-- 近 14 天趋势 -->
|
||||
<div class="card">
|
||||
<div class="card-title">近 14 天运行趋势</div>
|
||||
<div class="trend">
|
||||
<div class="tcol" v-for="d in st.trend" :key="d.day" :title="`${d.day} · ${d.runs} 次(成功 ${d.success} / 失败 ${d.failed})`">
|
||||
<div class="tstack">
|
||||
<div class="tbar failed" :style="{ height: pct(d.failed, maxRuns) + '%' }"></div>
|
||||
<div class="tbar success" :style="{ height: pct(d.success, maxRuns) + '%' }"></div>
|
||||
</div>
|
||||
<span class="tday">{{ d.day }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 插件 / 用户排行 -->
|
||||
<div class="rank-wrap">
|
||||
<div class="card">
|
||||
<div class="card-title">插件排行(按运行次数)</div>
|
||||
<ul class="rank">
|
||||
<li v-for="(p, i) in st.topPlugins" :key="p.pluginId">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ p.name || p.pluginId }}</span><em>{{ p.runs }} 次</em></div>
|
||||
<div class="rbar"><i :style="{ width: pct(p.runs, rankMax(st.topPlugins)) + '%' }"></i></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topPlugins.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-title">活跃用户</div>
|
||||
<ul class="rank">
|
||||
<li v-for="(u, i) in st.topUsers" :key="u.account">
|
||||
<span class="rk">{{ i + 1 }}</span>
|
||||
<div class="rbody">
|
||||
<div class="rhead"><span class="rname">{{ u.account }}</span><em>{{ u.runs }} 次</em></div>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!st.topUsers.length" class="empty">暂无运行记录</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 最近运行 -->
|
||||
<div class="page-head sub cp-rise">
|
||||
<div><h4>最近运行</h4></div>
|
||||
</div>
|
||||
<n-card class="cp-rise" :bordered="false" size="small">
|
||||
<n-data-table :columns="recentCols" :data="st.recent" size="small" :row-key="r => r.at + r.pluginId" :single-line="false" />
|
||||
</n-card>
|
||||
</template>
|
||||
|
||||
<n-skeleton v-else-if="busy" text :repeat="4" style="margin-top: 20px" />
|
||||
<div v-else class="empty-tip cp-rise">加载失败或暂无数据</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { h } from 'vue'
|
||||
import { NTag } from 'naive-ui'
|
||||
import { Refresh } from '@element-plus/icons-vue'
|
||||
import { adminStats } from '../api'
|
||||
import { message } from '../naive'
|
||||
|
||||
const busy = ref(false)
|
||||
const st = ref(null)
|
||||
|
||||
function statusTag(s) {
|
||||
const map = { done: 'success', success: 'success', error: 'error', failed: 'error', running: 'info', start: 'info' }
|
||||
return h(NTag, { size: 'small', bordered: false, type: map[s] || 'default', round: true },
|
||||
{ default: () => (s === 'done' || s === 'success' ? '成功' : s === 'error' || s === 'failed' ? '失败' : s) })
|
||||
}
|
||||
function acctCell(r) {
|
||||
const nn = r.nickname
|
||||
if (!nn) return h('span', null, r.account || '—')
|
||||
return h('div', { class: 'acct' }, [
|
||||
h('div', { class: 'ann' }, r.account || '—'),
|
||||
h('div', { class: 'anick' }, nn || ''),
|
||||
])
|
||||
}
|
||||
function fmtDur(sec) {
|
||||
sec = +sec || 0
|
||||
if (sec < 60) return sec + 's'
|
||||
const m = Math.floor(sec / 60), s = sec % 60
|
||||
if (m < 60) return `${m}m${s ? s + 's' : ''}`
|
||||
const hh = Math.floor(m / 60)
|
||||
return `${hh}h${m % 60}m`
|
||||
}
|
||||
const recentCols = [
|
||||
{ title: '时间', key: 'at', width: 165 },
|
||||
{ title: '状态', key: 'status', width: 90, render: r => statusTag(r.status) },
|
||||
{ title: '账号', key: 'account', width: 110, render: r => acctCell(r) },
|
||||
{ title: '插件', key: 'pluginId', width: 150, ellipsis: { tooltip: true } },
|
||||
{ title: '版本', key: 'version', width: 90 },
|
||||
{ title: '时长', key: 'durationSec', width: 90, render: r => fmtDur(r.durationSec) },
|
||||
{ title: '信息', key: 'msg', minWidth: 220, ellipsis: { tooltip: true }, render: r => r.msg || h('span', { class: 'dim' }, '—') },
|
||||
]
|
||||
const maxRuns = () => Math.max(1, ...(st.value?.trend || []).map(t => t.runs || 0))
|
||||
const pct = (n, max) => Math.max(1, Math.round((n || 0) / (max || 1) * 100))
|
||||
const rankMax = list => Math.max(1, ...(list || []).map(x => x.runs || 1))
|
||||
|
||||
async function refresh() {
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminStats()
|
||||
st.value = {
|
||||
users: r.users || {}, plugins: r.plugins || {}, runs: r.runs || {},
|
||||
trend: r.trend || [], topPlugins: r.topPlugins || [], topUsers: r.topUsers || [],
|
||||
recent: r.recent || [],
|
||||
}
|
||||
} catch (e) { message.error('读取失败:' + (e.message || e)) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpis { display: grid; grid-template-columns: repeat(6, 1fr); gap: 14px; margin-bottom: 16px; }
|
||||
.kpi { padding: 16px 18px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.kpi .num { font-size: 26px; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .lab { font-size: 12px; color: var(--cp-ink-3); }
|
||||
.grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; margin-bottom: 16px; }
|
||||
.rank-wrap { display: flex; flex-direction: column; gap: 16px; }
|
||||
.card { padding: 18px 20px; }
|
||||
.card-title { font-size: 14px; font-weight: 600; color: var(--cp-ink-1); margin-bottom: 14px; }
|
||||
.trend { display: flex; gap: 4px; height: 160px; align-items: stretch; }
|
||||
.tcol { flex: 1; display: flex; flex-direction: column; justify-content: flex-end; align-items: center; gap: 4px; }
|
||||
.tstack { flex: 1; display: flex; align-items: flex-end; gap: 1px; width: 100%; }
|
||||
.tbar { flex: 1; border-radius: 1px 1px 0 0; }
|
||||
.tbar.success { background: #34a853; }
|
||||
.tbar.failed { background: #e5484d; }
|
||||
.tday { font-size: 10px; color: var(--cp-ink-3); }
|
||||
.rank { list-style: none; margin: 0; padding: 0; }
|
||||
.rank li { display: flex; align-items: center; gap: 10px; padding: 7px 0; }
|
||||
.rank .rk { width: 20px; height: 20px; flex: none; border-radius: 6px; background: var(--cp-bg-2); color: var(--cp-ink-3); font-size: 12px; display: flex; align-items: center; justify-content: center; }
|
||||
.rank li:nth-child(1) .rk { background: rgba(59,108,255,.12); color: var(--cp-blue); }
|
||||
.rank .rbody { flex: 1; min-width: 0; }
|
||||
.rhead { display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px; }
|
||||
.rname { font-size: 13px; color: var(--cp-ink-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rhead em { font-style: normal; font-size: 12px; color: var(--cp-ink-3); }
|
||||
.rbar { height: 5px; border-radius: 3px; background: var(--cp-bg-2); overflow: hidden; }
|
||||
.rbar i { display: block; height: 100%; background: var(--cp-blue); border-radius: 3px; }
|
||||
.page-head.sub h4 { margin: 0; font-size: 15px; }
|
||||
.empty { color: var(--cp-ink-3); font-size: 12px; justify-content: center; padding: 16px 0 !important; }
|
||||
.empty-tip { padding: 30px; text-align: center; color: var(--cp-ink-3); }
|
||||
</style>
|
||||
|
||||
<style>
|
||||
.dim { color: var(--cp-ink-3); }
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// dev 时把 /api 代理到控制面后端(8800),实现前后端分离开发;生产由 FastAPI 挂载 dist
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8800', changeOrigin: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""controlplane 运维/构建工具集(CLI、PyInstaller spec、Windows 运维脚本)。"""
|
||||
@@ -0,0 +1,384 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||
|
||||
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||
- 按账号授予 / 撤销插件与平台权限
|
||||
- 发布执行机壳子(主程序)新版安装包(shell-release,上传到中心机 shell 源)
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。
|
||||
本脚本运行在中心机本机,直接复用 desktop/controlplane/.env 与 .admin_secret:
|
||||
- X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
- X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret
|
||||
对指定管理员账号临时签发短期票据(与 app.py 完全一致,签名不可伪造)。
|
||||
因此本 CLI 只在"中心机本机 + 拥有管理密钥"的环境下可用,等价于本地管理台白名单。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
k, v = _k.strip(), _v.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > CONTROLPLANE_TOKEN > .admin_secret。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or os.getenv("CONTROLPLANE_TOKEN") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _mint_admin_token(account: str, secret: str) -> str:
|
||||
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||
_hdrs_json: Optional[bool] = None) -> dict:
|
||||
import requests
|
||||
url = self.base + path # path 已是完整路径(含 query)
|
||||
try:
|
||||
if json_body is not None:
|
||||
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||
else:
|
||||
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||
except requests.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("msg") or detail
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||
return data if isinstance(data, dict) else {"result": data}
|
||||
|
||||
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
print("(暂无插件)")
|
||||
return
|
||||
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||
for p in rows:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_cli",
|
||||
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
p_del.add_argument("plugin_id")
|
||||
|
||||
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||
p_status.add_argument("plugin_id")
|
||||
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||
help="新状态(留空不改变)")
|
||||
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||
|
||||
sub.add_parser("users", help="列出账号清单")
|
||||
|
||||
p_user = sub.add_parser("user-add", help="新建账号")
|
||||
p_user.add_argument("account")
|
||||
p_user.add_argument("--password", required=True)
|
||||
p_user.add_argument("--dept", default="")
|
||||
p_user.add_argument("--nickname", default="")
|
||||
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||
|
||||
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||
p_upd.add_argument("account")
|
||||
p_upd.add_argument("--dept", default=None)
|
||||
p_upd.add_argument("--nickname", default=None)
|
||||
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||
default=None)
|
||||
|
||||
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||
p_rp.add_argument("account")
|
||||
p_rp.add_argument("--password", required=True)
|
||||
|
||||
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||
p_del_u.add_argument("account")
|
||||
|
||||
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||
p_grant.add_argument("account")
|
||||
p_grant.add_argument("plugin_id")
|
||||
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||
|
||||
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||
p_revoke.add_argument("account")
|
||||
p_revoke.add_argument("plugin_id")
|
||||
|
||||
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||
p_gp.add_argument("account")
|
||||
p_gp.add_argument("platform_id")
|
||||
|
||||
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||
p_rp_plt.add_argument("account")
|
||||
p_rp_plt.add_argument("platform_id")
|
||||
|
||||
sub.add_parser("stats", help="运行统计看板")
|
||||
|
||||
sub.add_parser("me", help="校验当前管理身份")
|
||||
|
||||
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),无法签发管理票据。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||
print(f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}")
|
||||
print(f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}")
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
_plugin_rows(data.get("plugins", {}))
|
||||
|
||||
elif cmd == "plugin-del":
|
||||
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||
print(f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "plugin-status":
|
||||
import urllib.parse as _q
|
||||
body = {}
|
||||
if args.status:
|
||||
body["status"] = args.status
|
||||
if args.force_min_version and args.force_deadline:
|
||||
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||
elif args.clear_force:
|
||||
body["clear_force"] = True
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
print("[ok]", json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
accounts = data.get("accounts", "")
|
||||
if isinstance(accounts, dict):
|
||||
accounts = list(accounts.values())
|
||||
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||
if not accounts:
|
||||
print("(暂无账号)")
|
||||
return 0
|
||||
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||
for a in accounts:
|
||||
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||
|
||||
elif cmd == "user-add":
|
||||
r = c.call("POST", "/api/admin/account", {
|
||||
"account": args.account, "password": args.password,
|
||||
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||
print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||
|
||||
elif cmd == "user-update":
|
||||
body = {"account": args.account}
|
||||
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||
if v is not None:
|
||||
body[k] = v
|
||||
r = c.call("POST", "/api/admin/account/update", body)
|
||||
print(f"[ok] 已更新 {r.get('account')}")
|
||||
|
||||
elif cmd == "user-reset-pwd":
|
||||
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||
print(f"[ok] 已重置 {r.get('account')} 密码")
|
||||
|
||||
elif cmd == "user-del":
|
||||
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||
print(f"[ok] 已删除账号 {r.get('account')}")
|
||||
|
||||
elif cmd == "grant":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||
print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||
f"/run={'y' if not args.no_run else 'n'})")
|
||||
|
||||
elif cmd == "revoke":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "grant-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||
print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "revoke-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "stats":
|
||||
print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2))
|
||||
|
||||
elif cmd == "me":
|
||||
data = c.call("GET", "/api/admin/me")
|
||||
print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||
f"部门:{data.get('dept') or ''}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
try:
|
||||
_run(args)
|
||||
except SystemExit as exc:
|
||||
if exc.code:
|
||||
print(str(exc.code))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane firewall script
|
||||
rem opens TCP port 8800. Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-8800" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-8800" dir=in action=allow protocol=TCP localport=8800
|
||||
|
||||
echo [OK] Firewall rule created: TCP 8800 open.
|
||||
pause
|
||||
@@ -0,0 +1,23 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center SMB firewall script
|
||||
rem opens SMB/NetBIOS ports so the deploy machine can reach
|
||||
rem the \\...\code share. Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-smb445" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-smb445" dir=in action=allow protocol=TCP localport=445
|
||||
netsh advfirewall firewall add rule name="37du-center-smb445udp" dir=in action=allow protocol=UDP localport=445
|
||||
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb139" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb139" dir=in action=allow protocol=TCP localport=139
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb137" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb137" dir=in action=allow protocol=UDP localport=137
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb138" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb138" dir=in action=allow protocol=UDP localport=138
|
||||
netsh advfirewall firewall delete rule name="37du-center-nb135" >nul 2>&1
|
||||
netsh advfirewall firewall add rule name="37du-center-nb135" dir=in action=allow protocol=UDP localport=135
|
||||
|
||||
echo [OK] Firewall rules created: SMB/NetBIOS open.
|
||||
pause
|
||||
@@ -0,0 +1,39 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane deployment script
|
||||
rem 1) copy 37du-center.exe to D:\code\controlplane
|
||||
rem 2) register auto-start (Startup folder vbs)
|
||||
rem 3) launch 37du-center.exe
|
||||
rem Run as Administrator.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
set "TARGET=D:\code\controlplane"
|
||||
|
||||
rem locate exe: parent folder (controlplane/), or its dist-exe\ subfolder
|
||||
if exist "%~dp0..\37du-center.exe" (
|
||||
set "SRC=%~dp0..\37du-center.exe"
|
||||
) else if exist "%~dp0..\dist-exe\37du-center.exe" (
|
||||
set "SRC=%~dp0..\dist-exe\37du-center.exe"
|
||||
) else (
|
||||
set "SRC=%~dp0..\dist\37du-center.exe"
|
||||
)
|
||||
if not exist "%SRC%" (echo [ERROR] Not found: 37du-center.exe & pause & exit /b 1)
|
||||
|
||||
rem 1) copy to deployment folder
|
||||
if not exist "%TARGET%" mkdir "%TARGET%"
|
||||
copy /y "%SRC%" "%TARGET%\37du-center.exe" >nul
|
||||
echo [OK] Copied to %TARGET%
|
||||
|
||||
rem 2) register auto-start
|
||||
set "STARTUP=%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup"
|
||||
set "VBS=%STARTUP%\37du-center.vbs"
|
||||
echo Set WshShell = CreateObject("WScript.Shell") > "%VBS%"
|
||||
echo WshShell.Run """%TARGET%\37du-center.exe""", 0, False >> "%VBS%"
|
||||
echo [OK] Auto-start registered.
|
||||
|
||||
rem 3) launch service
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
start "" "%TARGET%\37du-center.exe"
|
||||
echo [OK] 37du-center started. Visit http://this-host-ip:8800
|
||||
pause
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
rem ============================================================
|
||||
rem 37du center control-plane stop script
|
||||
rem stops 37du-center.exe (auto-start registration is kept)
|
||||
rem MUST run as Administrator because the service was started
|
||||
rem from an elevated register_autostart.bat.
|
||||
rem ============================================================
|
||||
net session >nul 2>&1 || (echo [ERROR] Please run as Administrator. & pause & exit /b 1)
|
||||
|
||||
taskkill /f /im 37du-center.exe >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [OK] 37du-center.exe is not running.
|
||||
) else (
|
||||
echo [OK] 37du-center.exe stopped.
|
||||
)
|
||||
pause
|
||||
@@ -0,0 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端(执行机底座):场景插件宿主。
|
||||
|
||||
组装层 main.py 之外的领域逻辑已归入 core 子包。本 `__init__` 作为 facade 再导出
|
||||
core 内各模块,以兼容 `from webhost.backend import X` 的既有用法(含插件 `auth` 引用)。
|
||||
"""
|
||||
from webhost.backend.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
cpapi,
|
||||
hub,
|
||||
licensing,
|
||||
meta,
|
||||
runner,
|
||||
scheduler,
|
||||
session,
|
||||
state,
|
||||
winjob,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
# 登录成功即按账号权限自下载/更新插件并重载(离线/失败不影响登录)
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.plugins import load_plugins
|
||||
sync_plugins(b.account.strip())
|
||||
load_plugins(None, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@router.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
|
||||
_SESS_LOCK, _sess_persist)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
|
||||
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
|
||||
|
||||
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
|
||||
"""
|
||||
r = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/auth",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
|
||||
acct = r.get("account") or account
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (acct, time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/login")
|
||||
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
|
||||
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
|
||||
if not d.account:
|
||||
raise HTTPException(400, "工号不能为空")
|
||||
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/inline")
|
||||
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
|
||||
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
|
||||
|
||||
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
|
||||
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"code": d.code.strip()})
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return _cp_call(
|
||||
"GET", "/api/admin/dingtalk/inline_qr",
|
||||
params={"back": back},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
|
||||
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
|
||||
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
|
||||
<script>
|
||||
(async function(){
|
||||
var q = new URLSearchParams(location.search);
|
||||
var account = q.get('account') || '';
|
||||
var nickname = q.get('nickname') || '';
|
||||
if (account) {
|
||||
try {
|
||||
await fetch('/api/admin/dingtalk/login', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ account: account, nickname: nickname })
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
try { window.opener && window.opener.location.reload(); } catch (e) {}
|
||||
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
|
||||
})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「业务元数据与平台登录」路由:/api/meta 聚合 + 平台真实登录/登出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/plugins/sync")
|
||||
def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/shell/update-status")
|
||||
def shell_update_status(request: Request) -> dict:
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示。"""
|
||||
_require_login(request)
|
||||
return _shell_updater.pending_status()
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.apply_update()
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
|
||||
online = licensing.is_online()
|
||||
deny = licensing.run_check_allowed(plugin.id, account, online)
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端领域逻辑核心(core)包。
|
||||
|
||||
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
|
||||
"""
|
||||
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主配置固化:加载本模块 env(webhost/.env) 并输出全部环境常量与路径。
|
||||
|
||||
依赖方向:config ← 所有领域逻辑与路由模块(只读,不含业务逻辑)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
|
||||
# 打包运行(frozen)时:底座根 = exe 所在目录(.env、plugins/ 与 exe 同级部署);
|
||||
# 前端静态资源打包进 exe 内部,运行时从解压目录(_MEIPASS)读取
|
||||
if getattr(sys, "frozen", False):
|
||||
_HOST_ROOT = Path(sys.executable).resolve().parent
|
||||
DIST = Path(getattr(sys, "_MEIPASS", _HOST_ROOT)) / "frontend" / "dist"
|
||||
else:
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[1]
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
PORT = 8799
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = _HOST_ROOT / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
_k, _v = _k.strip(), _v.strip()
|
||||
if _k and _k not in os.environ:
|
||||
os.environ[_k] = _v
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
@@ -0,0 +1,85 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。
|
||||
|
||||
底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
if not config.CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": config.CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。
|
||||
run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._clients: list = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def bind(self, loop: asyncio.AbstractEventLoop):
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, websocket) -> None:
|
||||
await websocket.accept()
|
||||
with self._lock:
|
||||
self._clients.append(websocket)
|
||||
try:
|
||||
await websocket.receive_text() # 挂起直到客户端断开
|
||||
finally:
|
||||
with self._lock:
|
||||
self._clients.remove(websocket)
|
||||
|
||||
def publish(self, event: Dict) -> None:
|
||||
if self._loop is None:
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(self._send(event), self._loop)
|
||||
|
||||
async def _send(self, event: Dict) -> None:
|
||||
with self._lock:
|
||||
clients = list(self._clients)
|
||||
for ws in clients:
|
||||
try:
|
||||
await ws.send_json(event)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._clients.remove(ws)
|
||||
|
||||
|
||||
HUB = Hub()
|
||||
@@ -0,0 +1,283 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
|
||||
|
||||
职责(对应架构设计七、八节):
|
||||
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
|
||||
license.json (离线授权票据,Ed25519 签名,离线一直有效)
|
||||
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
|
||||
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
|
||||
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
|
||||
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
|
||||
- verify_license() / verify_control() —— 用缓存公钥离线验签。
|
||||
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
KEYS_DIR = _APP_DATA / "keys"
|
||||
license_path = _APP_DATA / "license.json"
|
||||
control_path = _APP_DATA / "control.json"
|
||||
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
|
||||
|
||||
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
|
||||
_ONLINE_TTL = 180
|
||||
_last_sync = 0.0
|
||||
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
|
||||
|
||||
_CONTROLPLANE_URL = "" # 由 main.py 注入
|
||||
|
||||
|
||||
def init(controlplane_url: str, sync_lock) -> None:
|
||||
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
|
||||
global _CONTROLPLANE_URL, _sync_lock
|
||||
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
|
||||
_sync_lock = sync_lock
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
KEYS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
# ==================== 联网判定 ====================
|
||||
def touch_sync() -> None:
|
||||
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
|
||||
global _last_sync
|
||||
with _sync_lock:
|
||||
_last_sync = time.time()
|
||||
|
||||
|
||||
def is_online() -> bool:
|
||||
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
|
||||
with _sync_lock:
|
||||
return (time.time() - _last_sync) <= _ONLINE_TTL
|
||||
|
||||
|
||||
# ==================== 公钥缓存与验签 ====================
|
||||
def _pub_pem_path() -> Path:
|
||||
return KEYS_DIR / "pub.pem"
|
||||
|
||||
|
||||
def cache_public_key(pem_text: str) -> None:
|
||||
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
|
||||
pem_text = (pem_text or "").strip()
|
||||
if not pem_text:
|
||||
return
|
||||
_pub_pem_path().write_text(pem_text, encoding="ascii")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def _load_public_key() -> Ed25519PublicKey | None:
|
||||
try:
|
||||
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
|
||||
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
|
||||
return None
|
||||
|
||||
|
||||
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
"""验签返回 payload;签名非法抛 ValueError。"""
|
||||
if "." not in blob:
|
||||
raise ValueError("bad blob")
|
||||
b64, sig64 = blob.rsplit(".", 1)
|
||||
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
|
||||
|
||||
def verify_license() -> dict:
|
||||
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
|
||||
if not license_path.is_file():
|
||||
raise ValueError("无本地授权票据(license.json)")
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
raise ValueError("缺少中心机公钥,无法验签授权票据")
|
||||
data = json.loads(license_path.read_text(encoding="utf-8"))
|
||||
return _verify_blob(data["ticket"], pub)
|
||||
|
||||
|
||||
def verify_control() -> dict:
|
||||
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
|
||||
if not control_path.is_file():
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
try:
|
||||
data = json.loads(control_path.read_text(encoding="utf-8"))
|
||||
payload = _verify_blob(data["ticket"], pub)
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
def save_license(ticket_json: dict | str) -> None:
|
||||
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
license_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def save_control(ticket_json: dict | str) -> None:
|
||||
"""持久化管控清单缓存。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
control_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
|
||||
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
|
||||
|
||||
- 验签授权票据,校验该插件 canRun。
|
||||
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
|
||||
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
|
||||
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
|
||||
"""
|
||||
control = verify_control()
|
||||
if plugin_id in control.get("revokedPlugins", []):
|
||||
return "插件已被下架(revoked),禁止运行"
|
||||
if plugin_id in control.get("disabledPlugins", []):
|
||||
return "插件已被禁用(disabled),禁止运行"
|
||||
|
||||
# 授权:先验签本地授权票据(离线可用)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except Exception as _exc: # noqa: BLE001 授权票据不可用
|
||||
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
|
||||
|
||||
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
|
||||
grant = lic_plugins.get(plugin_id)
|
||||
if not grant:
|
||||
return f"账号 {account} 无插件「{plugin_id}」的授权"
|
||||
if not grant.get("canRun"):
|
||||
return f"账号 {account} 无「{plugin_id}」的运行授权"
|
||||
|
||||
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
|
||||
if online:
|
||||
forced = next((f for f in control.get("forcedUpdates", [])
|
||||
if f.get("pluginId") == plugin_id), None)
|
||||
if forced:
|
||||
min_ver = forced.get("minVersion", "")
|
||||
deadline = forced.get("deadline", "")
|
||||
if min_ver and deadline and _deadline_passed(deadline):
|
||||
installed = _installed_version(plugin_id)
|
||||
if installed and _version_lt(installed, min_ver):
|
||||
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
|
||||
f"当前 v{installed} 已禁止启动,请先更新")
|
||||
return None
|
||||
|
||||
|
||||
def _installed_version(plugin_id: str) -> str:
|
||||
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
|
||||
act = _APP_DATA / "active.json"
|
||||
try:
|
||||
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
|
||||
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _deadline_passed(deadline: str) -> bool:
|
||||
try:
|
||||
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
|
||||
return datetime.now(dt.tzinfo) > dt
|
||||
except Exception: # noqa: BLE001
|
||||
# 解析失败时按未过期兜底(不误伤在线用户)
|
||||
return False
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""版本比较:数字段按 int,非数字段按 str 小写。"""
|
||||
def _k(s):
|
||||
try:
|
||||
return (1, int(s))
|
||||
except ValueError:
|
||||
return (0, str(s).lower())
|
||||
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
|
||||
|
||||
|
||||
# ==================== 运行上报 ====================
|
||||
def report(account: str, device_id: str, plugin_id: str, version: str,
|
||||
status: str, msg: str = "", duration_sec: int = 0) -> None:
|
||||
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
|
||||
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
|
||||
"version": version, "status": status, "msg": msg,
|
||||
"duration_sec": int(duration_sec),
|
||||
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
||||
if not _CONTROLPLANE_URL:
|
||||
return
|
||||
if _push_report(rec):
|
||||
touch_sync()
|
||||
return
|
||||
# 离线:暂存待补报
|
||||
try:
|
||||
with open(reports_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _push_report(rec: dict) -> bool:
|
||||
"""同步上报一条到中心机;成功返回 True。"""
|
||||
try:
|
||||
_push_via_tempfile(rec) # 用 go-offset 方式直连
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _push_via_tempfile(rec: dict) -> None:
|
||||
"""向 /api/runtime/report 的同步 POST(requests)。"""
|
||||
import requests
|
||||
|
||||
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
|
||||
json=rec, timeout=5)
|
||||
r.raise_for_status()
|
||||
|
||||
|
||||
def flush_offline_reports() -> int:
|
||||
"""重连后补报此前暂存的离线记录;返回补报条数。"""
|
||||
if not reports_path.is_file():
|
||||
return 0
|
||||
sent = 0
|
||||
pending = []
|
||||
try:
|
||||
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
|
||||
for ln in lines:
|
||||
try:
|
||||
rec = json.loads(ln)
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
_push_via_tempfile(rec)
|
||||
sent += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pending.append(ln) # 仍失败则保留下次再补
|
||||
if not pending:
|
||||
reports_path.unlink(missing_ok=True) # 全部成功则清空
|
||||
else:
|
||||
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return sent
|
||||
@@ -0,0 +1,114 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主插件元数据 / 平台权限解析。
|
||||
|
||||
- 插件元数据由 plugin.json(manifest) 驱动,离线与旧插件兼容
|
||||
- 平台/插件白名单来自中心机,按账号过滤(三态降级:授权集 / 空集防越权 / None 离线兜底全量)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
"""组装插件元数据(manifest 驱动)。
|
||||
|
||||
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
|
||||
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
|
||||
"""
|
||||
manifest = _read_own_manifest(p)
|
||||
name = (manifest or {}).get("name") or p.name
|
||||
description = (manifest or {}).get("description")
|
||||
if description is None:
|
||||
description = p.description
|
||||
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
|
||||
if fields is None:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
def _read_own_manifest(p) -> dict | None:
|
||||
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
|
||||
try:
|
||||
mod = sys.modules.get(type(p).__module__)
|
||||
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
|
||||
if not jar or not jar.is_file():
|
||||
return None
|
||||
return json.loads(jar.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _fields_from_schema(schema: dict) -> list | None:
|
||||
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
|
||||
if not schema or schema.get("type") != "object" or not schema.get("properties"):
|
||||
return None
|
||||
out = []
|
||||
for key, prop in schema["properties"].items():
|
||||
item = {"key": key, "label": prop.get("title", key),
|
||||
"default": prop.get("default", "")}
|
||||
t = prop.get("type", "string")
|
||||
if t == "integer" or t == "number":
|
||||
item["type"] = "int"
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
if d:
|
||||
item["description"] = d
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.core.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
- get_session / get_user_id 在本进程内直接读取共享 cookie 文件重建,不依赖主进程
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
if getattr(sys, "frozen", False):
|
||||
root = os.path.dirname(os.path.abspath(sys.executable)) # 打包运行:exe 同级目录
|
||||
os.chdir(root)
|
||||
return root
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__))))) # core/plugin_runner.py → 项目根
|
||||
if root not in sys.path:
|
||||
sys.path.insert(0, root)
|
||||
return root
|
||||
|
||||
|
||||
_ROOT = _bootstrap_paths()
|
||||
try:
|
||||
os.chdir(_ROOT)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
|
||||
try:
|
||||
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
_PROTO.flush()
|
||||
except Exception: # noqa: BLE001 通道已关则静默
|
||||
pass
|
||||
|
||||
|
||||
def _run() -> int:
|
||||
# 协议通道 = 原始 sys.stdout(fd1);把插件的 print 改道到 stderr,防止污染协议行
|
||||
global _PROTO
|
||||
_PROTO = sys.stdout
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
plugin_id = args.get("--plugin") or (sys.argv[sys.argv.index("--plugin") + 1]
|
||||
if "--plugin" in sys.argv else "")
|
||||
if not plugin_id:
|
||||
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
|
||||
return 2
|
||||
# 宿主透传的插件白名单:与宿主进程加载集保持一致(未传 = 全量)
|
||||
allowed_arg = (sys.argv[sys.argv.index("--allowed") + 1]
|
||||
if "--allowed" in sys.argv else "")
|
||||
allowed = {s for s in allowed_arg.split(",") if s} if allowed_arg else None
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
fields: dict = {}
|
||||
try:
|
||||
_line = sys.stdin.readline().strip()
|
||||
if _line:
|
||||
fields = json.loads(_line) or {}
|
||||
except Exception as _e: # noqa: BLE001
|
||||
fields = {}
|
||||
|
||||
class _ChildContext(RunContext):
|
||||
"""子进程版上下文:log/progress 经 stdout 回传;登录态在本进程重建。"""
|
||||
|
||||
def __init__(self, run_id: str, plugin_id: str, auth):
|
||||
super().__init__(hub=None, run_id=run_id, plugin_id=plugin_id, auth=auth)
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
_emit({"ev": "log", "level": level, "msg": str(msg)})
|
||||
|
||||
def progress(self, pct: int):
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins(allowed)
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
result = plugin.run(fields, ctx)
|
||||
_emit({"ev": "result", "ok": True, "result": result})
|
||||
return 0
|
||||
except KeyError:
|
||||
_emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"})
|
||||
return 3
|
||||
except Exception as _e: # noqa: BLE001 插件顶层兜底
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
_emit({"ev": "result", "ok": False, "error": str(_e)})
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_run())
|
||||
@@ -0,0 +1,185 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 30 # 包下载超时(秒)
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
return str(json.loads(mf.read_text(encoding="utf-8")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["failed"])
|
||||
return result
|
||||
@@ -0,0 +1,165 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||||
|
||||
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
|
||||
由 Windows Job Object 整树托管(含浏览器孙进程)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import scheduler as _scheduler
|
||||
from webhost.backend.core import winjob as _winjob
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import state as _st
|
||||
from webhost.backend.core.hub import HUB
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
# 打包运行(frozen):拉起同级 37du-host-runner.exe(console 壳,内置同一套执行代码)
|
||||
if getattr(sys, "frozen", False):
|
||||
runner_exe = Path(sys.executable).with_name("37du-host-runner.exe")
|
||||
cmd = [str(runner_exe), "--plugin", plugin.id, "--run", run_id]
|
||||
root = Path(sys.executable).resolve().parent
|
||||
else:
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
job.assign(proc)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_st._set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||||
try:
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id) or {}
|
||||
account = run.get("account", "")
|
||||
status = "done" if run.get("status") == "done" else \
|
||||
("running" if run.get("status") == "running" else "error")
|
||||
msg = run.get("error") or ""
|
||||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||||
licensing.report(account=account, device_id="",
|
||||
plugin_id=plugin_id, version=run.get("version", ""),
|
||||
status=status, msg=msg, duration_sec=duration)
|
||||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||||
_LOGGER.warning("运行上报失败:%s", _exc)
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""设备级单活调度器:整机同一时刻只运行一个插件进程。
|
||||
|
||||
- active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。
|
||||
- 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。
|
||||
- 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活;
|
||||
启动失败回滚到"空闲",不让半激活状态阻塞后续启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
ACTIVE_PATH = _APP_DATA / "active.json"
|
||||
|
||||
# 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。
|
||||
_SCHED_COND = threading.Condition()
|
||||
|
||||
|
||||
def init_active() -> None:
|
||||
"""初始化 active.json(无则写入空闲态),并确保数据目录可写。
|
||||
进程启动时若残留 running/switching(上次异常退出/断电),复位为空闲,
|
||||
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
if not ACTIVE_PATH.is_file():
|
||||
write_active(userId="", pluginId="", version="", status="idle")
|
||||
elif read_active().get("status") in ("running", "switching"):
|
||||
_LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲")
|
||||
write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="")
|
||||
|
||||
|
||||
def read_active() -> dict:
|
||||
try:
|
||||
d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {}
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def _is_busy() -> bool:
|
||||
return read_active().get("status") in ("running", "switching")
|
||||
|
||||
|
||||
def write_active(**kw) -> None:
|
||||
"""写回 active.json(保留既有键,仅更新传入字段)。"""
|
||||
d = read_active()
|
||||
d.update(kw)
|
||||
d.setdefault("userId", "")
|
||||
d.setdefault("pluginId", "")
|
||||
d.setdefault("version", "")
|
||||
d.setdefault("status", "idle")
|
||||
d.setdefault("startedAt", "")
|
||||
d.setdefault("runId", "")
|
||||
try:
|
||||
# 原子写:先写临时文件再 os.replace,避免写入中断留下半截 JSON 被误读
|
||||
tmp = ACTIVE_PATH.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
|
||||
os.replace(tmp, ACTIVE_PATH)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("写 active.json 失败:%s", _exc)
|
||||
|
||||
|
||||
def current() -> dict:
|
||||
"""当前活动插件(空闲则返回空映射)。"""
|
||||
return read_active()
|
||||
|
||||
|
||||
def is_active(plugin_id: str) -> bool:
|
||||
"""当前设备是否正在跑该插件。"""
|
||||
a = read_active()
|
||||
return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id)
|
||||
|
||||
|
||||
def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict:
|
||||
"""设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。
|
||||
|
||||
- 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。
|
||||
- `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。
|
||||
- 启动失败回滚到"空闲"并唤醒等待者。
|
||||
"""
|
||||
with _SCHED_COND:
|
||||
while _is_busy():
|
||||
_SCHED_COND.wait()
|
||||
write_active(status="switching", startedAt=_now())
|
||||
try:
|
||||
run_id = start_fn()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
return {"ok": False, "error": f"启动失败:{_exc}"}
|
||||
write_active(userId=user, pluginId=plugin_id, version=version,
|
||||
status="running", runId=run_id, startedAt=_now())
|
||||
return {"ok": True, "run_id": run_id}
|
||||
|
||||
|
||||
def mark_done(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。"""
|
||||
with _SCHED_COND:
|
||||
a = read_active()
|
||||
if a.get("pluginId") == plugin_id and a.get("runId") == run_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
elif a.get("pluginId") == plugin_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
|
||||
|
||||
会话状态(token->account 活跃ts)只在此模块定义;admin/dingtalk/meta 等路由经本模块访问。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
|
||||
_SESS_TTL = 7 * 24 * 3600
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
|
||||
# 打包运行(frozen)时落盘到 exe 同级目录
|
||||
_SESS_FILE = (Path(sys.executable).resolve().parent if getattr(sys, "frozen", False)
|
||||
else Path(__file__).resolve().parents[1]) / "_cp_sessions.json"
|
||||
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _sess_persist():
|
||||
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
|
||||
try:
|
||||
with _SESS_LOCK:
|
||||
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
|
||||
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("本机会话持久化失败: %s", _exc)
|
||||
|
||||
|
||||
def _sess_load():
|
||||
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
|
||||
if not _SESS_FILE.is_file():
|
||||
return
|
||||
try:
|
||||
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
_now = time.time()
|
||||
with _SESS_LOCK:
|
||||
for _t, _it in (_raw or {}).items():
|
||||
try:
|
||||
_a, _ts = _it[0], float(_it[1])
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
continue
|
||||
if _now - _ts <= _SESS_TTL:
|
||||
_SESS[_t] = (_a, _ts)
|
||||
|
||||
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
account = ""
|
||||
with _SESS_LOCK:
|
||||
item = _SESS.get(token)
|
||||
if item:
|
||||
_account, _ts = item
|
||||
if time.time() - _ts <= _SESS_TTL:
|
||||
_SESS[token] = (_account, time.time()) # 滑动续期
|
||||
account = _account
|
||||
else:
|
||||
_SESS.pop(token, None)
|
||||
if account:
|
||||
_sess_persist() # 滑动续期也落盘,重启后仍有效
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机壳子(主程序)自动更新:自动下载新版安装包,由用户点击触发静默升级重启。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检查+下载:启动时后台检查控制面 /api/shell/version,版本落后则自动把新版安装包
|
||||
下载到 %LOCALAPPDATA%\\37duAutomation\\shell\\(本地缓存,不打断用户)。
|
||||
2. 应用:前端提示"发现新版本"后用户点击 → apply_update() 运行安装包
|
||||
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
|
||||
安装完成由 [Run] 自动重启新版本主程序。
|
||||
3. 离线/控制面不可达/校验失败:静默跳过,不影响使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
|
||||
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
|
||||
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
|
||||
_PENDING: dict = {}
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。"""
|
||||
if not getattr(sys, "frozen", False):
|
||||
return ""
|
||||
vf = Path(sys.executable).resolve().parent / "shell.version"
|
||||
try:
|
||||
return vf.read_text(encoding="utf-8").strip() if vf.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def check_and_download() -> dict | None:
|
||||
"""检查壳子更新并自动下载安装包到本地缓存。有可用更新返回 {version, notes};否则 None。"""
|
||||
cur = local_shell_version()
|
||||
if not cur or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
|
||||
headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
info = r.json()
|
||||
except Exception as _exc: # noqa: BLE001 离线/不可达
|
||||
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
|
||||
return None
|
||||
if not info.get("available") or not info.get("version"):
|
||||
return None
|
||||
cloud = str(info["version"])
|
||||
if not _version_lt(cur, cloud):
|
||||
return None
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/pkg",
|
||||
headers=_headers(), timeout=300)
|
||||
r.raise_for_status()
|
||||
data = r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
return None
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(data).hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
return None
|
||||
try:
|
||||
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
pkg.write_bytes(data)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
|
||||
return None
|
||||
_PENDING["version"] = cloud
|
||||
_PENDING["notes"] = info.get("notes", "")
|
||||
_LOGGER.info("壳子新版本已下载待应用:%s → %s(%d 字节)", cur, cloud, len(data))
|
||||
return {"version": cloud, "notes": _PENDING["notes"]}
|
||||
|
||||
|
||||
def cached_pkg(version: str) -> Path | None:
|
||||
"""本地缓存的指定版本安装包路径;不存在返回 None。"""
|
||||
p = _SHELL_CACHE / f"setup-37du-host-{version}.exe"
|
||||
return p if p.is_file() else None
|
||||
|
||||
|
||||
def pending_status() -> dict:
|
||||
"""当前更新状态(供前端提示):当前版本 / 待应用新版本 / 是否已下载。"""
|
||||
return {
|
||||
"current": local_shell_version(),
|
||||
"new": _PENDING.get("version", ""),
|
||||
"notes": _PENDING.get("notes", ""),
|
||||
"downloaded": bool(_PENDING.get("version"))
|
||||
and cached_pkg(_PENDING.get("version", "")) is not None,
|
||||
}
|
||||
|
||||
|
||||
def apply_update() -> None:
|
||||
"""运行新版安装包静默覆盖安装并退出本进程(升级完成后由 Inno 重启新版本)。
|
||||
|
||||
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
|
||||
"""
|
||||
version = _PENDING.get("version", "")
|
||||
pkg = cached_pkg(version)
|
||||
if not pkg:
|
||||
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
|
||||
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
time.sleep(1) # 给安装器接管进程,随后退出让 Inno CloseApplications 收尾
|
||||
os._exit(0)
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。
|
||||
|
||||
- ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写
|
||||
(`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`),
|
||||
避免 from-import 复制绑定读不到最新值。
|
||||
- RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。
|
||||
依赖方向:state ← 领域逻辑与路由模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
|
||||
def set_allowed(v: set | None) -> None:
|
||||
global ALLOWED
|
||||
ALLOWED = v
|
||||
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Windows Job Object 封装:插件执行子进程整树托管。
|
||||
|
||||
- KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的
|
||||
浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程;
|
||||
- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。
|
||||
非 Windows 平台所有方法安全降级为 no-op。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import sys
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_AVAILABLE = sys.platform == "win32"
|
||||
if _AVAILABLE:
|
||||
try:
|
||||
_K32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
except AttributeError: # 非 Windows 误导入
|
||||
_AVAILABLE = False
|
||||
|
||||
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
||||
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000
|
||||
_JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100
|
||||
_PROCESS_SET_QUOTA = 0x0100
|
||||
_PROCESS_TERMINATE = 0x0001
|
||||
|
||||
|
||||
if _AVAILABLE:
|
||||
class _IO_COUNTERS(ctypes.Structure):
|
||||
_fields_ = [(n, ctypes.c_uint64) for n in (
|
||||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
||||
|
||||
class _BASIC_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("PerProcessUserTimeLimit", ctypes.c_int64),
|
||||
("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", ctypes.c_uint32),
|
||||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||||
("ActiveProcessLimit", ctypes.c_uint32),
|
||||
("Affinity", ctypes.c_size_t),
|
||||
("PriorityClass", ctypes.c_uint32),
|
||||
("SchedulingClass", ctypes.c_uint32),
|
||||
]
|
||||
|
||||
class _EXT_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("BasicLimitInformation", _BASIC_LIMIT_INFO),
|
||||
("IoInfo", _IO_COUNTERS),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||||
("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
|
||||
class Job:
|
||||
"""一次性的插件子进程作业。用法:job = Job(); job.assign(proc); …; job.terminate()/close()。"""
|
||||
|
||||
def __init__(self, max_mem_mb: int = 0):
|
||||
self._h = None
|
||||
if not _AVAILABLE:
|
||||
return
|
||||
h = _K32.CreateJobObjectW(None, None)
|
||||
if not h:
|
||||
_LOGGER.warning("创建 Job Object 失败(winerror=%s),退化为无作业托管", ctypes.get_last_error())
|
||||
return
|
||||
info = _EXT_LIMIT_INFO()
|
||||
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if max_mem_mb > 0:
|
||||
info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY
|
||||
info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024
|
||||
if not _K32.SetInformationJobObject(
|
||||
h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
ctypes.byref(info), ctypes.sizeof(info)):
|
||||
_LOGGER.warning("设置 Job Object 限制失败(winerror=%s)", ctypes.get_last_error())
|
||||
self._h = h
|
||||
|
||||
def assign(self, proc) -> None:
|
||||
"""把子进程(及其后代)纳入作业托管。"""
|
||||
if not self._h:
|
||||
return
|
||||
if not _K32.AssignProcessToJobObject(self._h, int(proc._handle)):
|
||||
_LOGGER.warning("子进程纳入 Job Object 失败(winerror=%s)", ctypes.get_last_error())
|
||||
|
||||
def terminate(self, exit_code: int = 1) -> None:
|
||||
"""终止作业内全部进程(整树强杀,含浏览器等孙进程)。"""
|
||||
if self._h:
|
||||
_K32.TerminateJobObject(self._h, exit_code)
|
||||
|
||||
def close(self) -> None:
|
||||
"""关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。"""
|
||||
if self._h:
|
||||
_K32.CloseHandle(self._h)
|
||||
self._h = None
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
|
||||
|
||||
业务逻辑已按领域拆到 sibling 模块:
|
||||
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
|
||||
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
|
||||
- apis/ 路由子包(admin / dingtalk / meta / runs)
|
||||
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级
|
||||
def _boot_shell_check() -> None:
|
||||
try:
|
||||
from webhost.backend.core.shell_updater import check_and_download
|
||||
check_and_download()
|
||||
except Exception as _exc: # noqa: BLE001 检查失败不阻断启动
|
||||
_LOGGER.warning("启动壳子更新检查失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_shell_check, daemon=True).start()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
|
||||
|
||||
if config.DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
def _port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
print(f"[webhost] port {config.PORT} free = {_port_free(config.PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")
|
||||
@@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件注册表——目录动态扫描加载。
|
||||
|
||||
加载约定(扫描协议):
|
||||
- 插件形态:plugins/ 下的**目录包**(含 __init__.py,在其中定义 ScenePlugin 子类并
|
||||
PLUGINS.append,如 seal_check/)。顶层单模块(*.py)仅用于兼容旧 demo/platform_check。
|
||||
- 私有辅助文件**必须用 `_` 前缀**(如 _utils.py、_common/),扫描时一律排除,
|
||||
避免被误当作插件 import。
|
||||
- 只有继承 ScenePlugin 并通过 PLUGINS.append 注册的才会进入注册表;_ 前缀约定
|
||||
确保辅助模块根本不会被 import,杜绝误注册与无用告警。
|
||||
- 同名冲突:目录优先于同名 .py(先收目录再收 py,同名仅保留目录)。
|
||||
- 单个插件加载失败记 ERROR 并保留堆栈首行后跳过,不拖垮整体启动。
|
||||
|
||||
阶段二(权限):把「有权限的插件名」传给 load_plugins(allowed) 即可,无权限不 import。
|
||||
届时触发点建议从「import 副作用」改为由 main.py 在应用启动时显式调用 load_plugins(),
|
||||
以便每次按登录账号动态决定允许集。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import pathlib
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
|
||||
|
||||
# 插件目录(源码/打包统一的"单一真源"位置):
|
||||
# - 打包运行(frozen)时:exe 同级 plugins/(中心机下发插件包解压到这里)
|
||||
# - 源码运行:仓库根 plugins/(插件源码独立于底座,不随 webhost 发布)
|
||||
# 两种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
if getattr(sys, "frozen", False):
|
||||
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
|
||||
else:
|
||||
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
|
||||
_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parents[4] / "plugins"
|
||||
if _PLUGINS_ROOT.is_dir() and str(_PLUGINS_ROOT) not in __path__:
|
||||
__path__.append(str(_PLUGINS_ROOT))
|
||||
_PKG_NAME = __name__
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _discover_modules() -> list:
|
||||
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
|
||||
names: list = []
|
||||
seen: set = set()
|
||||
for d in sorted(_PLUGINS_ROOT.iterdir()):
|
||||
if not d.is_dir() or d.name.startswith("_") or d.name == "__pycache__":
|
||||
continue
|
||||
if (d / "__init__.py").exists():
|
||||
names.append(d.name)
|
||||
seen.add(d.name)
|
||||
for f in sorted(_PLUGINS_ROOT.glob("*.py")):
|
||||
if f.name in ("__init__.py", "base.py") or f.name.startswith("_"):
|
||||
continue
|
||||
if f.stem not in seen: # 已被同名目录占用则跳过
|
||||
names.append(f.stem)
|
||||
return names
|
||||
|
||||
|
||||
def load_plugins(allowed: set = None, reload: bool = False) -> None:
|
||||
"""动态加载插件。allowed 为 None = 全量;否则为严格白名单(空集 = 零权限,全不加载)。
|
||||
|
||||
reload=True 时先清空注册表与已加载模块缓存(用于插件自下载/更新后的重载,使新代码生效)。
|
||||
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
|
||||
"""
|
||||
if reload:
|
||||
PLUGINS.clear()
|
||||
for _m in [m for m in sys.modules
|
||||
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME]:
|
||||
del sys.modules[_m]
|
||||
for _mod in _discover_modules():
|
||||
if allowed is not None and _mod not in allowed:
|
||||
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
|
||||
continue
|
||||
try:
|
||||
importlib.import_module(f"{_PKG_NAME}.{_mod}")
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("插件 %s 加载失败,已跳过\n%s", _mod,
|
||||
traceback.format_exc(limit=1))
|
||||
|
||||
|
||||
# 注意:这里不再 import 时自动加载。由宿主(main.py)在应用启动时显式调用
|
||||
# load_plugins(allowed) 一次性加载,以便阶段二可传入按账号动态计算的权限白名单。
|
||||
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""场景插件抽象:后端 `run` 承载真实逻辑(浏览器自动化/登录态等),
|
||||
前端按 `fields` 渲染通用表单,执行过程经 `RunContext.log/progress` 推送到 WebSocket。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
|
||||
|
||||
class RunContext:
|
||||
"""传给插件 `run` 的执行上下文:把日志/进度实时推给前端,并提供共享登录态访问。"""
|
||||
|
||||
def __init__(self, hub, run_id: str, plugin_id: str, auth=None):
|
||||
self._hub = hub
|
||||
self._auth = auth # webhost.backend.auth 模块(宿主注入的共享登录态)
|
||||
self.run_id = run_id
|
||||
self.plugin_id = plugin_id
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
self._hub.publish({
|
||||
"t": "log", "run_id": self.run_id, "plugin_id": self.plugin_id,
|
||||
"level": level, "msg": msg,
|
||||
})
|
||||
|
||||
def progress(self, pct: int):
|
||||
self._hub.publish({
|
||||
"t": "progress", "run_id": self.run_id,
|
||||
"plugin_id": self.plugin_id, "pct": int(max(0, min(100, pct))),
|
||||
})
|
||||
|
||||
# ---------- 共享登录态 ----------
|
||||
def get_session(self, platform: str) -> "requests.Session":
|
||||
"""获取指定平台的共享登录 session,可直接传给 shared 数据模块。"""
|
||||
if not self._auth:
|
||||
raise RuntimeError("宿主未注入登录态服务,无法构建 session")
|
||||
return self._auth.build_session(platform)
|
||||
|
||||
def get_user_id(self, platform: str) -> str:
|
||||
"""获取指定平台的用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if not self._auth:
|
||||
raise RuntimeError("宿主未注入登录态服务,无法获取 user_id")
|
||||
return self._auth.get_user_id(platform)
|
||||
|
||||
|
||||
class ScenePlugin:
|
||||
"""场景插件基类。新增场景:子类填 id/name/fields/run 并注册到 plugins 列表。"""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
version: str = "1.0.0"
|
||||
description: str = ""
|
||||
platform: str = "" # 所需平台登录态:hr / oa / ""(无需登录)
|
||||
uses_month: bool = False # 是否需要底座页眉的“执行月份”(前端据此注入 ref_month 字段)
|
||||
# 表单字段定义:[{key,label,type,default,options}]
|
||||
# type ∈ int | text | select
|
||||
fields: List[dict] = []
|
||||
# 声明式能力/权限(manifest 驱动):与插件包 plugin.json 保持一致;
|
||||
# 缺省场景可用本地类补充,plugin.json 存在时以其为权威。
|
||||
capabilities: List[str] = []
|
||||
permissions: dict = {}
|
||||
|
||||
def run(self, fields: dict, ctx: RunContext) -> dict:
|
||||
raise NotImplementedError(f"插件 {self.id} 未实现 run")
|
||||
|
||||
|
||||
class _Registry(list):
|
||||
def find(self, pid: str) -> ScenePlugin:
|
||||
for p in self:
|
||||
if p.id == pid:
|
||||
return p
|
||||
raise KeyError(pid)
|
||||
|
||||
|
||||
PLUGINS: _Registry = _Registry()
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost.backend.shared:webhost 共享模块(登录/导出/封存拉取)
|
||||
|
||||
原 desktop/shared 迁入,webhost 单一真源,完全自包含、不依赖其他目录。
|
||||
与 workflows/(影刀版)为**独立维护的两份副本**,修改时若需同步,
|
||||
请手动将 workflows 对应文件复制覆盖到本目录。
|
||||
"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,241 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=OA 登录页 URL
|
||||
SUCCESS_KEYWORD=OA 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
oa_validate_url=(可选,.env/系统变量)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(force=True) 影刀自定义指令调用入口,force 传 True/False(是否强制重新登录),返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main(force=True))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://oa.37du.co/login.jsp'
|
||||
SUCCESS_KEYWORD = 'https://oa.37du.co/sys/portal/page.jsp'
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化 ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.get(validate_url, params={"method": "sumTodoCount"}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_url / oa_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main(force=True)
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,401 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: org_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 组织维护(组织设置)导出(影刀共享指令,单文件自包含)——从共享登录态读取
|
||||
HR cookies,调用组织维护台账实时查询接口(queryRealTimeData.mc)分页拉取
|
||||
全部组织数据,转换为页面 18 列格式后导出 Excel。纯接口实现,无需浏览器。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du组织维护导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
output_path Excel 保存路径(默认 D:\\资料\\人资\\组织维护\\组织维护.xlsx)
|
||||
2. 命令行:python org_export.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 export_orgs(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
PAGE_MAX_SIZE = 500 # 每页最大条数
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由自实现前端加密动态生成(等价抓包原始串,即 in_use in ('1') 条件);
|
||||
# 需要追加/修改查询条件时改 ORG_QUERY_CONDITIONS 后由 encode_common_query 重新加密
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 接口字段 -> 页面列名映射(「序号」接口不返回,转换时按行号生成;
|
||||
# 分管部门对应 pt_structure2.ORG_ALIAS,当前数据未使用但列位保留) ----------
|
||||
ORG_FIELD_MAP = [
|
||||
("pt_organzation.ORG_NAME", "组织名称"),
|
||||
("pt_organzation.ORG_CODE", "组织编号"),
|
||||
("pt_organzation.ORG_TYPE_CODE", "组织类型"),
|
||||
("pt_structure1.ORG_ALIAS", "上级组织"),
|
||||
("org_principal_staff_name_select.org_principal_staff_name", "组织负责人"),
|
||||
("pt_structure2.ORG_ALIAS", "分管部门"),
|
||||
("branch_leader_name_select.branch_leader_name", "分管领导"),
|
||||
("pt_organzation.BEGIN_DATE", "成立日期"),
|
||||
("pt_orgnization_extend.FOUND_DOC_NUM", "成立文号"),
|
||||
("pt_organzation.CANT_CODE", "所属地区"),
|
||||
("pt_organzation.office_address", "办公地址"),
|
||||
("pt_organzation.remarks", "备注"),
|
||||
("pt_orgnization_extend.FOUND_REASON", "成立原因"),
|
||||
("pt_structure.ORG_FULL_PATH", "组织全路径"),
|
||||
("pt_organzation.create_time", "创建时间"),
|
||||
("pt_organzation.IN_USE", "使用状态"),
|
||||
("pt_organzation_ext.ext_payday", "发薪日"),
|
||||
]
|
||||
|
||||
# 使用状态编码 -> 文字
|
||||
IN_USE_MAP = {"1": "在用", "0": "停用"}
|
||||
|
||||
# ---------- 默认导出参数(内置默认值,便于分发共享;如需覆盖请直接改这里或由 main(args) 传参) ----------
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
|
||||
# ---------- 项目级重试次数(单页请求失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成组织维护查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 接口请求 ====================
|
||||
def _fetch_org_page_once(session, page_no, page_size):
|
||||
"""请求单页组织维护数据(单次请求,不含重试)。"""
|
||||
params = ORG_QUERY_BASE_PARAMS.copy()
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
resp = session.request("POST", ORG_QUERY_URL, params=params, timeout=30)
|
||||
if not resp or resp.status_code != 200:
|
||||
raise RuntimeError(f"组织维护接口状态码异常: {getattr(resp, 'status_code', '无响应')}")
|
||||
if _is_expired(resp.text):
|
||||
raise LoginRequiredError("HR 登录态已失效,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _fetch_org_page(session, page_no, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页组织维护数据(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _fetch_org_page_once(session, page_no, page_size)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("组织维护第%d页请求第 %d 次失败:%s,%.1f 秒后重试", page_no, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("组织维护第%d页连续 %d 次请求失败,放弃", page_no, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_all_orgs(session):
|
||||
"""分页抓取全部组织维护数据(在职组织,in_use=1),返回接口原始记录列表。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
total_page = None
|
||||
while True:
|
||||
data = _fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"组织维护第{page_no}页接口返回错误:{data.get('meg') or data.get('des')}")
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("组织维护无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
|
||||
if total_page is None:
|
||||
logger.info("总记录数:%s,总页数:%s", data.get("count"), data.get("pageCount"))
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("组织维护已抓取 %d/%s 页,累计 %d/%s 条",
|
||||
page_no, total_page, len(all_rows), data.get("count"))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 字段转换 ====================
|
||||
def to_org_rows(datalist):
|
||||
"""将接口原始记录转换为页面列名顺序的字典列表(18 列,含序号)。"""
|
||||
rows = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row = {"序号": i}
|
||||
for key, name in ORG_FIELD_MAP:
|
||||
value = r.get(key)
|
||||
if name == "使用状态":
|
||||
value = IN_USE_MAP.get(str(value), value)
|
||||
elif name == "成立日期" and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_orgs(output_path=None):
|
||||
"""查询全部组织维护数据并导出 Excel(18 列,与页面列一致)。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
(导出文件路径, 数据条数)
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 请求失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
logger.info("===== 开始组织维护导出,保存路径:%s =====", output_path)
|
||||
session = _build_session()
|
||||
datalist = fetch_all_orgs(session)
|
||||
if not datalist:
|
||||
raise RuntimeError("组织维护接口未查询到任何数据")
|
||||
|
||||
rows = to_org_rows(datalist)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
pd.DataFrame(rows).to_excel(output_path, index=False)
|
||||
logger.info("===== 组织维护导出完成:共 %d 条,已保存 %s =====", len(rows), output_path)
|
||||
return output_path, len(rows)
|
||||
|
||||
|
||||
def main(output_path=None):
|
||||
"""影刀自定义指令入口「37du组织维护导出」。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(缺省用内置默认值 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "count": int}
|
||||
save_path 即导出的 Excel 文件路径。
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
try:
|
||||
save_path, count = export_orgs(output_path)
|
||||
return {"success": True, "save_path": save_path, "count": count}
|
||||
except Exception as e:
|
||||
logger.error("组织维护导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "save_path": output_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
output_path = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
main(output_path)
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
"员工基础信息": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
]),
|
||||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||||
"雇主险增减员导出模板": ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
|
||||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name, user_id=None):
|
||||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||||
|
||||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
template_name: 模板名(对应模板列表的 ext1)
|
||||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||||
|
||||
Returns:
|
||||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||||
"""
|
||||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||||
try:
|
||||
# 1. 模板列表 -> 按名称匹配拿 id
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」(可选:%s),回退内置模板",
|
||||
template_name, [t.get("ext1") for t in templates])
|
||||
return None
|
||||
|
||||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||||
|
||||
Returns:
|
||||
临时 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到临时目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态(与浏览器版输出规范一致)。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None, ttl=DEFAULT_TTL_SECONDS):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出),
|
||||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||||
不同模板导出到不同路径,不会互相复用。纯接口实现,无需浏览器。
|
||||
|
||||
Args:
|
||||
download_dir: 单状态临时文件目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||||
(默认 DEFAULT_STATUSES)
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None: # None 使用默认缓存有效期
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过接口导出
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s),临时目录:%s =====",
|
||||
template_name, statuses, leave_desc, download_dir)
|
||||
|
||||
session = _build_session()
|
||||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
# 合并所有花名册文件
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
|
||||
|
||||
def main(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template: 自定义导出模板名
|
||||
output_path / download_dir: 保存路径与临时下载目录
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||||
"""
|
||||
# 在职状态:兼容 str / list / 逗号分隔
|
||||
if isinstance(statuses, str):
|
||||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||||
elif statuses:
|
||||
statuses = [str(s) for s in statuses]
|
||||
else:
|
||||
statuses = list(DEFAULT_STATUSES)
|
||||
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
|
||||
try:
|
||||
save_path = export_roster(
|
||||
download_dir=download_dir, output_path=output_path,
|
||||
template_name=template, statuses=statuses,
|
||||
leave_start=leave_start, leave_end=leave_end)
|
||||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
statuses = ["在职"]
|
||||
leave_start = ""
|
||||
leave_end = ""
|
||||
template = "员工基础信息"
|
||||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||||
template=template, output_path=output_path)
|
||||
@@ -0,0 +1,440 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;登录态失效抛 HRSessionExpiredError。
|
||||
|
||||
按项目规范做全局重试(最大 3 次,指数退避),仅在网络/服务端异常时重试;
|
||||
登录态失效(HRSessionExpiredError)属确定性失败,直接抛出、不重试。
|
||||
"""
|
||||
last_exc = None
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt < 3:
|
||||
time.sleep(1.0 * (2 ** (attempt - 1)))
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(aa.md:getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
params = {
|
||||
"tree_code": "cq37du",
|
||||
"user_id": user_id,
|
||||
"sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"dept_org_name": "",
|
||||
"confirm_state": "",
|
||||
"person_status": "",
|
||||
"identity": "",
|
||||
"staff_status": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"post_type": "1",
|
||||
"custom_dept_ids": "",
|
||||
"custom_dept_names": "",
|
||||
"STAFF_ID": "",
|
||||
"sealOrgAlias": "",
|
||||
"seal_dept_stru_id": "",
|
||||
"kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "",
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"yearmonth": yearmonth,
|
||||
"kq_data_state": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤封存登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount") or 0
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据;
|
||||
# 仅当 pageCount 存在且已到最后页,或返回行数不足一页时才结束分页。
|
||||
if total_page and page_no >= total_page:
|
||||
break
|
||||
if len(page_list) < PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _seal_path(ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(SAVE_DIR, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
def _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
|
||||
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
|
||||
|
||||
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
|
||||
列顺序不变,保证保存的封存数据信息不丢失。
|
||||
"""
|
||||
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
|
||||
return frame.rename(columns=rename)
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get(SEAL_UNIT_FIELD)) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
path = _seal_path(ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("封存数据导出失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 自动化工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1576
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "37du-webhost-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
<template>
|
||||
<div v-if="booting" class="boot">
|
||||
<span class="boot-logo">37</span>
|
||||
<span class="boot-txt">{{ syncing ? '正在同步插件,请稍候…' : (store.appName || '自动化工作台') }}</span>
|
||||
<span class="boot-dots"><i></i><i></i><i></i></span>
|
||||
</div>
|
||||
<LoginPage v-else-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<!-- 壳子更新提示:控制面有新版本且已自动下载,点击重启升级 -->
|
||||
<div v-if="shellUpdate.downloaded" class="update-bar">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
|
||||
</div>
|
||||
<!-- 顶部:品牌 + 平台登录态 + 当前账号/登出 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>{{ wsText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-divider direction="vertical" class="vdiv" />
|
||||
|
||||
<div class="band">
|
||||
<span class="band-label">平台登录态</span>
|
||||
<el-tooltip
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
:content="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
|
||||
placement="bottom"
|
||||
:disabled="p.online && p.allowed !== false"
|
||||
>
|
||||
<el-button
|
||||
class="chip"
|
||||
:class="{ online: p.online, locked: p.allowed === false }"
|
||||
:disabled="busyLogin === p.id || p.allowed === false"
|
||||
:loading="busyLogin === p.id"
|
||||
round
|
||||
@click="login(p.id)"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<div class="spacer"></div>
|
||||
|
||||
<div class="run-state">
|
||||
<template v-if="store.running">
|
||||
<span class="run-pct">{{ store.progress }}%</span>
|
||||
<el-progress
|
||||
:percentage="store.progress"
|
||||
:show-text="false"
|
||||
:stroke-width="8"
|
||||
color="#3b6cff"
|
||||
class="run-bar"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
|
||||
<el-avatar :size="26" class="acct-avatar" :src="store.avatarUrl" :key="store.avatarUrl" @error="onAvatarError">
|
||||
<span class="acct-avatar-fb">{{ (store.nickname || store.current).slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
|
||||
</button>
|
||||
<el-button
|
||||
v-if="store.isAdmin"
|
||||
v-show="store.controlplane"
|
||||
class="chip admin-chip"
|
||||
title="打开中心机控制面进行插件/账号/授权管理"
|
||||
round
|
||||
@click="openConsole"
|
||||
>
|
||||
<el-icon class="geo"><Setting /></el-icon>管理控制台
|
||||
</el-button>
|
||||
<el-button class="chip" round @click="logout">登出</el-button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 主体:左场景 | 右插件页 + 日志 -->
|
||||
<div class="body">
|
||||
<aside class="panel side">
|
||||
<div class="side-head">
|
||||
<span class="sec-title">场景</span>
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<ul class="scene-list">
|
||||
<li
|
||||
v-for="(p, i) in store.plugins"
|
||||
:key="p.id"
|
||||
:class="{ active: p.id === store.selectedId && store.view === 'plugin' }"
|
||||
@click="openPlugin(p.id)"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: PALETTE[i % PALETTE.length] }">
|
||||
{{ p.name.slice(0, 1) }}
|
||||
</span>
|
||||
<span class="scene-name">{{ p.name }}</span>
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员在控制面授权</span></div>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate } from './api'
|
||||
|
||||
function openConsole() {
|
||||
if (!store.controlplane) return
|
||||
window.open(store.controlplane, '_blank', 'noopener')
|
||||
}
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
// 顶栏头像加载失败:清除缓存返回首字符兜底
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const wsText = computed(() =>
|
||||
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
|
||||
|
||||
function openPlugin(id) {
|
||||
store.selectedId = id
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
function openWS() {
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => {
|
||||
store.wsOn = false
|
||||
// 仅登录态下自动重连刷新;未登录被拒(1008)时静默,避免 reload 死循环
|
||||
if (store.current) setTimeout(() => (location.reload()), 2500)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
await checkSession()
|
||||
booting.value = false // 会话判定完成(登录/未登录/后端不可达均已定),再渲染首屏
|
||||
loadAvatar()
|
||||
loadShellStatus()
|
||||
})
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
const booting = ref(true) // 鉴权判定中:未确定会话前先显示加载骨架,避免「闪一下登录页再进首页」
|
||||
const syncing = ref(false) // 首次启动/启动时:按账号权限自下载/更新插件(等待下载界面)
|
||||
|
||||
// ===== 壳子自动更新:控制面有新版本且已自动下载 → 提示用户点击重启升级 =====
|
||||
const shellUpdate = ref({})
|
||||
const updating = ref(false)
|
||||
async function loadShellStatus() {
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {}
|
||||
}
|
||||
async function doShellUpdate() {
|
||||
updating.value = true
|
||||
try {
|
||||
await applyShellUpdate() // 后端运行静默安装并退出进程,升级后自动重启
|
||||
} catch (e) {
|
||||
updating.value = false
|
||||
ElMessage.error('更新失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
// 平台登录等轻量操作反馈:统一走 element-plus 全局消息
|
||||
function showToast(msg, type = 'info') {
|
||||
ElMessage({ message: msg, type, duration: 2200 })
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
// 登录态一律以**后端会话 cookie** 为准(钉钉扫码/账号登录/后端重启后均从 admin/me 判定),
|
||||
// 不再以 localStorage 的 cp_account 早退——否则全新扫码流程(未写过 cp_account)回跳后无法进入插件页。
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account) {
|
||||
store.current = ''; store.isAdmin = false; store.dept = ''; store.nickname = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
return
|
||||
}
|
||||
store.current = me.account
|
||||
store.isAdmin = !!me.is_admin
|
||||
store.dept = me.dept || ''
|
||||
store.nickname = me.nickname || ''
|
||||
try { localStorage.setItem('cp_account', me.account) } catch (_) {}
|
||||
// 会话确认后:按账号权限自下载/更新插件(首次启动等待下载完成;离线/失败直接跳过)
|
||||
syncing.value = true
|
||||
try { await syncPlugins() } catch (_) {}
|
||||
syncing.value = false
|
||||
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
|
||||
await refreshMeta()
|
||||
} catch (_) { /* 后端 down:无法校验,保持现状(可能为登录页或本地态) */ }
|
||||
}
|
||||
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
if (!store.selectedId) store.selectedId = store.plugins[0]?.id || ''
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.isAdmin = !!ok.is_admin
|
||||
store.dept = ok.dept || ''
|
||||
store.nickname = ok.nickname || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
|
||||
await refreshMeta()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
// 首次登录/钉钉自动建号的默认密码:提示立即改密
|
||||
if (ok.must_change_pwd) { promptChangePwd(ok.account) }
|
||||
}
|
||||
|
||||
async function promptChangePwd(account) {
|
||||
try {
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'当前账号正使用默认密码,请立即设置新密码(至少 6 位),避免他人误登录',
|
||||
'首次登录 · 修改密码',
|
||||
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
|
||||
try {
|
||||
await adminPassword({ account, old_password: '', new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e) {
|
||||
ElMessage.warning('改密失败:' + (e.message || e))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
store.nickname = ''
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
const label = p?.label || id
|
||||
if (p?.online) {
|
||||
showToast(`${label} 已登录`, 'success')
|
||||
return
|
||||
}
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const ok = !!(r && r.online)
|
||||
if (p) p.online = ok
|
||||
log(ok ? 'INFO' : 'ERROR',
|
||||
ok ? `平台 ${label} 登录成功` : `平台 ${label} 登录未生效:${(r && r.message) || ''}`)
|
||||
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`, ok ? 'success' : 'error')
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
|
||||
showToast(`登录失败:${e.message || e}`, 'error')
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.boot {
|
||||
min-height: 100vh;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 14px; background: var(--bg);
|
||||
}
|
||||
.boot-logo {
|
||||
width: 54px; height: 54px; border-radius: 16px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 20px; font-weight: 800;
|
||||
box-shadow: 0 10px 26px -8px rgba(59,108,255,.65);
|
||||
animation: bootpop .4s ease;
|
||||
}
|
||||
.boot-txt { font-size: 13px; color: var(--text-faint); letter-spacing: .06em; }
|
||||
.boot-dots { display: flex; gap: 5px; }
|
||||
.boot-dots i {
|
||||
width: 6px; height: 6px; border-radius: 50%; background: var(--primary);
|
||||
animation: bootblink 1s infinite ease-in-out;
|
||||
}
|
||||
.boot-dots i:nth-child(2) { animation-delay: .15s; }
|
||||
.boot-dots i:nth-child(3) { animation-delay: .3s; }
|
||||
@keyframes bootpop { from { transform: scale(.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes bootblink { 0%,80%,100% { opacity: .25; } 40% { opacity: 1; transform: translateY(-2px); } }
|
||||
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 12px 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.update-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: var(--primary-weak);
|
||||
border: 1px solid rgba(59, 108, 255, .35);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: var(--text-sub);
|
||||
}
|
||||
.update-bar b { color: var(--primary); }
|
||||
.update-bar em { font-style: normal; color: var(--text-faint); margin-left: 6px; }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo {
|
||||
width: 36px; height: 36px; border-radius: 10px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 14px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(59,108,255,.6);
|
||||
}
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
|
||||
.vdiv { height: 26px; margin: 0 2px; }
|
||||
|
||||
.band { display: flex; align-items: center; gap: 8px; }
|
||||
.band-label { font-size: 12px; color: var(--text-faint); margin-right: 4px; }
|
||||
|
||||
.chip { padding: 5px 14px; border-radius: 999px; }
|
||||
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; margin-right: 6px; display: inline-block; }
|
||||
.chip.online { border-color: transparent; background: var(--ok-weak); color: #1a8f63; }
|
||||
.chip.online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(34,176,122,.18); }
|
||||
.chip.locked { border-style: dashed; opacity: .5; }
|
||||
.admin-chip { border-color: rgba(59,108,255,.45); color: var(--primary); background: var(--primary-weak-2); margin-left: 4px; }
|
||||
.admin-chip:hover { border-color: var(--primary); }
|
||||
.admin-chip .geo { margin-right: 4px; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-bar { width: 180px; flex-shrink: 0; }
|
||||
.run-pct { font-size: 12px; font-weight: 700; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
|
||||
.acct-btn {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
padding: 4px 8px; margin: -4px -8px; border-radius: 8px;
|
||||
font: inherit; transition: background .13s;
|
||||
}
|
||||
.acct-btn:hover { background: var(--surface-2); }
|
||||
.acct-avatar { flex-shrink: 0; }
|
||||
.acct-avatar-fb { font-size: 12px; font-weight: 700; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
.side { width: 232px; flex-shrink: 0; display: flex; flex-direction: column; padding: 14px 12px; }
|
||||
.side-head { display: flex; align-items: center; justify-content: space-between; padding: 0 6px 10px; }
|
||||
.count { font-size: 11px; color: var(--text-faint); background: var(--surface-2); border: 1px solid var(--border); border-radius: 999px; padding: 1px 8px; }
|
||||
.scene-list { list-style: none; margin: 0; padding: 0; flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.scene-list li {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
position: relative;
|
||||
transition: background .13s, transform .13s ease;
|
||||
}
|
||||
.scene-list li:hover { background: var(--surface-2); transform: translateX(2px); }
|
||||
.scene-list li.active { background: var(--primary-weak); }
|
||||
.scene-list li.active::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 3px; background: var(--primary);
|
||||
}
|
||||
.scene-list li.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #fff; font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.scene-empty {
|
||||
flex: 1; display: grid; place-items: center; text-align: center;
|
||||
font-size: 12.5px; color: var(--text-sub); line-height: 1.9; padding: 20px 12px;
|
||||
}
|
||||
.scene-empty span { font-size: 11px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||||
|
||||
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
|
||||
</style>
|
||||
@@ -0,0 +1,74 @@
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function syncPlugins() {
|
||||
return j('/api/plugins/sync', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
// v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL
|
||||
export async function authDingtalk() {
|
||||
return j('/api/auth/dingtalk')
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<template>
|
||||
<div class="panel log-wrap">
|
||||
<div class="log-head">
|
||||
<div class="log-title">
|
||||
<i class="status" :class="store.wsOn ? 'on' : 'off'" :title="store.wsOn ? '实时连接正常' : '连接已中断'"></i>
|
||||
<span>运行日志</span>
|
||||
<span v-if="store.running" class="live">● LIVE</span>
|
||||
<span v-else-if="store.logs.length" class="count">{{ visibleLogs.length }} 条</span>
|
||||
</div>
|
||||
|
||||
<div class="log-tools">
|
||||
<el-radio-group v-model="level" size="small">
|
||||
<el-radio-button v-for="l in LEVELS" :key="l" :value="l">{{ l }}</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-button size="small" :icon="CopyDocument" circle title="复制日志" :disabled="!visibleLogs.length"
|
||||
@click="copy" />
|
||||
<el-button size="small" :icon="pause ? VideoPlay : VideoPause" circle :title="pause ? '继续滚动' : '暂停滚动'"
|
||||
@click="pause = !pause" />
|
||||
<el-button size="small" plain :disabled="!store.logs.length" @click="confirmClear">清空</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div ref="box" class="log-box">
|
||||
<div v-if="!visibleLogs.length" class="log-empty">
|
||||
<template v-if="store.logs.length">当前级别无日志</template>
|
||||
<template v-else>暂无日志,点击「一键执行」开始</template>
|
||||
</div>
|
||||
<div v-for="(l, i) in visibleLogs" :key="i" class="log-line">
|
||||
<span class="t">{{ l.time }}</span>
|
||||
<span class="lv" :class="'s-' + (l.level || 'INFO')">[{{ l.level || 'INFO' }}]</span>
|
||||
<span>{{ l.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { nextTick, ref, watch, computed } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { CopyDocument, VideoPause, VideoPlay } from '@element-plus/icons-vue'
|
||||
import { store, clearLogs } from '../store'
|
||||
|
||||
const LEVELS = ['全部', 'INFO', 'WARN', 'ERROR']
|
||||
const level = ref('全部')
|
||||
const pause = ref(false)
|
||||
const box = ref(null)
|
||||
|
||||
const visibleLogs = computed(() => {
|
||||
if (level.value === '全部') return store.logs
|
||||
return store.logs.filter((l) => l.level === level.value)
|
||||
})
|
||||
|
||||
// 日志变化或过滤切换时,若未暂停则自动滚到最新
|
||||
watch(
|
||||
[() => store.logs.length, level],
|
||||
async () => {
|
||||
if (pause.value) return
|
||||
await nextTick()
|
||||
if (box.value) box.value.scrollTop = box.value.scrollHeight
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function confirmClear() {
|
||||
ElMessageBox.confirm('确认清空全部运行日志?', '清空日志', {
|
||||
confirmButtonText: '清空',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
.then(() => { clearLogs(); ElMessage.success('日志已清空') })
|
||||
.catch(() => { })
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
const text = visibleLogs.value.map((l) => `[${l.time}] [${l.level || 'INFO'}] ${l.msg}`).join('\n')
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
ElMessage.success(`已复制 ${visibleLogs.value.length} 条日志`)
|
||||
} catch (_) {
|
||||
ElMessage.error('复制失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.log-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 216px;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.log-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px 8px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.log-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.log-tools .el-button+.el-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status.on {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 3px var(--ok-weak);
|
||||
}
|
||||
|
||||
.status.off {
|
||||
background: #c6ccdc;
|
||||
}
|
||||
|
||||
.live {
|
||||
color: var(--ok);
|
||||
font-size: 10px;
|
||||
animation: blink 1s infinite;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
.count {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% {
|
||||
opacity: .2;
|
||||
}
|
||||
}
|
||||
|
||||
.log-empty {
|
||||
color: var(--text-faint);
|
||||
padding: 14px;
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,743 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<!-- 巨大 37:节点阵列 -->
|
||||
<div class="ghost" aria-hidden="true">37</div>
|
||||
|
||||
<!-- 基线管道:流程节点 -->
|
||||
<div class="pipeline" aria-hidden="true">
|
||||
<i></i><i></i><i></i>
|
||||
</div>
|
||||
|
||||
<!-- 顶部:品牌 + 系统状态 -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="mark">37</span>
|
||||
<span class="name">{{ appName || '37du 自动化工作台' }}</span>
|
||||
</div>
|
||||
<div class="sys">
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
<span>引擎运行中</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 中央:接入终端 -->
|
||||
<main class="panel">
|
||||
<span class="core-mark">37 CORE · AUTOMATION</span>
|
||||
<h1>自动化工作台</h1>
|
||||
<p class="sub">使用统一账号或钉钉扫码,进入你的流程中心</p>
|
||||
|
||||
<el-form label-position="top" class="form" @submit.prevent="doLogin">
|
||||
<el-form-item label="员工账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" autocomplete="username" size="large" clearable
|
||||
@keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="password" type="password" placeholder="请输入密码" autocomplete="current-password" size="large"
|
||||
show-password @keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" size="large" class="primary" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '进 入 中 …' : '进 入 工 作 台' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="divider"><span>或</span></div>
|
||||
|
||||
<el-button size="large" class="dingtalk" :loading="dingBusy" :icon="ChatDotRound" @click="openDing">
|
||||
钉钉扫码接入
|
||||
</el-button>
|
||||
</main>
|
||||
|
||||
<!-- 底部:流程状态 -->
|
||||
<footer class="footbar">
|
||||
<div class="flows">
|
||||
<span>接入终端就绪</span>
|
||||
<span class="f-blocks" aria-hidden="true">
|
||||
<i></i><i></i><i></i><i></i><i></i>
|
||||
</span>
|
||||
</div>
|
||||
<span class="copyright">© 37du 自动化工作台</span>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ChatDotRound } from '@element-plus/icons-vue'
|
||||
import { adminLogin, adminPassword, authDingtalk } from '../api'
|
||||
|
||||
defineProps({ appName: { type: String, default: '' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const dingBusy = ref(false)
|
||||
|
||||
async function doLogin() {
|
||||
if (busy.value) return
|
||||
if (!account.value.trim() || !password.value) { ElMessage.warning('请输入账号和密码'); return }
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
ElMessage.success('登录成功')
|
||||
emit('ok', {
|
||||
account: account.value.trim(),
|
||||
is_admin: !!r.is_admin,
|
||||
dept: r.dept || '',
|
||||
must_change_pwd: !!r.must_change_pwd
|
||||
})
|
||||
} catch (e) {
|
||||
ElMessage.error('登录失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 钉钉扫码登录:壳后端直接生成授权 URL,当前窗口跳转钉钉;扫码后浏览器自动跳回 /auth/done
|
||||
async function openDing() {
|
||||
if (dingBusy.value) return
|
||||
dingBusy.value = true
|
||||
try {
|
||||
const r = await authDingtalk()
|
||||
if (r && r.url) {
|
||||
window.location.href = r.url
|
||||
return
|
||||
}
|
||||
ElMessage.error('钉钉登录未配置,请联系管理员')
|
||||
} catch (e) {
|
||||
ElMessage.error('钉钉登录不可用:' + (e.message || e))
|
||||
}
|
||||
dingBusy.value = false
|
||||
}
|
||||
|
||||
async function promptChangePwd(acc, r) {
|
||||
try {
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'当前为系统默认密码,请立即设置新密码(至少 6 位)',
|
||||
'首次登录 · 修改密码',
|
||||
{
|
||||
inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说'
|
||||
})
|
||||
try {
|
||||
await adminPassword({ account: acc, old_password: '', new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e2) {
|
||||
ElMessage.warning('改密失败:' + (e2.message || e2))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
emit('ok', { account: acc, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ============================================================
|
||||
暖米画布 + 工程网格 + 点阵 37 + 接入终端
|
||||
- 精密感来自网格与节点,不来自阴影
|
||||
- 体温红只出现在:port 聚焦、主按钮、管线节点、状态点
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 画布 ---------- */
|
||||
.login {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 110px 24px 170px;
|
||||
overflow: hidden;
|
||||
background: #EDE7DB;
|
||||
color: #1C1712;
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
/* 工程网格:边缘径向淡出 */
|
||||
.login::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(28, 23, 18, .045) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(28, 23, 18, .045) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
-webkit-mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 顶部暖辉光 */
|
||||
.login::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background: radial-gradient(660px 480px at 50% 38%, rgba(209, 74, 43, .06), transparent 68%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 巨大 37:节点阵列 ---------- */
|
||||
.ghost {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: -0.12em;
|
||||
transform: translateX(-50%);
|
||||
font-family: 'Helvetica Neue', 'Arial Narrow', Arial, sans-serif;
|
||||
font-size: clamp(280px, 74vw, 640px);
|
||||
font-weight: 800;
|
||||
line-height: .72;
|
||||
letter-spacing: -.08em;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
color: rgba(28, 23, 18, .05);
|
||||
/* 兜底 */
|
||||
animation: breathe 7s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .8;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@supports ((-webkit-background-clip: text) or (background-clip: text)) {
|
||||
.ghost {
|
||||
color: transparent;
|
||||
background-image: radial-gradient(circle at 1px 1px,
|
||||
rgba(28, 23, 18, .16) 1px, transparent 1.9px);
|
||||
background-size: 9px 9px;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 基线管道 ---------- */
|
||||
.pipeline {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 0;
|
||||
transform: translateX(-50%);
|
||||
width: min(920px, 92vw);
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg,
|
||||
transparent, rgba(28, 23, 18, .14) 18%,
|
||||
rgba(28, 23, 18, .14) 82%, transparent);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pipeline i {
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .10);
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(1) {
|
||||
left: 22%;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(2) {
|
||||
left: 50%;
|
||||
animation: blip 3.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(3) {
|
||||
left: 78%;
|
||||
}
|
||||
|
||||
@keyframes blip {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .35;
|
||||
transform: scale(.85);
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 顶部栏 ---------- */
|
||||
.topbar {
|
||||
position: absolute;
|
||||
top: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mark {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #F7F2E8;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .01em;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .04em;
|
||||
color: #6B6155;
|
||||
}
|
||||
|
||||
.sys {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
animation: pulse 2.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, .4);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px rgba(209, 74, 43, 0);
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.sep {
|
||||
color: #C4BBA8;
|
||||
}
|
||||
|
||||
/* ---------- 中央:接入终端 ---------- */
|
||||
.panel {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
padding: 40px 36px 36px;
|
||||
background: #F8F4EC;
|
||||
border: 1px solid #DDD4C2;
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
0 1px 0 rgba(255, 255, 255, .9) inset,
|
||||
0 24px 48px -28px rgba(28, 23, 18, .30);
|
||||
animation: rise .45s cubic-bezier(.22, 1, .36, 1) both;
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* 卡片内元素依次点亮:终端端口逐个上电 */
|
||||
@keyframes seq {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
animation: seq .5s .05s both;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
animation: seq .5s .10s both;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
animation: seq .5s .15s both;
|
||||
}
|
||||
|
||||
.form {
|
||||
animation: seq .55s .20s both;
|
||||
}
|
||||
|
||||
.divider {
|
||||
animation: seq .5s .26s both;
|
||||
}
|
||||
|
||||
.dingtalk {
|
||||
animation: seq .5s .32s both;
|
||||
}
|
||||
|
||||
/* 底部金手指纹理 */
|
||||
.panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 36px;
|
||||
right: 36px;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background-image: repeating-linear-gradient(to right,
|
||||
rgba(201, 191, 171, .65) 0 8px,
|
||||
transparent 8px 12px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
display: block;
|
||||
margin-bottom: 20px;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .18em;
|
||||
color: #D14A2B;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
letter-spacing: -.01em;
|
||||
color: #1C1712;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
margin: 0 0 34px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 表单:接口式输入 ---------- */
|
||||
.form :deep(.el-form-item) {
|
||||
position: relative;
|
||||
padding-left: 16px;
|
||||
margin-bottom: 26px;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__content) {
|
||||
position: relative;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
/* 左侧接口指示灯 */
|
||||
.form :deep(.el-form-item__content)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -16px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: #C9BFAB;
|
||||
transition: background .2s, box-shadow .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item:focus-within .el-form-item__content)::before {
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .12);
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
line-height: 1.4;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* 底线式输入 */
|
||||
.form :deep(.el-input__wrapper) {
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
box-shadow: none !important;
|
||||
border-bottom: 1px solid #D8D0BC;
|
||||
transition: border-color .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper:hover) {
|
||||
border-bottom-color: #BCB29A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper.is-focus) {
|
||||
border-bottom-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner) {
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
color: #1C1712;
|
||||
caret-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner::placeholder) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix),
|
||||
.form :deep(.el-input__prefix),
|
||||
.form :deep(.el-input__suffix-inner) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix-inner .el-input__icon:hover) {
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 主按钮 ---------- */
|
||||
.primary.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
margin-top: 6px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #FFF8F2;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .12em;
|
||||
box-shadow: 0 12px 28px -14px rgba(209, 74, 43, .7);
|
||||
transition: background-color .15s, opacity .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.primary.el-button:hover,
|
||||
.primary.el-button:focus {
|
||||
background: #BB3F21;
|
||||
color: #FFF8F2;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 15px 30px -14px rgba(209, 74, 43, .78);
|
||||
}
|
||||
|
||||
.primary.el-button:active {
|
||||
background: #A53517;
|
||||
transform: translateY(1px) scale(.99);
|
||||
box-shadow: 0 6px 16px -12px rgba(209, 74, 43, .8);
|
||||
}
|
||||
|
||||
.primary.el-button.is-disabled,
|
||||
.primary.el-button.is-loading {
|
||||
background: #D14A2B;
|
||||
opacity: .55;
|
||||
}
|
||||
|
||||
/* ---------- 分隔线 ---------- */
|
||||
.divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin: 28px 0 16px;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: .04em;
|
||||
color: #8D8476;
|
||||
}
|
||||
|
||||
.divider::before,
|
||||
.divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: #E0D9C6;
|
||||
}
|
||||
|
||||
/* ---------- 钉钉按钮 ---------- */
|
||||
.dingtalk.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #DED6C2;
|
||||
background: #FDFBF6;
|
||||
color: #1C1712;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
transition: border-color .15s, background-color .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.dingtalk.el-button:hover,
|
||||
.dingtalk.el-button:focus {
|
||||
border-color: #C4BBA8;
|
||||
background: #FFFFFF;
|
||||
color: #1C1712;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 8px 20px -14px rgba(28, 23, 18, .28);
|
||||
}
|
||||
|
||||
.dingtalk.el-button:active {
|
||||
transform: translateY(0) scale(.99);
|
||||
}
|
||||
|
||||
.dingtalk.el-button :deep(.el-icon) {
|
||||
color: #1491F0;
|
||||
}
|
||||
|
||||
/* ---------- 键盘可达 ---------- */
|
||||
.primary.el-button:focus-visible,
|
||||
.dingtalk.el-button:focus-visible {
|
||||
outline: 2px solid #D14A2B;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
/* ---------- 底部:流程状态 ---------- */
|
||||
.footbar {
|
||||
position: absolute;
|
||||
bottom: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.flows {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.f-blocks {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.f-blocks i {
|
||||
width: 12px;
|
||||
height: 4px;
|
||||
border-radius: 1px;
|
||||
background: #C9BEAA;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .1em;
|
||||
color: #9A8F7C;
|
||||
}
|
||||
|
||||
/* ---------- 自适应 ---------- */
|
||||
@media (max-width: 720px) {
|
||||
.login {
|
||||
padding: 96px 20px 140px;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
top: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
bottom: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
padding: 32px 24px 30px;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
font-size: 23px;
|
||||
}
|
||||
|
||||
.panel::after {
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 680px) {
|
||||
.login {
|
||||
align-items: flex-start;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 80px 24px 120px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
.dot,
|
||||
.pipeline i,
|
||||
.ghost {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.panel {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.core-mark,
|
||||
.panel h1,
|
||||
.panel .sub,
|
||||
.form,
|
||||
.divider,
|
||||
.dingtalk {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
* {
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,279 @@
|
||||
<template>
|
||||
<div v-if="plugin" class="plugin-page">
|
||||
<!-- 页头 -->
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
|
||||
<div class="ident-meta">
|
||||
<h2>{{ plugin.name }} <span class="ver-tag">v{{ plugin.version }}</span></h2>
|
||||
<p>{{ plugin.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="plugin?.uses_month" class="month">
|
||||
<span class="field-label">执行月份</span>
|
||||
<el-select v-model="month" class="month-sel" :disabled="store.running">
|
||||
<el-option v-for="m in months" :key="m" :value="m" :label="m" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果横幅 -->
|
||||
<el-alert v-if="store.lastResult" :type="store.lastResult.ok ? 'success' : 'error'" :closable="true"
|
||||
:close-text="null" class="banner" @close="closeBanner" show-icon>
|
||||
<template #title>
|
||||
<span>
|
||||
{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败:' + store.lastResult.error }}
|
||||
</span>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 参数 -->
|
||||
<div class="sec-head">
|
||||
<span class="sec-title">参数配置</span>
|
||||
<el-button v-if="Object.keys(form).length" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
</div>
|
||||
<el-form label-width="auto" class="form-card">
|
||||
<div class="fields">
|
||||
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
|
||||
<template v-if="f.type === 'int'">
|
||||
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
|
||||
</template>
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form[f.key]" :placeholder="String(f.default ?? '')"
|
||||
:disabled="store.running">
|
||||
<template v-if="f.help" #suffix>
|
||||
<el-tooltip :content="f.help" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select v-else v-model="form[f.key]" :disabled="store.running">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span v-if="store.running" class="run-ind">
|
||||
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
|
||||
</span>
|
||||
<el-button type="primary" size="large" :loading="store.running" @click="run">
|
||||
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
<p class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
</div>
|
||||
|
||||
<el-empty v-else-if="!store.plugins.length" description="当前账号暂无可用场景" />
|
||||
<el-empty v-else description="未选择场景" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { QuestionFilled, RefreshLeft } from '@element-plus/icons-vue'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
const now = new Date()
|
||||
const list = []
|
||||
for (let off = 1; off <= 6; off++) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - off, 1)
|
||||
list.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
|
||||
}
|
||||
return list
|
||||
})
|
||||
const month = ref(months.value[0])
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
const idx = computed(() => Math.max(0, store.plugins.findIndex((p) => p.id === store.selectedId)))
|
||||
const avatarBg = computed(() => PALETTE[idx.value % PALETTE.length])
|
||||
|
||||
const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null)
|
||||
|
||||
const form = ref({})
|
||||
|
||||
function buildFormDefaults(p) {
|
||||
const f = {}
|
||||
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
|
||||
return f
|
||||
}
|
||||
|
||||
watch(
|
||||
() => plugin.value?.id,
|
||||
(id) => {
|
||||
form.value = buildFormDefaults(store.plugins.find((x) => x.id === id))
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function resetForm() {
|
||||
form.value = buildFormDefaults(plugin.value)
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
if (plugin.value.platform && !(store.platforms.find((p) => p.id === plugin.value.platform)?.online)) {
|
||||
log('WARN', `插件「${plugin.value.name}」需要先登录平台「${store.platforms.find((p) => p.id === plugin.value.platform)?.label || plugin.value.platform}」才能正确执行`)
|
||||
}
|
||||
store.running = true
|
||||
store.progress = 0
|
||||
store.currentRun = ''
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
try {
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
} catch (e) {
|
||||
store.running = false
|
||||
store.lastResult = { ok: false, error: e.message || String(e) }
|
||||
log('ERROR', `启动执行失败:${e.message || e}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
watch(
|
||||
() => store.lastResult,
|
||||
async (res) => {
|
||||
if (res && res.ok && store.lastRunId) {
|
||||
try {
|
||||
const run = await getRun(store.lastRunId)
|
||||
store.lastSummary = run.result?.summary || ''
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function closeBanner() {
|
||||
store.lastResult = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.plugin-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ident {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 13px;
|
||||
flex-shrink: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.ident-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ident-meta h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ident-meta p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.ver-tag {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--text-faint);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.month {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.month-sel {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-card .el-form-item {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.help-ic {
|
||||
color: var(--text-faint);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 14px;
|
||||
border-top: 1px dashed var(--border);
|
||||
padding-top: 14px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.run-ind {
|
||||
flex: 1;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
margin: 0;
|
||||
padding-left: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,309 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="350px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<el-avatar :size="60" :src="store.avatarUrl" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
<em v-if="store.isAdmin" class="admin">管理员</em>
|
||||
</div>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>已授权插件</span>
|
||||
<span class="mono">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>平台在线</span>
|
||||
<span class="mono">{{ store.platforms.filter(p => p.online).length }}/{{ store.platforms.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 平台登录态 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<span>平台登录态</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-for="(p, i) in store.platforms" :key="p.id" class="prow">
|
||||
<span class="ridx mono">P0{{ i + 1 }}</span>
|
||||
<span class="dot" :class="{ on: p.online }"></span>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<el-button size="small" :disabled="busy === p.id || p.online" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : p.online ? '正常' : '重新登录' }}
|
||||
</el-button>
|
||||
<el-button v-if="p.online" size="small" plain type="danger" :disabled="busy === p.id" @click="logout(p.id)">登出</el-button>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<!-- 我的插件 -->
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Box /></el-icon>
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-if="!store.plugins.length" description="当前账号暂无可用插件" />
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
<span class="iname">{{ p.name }}</span>
|
||||
<span class="mono iver">v{{ p.version }}</span>
|
||||
<span class="i-dot"></span>
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
|
||||
<!-- 修改密码 -->
|
||||
<el-card class="pwd-card" shadow="never" title="修改密码">
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" style="width: 100%">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先真实姓名(钉钉登录带入),无姓名时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins'])
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
ElMessage.success(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
ElMessage.success(`平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
ElMessage.error(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
ElMessage.success(`平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const formRef = ref()
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v && v === form.oldPwd
|
||||
? cb(new Error('新密码不能与原密码相同')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v !== form.newPwd
|
||||
? cb(new Error('两次输入的密码不一致')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
}
|
||||
const pwdBusy = ref(false)
|
||||
async function changePwd() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: form.oldPwd,
|
||||
new_password: form.newPwd,
|
||||
})
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mono { font-family: var(--font-mono); letter-spacing: .04em; }
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 18px;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 28px -18px rgba(23, 24, 26, .35);
|
||||
}
|
||||
.cover {
|
||||
height: 66px;
|
||||
background:
|
||||
radial-gradient(360px 200px at 90% -30%, rgba(208, 74, 36, .5), transparent 60%),
|
||||
radial-gradient(300px 180px at -10% 120%, rgba(120, 128, 140, .4), transparent 60%),
|
||||
#1a1c1f;
|
||||
position: relative;
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 16px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 6px 16px -6px rgba(23, 24, 26, .45);
|
||||
background: #17181a;
|
||||
color: #f6f4ec;
|
||||
font-weight: 700;
|
||||
flex: none;
|
||||
}
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong { font-size: 16px; letter-spacing: .01em; color: #17181a; }
|
||||
.admin {
|
||||
font-style: normal; font-size: 10.5px; font-weight: 600;
|
||||
color: #d04a24;
|
||||
border: 1px solid rgba(208, 74, 36, .35);
|
||||
background: rgba(208, 74, 36, .07);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
.dept { font-size: 12px; color: var(--text-faint); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 11px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: #17181a; font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: #d04a24; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.prow:last-child { border-bottom: none; }
|
||||
.ridx { flex: none; width: 26px; font-size: 11px; color: var(--text-faint); }
|
||||
.dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: #c6ccdc;
|
||||
}
|
||||
.dot.on { background: #22b07a; box-shadow: 0 0 0 3px rgba(34, 176, 122, .16); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.prow :deep(.el-button--primary) { border-color: transparent; }
|
||||
.prow :deep(.el-button--danger.is-plain) { border-color: rgba(214, 69, 69, .35); color: #d64545; }
|
||||
|
||||
/* ---------- 我的插件:台账式列表 ---------- */
|
||||
.ilist { display: flex; flex-direction: column; }
|
||||
.irow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: #d04a24; }
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-card { margin-top: 16px; border-radius: 14px; border-color: var(--border); }
|
||||
.pwd-card :deep(.el-card__header) {
|
||||
font-size: 13px; font-weight: 600;
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.pwd-card :deep(.el-card__body) { padding: 16px; }
|
||||
.pwd-card :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-card :deep(.el-button--primary) { width: 100%; border-color: transparent; background: #17181a; }
|
||||
.pwd-card :deep(.el-button--primary:hover) { background: #26282c; }
|
||||
</style>
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import 'element-plus/dist/index.css'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
const app = createApp(App)
|
||||
// 全量注册图标,模板中可直接 <component :is="XxxIcon"> 使用
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,93 @@
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '',
|
||||
controlplane: '', // 控制面地址(管理员跳转用),来自 /api/meta
|
||||
platforms: [],
|
||||
plugins: [],
|
||||
selectedId: '',
|
||||
logs: [], // {time, level, msg}
|
||||
progress: 0,
|
||||
running: false,
|
||||
currentRun: '', // 当前接收日志/进度的 run_id
|
||||
lastRunId: '', // 最近一次执行的 run_id
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
dept: '',
|
||||
nickname: '', // 真实姓名(中心机 accounts.nickname,钉钉登录时自动带入)
|
||||
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
// 缓存按账号隔离(cp_avatar_url_<账号>),切换账号不会串用上一个人的头像
|
||||
const AVATAR_API = 'https://v2.xxapi.cn/api/head'
|
||||
|
||||
function avatarCacheKey() {
|
||||
return `cp_avatar_url_${store.current || 'anon'}`
|
||||
}
|
||||
|
||||
export function loadAvatar() {
|
||||
const key = avatarCacheKey()
|
||||
try {
|
||||
const cached = localStorage.getItem(key)
|
||||
if (cached) { store.avatarUrl = cached; return }
|
||||
} catch (_) {}
|
||||
store.avatarUrl = ''
|
||||
fetch(AVATAR_API, { signal: AbortSignal.timeout(4000) })
|
||||
.then((r) => r.json())
|
||||
.then((j) => {
|
||||
if (j && j.code === 200 && j.data) {
|
||||
store.avatarUrl = j.data
|
||||
try { localStorage.setItem(avatarCacheKey(), j.data) } catch (_) {}
|
||||
}
|
||||
})
|
||||
.catch(() => { /* 网络不可达/超时:保持首字符色块兜底 */ })
|
||||
}
|
||||
|
||||
export function clearAvatarCache() {
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem(avatarCacheKey()) } catch (_) {}
|
||||
loadAvatar()
|
||||
}
|
||||
|
||||
export function clearLogs() {
|
||||
store.logs = []
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
}
|
||||
|
||||
export function log(level, msg) {
|
||||
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
store.logs.push({ time, level, msg })
|
||||
if (store.logs.length > 500) store.logs.splice(0, store.logs.length - 500)
|
||||
}
|
||||
|
||||
export function handleEvent(ev) {
|
||||
switch (ev.t) {
|
||||
case 'run_start':
|
||||
store.currentRun = ev.run_id
|
||||
if (!store.running) { clearLogs() }
|
||||
break
|
||||
case 'log':
|
||||
if (ev.run_id === store.currentRun || !store.currentRun) {
|
||||
log(ev.level || 'INFO', ev.msg)
|
||||
}
|
||||
break
|
||||
case 'progress':
|
||||
if (ev.run_id === store.currentRun) store.progress = ev.pct
|
||||
break
|
||||
case 'run_done':
|
||||
store.running = false
|
||||
store.progress = 100
|
||||
store.lastResult = { ok: ev.ok, error: ev.error || '' }
|
||||
if (ev.ok) log('INFO', '===== 执行完成 =====')
|
||||
else log('ERROR', `执行失败:${ev.error}`)
|
||||
store.currentRun = ''
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
|
||||
/* element-plus 主题与品牌蓝统一 */
|
||||
--el-color-primary: #3b6cff;
|
||||
--el-color-primary-light-3: #6f8dff;
|
||||
--el-color-primary-light-5: #a3b7ff;
|
||||
--el-color-primary-light-7: #d0dcff;
|
||||
--el-color-primary-light-8: #e2e9ff;
|
||||
--el-color-primary-light-9: #eef2ff;
|
||||
--el-color-primary-dark-2: #2f56d6;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-border-radius-small: 6px;
|
||||
--el-border-radius-round: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// dev 时把 /api 与 /ws 代理到 FastAPI 后端,实现前后端分离开发
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
FROZEN = getattr(sys, "frozen", False)
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn", "37du-host")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _wait_ready(proc: subprocess.Popen | None) -> None:
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return
|
||||
if proc is not None and proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _start_server():
|
||||
"""拉起 uvicorn 服务:源码运行=子进程;打包运行=进程内后台线程。"""
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
if FROZEN:
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
def _serve() -> None:
|
||||
try:
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")
|
||||
except BaseException:
|
||||
import traceback
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
|
||||
t = threading.Thread(target=_serve, daemon=True, name="uvicorn")
|
||||
t.start()
|
||||
_wait_ready(None)
|
||||
return t
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
_wait_ready(proc)
|
||||
return proc
|
||||
|
||||
|
||||
def _apply_win11_corners(window) -> None:
|
||||
"""Win11 窗口圆角:去掉老式方角观感(DWM 设置圆角偏好,失败静默忽略)。"""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||
DWMWCP_ROUND = 2
|
||||
|
||||
def _on_shown():
|
||||
try:
|
||||
hwnd = int(window.native.Handle)
|
||||
ctypes.windll.dwmapi.DwmSetWindowAttribute(
|
||||
ctypes.c_int(hwnd),
|
||||
ctypes.c_int(DWMWA_WINDOW_CORNER_PREFERENCE),
|
||||
ctypes.byref(ctypes.c_int(DWMWCP_ROUND)),
|
||||
ctypes.c_int(4),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window.events.shown += _on_shown
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
window = webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
_apply_win11_corners(window)
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(server) -> None:
|
||||
if isinstance(server, threading.Thread):
|
||||
# 打包运行:uvicorn 为进程内线程,进程退出即随之结束,无需也无法 terminate
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
server.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("37du.Host")
|
||||
except Exception:
|
||||
pass
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
def _fatal_log(msg: str) -> None:
|
||||
"""窗口模式无控制台:崩溃现场落盘到 exe 同级 crash.log,便于诊断。"""
|
||||
try:
|
||||
(HERE / "crash.log").write_text(msg, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
import traceback
|
||||
if FROZEN:
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
@@ -0,0 +1,49 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + plugins/
|
||||
; 不含: 37du-host-console.exe(调试版)、.env(机器特定配置,缺失时使用默认值)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.0.0"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
AppId={{8F3D5C7A-2B41-4E9A-9D6C-37DUE5A1B0F0}
|
||||
AppName={#MyAppName}
|
||||
AppVersion={#MyAppVersion}
|
||||
AppPublisher=37du
|
||||
DefaultDirName={localappdata}\Programs\37duHost
|
||||
PrivilegesRequired=lowest
|
||||
OutputDir=..\installer
|
||||
OutputBaseFilename=setup-37du-host-{#MyAppVersion}
|
||||
Compression=lzma2
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
UninstallDisplayName={#MyAppName}
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; 主程序 onedir 目录(exe + _internal 依赖)
|
||||
Source: "..\dist-exe\37du-host\*"; DestDir: "{app}"; Flags: recursesubdirs ignoreversion
|
||||
; 插件执行壳(onefile 单文件,需与主程序 exe 同级)
|
||||
Source: "..\dist-exe\37du-host-runner.exe"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 壳子版本标记:执行端据此比对控制面版本判断是否需要自动升级
|
||||
Source: "..\tools\shell.version"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 插件不由安装包分发:执行机首次启动/登录后按账号权限从控制面自下载(见 backend/core/plugin_sync.py)
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"
|
||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
; 交互安装:向导结束自动启动;静默升级(/VERYSILENT)后也自动启动新版本,实现"重启自动更新"
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "立即启动 {#MyAppName}"; Flags: nowait postinstall
|
||||
|
||||
[UninstallDelete]
|
||||
; 卸载时清理整个安装目录(含运行期生成的 .webhost.pid / _cp_sessions.json 等)
|
||||
Type: filesandordirs; Name: "{app}"
|
||||
@@ -0,0 +1 @@
|
||||
1.0.0
|
||||
Reference in New Issue
Block a user