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

This commit is contained in:
2026-09-24 15:59:44 +08:00
parent 8a196d6c87
commit 08a9b962b4
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 ""
+8 -3
View File
@@ -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] = 仓库根
+455 -449
View File
@@ -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"