rescue: 断电事故后工作区全量备份

This commit is contained in:
2026-09-24 15:59:44 +08:00
parent be1a2899ba
commit 7e0838de64
204 changed files with 77921 additions and 77173 deletions
+134 -128
View File
@@ -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")
+322 -322
View File
@@ -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 安装完成超时")
+128
View File
@@ -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())
+242 -241
View File
@@ -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 ""