refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移: 1. 将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构 2. 移动并整理了插件目录结构,将插件统一放入根级plugins/ 3. 调整了前端项目的路径与配置,统一前后端开发构建流程 4. 清理了废弃的旧版app/目录与冗余的构建中间文件 5. 更新了.gitignore与README.md,适配新的项目结构
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端(执行机底座):场景插件宿主。
|
||||
|
||||
组装层 main.py 之外的领域逻辑已归入 core 子包。本 `__init__` 作为 facade 再导出
|
||||
core 内各模块,以兼容 `from webhost.backend import X` 的既有用法(含插件 `auth` 引用)。
|
||||
"""
|
||||
from webhost.backend.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
cpapi,
|
||||
hub,
|
||||
licensing,
|
||||
meta,
|
||||
runner,
|
||||
scheduler,
|
||||
session,
|
||||
state,
|
||||
winjob,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
# 登录成功即按账号权限自下载/更新插件并重载(离线/失败不影响登录)
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.plugins import load_plugins
|
||||
sync_plugins(b.account.strip())
|
||||
load_plugins(None, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后插件同步失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@router.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
|
||||
_SESS_LOCK, _sess_persist)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
|
||||
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
|
||||
|
||||
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
|
||||
"""
|
||||
r = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/auth",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
|
||||
acct = r.get("account") or account
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (acct, time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(acct)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
|
||||
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/login")
|
||||
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
|
||||
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
|
||||
if not d.account:
|
||||
raise HTTPException(400, "工号不能为空")
|
||||
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/inline")
|
||||
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
|
||||
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
|
||||
|
||||
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
|
||||
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
|
||||
"""
|
||||
if not d.code.strip():
|
||||
raise HTTPException(400, "缺少扫码截图码")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
json={"code": d.code.strip()})
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account:
|
||||
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
|
||||
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return _cp_call(
|
||||
"GET", "/api/admin/dingtalk/inline_qr",
|
||||
params={"back": back},
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
|
||||
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
|
||||
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
|
||||
<script>
|
||||
(async function(){
|
||||
var q = new URLSearchParams(location.search);
|
||||
var account = q.get('account') || '';
|
||||
var nickname = q.get('nickname') || '';
|
||||
if (account) {
|
||||
try {
|
||||
await fetch('/api/admin/dingtalk/login', {
|
||||
method:'POST', headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({ account: account, nickname: nickname })
|
||||
});
|
||||
} catch (e) {}
|
||||
}
|
||||
try { window.opener && window.opener.location.reload(); } catch (e) {}
|
||||
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
|
||||
})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
@@ -0,0 +1,100 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「业务元数据与平台登录」路由:/api/meta 聚合 + 平台真实登录/登出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
from webhost.backend.core import shell_updater as _shell_updater
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/plugins/sync")
|
||||
def plugins_sync(request: Request) -> dict:
|
||||
"""按当前登录账号权限自下载/更新插件,成功后重载注册表。
|
||||
|
||||
离线(控制面不可达)/未配置时返回空统计,前端直接沿用本地插件进入主界面。
|
||||
"""
|
||||
account = _require_login(request)
|
||||
result = sync_plugins(account)
|
||||
try:
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
except Exception as _exc: # noqa: BLE001 重载失败不阻断返回
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("插件同步后重载失败:%s", _exc)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/api/shell/update-status")
|
||||
def shell_update_status(request: Request) -> dict:
|
||||
"""壳子更新状态:前端据此显示"发现新版本,点击重启更新"提示。"""
|
||||
_require_login(request)
|
||||
return _shell_updater.pending_status()
|
||||
|
||||
|
||||
@router.post("/api/shell/apply")
|
||||
def shell_apply(request: Request) -> dict:
|
||||
"""应用壳子更新:运行新版安装包静默安装并退出进程(升级完成后自动重启新版本)。"""
|
||||
_require_login(request)
|
||||
_shell_updater.apply_update()
|
||||
return {"ok": True} # 实际不会走到这里(apply 内 os._exit)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
plugin = PLUGINS.find(req.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
|
||||
online = licensing.is_online()
|
||||
deny = licensing.run_check_allowed(plugin.id, account, online)
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start(_run_id):
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.fields, _run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return _run_id
|
||||
_scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端领域逻辑核心(core)包。
|
||||
|
||||
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
|
||||
"""
|
||||
@@ -0,0 +1,128 @@
|
||||
# -*- 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")
|
||||
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主配置固化:加载本模块 env(webhost/.env) 并输出全部环境常量与路径。
|
||||
|
||||
依赖方向:config ← 所有领域逻辑与路由模块(只读,不含业务逻辑)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
|
||||
# 打包运行(frozen)时:底座根 = exe 所在目录(.env、plugins/ 与 exe 同级部署);
|
||||
# 前端静态资源打包进 exe 内部,运行时从解压目录(_MEIPASS)读取
|
||||
if getattr(sys, "frozen", False):
|
||||
_HOST_ROOT = Path(sys.executable).resolve().parent
|
||||
DIST = Path(getattr(sys, "_MEIPASS", _HOST_ROOT)) / "frontend" / "dist"
|
||||
else:
|
||||
_HOST_ROOT = Path(__file__).resolve().parents[1]
|
||||
DIST = _HOST_ROOT / "frontend" / "dist"
|
||||
|
||||
PORT = 8799
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = _HOST_ROOT / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
try:
|
||||
for _ln in env_path.read_text(encoding="utf-8").splitlines():
|
||||
_line = _ln.strip()
|
||||
if not _line or _line.startswith("#") or "=" not in _line:
|
||||
continue
|
||||
_k, _v = _line.split("=", 1)
|
||||
_k, _v = _k.strip(), _v.strip()
|
||||
if _k and _k not in os.environ:
|
||||
os.environ[_k] = _v
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("读取 .env 失败: %s", _exc)
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
|
||||
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
|
||||
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
|
||||
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
|
||||
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
|
||||
@@ -0,0 +1,85 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。
|
||||
|
||||
底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
if not config.CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": config.CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw)
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
body = {"detail": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
|
||||
return body
|
||||
|
||||
|
||||
def _sync_licensing(account: str) -> None:
|
||||
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
|
||||
|
||||
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.cache_public_key(r.json().get("pub", ""))
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_license(r.json())
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
licensing.save_control(r.json())
|
||||
licensing.flush_offline_reports()
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。
|
||||
run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Dict
|
||||
|
||||
|
||||
class Hub:
|
||||
def __init__(self):
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._clients: list = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def bind(self, loop: asyncio.AbstractEventLoop):
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, websocket) -> None:
|
||||
await websocket.accept()
|
||||
with self._lock:
|
||||
self._clients.append(websocket)
|
||||
try:
|
||||
await websocket.receive_text() # 挂起直到客户端断开
|
||||
finally:
|
||||
with self._lock:
|
||||
self._clients.remove(websocket)
|
||||
|
||||
def publish(self, event: Dict) -> None:
|
||||
if self._loop is None:
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(self._send(event), self._loop)
|
||||
|
||||
async def _send(self, event: Dict) -> None:
|
||||
with self._lock:
|
||||
clients = list(self._clients)
|
||||
for ws in clients:
|
||||
try:
|
||||
await ws.send_json(event)
|
||||
except Exception:
|
||||
with self._lock:
|
||||
self._clients.remove(ws)
|
||||
|
||||
|
||||
HUB = Hub()
|
||||
@@ -0,0 +1,283 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
|
||||
|
||||
职责(对应架构设计七、八节):
|
||||
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
|
||||
license.json (离线授权票据,Ed25519 签名,离线一直有效)
|
||||
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
|
||||
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
|
||||
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
|
||||
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
|
||||
- verify_license() / verify_control() —— 用缓存公钥离线验签。
|
||||
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
KEYS_DIR = _APP_DATA / "keys"
|
||||
license_path = _APP_DATA / "license.json"
|
||||
control_path = _APP_DATA / "control.json"
|
||||
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
|
||||
|
||||
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
|
||||
_ONLINE_TTL = 180
|
||||
_last_sync = 0.0
|
||||
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
|
||||
|
||||
_CONTROLPLANE_URL = "" # 由 main.py 注入
|
||||
|
||||
|
||||
def init(controlplane_url: str, sync_lock) -> None:
|
||||
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
|
||||
global _CONTROLPLANE_URL, _sync_lock
|
||||
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
|
||||
_sync_lock = sync_lock
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
KEYS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
|
||||
# ==================== 联网判定 ====================
|
||||
def touch_sync() -> None:
|
||||
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
|
||||
global _last_sync
|
||||
with _sync_lock:
|
||||
_last_sync = time.time()
|
||||
|
||||
|
||||
def is_online() -> bool:
|
||||
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
|
||||
with _sync_lock:
|
||||
return (time.time() - _last_sync) <= _ONLINE_TTL
|
||||
|
||||
|
||||
# ==================== 公钥缓存与验签 ====================
|
||||
def _pub_pem_path() -> Path:
|
||||
return KEYS_DIR / "pub.pem"
|
||||
|
||||
|
||||
def cache_public_key(pem_text: str) -> None:
|
||||
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
|
||||
pem_text = (pem_text or "").strip()
|
||||
if not pem_text:
|
||||
return
|
||||
_pub_pem_path().write_text(pem_text, encoding="ascii")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def _load_public_key() -> Ed25519PublicKey | None:
|
||||
try:
|
||||
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
|
||||
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
|
||||
return None
|
||||
|
||||
|
||||
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
|
||||
"""验签返回 payload;签名非法抛 ValueError。"""
|
||||
if "." not in blob:
|
||||
raise ValueError("bad blob")
|
||||
b64, sig64 = blob.rsplit(".", 1)
|
||||
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
|
||||
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
|
||||
if len(sig) != 64:
|
||||
raise ValueError("bad signature len")
|
||||
pub.verify(sig, canon)
|
||||
return json.loads(canon)
|
||||
|
||||
|
||||
def verify_license() -> dict:
|
||||
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
|
||||
if not license_path.is_file():
|
||||
raise ValueError("无本地授权票据(license.json)")
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
raise ValueError("缺少中心机公钥,无法验签授权票据")
|
||||
data = json.loads(license_path.read_text(encoding="utf-8"))
|
||||
return _verify_blob(data["ticket"], pub)
|
||||
|
||||
|
||||
def verify_control() -> dict:
|
||||
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
|
||||
if not control_path.is_file():
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
pub = _load_public_key()
|
||||
if pub is None:
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
try:
|
||||
data = json.loads(control_path.read_text(encoding="utf-8"))
|
||||
payload = _verify_blob(data["ticket"], pub)
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
|
||||
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
def save_license(ticket_json: dict | str) -> None:
|
||||
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
license_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def save_control(ticket_json: dict | str) -> None:
|
||||
"""持久化管控清单缓存。"""
|
||||
if isinstance(ticket_json, dict):
|
||||
text = json.dumps(ticket_json, ensure_ascii=False)
|
||||
else:
|
||||
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
|
||||
control_path.write_text(text, encoding="utf-8")
|
||||
touch_sync()
|
||||
|
||||
|
||||
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
|
||||
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
|
||||
|
||||
- 验签授权票据,校验该插件 canRun。
|
||||
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
|
||||
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
|
||||
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
|
||||
"""
|
||||
control = verify_control()
|
||||
if plugin_id in control.get("revokedPlugins", []):
|
||||
return "插件已被下架(revoked),禁止运行"
|
||||
if plugin_id in control.get("disabledPlugins", []):
|
||||
return "插件已被禁用(disabled),禁止运行"
|
||||
|
||||
# 授权:先验签本地授权票据(离线可用)
|
||||
try:
|
||||
lic = verify_license()
|
||||
except Exception as _exc: # noqa: BLE001 授权票据不可用
|
||||
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
|
||||
|
||||
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
|
||||
grant = lic_plugins.get(plugin_id)
|
||||
if not grant:
|
||||
return f"账号 {account} 无插件「{plugin_id}」的授权"
|
||||
if not grant.get("canRun"):
|
||||
return f"账号 {account} 无「{plugin_id}」的运行授权"
|
||||
|
||||
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
|
||||
if online:
|
||||
forced = next((f for f in control.get("forcedUpdates", [])
|
||||
if f.get("pluginId") == plugin_id), None)
|
||||
if forced:
|
||||
min_ver = forced.get("minVersion", "")
|
||||
deadline = forced.get("deadline", "")
|
||||
if min_ver and deadline and _deadline_passed(deadline):
|
||||
installed = _installed_version(plugin_id)
|
||||
if installed and _version_lt(installed, min_ver):
|
||||
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
|
||||
f"当前 v{installed} 已禁止启动,请先更新")
|
||||
return None
|
||||
|
||||
|
||||
def _installed_version(plugin_id: str) -> str:
|
||||
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
|
||||
act = _APP_DATA / "active.json"
|
||||
try:
|
||||
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
|
||||
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _deadline_passed(deadline: str) -> bool:
|
||||
try:
|
||||
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
|
||||
return datetime.now(dt.tzinfo) > dt
|
||||
except Exception: # noqa: BLE001
|
||||
# 解析失败时按未过期兜底(不误伤在线用户)
|
||||
return False
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""版本比较:数字段按 int,非数字段按 str 小写。"""
|
||||
def _k(s):
|
||||
try:
|
||||
return (1, int(s))
|
||||
except ValueError:
|
||||
return (0, str(s).lower())
|
||||
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
|
||||
|
||||
|
||||
# ==================== 运行上报 ====================
|
||||
def report(account: str, device_id: str, plugin_id: str, version: str,
|
||||
status: str, msg: str = "", duration_sec: int = 0) -> None:
|
||||
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
|
||||
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
|
||||
"version": version, "status": status, "msg": msg,
|
||||
"duration_sec": int(duration_sec),
|
||||
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
||||
if not _CONTROLPLANE_URL:
|
||||
return
|
||||
if _push_report(rec):
|
||||
touch_sync()
|
||||
return
|
||||
# 离线:暂存待补报
|
||||
try:
|
||||
with open(reports_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _push_report(rec: dict) -> bool:
|
||||
"""同步上报一条到中心机;成功返回 True。"""
|
||||
try:
|
||||
_push_via_tempfile(rec) # 用 go-offset 方式直连
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _push_via_tempfile(rec: dict) -> None:
|
||||
"""向 /api/runtime/report 的同步 POST(requests)。"""
|
||||
import requests
|
||||
|
||||
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
|
||||
json=rec, timeout=5)
|
||||
r.raise_for_status()
|
||||
|
||||
|
||||
def flush_offline_reports() -> int:
|
||||
"""重连后补报此前暂存的离线记录;返回补报条数。"""
|
||||
if not reports_path.is_file():
|
||||
return 0
|
||||
sent = 0
|
||||
pending = []
|
||||
try:
|
||||
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
|
||||
for ln in lines:
|
||||
try:
|
||||
rec = json.loads(ln)
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
_push_via_tempfile(rec)
|
||||
sent += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pending.append(ln) # 仍失败则保留下次再补
|
||||
if not pending:
|
||||
reports_path.unlink(missing_ok=True) # 全部成功则清空
|
||||
else:
|
||||
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
return sent
|
||||
@@ -0,0 +1,114 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主插件元数据 / 平台权限解析。
|
||||
|
||||
- 插件元数据由 plugin.json(manifest) 驱动,离线与旧插件兼容
|
||||
- 平台/插件白名单来自中心机,按账号过滤(三态降级:授权集 / 空集防越权 / None 离线兜底全量)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
"""组装插件元数据(manifest 驱动)。
|
||||
|
||||
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
|
||||
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
|
||||
"""
|
||||
manifest = _read_own_manifest(p)
|
||||
name = (manifest or {}).get("name") or p.name
|
||||
description = (manifest or {}).get("description")
|
||||
if description is None:
|
||||
description = p.description
|
||||
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
|
||||
if fields is None:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
|
||||
def _read_own_manifest(p) -> dict | None:
|
||||
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
|
||||
try:
|
||||
mod = sys.modules.get(type(p).__module__)
|
||||
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
|
||||
if not jar or not jar.is_file():
|
||||
return None
|
||||
return json.loads(jar.read_text(encoding="utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _fields_from_schema(schema: dict) -> list | None:
|
||||
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
|
||||
if not schema or schema.get("type") != "object" or not schema.get("properties"):
|
||||
return None
|
||||
out = []
|
||||
for key, prop in schema["properties"].items():
|
||||
item = {"key": key, "label": prop.get("title", key),
|
||||
"default": prop.get("default", "")}
|
||||
t = prop.get("type", "string")
|
||||
if t == "integer" or t == "number":
|
||||
item["type"] = "int"
|
||||
elif t == "string" and "enum" in prop:
|
||||
item["type"] = "select"
|
||||
item["options"] = prop["enum"]
|
||||
else:
|
||||
item["type"] = "text"
|
||||
d = prop.get("description")
|
||||
if d:
|
||||
item["description"] = d
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def _account_allowed_platforms(account: str) -> set | None:
|
||||
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/platforms/allowed",
|
||||
params={"account": account}, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
return set(r.json().get("allowed", []))
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
|
||||
def _cloud_plugin_ids(account: str) -> set | None:
|
||||
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
|
||||
|
||||
降级策略(三态):
|
||||
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
|
||||
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
|
||||
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
|
||||
"""
|
||||
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
|
||||
if not token or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
headers={"Authorization": f"Bearer {token}"}, timeout=5)
|
||||
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
|
||||
return None
|
||||
if r.status_code == 401:
|
||||
return set()
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return {p["id"] for p in r.json().get("plugins", [])}
|
||||
@@ -0,0 +1,108 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.core.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
- get_session / get_user_id 在本进程内直接读取共享 cookie 文件重建,不依赖主进程
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
if getattr(sys, "frozen", False):
|
||||
root = os.path.dirname(os.path.abspath(sys.executable)) # 打包运行:exe 同级目录
|
||||
os.chdir(root)
|
||||
return root
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__))))) # core/plugin_runner.py → 项目根
|
||||
if root not in sys.path:
|
||||
sys.path.insert(0, root)
|
||||
return root
|
||||
|
||||
|
||||
_ROOT = _bootstrap_paths()
|
||||
try:
|
||||
os.chdir(_ROOT)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
|
||||
try:
|
||||
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
_PROTO.flush()
|
||||
except Exception: # noqa: BLE001 通道已关则静默
|
||||
pass
|
||||
|
||||
|
||||
def _run() -> int:
|
||||
# 协议通道 = 原始 sys.stdout(fd1);把插件的 print 改道到 stderr,防止污染协议行
|
||||
global _PROTO
|
||||
_PROTO = sys.stdout
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
plugin_id = args.get("--plugin") or (sys.argv[sys.argv.index("--plugin") + 1]
|
||||
if "--plugin" in sys.argv else "")
|
||||
if not plugin_id:
|
||||
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
|
||||
return 2
|
||||
# 宿主透传的插件白名单:与宿主进程加载集保持一致(未传 = 全量)
|
||||
allowed_arg = (sys.argv[sys.argv.index("--allowed") + 1]
|
||||
if "--allowed" in sys.argv else "")
|
||||
allowed = {s for s in allowed_arg.split(",") if s} if allowed_arg else None
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
fields: dict = {}
|
||||
try:
|
||||
_line = sys.stdin.readline().strip()
|
||||
if _line:
|
||||
fields = json.loads(_line) or {}
|
||||
except Exception as _e: # noqa: BLE001
|
||||
fields = {}
|
||||
|
||||
class _ChildContext(RunContext):
|
||||
"""子进程版上下文:log/progress 经 stdout 回传;登录态在本进程重建。"""
|
||||
|
||||
def __init__(self, run_id: str, plugin_id: str, auth):
|
||||
super().__init__(hub=None, run_id=run_id, plugin_id=plugin_id, auth=auth)
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
_emit({"ev": "log", "level": level, "msg": str(msg)})
|
||||
|
||||
def progress(self, pct: int):
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins(allowed)
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
result = plugin.run(fields, ctx)
|
||||
_emit({"ev": "result", "ok": True, "result": result})
|
||||
return 0
|
||||
except KeyError:
|
||||
_emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"})
|
||||
return 3
|
||||
except Exception as _e: # noqa: BLE001 插件顶层兜底
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
_emit({"ev": "result", "ok": False, "error": str(_e)})
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_run())
|
||||
@@ -0,0 +1,185 @@
|
||||
# -*- 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 zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 30 # 包下载超时(秒)
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
|
||||
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 sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
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",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["failed"])
|
||||
return result
|
||||
@@ -0,0 +1,165 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||||
|
||||
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
|
||||
由 Windows Job Object 整树托管(含浏览器孙进程)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import scheduler as _scheduler
|
||||
from webhost.backend.core import winjob as _winjob
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core import state as _st
|
||||
from webhost.backend.core.hub import HUB
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||||
"""
|
||||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||||
|
||||
# 打包运行(frozen):拉起同级 37du-host-runner.exe(console 壳,内置同一套执行代码)
|
||||
if getattr(sys, "frozen", False):
|
||||
runner_exe = Path(sys.executable).with_name("37du-host-runner.exe")
|
||||
cmd = [str(runner_exe), "--plugin", plugin.id, "--run", run_id]
|
||||
root = Path(sys.executable).resolve().parent
|
||||
else:
|
||||
runner = Path(__file__).with_name("plugin_runner.py")
|
||||
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
|
||||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||||
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
job.assign(proc)
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": f"拉起执行子进程失败: {e}"})
|
||||
return
|
||||
|
||||
def _publish_event(ev: dict):
|
||||
t = ev.get("ev")
|
||||
if t == "log":
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||||
elif t == "progress":
|
||||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"pct": int(ev.get("pct", 0))})
|
||||
|
||||
_result: dict = {}
|
||||
_rlock = threading.Lock()
|
||||
|
||||
def _drain_out():
|
||||
for line in proc.stdout:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
ev = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if ev.get("ev") in ("log", "progress"):
|
||||
_publish_event(ev)
|
||||
elif ev.get("ev") == "result":
|
||||
with _rlock:
|
||||
_result.update(ev)
|
||||
|
||||
def _drain_err():
|
||||
for line in proc.stderr:
|
||||
line = line.strip()
|
||||
if line:
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "ERROR", "msg": line})
|
||||
|
||||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||||
t_out.start(); t_err.start()
|
||||
|
||||
try:
|
||||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||||
proc.stdin.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
timed_out = False
|
||||
try:
|
||||
proc.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
timed_out = True
|
||||
try:
|
||||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||||
proc.wait(timeout=5)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
pass
|
||||
|
||||
try:
|
||||
with _rlock:
|
||||
ev = dict(_result)
|
||||
if ev:
|
||||
ok = bool(ev.get("ok"))
|
||||
_st._set_run(run_id, status="done" if ok else "error",
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
else:
|
||||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
|
||||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||||
try:
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id) or {}
|
||||
account = run.get("account", "")
|
||||
status = "done" if run.get("status") == "done" else \
|
||||
("running" if run.get("status") == "running" else "error")
|
||||
msg = run.get("error") or ""
|
||||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||||
licensing.report(account=account, device_id="",
|
||||
plugin_id=plugin_id, version=run.get("version", ""),
|
||||
status=status, msg=msg, duration_sec=duration)
|
||||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||||
_LOGGER.warning("运行上报失败:%s", _exc)
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""设备级单活调度器:整机同一时刻只运行一个插件进程。
|
||||
|
||||
- active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。
|
||||
- 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。
|
||||
- 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活;
|
||||
启动失败回滚到"空闲",不让半激活状态阻塞后续启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
ACTIVE_PATH = _APP_DATA / "active.json"
|
||||
|
||||
# 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。
|
||||
_SCHED_COND = threading.Condition()
|
||||
|
||||
|
||||
def init_active() -> None:
|
||||
"""初始化 active.json(无则写入空闲态),并确保数据目录可写。
|
||||
进程启动时若残留 running/switching(上次异常退出/断电),复位为空闲,
|
||||
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
if not ACTIVE_PATH.is_file():
|
||||
write_active(userId="", pluginId="", version="", status="idle")
|
||||
elif read_active().get("status") in ("running", "switching"):
|
||||
_LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲")
|
||||
write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="")
|
||||
|
||||
|
||||
def read_active() -> dict:
|
||||
try:
|
||||
d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {}
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
|
||||
def _is_busy() -> bool:
|
||||
return read_active().get("status") in ("running", "switching")
|
||||
|
||||
|
||||
def write_active(**kw) -> None:
|
||||
"""写回 active.json(保留既有键,仅更新传入字段)。"""
|
||||
d = read_active()
|
||||
d.update(kw)
|
||||
d.setdefault("userId", "")
|
||||
d.setdefault("pluginId", "")
|
||||
d.setdefault("version", "")
|
||||
d.setdefault("status", "idle")
|
||||
d.setdefault("startedAt", "")
|
||||
d.setdefault("runId", "")
|
||||
try:
|
||||
# 原子写:先写临时文件再 os.replace,避免写入中断留下半截 JSON 被误读
|
||||
tmp = ACTIVE_PATH.with_suffix(".json.tmp")
|
||||
tmp.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
|
||||
os.replace(tmp, ACTIVE_PATH)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("写 active.json 失败:%s", _exc)
|
||||
|
||||
|
||||
def current() -> dict:
|
||||
"""当前活动插件(空闲则返回空映射)。"""
|
||||
return read_active()
|
||||
|
||||
|
||||
def is_active(plugin_id: str) -> bool:
|
||||
"""当前设备是否正在跑该插件。"""
|
||||
a = read_active()
|
||||
return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id)
|
||||
|
||||
|
||||
def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict:
|
||||
"""设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。
|
||||
|
||||
- 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。
|
||||
- `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。
|
||||
- 启动失败回滚到"空闲"并唤醒等待者。
|
||||
"""
|
||||
with _SCHED_COND:
|
||||
while _is_busy():
|
||||
_SCHED_COND.wait()
|
||||
write_active(status="switching", startedAt=_now())
|
||||
try:
|
||||
run_id = start_fn()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
return {"ok": False, "error": f"启动失败:{_exc}"}
|
||||
write_active(userId=user, pluginId=plugin_id, version=version,
|
||||
status="running", runId=run_id, startedAt=_now())
|
||||
return {"ok": True, "run_id": run_id}
|
||||
|
||||
|
||||
def mark_done(plugin_id: str, run_id: str) -> None:
|
||||
"""运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。"""
|
||||
with _SCHED_COND:
|
||||
a = read_active()
|
||||
if a.get("pluginId") == plugin_id and a.get("runId") == run_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
elif a.get("pluginId") == plugin_id:
|
||||
write_active(status="idle")
|
||||
_SCHED_COND.notify_all()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
|
||||
|
||||
会话状态(token->account 活跃ts)只在此模块定义;admin/dingtalk/meta 等路由经本模块访问。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
|
||||
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
|
||||
SESSION_COOKIE = "cp_session"
|
||||
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
|
||||
_SESS_TTL = 7 * 24 * 3600
|
||||
_SESS: dict[str, tuple] = {}
|
||||
_SESS_LOCK = threading.Lock()
|
||||
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
|
||||
# 打包运行(frozen)时落盘到 exe 同级目录
|
||||
_SESS_FILE = (Path(sys.executable).resolve().parent if getattr(sys, "frozen", False)
|
||||
else Path(__file__).resolve().parents[1]) / "_cp_sessions.json"
|
||||
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _sess_persist():
|
||||
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
|
||||
try:
|
||||
with _SESS_LOCK:
|
||||
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
|
||||
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("本机会话持久化失败: %s", _exc)
|
||||
|
||||
|
||||
def _sess_load():
|
||||
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
|
||||
if not _SESS_FILE.is_file():
|
||||
return
|
||||
try:
|
||||
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
_now = time.time()
|
||||
with _SESS_LOCK:
|
||||
for _t, _it in (_raw or {}).items():
|
||||
try:
|
||||
_a, _ts = _it[0], float(_it[1])
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
continue
|
||||
if _now - _ts <= _SESS_TTL:
|
||||
_SESS[_t] = (_a, _ts)
|
||||
|
||||
|
||||
def _sess_account(request) -> str:
|
||||
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
account = ""
|
||||
with _SESS_LOCK:
|
||||
item = _SESS.get(token)
|
||||
if item:
|
||||
_account, _ts = item
|
||||
if time.time() - _ts <= _SESS_TTL:
|
||||
_SESS[token] = (_account, time.time()) # 滑动续期
|
||||
account = _account
|
||||
else:
|
||||
_SESS.pop(token, None)
|
||||
if account:
|
||||
_sess_persist() # 滑动续期也落盘,重启后仍有效
|
||||
return account
|
||||
|
||||
|
||||
def _require_login(request: Request) -> str:
|
||||
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
raise HTTPException(401, "未登录:请先登录统一账户")
|
||||
return account
|
||||
|
||||
|
||||
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机壳子(主程序)自动更新:自动下载新版安装包,由用户点击触发静默升级重启。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检查+下载:启动时后台检查控制面 /api/shell/version,版本落后则自动把新版安装包
|
||||
下载到 %LOCALAPPDATA%\\37duAutomation\\shell\\(本地缓存,不打断用户)。
|
||||
2. 应用:前端提示"发现新版本"后用户点击 → apply_update() 运行安装包
|
||||
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
|
||||
安装完成由 [Run] 自动重启新版本主程序。
|
||||
3. 离线/控制面不可达/校验失败:静默跳过,不影响使用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
|
||||
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
|
||||
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
|
||||
_PENDING: dict = {}
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。"""
|
||||
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 ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
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 check_and_download() -> dict | None:
|
||||
"""检查壳子更新并自动下载安装包到本地缓存。有可用更新返回 {version, notes};否则 None。"""
|
||||
cur = local_shell_version()
|
||||
if not cur or not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
|
||||
headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
info = r.json()
|
||||
except Exception as _exc: # noqa: BLE001 离线/不可达
|
||||
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
|
||||
return None
|
||||
if not info.get("available") or not info.get("version"):
|
||||
return None
|
||||
cloud = str(info["version"])
|
||||
if not _version_lt(cur, cloud):
|
||||
return None
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/pkg",
|
||||
headers=_headers(), timeout=300)
|
||||
r.raise_for_status()
|
||||
data = r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
|
||||
return None
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(data).hexdigest() != expect:
|
||||
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
|
||||
return None
|
||||
try:
|
||||
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
|
||||
pkg.write_bytes(data)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
|
||||
return None
|
||||
_PENDING["version"] = cloud
|
||||
_PENDING["notes"] = info.get("notes", "")
|
||||
_LOGGER.info("壳子新版本已下载待应用:%s → %s(%d 字节)", cur, cloud, len(data))
|
||||
return {"version": cloud, "notes": _PENDING["notes"]}
|
||||
|
||||
|
||||
def cached_pkg(version: str) -> Path | None:
|
||||
"""本地缓存的指定版本安装包路径;不存在返回 None。"""
|
||||
p = _SHELL_CACHE / f"setup-37du-host-{version}.exe"
|
||||
return p if p.is_file() else None
|
||||
|
||||
|
||||
def pending_status() -> dict:
|
||||
"""当前更新状态(供前端提示):当前版本 / 待应用新版本 / 是否已下载。"""
|
||||
return {
|
||||
"current": local_shell_version(),
|
||||
"new": _PENDING.get("version", ""),
|
||||
"notes": _PENDING.get("notes", ""),
|
||||
"downloaded": bool(_PENDING.get("version"))
|
||||
and cached_pkg(_PENDING.get("version", "")) is not None,
|
||||
}
|
||||
|
||||
|
||||
def apply_update() -> None:
|
||||
"""运行新版安装包静默覆盖安装并退出本进程(升级完成后由 Inno 重启新版本)。
|
||||
|
||||
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
|
||||
"""
|
||||
version = _PENDING.get("version", "")
|
||||
pkg = cached_pkg(version)
|
||||
if not pkg:
|
||||
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
|
||||
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
time.sleep(1) # 给安装器接管进程,随后退出让 Inno CloseApplications 收尾
|
||||
os._exit(0)
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。
|
||||
|
||||
- ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写
|
||||
(`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`),
|
||||
避免 from-import 复制绑定读不到最新值。
|
||||
- RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。
|
||||
依赖方向:state ← 领域逻辑与路由模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
|
||||
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
|
||||
for p in platform_auth.platforms()}
|
||||
|
||||
# 运行会话:run_id -> {status, account, result, error}
|
||||
RUNS: dict = {}
|
||||
RUN_LOCK = threading.Lock()
|
||||
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
|
||||
|
||||
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
|
||||
ALLOWED: set | None = None
|
||||
|
||||
|
||||
def set_allowed(v: set | None) -> None:
|
||||
global ALLOWED
|
||||
ALLOWED = v
|
||||
|
||||
|
||||
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
|
||||
_NS_LOCKS: dict[str, threading.Lock] = {}
|
||||
_NS_GUARD = threading.Lock()
|
||||
|
||||
|
||||
def _ns_gate(platform: str) -> threading.Lock:
|
||||
key = (platform or "").strip() or "local"
|
||||
with _NS_GUARD:
|
||||
if key not in _NS_LOCKS:
|
||||
_NS_LOCKS[key] = threading.Lock()
|
||||
return _NS_LOCKS[key]
|
||||
|
||||
|
||||
def _set_run(run_id: str, **kw) -> None:
|
||||
"""更新运行记录字段(保留 account 等既有键)。"""
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if run is not None:
|
||||
run.update(kw)
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Windows Job Object 封装:插件执行子进程整树托管。
|
||||
|
||||
- KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的
|
||||
浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程;
|
||||
- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。
|
||||
非 Windows 平台所有方法安全降级为 no-op。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import logging
|
||||
import sys
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_AVAILABLE = sys.platform == "win32"
|
||||
if _AVAILABLE:
|
||||
try:
|
||||
_K32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
except AttributeError: # 非 Windows 误导入
|
||||
_AVAILABLE = False
|
||||
|
||||
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
||||
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000
|
||||
_JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100
|
||||
_PROCESS_SET_QUOTA = 0x0100
|
||||
_PROCESS_TERMINATE = 0x0001
|
||||
|
||||
|
||||
if _AVAILABLE:
|
||||
class _IO_COUNTERS(ctypes.Structure):
|
||||
_fields_ = [(n, ctypes.c_uint64) for n in (
|
||||
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
|
||||
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
|
||||
|
||||
class _BASIC_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("PerProcessUserTimeLimit", ctypes.c_int64),
|
||||
("PerJobUserTimeLimit", ctypes.c_int64),
|
||||
("LimitFlags", ctypes.c_uint32),
|
||||
("MinimumWorkingSetSize", ctypes.c_size_t),
|
||||
("MaximumWorkingSetSize", ctypes.c_size_t),
|
||||
("ActiveProcessLimit", ctypes.c_uint32),
|
||||
("Affinity", ctypes.c_size_t),
|
||||
("PriorityClass", ctypes.c_uint32),
|
||||
("SchedulingClass", ctypes.c_uint32),
|
||||
]
|
||||
|
||||
class _EXT_LIMIT_INFO(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("BasicLimitInformation", _BASIC_LIMIT_INFO),
|
||||
("IoInfo", _IO_COUNTERS),
|
||||
("ProcessMemoryLimit", ctypes.c_size_t),
|
||||
("JobMemoryLimit", ctypes.c_size_t),
|
||||
("PeakProcessMemoryUsed", ctypes.c_size_t),
|
||||
("PeakJobMemoryUsed", ctypes.c_size_t),
|
||||
]
|
||||
|
||||
|
||||
class Job:
|
||||
"""一次性的插件子进程作业。用法:job = Job(); job.assign(proc); …; job.terminate()/close()。"""
|
||||
|
||||
def __init__(self, max_mem_mb: int = 0):
|
||||
self._h = None
|
||||
if not _AVAILABLE:
|
||||
return
|
||||
h = _K32.CreateJobObjectW(None, None)
|
||||
if not h:
|
||||
_LOGGER.warning("创建 Job Object 失败(winerror=%s),退化为无作业托管", ctypes.get_last_error())
|
||||
return
|
||||
info = _EXT_LIMIT_INFO()
|
||||
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if max_mem_mb > 0:
|
||||
info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY
|
||||
info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024
|
||||
if not _K32.SetInformationJobObject(
|
||||
h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
ctypes.byref(info), ctypes.sizeof(info)):
|
||||
_LOGGER.warning("设置 Job Object 限制失败(winerror=%s)", ctypes.get_last_error())
|
||||
self._h = h
|
||||
|
||||
def assign(self, proc) -> None:
|
||||
"""把子进程(及其后代)纳入作业托管。"""
|
||||
if not self._h:
|
||||
return
|
||||
if not _K32.AssignProcessToJobObject(self._h, int(proc._handle)):
|
||||
_LOGGER.warning("子进程纳入 Job Object 失败(winerror=%s)", ctypes.get_last_error())
|
||||
|
||||
def terminate(self, exit_code: int = 1) -> None:
|
||||
"""终止作业内全部进程(整树强杀,含浏览器等孙进程)。"""
|
||||
if self._h:
|
||||
_K32.TerminateJobObject(self._h, exit_code)
|
||||
|
||||
def close(self) -> None:
|
||||
"""关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。"""
|
||||
if self._h:
|
||||
_K32.CloseHandle(self._h)
|
||||
self._h = None
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
|
||||
|
||||
业务逻辑已按领域拆到 sibling 模块:
|
||||
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
|
||||
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
|
||||
- apis/ 路由子包(admin / dingtalk / meta / runs)
|
||||
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import socket
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
HUB.bind(asyncio.get_running_loop())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
|
||||
try:
|
||||
from webhost.backend.core.session import _SESS
|
||||
_accts = {_a for _, (_a, _t) in _SESS.items()}
|
||||
except Exception: # noqa: BLE001
|
||||
_accts = set()
|
||||
if _accts:
|
||||
_acct = next(iter(_accts))
|
||||
|
||||
def _boot_sync() -> None:
|
||||
try:
|
||||
from webhost.backend.core.plugin_sync import sync_plugins
|
||||
sync_plugins(_acct)
|
||||
load_plugins(_st.ALLOWED, reload=True)
|
||||
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
|
||||
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
|
||||
_LOGGER.warning("启动插件更新失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_sync, daemon=True).start()
|
||||
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级
|
||||
def _boot_shell_check() -> None:
|
||||
try:
|
||||
from webhost.backend.core.shell_updater import check_and_download
|
||||
check_and_download()
|
||||
except Exception as _exc: # noqa: BLE001 检查失败不阻断启动
|
||||
_LOGGER.warning("启动壳子更新检查失败:%s", _exc)
|
||||
|
||||
threading.Thread(target=_boot_shell_check, daemon=True).start()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
|
||||
|
||||
if config.DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
def _port_free(port: int) -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", port)) != 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
print(f"[webhost] port {config.PORT} free = {_port_free(config.PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")
|
||||
@@ -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) 一次性加载,以便阶段二可传入按账号动态计算的权限白名单。
|
||||
@@ -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()
|
||||
@@ -0,0 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost.backend.shared:webhost 共享模块(登录/导出/封存拉取)
|
||||
|
||||
原 desktop/shared 迁入,webhost 单一真源,完全自包含、不依赖其他目录。
|
||||
与 workflows/(影刀版)为**独立维护的两份副本**,修改时若需同步,
|
||||
请手动将 workflows 对应文件复制覆盖到本目录。
|
||||
"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- 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)
|
||||
@@ -0,0 +1,241 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: oa_login.py
|
||||
@Description: OA 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duOA登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 OA 系统影刀脚本(请假/加班/社保增减等)复用。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 oa_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 SessionPage / requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=OA 登录页 URL
|
||||
SUCCESS_KEYWORD=OA 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
oa_validate_url=(可选,.env/系统变量)轻量会话校验接口 URL;默认使用 sumTodoCount 待办统计接口
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv
|
||||
|
||||
入口:
|
||||
main(force=True) 影刀自定义指令调用入口,force 传 True/False(是否强制重新登录),返回 JSON 安全 dict
|
||||
python oa_login.py 独立运行(等价于 main(force=True))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from DrissionPage import ChromiumPage
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
|
||||
# ================== 共享路径(与 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, 'oa_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://oa.37du.co/login.jsp'
|
||||
SUCCESS_KEYWORD = 'https://oa.37du.co/sys/portal/page.jsp'
|
||||
USERNAME = os.getenv('oa_login_username', '')
|
||||
PASSWORD = os.getenv('oa_login_password', '')
|
||||
|
||||
# OA 会话校验接口:cookies 有效时返回 JSON,失效时被重定向到登录页返回 HTML
|
||||
TODO_COUNT_URL = "https://oa.37du.co/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
USERNAME_INPUT = 'tag:input@name=j_username'
|
||||
PASSWORD_INPUT = 'tag:input@name=j_password'
|
||||
LOGIN_BTN = '.lui_login_button_div_c'
|
||||
|
||||
TIMEOUT = 10
|
||||
WAIT_AFTER_LOAD = 2
|
||||
|
||||
|
||||
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_oa_session_valid():
|
||||
"""API 轻量校验 OA cookies:请求 oa_validate_url(默认 sumTodoCount 待办统计接口),
|
||||
返回 JSON 视为 cookies 有效;被重定向到登录页返回 HTML 即视为失效。
|
||||
|
||||
与业务脚本(overtime_approval/leave_approval/social_change 等)使用同一套接口与校验逻辑:
|
||||
requests.Session + Chrome UA + 仅注入 37du.co 域 cookies,GET method=sumTodoCount。
|
||||
"""
|
||||
validate_url = os.getenv('oa_validate_url', '').strip() or TODO_COUNT_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.get(validate_url, params={"method": "sumTodoCount"}, 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
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login(timeout=TIMEOUT, wait_after_load=WAIT_AFTER_LOAD):
|
||||
"""打开浏览器完成 OA 账号密码登录,成功保存 cookies。"""
|
||||
page = ChromiumPage()
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(wait_after_load)
|
||||
|
||||
username_input = page.ele(USERNAME_INPUT)
|
||||
if not username_input:
|
||||
raise RuntimeError("未找到用户名输入框")
|
||||
username_input.input(USERNAME)
|
||||
page.wait(0.5)
|
||||
|
||||
password_input = page.ele(PASSWORD_INPUT)
|
||||
if not password_input:
|
||||
raise RuntimeError("未找到密码输入框")
|
||||
password_input.input(PASSWORD)
|
||||
page.wait(0.5)
|
||||
|
||||
login_button = page.ele(LOGIN_BTN)
|
||||
if not login_button:
|
||||
raise RuntimeError("未找到登录按钮")
|
||||
login_button.click()
|
||||
page.wait(0.5)
|
||||
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print(f"登录成功!当前 URL: {page.url}")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
|
||||
error_elem = page.ele('.error-msg') or page.ele('.alert-danger')
|
||||
if error_elem:
|
||||
print(f"登录失败,提示: {error_elem.text}")
|
||||
raise RuntimeError(f"登录超时,当前 URL: {page.url}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 OA 登录态并缓存 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": "登录配置缺失(oa_login_url / oa_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(oa_login_username / oa_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_oa_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 OA 登录态")
|
||||
_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(force=True):
|
||||
"""
|
||||
影刀自定义指令「37duOA登录」调用入口。
|
||||
force: bool 是否强制重新登录(默认 True,便于本地独立运行直接刷新登录态)
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
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=True)
|
||||
print("最终结果:", result)
|
||||
@@ -0,0 +1,401 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: org_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 组织维护(组织设置)导出(影刀共享指令,单文件自包含)——从共享登录态读取
|
||||
HR cookies,调用组织维护台账实时查询接口(queryRealTimeData.mc)分页拉取
|
||||
全部组织数据,转换为页面 18 列格式后导出 Excel。纯接口实现,无需浏览器。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du组织维护导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
output_path Excel 保存路径(默认 D:\\资料\\人资\\组织维护\\组织维护.xlsx)
|
||||
2. 命令行:python org_export.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 export_orgs(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_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')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
ORG_QUERY_URL = "https://hr.37du.co/RedseaPlatform/hrRoster/110118b4-b094-11ea-b588-14187743d052/queryRealTimeData.mc"
|
||||
ORG_TABLE_ID = "assemble-pt_organzation"
|
||||
ORG_ROSTER_ID = "110118b4-b094-11ea-b588-14187743d052"
|
||||
PAGE_MAX_SIZE = 500 # 每页最大条数
|
||||
|
||||
# 组织维护查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 由自实现前端加密动态生成(等价抓包原始串,即 in_use in ('1') 条件);
|
||||
# 需要追加/修改查询条件时改 ORG_QUERY_CONDITIONS 后由 encode_common_query 重新加密
|
||||
ORG_QUERY_CONDITIONS = [
|
||||
build_condition("`pt_organzation.IN_USE`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
]
|
||||
|
||||
ORG_QUERY_BASE_PARAMS = {
|
||||
"menuName": "组织维护",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": encode_common_query(ORG_QUERY_CONDITIONS),
|
||||
"newCondition": "",
|
||||
"urlConditions": "_t%3A1788589944798%23clickFlag%3Atrue%23cancelNodeClick%3A1%23treePermitType%3Apermit%23useSealTreeData%3A0%23menuName%3A%E7%BB%84%E7%BB%87%E7%BB%B4%E6%8A%A4%23_t%3A1788589944798%23",
|
||||
"exportConfig": "",
|
||||
"tableId": ORG_TABLE_ID,
|
||||
"rosterId": ORG_ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http://hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
}
|
||||
|
||||
# ---------- 接口字段 -> 页面列名映射(「序号」接口不返回,转换时按行号生成;
|
||||
# 分管部门对应 pt_structure2.ORG_ALIAS,当前数据未使用但列位保留) ----------
|
||||
ORG_FIELD_MAP = [
|
||||
("pt_organzation.ORG_NAME", "组织名称"),
|
||||
("pt_organzation.ORG_CODE", "组织编号"),
|
||||
("pt_organzation.ORG_TYPE_CODE", "组织类型"),
|
||||
("pt_structure1.ORG_ALIAS", "上级组织"),
|
||||
("org_principal_staff_name_select.org_principal_staff_name", "组织负责人"),
|
||||
("pt_structure2.ORG_ALIAS", "分管部门"),
|
||||
("branch_leader_name_select.branch_leader_name", "分管领导"),
|
||||
("pt_organzation.BEGIN_DATE", "成立日期"),
|
||||
("pt_orgnization_extend.FOUND_DOC_NUM", "成立文号"),
|
||||
("pt_organzation.CANT_CODE", "所属地区"),
|
||||
("pt_organzation.office_address", "办公地址"),
|
||||
("pt_organzation.remarks", "备注"),
|
||||
("pt_orgnization_extend.FOUND_REASON", "成立原因"),
|
||||
("pt_structure.ORG_FULL_PATH", "组织全路径"),
|
||||
("pt_organzation.create_time", "创建时间"),
|
||||
("pt_organzation.IN_USE", "使用状态"),
|
||||
("pt_organzation_ext.ext_payday", "发薪日"),
|
||||
]
|
||||
|
||||
# 使用状态编码 -> 文字
|
||||
IN_USE_MAP = {"1": "在用", "0": "停用"}
|
||||
|
||||
# ---------- 默认导出参数(内置默认值,便于分发共享;如需覆盖请直接改这里或由 main(args) 传参) ----------
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
|
||||
# ---------- 项目级重试次数(单页请求失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 hr.37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
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 or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成组织维护查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 接口请求 ====================
|
||||
def _fetch_org_page_once(session, page_no, page_size):
|
||||
"""请求单页组织维护数据(单次请求,不含重试)。"""
|
||||
params = ORG_QUERY_BASE_PARAMS.copy()
|
||||
params.update(get_date_params())
|
||||
params.update({
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"_t": str(int(time.time() * 1000)),
|
||||
})
|
||||
resp = session.request("POST", ORG_QUERY_URL, params=params, timeout=30)
|
||||
if not resp or resp.status_code != 200:
|
||||
raise RuntimeError(f"组织维护接口状态码异常: {getattr(resp, 'status_code', '无响应')}")
|
||||
if _is_expired(resp.text):
|
||||
raise LoginRequiredError("HR 登录态已失效,请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _fetch_org_page(session, page_no, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页组织维护数据(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _fetch_org_page_once(session, page_no, page_size)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("组织维护第%d页请求第 %d 次失败:%s,%.1f 秒后重试", page_no, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("组织维护第%d页连续 %d 次请求失败,放弃", page_no, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_all_orgs(session):
|
||||
"""分页抓取全部组织维护数据(在职组织,in_use=1),返回接口原始记录列表。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
total_page = None
|
||||
while True:
|
||||
data = _fetch_org_page(session, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"组织维护第{page_no}页接口返回错误:{data.get('meg') or data.get('des')}")
|
||||
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("组织维护无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
|
||||
if total_page is None:
|
||||
logger.info("总记录数:%s,总页数:%s", data.get("count"), data.get("pageCount"))
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("组织维护已抓取 %d/%s 页,累计 %d/%s 条",
|
||||
page_no, total_page, len(all_rows), data.get("count"))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2) # 轻微限速,避免触发风控
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 字段转换 ====================
|
||||
def to_org_rows(datalist):
|
||||
"""将接口原始记录转换为页面列名顺序的字典列表(18 列,含序号)。"""
|
||||
rows = []
|
||||
for i, r in enumerate(datalist, 1):
|
||||
row = {"序号": i}
|
||||
for key, name in ORG_FIELD_MAP:
|
||||
value = r.get(key)
|
||||
if name == "使用状态":
|
||||
value = IN_USE_MAP.get(str(value), value)
|
||||
elif name == "成立日期" and value:
|
||||
value = str(value).split(" ")[0] # 去掉 00:00:00 时分秒
|
||||
row[name] = value
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_orgs(output_path=None):
|
||||
"""查询全部组织维护数据并导出 Excel(18 列,与页面列一致)。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
(导出文件路径, 数据条数)
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 请求失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
|
||||
logger.info("===== 开始组织维护导出,保存路径:%s =====", output_path)
|
||||
session = _build_session()
|
||||
datalist = fetch_all_orgs(session)
|
||||
if not datalist:
|
||||
raise RuntimeError("组织维护接口未查询到任何数据")
|
||||
|
||||
rows = to_org_rows(datalist)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
pd.DataFrame(rows).to_excel(output_path, index=False)
|
||||
logger.info("===== 组织维护导出完成:共 %d 条,已保存 %s =====", len(rows), output_path)
|
||||
return output_path, len(rows)
|
||||
|
||||
|
||||
def main(output_path=None):
|
||||
"""影刀自定义指令入口「37du组织维护导出」。
|
||||
|
||||
Args:
|
||||
output_path: Excel 保存路径(缺省用内置默认值 DEFAULT_OUTPUT_PATH)
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "count": int}
|
||||
save_path 即导出的 Excel 文件路径。
|
||||
"""
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
try:
|
||||
save_path, count = export_orgs(output_path)
|
||||
return {"success": True, "save_path": save_path, "count": count}
|
||||
except Exception as e:
|
||||
logger.error("组织维护导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "save_path": output_path}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
output_path = r"D:\资料\人资\组织维护\组织维护.xlsx"
|
||||
main(output_path)
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: roster_export_api.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-05
|
||||
@Description: 员工花名册导出(影刀共享指令,单文件自包含)——纯接口版。
|
||||
与浏览器版 roster_export.py 的 main(...) 调用签名完全一致:
|
||||
main(statuses, leave_start, leave_end, template, output_path, download_dir)
|
||||
底层改为:访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)->
|
||||
接收 "--end--|文件路径" 推送 -> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
无需 DrissionPage/浏览器,字典翻译(星级/参保类型/职衔/职级等)由服务端完成。
|
||||
@Version: 1.0.0
|
||||
|
||||
运行方式:
|
||||
1. 影刀:注册为自定义指令「37du花名册导出」,main(...) 关键字传参(缺省用内置默认值,见 DEFAULT_* 常量)
|
||||
statuses 在职状态,str "在职" / "在职,离职" 或 list(默认 在职+离职)
|
||||
leave_start 离职时间开始 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
leave_end 离职时间结束 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template 自定义导出模板名(默认 员工基础信息)
|
||||
output_path 合并后 Excel 保存路径(默认 D:\\资料\\人资\\花名册\\花名册.xlsx)
|
||||
download_dir 单状态临时文件目录(默认 D:\\资料\\人资\\花名册\\download,合并后自动清理)
|
||||
2. 命令行:python roster_export_api.py 直接运行(__main__ 中按示例传参)
|
||||
3. 业务脚本:懒加载本模块调用 main(...) / export_roster(...)
|
||||
|
||||
依赖安装(启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
|
||||
pip install requests pandas openpyxl websocket-client
|
||||
|
||||
登录态:读取 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json(由「37duHR登录」指令写入);
|
||||
缺失/失效时不自动补登,抛出提示先重新执行「37duHR登录」指令。
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(启动校验:全部必须预先安装,不懒加载) ====================
|
||||
try:
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(共享指令要求所有库在启动前装齐,不懒加载)。\n"
|
||||
"请先执行安装:\n"
|
||||
" pip install requests pandas openpyxl websocket-client\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,正常 INFO 不输出大体积 JSON) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
# 自定义 Base64 字符表(索引0~63,64为填充字符)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_PAD_CHAR = '7' # 填充字符(索引64)
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
# 1. JSON(无空格,同 JSON.stringify) 2. URI 编码(不编码 ! ' ( ) * - . _ ~)
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
# 3. 自定义 Base64 + 盐值 4. 重排:前2位 + 后3位 + 中间部分
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 路径 & 常量配置 ====================
|
||||
# 缓存统一放在 %LOCALAPPDATA%\37duAutomation(影刀版共享目录)
|
||||
_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')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
# 自定义导出模板定义(页面「自定义导出」弹窗同款接口:列表拿 id -> 详情拿 exportField)
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取;登录用户变更时需同步更新 currentUserId / currentStaffId 等)
|
||||
# commonQuery 在导出时按「在职/离职」条件动态加密生成
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致)
|
||||
"员工基础信息": ",".join([
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.leaveOffice_date", # 离职时间
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"hr_staff_base_ext.ext_technician_code", # 技师工号
|
||||
"hr_staff_base_ext.ext_star_level", # 星级
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"pt_staff_stru.POST_LEVEL_ID", # 职衔
|
||||
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
|
||||
"pt_post_level.ext_grade_name", # 职等
|
||||
"hr_staff_base.mobile_phone", # 手机号码
|
||||
"hr_staff_base.person_status", # 在职状态
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
|
||||
"hr_staff_base.nation", # 民族
|
||||
"hr_staff_base.sex", # 性别
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.period", # 试用期限(月)
|
||||
"hr_staff_base.pre_correction_date", # 试用期结束日期
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
|
||||
"hr_staff_base.identity", # 用工类型
|
||||
]),
|
||||
# 「雇主险增减员导出模板」(14 列,无三级/五级部门,顺序按模板)
|
||||
"雇主险增减员导出模板": ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
]),
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数(与浏览器版 roster_export.py 保持一致) ----------
|
||||
DEFAULT_TEMPLATE = "员工基础信息"
|
||||
DEFAULT_STATUSES = ["在职", "离职"]
|
||||
DEFAULT_OUTPUT_PATH = r"D:\资料\人资\花名册\花名册.xlsx"
|
||||
DEFAULT_DOWNLOAD_DIR = r"D:\资料\人资\花名册\download"
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
|
||||
# 异步导出等待超时(秒,服务端逐条生成 7000+ 条约需 10~20 秒,留足余量)
|
||||
EXPORT_TIMEOUT_SECONDS = 300
|
||||
|
||||
# ---------- 项目级重试次数(单状态导出失败最大尝试次数,含首次) ----------
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== 登录态(共享 cookies 文件) ====================
|
||||
def _build_session():
|
||||
"""读取共享 HR cookies 构造 requests 会话(仅取 37du.co 域)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 共享 cookies 文件不存在
|
||||
"""
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先调用「37duHR登录」指令完成登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def _is_expired(text) -> bool:
|
||||
"""接口正常返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
|
||||
return bool(text) and not text.lstrip().startswith(("{", "["))
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
|
||||
# 上月(本月 1 号减一天即上月最后一天)
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
"""在职人员条件:主职 in (1) + 在职状态 in (1),等价页面默认抓包条件。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
"""离职人员条件:主职 in (1) + 在职状态 in (2) + 离职时间区间,等价页面离职筛选抓包串。"""
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name, user_id=None):
|
||||
"""按模板名动态解析 exportFilters 字段串(与页面「自定义导出」弹窗逻辑一致)。
|
||||
|
||||
两步:模板列表(redmagicapi select,拿 id + ext1 名称)-> 模板详情
|
||||
(getPtusersexportdefine,拿 exportField JSON)-> 按 exportField 顺序拼接字段串。
|
||||
|
||||
Args:
|
||||
session: 已登录的 requests.Session 对象
|
||||
template_name: 模板名(对应模板列表的 ext1)
|
||||
user_id: 当前登录用户 id(缺省用 ROSTER_QUERY_BASE_PARAMS 里的 currentUserId)
|
||||
|
||||
Returns:
|
||||
exportFilters 字段串(逗号分隔,顺序与模板一致);解析失败返回 None(调用方回退内置模板)
|
||||
"""
|
||||
user_id = user_id or ROSTER_QUERY_BASE_PARAMS["currentUserId"]
|
||||
try:
|
||||
# 1. 模板列表 -> 按名称匹配拿 id
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」(可选:%s),回退内置模板",
|
||||
template_name, [t.get("ext1") for t in templates])
|
||||
return None
|
||||
|
||||
# 2. 模板详情 -> exportField JSON -> 按顺序拼字段串
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。
|
||||
|
||||
服务端依赖页面访问后的会话状态,未绑定时 bridge 返回 "0"、WS 握手报 500(用户登录)。
|
||||
"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先重新调用「37duHR登录」指令完成登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。
|
||||
|
||||
Returns:
|
||||
临时 Excel 文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: 登录态失效
|
||||
RuntimeError: 提交失败 / 超时 / 下载失败
|
||||
"""
|
||||
# 1. 会话绑定(页面访问 + bridge 注册)
|
||||
_bind_session(session)
|
||||
|
||||
# 2. WebSocket 连接并订阅主题
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
# 3. 提交异步导出任务(按状态构造 commonQuery,服务端翻译全部字典字段)
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
# 4. 接收进度推送,直到 --end--|文件路径
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
# 5. 下载文件到临时目录
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态(与浏览器版输出规范一致)。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
|
||||
# 删除临时下载的单个文件
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None, ttl=DEFAULT_TTL_SECONDS):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出),
|
||||
超时才重新导出。花名册版本由「模板 + 输出路径」共同隔离(各业务场景路径独立),
|
||||
不同模板导出到不同路径,不会互相复用。纯接口实现,无需浏览器。
|
||||
|
||||
Args:
|
||||
download_dir: 单状态临时文件目录(默认 DEFAULT_DOWNLOAD_DIR)
|
||||
output_path: 合并后保存路径(默认 DEFAULT_OUTPUT_PATH)
|
||||
template_name: 自定义导出模板名(默认 DEFAULT_TEMPLATE)
|
||||
statuses: 需导出的在职状态列表,如 ["在职"] / ["离职"] / ["在职","离职"]
|
||||
(默认 DEFAULT_STATUSES)
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职状态时生效;缺省自动计算)
|
||||
ttl: 缓存有效期(秒),默认 DEFAULT_TTL_SECONDS(15 分钟);传 0 表示总是重新导出
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失或失效
|
||||
RuntimeError: 导出失败(重试耗尽)或接口返回异常
|
||||
"""
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None: # None 使用默认缓存有效期
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用,跳过接口导出
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s),临时目录:%s =====",
|
||||
template_name, statuses, leave_desc, download_dir)
|
||||
|
||||
session = _build_session()
|
||||
# 模板动态解析(列表 -> 详情 -> exportField),失败回退内置模板字段串
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
# 合并所有花名册文件
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
|
||||
|
||||
def main(statuses=None, leave_start=None, leave_end=None,
|
||||
template=None, output_path=None, download_dir=None):
|
||||
"""影刀自定义指令入口「37du花名册导出」(与浏览器版 roster_export.py 签名一致)。
|
||||
|
||||
Args(缺省用内置默认值,见 DEFAULT_* 常量):
|
||||
statuses: 在职状态,str "在职" 或 "在职,离职",或 list ["在职","离职"]
|
||||
leave_start / leave_end: 离职时间范围 "YYYY-MM-DD"(离职时需要;不传默认 上月1日到今天)
|
||||
template: 自定义导出模板名
|
||||
output_path / download_dir: 保存路径与临时下载目录
|
||||
|
||||
Returns:
|
||||
{"success": bool, "save_path": str, "statuses": [...], "template": str}
|
||||
save_path 即调用方传入的 output_path(合并后的花名册文件路径)。
|
||||
"""
|
||||
# 在职状态:兼容 str / list / 逗号分隔
|
||||
if isinstance(statuses, str):
|
||||
statuses = [s.strip() for s in statuses.replace(",", ",").split(",") if s.strip()]
|
||||
elif statuses:
|
||||
statuses = [str(s) for s in statuses]
|
||||
else:
|
||||
statuses = list(DEFAULT_STATUSES)
|
||||
|
||||
template = template or DEFAULT_TEMPLATE
|
||||
output_path = output_path or DEFAULT_OUTPUT_PATH
|
||||
download_dir = download_dir or DEFAULT_DOWNLOAD_DIR
|
||||
|
||||
try:
|
||||
save_path = export_roster(
|
||||
download_dir=download_dir, output_path=output_path,
|
||||
template_name=template, statuses=statuses,
|
||||
leave_start=leave_start, leave_end=leave_end)
|
||||
return {"success": True, "save_path": save_path, "statuses": statuses, "template": template}
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
return {"success": False, "error": str(e), "statuses": statuses, "template": template}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
statuses = ["在职"]
|
||||
leave_start = ""
|
||||
leave_end = ""
|
||||
template = "员工基础信息"
|
||||
output_path = r"D:\资料\人资\排班异常识别\员工花名册.xlsx"
|
||||
main(statuses=statuses, leave_start=leave_start, leave_end=leave_end,
|
||||
template=template, output_path=output_path)
|
||||
@@ -0,0 +1,440 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: seal_data_export.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-09-07
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 封存数据导出与预处理模块(影刀单文件,自包含)。
|
||||
统一负责:拉取当月全集团考勤封存数据 → 预处理筛选(所属单位仅保留白名单单位)→
|
||||
保存为预处理后的封存表(固定路径)。检查1/检查5 等各检查模块不再直连接口,
|
||||
一律通过本模块 load_seal_rows() 读取预处理封存表。
|
||||
|
||||
所属单位白名单(预处理口径,需调整时只改 SEAL_UNIT_WHITELIST 一处):
|
||||
财务管理部 / 集团管理中心 / 集团营建中心 / 金色印象事业部 / 金色湖畔事业部
|
||||
|
||||
数据来源(接口直取,对应 aa.md / aa.json):
|
||||
- 接口:POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc
|
||||
sqlId = kq_count_leave_wage_SelectV2,入参 yearmonth = YYYYMM,base_code 留空 = 全集团批量。
|
||||
- 每员工一条封存记录,所属单位字段 BELONG_UNIT_ORG_NAME(aa.md 列:所属单位)。
|
||||
|
||||
输出:
|
||||
考勤封存数据_{月份}.xlsx 预处理后的封存表(固定路径,覆盖式保存,仅含白名单单位员工,
|
||||
中文表头,供人工复核 & 各检查模块读取复用)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:需存在「37duHR登录」写入的共享登录态(hr_cookies.json)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_seal_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[DEBUG] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[INFO] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[WARN] {msg}")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
print(f"[ERROR] {msg}")
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
_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')
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SEAL_URL = "https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
SEAL_SQL_ID = "kq_count_leave_wage_SelectV2"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
SAVE_DIR = os.getenv("monthly_seal_save_dir") or r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 所属单位白名单(预处理口径:封存表仅保留以下单位员工)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_UNIT_WHITELIST: Tuple[str, ...] = (
|
||||
"财务管理部",
|
||||
"集团管理中心",
|
||||
"集团营建中心",
|
||||
"金色印象事业部",
|
||||
"金色湖畔事业部",
|
||||
)
|
||||
|
||||
# 封存记录工号字段
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
|
||||
# 中文导出列 → 接口字段(来源:aa.md 封存页列定义。保存封存数据时按此重命名表头,读取时反查还原)
|
||||
CN_FIELD_MAP: Dict[str, str] = {
|
||||
"姓名": "staff_name", "工号": "base_code", "岗位": "POST_ALIAS_NAME",
|
||||
"所属单位": "BELONG_UNIT_ORG_NAME", "一级部门": "DEPT_ORG_ONE",
|
||||
"二级部门": "DEPT_ORG_TWO", "三级部门": "DEPT_ORG_THREE",
|
||||
"四级部门": "DEPT_ORG_FOUR", "五级部门": "DEPT_ORG_FIVE", "部门全路径": "ORG_FULL_PATH",
|
||||
"封存月份": "yearmonth", "开始日期": "count_begin_date", "结束日期": "count_end_date",
|
||||
"实际出勤天日": "kq_stat_cal_ext19", "_在职应勤工作日": "kq_stat_month_yq_work_day_in",
|
||||
"休息天": "kq_stat_cal_ext9", "旷工天数": "kq_stat_cal_ext39", "漏打卡次数": "kq_stat_cal_ext8",
|
||||
"年假天": "kq_stat_leave_day_num1", "_病假天": "kq_stat_leave_day_num4",
|
||||
"_产假天": "kq_stat_leave_day_num5", "_事假天": "kq_stat_leave_day_num9",
|
||||
"_普通事假天": "kq_stat_leave_day_num16", "_特殊事假天": "kq_stat_leave_day_num17",
|
||||
"_小时特假小时": "kq_stat_leave_hour_num18", "_普通事假(晚/高峰)天": "kq_stat_leave_day_num19",
|
||||
"_普通事假(早/中)天": "kq_stat_leave_day_num20", "_特别福利假天": "kq_stat_leave_day_num23",
|
||||
"_年度福利假天": "kq_stat_leave_day_num24",
|
||||
"_工作日加班转补贴小时": "kq_stat_ps_bt_hour", "法定节假日加班转补贴天": "kq_stat_cal_ext69",
|
||||
"休息日加班转补贴天": "kq_stat_cal_ext44", "当月未休调休天": "kq_stat_cal_ext63",
|
||||
"迟到30分钟内次数": "kq_stat_cal_ext60", "迟到30到60分钟内次数": "kq_stat_cal_ext61",
|
||||
"迟到60到120分钟内次数": "kq_stat_cal_ext62",
|
||||
"早退30分钟内次数": "kq_stat_cal_ext51", "早退30到60分钟内次数": "kq_stat_cal_ext52",
|
||||
"早退60到120分钟内次数": "kq_stat_cal_ext53", "连班次数": "kq_stat_cal_ext40",
|
||||
"是否未休小时特假": "kq_stat_cal_ext42", "是否全勤": "kq_stat_cal_ext43",
|
||||
"离职时间": "leaveOffice_date", "入职日期": "join_date", "身份证": "idCard",
|
||||
"用工类型": "identity", "操作时间": "operate_time", "操作人": "operator_name",
|
||||
"考勤封存状态": "kq_data_state", "考勤封存操作人": "kq_data_operator_name",
|
||||
"员工状态": "staff_status", "在职状态": "person_status_name",
|
||||
}
|
||||
|
||||
|
||||
# ==================== HR 登录态(共享 cookies) ====================
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _load_shared_hr_cookies():
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
return None
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
return json.load(f) or None
|
||||
|
||||
|
||||
def _ensure_hr_cookies():
|
||||
if _load_shared_hr_cookies():
|
||||
return True
|
||||
raise RuntimeError(
|
||||
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
|
||||
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python workflows/share/hr_login.py")
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
if not cookies:
|
||||
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;登录态失效抛 HRSessionExpiredError。
|
||||
|
||||
按项目规范做全局重试(最大 3 次,指数退避),仅在网络/服务端异常时重试;
|
||||
登录态失效(HRSessionExpiredError)属确定性失败,直接抛出、不重试。
|
||||
"""
|
||||
last_exc = None
|
||||
for attempt in range(1, 4):
|
||||
try:
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt < 3:
|
||||
time.sleep(1.0 * (2 ** (attempt - 1)))
|
||||
raise last_exc
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def _relogin_get_user_id():
|
||||
"""登录态失效后:重建会话 → 重新获取 userId。"""
|
||||
_ensure_hr_cookies()
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
return session, _clean(info.get("userId"))
|
||||
|
||||
|
||||
# ==================== 考勤封存接口(aa.md:getPageAjaxList.mc + leave_wage_SelectV2) ====================
|
||||
def fetch_seal_page(session, user_id, yearmonth, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页考勤封存数据。
|
||||
|
||||
base_code / staff_name 留空 = 不过滤,按组织树全集团批量返回当月封存记录。
|
||||
"""
|
||||
params = {
|
||||
"tree_code": "cq37du",
|
||||
"user_id": user_id,
|
||||
"sqlId": SEAL_SQL_ID,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"dept_org_name": "",
|
||||
"confirm_state": "",
|
||||
"person_status": "",
|
||||
"identity": "",
|
||||
"staff_status": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"post_type": "1",
|
||||
"custom_dept_ids": "",
|
||||
"custom_dept_names": "",
|
||||
"STAFF_ID": "",
|
||||
"sealOrgAlias": "",
|
||||
"seal_dept_stru_id": "",
|
||||
"kqDataOperatorName": "",
|
||||
"kqDataOperatorId": "",
|
||||
"base_code": "",
|
||||
"staff_name": "",
|
||||
"yearmonth": yearmonth,
|
||||
"kq_data_state": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SEAL_URL, params, "考勤封存")
|
||||
|
||||
|
||||
def fetch_all_seal(session, user_id, yearmonth: str) -> List[dict]:
|
||||
"""分页抓取某月全集团完整封存数据(pageSize=500 分页拉取)。"""
|
||||
all_rows: List[dict] = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("考勤封存登录态过期,自动补登录后续抓")
|
||||
session, user_id = _relogin_get_user_id()
|
||||
data = fetch_seal_page(session, user_id, yearmonth, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
logger.error("考勤封存第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤封存无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount") or 0
|
||||
logger.info("考勤封存已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
# 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据;
|
||||
# 仅当 pageCount 存在且已到最后页,或返回行数不足一页时才结束分页。
|
||||
if total_page and page_no >= total_page:
|
||||
break
|
||||
if len(page_list) < PAGE_MAX_SIZE:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
try:
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
if s.endswith(".0"):
|
||||
s = s[:-2]
|
||||
return s
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _normalize_month(month) -> str:
|
||||
"""月份归一化:None → 上月;YYYYMM → YYYY-MM;其余原样。"""
|
||||
if not month:
|
||||
py, pm = _prev_month(date.today().year, date.today().month)
|
||||
return f"{py:04d}-{pm:02d}"
|
||||
s = str(month).strip()
|
||||
if len(s) == 6 and s.isdigit():
|
||||
return f"{s[:4]}-{s[4:]}"
|
||||
return s
|
||||
|
||||
|
||||
def _seal_path(ym: str) -> str:
|
||||
"""预处理封存表固定路径(按月覆盖式保存,供检查模块稳定读取)。"""
|
||||
return os.path.join(SAVE_DIR, f"考勤封存数据_{ym}.xlsx")
|
||||
|
||||
|
||||
def _rename_columns_cn(frame: "pd.DataFrame", cn_map: Dict[str, str]) -> "pd.DataFrame":
|
||||
"""把封存数据列名按 中文导出列→接口字段 映射替换为中文表头。
|
||||
|
||||
仅重命名 cn_map 中存在的列,未映射的列(如各类 kq_stat_* 扩展字段)保留原英文名,
|
||||
列顺序不变,保证保存的封存数据信息不丢失。
|
||||
"""
|
||||
rename = {en: cn for cn, en in cn_map.items() if en in frame.columns}
|
||||
return frame.rename(columns=rename)
|
||||
|
||||
|
||||
# ==================== 预处理:所属单位白名单筛选 ====================
|
||||
def _filter_by_unit(rows: List[dict]) -> List[dict]:
|
||||
"""封存数据预处理:仅保留所属单位在白名单内的记录。"""
|
||||
return [rec for rec in rows if _clean(rec.get(SEAL_UNIT_FIELD)) in SEAL_UNIT_WHITELIST]
|
||||
|
||||
|
||||
# ==================== 导出 / 读取 ====================
|
||||
def export_seal_data(month: str = None) -> List[dict]:
|
||||
"""拉取当月全集团考勤封存数据 → 所属单位白名单预处理 → 保存固定路径封存表。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(接口原始字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
yearmonth = ym.replace("-", "")
|
||||
logger.info("===== 封存数据导出与预处理,月份:%s =====", ym)
|
||||
|
||||
# 1. 拉取当月全集团封存数据(base_code 留空批量)
|
||||
session = build_hr_session()
|
||||
user_id = _clean(fetch_cur_user_info(session).get("userId"))
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败")
|
||||
seal_rows = fetch_all_seal(session, user_id, yearmonth)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」未拉到考勤封存数据,请确认该月已封存。")
|
||||
logger.info("全集团封存记录共 %d 人:%s", len(seal_rows), ym)
|
||||
|
||||
# 2. 预处理:所属单位白名单筛选
|
||||
filtered = _filter_by_unit(seal_rows)
|
||||
logger.info("封存数据预处理:全集团 %d 人 → 白名单单位 %d 人", len(seal_rows), len(filtered))
|
||||
|
||||
# 3. 保存预处理封存表(固定路径,覆盖式)
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
path = _seal_path(ym)
|
||||
try:
|
||||
_rename_columns_cn(pd.DataFrame(filtered), CN_FIELD_MAP).to_excel(path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(path)}」后重试")
|
||||
logger.info("预处理封存表已保存:%s(%d 行)", path, len(filtered))
|
||||
return filtered
|
||||
|
||||
|
||||
def load_seal_rows(month: str = None) -> List[dict]:
|
||||
"""读取预处理封存表(固定路径),返回接口原始字段名的记录行列表,供各检查模块使用。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM"(或 YYYYMM),默认上月。
|
||||
|
||||
Returns:
|
||||
预处理后的封存记录行列表(中文表头已反查还原为接口字段名)。
|
||||
"""
|
||||
ym = _normalize_month(month)
|
||||
path = _seal_path(ym)
|
||||
if not os.path.exists(path):
|
||||
raise RuntimeError(
|
||||
f"未找到预处理封存表:{path}\n"
|
||||
"请先运行「seal_data_export.py」导出并预处理当月封存数据(所属单位白名单筛选),"
|
||||
"再运行各检查模块。")
|
||||
df = pd.read_excel(path, dtype=str)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
# CN_FIELD_MAP 为 中文导出列→接口字段,反查:中文表头 → 接口字段名
|
||||
reverse = {cn: en for cn, en in CN_FIELD_MAP.items()}
|
||||
df = df.rename(columns={c: reverse.get(c, c) for c in df.columns})
|
||||
rows: List[dict] = [dict(r) for r in df.to_dict(orient="records")]
|
||||
logger.info("已读取预处理封存表:%s(%d 行)", path, len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_seal_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = export_seal_data(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【封存数据导出与预处理完成】")
|
||||
logger.info(" 月份:%s | 白名单单位封存人数:%d", _normalize_month(month), len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
if "正被占用" in str(e):
|
||||
logger.error("=========== 提醒 ===========")
|
||||
logger.error(str(e))
|
||||
return {"success": False, "message": str(e)}
|
||||
logger.error("封存数据导出失败:%s\n%s", e, traceback.format_exc())
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>37du 自动化工作台</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1576
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "37du-webhost-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
<template>
|
||||
<div v-if="booting" class="boot">
|
||||
<span class="boot-logo">37</span>
|
||||
<span class="boot-txt">{{ syncing ? '正在同步插件,请稍候…' : (store.appName || '自动化工作台') }}</span>
|
||||
<span class="boot-dots"><i></i><i></i><i></i></span>
|
||||
</div>
|
||||
<LoginPage v-else-if="!store.current" :app-name="store.appName" @ok="onLogin" />
|
||||
<div class="__app" v-else>
|
||||
<!-- 壳子更新提示:控制面有新版本且已自动下载,点击重启升级 -->
|
||||
<div v-if="shellUpdate.downloaded" class="update-bar">
|
||||
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
|
||||
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
|
||||
</div>
|
||||
<!-- 顶部:品牌 + 平台登录态 + 当前账号/登出 + 进度 -->
|
||||
<header class="topbar panel">
|
||||
<div class="brand">
|
||||
<span class="logo">37</span>
|
||||
<div class="brand-meta">
|
||||
<strong>{{ store.appName }}</strong>
|
||||
<span>{{ wsText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-divider direction="vertical" class="vdiv" />
|
||||
|
||||
<div class="band">
|
||||
<span class="band-label">平台登录态</span>
|
||||
<el-tooltip
|
||||
v-for="p in store.platforms"
|
||||
:key="p.id"
|
||||
:content="p.allowed === false ? '无平台访问权限,需管理员在控制面授权' : (p.online ? '已登录,点击刷新' : '未登录,点击登录')"
|
||||
placement="bottom"
|
||||
:disabled="p.online && p.allowed !== false"
|
||||
>
|
||||
<el-button
|
||||
class="chip"
|
||||
:class="{ online: p.online, locked: p.allowed === false }"
|
||||
:disabled="busyLogin === p.id || p.allowed === false"
|
||||
:loading="busyLogin === p.id"
|
||||
round
|
||||
@click="login(p.id)"
|
||||
>
|
||||
<i class="dot"></i>
|
||||
<span>{{ busyLogin === p.id ? '登录中…' : p.label }}</span>
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
|
||||
<div class="spacer"></div>
|
||||
|
||||
<div class="run-state">
|
||||
<template v-if="store.running">
|
||||
<span class="run-pct">{{ store.progress }}%</span>
|
||||
<el-progress
|
||||
:percentage="store.progress"
|
||||
:show-text="false"
|
||||
:stroke-width="8"
|
||||
color="#3b6cff"
|
||||
class="run-bar"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="acct">
|
||||
<button class="acct-btn" title="个人中心" @click="profileOpen = true">
|
||||
<el-avatar :size="26" class="acct-avatar" :src="store.avatarUrl" :key="store.avatarUrl" @error="onAvatarError">
|
||||
<span class="acct-avatar-fb">{{ (store.nickname || store.current).slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<span class="acct-name">{{ store.nickname || store.current }}</span>
|
||||
<el-tag v-if="store.isAdmin" size="small" type="primary" effect="light" round>管理员</el-tag>
|
||||
</button>
|
||||
<el-button
|
||||
v-if="store.isAdmin"
|
||||
v-show="store.controlplane"
|
||||
class="chip admin-chip"
|
||||
title="打开中心机控制面进行插件/账号/授权管理"
|
||||
round
|
||||
@click="openConsole"
|
||||
>
|
||||
<el-icon class="geo"><Setting /></el-icon>管理控制台
|
||||
</el-button>
|
||||
<el-button class="chip" round @click="logout">登出</el-button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 主体:左场景 | 右插件页 + 日志 -->
|
||||
<div class="body">
|
||||
<aside class="panel side">
|
||||
<div class="side-head">
|
||||
<span class="sec-title">场景</span>
|
||||
<span class="count">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<ul class="scene-list">
|
||||
<li
|
||||
v-for="(p, i) in store.plugins"
|
||||
:key="p.id"
|
||||
:class="{ active: p.id === store.selectedId && store.view === 'plugin' }"
|
||||
@click="openPlugin(p.id)"
|
||||
>
|
||||
<span class="scene-icon" :style="{ background: PALETTE[i % PALETTE.length] }">
|
||||
{{ p.name.slice(0, 1) }}
|
||||
</span>
|
||||
<span class="scene-name">{{ p.name }}</span>
|
||||
<em>v{{ p.version }}</em>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="!store.plugins.length" class="scene-empty">当前账号暂无可用场景<br><span>请联系管理员在控制面授权</span></div>
|
||||
<div class="side-foot">场景以插件方式接入</div>
|
||||
</aside>
|
||||
|
||||
<main class="main">
|
||||
<div class="page-scroll panel">
|
||||
<PluginPage v-if="store.view === 'plugin'" />
|
||||
</div>
|
||||
<LogPanel />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import PluginPage from './components/PluginPage.vue'
|
||||
import LogPanel from './components/LogPanel.vue'
|
||||
import LoginPage from './components/LoginPage.vue'
|
||||
import ProfilePanel from './components/ProfilePanel.vue'
|
||||
import { store, handleEvent, clearLogs, log, loadAvatar, clearAvatarCache } from './store'
|
||||
import { connectWS, fetchMeta, loginPlatform, adminLogout, adminMe, adminPassword, syncPlugins, getShellStatus, applyShellUpdate } from './api'
|
||||
|
||||
function openConsole() {
|
||||
if (!store.controlplane) return
|
||||
window.open(store.controlplane, '_blank', 'noopener')
|
||||
}
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
|
||||
// 顶栏头像加载失败:清除缓存返回首字符兜底
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const wsText = computed(() =>
|
||||
store.wsOn ? '服务已连接' : '连接中断,正在重连…')
|
||||
|
||||
function openPlugin(id) {
|
||||
store.selectedId = id
|
||||
store.view = 'plugin'
|
||||
}
|
||||
|
||||
function openWS() {
|
||||
if (window.__ws) window.__ws.close()
|
||||
const ws = connectWS(handleEvent)
|
||||
window.__ws = ws
|
||||
ws.onopen = () => (store.wsOn = true)
|
||||
ws.onclose = () => {
|
||||
store.wsOn = false
|
||||
// 仅登录态下自动重连刷新;未登录被拒(1008)时静默,避免 reload 死循环
|
||||
if (store.current) setTimeout(() => (location.reload()), 2500)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const meta = await fetchMeta()
|
||||
store.appName = meta.appName
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
store.selectedId = store.plugins[0]?.id || ''
|
||||
clearLogs()
|
||||
openWS()
|
||||
await checkSession()
|
||||
booting.value = false // 会话判定完成(登录/未登录/后端不可达均已定),再渲染首屏
|
||||
loadAvatar()
|
||||
loadShellStatus()
|
||||
})
|
||||
|
||||
const profileOpen = ref(false)
|
||||
const busyLogin = ref('')
|
||||
const booting = ref(true) // 鉴权判定中:未确定会话前先显示加载骨架,避免「闪一下登录页再进首页」
|
||||
const syncing = ref(false) // 首次启动/启动时:按账号权限自下载/更新插件(等待下载界面)
|
||||
|
||||
// ===== 壳子自动更新:控制面有新版本且已自动下载 → 提示用户点击重启升级 =====
|
||||
const shellUpdate = ref({})
|
||||
const updating = ref(false)
|
||||
async function loadShellStatus() {
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {}
|
||||
}
|
||||
async function doShellUpdate() {
|
||||
updating.value = true
|
||||
try {
|
||||
await applyShellUpdate() // 后端运行静默安装并退出进程,升级后自动重启
|
||||
} catch (e) {
|
||||
updating.value = false
|
||||
ElMessage.error('更新失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
|
||||
// 平台登录等轻量操作反馈:统一走 element-plus 全局消息
|
||||
function showToast(msg, type = 'info') {
|
||||
ElMessage({ message: msg, type, duration: 2200 })
|
||||
}
|
||||
|
||||
async function checkSession() {
|
||||
// 登录态一律以**后端会话 cookie** 为准(钉钉扫码/账号登录/后端重启后均从 admin/me 判定),
|
||||
// 不再以 localStorage 的 cp_account 早退——否则全新扫码流程(未写过 cp_account)回跳后无法进入插件页。
|
||||
try {
|
||||
const me = await adminMe()
|
||||
if (!me.account) {
|
||||
store.current = ''; store.isAdmin = false; store.dept = ''; store.nickname = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
return
|
||||
}
|
||||
store.current = me.account
|
||||
store.isAdmin = !!me.is_admin
|
||||
store.dept = me.dept || ''
|
||||
store.nickname = me.nickname || ''
|
||||
try { localStorage.setItem('cp_account', me.account) } catch (_) {}
|
||||
// 会话确认后:按账号权限自下载/更新插件(首次启动等待下载完成;离线/失败直接跳过)
|
||||
syncing.value = true
|
||||
try { await syncPlugins() } catch (_) {}
|
||||
syncing.value = false
|
||||
// 会话有效:补拉插件清单(未登录时 meta 不返回插件)
|
||||
await refreshMeta()
|
||||
} catch (_) { /* 后端 down:无法校验,保持现状(可能为登录页或本地态) */ }
|
||||
}
|
||||
|
||||
async function refreshMeta() {
|
||||
try {
|
||||
const meta = await fetchMeta()
|
||||
store.controlplane = meta.controlplane || ''
|
||||
store.platforms = meta.platforms
|
||||
store.plugins = meta.plugins || []
|
||||
if (!store.selectedId) store.selectedId = store.plugins[0]?.id || ''
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function onLogin(ok) {
|
||||
store.current = ok.account
|
||||
store.isAdmin = !!ok.is_admin
|
||||
store.dept = ok.dept || ''
|
||||
store.nickname = ok.nickname || ''
|
||||
try { localStorage.setItem('cp_account', ok.account) } catch (_) {}
|
||||
// 登录后:刷新平台权限与插件清单,并用带会话的连接重建 WS
|
||||
await refreshMeta()
|
||||
openWS()
|
||||
loadAvatar()
|
||||
// 首次登录/钉钉自动建号的默认密码:提示立即改密
|
||||
if (ok.must_change_pwd) { promptChangePwd(ok.account) }
|
||||
}
|
||||
|
||||
async function promptChangePwd(account) {
|
||||
try {
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'当前账号正使用默认密码,请立即设置新密码(至少 6 位),避免他人误登录',
|
||||
'首次登录 · 修改密码',
|
||||
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
|
||||
try {
|
||||
await adminPassword({ account, old_password: '', new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e) {
|
||||
ElMessage.warning('改密失败:' + (e.message || e))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
}
|
||||
async function logout() {
|
||||
try { await adminLogout() } catch (_) {}
|
||||
store.current = ''
|
||||
store.isAdmin = false
|
||||
store.nickname = ''
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem('cp_account') } catch (_) {}
|
||||
}
|
||||
|
||||
async function login(id) {
|
||||
if (busyLogin.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
const label = p?.label || id
|
||||
if (p?.online) {
|
||||
showToast(`${label} 已登录`, 'success')
|
||||
return
|
||||
}
|
||||
busyLogin.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
const ok = !!(r && r.online)
|
||||
if (p) p.online = ok
|
||||
log(ok ? 'INFO' : 'ERROR',
|
||||
ok ? `平台 ${label} 登录成功` : `平台 ${label} 登录未生效:${(r && r.message) || ''}`)
|
||||
showToast(ok ? `${label} 登录成功` : `${label} 登录失败:${(r && r.message) || '登录态未生效'}`, ok ? 'success' : 'error')
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${label} 登录失败:${e.message || e}`)
|
||||
showToast(`登录失败:${e.message || e}`, 'error')
|
||||
} finally {
|
||||
busyLogin.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.boot {
|
||||
min-height: 100vh;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 14px; background: var(--bg);
|
||||
}
|
||||
.boot-logo {
|
||||
width: 54px; height: 54px; border-radius: 16px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 20px; font-weight: 800;
|
||||
box-shadow: 0 10px 26px -8px rgba(59,108,255,.65);
|
||||
animation: bootpop .4s ease;
|
||||
}
|
||||
.boot-txt { font-size: 13px; color: var(--text-faint); letter-spacing: .06em; }
|
||||
.boot-dots { display: flex; gap: 5px; }
|
||||
.boot-dots i {
|
||||
width: 6px; height: 6px; border-radius: 50%; background: var(--primary);
|
||||
animation: bootblink 1s infinite ease-in-out;
|
||||
}
|
||||
.boot-dots i:nth-child(2) { animation-delay: .15s; }
|
||||
.boot-dots i:nth-child(3) { animation-delay: .3s; }
|
||||
@keyframes bootpop { from { transform: scale(.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes bootblink { 0%,80%,100% { opacity: .25; } 40% { opacity: 1; transform: translateY(-2px); } }
|
||||
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 12px 18px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.update-bar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 8px 14px; margin-bottom: 12px; flex-shrink: 0;
|
||||
background: var(--primary-weak);
|
||||
border: 1px solid rgba(59, 108, 255, .35);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px; color: var(--text-sub);
|
||||
}
|
||||
.update-bar b { color: var(--primary); }
|
||||
.update-bar em { font-style: normal; color: var(--text-faint); margin-left: 6px; }
|
||||
.brand { display: flex; align-items: center; gap: 11px; }
|
||||
.logo {
|
||||
width: 36px; height: 36px; border-radius: 10px;
|
||||
display: grid; place-items: center;
|
||||
background: var(--primary-grad); color: #fff;
|
||||
font-size: 14px; font-weight: 800;
|
||||
box-shadow: 0 4px 12px -3px rgba(59,108,255,.6);
|
||||
}
|
||||
.brand-meta { display: flex; flex-direction: column; line-height: 1.2; }
|
||||
.brand-meta strong { font-size: 14px; }
|
||||
.brand-meta span { font-size: 11px; color: var(--text-faint); }
|
||||
|
||||
.vdiv { height: 26px; margin: 0 2px; }
|
||||
|
||||
.band { display: flex; align-items: center; gap: 8px; }
|
||||
.band-label { font-size: 12px; color: var(--text-faint); margin-right: 4px; }
|
||||
|
||||
.chip { padding: 5px 14px; border-radius: 999px; }
|
||||
.chip .dot { width: 9px; height: 9px; border-radius: 50%; background: #c6ccdc; margin-right: 6px; display: inline-block; }
|
||||
.chip.online { border-color: transparent; background: var(--ok-weak); color: #1a8f63; }
|
||||
.chip.online .dot { background: var(--ok); box-shadow: 0 0 0 3px rgba(34,176,122,.18); }
|
||||
.chip.locked { border-style: dashed; opacity: .5; }
|
||||
.admin-chip { border-color: rgba(59,108,255,.45); color: var(--primary); background: var(--primary-weak-2); margin-left: 4px; }
|
||||
.admin-chip:hover { border-color: var(--primary); }
|
||||
.admin-chip .geo { margin-right: 4px; }
|
||||
|
||||
.spacer { flex: 1; }
|
||||
.run-state { display: flex; align-items: center; gap: 10px; }
|
||||
.run-bar { width: 180px; flex-shrink: 0; }
|
||||
.run-pct { font-size: 12px; font-weight: 700; color: var(--primary); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.acct { display: flex; align-items: center; gap: 8px; margin-left: 12px; }
|
||||
.acct-btn {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
border: none; background: transparent; cursor: pointer;
|
||||
padding: 4px 8px; margin: -4px -8px; border-radius: 8px;
|
||||
font: inherit; transition: background .13s;
|
||||
}
|
||||
.acct-btn:hover { background: var(--surface-2); }
|
||||
.acct-avatar { flex-shrink: 0; }
|
||||
.acct-avatar-fb { font-size: 12px; font-weight: 700; }
|
||||
.acct-name { font-size: 13px; font-weight: 600; color: var(--text-sub); }
|
||||
|
||||
.body { flex: 1; display: flex; gap: 14px; min-height: 0; margin-top: 14px; }
|
||||
|
||||
.side { width: 232px; flex-shrink: 0; display: flex; flex-direction: column; padding: 14px 12px; }
|
||||
.side-head { display: flex; align-items: center; justify-content: space-between; padding: 0 6px 10px; }
|
||||
.count { font-size: 11px; color: var(--text-faint); background: var(--surface-2); border: 1px solid var(--border); border-radius: 999px; padding: 1px 8px; }
|
||||
.scene-list { list-style: none; margin: 0; padding: 0; flex: 1; overflow: auto; display: flex; flex-direction: column; gap: 2px; }
|
||||
.scene-list li {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 9px 10px; border-radius: var(--radius-sm); cursor: pointer;
|
||||
position: relative;
|
||||
transition: background .13s, transform .13s ease;
|
||||
}
|
||||
.scene-list li:hover { background: var(--surface-2); transform: translateX(2px); }
|
||||
.scene-list li.active { background: var(--primary-weak); }
|
||||
.scene-list li.active::before {
|
||||
content: ''; position: absolute; left: 0; top: 9px; bottom: 9px;
|
||||
width: 3px; border-radius: 3px; background: var(--primary);
|
||||
}
|
||||
.scene-list li.active .scene-name { color: var(--primary); font-weight: 600; }
|
||||
.scene-icon {
|
||||
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
|
||||
display: grid; place-items: center; color: #fff; font-size: 12px; font-weight: 700;
|
||||
}
|
||||
.scene-name { flex: 1; color: var(--text-sub); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.scene-list em { font-style: normal; font-size: 10px; color: var(--text-faint); }
|
||||
.scene-empty {
|
||||
flex: 1; display: grid; place-items: center; text-align: center;
|
||||
font-size: 12.5px; color: var(--text-sub); line-height: 1.9; padding: 20px 12px;
|
||||
}
|
||||
.scene-empty span { font-size: 11px; color: var(--text-faint); }
|
||||
.side-foot { font-size: 10px; color: var(--text-faint); text-align: center; padding-top: 10px; border-top: 1px dashed var(--border); margin-top: 8px; }
|
||||
|
||||
.main { flex: 1; display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.page-scroll { flex: 1; min-height: 0; padding: 20px 24px; overflow: auto; }
|
||||
</style>
|
||||
@@ -0,0 +1,74 @@
|
||||
// 与 FastAPI 后端交互 + WebSocket 实时流
|
||||
const WS_BASE = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (e) {}
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
export async function fetchMeta() {
|
||||
return j('/api/meta')
|
||||
}
|
||||
|
||||
export async function syncPlugins() {
|
||||
return j('/api/plugins/sync', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function getShellStatus() {
|
||||
return j('/api/shell/update-status')
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function loginPlatform(id) {
|
||||
return j(`/api/platforms/${id}/login`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function logoutPlatform(id) {
|
||||
return j(`/api/platforms/${id}/logout`, { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function startRun(pluginId, fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
export function connectWS(onEvent) {
|
||||
const ws = new WebSocket(WS_BASE + '/ws')
|
||||
ws.onmessage = (e) => {
|
||||
try { onEvent(JSON.parse(e.data)) } catch (_) {}
|
||||
}
|
||||
return ws
|
||||
}
|
||||
|
||||
// ===== 统一账户登录/会话(底座仅保留认证与个人密码,管理走中心机控制面) =====
|
||||
export async function adminMe() {
|
||||
return j('/api/admin/me')
|
||||
}
|
||||
export async function adminLogin(account, password) {
|
||||
return j('/api/admin/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ account, password }) })
|
||||
}
|
||||
// v3 钉钉直连接登录:生成钉钉授权 URL(redirect_uri=本机 /auth/done),前端当前窗口跳转到该 URL
|
||||
export async function authDingtalk() {
|
||||
return j('/api/auth/dingtalk')
|
||||
}
|
||||
export async function adminLogout() {
|
||||
return j('/api/admin/logout', { method: 'POST' })
|
||||
}
|
||||
export async function adminPassword(body) {
|
||||
return j('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<template>
|
||||
<div class="panel log-wrap">
|
||||
<div class="log-head">
|
||||
<div class="log-title">
|
||||
<i class="status" :class="store.wsOn ? 'on' : 'off'" :title="store.wsOn ? '实时连接正常' : '连接已中断'"></i>
|
||||
<span>运行日志</span>
|
||||
<span v-if="store.running" class="live">● LIVE</span>
|
||||
<span v-else-if="store.logs.length" class="count">{{ visibleLogs.length }} 条</span>
|
||||
</div>
|
||||
|
||||
<div class="log-tools">
|
||||
<el-radio-group v-model="level" size="small">
|
||||
<el-radio-button v-for="l in LEVELS" :key="l" :value="l">{{ l }}</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-button size="small" :icon="CopyDocument" circle title="复制日志" :disabled="!visibleLogs.length"
|
||||
@click="copy" />
|
||||
<el-button size="small" :icon="pause ? VideoPlay : VideoPause" circle :title="pause ? '继续滚动' : '暂停滚动'"
|
||||
@click="pause = !pause" />
|
||||
<el-button size="small" plain :disabled="!store.logs.length" @click="confirmClear">清空</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div ref="box" class="log-box">
|
||||
<div v-if="!visibleLogs.length" class="log-empty">
|
||||
<template v-if="store.logs.length">当前级别无日志</template>
|
||||
<template v-else>暂无日志,点击「一键执行」开始</template>
|
||||
</div>
|
||||
<div v-for="(l, i) in visibleLogs" :key="i" class="log-line">
|
||||
<span class="t">{{ l.time }}</span>
|
||||
<span class="lv" :class="'s-' + (l.level || 'INFO')">[{{ l.level || 'INFO' }}]</span>
|
||||
<span>{{ l.msg }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { nextTick, ref, watch, computed } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { CopyDocument, VideoPause, VideoPlay } from '@element-plus/icons-vue'
|
||||
import { store, clearLogs } from '../store'
|
||||
|
||||
const LEVELS = ['全部', 'INFO', 'WARN', 'ERROR']
|
||||
const level = ref('全部')
|
||||
const pause = ref(false)
|
||||
const box = ref(null)
|
||||
|
||||
const visibleLogs = computed(() => {
|
||||
if (level.value === '全部') return store.logs
|
||||
return store.logs.filter((l) => l.level === level.value)
|
||||
})
|
||||
|
||||
// 日志变化或过滤切换时,若未暂停则自动滚到最新
|
||||
watch(
|
||||
[() => store.logs.length, level],
|
||||
async () => {
|
||||
if (pause.value) return
|
||||
await nextTick()
|
||||
if (box.value) box.value.scrollTop = box.value.scrollHeight
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function confirmClear() {
|
||||
ElMessageBox.confirm('确认清空全部运行日志?', '清空日志', {
|
||||
confirmButtonText: '清空',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
})
|
||||
.then(() => { clearLogs(); ElMessage.success('日志已清空') })
|
||||
.catch(() => { })
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
const text = visibleLogs.value.map((l) => `[${l.time}] [${l.level || 'INFO'}] ${l.msg}`).join('\n')
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
ElMessage.success(`已复制 ${visibleLogs.value.length} 条日志`)
|
||||
} catch (_) {
|
||||
ElMessage.error('复制失败')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.log-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 216px;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.log-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px 8px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.log-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.log-tools .el-button+.el-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.status.on {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 3px var(--ok-weak);
|
||||
}
|
||||
|
||||
.status.off {
|
||||
background: #c6ccdc;
|
||||
}
|
||||
|
||||
.live {
|
||||
color: var(--ok);
|
||||
font-size: 10px;
|
||||
animation: blink 1s infinite;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
|
||||
.count {
|
||||
font-size: 11px;
|
||||
color: var(--text-faint);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@keyframes blink {
|
||||
50% {
|
||||
opacity: .2;
|
||||
}
|
||||
}
|
||||
|
||||
.log-empty {
|
||||
color: var(--text-faint);
|
||||
padding: 14px;
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,743 @@
|
||||
<template>
|
||||
<div class="login">
|
||||
<!-- 巨大 37:节点阵列 -->
|
||||
<div class="ghost" aria-hidden="true">37</div>
|
||||
|
||||
<!-- 基线管道:流程节点 -->
|
||||
<div class="pipeline" aria-hidden="true">
|
||||
<i></i><i></i><i></i>
|
||||
</div>
|
||||
|
||||
<!-- 顶部:品牌 + 系统状态 -->
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<span class="mark">37</span>
|
||||
<span class="name">{{ appName || '37du 自动化工作台' }}</span>
|
||||
</div>
|
||||
<div class="sys">
|
||||
<span class="dot" aria-hidden="true"></span>
|
||||
<span>引擎运行中</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- 中央:接入终端 -->
|
||||
<main class="panel">
|
||||
<span class="core-mark">37 CORE · AUTOMATION</span>
|
||||
<h1>自动化工作台</h1>
|
||||
<p class="sub">使用统一账号或钉钉扫码,进入你的流程中心</p>
|
||||
|
||||
<el-form label-position="top" class="form" @submit.prevent="doLogin">
|
||||
<el-form-item label="员工账号">
|
||||
<el-input v-model="account" placeholder="请输入账号" autocomplete="username" size="large" clearable
|
||||
@keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-form-item label="密码">
|
||||
<el-input v-model="password" type="password" placeholder="请输入密码" autocomplete="current-password" size="large"
|
||||
show-password @keyup.enter="doLogin" />
|
||||
</el-form-item>
|
||||
<el-button type="primary" size="large" class="primary" :loading="busy" @click="doLogin">
|
||||
{{ busy ? '进 入 中 …' : '进 入 工 作 台' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
|
||||
<div class="divider"><span>或</span></div>
|
||||
|
||||
<el-button size="large" class="dingtalk" :loading="dingBusy" :icon="ChatDotRound" @click="openDing">
|
||||
钉钉扫码接入
|
||||
</el-button>
|
||||
</main>
|
||||
|
||||
<!-- 底部:流程状态 -->
|
||||
<footer class="footbar">
|
||||
<div class="flows">
|
||||
<span>接入终端就绪</span>
|
||||
<span class="f-blocks" aria-hidden="true">
|
||||
<i></i><i></i><i></i><i></i><i></i>
|
||||
</span>
|
||||
</div>
|
||||
<span class="copyright">© 37du 自动化工作台</span>
|
||||
</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ChatDotRound } from '@element-plus/icons-vue'
|
||||
import { adminLogin, adminPassword, authDingtalk } from '../api'
|
||||
|
||||
defineProps({ appName: { type: String, default: '' } })
|
||||
const emit = defineEmits(['ok'])
|
||||
|
||||
const account = ref('')
|
||||
const password = ref('')
|
||||
const busy = ref(false)
|
||||
const dingBusy = ref(false)
|
||||
|
||||
async function doLogin() {
|
||||
if (busy.value) return
|
||||
if (!account.value.trim() || !password.value) { ElMessage.warning('请输入账号和密码'); return }
|
||||
busy.value = true
|
||||
try {
|
||||
const r = await adminLogin(account.value, password.value)
|
||||
ElMessage.success('登录成功')
|
||||
emit('ok', {
|
||||
account: account.value.trim(),
|
||||
is_admin: !!r.is_admin,
|
||||
dept: r.dept || '',
|
||||
must_change_pwd: !!r.must_change_pwd
|
||||
})
|
||||
} catch (e) {
|
||||
ElMessage.error('登录失败:' + (e.message || e))
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 钉钉扫码登录:壳后端直接生成授权 URL,当前窗口跳转钉钉;扫码后浏览器自动跳回 /auth/done
|
||||
async function openDing() {
|
||||
if (dingBusy.value) return
|
||||
dingBusy.value = true
|
||||
try {
|
||||
const r = await authDingtalk()
|
||||
if (r && r.url) {
|
||||
window.location.href = r.url
|
||||
return
|
||||
}
|
||||
ElMessage.error('钉钉登录未配置,请联系管理员')
|
||||
} catch (e) {
|
||||
ElMessage.error('钉钉登录不可用:' + (e.message || e))
|
||||
}
|
||||
dingBusy.value = false
|
||||
}
|
||||
|
||||
async function promptChangePwd(acc, r) {
|
||||
try {
|
||||
const { value: np } = await ElMessageBox.prompt(
|
||||
'当前为系统默认密码,请立即设置新密码(至少 6 位)',
|
||||
'首次登录 · 修改密码',
|
||||
{
|
||||
inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
|
||||
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说'
|
||||
})
|
||||
try {
|
||||
await adminPassword({ account: acc, old_password: '', new_password: np })
|
||||
ElMessage.success('密码已更新')
|
||||
} catch (e2) {
|
||||
ElMessage.warning('改密失败:' + (e2.message || e2))
|
||||
}
|
||||
} catch (_) { /* 用户取消 */ }
|
||||
emit('ok', { account: acc, is_admin: !!r.is_admin, dept: '', created: !!r.created, nickname: r.nickname || '' })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ============================================================
|
||||
暖米画布 + 工程网格 + 点阵 37 + 接入终端
|
||||
- 精密感来自网格与节点,不来自阴影
|
||||
- 体温红只出现在:port 聚焦、主按钮、管线节点、状态点
|
||||
============================================================ */
|
||||
|
||||
/* ---------- 画布 ---------- */
|
||||
.login {
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 110px 24px 170px;
|
||||
overflow: hidden;
|
||||
background: #EDE7DB;
|
||||
color: #1C1712;
|
||||
font-family: var(--font-body, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif);
|
||||
}
|
||||
|
||||
/* 工程网格:边缘径向淡出 */
|
||||
.login::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(28, 23, 18, .045) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(28, 23, 18, .045) 1px, transparent 1px);
|
||||
background-size: 44px 44px;
|
||||
-webkit-mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
mask-image: radial-gradient(ellipse 70% 60% at 50% 45%, #000 20%, transparent 78%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 顶部暖辉光 */
|
||||
.login::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 0;
|
||||
background: radial-gradient(660px 480px at 50% 38%, rgba(209, 74, 43, .06), transparent 68%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 巨大 37:节点阵列 ---------- */
|
||||
.ghost {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: -0.12em;
|
||||
transform: translateX(-50%);
|
||||
font-family: 'Helvetica Neue', 'Arial Narrow', Arial, sans-serif;
|
||||
font-size: clamp(280px, 74vw, 640px);
|
||||
font-weight: 800;
|
||||
line-height: .72;
|
||||
letter-spacing: -.08em;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
color: rgba(28, 23, 18, .05);
|
||||
/* 兜底 */
|
||||
animation: breathe 7s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes breathe {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .8;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@supports ((-webkit-background-clip: text) or (background-clip: text)) {
|
||||
.ghost {
|
||||
color: transparent;
|
||||
background-image: radial-gradient(circle at 1px 1px,
|
||||
rgba(28, 23, 18, .16) 1px, transparent 1.9px);
|
||||
background-size: 9px 9px;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 基线管道 ---------- */
|
||||
.pipeline {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 0;
|
||||
transform: translateX(-50%);
|
||||
width: min(920px, 92vw);
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg,
|
||||
transparent, rgba(28, 23, 18, .14) 18%,
|
||||
rgba(28, 23, 18, .14) 82%, transparent);
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pipeline i {
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .10);
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(1) {
|
||||
left: 22%;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(2) {
|
||||
left: 50%;
|
||||
animation: blip 3.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.pipeline i:nth-child(3) {
|
||||
left: 78%;
|
||||
}
|
||||
|
||||
@keyframes blip {
|
||||
|
||||
0%,
|
||||
100% {
|
||||
opacity: .35;
|
||||
transform: scale(.85);
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 顶部栏 ---------- */
|
||||
.topbar {
|
||||
position: absolute;
|
||||
top: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.mark {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex: none;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #F7F2E8;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: .01em;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 12.5px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .04em;
|
||||
color: #6B6155;
|
||||
}
|
||||
|
||||
.sys {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #D14A2B;
|
||||
animation: pulse 2.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, .4);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px rgba(209, 74, 43, 0);
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(209, 74, 43, 0);
|
||||
}
|
||||
}
|
||||
|
||||
.sep {
|
||||
color: #C4BBA8;
|
||||
}
|
||||
|
||||
/* ---------- 中央:接入终端 ---------- */
|
||||
.panel {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
max-width: 360px;
|
||||
padding: 40px 36px 36px;
|
||||
background: #F8F4EC;
|
||||
border: 1px solid #DDD4C2;
|
||||
border-radius: 14px;
|
||||
box-shadow:
|
||||
0 1px 0 rgba(255, 255, 255, .9) inset,
|
||||
0 24px 48px -28px rgba(28, 23, 18, .30);
|
||||
animation: rise .45s cubic-bezier(.22, 1, .36, 1) both;
|
||||
}
|
||||
|
||||
@keyframes rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* 卡片内元素依次点亮:终端端口逐个上电 */
|
||||
@keyframes seq {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(7px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
animation: seq .5s .05s both;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
animation: seq .5s .10s both;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
animation: seq .5s .15s both;
|
||||
}
|
||||
|
||||
.form {
|
||||
animation: seq .55s .20s both;
|
||||
}
|
||||
|
||||
.divider {
|
||||
animation: seq .5s .26s both;
|
||||
}
|
||||
|
||||
.dingtalk {
|
||||
animation: seq .5s .32s both;
|
||||
}
|
||||
|
||||
/* 底部金手指纹理 */
|
||||
.panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 36px;
|
||||
right: 36px;
|
||||
bottom: 0;
|
||||
height: 3px;
|
||||
background-image: repeating-linear-gradient(to right,
|
||||
rgba(201, 191, 171, .65) 0 8px,
|
||||
transparent 8px 12px);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.core-mark {
|
||||
display: block;
|
||||
margin-bottom: 20px;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .18em;
|
||||
color: #D14A2B;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 26px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
letter-spacing: -.01em;
|
||||
color: #1C1712;
|
||||
}
|
||||
|
||||
.panel .sub {
|
||||
margin: 0 0 34px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 表单:接口式输入 ---------- */
|
||||
.form :deep(.el-form-item) {
|
||||
position: relative;
|
||||
padding-left: 16px;
|
||||
margin-bottom: 26px;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__content) {
|
||||
position: relative;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
/* 左侧接口指示灯 */
|
||||
.form :deep(.el-form-item__content)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -16px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: #C9BFAB;
|
||||
transition: background .2s, box-shadow .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item:focus-within .el-form-item__content)::before {
|
||||
background: #D14A2B;
|
||||
box-shadow: 0 0 0 3px rgba(209, 74, 43, .12);
|
||||
}
|
||||
|
||||
.form :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
line-height: 1.4;
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* 底线式输入 */
|
||||
.form :deep(.el-input__wrapper) {
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
box-shadow: none !important;
|
||||
border-bottom: 1px solid #D8D0BC;
|
||||
transition: border-color .2s;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper:hover) {
|
||||
border-bottom-color: #BCB29A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__wrapper.is-focus) {
|
||||
border-bottom-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner) {
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
color: #1C1712;
|
||||
caret-color: #D14A2B;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__inner::placeholder) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix),
|
||||
.form :deep(.el-input__prefix),
|
||||
.form :deep(.el-input__suffix-inner) {
|
||||
color: #9A8F7A;
|
||||
}
|
||||
|
||||
.form :deep(.el-input__suffix-inner .el-input__icon:hover) {
|
||||
color: #635A4D;
|
||||
}
|
||||
|
||||
/* ---------- 主按钮 ---------- */
|
||||
.primary.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
margin-top: 6px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: #D14A2B;
|
||||
color: #FFF8F2;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .12em;
|
||||
box-shadow: 0 12px 28px -14px rgba(209, 74, 43, .7);
|
||||
transition: background-color .15s, opacity .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.primary.el-button:hover,
|
||||
.primary.el-button:focus {
|
||||
background: #BB3F21;
|
||||
color: #FFF8F2;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 15px 30px -14px rgba(209, 74, 43, .78);
|
||||
}
|
||||
|
||||
.primary.el-button:active {
|
||||
background: #A53517;
|
||||
transform: translateY(1px) scale(.99);
|
||||
box-shadow: 0 6px 16px -12px rgba(209, 74, 43, .8);
|
||||
}
|
||||
|
||||
.primary.el-button.is-disabled,
|
||||
.primary.el-button.is-loading {
|
||||
background: #D14A2B;
|
||||
opacity: .55;
|
||||
}
|
||||
|
||||
/* ---------- 分隔线 ---------- */
|
||||
.divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin: 28px 0 16px;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: .04em;
|
||||
color: #8D8476;
|
||||
}
|
||||
|
||||
.divider::before,
|
||||
.divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: #E0D9C6;
|
||||
}
|
||||
|
||||
/* ---------- 钉钉按钮 ---------- */
|
||||
.dingtalk.el-button {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #DED6C2;
|
||||
background: #FDFBF6;
|
||||
color: #1C1712;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
letter-spacing: .02em;
|
||||
transition: border-color .15s, background-color .15s, transform .12s ease, box-shadow .15s ease;
|
||||
}
|
||||
|
||||
.dingtalk.el-button:hover,
|
||||
.dingtalk.el-button:focus {
|
||||
border-color: #C4BBA8;
|
||||
background: #FFFFFF;
|
||||
color: #1C1712;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 8px 20px -14px rgba(28, 23, 18, .28);
|
||||
}
|
||||
|
||||
.dingtalk.el-button:active {
|
||||
transform: translateY(0) scale(.99);
|
||||
}
|
||||
|
||||
.dingtalk.el-button :deep(.el-icon) {
|
||||
color: #1491F0;
|
||||
}
|
||||
|
||||
/* ---------- 键盘可达 ---------- */
|
||||
.primary.el-button:focus-visible,
|
||||
.dingtalk.el-button:focus-visible {
|
||||
outline: 2px solid #D14A2B;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
/* ---------- 底部:流程状态 ---------- */
|
||||
.footbar {
|
||||
position: absolute;
|
||||
bottom: 40px;
|
||||
left: 48px;
|
||||
right: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 3;
|
||||
}
|
||||
|
||||
.flows {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .12em;
|
||||
color: #6F6659;
|
||||
}
|
||||
|
||||
.f-blocks {
|
||||
display: flex;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.f-blocks i {
|
||||
width: 12px;
|
||||
height: 4px;
|
||||
border-radius: 1px;
|
||||
background: #C9BEAA;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
font-size: 10.5px;
|
||||
letter-spacing: .1em;
|
||||
color: #9A8F7C;
|
||||
}
|
||||
|
||||
/* ---------- 自适应 ---------- */
|
||||
@media (max-width: 720px) {
|
||||
.login {
|
||||
padding: 96px 20px 140px;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
top: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
bottom: 24px;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
padding: 32px 24px 30px;
|
||||
}
|
||||
|
||||
.panel h1 {
|
||||
font-size: 23px;
|
||||
}
|
||||
|
||||
.panel::after {
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
}
|
||||
|
||||
.copyright {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 680px) {
|
||||
.login {
|
||||
align-items: flex-start;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding: 80px 24px 120px;
|
||||
}
|
||||
|
||||
.footbar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
.dot,
|
||||
.pipeline i,
|
||||
.ghost {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.panel {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.core-mark,
|
||||
.panel h1,
|
||||
.panel .sub,
|
||||
.form,
|
||||
.divider,
|
||||
.dingtalk {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
* {
|
||||
transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,279 @@
|
||||
<template>
|
||||
<div v-if="plugin" class="plugin-page">
|
||||
<!-- 页头 -->
|
||||
<div class="head">
|
||||
<div class="ident">
|
||||
<span class="avatar" :style="{ background: avatarBg }">{{ plugin.name.slice(0, 1) }}</span>
|
||||
<div class="ident-meta">
|
||||
<h2>{{ plugin.name }} <span class="ver-tag">v{{ plugin.version }}</span></h2>
|
||||
<p>{{ plugin.description || '暂无描述' }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="plugin?.uses_month" class="month">
|
||||
<span class="field-label">执行月份</span>
|
||||
<el-select v-model="month" class="month-sel" :disabled="store.running">
|
||||
<el-option v-for="m in months" :key="m" :value="m" :label="m" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果横幅 -->
|
||||
<el-alert v-if="store.lastResult" :type="store.lastResult.ok ? 'success' : 'error'" :closable="true"
|
||||
:close-text="null" class="banner" @close="closeBanner" show-icon>
|
||||
<template #title>
|
||||
<span>
|
||||
{{ store.lastResult.ok ? (store.lastSummary || '执行完成') : '执行失败:' + store.lastResult.error }}
|
||||
</span>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<!-- 参数 -->
|
||||
<div class="sec-head">
|
||||
<span class="sec-title">参数配置</span>
|
||||
<el-button v-if="Object.keys(form).length" size="small" text :disabled="store.running" :icon="RefreshLeft"
|
||||
@click="resetForm">恢复默认</el-button>
|
||||
</div>
|
||||
<el-form label-width="auto" class="form-card">
|
||||
<div class="fields">
|
||||
<el-form-item v-for="f in plugin.fields" :key="f.key" :label="f.label">
|
||||
<template v-if="f.type === 'int'">
|
||||
<el-input-number v-model="form[f.key]" :controls="false" placeholder="0" :disabled="store.running" />
|
||||
</template>
|
||||
<el-input v-else-if="f.type === 'text'" v-model="form[f.key]" :placeholder="String(f.default ?? '')"
|
||||
:disabled="store.running">
|
||||
<template v-if="f.help" #suffix>
|
||||
<el-tooltip :content="f.help" placement="bottom"><el-icon class="help-ic">
|
||||
<QuestionFilled />
|
||||
</el-icon></el-tooltip>
|
||||
</template>
|
||||
</el-input>
|
||||
<el-select v-else v-model="form[f.key]" :disabled="store.running">
|
||||
<el-option v-for="opt in f.options" :key="opt" :value="opt" :label="opt" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<span v-if="store.running" class="run-ind">
|
||||
<el-progress :percentage="store.progress" :show-text="false" color="#3b6cff" />
|
||||
</span>
|
||||
<el-button type="primary" size="large" :loading="store.running" @click="run">
|
||||
{{ store.running ? '执行中 ' + store.progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
<p class="hint">执行日志与进度实时显示在下方日志区,结果完成后自动汇总于此。</p>
|
||||
</div>
|
||||
|
||||
<el-empty v-else-if="!store.plugins.length" description="当前账号暂无可用场景" />
|
||||
<el-empty v-else description="未选择场景" />
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { QuestionFilled, RefreshLeft } from '@element-plus/icons-vue'
|
||||
import { store, log } from '../store'
|
||||
import { startRun, getRun } from '../api'
|
||||
|
||||
const months = computed(() => {
|
||||
const now = new Date()
|
||||
const list = []
|
||||
for (let off = 1; off <= 6; off++) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - off, 1)
|
||||
list.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
|
||||
}
|
||||
return list
|
||||
})
|
||||
const month = ref(months.value[0])
|
||||
|
||||
const PALETTE = ['#3b6cff', '#7c5cff', '#12a4d8', '#22b07a', '#e88a3a', '#e5484d']
|
||||
const idx = computed(() => Math.max(0, store.plugins.findIndex((p) => p.id === store.selectedId)))
|
||||
const avatarBg = computed(() => PALETTE[idx.value % PALETTE.length])
|
||||
|
||||
const plugin = computed(() => store.plugins.find((p) => p.id === store.selectedId) || null)
|
||||
|
||||
const form = ref({})
|
||||
|
||||
function buildFormDefaults(p) {
|
||||
const f = {}
|
||||
if (p) p.fields.forEach((x) => (f[x.key] = x.default ?? (x.type === 'int' ? 0 : '')))
|
||||
return f
|
||||
}
|
||||
|
||||
watch(
|
||||
() => plugin.value?.id,
|
||||
(id) => {
|
||||
form.value = buildFormDefaults(store.plugins.find((x) => x.id === id))
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
function resetForm() {
|
||||
form.value = buildFormDefaults(plugin.value)
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (!plugin.value || store.running) return
|
||||
if (plugin.value.platform && !(store.platforms.find((p) => p.id === plugin.value.platform)?.online)) {
|
||||
log('WARN', `插件「${plugin.value.name}」需要先登录平台「${store.platforms.find((p) => p.id === plugin.value.platform)?.label || plugin.value.platform}」才能正确执行`)
|
||||
}
|
||||
store.running = true
|
||||
store.progress = 0
|
||||
store.currentRun = ''
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
const payload = { ...form.value }
|
||||
if (plugin.value.uses_month) payload.ref_month = month.value // 仅月度插件注入月份
|
||||
try {
|
||||
const r = await startRun(plugin.value.id, payload)
|
||||
store.lastRunId = r.run_id
|
||||
} catch (e) {
|
||||
store.running = false
|
||||
store.lastResult = { ok: false, error: e.message || String(e) }
|
||||
log('ERROR', `启动执行失败:${e.message || e}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 完成时拉取后端摘要填充横幅
|
||||
watch(
|
||||
() => store.lastResult,
|
||||
async (res) => {
|
||||
if (res && res.ok && store.lastRunId) {
|
||||
try {
|
||||
const run = await getRun(store.lastRunId)
|
||||
store.lastSummary = run.result?.summary || ''
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function closeBanner() {
|
||||
store.lastResult = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.plugin-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.ident {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 13px;
|
||||
flex-shrink: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.ident-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.ident-meta h2 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.ident-meta p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-sub);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.ver-tag {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--text-faint);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
padding: 1px 7px;
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.month {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.month-sel {
|
||||
width: 120px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-card .el-form-item {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.help-ic {
|
||||
color: var(--text-faint);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 14px;
|
||||
border-top: 1px dashed var(--border);
|
||||
padding-top: 14px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.run-ind {
|
||||
flex: 1;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-faint);
|
||||
margin: 0;
|
||||
padding-left: 2px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,309 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="350px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<el-avatar :size="60" :src="store.avatarUrl" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1).toUpperCase() }}</span>
|
||||
</el-avatar>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
<em v-if="store.isAdmin" class="admin">管理员</em>
|
||||
</div>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>已授权插件</span>
|
||||
<span class="mono">{{ store.plugins.length }}</span>
|
||||
</div>
|
||||
<div class="crow">
|
||||
<span>平台在线</span>
|
||||
<span class="mono">{{ store.platforms.filter(p => p.online).length }}/{{ store.platforms.length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 平台登录态 -->
|
||||
<el-collapse v-model="activeNames">
|
||||
<el-collapse-item name="platforms">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Connection /></el-icon>
|
||||
<span>平台登录态</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-for="(p, i) in store.platforms" :key="p.id" class="prow">
|
||||
<span class="ridx mono">P0{{ i + 1 }}</span>
|
||||
<span class="dot" :class="{ on: p.online }"></span>
|
||||
<span class="pname">{{ p.label }}</span>
|
||||
<el-button size="small" :disabled="busy === p.id || p.online" @click="relogin(p.id)">
|
||||
{{ busy === p.id ? '处理中…' : p.online ? '正常' : '重新登录' }}
|
||||
</el-button>
|
||||
<el-button v-if="p.online" size="small" plain type="danger" :disabled="busy === p.id" @click="logout(p.id)">登出</el-button>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
|
||||
<!-- 我的插件 -->
|
||||
<el-collapse-item name="plugins">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Box /></el-icon>
|
||||
<span>我的插件 ({{ store.plugins.length }})</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-if="!store.plugins.length" description="当前账号暂无可用插件" />
|
||||
<div v-else class="ilist">
|
||||
<div v-for="(p, i) in store.plugins" :key="p.id" class="irow">
|
||||
<span class="ridx mono">{{ String(i + 1).padStart(2, '0') }}</span>
|
||||
<span class="iname">{{ p.name }}</span>
|
||||
<span class="mono iver">v{{ p.version }}</span>
|
||||
<span class="i-dot"></span>
|
||||
</div>
|
||||
</div>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
|
||||
<!-- 修改密码 -->
|
||||
<el-card class="pwd-card" shadow="never" title="修改密码">
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef">
|
||||
<el-form-item label="旧密码" prop="oldPwd">
|
||||
<el-input v-model="form.oldPwd" type="password" show-password placeholder="请输入旧密码" />
|
||||
</el-form-item>
|
||||
<el-form-item label="新密码" prop="newPwd">
|
||||
<el-input v-model="form.newPwd" type="password" show-password placeholder="至少 6 位,不与原密码相同" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认新密码" prop="newPwd2">
|
||||
<el-input v-model="form.newPwd2" type="password" show-password placeholder="再次输入新密码" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="pwdBusy" @click="changePwd" style="width: 100%">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword } from '../api'
|
||||
|
||||
const emit = defineEmits(['close'])
|
||||
// 由父组件 v-if 控制挂载,挂载即展开;关闭经 @close 通知父组件卸载
|
||||
const visible = ref(true)
|
||||
|
||||
// 展示名:优先真实姓名(钉钉登录带入),无姓名时回退账号(工号)
|
||||
const displayName = computed(() => store.nickname || store.current)
|
||||
|
||||
// 头像:复用全局 store 的在线头像(带 localStorage 缓存);加载失败时清除缓存并回退首字符色块
|
||||
function onAvatarError() {
|
||||
clearAvatarCache()
|
||||
}
|
||||
|
||||
const activeNames = ref(['platforms', 'plugins'])
|
||||
const busy = ref('')
|
||||
|
||||
async function relogin(id) {
|
||||
if (busy.value) return
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p?.online) {
|
||||
ElMessage.success(`${p.label} 已登录`)
|
||||
return
|
||||
}
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await loginPlatform(id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 登录成功`)
|
||||
ElMessage.success(`平台 ${p.label} 登录成功`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登录失败:${e.message || e}`)
|
||||
ElMessage.error(`登录失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function logout(id) {
|
||||
busy.value = id
|
||||
try {
|
||||
const r = await logoutPlatform(id)
|
||||
const p = store.platforms.find((x) => x.id === id)
|
||||
if (p) {
|
||||
p.online = !!r.online
|
||||
log('INFO', `平台 ${p.label} 已登出`)
|
||||
ElMessage.success(`平台 ${p.label} 已登出`)
|
||||
}
|
||||
} catch (e) {
|
||||
log('ERROR', `平台 ${(store.platforms.find((x) => x.id === id) || {}).label || id} 登出失败:${e.message || e}`)
|
||||
ElMessage.error(`登出失败:${e.message || e}`)
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 修改密码
|
||||
const formRef = ref()
|
||||
const form = reactive({ oldPwd: '', newPwd: '', newPwd2: '' })
|
||||
const rules = {
|
||||
oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
|
||||
newPwd: [
|
||||
{ required: true, message: '请输入新密码', trigger: 'blur' },
|
||||
{ min: 6, message: '新密码至少 6 位', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v && v === form.oldPwd
|
||||
? cb(new Error('新密码不能与原密码相同')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
newPwd2: [
|
||||
{ required: true, message: '请再次输入新密码', trigger: 'blur' },
|
||||
{
|
||||
validator: (_, v, cb) => (v !== form.newPwd
|
||||
? cb(new Error('两次输入的密码不一致')) : cb()),
|
||||
trigger: 'blur'
|
||||
},
|
||||
],
|
||||
}
|
||||
const pwdBusy = ref(false)
|
||||
async function changePwd() {
|
||||
await formRef.value.validate().catch(() => Promise.reject())
|
||||
pwdBusy.value = true
|
||||
try {
|
||||
await adminPassword({
|
||||
account: store.current,
|
||||
old_password: form.oldPwd,
|
||||
new_password: form.newPwd,
|
||||
})
|
||||
ElMessage.success('密码已修改,下次登录请使用新密码')
|
||||
form.oldPwd = form.newPwd = form.newPwd2 = ''
|
||||
setTimeout(() => emit('close'), 800)
|
||||
} catch (e) {
|
||||
ElMessage.error('修改失败:' + (e.message || e))
|
||||
} finally {
|
||||
pwdBusy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mono { font-family: var(--font-mono); letter-spacing: .04em; }
|
||||
|
||||
/* ================= 个人信息卡 ================= */
|
||||
.pcard {
|
||||
margin-bottom: 18px;
|
||||
background: #ffffff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 10px 28px -18px rgba(23, 24, 26, .35);
|
||||
}
|
||||
.cover {
|
||||
height: 66px;
|
||||
background:
|
||||
radial-gradient(360px 200px at 90% -30%, rgba(208, 74, 36, .5), transparent 60%),
|
||||
radial-gradient(300px 180px at -10% 120%, rgba(120, 128, 140, .4), transparent 60%),
|
||||
#1a1c1f;
|
||||
position: relative;
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 16px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 6px 16px -6px rgba(23, 24, 26, .45);
|
||||
background: #17181a;
|
||||
color: #f6f4ec;
|
||||
font-weight: 700;
|
||||
flex: none;
|
||||
}
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong { font-size: 16px; letter-spacing: .01em; color: #17181a; }
|
||||
.admin {
|
||||
font-style: normal; font-size: 10.5px; font-weight: 600;
|
||||
color: #d04a24;
|
||||
border: 1px solid rgba(208, 74, 36, .35);
|
||||
background: rgba(208, 74, 36, .07);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
letter-spacing: .04em;
|
||||
}
|
||||
.dept { font-size: 12px; color: var(--text-faint); }
|
||||
|
||||
.pcard-rows { border-top: 1px solid var(--border); }
|
||||
.crow {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 11px 18px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
.crow:last-child { border-bottom: none; }
|
||||
.crow span:first-child { color: var(--text-sub); }
|
||||
.crow .mono { color: #17181a; font-size: 13px; font-weight: 600; }
|
||||
|
||||
/* ================= 折叠面板 ================= */
|
||||
.panel-title { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-sub); }
|
||||
.panel-title :deep(.el-icon) { color: #d04a24; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.prow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.prow:last-child { border-bottom: none; }
|
||||
.ridx { flex: none; width: 26px; font-size: 11px; color: var(--text-faint); }
|
||||
.dot {
|
||||
flex: none; width: 7px; height: 7px; border-radius: 50%;
|
||||
background: #c6ccdc;
|
||||
}
|
||||
.dot.on { background: #22b07a; box-shadow: 0 0 0 3px rgba(34, 176, 122, .16); }
|
||||
.pname { flex: 1; color: var(--text-sub); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.prow :deep(.el-button--primary) { border-color: transparent; }
|
||||
.prow :deep(.el-button--danger.is-plain) { border-color: rgba(214, 69, 69, .35); color: #d64545; }
|
||||
|
||||
/* ---------- 我的插件:台账式列表 ---------- */
|
||||
.ilist { display: flex; flex-direction: column; }
|
||||
.irow {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 11px 0;
|
||||
border-bottom: 1px dashed var(--border);
|
||||
}
|
||||
.irow:last-child { border-bottom: none; }
|
||||
.iname { flex: 1; color: var(--text); font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iver { font-size: 11px; color: var(--text-faint); }
|
||||
.i-dot { flex: none; width: 5px; height: 5px; border-radius: 50%; background: #d04a24; }
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-card { margin-top: 16px; border-radius: 14px; border-color: var(--border); }
|
||||
.pwd-card :deep(.el-card__header) {
|
||||
font-size: 13px; font-weight: 600;
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.pwd-card :deep(.el-card__body) { padding: 16px; }
|
||||
.pwd-card :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-card :deep(.el-button--primary) { width: 100%; border-color: transparent; background: #17181a; }
|
||||
.pwd-card :deep(.el-button--primary:hover) { background: #26282c; }
|
||||
</style>
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import 'element-plus/dist/index.css'
|
||||
import App from './App.vue'
|
||||
import './style.css'
|
||||
|
||||
const app = createApp(App)
|
||||
// 全量注册图标,模板中可直接 <component :is="XxxIcon"> 使用
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component)
|
||||
}
|
||||
app.use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,93 @@
|
||||
import { reactive } from 'vue'
|
||||
|
||||
export const store = reactive({
|
||||
appName: '',
|
||||
controlplane: '', // 控制面地址(管理员跳转用),来自 /api/meta
|
||||
platforms: [],
|
||||
plugins: [],
|
||||
selectedId: '',
|
||||
logs: [], // {time, level, msg}
|
||||
progress: 0,
|
||||
running: false,
|
||||
currentRun: '', // 当前接收日志/进度的 run_id
|
||||
lastRunId: '', // 最近一次执行的 run_id
|
||||
lastResult: null, // {ok, error}
|
||||
lastSummary: '', // 完成时后端返回的摘要
|
||||
wsOn: false,
|
||||
// 控制面管理视图(统一后端数据库 API)
|
||||
isAdmin: false,
|
||||
dept: '',
|
||||
nickname: '', // 真实姓名(中心机 accounts.nickname,钉钉登录时自动带入)
|
||||
avatarUrl: '', // 在线头像(localStorage 缓存,避免每次刷新都请求)
|
||||
current: (() => { try { return localStorage.getItem('cp_account') || '' } catch (_) { return '' } })(),
|
||||
view: 'plugin', // 'plugin' | 'admin'
|
||||
})
|
||||
|
||||
// ===== 在线头像:优先读缓存,无缓存时请求接口并落盘;图片加载失败时清除缓存重新拉取 =====
|
||||
// 缓存按账号隔离(cp_avatar_url_<账号>),切换账号不会串用上一个人的头像
|
||||
const AVATAR_API = 'https://v2.xxapi.cn/api/head'
|
||||
|
||||
function avatarCacheKey() {
|
||||
return `cp_avatar_url_${store.current || 'anon'}`
|
||||
}
|
||||
|
||||
export function loadAvatar() {
|
||||
const key = avatarCacheKey()
|
||||
try {
|
||||
const cached = localStorage.getItem(key)
|
||||
if (cached) { store.avatarUrl = cached; return }
|
||||
} catch (_) {}
|
||||
store.avatarUrl = ''
|
||||
fetch(AVATAR_API, { signal: AbortSignal.timeout(4000) })
|
||||
.then((r) => r.json())
|
||||
.then((j) => {
|
||||
if (j && j.code === 200 && j.data) {
|
||||
store.avatarUrl = j.data
|
||||
try { localStorage.setItem(avatarCacheKey(), j.data) } catch (_) {}
|
||||
}
|
||||
})
|
||||
.catch(() => { /* 网络不可达/超时:保持首字符色块兜底 */ })
|
||||
}
|
||||
|
||||
export function clearAvatarCache() {
|
||||
store.avatarUrl = ''
|
||||
try { localStorage.removeItem(avatarCacheKey()) } catch (_) {}
|
||||
loadAvatar()
|
||||
}
|
||||
|
||||
export function clearLogs() {
|
||||
store.logs = []
|
||||
store.lastResult = null
|
||||
store.lastSummary = ''
|
||||
}
|
||||
|
||||
export function log(level, msg) {
|
||||
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
store.logs.push({ time, level, msg })
|
||||
if (store.logs.length > 500) store.logs.splice(0, store.logs.length - 500)
|
||||
}
|
||||
|
||||
export function handleEvent(ev) {
|
||||
switch (ev.t) {
|
||||
case 'run_start':
|
||||
store.currentRun = ev.run_id
|
||||
if (!store.running) { clearLogs() }
|
||||
break
|
||||
case 'log':
|
||||
if (ev.run_id === store.currentRun || !store.currentRun) {
|
||||
log(ev.level || 'INFO', ev.msg)
|
||||
}
|
||||
break
|
||||
case 'progress':
|
||||
if (ev.run_id === store.currentRun) store.progress = ev.pct
|
||||
break
|
||||
case 'run_done':
|
||||
store.running = false
|
||||
store.progress = 100
|
||||
store.lastResult = { ok: ev.ok, error: ev.error || '' }
|
||||
if (ev.ok) log('INFO', '===== 执行完成 =====')
|
||||
else log('ERROR', `执行失败:${ev.error}`)
|
||||
store.currentRun = ''
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/* ============ 37du Web Host 设计系统(亮色) ============ */
|
||||
:root {
|
||||
--bg: #eef2f9;
|
||||
--bg-grad: linear-gradient(180deg, #f4f7fc 0%, #e9eef7 100%);
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f7f9fd;
|
||||
--border: #e5eaf3;
|
||||
--border-strong: #cdd6e6;
|
||||
|
||||
--text: #1f2633;
|
||||
--text-sub: #5b6477;
|
||||
--text-faint: #98a0b3;
|
||||
|
||||
--primary: #3b6cff;
|
||||
--primary-2: #6f8dff;
|
||||
--primary-grad: linear-gradient(135deg, #4c79ff 0%, #3b6cff 100%);
|
||||
--primary-weak: #eef2ff;
|
||||
--primary-weak-2: #e2e9ff;
|
||||
|
||||
--ok: #22b07a;
|
||||
--ok-weak: #e6f7f0;
|
||||
--err: #e5484d;
|
||||
--err-weak: #fdecec;
|
||||
--warn: #d99a1b;
|
||||
|
||||
--shadow-sm: 0 1px 2px rgba(24, 39, 75, 0.05);
|
||||
--shadow-md: 0 6px 24px -8px rgba(24, 39, 75, 0.18);
|
||||
--radius: 14px;
|
||||
--radius-sm: 9px;
|
||||
--mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-mono: "JetBrains Mono", "Consolas", "Courier New", monospace;
|
||||
--font-body: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
|
||||
/* element-plus 主题与品牌蓝统一 */
|
||||
--el-color-primary: #3b6cff;
|
||||
--el-color-primary-light-3: #6f8dff;
|
||||
--el-color-primary-light-5: #a3b7ff;
|
||||
--el-color-primary-light-7: #d0dcff;
|
||||
--el-color-primary-light-8: #e2e9ff;
|
||||
--el-color-primary-light-9: #eef2ff;
|
||||
--el-color-primary-dark-2: #2f56d6;
|
||||
--el-border-radius-base: 8px;
|
||||
--el-border-radius-small: 6px;
|
||||
--el-border-radius-round: 20px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Inter", "Microsoft YaHei UI", "PingFang SC", -apple-system, sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.__app {
|
||||
height: 100%;
|
||||
background: var(--bg-grad);
|
||||
padding: 16px 18px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* 滚动条 */
|
||||
::-webkit-scrollbar { width: 10px; height: 10px; }
|
||||
::-webkit-scrollbar-thumb { background: #d4dae8; border-radius: 6px; border: 2px solid transparent; background-clip: content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: #c1c9dc; background-clip: content-box; border: 2px solid transparent; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
|
||||
/* 通用白卡 */
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
/* 分节标题 */
|
||||
.sec-title {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* 按钮 */
|
||||
.btn {
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--surface);
|
||||
color: var(--text-sub);
|
||||
border-radius: 8px;
|
||||
padding: 7px 16px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: all .15s ease;
|
||||
}
|
||||
.btn:hover { color: var(--text); border-color: #b9c3d8; background: var(--surface-2); }
|
||||
.btn:active { transform: translateY(1px); }
|
||||
.btn:disabled { color: #c0c6d4; border-color: var(--border); background: #f4f6fb; cursor: not-allowed; transform: none; }
|
||||
|
||||
.btn.primary {
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
border: 1px solid transparent;
|
||||
font-weight: 600;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, 0.55);
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) { box-shadow: 0 8px 20px -6px rgba(59, 108, 255, 0.65); color: #fff; }
|
||||
.btn.primary:disabled { background: #b9c6f0; box-shadow: none; }
|
||||
|
||||
/* 输入 / 选择 */
|
||||
.input {
|
||||
height: 34px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
padding: 0 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.input:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-weak); }
|
||||
select.input { padding-right: 30px; appearance: none; cursor: pointer;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%237b8497' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat; background-position: right 10px center; }
|
||||
.field-label { color: var(--text-sub); font-size: 13px; }
|
||||
|
||||
/* 进度条 */
|
||||
.progress { height: 8px; width: 180px; background: #e8ecf5; border-radius: 6px; overflow: hidden; }
|
||||
.progress > div { height: 100%; border-radius: 6px;
|
||||
background: var(--primary-grad);
|
||||
transition: width .25s ease;
|
||||
box-shadow: 0 0 6px rgba(59,108,255,.5); }
|
||||
|
||||
/* 日志 */
|
||||
.log-box {
|
||||
font-family: var(--mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.75;
|
||||
color: var(--text);
|
||||
padding: 12px 14px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
.log-line:hover { background: #f7f9fd; }
|
||||
.log-box .t { color: var(--text-faint); margin-right: 10px; user-select: none; }
|
||||
.log-box .lv { margin-right: 6px; font-weight: 700; }
|
||||
.log-box .s-INFO { color: var(--primary); }
|
||||
.log-box .s-ERROR { color: var(--err); }
|
||||
.log-box .s-WARN { color: var(--warn); }
|
||||
|
||||
/* 过渡 */
|
||||
.fade-enter-active, .fade-leave-active { transition: opacity .18s ease, transform .18s ease; }
|
||||
.fade-enter-from { opacity: 0; transform: translateY(4px); }
|
||||
.fade-leave-to { opacity: 0; }
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// dev 时把 /api 与 /ws 代理到 FastAPI 后端,实现前后端分离开发
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
import psutil
|
||||
|
||||
FROZEN = getattr(sys, "frozen", False)
|
||||
PORT = 8799
|
||||
URL = f"http://127.0.0.1:{PORT}"
|
||||
HERE = Path(sys.executable).resolve().parent if FROZEN else Path(__file__).resolve().parent
|
||||
PID_FILE = HERE / ".webhost.pid"
|
||||
|
||||
|
||||
def _port_pids() -> list[int]:
|
||||
return [c.pid for c in psutil.net_connections(kind="inet")
|
||||
if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid]
|
||||
|
||||
|
||||
def _kill_existing() -> None:
|
||||
"""杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。"""
|
||||
targets = set(_port_pids())
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
targets.add(int(PID_FILE.read_text().strip()))
|
||||
except ValueError:
|
||||
pass
|
||||
for pid in targets:
|
||||
try:
|
||||
proc = psutil.Process(pid)
|
||||
if proc.name().lower().startswith(("python", "uvicorn", "37du-host")):
|
||||
proc.terminate()
|
||||
proc.wait(timeout=4)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
continue
|
||||
for _ in range(40): # 等待端口释放
|
||||
if not _port_pids():
|
||||
break
|
||||
time.sleep(0.25)
|
||||
|
||||
|
||||
def _port_free() -> bool:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
return s.connect_ex(("127.0.0.1", PORT)) != 0
|
||||
|
||||
|
||||
def _wait_ready(proc: subprocess.Popen | None) -> None:
|
||||
for _ in range(60): # 等待就绪
|
||||
if not _port_free():
|
||||
return
|
||||
if proc is not None and proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
raise RuntimeError("服务启动失败")
|
||||
|
||||
|
||||
def _start_server():
|
||||
"""拉起 uvicorn 服务:源码运行=子进程;打包运行=进程内后台线程。"""
|
||||
if not _port_free():
|
||||
_kill_existing()
|
||||
time.sleep(0.3)
|
||||
if FROZEN:
|
||||
# 窗口模式无 stdout/stderr(None),uvicorn 日志 formatter 会调 sys.stdout.isatty() 崩溃
|
||||
_devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115 进程级常驻
|
||||
sys.stdout = sys.stderr = _devnull
|
||||
import uvicorn
|
||||
from webhost.backend.main import app
|
||||
|
||||
def _serve() -> None:
|
||||
try:
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="warning")
|
||||
except BaseException:
|
||||
import traceback
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
|
||||
t = threading.Thread(target=_serve, daemon=True, name="uvicorn")
|
||||
t.start()
|
||||
_wait_ready(None)
|
||||
return t
|
||||
cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app",
|
||||
"--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"]
|
||||
proc = subprocess.Popen(cmd, cwd=str(HERE.parent),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
PID_FILE.write_text(str(proc.pid))
|
||||
_wait_ready(proc)
|
||||
return proc
|
||||
|
||||
|
||||
def _apply_win11_corners(window) -> None:
|
||||
"""Win11 窗口圆角:去掉老式方角观感(DWM 设置圆角偏好,失败静默忽略)。"""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||
DWMWCP_ROUND = 2
|
||||
|
||||
def _on_shown():
|
||||
try:
|
||||
hwnd = int(window.native.Handle)
|
||||
ctypes.windll.dwmapi.DwmSetWindowAttribute(
|
||||
ctypes.c_int(hwnd),
|
||||
ctypes.c_int(DWMWA_WINDOW_CORNER_PREFERENCE),
|
||||
ctypes.byref(ctypes.c_int(DWMWCP_ROUND)),
|
||||
ctypes.c_int(4),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
window.events.shown += _on_shown
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _open_window(app_name: str) -> bool:
|
||||
"""尝试 PyWebView 原生窗口;失败返回显示不可用。"""
|
||||
try:
|
||||
import webview # noqa: WPS433
|
||||
|
||||
window = webview.create_window(app_name, URL,
|
||||
width=1200, height=780, min_size=(1000, 660),
|
||||
background_color="#eef2f9")
|
||||
_apply_win11_corners(window)
|
||||
webview.start(gui="edgechromium")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _stop(server) -> None:
|
||||
if isinstance(server, threading.Thread):
|
||||
# 打包运行:uvicorn 为进程内线程,进程退出即随之结束,无需也无法 terminate
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
try:
|
||||
server.terminate()
|
||||
server.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
server.kill()
|
||||
except Exception:
|
||||
pass
|
||||
if PID_FILE.exists():
|
||||
try:
|
||||
PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def main() -> int:
|
||||
app_name = "37du 自动化工作台"
|
||||
# 任务栏图标分组/固定:统一 AppUserModelID(如做快捷方式需保持一致)
|
||||
try:
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("37du.Host")
|
||||
except Exception:
|
||||
pass
|
||||
proc = _start_server()
|
||||
|
||||
if not _open_window(app_name):
|
||||
# 回退:系统浏览器
|
||||
webbrowser.open(URL)
|
||||
print(f"[webhost] 已用系统浏览器打开:{URL}")
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
_stop(proc)
|
||||
return 0
|
||||
else:
|
||||
_stop(proc)
|
||||
return 0
|
||||
|
||||
|
||||
def _fatal_log(msg: str) -> None:
|
||||
"""窗口模式无控制台:崩溃现场落盘到 exe 同级 crash.log,便于诊断。"""
|
||||
try:
|
||||
(HERE / "crash.log").write_text(msg, encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except Exception:
|
||||
import traceback
|
||||
if FROZEN:
|
||||
_fatal_log(traceback.format_exc())
|
||||
raise
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
@@ -0,0 +1,49 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + plugins/
|
||||
; 不含: 37du-host-console.exe(调试版)、.env(机器特定配置,缺失时使用默认值)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.0.0"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
AppId={{8F3D5C7A-2B41-4E9A-9D6C-37DUE5A1B0F0}
|
||||
AppName={#MyAppName}
|
||||
AppVersion={#MyAppVersion}
|
||||
AppPublisher=37du
|
||||
DefaultDirName={localappdata}\Programs\37duHost
|
||||
PrivilegesRequired=lowest
|
||||
OutputDir=..\installer
|
||||
OutputBaseFilename=setup-37du-host-{#MyAppVersion}
|
||||
Compression=lzma2
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
UninstallDisplayName={#MyAppName}
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "创建桌面快捷方式"; GroupDescription: "附加任务:"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
; 主程序 onedir 目录(exe + _internal 依赖)
|
||||
Source: "..\dist-exe\37du-host\*"; DestDir: "{app}"; Flags: recursesubdirs ignoreversion
|
||||
; 插件执行壳(onefile 单文件,需与主程序 exe 同级)
|
||||
Source: "..\dist-exe\37du-host-runner.exe"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 壳子版本标记:执行端据此比对控制面版本判断是否需要自动升级
|
||||
Source: "..\tools\shell.version"; DestDir: "{app}"; Flags: ignoreversion
|
||||
; 插件不由安装包分发:执行机首次启动/登录后按账号权限从控制面自下载(见 backend/core/plugin_sync.py)
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"
|
||||
Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; AppUserModelID: "37du.Host"; Tasks: desktopicon
|
||||
|
||||
[Run]
|
||||
; 交互安装:向导结束自动启动;静默升级(/VERYSILENT)后也自动启动新版本,实现"重启自动更新"
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "立即启动 {#MyAppName}"; Flags: nowait postinstall
|
||||
|
||||
[UninstallDelete]
|
||||
; 卸载时清理整个安装目录(含运行期生成的 .webhost.pid / _cp_sessions.json 等)
|
||||
Type: filesandordirs; Name: "{app}"
|
||||
@@ -0,0 +1 @@
|
||||
1.0.0
|
||||
Reference in New Issue
Block a user