Files
37duAutomation/desktop/webhost/backend/core/chrome_manager.py
T

323 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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 安装完成超时")