feat(controlplane): 完成多页面管理台重构与平台权限控制
1. 重构控制面前端为多页面路由架构,拆分出概览/插件/账号/权限管理页面 2. 引入Element Plus组件库优化UI样式与交互 3. 新增平台登录权限校验,支持按账号授权HR/OA平台访问 4. 新增平台登出接口与个人中心功能 5. 完善账号管理、插件授权相关API与UI交互 6. 新增防火墙、启停、自启动脚本与部署文档
This commit is contained in:
@@ -68,6 +68,19 @@ def login(pid: str) -> dict:
|
||||
"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 数据模块)。
|
||||
|
||||
|
||||
+149
-55
@@ -16,6 +16,7 @@ import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
@@ -27,6 +28,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import winjob as _winjob
|
||||
from webhost.backend.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
|
||||
|
||||
@@ -63,17 +65,26 @@ CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> account;登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
_SESS: dict[str, str] = {}
|
||||
_SESS_TTL = 24 * 3600 # 会话空闲有效期 24h(惰性过期,防长期运行无限累积)
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _sess_account(request: Request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
return _SESS.get(token, "")
|
||||
item = _SESS.get(token)
|
||||
if not item:
|
||||
return ""
|
||||
account, ts = item
|
||||
if time.time() - ts > _SESS_TTL:
|
||||
_SESS.pop(token, None)
|
||||
return ""
|
||||
_SESS[token] = (account, time.time()) # 滑动续期
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
@@ -88,11 +99,34 @@ def _require_login(request: Request) -> str:
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, result, error}
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
# 平台命名空间并发闸:同平台(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)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
@@ -153,7 +187,9 @@ def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
load_plugins(_resolve_allowed())
|
||||
global ALLOWED
|
||||
ALLOWED = _resolve_allowed()
|
||||
load_plugins(ALLOWED)
|
||||
yield
|
||||
|
||||
|
||||
@@ -193,7 +229,7 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = b.account.strip()
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
@@ -233,22 +269,59 @@ def _plugin_schema(p) -> dict:
|
||||
"fields": p.fields}
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{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
|
||||
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta() -> dict:
|
||||
plugins = [_plugin_schema(p) for p in PLUGINS]
|
||||
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据)
|
||||
plugins = [_plugin_schema(p) for p in PLUGINS] if account else []
|
||||
allowed = _account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed) if allowed is not None else True}
|
||||
for pid, m in PLATFORMS.items()]
|
||||
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.login(pid)
|
||||
return platform_auth.logout(pid)
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
@@ -260,6 +333,28 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(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()
|
||||
_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")
|
||||
@@ -270,22 +365,6 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-u", str(runner), "--plugin", plugin.id,
|
||||
"--run", run_id],
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None,
|
||||
"error": f"拉起执行子进程失败: {e}"}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
@@ -327,35 +406,35 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
proc.kill()
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
with RUN_LOCK:
|
||||
RUNS[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)已强制终止"
|
||||
with RUN_LOCK:
|
||||
RUNS[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})且未返回结果"
|
||||
with RUN_LOCK:
|
||||
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_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)已强制终止"
|
||||
_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})且未返回结果"
|
||||
_set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
@app.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
@@ -364,26 +443,41 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
with RUN_LOCK:
|
||||
if len(RUNS) >= MAX_RUNS:
|
||||
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
|
||||
RUNS[run_id] = {"status": "running", "result": None, "error": None}
|
||||
RUNS[run_id] = {"status": "running", "account": account,
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
|
||||
daemon=True, name=f"run-{plugin.id}").start()
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _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:
|
||||
_run_target(plugin, req.fields, run_id)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
_require_login(request)
|
||||
account = _require_login(request)
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run:
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ def _run() -> int:
|
||||
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 = {}
|
||||
@@ -78,7 +82,7 @@ def _run() -> int:
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins()
|
||||
load_plugins(allowed)
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
|
||||
@@ -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
|
||||
+107
-27
@@ -19,10 +19,10 @@
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
class="chip"
|
||||
:class="{ online: p.online }"
|
||||
:disabled="busyLogin === p.id"
|
||||
:class="{ online: p.online, locked: p.allowed === false }"
|
||||
:disabled="busyLogin === p.id || p.allowed === false"
|
||||
@click="login(p.id)"
|
||||
:title="p.online ? '已登录,点击刷新' : '未登录,点击登录'"
|
||||
:title="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
@@ -37,8 +37,14 @@
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
|
||||
<span class="acct-avatar">
|
||||
<img v-if="store.avatarUrl" :src="store.avatarUrl" alt="" @error="clearAvatarCache">
|
||||
<span v-else class="acct-avatar-fb">{{ store.current.slice(0, 1).toUpperCase() }}</span>
|
||||
</span>
|
||||
<span class="acct-name">{{ store.current }}</span>
|
||||
<em v-if="store.isAdmin" class="acct-tag">管理员</em>
|
||||
</button>
|
||||
<button class="chip" @click="logout">登出</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -75,6 +81,8 @@
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
|
||||
<div v-if="toast" class="toast">{{ toast }}</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
@@ -82,8 +90,9 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import { store, handleEvent, clearLogs } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout } from './api'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe } from './api'
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
@@ -95,55 +104,103 @@ function openPlugin(id) {
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins
|
||||
store.selectedId = meta.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
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; setTimeout(() => (location.reload()), 2500) }
|
||||
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.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
checkSession()
|
||||
loadAvatar()
|
||||
})
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
|
||||
// 极简顶部 toast:平台登录等轻量操作反馈
|
||||
const toast = ref('')
|
||||
let toastTimer = null
|
||||
function showToast(msg) {
|
||||
toast.value = msg
|
||||
if (toastTimer) clearTimeout(toastTimer)
|
||||
toastTimer = setTimeout(() => (toast.value = ''), 2200)
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
// 已在本地标记登录:与后端会话 cookie 是否一致(后端重启会失效,此时回登录页)
|
||||
if (!store.current) return
|
||||
try {
|
||||
const me = await fetch('/api/admin/me').then((r) => r.json())
|
||||
if (!me.account) { store.current = ''; store.isAdmin = false }
|
||||
else store.isAdmin = !!me.is_admin
|
||||
} catch (_) { /* 后端 down:暂保持本地态 */
|
||||
}
|
||||
const me = await adminMe()
|
||||
if (!me.account) { store.current = ''; store.isAdmin = false; store.dept = '' }
|
||||
else {
|
||||
store.isAdmin = !!me.is_admin
|
||||
store.dept = me.dept || ''
|
||||
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
|
||||
await refreshMeta()
|
||||
}
|
||||
} catch (_) { /* 后端 down:暂保持本地态 */ }
|
||||
}
|
||||
|
||||
function onLogin(ok) {
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
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 || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
|
||||
await refreshMeta()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
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} 已登录`)
|
||||
return
|
||||
}
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) p.online = !!r.online
|
||||
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) || '登录态未生效'}`)
|
||||
} catch (e) {
|
||||
alert('登录失败:' + (e.message || e))
|
||||
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
|
||||
showToast(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
@@ -184,12 +241,29 @@ async function login(id) {
|
||||
.chip:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.chip:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.chip:disabled:hover { border-color: var(--border-strong); color: var(--text-sub); }
|
||||
.chip.locked { border-style: dashed; opacity: .5; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-label { font-size: 12px; color: var(--primary); font-weight: 600; min-width: 38px; text-align: right; }
|
||||
|
||||
.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 {
|
||||
width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;
|
||||
position: relative; overflow: hidden;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.acct-avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
.acct-avatar-fb { line-height: 1; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
.acct-tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
border: 1px solid var(--primary-weak); background: var(--primary-weak); border-radius: 999px; padding: 1px 7px; }
|
||||
@@ -213,12 +287,18 @@ async function login(id) {
|
||||
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 li.active .scene-name { color: var(--primary); }
|
||||
.scene-list li.admin-entry { border-top: 1px dashed var(--border); margin-top: 6px; border-radius: 0; }
|
||||
.scene-list li.admin-entry.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; 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; }
|
||||
|
||||
.toast {
|
||||
position: fixed; top: 18px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(24, 39, 75, .92); color: #fff;
|
||||
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
|
||||
z-index: 60; animation: toast-in .15s ease;
|
||||
box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
|
||||
}
|
||||
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, -6px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
||||
</style>
|
||||
@@ -19,6 +19,10 @@ 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',
|
||||
@@ -44,20 +48,11 @@ export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return jj('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return jj('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
async function jj(url, opts) {
|
||||
const r = await fetch(url, opts)
|
||||
if (!r.ok) {
|
||||
let m = `HTTP ${r.status}`
|
||||
try { m = (await r.json()).detail || m } catch (_) {}
|
||||
throw new Error(m)
|
||||
}
|
||||
return r.json()
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<i class="blob b1"></i>
|
||||
<i class="blob b2"></i>
|
||||
<i class="blob b3"></i>
|
||||
|
||||
<div class="card">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
@@ -8,13 +12,35 @@
|
||||
<span>统一账户登录</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<input v-model="account" placeholder="账号" @keyup.enter="doLogin">
|
||||
<input v-model="password" type="password" placeholder="密码" @keyup.enter="doLogin">
|
||||
<label class="field">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="12" cy="8" r="3.6" />
|
||||
<path d="M4.5 20a7.5 7.5 0 0 1 15 0" />
|
||||
</svg>
|
||||
<input v-model="account" placeholder="账号" autocomplete="username" @keyup.enter="doLogin">
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"
|
||||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="4.5" y="10.5" width="15" height="9.5" rx="2.5" />
|
||||
<path d="M8 10.5V7.8a4 4 0 0 1 8 0v2.7" />
|
||||
</svg>
|
||||
<input v-model="password" type="password" placeholder="密码" autocomplete="current-password" @keyup.enter="doLogin">
|
||||
</label>
|
||||
</div>
|
||||
<button class="primary" :disabled="busy" @click="doLogin">{{ busy ? '校验中…' : '登录' }}</button>
|
||||
<p class="tip">账号统一由控制面带部门建档,所有账号均需密码登录,密码不落前端明文。</p>
|
||||
<p class="msg" v-if="msg">{{ msg }}</p>
|
||||
|
||||
<button class="primary" :disabled="busy" @click="doLogin">
|
||||
<span v-if="busy" class="spinner"></span>
|
||||
{{ busy ? '校验中…' : '登录' }}
|
||||
</button>
|
||||
|
||||
<transition name="fade">
|
||||
<p class="msg" v-if="msg">{{ msg }}</p>
|
||||
</transition>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -33,9 +59,10 @@ const msg = ref('')
|
||||
async function doLogin() {
|
||||
if (!account.value || !password.value) return (msg.value = '请输入账号和密码')
|
||||
busy.value = true
|
||||
msg.value = ''
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin })
|
||||
emit('ok', { account: account.value.trim(), is_admin: !!r.is_admin, dept: r.dept || '' })
|
||||
} catch (e) {
|
||||
msg.value = '登录失败:' + (e.message || e)
|
||||
} finally {
|
||||
@@ -45,21 +72,204 @@ async function doLogin() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login { display: grid; place-items: center; height: 100%; }
|
||||
.card { width: 340px; display: flex; flex-direction: column; gap: 14px;
|
||||
border: 1px solid var(--border); border-radius: 12px; padding: 28px; box-shadow: 0 10px 30px -14px rgba(0,0,0,.18); }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 4px; }
|
||||
.logo { width: 40px; height: 40px; border-radius: 11px; display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff; font-size: 15px; font-weight: 800; }
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.brand-meta strong { font-size: 15px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
.login {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
height: 100%;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: radial-gradient(1100px 520px at 50% -12%, rgba(59, 108, 255, .07), transparent 62%);
|
||||
}
|
||||
|
||||
/* ---------- 背景光斑 ---------- */
|
||||
.blob {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
filter: blur(90px);
|
||||
opacity: .38;
|
||||
pointer-events: none;
|
||||
will-change: transform;
|
||||
animation: float 18s ease-in-out infinite;
|
||||
}
|
||||
.b1 { width: 460px; height: 460px; background: #a8c1ff; top: -150px; right: -110px; }
|
||||
.b2 { width: 400px; height: 400px; background: #9fe3c8; bottom: -140px; left: -90px; animation-delay: -6s; }
|
||||
.b3 { width: 280px; height: 280px; background: #ffd6a8; bottom: 18%; right: 10%; opacity: .22; animation-delay: -12s; }
|
||||
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translate3d(0, 0, 0) scale(1); }
|
||||
50% { transform: translate3d(0, -22px, 0) scale(1.06); }
|
||||
}
|
||||
|
||||
/* ---------- 卡片 ---------- */
|
||||
.card {
|
||||
width: 380px;
|
||||
max-width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
padding: 32px 32px 26px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 20px;
|
||||
background: var(--surface);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
box-shadow:
|
||||
0 24px 60px -26px rgba(24, 39, 75, .34),
|
||||
0 2px 10px -3px rgba(24, 39, 75, .08);
|
||||
animation: rise .5s cubic-bezier(.22, 1, .36, 1) both;
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from { opacity: 0; transform: translateY(14px) scale(.985); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* ---------- 品牌区 ---------- */
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-bottom: 2px; }
|
||||
|
||||
.logo {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
flex: none;
|
||||
border-radius: 12px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .02em;
|
||||
box-shadow: 0 6px 16px -5px rgba(59, 108, 255, .65);
|
||||
}
|
||||
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.3; min-width: 0; }
|
||||
.brand-meta strong {
|
||||
font-size: 15px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.brand-meta span { font-size: 11.5px; color: var(--text-faint); letter-spacing: .02em; }
|
||||
|
||||
/* ---------- 输入框 ---------- */
|
||||
.row { display: flex; flex-direction: column; gap: 10px; }
|
||||
.row input { border: 1px solid var(--border-strong); border-radius: var(--radius-sm); padding: 10px 12px; background: var(--surface); font: inherit; }
|
||||
.row input:focus { outline: none; border-color: var(--primary); }
|
||||
button.primary { border: none; border-radius: var(--radius-sm); padding: 10px; cursor: pointer;
|
||||
background: var(--primary); color: #fff; font: inherit; }
|
||||
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
||||
.tip { color: var(--text-faint); font-size: 11.5px; line-height: 1.6; }
|
||||
.msg { color: #e5484d; font-size: 12px; }
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 0 13px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
transition: border-color .18s, box-shadow .18s;
|
||||
}
|
||||
.field:hover { border-color: var(--primary); }
|
||||
|
||||
.field:focus-within {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 4px var(--primary-weak);
|
||||
}
|
||||
|
||||
.field svg {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
flex: none;
|
||||
color: var(--text-faint);
|
||||
transition: color .18s;
|
||||
}
|
||||
.field:focus-within svg { color: var(--primary); }
|
||||
|
||||
.field input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 12px 0;
|
||||
border: none;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
.field input::placeholder { color: var(--text-faint); }
|
||||
|
||||
/* 干掉 Chrome 自动填充的黄色底色 */
|
||||
.field input:-webkit-autofill {
|
||||
-webkit-text-fill-color: currentColor;
|
||||
transition: background-color 9999s ease-in-out 0s;
|
||||
}
|
||||
|
||||
/* ---------- 主按钮 ---------- */
|
||||
button.primary {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
margin-top: 2px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: .06em;
|
||||
box-shadow: 0 8px 20px -7px rgba(59, 108, 255, .65);
|
||||
transition: box-shadow .18s, transform .12s, filter .18s;
|
||||
}
|
||||
button.primary:hover:not(:disabled) {
|
||||
filter: brightness(1.05);
|
||||
box-shadow: 0 12px 28px -9px rgba(59, 108, 255, .75);
|
||||
}
|
||||
button.primary:active:not(:disabled) {
|
||||
transform: translateY(1px);
|
||||
box-shadow: 0 5px 14px -7px rgba(59, 108, 255, .65);
|
||||
}
|
||||
button.primary:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 4px var(--primary-weak), 0 8px 20px -7px rgba(59, 108, 255, .65);
|
||||
}
|
||||
button.primary:disabled { opacity: .6; cursor: not-allowed; box-shadow: none; }
|
||||
|
||||
.spinner {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 2px solid rgba(255, 255, 255, .38);
|
||||
border-top-color: #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin .7s linear infinite;
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* ---------- 提示信息 ---------- */
|
||||
.msg {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid rgba(229, 72, 77, .18);
|
||||
border-radius: 10px;
|
||||
background: rgba(229, 72, 77, .08);
|
||||
color: #e5484d;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.fade-enter-active,
|
||||
.fade-leave-active { transition: opacity .2s, transform .2s; }
|
||||
.fade-enter-from,
|
||||
.fade-leave-to { opacity: 0; transform: translateY(-4px); }
|
||||
|
||||
/* ---------- 自适应 & 降级 ---------- */
|
||||
@media (max-width: 420px) {
|
||||
.login { padding: 16px; }
|
||||
.card { padding: 26px 22px 22px; border-radius: 16px; }
|
||||
.blob { filter: blur(70px); opacity: .3; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.blob, .card { animation: none; }
|
||||
* { transition-duration: .01ms !important; }
|
||||
}
|
||||
</style>
|
||||
@@ -69,7 +69,7 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { store } from '../store'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
@@ -109,8 +109,14 @@ async function run() {
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
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}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
@@ -160,13 +166,12 @@ function closeBanner() {
|
||||
|
||||
.form-card {
|
||||
display: flex; flex-direction: column; gap: 16px;
|
||||
background: var(--surface-2); border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm); padding: 16px;
|
||||
padding: 2px 0 0;
|
||||
}
|
||||
.fields { display: flex; gap: 24px; flex-wrap: wrap; }
|
||||
.fgroup { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
|
||||
.fgroup .input { width: 150px; }
|
||||
.actions { display: flex; justify-content: flex-end; }
|
||||
.actions { display: flex; justify-content: flex-end; border-top: 1px dashed var(--border); padding-top: 14px; }
|
||||
.run-btn { min-width: 128px; height: 38px; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.spin { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.7s linear infinite; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
<template>
|
||||
<div class="mask" @click.self="emit('close')">
|
||||
<aside class="profile">
|
||||
<header class="head">
|
||||
<div class="avatar" aria-hidden="true">
|
||||
<img v-if="store.avatarUrl && !avatarFailed" :src="store.avatarUrl" alt="" @error="onAvatarError">
|
||||
<span v-else>{{ store.current.slice(0, 1).toUpperCase() }}</span>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="name-line">
|
||||
<strong>{{ store.current }}</strong>
|
||||
<em v-if="store.isAdmin" class="tag">管理员</em>
|
||||
</div>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
<button class="close" title="关闭" @click="emit('close')">✕</button>
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
<!-- 分节:平台登录态 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">平台登录态</div>
|
||||
<div v-for="p in store.platforms" :key="p.id" class="prow">
|
||||
<i class="dot" :class="{ on: p.online }"></i>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<span class="pstat">{{ p.online ? '已登录' : '未登录' }}</span>
|
||||
<button class="btn mini" :disabled="busy === p.id" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : '重新登录' }}
|
||||
</button>
|
||||
<button class="btn mini" :disabled="busy === p.id || !p.online" @click="logout(p.id)">登出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分节:我的插件 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">我的插件</div>
|
||||
<div v-if="store.plugins.length" class="plist">
|
||||
<div v-for="p in store.plugins" :key="p.id" class="prow flat">
|
||||
<span class="pname">{{ p.name }}</span>
|
||||
<span class="ver">v{{ p.version }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="empty">当前账号暂无可用插件</p>
|
||||
</div>
|
||||
|
||||
<!-- 分节:修改密码 -->
|
||||
<div class="sec">
|
||||
<div class="sec-title">修改密码</div>
|
||||
<input class="input" v-model="oldPwd" type="password" placeholder="旧密码">
|
||||
<input class="input" v-model="newPwd" type="password" placeholder="新密码">
|
||||
<input class="input" v-model="againPwd" type="password" placeholder="确认新密码">
|
||||
<button class="btn primary block" :disabled="pwdBusy" @click="changePwd">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</button>
|
||||
<p v-if="pwdMsg" class="msg" :class="{ ok: pwdOk }">{{ pwdMsg }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<transition name="fade">
|
||||
<div v-if="tipMsg" class="tip">{{ tipMsg }}</div>
|
||||
</transition>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { store, log, clearAvatarCache } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
const avatarFailed = ref(false)
|
||||
function onAvatarError() {
|
||||
avatarFailed.value = true
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const busy = ref('')
|
||||
// 面板内轻提示:已登录再点击等操作反馈
|
||||
const tipMsg = ref('')
|
||||
let tipTimer = null
|
||||
function tip(m) {
|
||||
tipMsg.value = m
|
||||
if (tipTimer) clearTimeout(tipTimer)
|
||||
tipTimer = setTimeout(() => (tipMsg.value = ''), 2000)
|
||||
}
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
tip(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
alert('登录失败:' + (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} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
tip('登出失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const oldPwd = ref('')
|
||||
const newPwd = ref('')
|
||||
const againPwd = ref('')
|
||||
const pwdBusy = ref(false)
|
||||
const pwdMsg = ref('')
|
||||
const pwdOk = ref(false)
|
||||
async function changePwd() {
|
||||
pwdMsg.value = ''
|
||||
if (!oldPwd.value || !newPwd.value) return (pwdMsg.value = '请填写完整密码')
|
||||
if (newPwd.value !== againPwd.value) return (pwdMsg.value = '两次新密码不一致')
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: oldPwd.value,
|
||||
new_password: newPwd.value,
|
||||
})
|
||||
pwdMsg.value = '密码已修改'
|
||||
pwdOk.value = true
|
||||
oldPwd.value = newPwd.value = againPwd.value = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
pwdOk.value = false
|
||||
pwdMsg.value = '修改失败:' + (e.message || e)
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mask {
|
||||
position: fixed; inset: 0; z-index: 50;
|
||||
background: rgba(31, 38, 51, 0.35);
|
||||
display: flex; justify-content: flex-end;
|
||||
animation: fade .18s ease;
|
||||
}
|
||||
.tip {
|
||||
position: absolute; top: 18px; left: 50%; transform: translateX(-50%);
|
||||
background: rgba(24, 39, 75, .92); color: #fff;
|
||||
padding: 8px 18px; border-radius: 999px; font-size: 12.5px;
|
||||
z-index: 5; box-shadow: 0 8px 24px -8px rgba(24, 39, 75, .4);
|
||||
animation: fade .15s ease;
|
||||
}
|
||||
.profile {
|
||||
width: 320px; height: 100%;
|
||||
background: var(--surface);
|
||||
display: flex; flex-direction: column;
|
||||
box-shadow: -12px 0 34px -12px rgba(24, 39, 75, 0.3);
|
||||
animation: slide .2s ease;
|
||||
}
|
||||
@keyframes slide { from { transform: translateX(100%); } to { transform: translateX(0); } }
|
||||
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
|
||||
|
||||
.head {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 18px 20px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.avatar {
|
||||
width: 46px; height: 46px; border-radius: 50%;
|
||||
position: relative; overflow: hidden; flex-shrink: 0;
|
||||
display: grid; place-items: center;
|
||||
color: #fff; font-size: 18px; font-weight: 700;
|
||||
background: var(--primary-grad);
|
||||
}
|
||||
.avatar img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
|
||||
.meta { flex: 1; min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong { font-size: 15px; }
|
||||
.tag { font-style: normal; font-size: 10px; color: var(--primary);
|
||||
background: var(--primary-weak); border-radius: 999px; padding: 1px 8px; }
|
||||
.dept { font-size: 11.5px; color: var(--text-faint); }
|
||||
.close {
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
color: var(--text-faint); font-size: 14px; padding: 6px; border-radius: 8px;
|
||||
}
|
||||
.close:hover { color: var(--text); background: var(--surface-2); }
|
||||
|
||||
.body { flex: 1; overflow: auto; padding: 4px 20px 20px; }
|
||||
.sec { padding: 14px 0 4px; }
|
||||
.sec + .sec { border-top: 1px dashed var(--border); margin-top: 6px; }
|
||||
.sec-title {
|
||||
font-size: 11px; font-weight: 700; letter-spacing: 0.04em;
|
||||
color: var(--text-faint); margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.prow { display: flex; align-items: center; gap: 8px; padding: 7px 0; }
|
||||
.prow.flat { padding: 6px 0; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: #c6ccdc; flex-shrink: 0; }
|
||||
.dot.on { background: var(--ok); box-shadow: 0 0 0 3px rgba(34, 176, 122, 0.18); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13px;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pstat { font-size: 11px; color: var(--text-faint); }
|
||||
.ver { font-size: 11px; color: var(--text-faint); }
|
||||
.plist { display: flex; flex-direction: column; }
|
||||
.empty { color: var(--text-faint); font-size: 12px; margin: 4px 0; }
|
||||
.btn.mini { padding: 3px 10px; font-size: 12px; }
|
||||
|
||||
.input { width: 100%; margin-bottom: 10px; }
|
||||
.btn.block { width: 100%; margin-top: 2px; }
|
||||
.msg { font-size: 12px; color: var(--err); margin: 8px 0 0; }
|
||||
.msg.ok { color: var(--ok); }
|
||||
</style>
|
||||
@@ -14,11 +14,45 @@ export const store = reactive({
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
isAdmin: false,
|
||||
dept: '',
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user