rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -1,128 +1,134 @@
|
||||
# -*- 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")
|
||||
# -*- 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')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容旧逻辑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
|
||||
# 各平台 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")
|
||||
|
||||
@@ -1,323 +1,323 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""环境包版插件执行守护:Job Object 托管 + 内存上限 + 超时强杀。
|
||||
|
||||
Node 壳(electron-shell runner.js)在**便携环境包**模式下不再直接 spawn
|
||||
plugin_runner,而是经由本守护拉起,以获得旧 Python 底座同等的进程托管能力:
|
||||
|
||||
python job_guard.py [--mem <MB>] [--timeout <秒>] -- <python> -u <plugin_runner.py> [args...]
|
||||
|
||||
- Job Object(KILL_ON_JOB_CLOSE + PROCESS_MEMORY_LIMIT,复用 winjob.py)
|
||||
→ 插件及其拉起的浏览器孙进程整体托管,内存超限/超时/宿主退出即整树终止;
|
||||
- stdin/stdout/stderr 三通道逐字节透传(plugin_runner 协议不经过本进程改写,
|
||||
与 Node 直接 spawn 时逐字节一致:fields 单行 JSON → 事件行/诊断行);
|
||||
- 退出码 = 子进程退出码(透传),Node 侧结论判定逻辑不变;
|
||||
- 非 Windows 平台安全降级为直接 spawn 子进程(winjob 内部 no-op)。
|
||||
|
||||
本文件同时进入环境包运行时子集(webhost/backend/core/job_guard.py),
|
||||
不依赖任何第三方包(ctypes 标准库实现)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from webhost.backend.core import winjob # 环境包/仓库内相对解析
|
||||
except Exception: # noqa: BLE001 兜底:直接同目录导入
|
||||
import winjob
|
||||
|
||||
|
||||
def _forward(src, dst, name: str) -> None:
|
||||
"""把 src 的字节流逐块转发到 dst;EOF 后 flush 并结束。"""
|
||||
try:
|
||||
while True:
|
||||
chunk = src.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
dst.write(chunk)
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001 通道关闭即结束
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description="37du 插件执行守护(Job Object 托管)")
|
||||
parser.add_argument("--mem", type=int, default=0, help="作业级内存上限(MB),0=不限")
|
||||
parser.add_argument("--timeout", type=int, default=0, help="超时秒数,0=不限(Node 侧仍有兜底强杀)")
|
||||
parser.add_argument("child", nargs=argparse.REMAINDER, help="-- 之后为真实子进程命令")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if not args.child or args.child[0] != "--":
|
||||
print("用法:python job_guard.py [--mem MB] [--timeout 秒] -- <cmd...>", file=sys.stderr)
|
||||
return 2
|
||||
child_cmd = args.child[1:]
|
||||
if not child_cmd:
|
||||
print("缺少子进程命令", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
# 透传环境(宿主注入的 PLUGINS_ROOT / PLATFORM_ACCOUNT 等原样继承)
|
||||
env = dict(os.environ)
|
||||
|
||||
# 1) 子进程:stdin/stdout/stderr 直接对接父进程(Node 侧),协议零改写
|
||||
try:
|
||||
child = subprocess.Popen(
|
||||
child_cmd,
|
||||
stdin=sys.stdin.buffer,
|
||||
stdout=sys.stdout.buffer,
|
||||
stderr=sys.stderr.buffer,
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
bufsize=0,
|
||||
)
|
||||
except OSError as e:
|
||||
print(f"拉起子进程失败: {e}", file=sys.stderr)
|
||||
return 127
|
||||
|
||||
# 2) Job Object 托管(Windows):整树终止 + 内存上限
|
||||
job = winjob.Job(max_mem_mb=int(args.mem or 0))
|
||||
try:
|
||||
job.assign(child)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 3) 超时守护(兜底;Node 侧 taskkill 仍作为第二道防线)
|
||||
timed_out = {"v": False}
|
||||
|
||||
def _kill_on_timeout() -> None:
|
||||
time.sleep(max(1, int(args.timeout or 0)))
|
||||
timed_out["v"] = True
|
||||
try:
|
||||
job.terminate(1)
|
||||
except Exception: # noqa: BLE001
|
||||
try:
|
||||
child.kill()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
timer = None
|
||||
if int(args.timeout or 0) > 0:
|
||||
timer = threading.Thread(target=_kill_on_timeout, daemon=True)
|
||||
timer.start()
|
||||
|
||||
# 4) 等子进程结束(进程退出/超时终止均在此返回);子进程自身已接管三通道
|
||||
try:
|
||||
code = child.wait()
|
||||
except KeyboardInterrupt:
|
||||
job.terminate(1)
|
||||
try:
|
||||
code = child.wait(timeout=5)
|
||||
except Exception: # noqa: BLE001
|
||||
code = 1
|
||||
|
||||
job.close()
|
||||
if timed_out["v"]:
|
||||
print(f"[job_guard] 插件执行超时({args.timeout}s)已强制终止", file=sys.stderr)
|
||||
return int(code) if code is not None else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,241 +1,242 @@
|
||||
# -*- 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 threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
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 _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
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 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
# -*- 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 threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
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:
|
||||
# utf-8-sig:防 plugin.json 带 UTF-8 BOM(json.loads 遇 BOM 会抛 JSONDecodeError → 误判为新装重下)
|
||||
return str(json.loads(mf.read_text(encoding="utf-8-sig")).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 _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
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 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
|
||||
@@ -66,12 +66,14 @@ _PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。"""
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。
|
||||
用 utf-8-sig 读取:防文件带 UTF-8 BOM(记事本另存 UTF-8 时常见),否则会读到
|
||||
"\\ufeff1.2.0" 导致版本比对永远判为"不大于"(P1 修复:壳子升级失效根因)。"""
|
||||
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 ""
|
||||
return vf.read_text(encoding="utf-8-sig").strip() if vf.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
@@ -19,17 +19,22 @@ from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
|
||||
|
||||
# 插件目录(源码/打包统一的"单一真源"位置):
|
||||
# 插件目录(源码/打包/环境包统一的"单一真源"位置):
|
||||
# - 环境包/便携运行时:由宿主(Node 壳)显式注入 PLUGINS_ROOT 环境变量(指向插件根)
|
||||
# - 打包运行(frozen)时:exe 同级 plugins/(中心机下发插件包解压到这里)
|
||||
# - 源码运行:仓库根 plugins/(插件源码独立于底座,不随 webhost 发布)
|
||||
# 两种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
if getattr(sys, "frozen", False):
|
||||
# 三种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
_env_plugins_root = os.getenv("PLUGINS_ROOT", "").strip()
|
||||
if _env_plugins_root:
|
||||
_PLUGINS_ROOT = pathlib.Path(_env_plugins_root).resolve()
|
||||
elif getattr(sys, "frozen", False):
|
||||
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
|
||||
else:
|
||||
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
|
||||
|
||||
@@ -1,449 +1,455 @@
|
||||
# -*- 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)
|
||||
# -*- 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')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
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)
|
||||
|
||||
@@ -48,6 +48,12 @@ _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')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
@@ -125,6 +125,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -90,6 +90,12 @@ _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')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
@@ -1,12 +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>
|
||||
<!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>
|
||||
File diff suppressed because it is too large
Load Diff
+129
-129
@@ -1,130 +1,130 @@
|
||||
// 与 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 checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { 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 async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
// 与 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 checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { 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 async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,353 +1,353 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<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>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<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-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<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-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } 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()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
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: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.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: var(--text); 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: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.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: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<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>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<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-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<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-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } 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()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
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: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.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: var(--text); 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: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.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: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
</style>
|
||||
@@ -1,160 +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); }
|
||||
/* ============ 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; }
|
||||
+248
-248
@@ -1,249 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
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
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
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:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
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())
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
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
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
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:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
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
|
||||
@@ -5,7 +5,7 @@
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#define MyAppVersion "1.2.1"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.2.0
|
||||
1.2.1
|
||||
Reference in New Issue
Block a user