refactor: 完成项目目录重构与代码迁移

本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
2026-09-14 17:46:09 +08:00
parent cb04790d28
commit 1e533dd1b3
131 changed files with 4071 additions and 38034 deletions
@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
"""插件注册表——目录动态扫描加载。
加载约定(扫描协议):
- 插件形态:plugins/ 下的**目录包**(含 __init__.py,在其中定义 ScenePlugin 子类并
PLUGINS.append,如 seal_check/)。顶层单模块(*.py)仅用于兼容旧 demo/platform_check。
- 私有辅助文件**必须用 `_` 前缀**(如 _utils.py、_common/),扫描时一律排除,
避免被误当作插件 import。
- 只有继承 ScenePlugin 并通过 PLUGINS.append 注册的才会进入注册表;_ 前缀约定
确保辅助模块根本不会被 import,杜绝误注册与无用告警。
- 同名冲突:目录优先于同名 .py(先收目录再收 py,同名仅保留目录)。
- 单个插件加载失败记 ERROR 并保留堆栈首行后跳过,不拖垮整体启动。
阶段二(权限):把「有权限的插件名」传给 load_plugins(allowed) 即可,无权限不 import。
届时触发点建议从「import 副作用」改为由 main.py 在应用启动时显式调用 load_plugins(),
以便每次按登录账号动态决定允许集。
"""
from __future__ import annotations
import importlib
import logging
import pathlib
import sys
import traceback
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
# 插件目录(源码/打包统一的"单一真源"位置):
# - 打包运行(frozen)时:exe 同级 plugins/(中心机下发插件包解压到这里)
# - 源码运行:仓库根 plugins/(插件源码独立于底座,不随 webhost 发布)
# 两种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
if getattr(sys, "frozen", False):
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
else:
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
_PLUGINS_ROOT = pathlib.Path(__file__).resolve().parents[4] / "plugins"
if _PLUGINS_ROOT.is_dir() and str(_PLUGINS_ROOT) not in __path__:
__path__.append(str(_PLUGINS_ROOT))
_PKG_NAME = __name__
_LOGGER = logging.getLogger(__name__)
def _discover_modules() -> list:
"""发现插件模块:目录优先,排除 base 与 `_` 前缀的私有文件。"""
names: list = []
seen: set = set()
for d in sorted(_PLUGINS_ROOT.iterdir()):
if not d.is_dir() or d.name.startswith("_") or d.name == "__pycache__":
continue
if (d / "__init__.py").exists():
names.append(d.name)
seen.add(d.name)
for f in sorted(_PLUGINS_ROOT.glob("*.py")):
if f.name in ("__init__.py", "base.py") or f.name.startswith("_"):
continue
if f.stem not in seen: # 已被同名目录占用则跳过
names.append(f.stem)
return names
def load_plugins(allowed: set = None, reload: bool = False) -> None:
"""动态加载插件。allowed 为 None = 全量;否则为严格白名单(空集 = 零权限,全不加载)。
reload=True 时先清空注册表与已加载模块缓存(用于插件自下载/更新后的重载,使新代码生效)。
单插件加载失败记 ERROR(含堆栈首行)后跳过,不拖垮整体启动。
"""
if reload:
PLUGINS.clear()
for _m in [m for m in sys.modules
if m.startswith(_PKG_NAME + ".") and m != _PKG_NAME]:
del sys.modules[_m]
for _mod in _discover_modules():
if allowed is not None and _mod not in allowed:
_LOGGER.info("插件 %s 不在权限白名单,跳过加载", _mod)
continue
try:
importlib.import_module(f"{_PKG_NAME}.{_mod}")
except Exception as _exc: # noqa: BLE001
_LOGGER.error("插件 %s 加载失败,已跳过\n%s", _mod,
traceback.format_exc(limit=1))
# 注意:这里不再 import 时自动加载。由宿主(main.py)在应用启动时显式调用
# load_plugins(allowed) 一次性加载,以便阶段二可传入按账号动态计算的权限白名单。
+74
View File
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
"""场景插件抽象:后端 `run` 承载真实逻辑(浏览器自动化/登录态等),
前端按 `fields` 渲染通用表单,执行过程经 `RunContext.log/progress` 推送到 WebSocket。
"""
from __future__ import annotations
from typing import List
class RunContext:
"""传给插件 `run` 的执行上下文:把日志/进度实时推给前端,并提供共享登录态访问。"""
def __init__(self, hub, run_id: str, plugin_id: str, auth=None):
self._hub = hub
self._auth = auth # webhost.backend.auth 模块(宿主注入的共享登录态)
self.run_id = run_id
self.plugin_id = plugin_id
def log(self, msg: str, level: str = "INFO"):
self._hub.publish({
"t": "log", "run_id": self.run_id, "plugin_id": self.plugin_id,
"level": level, "msg": msg,
})
def progress(self, pct: int):
self._hub.publish({
"t": "progress", "run_id": self.run_id,
"plugin_id": self.plugin_id, "pct": int(max(0, min(100, pct))),
})
# ---------- 共享登录态 ----------
def get_session(self, platform: str) -> "requests.Session":
"""获取指定平台的共享登录 session,可直接传给 shared 数据模块。"""
if not self._auth:
raise RuntimeError("宿主未注入登录态服务,无法构建 session")
return self._auth.build_session(platform)
def get_user_id(self, platform: str) -> str:
"""获取指定平台的用户 ID(HR 数据接口大多需要 user_id 参数)。"""
if not self._auth:
raise RuntimeError("宿主未注入登录态服务,无法获取 user_id")
return self._auth.get_user_id(platform)
class ScenePlugin:
"""场景插件基类。新增场景:子类填 id/name/fields/run 并注册到 plugins 列表。"""
id: str = ""
name: str = ""
version: str = "1.0.0"
description: str = ""
platform: str = "" # 所需平台登录态:hr / oa / ""(无需登录)
uses_month: bool = False # 是否需要底座页眉的“执行月份”(前端据此注入 ref_month 字段)
# 表单字段定义:[{key,label,type,default,options}]
# type ∈ int | text | select
fields: List[dict] = []
# 声明式能力/权限(manifest 驱动):与插件包 plugin.json 保持一致;
# 缺省场景可用本地类补充,plugin.json 存在时以其为权威。
capabilities: List[str] = []
permissions: dict = {}
def run(self, fields: dict, ctx: RunContext) -> dict:
raise NotImplementedError(f"插件 {self.id} 未实现 run")
class _Registry(list):
def find(self, pid: str) -> ScenePlugin:
for p in self:
if p.id == pid:
return p
raise KeyError(pid)
PLUGINS: _Registry = _Registry()