# -*- coding: utf-8 -*- """webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。 流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本, 缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到 plugins// 原子替换;更新成功后由宿主重载插件注册表。 本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回 授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。 降级策略: - 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行) - 单个插件下载/校验/解压失败 → 记 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//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//(临时目录 → 原子替换)。 包根目录需含 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