rescue: 断电事故后工作区全量备份
This commit is contained in:
@@ -262,7 +262,8 @@ def _shell_meta() -> dict:
|
||||
if not vf.is_file():
|
||||
return {}
|
||||
try:
|
||||
d = json.loads(vf.read_text(encoding="utf-8"))
|
||||
# utf-8-sig:防 version.json 带 UTF-8 BOM(否则 json.loads 抛 JSONDecodeError → 回退失败)
|
||||
d = json.loads(vf.read_text(encoding="utf-8-sig"))
|
||||
return d if isinstance(d, dict) else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
|
||||
+220
-220
@@ -1,220 +1,220 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||||
|
||||
后台线程发送,失败仅记日志不阻断业务。
|
||||
|
||||
配置项(controlplane/.env):
|
||||
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||||
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||||
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||||
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote_plus
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||||
_SIGN_NAME = "37du 自动化平台"
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _footer() -> str:
|
||||
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||||
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||||
"""unionid → userid(精确,无重名歧义)。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||||
{"unionid": unionid})
|
||||
return ((body.get("result") or {}).get("userid")) or ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _userid_by_name(at: str, name: str) -> str:
|
||||
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||||
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||||
headers={"x-acs-dingtalk-access-token": at})
|
||||
lst = body.get("list") or []
|
||||
return str(lst[0]) if lst else ""
|
||||
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||||
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||||
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||||
status: str = "info") -> bool:
|
||||
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||||
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += f"\n\n---\n\n{_footer()}"
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||||
{"agent_id": agent_id, "userid_list": userid,
|
||||
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉工作通知被拒: %s", body)
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉工作通知异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||||
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
if not agent_id:
|
||||
return
|
||||
try:
|
||||
at = _dingtalk_topapi_token()
|
||||
if not at:
|
||||
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||||
return
|
||||
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||||
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||||
if not uid and nickname:
|
||||
uid = _userid_by_name(at, nickname)
|
||||
if uid:
|
||||
_send_work_to(
|
||||
at, agent_id, uid, "账号开通通知",
|
||||
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 初始密码:{password}\n\n"
|
||||
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||||
status="success")
|
||||
else:
|
||||
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||||
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||||
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||||
admin_uid = _userid_by_name(at, admin_name)
|
||||
if admin_uid:
|
||||
_send_work_to(
|
||||
at, agent_id, admin_uid, "新账号待开通权限",
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 姓名:{nickname or '—'}\n\n"
|
||||
f"> 来源:{source}\n\n"
|
||||
"> 备注:请到管理台为该账号开通插件权限",
|
||||
status="warning")
|
||||
else:
|
||||
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉建号通知异常: %s", e)
|
||||
|
||||
|
||||
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||||
unionid: str = "", source: str = "管理台") -> None:
|
||||
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||||
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||||
def _signed_webhook_url() -> str:
|
||||
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||||
if secret:
|
||||
ts = str(int(time.time() * 1000))
|
||||
sign = base64.b64encode(hmac.new(
|
||||
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||||
hashlib.sha256).digest()).decode("utf-8")
|
||||
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||||
return url
|
||||
|
||||
|
||||
def _send_robot(title: str, text: str) -> None:
|
||||
url = _signed_webhook_url()
|
||||
if not url:
|
||||
return
|
||||
try:
|
||||
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉群通知被拒: %s", body)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉群通知异常: %s", e)
|
||||
|
||||
|
||||
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||||
def _admin_names() -> list[str]:
|
||||
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||||
try:
|
||||
from controlplane.core.db import _db
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||||
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||||
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||||
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||||
return []
|
||||
|
||||
|
||||
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||||
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||||
title = "内网文件服务器下线告警"
|
||||
content = (
|
||||
f"> 服务:{hostname or '—'}\n\n"
|
||||
f"> 地址:{host}\n\n"
|
||||
f"> IP:{ip or '—'}\n\n"
|
||||
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||||
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||||
"服务恢复后将自动解除告警")
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
at = _dingtalk_topapi_token() if agent_id else ""
|
||||
sent_any = False
|
||||
if at:
|
||||
for name in _admin_names():
|
||||
if not name:
|
||||
continue
|
||||
uid = _userid_by_name(at, name)
|
||||
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||||
sent_any = True
|
||||
if not sent_any:
|
||||
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||||
if not sent_any:
|
||||
_send_robot(title, content)
|
||||
|
||||
|
||||
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||||
last_seen: str = "") -> None:
|
||||
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||||
threading.Thread(target=_work_fileserver_down,
|
||||
args=(host, hostname, ip, last_seen), daemon=True).start()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
|
||||
|
||||
后台线程发送,失败仅记日志不阻断业务。
|
||||
|
||||
配置项(controlplane/.env):
|
||||
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
|
||||
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
|
||||
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
|
||||
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote_plus
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from controlplane.core import config
|
||||
from controlplane.core.dingtalk import _dingtalk_topapi_token
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
|
||||
_SIGN_NAME = "37du 自动化平台"
|
||||
_STATUS_COLORS = {
|
||||
"info": "#0077ff", # 蓝色
|
||||
"success": "#00b300", # 绿色
|
||||
"warning": "#ff9900", # 橙色
|
||||
"error": "#ff0000", # 红色
|
||||
}
|
||||
|
||||
|
||||
def _footer() -> str:
|
||||
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
|
||||
req.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
with urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
|
||||
def _userid_by_unionid(at: str, unionid: str) -> str:
|
||||
"""unionid → userid(精确,无重名歧义)。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
|
||||
{"unionid": unionid})
|
||||
return ((body.get("result") or {}).get("userid")) or ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _userid_by_name(at: str, name: str) -> str:
|
||||
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://api.dingtalk.com/v1.0/contact/users/search",
|
||||
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
|
||||
headers={"x-acs-dingtalk-access-token": at})
|
||||
lst = body.get("list") or []
|
||||
return str(lst[0]) if lst else ""
|
||||
except Exception as e: # noqa: BLE001 查询失败不阻断业务
|
||||
log.warning("钉钉搜索用户失败(%s):%s", name, e)
|
||||
return ""
|
||||
|
||||
|
||||
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
|
||||
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
|
||||
status: str = "info") -> bool:
|
||||
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
|
||||
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += f"\n\n---\n\n{_footer()}"
|
||||
try:
|
||||
body = _post_json(
|
||||
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
|
||||
{"agent_id": agent_id, "userid_list": userid,
|
||||
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉工作通知被拒: %s", body)
|
||||
return False
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉工作通知异常: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
|
||||
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
if not agent_id:
|
||||
return
|
||||
try:
|
||||
at = _dingtalk_topapi_token()
|
||||
if not at:
|
||||
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
|
||||
return
|
||||
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
|
||||
uid = _userid_by_unionid(at, unionid) if unionid else ""
|
||||
if not uid and nickname:
|
||||
uid = _userid_by_name(at, nickname)
|
||||
if uid:
|
||||
_send_work_to(
|
||||
at, agent_id, uid, "账号开通通知",
|
||||
f"**🔹 {nickname or account}‑账号开通**\n\n"
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 初始密码:{password}\n\n"
|
||||
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
|
||||
status="success")
|
||||
else:
|
||||
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
|
||||
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
|
||||
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
|
||||
admin_uid = _userid_by_name(at, admin_name)
|
||||
if admin_uid:
|
||||
_send_work_to(
|
||||
at, agent_id, admin_uid, "新账号待开通权限",
|
||||
f"> 账号:{account}\n\n"
|
||||
f"> 姓名:{nickname or '—'}\n\n"
|
||||
f"> 来源:{source}\n\n"
|
||||
"> 备注:请到管理台为该账号开通插件权限",
|
||||
status="warning")
|
||||
else:
|
||||
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉建号通知异常: %s", e)
|
||||
|
||||
|
||||
def notify_account_created(account: str, nickname: str = "", password: str = "",
|
||||
unionid: str = "", source: str = "管理台") -> None:
|
||||
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
|
||||
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
|
||||
def _signed_webhook_url() -> str:
|
||||
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
|
||||
if secret:
|
||||
ts = str(int(time.time() * 1000))
|
||||
sign = base64.b64encode(hmac.new(
|
||||
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
|
||||
hashlib.sha256).digest()).decode("utf-8")
|
||||
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
|
||||
return url
|
||||
|
||||
|
||||
def _send_robot(title: str, text: str) -> None:
|
||||
url = _signed_webhook_url()
|
||||
if not url:
|
||||
return
|
||||
try:
|
||||
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
|
||||
if body.get("errcode") != 0:
|
||||
log.warning("钉钉群通知被拒: %s", body)
|
||||
except Exception as e: # noqa: BLE001 通知失败不阻断业务
|
||||
log.warning("钉钉群通知异常: %s", e)
|
||||
|
||||
|
||||
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
|
||||
def _admin_names() -> list[str]:
|
||||
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
|
||||
try:
|
||||
from controlplane.core.db import _db
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
|
||||
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
|
||||
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
|
||||
log.warning("取管理员名单失败,离线告警回退群机器人")
|
||||
return []
|
||||
|
||||
|
||||
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
|
||||
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
|
||||
title = "内网文件服务器下线告警"
|
||||
content = (
|
||||
f"> 服务:{hostname or '—'}\n\n"
|
||||
f"> 地址:{host}\n\n"
|
||||
f"> IP:{ip or '—'}\n\n"
|
||||
f"> 最后心跳:{last_seen or '—'}\n\n"
|
||||
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
|
||||
"服务恢复后将自动解除告警")
|
||||
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
|
||||
at = _dingtalk_topapi_token() if agent_id else ""
|
||||
sent_any = False
|
||||
if at:
|
||||
for name in _admin_names():
|
||||
if not name:
|
||||
continue
|
||||
uid = _userid_by_name(at, name)
|
||||
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
|
||||
sent_any = True
|
||||
if not sent_any:
|
||||
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
|
||||
if not sent_any:
|
||||
_send_robot(title, content)
|
||||
|
||||
|
||||
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
|
||||
last_seen: str = "") -> None:
|
||||
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
|
||||
threading.Thread(target=_work_fileserver_down,
|
||||
args=(host, hostname, ip, last_seen), daemon=True).start()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"filename": "setup-37du-host-1.0.0.exe",
|
||||
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||
"notes": "初始版本"
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"filename": "setup-37du-host-1.0.0.exe",
|
||||
"sha256": "57ee9cb4d10b25914276a277bfe42b0751f4c26c3c408af1293f723c7b4488a0",
|
||||
"notes": "初始版本"
|
||||
}
|
||||
@@ -1,487 +1,487 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||
|
||||
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||
- 按账号授予 / 撤销插件与平台权限
|
||||
- 发布执行机壳子(主程序)新版安装包(shell-release,上传到中心机 shell 源)
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
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
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _mint_admin_token(account: str, secret: str) -> str:
|
||||
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||
_hdrs_json: Optional[bool] = None) -> dict:
|
||||
import requests
|
||||
url = self.base + path # path 已是完整路径(含 query)
|
||||
try:
|
||||
if json_body is not None:
|
||||
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||
else:
|
||||
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||
except requests.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("msg") or detail
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||
return data if isinstance(data, dict) else {"result": data}
|
||||
|
||||
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
print("(暂无插件)")
|
||||
return
|
||||
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||
for p in rows:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_cli",
|
||||
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
p_del.add_argument("plugin_id")
|
||||
|
||||
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||
p_status.add_argument("plugin_id")
|
||||
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||
help="新状态(留空不改变)")
|
||||
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||
|
||||
sub.add_parser("users", help="列出账号清单")
|
||||
|
||||
p_user = sub.add_parser("user-add", help="新建账号")
|
||||
p_user.add_argument("account")
|
||||
p_user.add_argument("--password", required=True)
|
||||
p_user.add_argument("--dept", default="")
|
||||
p_user.add_argument("--nickname", default="")
|
||||
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||
|
||||
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||
p_upd.add_argument("account")
|
||||
p_upd.add_argument("--dept", default=None)
|
||||
p_upd.add_argument("--nickname", default=None)
|
||||
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||
default=None)
|
||||
|
||||
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||
p_rp.add_argument("account")
|
||||
p_rp.add_argument("--password", required=True)
|
||||
|
||||
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||
p_del_u.add_argument("account")
|
||||
|
||||
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||
p_grant.add_argument("account")
|
||||
p_grant.add_argument("plugin_id")
|
||||
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||
|
||||
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||
p_revoke.add_argument("account")
|
||||
p_revoke.add_argument("plugin_id")
|
||||
|
||||
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||
p_gp.add_argument("account")
|
||||
p_gp.add_argument("platform_id")
|
||||
|
||||
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||
p_rp_plt.add_argument("account")
|
||||
p_rp_plt.add_argument("platform_id")
|
||||
|
||||
sub.add_parser("stats", help="运行统计看板")
|
||||
|
||||
sub.add_parser("me", help="校验当前管理身份")
|
||||
|
||||
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||
print(f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}")
|
||||
print(f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}")
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
_plugin_rows(data.get("plugins", {}))
|
||||
|
||||
elif cmd == "plugin-del":
|
||||
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||
print(f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "plugin-status":
|
||||
import urllib.parse as _q
|
||||
body = {}
|
||||
if args.status:
|
||||
body["status"] = args.status
|
||||
if args.force_min_version and args.force_deadline:
|
||||
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||
elif args.clear_force:
|
||||
body["clear_force"] = True
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
print("[ok]", json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
accounts = data.get("accounts", "")
|
||||
if isinstance(accounts, dict):
|
||||
accounts = list(accounts.values())
|
||||
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||
if not accounts:
|
||||
print("(暂无账号)")
|
||||
return 0
|
||||
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||
for a in accounts:
|
||||
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||
|
||||
elif cmd == "user-add":
|
||||
r = c.call("POST", "/api/admin/account", {
|
||||
"account": args.account, "password": args.password,
|
||||
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||
print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||
|
||||
elif cmd == "user-update":
|
||||
body = {"account": args.account}
|
||||
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||
if v is not None:
|
||||
body[k] = v
|
||||
r = c.call("POST", "/api/admin/account/update", body)
|
||||
print(f"[ok] 已更新 {r.get('account')}")
|
||||
|
||||
elif cmd == "user-reset-pwd":
|
||||
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||
print(f"[ok] 已重置 {r.get('account')} 密码")
|
||||
|
||||
elif cmd == "user-del":
|
||||
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||
print(f"[ok] 已删除账号 {r.get('account')}")
|
||||
|
||||
elif cmd == "grant":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||
print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||
f"/run={'y' if not args.no_run else 'n'})")
|
||||
|
||||
elif cmd == "revoke":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "grant-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||
print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "revoke-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "stats":
|
||||
print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2))
|
||||
|
||||
elif cmd == "me":
|
||||
data = c.call("GET", "/api/admin/me")
|
||||
print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||
f"部门:{data.get('dept') or ''}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
try:
|
||||
_run(args)
|
||||
except SystemExit as exc:
|
||||
if exc.code:
|
||||
print(str(exc.code))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# -*- coding: utf-8 -*-
|
||||
"""agent 脚手架 · 中心机插件发布与账号权限管理 CLI(单文件自包含)。
|
||||
|
||||
用途:让 agent / 运维以命令行方式管理中心机,无需打开浏览器即可:
|
||||
- 发布 / 删除插件包(按最近 3 版自动裁剪保留)
|
||||
- 变更插件状态(published / disabled / revoked)与强制更新阈值
|
||||
- 建号 / 重置密码 / 改部门昵称 / 授撤销管理员 / 删除账号
|
||||
- 按账号授予 / 撤销插件与平台权限
|
||||
- 发布执行机壳子(主程序)新版安装包(shell-release,上传到中心机 shell 源)
|
||||
- 查看插件 / 账号 / 运行统计
|
||||
|
||||
鉴权:
|
||||
管理接口同时需要 内部凭证(X-API-Token) + 管理票据(X-Admin-Token)。管理票据两种获取方式:
|
||||
- 密码登录(推荐,任意机器可用):--password 或环境变量 AGENT_ADMIN_PASSWORD,
|
||||
走 /api/admin/auth 用账号+密码换 1 小时票据,管理主密钥不出服务器。
|
||||
- 本机密钥自签(原方式,中心机本机):直接复用 desktop/controlplane/.env 与 .admin_secret,
|
||||
X-API-Token 取自 CONTROLPLANE_TOKEN(.env);为空则该接口不强制,无需携带。
|
||||
X-Admin-Token 用 CONTROLPLANE_ADMIN_SECRET > .admin_secret 本地自签(不再回退 CONTROLPLANE_TOKEN)。
|
||||
中心机地址默认本机 8800;远程发版用 --base 或环境变量 CONTROLPLANE_AGENT_BASE 指向中心机公网地址。
|
||||
|
||||
管理员账号:需用 --admin 显式指定(或设环境变量 AGENT_ADMIN_ACCOUNT),该账号须 is_admin=1。
|
||||
|
||||
运行(项目 .venv,需在 desktop/ 目录下执行,模块搜索根 = desktop/):
|
||||
python -m controlplane.tools.agent_cli publish plugin.zip --id report --version 1.2.0
|
||||
python -m controlplane.tools.agent_cli plugins
|
||||
python -m controlplane.tools.agent_cli grant alice report # 默认授予 download+run
|
||||
python -m controlplane.tools.agent_cli users
|
||||
需一次性传参的自包含要求:无外部参数依赖,配置固化/读取 .env 即可。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parent.parent # tools/agent_cli.py → controlplane/(.env / .admin_secret)
|
||||
|
||||
|
||||
def _load_dotenv() -> None:
|
||||
"""读取 controlplane/.env(同 app.py 规则:环境变量优先,不覆盖已存在值)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
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
|
||||
|
||||
|
||||
_load_dotenv()
|
||||
|
||||
BASE_URL = os.getenv("CONTROLPLANE_AGENT_BASE", "").rstrip("/") or \
|
||||
f"http://127.0.0.1:{os.getenv('CONTROLPLANE_PORT', '8800')}"
|
||||
API_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 内网文件服务器:上传直链来源(复用 controlplane/.env 新增键)
|
||||
FILESERVER_BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/")
|
||||
FILESERVER_TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
|
||||
|
||||
def _admin_secret() -> str:
|
||||
"""与 app.py 完全一致:CONTROLPLANE_ADMIN_SECRET > .admin_secret(不再回退 CONTROLPLANE_TOKEN,
|
||||
传输凭证与管理密钥分离,避免持 X-API-Token 者自签管理员票据)。"""
|
||||
cand = os.getenv("CONTROLPLANE_ADMIN_SECRET") or ""
|
||||
if cand:
|
||||
return cand
|
||||
_f = APP_DIR / ".admin_secret"
|
||||
if _f.is_file():
|
||||
return _f.read_text(encoding="utf-8").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _mint_admin_token(account: str, secret: str) -> str:
|
||||
"""临时签发 1 小时管理票据(算法必须与 app._sign_admin_token 一致)。"""
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps({"a": account, "e": int(time.time()) + 3600}, separators=(",", ":")).encode()
|
||||
).decode().rstrip("=")
|
||||
sig = hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return f"{payload}.{sig}"
|
||||
|
||||
|
||||
class Client:
|
||||
"""携带 X-API-Token + X-Admin-Token 的中心机 API 客户端。"""
|
||||
|
||||
def __init__(self, base: str, api_token: str, admin: str, secret: str, token: str = ""):
|
||||
self.base = base
|
||||
self.api_token = api_token
|
||||
self.admin = admin
|
||||
self.secret = secret
|
||||
self.token = token # 密码登录换取的票据;非空时直接使用,不再本地自签
|
||||
|
||||
def _headers(self, json_body: bool = True) -> dict:
|
||||
h = {}
|
||||
if self.api_token:
|
||||
h["X-API-Token"] = self.api_token
|
||||
if self.admin and self.token:
|
||||
h["X-Admin-Token"] = self.token
|
||||
elif self.admin and self.secret:
|
||||
h["X-Admin-Token"] = _mint_admin_token(self.admin, self.secret)
|
||||
if json_body:
|
||||
h["Content-Type"] = "application/json"
|
||||
return h
|
||||
|
||||
def call(self, method: str, path: str, json_body: Optional[dict] = None,
|
||||
_hdrs_json: Optional[bool] = None) -> dict:
|
||||
import requests
|
||||
url = self.base + path # path 已是完整路径(含 query)
|
||||
try:
|
||||
if json_body is not None:
|
||||
r = requests.request(method, url, headers=self._headers(True), json=json_body, timeout=30)
|
||||
else:
|
||||
r = requests.request(method, url, headers=self._headers(False), timeout=30)
|
||||
except requests.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接中心机 {self.base}({exc})。请确认服务已启动。")
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("msg") or detail
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail or r.text[:200]}")
|
||||
return data if isinstance(data, dict) else {"result": data}
|
||||
|
||||
def upload_pkg(self, path: str, plugin_id: str, name: str, version: str) -> dict:
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"plugin_id": plugin_id, "name": name, "version": version})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/pkg?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/zip")},
|
||||
timeout=60)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
def shell_release(self, path: str, version: str, notes: str, sha256: str = "") -> dict:
|
||||
"""上传壳子新版安装包到中心机(管理接口,缺省 sha256 由服务端计算并写 version.json)。"""
|
||||
import requests
|
||||
import urllib.parse
|
||||
qs = urllib.parse.urlencode({"version": version, "notes": notes, "sha256": sha256})
|
||||
with open(path, "rb") as fp:
|
||||
r = requests.post(f"{self.base}/api/admin/shell-release?{qs}",
|
||||
headers=self._headers(False),
|
||||
files={"upload": (Path(path).name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
try:
|
||||
data = r.json()
|
||||
except ValueError:
|
||||
data = {"raw": r.text[:300]}
|
||||
if r.status_code >= 400:
|
||||
detail = data.get("detail") if isinstance(data, dict) else data
|
||||
raise SystemExit(f"[x] HTTP {r.status_code}:{detail}")
|
||||
return data
|
||||
|
||||
|
||||
# ------------------------------ 输出辅助 ------------------------------
|
||||
def _plugin_rows(plugins) -> None:
|
||||
"""overview 的 plugins 为列表(含版本/授权明细),此处只打印核心字段。"""
|
||||
rows = plugins if isinstance(plugins, list) else \
|
||||
(list(plugins.values()) if isinstance(plugins, dict) else [])
|
||||
if not rows:
|
||||
print("(暂无插件)")
|
||||
return
|
||||
print(f"{'ID':<28}{'名称':<16}{'最新版':<10}{'状态':<12}账号数")
|
||||
for p in rows:
|
||||
if not isinstance(p, dict):
|
||||
continue
|
||||
print(f"{str(p.get('id', '')):<28}{str(p.get('name') or ''):<16}"
|
||||
f"{str(p.get('latest_version') or ''):<10}{str(p.get('status') or ''):<12}{len(p.get('accounts') or [])}")
|
||||
|
||||
|
||||
def _run_file(args: argparse.Namespace, c: Client) -> int:
|
||||
"""file push / list / rm:内网大文件源管理。"""
|
||||
try:
|
||||
import requests as _rq
|
||||
except ModuleNotFoundError:
|
||||
raise SystemExit("[x] 缺少 requests,请用项目 .venv 运行。")
|
||||
fcmd = args.file_cmd
|
||||
|
||||
if fcmd == "push":
|
||||
path = Path(args.path)
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"[x] 文件不存在:{path}")
|
||||
if not FILESERVER_BASE_URL or not FILESERVER_TOKEN:
|
||||
raise SystemExit("[x] 未配置内网文件服务器:请设 controlplane/.env 的 "
|
||||
"FILESERVER_BASE_URL 与 FILESERVER_TOKEN")
|
||||
# 第一步:传到文件服务器
|
||||
try:
|
||||
with open(path, "rb") as fp:
|
||||
r = _rq.post(f"{FILESERVER_BASE_URL}/api/upload",
|
||||
headers={"X-API-Token": FILESERVER_TOKEN},
|
||||
files={"upload": (path.name, fp, "application/octet-stream")},
|
||||
timeout=600)
|
||||
except _rq.ConnectionError as exc:
|
||||
raise SystemExit(f"[x] 无法连接内网文件服务器 {FILESERVER_BASE_URL}({exc})")
|
||||
if r.status_code >= 400:
|
||||
raise SystemExit(f"[x] 上传到文件服务器失败 HTTP {r.status_code}:{r.text[:200]}")
|
||||
up = r.json()
|
||||
url = up.get("url", "")
|
||||
if not url:
|
||||
raise SystemExit("[x] 文件服务器未返回 url")
|
||||
sha256 = args.sha256 or up.get("sha256", "")
|
||||
# 第二步:登记到中心机 file_sources
|
||||
body = {"category": args.category, "version": args.version,
|
||||
"filename": up.get("filename", path.name), "url": url,
|
||||
"sha256": sha256, "notes": args.notes, "enabled": True}
|
||||
rec = c.call("POST", "/api/admin/file-sources", body)
|
||||
print(f"[ok] 已登记 {args.category} v{args.version or '?'} → {url}")
|
||||
print(f" id={rec.get('id')} filename={path.name} sha256={str(sha256)[:16]}…")
|
||||
return 0
|
||||
|
||||
if fcmd == "list":
|
||||
data = c.call("GET", f"/api/admin/file-sources?category={args.category}", None, False)
|
||||
files = data.get("files", [])
|
||||
if not files:
|
||||
print("(暂无大文件源)")
|
||||
return 0
|
||||
print(f"{'ID':<4}{'分类':<10}{'版本':<12}{'启用':<6}文件名 / 链接")
|
||||
for f in files:
|
||||
print(f"{str(f.get('id')):<4}{str(f.get('category') or ''):<10}"
|
||||
f"{str(f.get('version') or ''):<12}{'是' if f.get('enabled') else '否':<6}"
|
||||
f"{f.get('filename') or ''}")
|
||||
print(f" {f.get('url') or ''}")
|
||||
return 0
|
||||
|
||||
if fcmd == "rm":
|
||||
r = c.call("DELETE", f"/api/admin/file-sources/{args.id}", None, False)
|
||||
print(f"[ok] 已删除登记 id={args.id}")
|
||||
return 0
|
||||
|
||||
raise SystemExit(f"[x] 未知 file 子命令:{fcmd}")
|
||||
|
||||
|
||||
# ================================ main ================================
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="agent_cli",
|
||||
description="37du 中心机 · agent 插件发布与管理 CLI",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--admin", default=os.getenv("AGENT_ADMIN_ACCOUNT", ""),
|
||||
help="用于签发管理票据的管理员账号(须 is_admin=1)")
|
||||
parser.add_argument("--password", default=os.getenv("AGENT_ADMIN_PASSWORD", ""),
|
||||
dest="admin_password",
|
||||
help="管理员密码(密码登录模式,任意机器可用;须放在子命令之前。留空则回退本机密钥自签票据)")
|
||||
parser.add_argument("--base", default=BASE_URL, help="中心机服务地址")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p_pub = sub.add_parser("publish", help="发布插件包 zip(自动裁剪保留最近 3 版)")
|
||||
p_pub.add_argument("pkg", help="插件 zip 路径")
|
||||
p_pub.add_argument("--id", dest="plugin_id", required=True, help="插件 ID(须与 plugin.json 内 id 一致)")
|
||||
p_pub.add_argument("--name", default="", help="插件名称(缺省取 plugin.json 内 name 或 ID)")
|
||||
p_pub.add_argument("--version", required=True, help="版本号,如 1.2.0")
|
||||
|
||||
sub.add_parser("plugins", help="列出插件清单")
|
||||
|
||||
p_del = sub.add_parser("plugin-del", help="删除插件(连带全部版本、授权、磁盘包)")
|
||||
p_del.add_argument("plugin_id")
|
||||
|
||||
p_status = sub.add_parser("plugin-status", help="变更插件状态/强制更新阈值")
|
||||
p_status.add_argument("plugin_id")
|
||||
p_status.add_argument("--status", choices=["published", "disabled", "revoked"], default="",
|
||||
help="新状态(留空不改变)")
|
||||
p_status.add_argument("--force-min-version", default="", help="强制最低版本(与 --force-deadline 成对)")
|
||||
p_status.add_argument("--force-deadline", default="", help="强制更新截止时间(ISO 字符串)")
|
||||
p_status.add_argument("--clear-force", action="store_true", help="清除强制更新配置")
|
||||
|
||||
sub.add_parser("users", help="列出账号清单")
|
||||
|
||||
p_user = sub.add_parser("user-add", help="新建账号")
|
||||
p_user.add_argument("account")
|
||||
p_user.add_argument("--password", required=True)
|
||||
p_user.add_argument("--dept", default="")
|
||||
p_user.add_argument("--nickname", default="")
|
||||
p_user.add_argument("--admin", dest="is_admin_flag", action="store_true", help="设为管理员")
|
||||
|
||||
p_upd = sub.add_parser("user-update", help="更新账号(部门/昵称/管理员)")
|
||||
p_upd.add_argument("account")
|
||||
p_upd.add_argument("--dept", default=None)
|
||||
p_upd.add_argument("--nickname", default=None)
|
||||
p_upd.add_argument("--is-admin", dest="is_admin_opt", type=lambda s: s in ("1", "true", "yes", "是"),
|
||||
default=None)
|
||||
|
||||
p_rp = sub.add_parser("user-reset-pwd", help="管理员重置账号密码")
|
||||
p_rp.add_argument("account")
|
||||
p_rp.add_argument("--password", required=True)
|
||||
|
||||
p_del_u = sub.add_parser("user-del", help="删除账号")
|
||||
p_del_u.add_argument("account")
|
||||
|
||||
p_grant = sub.add_parser("grant", help="授予账号某插件权限(默认 download+run)")
|
||||
p_grant.add_argument("account")
|
||||
p_grant.add_argument("plugin_id")
|
||||
p_grant.add_argument("--no-download", action="store_true", help="不授予下载权限")
|
||||
p_grant.add_argument("--no-run", action="store_true", help="不授予运行权限")
|
||||
|
||||
p_revoke = sub.add_parser("revoke", help="撤销账号某插件权限")
|
||||
p_revoke.add_argument("account")
|
||||
p_revoke.add_argument("plugin_id")
|
||||
|
||||
p_gp = sub.add_parser("grant-platform", help="授予账号某平台登录权限")
|
||||
p_gp.add_argument("account")
|
||||
p_gp.add_argument("platform_id")
|
||||
|
||||
p_rp_plt = sub.add_parser("revoke-platform", help="撤销账号某平台登录权限")
|
||||
p_rp_plt.add_argument("account")
|
||||
p_rp_plt.add_argument("platform_id")
|
||||
|
||||
sub.add_parser("stats", help="运行统计看板")
|
||||
|
||||
sub.add_parser("me", help="校验当前管理身份")
|
||||
|
||||
p_shell = sub.add_parser("shell-release", help="发布执行机壳子新版安装包(更新 shell 源 + version.json)")
|
||||
p_shell.add_argument("pkg", help="新安装包路径(setup-37du-host-<v>.exe)")
|
||||
p_shell.add_argument("--version", required=True, help="壳子版本号(须高于执行机本地 shell.version)")
|
||||
p_shell.add_argument("--notes", default="", help="更新说明(可选,执行机前端提示展示)")
|
||||
p_shell.add_argument("--sha256", default="", help="安装包 sha256(可选,缺省自动计算)")
|
||||
|
||||
p_file = sub.add_parser("file", help="内网大文件源管理:push/list/rm")
|
||||
file_sub = p_file.add_subparsers(dest="file_cmd", required=True)
|
||||
p_fpush = file_sub.add_parser("push", help="上传到内网文件服务器并登记到中心机")
|
||||
p_fpush.add_argument("path", help="本地文件路径")
|
||||
p_fpush.add_argument("--category", required=True, help="分类:shell/chrome/browser 等")
|
||||
p_fpush.add_argument("--version", default="", help="版本号(可选)")
|
||||
p_fpush.add_argument("--notes", default="", help="说明(可选)")
|
||||
p_fpush.add_argument("--sha256", default="", help="sha256(可选,缺省自动计算)")
|
||||
p_flist = file_sub.add_parser("list", help="列出大文件源")
|
||||
p_flist.add_argument("--category", default="", help="按分类过滤")
|
||||
p_frm = file_sub.add_parser("rm", help="删除中心机登记(不动内网服务器文件)")
|
||||
p_frm.add_argument("id", type=int, help="file_sources.id")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run(args: argparse.Namespace) -> int:
|
||||
if not args.admin:
|
||||
raise SystemExit("[x] 未指定管理员账号:请用 --admin <账号> 或设置环境变量 AGENT_ADMIN_ACCOUNT。")
|
||||
if args.admin_password.strip():
|
||||
# 密码登录模式(推荐,任意机器可用):账号+密码换 1 小时票据,主密钥不出服务器
|
||||
c = Client(args.base, API_TOKEN, args.admin, "")
|
||||
r = c.call("POST", "/api/admin/auth",
|
||||
{"account": args.admin, "password": args.admin_password})
|
||||
if not r.get("token"):
|
||||
raise SystemExit("[x] 登录成功但未返回票据,请检查中心机版本。")
|
||||
if not r.get("is_admin"):
|
||||
raise SystemExit(f"[x] 账号 {args.admin} 不是管理员(is_admin=0),无法执行管理操作。")
|
||||
c.token = str(r["token"])
|
||||
print(f"[ok] 已以 {args.admin} 登录 {args.base}(密码模式,票据 1 小时有效)")
|
||||
else:
|
||||
# 本机密钥自签模式(中心机本机):复用 .env/.admin_secret 本地签发票据
|
||||
secret = _admin_secret()
|
||||
if not secret:
|
||||
raise SystemExit("[x] 未找到管理密钥(CONTROLPLANE_ADMIN_SECRET / CONTROLPLANE_TOKEN / .admin_secret 均为空),"
|
||||
"无法签发管理票据;远程机器请改用密码登录:--password 或环境变量 AGENT_ADMIN_PASSWORD。")
|
||||
c = Client(args.base, API_TOKEN, args.admin, secret)
|
||||
cmd = args.command
|
||||
|
||||
if cmd == "shell-release":
|
||||
r = c.shell_release(args.pkg, args.version, args.notes, args.sha256)
|
||||
print(f"[ok] 已发布壳子 v{r.get('version')} → {r.get('filename')}")
|
||||
print(f" sha256={str(r.get('sha256') or '')[:16]}… notes={args.notes or '(无)'}")
|
||||
print(f" 各执行机下次启动自动检测下载,前端提示后点击「重启更新」即静默升级。")
|
||||
return 0
|
||||
|
||||
if cmd == "file":
|
||||
return _run_file(args, c)
|
||||
|
||||
if cmd == "publish":
|
||||
r = c.upload_pkg(args.pkg, args.plugin_id, args.name, args.version)
|
||||
print(f"[ok] 已发布 {r.get('plugin_id')} v{r.get('version')} → {r.get('filename')}")
|
||||
|
||||
elif cmd == "plugins":
|
||||
data = c.call("GET", "/api/admin/overview")
|
||||
_plugin_rows(data.get("plugins", {}))
|
||||
|
||||
elif cmd == "plugin-del":
|
||||
r = c.call("POST", "/api/admin/plugin/delete", {"plugin_id": args.plugin_id})
|
||||
print(f"[ok] 已删除插件 {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "plugin-status":
|
||||
import urllib.parse as _q
|
||||
body = {}
|
||||
if args.status:
|
||||
body["status"] = args.status
|
||||
if args.force_min_version and args.force_deadline:
|
||||
body.update({"force_min_version": args.force_min_version, "force_deadline": args.force_deadline})
|
||||
elif args.clear_force:
|
||||
body["clear_force"] = True
|
||||
r = c.call("POST", f"/api/admin/plugin/patch?{_q.urlencode({'plugin_id': args.plugin_id})}", body)
|
||||
print("[ok]", json.dumps(r, ensure_ascii=False))
|
||||
|
||||
elif cmd == "users":
|
||||
data = c.call("GET", "/api/admin/accounts")
|
||||
accounts = data.get("accounts", "")
|
||||
if isinstance(accounts, dict):
|
||||
accounts = list(accounts.values())
|
||||
accounts = [a for a in (accounts or []) if isinstance(a, dict)]
|
||||
if not accounts:
|
||||
print("(暂无账号)")
|
||||
return 0
|
||||
print(f"{'账号':<16}{'昵称':<14}{'部门':<12}{'管理员'}")
|
||||
for a in accounts:
|
||||
print(f"{str(a.get('account', '')):<16}{str(a.get('nickname') or ''):<14}"
|
||||
f"{str(a.get('dept') or ''):<12}{'是' if a.get('is_admin') else '否'}")
|
||||
|
||||
elif cmd == "user-add":
|
||||
r = c.call("POST", "/api/admin/account", {
|
||||
"account": args.account, "password": args.password,
|
||||
"dept": args.dept, "nickname": args.nickname, "is_admin": args.is_admin_flag})
|
||||
print(f"[ok] 已建号 {r.get('account')}" + ("(管理员)" if r.get("is_admin") else ""))
|
||||
|
||||
elif cmd == "user-update":
|
||||
body = {"account": args.account}
|
||||
for k, v in (("dept", args.dept), ("nickname", args.nickname), ("is_admin", args.is_admin_opt)):
|
||||
if v is not None:
|
||||
body[k] = v
|
||||
r = c.call("POST", "/api/admin/account/update", body)
|
||||
print(f"[ok] 已更新 {r.get('account')}")
|
||||
|
||||
elif cmd == "user-reset-pwd":
|
||||
r = c.call("POST", "/api/admin/account/reset_pwd", {"account": args.account, "new_password": args.password})
|
||||
print(f"[ok] 已重置 {r.get('account')} 密码")
|
||||
|
||||
elif cmd == "user-del":
|
||||
r = c.call("POST", "/api/admin/account/delete", {"account": args.account})
|
||||
print(f"[ok] 已删除账号 {r.get('account')}")
|
||||
|
||||
elif cmd == "grant":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": True,
|
||||
"can_download": not args.no_download, "can_run": not args.no_run})
|
||||
print(f"[ok] 已授予 {r.get('account')} → {r.get('plugin_id')}(download={'y' if not args.no_download else 'n'}"
|
||||
f"/run={'y' if not args.no_run else 'n'})")
|
||||
|
||||
elif cmd == "revoke":
|
||||
r = c.call("POST", "/api/admin/account_plugins", {
|
||||
"account": args.account, "plugin_id": args.plugin_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → {r.get('plugin_id')}")
|
||||
|
||||
elif cmd == "grant-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": True})
|
||||
print(f"[ok] 已授予 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "revoke-platform":
|
||||
r = c.call("POST", "/api/admin/account_platforms", {
|
||||
"account": args.account, "platform_id": args.platform_id, "granted": False})
|
||||
print(f"[ok] 已撤销 {r.get('account')} → 平台 {r.get('platform_id')}")
|
||||
|
||||
elif cmd == "stats":
|
||||
print(json.dumps(c.call("GET", "/api/admin/stats"), ensure_ascii=False, indent=2))
|
||||
|
||||
elif cmd == "me":
|
||||
data = c.call("GET", "/api/admin/me")
|
||||
print(f"登录账号:{data.get('account')} 管理员:{'是' if data.get('is_admin') else '否'} "
|
||||
f"部门:{data.get('dept') or ''}")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
try:
|
||||
_run(args)
|
||||
except SystemExit as exc:
|
||||
if exc.code:
|
||||
print(str(exc.code))
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,279 +1,279 @@
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_host (host),
|
||||
KEY idx_status (status),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
|
||||
-- ============================================================
|
||||
-- 37du 自动化平台 · 中心机控制面 表结构(MySQL 5.7+)
|
||||
-- 引擎:InnoDB / 字符集:utf8mb4 / 排序:utf8mb4_unicode_ci
|
||||
-- 执行:mysql -h<host> -u<user> -p < schema_mysql.sql
|
||||
-- 幂等:全部 CREATE TABLE IF NOT EXISTS,可重复执行
|
||||
-- ============================================================
|
||||
|
||||
CREATE DATABASE IF NOT EXISTS 37du_center
|
||||
DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
USE 37du_center;
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 迁移版本记录:db.py 启动幂等建表时登记,替代旧 _ensure_col 渐进补列
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version VARCHAR(64) NOT NULL COMMENT '迁移版本标识(如 20260916_001)',
|
||||
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '迁移执行时间',
|
||||
PRIMARY KEY (version)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='数据库迁移版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 统一账号
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '账号自增ID',
|
||||
account VARCHAR(64) NOT NULL COMMENT '登录账号(工号,唯一)',
|
||||
password_hash VARCHAR(128) NOT NULL COMMENT '密码哈希(加盐)',
|
||||
salt VARCHAR(64) NOT NULL COMMENT '密码盐值',
|
||||
is_admin TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否管理员:1=是 0=否',
|
||||
dept VARCHAR(64) NOT NULL DEFAULT '' COMMENT '所属部门',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称/姓名',
|
||||
dingtalk_uid VARCHAR(64) NOT NULL DEFAULT '' COMMENT '钉钉用户ID(扫码登录绑定)',
|
||||
must_change_pwd TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否必须改密:1=是 0=否',
|
||||
avatar VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像文件名(avatars/ 下)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '账号状态:1=启用 0=停用',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_account (account),
|
||||
KEY idx_dept (dept)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统一账号';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件元数据
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id VARCHAR(64) NOT NULL COMMENT '插件ID(唯一,如 seal_check)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '插件名称',
|
||||
latest_version VARCHAR(32) NOT NULL COMMENT '最新版本号',
|
||||
description VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件描述',
|
||||
category VARCHAR(64) NOT NULL DEFAULT '' COMMENT '分类',
|
||||
icon VARCHAR(255) NOT NULL DEFAULT '' COMMENT '图标标识',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'published' COMMENT '状态:published=正常 disabled=禁用 revoked=下架(白名单由代码层校验)',
|
||||
force_min_version VARCHAR(32) NULL COMMENT '强制更新最低版本(NULL=未开启;空串等价未开启)',
|
||||
force_deadline VARCHAR(32) NULL COMMENT '强制更新截止时间(ISO串,NULL=未开启;兼容 fromisoformat 解析)',
|
||||
manifest TEXT NULL COMMENT 'plugin.json 原文(JSON 串,可空;种子插件无 manifest)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件元数据';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 插件版本:每插件仅保留最近 N 版,旧版由应用层裁剪
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS plugin_versions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '版本记录自增ID',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '所属插件ID',
|
||||
version VARCHAR(32) NOT NULL COMMENT '版本号',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
size_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '包体积(字节)',
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_plugin_version (plugin_id, version),
|
||||
CONSTRAINT fk_pv_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-插件授权:含下载/运行权限位(合并原 plugin_grants)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_plugins (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
plugin_id VARCHAR(64) NOT NULL COMMENT '插件ID',
|
||||
can_download TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许下载:1=是 0=否',
|
||||
can_run TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否允许运行:1=是 0=否',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account, plugin_id),
|
||||
KEY idx_plugin (plugin_id),
|
||||
CONSTRAINT fk_ap_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ap_plugin FOREIGN KEY (plugin_id)
|
||||
REFERENCES plugins (id) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-插件授权(含下载/运行权限位)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 账号-平台白名单:账号可登录的平台
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS account_platforms (
|
||||
account VARCHAR(64) NOT NULL COMMENT '账号(工号)',
|
||||
platform_id VARCHAR(64) NOT NULL COMMENT '平台ID(hr/oa 等)',
|
||||
granted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '授权时间',
|
||||
PRIMARY KEY (account, platform_id),
|
||||
CONSTRAINT fk_pl_account FOREIGN KEY (account)
|
||||
REFERENCES accounts (account) ON DELETE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号-平台白名单';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 审计日志:下载/授权/管控/发布等关键操作留痕
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作账号(空=系统/客户端)',
|
||||
action VARCHAR(64) NOT NULL COMMENT '动作:download/grant/revoke-grant/plugin-patch/shell-release/chrome-config...',
|
||||
target VARCHAR(128) NOT NULL DEFAULT '' COMMENT '操作对象(插件ID/文件名等)',
|
||||
detail TEXT NOT NULL COMMENT '操作详情(JSON 串)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_action (action),
|
||||
KEY idx_account (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审计日志';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 运行上报:执行机运行记录(启动/完成/失败/离线补报)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS runtime_reports (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '记录自增ID',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '运行账号(工号)',
|
||||
device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '执行机设备ID',
|
||||
plugin_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT '插件ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '插件版本号',
|
||||
status VARCHAR(32) NOT NULL DEFAULT '' COMMENT '状态:start/done/success/error/failed',
|
||||
msg TEXT NOT NULL COMMENT '结果/错误信息',
|
||||
duration_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '运行时长(秒)',
|
||||
at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上报时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_at (at),
|
||||
KEY idx_account_at (account, at),
|
||||
KEY idx_plugin_at (plugin_id, at),
|
||||
KEY idx_status_at (status, at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运行上报';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机设备:环境/心跳上报(配合执行机 Chrome 检测)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
device_id VARCHAR(64) NOT NULL COMMENT '执行机设备ID(唯一,本机生成)',
|
||||
account VARCHAR(64) NOT NULL DEFAULT '' COMMENT '当前登录账号(工号,仅归属标识,不建外键以免误删设备记录)',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
os VARCHAR(64) NOT NULL DEFAULT '' COMMENT '操作系统(如 Windows 10 企业版)',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
chrome_installed TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已安装 Chrome:1=是 0=否',
|
||||
chrome_version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号',
|
||||
chrome_ok TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Chrome 是否就绪(已安装且版本可用):1=是 0=否',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后在线时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '设备状态:1=在线 0=离线',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (device_id),
|
||||
KEY idx_account (account),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机设备(环境/心跳上报)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- Chrome 安装包下载源配置:外链 URL,中心机不存包
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS chrome_releases (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '配置自增ID',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Chrome 版本号(展示/比对用)',
|
||||
url TEXT NOT NULL COMMENT '安装包外链下载地址',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '落盘文件名(可选)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用该下载源:1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Chrome 安装包下载源';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 系统级键值配置:全局配置沉淀(如环境依赖项)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS system_settings (
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '配置键',
|
||||
`value` TEXT NOT NULL COMMENT '配置值(JSON 文本)',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统级键值配置';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 执行机敏感凭证:中心机统一存明文源,下发时用执行机 RSA 公钥加密为密文
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS client_creds (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号)',
|
||||
pubkey_pem TEXT NOT NULL COMMENT '该账号上报的 RSA 公钥(PEM)',
|
||||
creds MEDIUMTEXT NOT NULL COMMENT '敏感凭证密文 JSON:{key: base64(RSA 密文)},各值用 pubkey_pem 加密',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='执行机敏感凭证(中心机下发,RSA 加密)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 大文件源:内网直链,走内网文件服务器(中心机不存大包)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS file_sources (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
category VARCHAR(32) NOT NULL DEFAULT '' COMMENT '分类:shell/chrome/browser 等',
|
||||
version VARCHAR(32) NOT NULL DEFAULT '' COMMENT '版本号(对比/展示用,可选)',
|
||||
filename VARCHAR(255) NOT NULL DEFAULT '' COMMENT '原文件名',
|
||||
url TEXT NOT NULL COMMENT '内网文件服务器直链',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT 'sha256 校验值(可选,有则校验)',
|
||||
notes VARCHAR(512) NOT NULL DEFAULT '' COMMENT '说明',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 壳子定时任务配置备份:执行机变更后全量推送,仅存数据防丢失(不做管理界面)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS schedule_backups (
|
||||
account VARCHAR(64) NOT NULL COMMENT '执行机账号(工号,任务归属创建者账号)',
|
||||
data MEDIUMTEXT NOT NULL COMMENT '定时任务全量配置 JSON({"schedules": [...]})',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (account)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS fileserver_status (
|
||||
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
|
||||
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
|
||||
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
|
||||
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
|
||||
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
|
||||
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
|
||||
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
|
||||
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
|
||||
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
|
||||
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
|
||||
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
|
||||
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
|
||||
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
|
||||
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_host (host),
|
||||
KEY idx_status (status),
|
||||
KEY idx_last_seen (last_seen)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -1,128 +1,128 @@
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
|
||||
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
|
||||
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
|
||||
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
|
||||
missing module named 'rich.table' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.syntax' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.progress' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.markup' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.console' - imported by httpx._main (top-level)
|
||||
missing module named 'pygments.util' - imported by httpx._main (top-level)
|
||||
missing module named pygments - imported by httpx._main (top-level)
|
||||
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named zstandard - imported by httpx._decoders (optional)
|
||||
missing module named brotlicffi - imported by httpx._decoders (optional)
|
||||
missing module named brotli - imported by httpx._decoders (optional)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
excluded module named win32con - imported by win32evtlogutil (top-level)
|
||||
excluded module named win32api - imported by win32evtlogutil (top-level)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
|
||||
This file lists modules PyInstaller was not able to find. This does not
|
||||
necessarily mean these modules are required for running your program. Both
|
||||
Python's standard library and 3rd-party Python packages often conditionally
|
||||
import optional modules, some of which may be available only on certain
|
||||
platforms.
|
||||
|
||||
Types of import:
|
||||
* top-level: imported at the top-level - look at these first
|
||||
* conditional: imported within an if-statement
|
||||
* delayed: imported within a function
|
||||
* optional: imported within a try-except-statement
|
||||
|
||||
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
|
||||
tracking down the missing module yourself. Thanks!
|
||||
|
||||
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
|
||||
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
|
||||
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
|
||||
missing module named resource - imported by posix (top-level)
|
||||
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
|
||||
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
|
||||
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
|
||||
missing module named fcntl - imported by subprocess (optional)
|
||||
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
|
||||
missing module named _scproxy - imported by urllib.request (conditional)
|
||||
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
|
||||
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
|
||||
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
|
||||
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
|
||||
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
|
||||
missing module named org - imported by pickle (optional)
|
||||
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
|
||||
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
|
||||
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
|
||||
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
|
||||
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
|
||||
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
|
||||
missing module named vms_lib - imported by platform (delayed, optional)
|
||||
missing module named java - imported by platform (delayed)
|
||||
missing module named _winreg - imported by platform (delayed, optional)
|
||||
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
|
||||
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
|
||||
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
|
||||
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
|
||||
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
|
||||
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
|
||||
missing module named 'rich.table' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.syntax' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.progress' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.markup' - imported by httpx._main (top-level)
|
||||
missing module named 'rich.console' - imported by httpx._main (top-level)
|
||||
missing module named 'pygments.util' - imported by httpx._main (top-level)
|
||||
missing module named pygments - imported by httpx._main (top-level)
|
||||
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
|
||||
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
|
||||
missing module named zstandard - imported by httpx._decoders (optional)
|
||||
missing module named brotlicffi - imported by httpx._decoders (optional)
|
||||
missing module named brotli - imported by httpx._decoders (optional)
|
||||
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
|
||||
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
|
||||
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
|
||||
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
|
||||
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
|
||||
missing module named readline - imported by websockets.cli (delayed, optional)
|
||||
missing module named werkzeug - imported by websockets.asyncio.router (optional)
|
||||
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
|
||||
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
|
||||
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
|
||||
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
|
||||
missing module named IPython - imported by dotenv.ipython (top-level)
|
||||
excluded module named win32con - imported by win32evtlogutil (top-level)
|
||||
excluded module named win32api - imported by win32evtlogutil (top-level)
|
||||
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
|
||||
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
|
||||
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
|
||||
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
|
||||
missing module named outcome - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
|
||||
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
|
||||
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
|
||||
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
|
||||
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
|
||||
missing module named cython - imported by pydantic.v1.version (optional)
|
||||
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
|
||||
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
|
||||
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
|
||||
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
|
||||
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
|
||||
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
|
||||
missing module named mypy - imported by pydantic.mypy (top-level)
|
||||
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
|
||||
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
|
||||
missing module named rich - imported by pydantic._internal._core_utils (conditional)
|
||||
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
|
||||
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
|
||||
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
|
||||
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
|
||||
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
|
||||
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
|
||||
missing module named gunicorn - imported by uvicorn.workers (top-level)
|
||||
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,68 +1,68 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
||||
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
||||
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 心跳上报间隔(秒)
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
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 = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
# -*- coding: utf-8 -*-
|
||||
"""内网文件服务器配置:只读加载 fileserver/.env(环境变量优先,不覆盖已存在值)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
"""定位 .env / 数据所在目录。
|
||||
|
||||
- 源码运行:fileserver/core/config.py → fileserver/
|
||||
- PyInstaller 打包(exe):取可执行文件同目录,便于随 exe 摆放 .env 与 data/
|
||||
"""
|
||||
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权 token
|
||||
# 落盘目录:.env 未配时默认 应用目录/data(受 .env 的 FILESERVER_DATA_DIR 覆盖)
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
|
||||
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
|
||||
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
# 心跳上报间隔(秒)
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def load_dotenv() -> None:
|
||||
"""读取本地 .env(同中心机 app.py 规则:环境变量优先)。"""
|
||||
env_path = APP_DIR / ".env"
|
||||
if not env_path.is_file():
|
||||
return
|
||||
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 = _k.strip()
|
||||
if k and k not in os.environ:
|
||||
os.environ[k] = _v.strip()
|
||||
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# load_dotenv 后再取一次,保证 .env 值生效
|
||||
PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
|
||||
TOKEN = os.getenv("FILESERVER_TOKEN", "")
|
||||
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
|
||||
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
|
||||
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
|
||||
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
|
||||
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
|
||||
|
||||
|
||||
def default_token() -> str:
|
||||
"""未配置 token 时一次性生成(仅开发便利,生产应写死到 .env)。"""
|
||||
return TOKEN or secrets.token_urlsafe(24)
|
||||
Binary file not shown.
@@ -1,3 +1,3 @@
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
fastapi>=0.110
|
||||
uvicorn>=0.29
|
||||
python-multipart>=0.0.9
|
||||
@@ -1,128 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
|
||||
|
||||
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
|
||||
任一端登录成功后,webhost 直接复用,无需重复登录
|
||||
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
|
||||
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
|
||||
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
|
||||
|
||||
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import requests
|
||||
|
||||
from webhost.backend.shared import hr_login as _hr
|
||||
from webhost.backend.shared import oa_login as _oa
|
||||
from webhost.backend.shared import seal_data_export as _seal
|
||||
|
||||
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
|
||||
|
||||
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容旧逻辑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
|
||||
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
|
||||
_COOKIE_DEFS = {
|
||||
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
|
||||
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
|
||||
}
|
||||
|
||||
# 登录模块(desktop/shared 真源)
|
||||
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
|
||||
|
||||
|
||||
class PlatformAuthError(Exception):
|
||||
"""平台不存在 / 登录态不可用等宿主层错误。"""
|
||||
|
||||
|
||||
def platforms() -> list:
|
||||
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
|
||||
|
||||
|
||||
def is_online(pid: str) -> bool:
|
||||
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
|
||||
if pid == "hr":
|
||||
return _hr._is_hr_session_valid()
|
||||
if pid == "oa":
|
||||
return _oa._is_oa_session_valid()
|
||||
return False
|
||||
|
||||
|
||||
def login(pid: str) -> dict:
|
||||
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
|
||||
|
||||
返回 {id, label, online, message}
|
||||
"""
|
||||
if pid not in _LOGIN_MODS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
result = _LOGIN_MODS[pid].ensure_login(force=False)
|
||||
ok = bool(result and result.get("success"))
|
||||
return {"id": pid, "label": _LABELS[pid], "online": ok,
|
||||
"message": (result or {}).get("message", "")}
|
||||
|
||||
|
||||
def logout(pid: str) -> dict:
|
||||
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
|
||||
|
||||
返回 {id, label, online}
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if os.path.exists(path):
|
||||
os.remove(path)
|
||||
return {"id": pid, "label": _LABELS[pid], "online": False}
|
||||
|
||||
|
||||
def build_session(pid: str) -> "requests.Session":
|
||||
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
|
||||
|
||||
若登录态缺失则抛 PlatformAuthError,提示先登录。
|
||||
"""
|
||||
if pid not in _COOKIE_DEFS:
|
||||
raise PlatformAuthError(f"未知平台: {pid}")
|
||||
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
|
||||
if not os.path.exists(path):
|
||||
raise PlatformAuthError(
|
||||
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cookies = json.load(f)
|
||||
if not cookies:
|
||||
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
domain = _COOKIE_DEFS[pid]["domain"]
|
||||
injected: set = set()
|
||||
for c in cookies:
|
||||
if c.get("domain") and domain in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"],
|
||||
domain=c["domain"], path=c.get("path", "/"))
|
||||
injected.add(c["name"])
|
||||
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
|
||||
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
|
||||
for c in cookies:
|
||||
name = c.get("name")
|
||||
if name and name not in injected:
|
||||
session.cookies.set(name, c.get("value", ""),
|
||||
domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def get_user_id(pid: str) -> str:
|
||||
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
|
||||
if pid == "hr":
|
||||
session = build_session("hr")
|
||||
info = _seal.fetch_cur_user_info(session)
|
||||
return str(info.get("userId") or "")
|
||||
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
|
||||
|
||||
@@ -1,323 +1,323 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
# -*- coding: utf-8 -*-
|
||||
"""执行机浏览器(Chrome)管理:检测本机是否已装 Chrome → 从中心机拿内网链接下载安装包 → 静默安装。
|
||||
|
||||
流程(对应前端交互):
|
||||
1. 检测:启动时/前端手动"检测",读注册表判断 Chrome 是否已装、装了给出版本号。
|
||||
在此基础上向前端返回"已安装(版本) / 未安装",未安装时展示"下载安装 Chrome"图标按钮。
|
||||
2. 下载:用户点击 → 后台流式下载中心机 file_sources(chrome) 登记的内网直链到
|
||||
%LOCALAPPDATA%\\37duAutomation\\chrome\\(先写 .part,完成校验后改名),
|
||||
进度写入状态供前端轮询展示。
|
||||
3. 安装:下载完成后前端提示"安装 Chrome",用户点击 → ChromeStandaloneSetup64.exe
|
||||
/silent /install 后台静默安装(Chrome 官方安装器参数,不需 Inno)。
|
||||
4. 中心机未登记 chrome / 校验失败 / 不可达:记录错误原因,前端提示,不影响其它功能。
|
||||
|
||||
并发控制:下载持独立锁防重入;检测轻量(读注册表),直接同步返回。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# 下载缓存目录:独立于程序目录(升级/清理不受影响)
|
||||
_CHROME_CACHE = Path(os.getenv("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "chrome"
|
||||
|
||||
# 下载互斥锁:防止并发重复下载
|
||||
_DL_LOCK = threading.Lock()
|
||||
|
||||
# 已下载待安装的安装包路径
|
||||
_PENDING_PKG: Path | None = None
|
||||
|
||||
# 运行态(供前端轮询 chrome status)
|
||||
_STATE: dict = {
|
||||
"installed": True, # 本机是否已装 Chrome
|
||||
"version": "", # 已装版本(未装为空)
|
||||
"checking": False, # 正在重新检测
|
||||
"check_error": "", # 检测/拉取云端信息错误
|
||||
"cloud_available": True, # 中心机是否登记了 chrome 内网链接
|
||||
# 下载
|
||||
"dl_status": "idle", # idle | downloading | downloaded | failed
|
||||
"dl_received": 0,
|
||||
"dl_total": 0,
|
||||
"dl_pct": 0,
|
||||
"dl_error": "",
|
||||
"installing": False, # 正在静默安装
|
||||
}
|
||||
|
||||
|
||||
# ===================== 检测 =====================
|
||||
|
||||
# Chrome 注册表探测点:按优先级尝试,兼容 64/32 位安装
|
||||
_CHROME_REGS = [
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"),
|
||||
]
|
||||
# 64 位 Google Chrome 默认安装目录(版本目录里 max.exe 可读 Product Version)
|
||||
_CHROME_INSTALL_DIRS = [
|
||||
Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Google" / "Chrome" / "Application",
|
||||
Path(os.environ.get("LOCALAPPDATA", Path.home().as_posix())) / "Google" / "Chrome" / "Application",
|
||||
]
|
||||
|
||||
_VERSION_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)$")
|
||||
|
||||
|
||||
def detect_local() -> dict:
|
||||
"""检测本机 Chrome:返回 {"installed": bool, "version": str},读注册表为主。"""
|
||||
exe = _find_chrome_exe()
|
||||
if not exe:
|
||||
return {"installed": False, "version": ""}
|
||||
version = _read_version(exe)
|
||||
return {"installed": True, "version": version}
|
||||
|
||||
|
||||
def _find_chrome_exe() -> Path | None:
|
||||
for hive, key in _CHROME_REGS:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ) as k:
|
||||
value, _ = winreg.QueryValueEx(k, "")
|
||||
if value and Path(value).is_file():
|
||||
return Path(value)
|
||||
except OSError:
|
||||
continue
|
||||
# 注册表探测失败时回退目录扫描(无版本目录成功语义)
|
||||
for d in _CHROME_INSTALL_DIRS:
|
||||
p = d / "chrome.exe"
|
||||
if p.is_file():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def _read_version(exe: Path) -> str:
|
||||
try:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
size, handle = wintypes.DWORD(0), wintypes.HANDLE()
|
||||
r = ctypes.windll.version.GetFileVersionInfoSizeW(str(exe), ctypes.byref(handle))
|
||||
if not r:
|
||||
return ""
|
||||
buf = ctypes.create_string_buffer(r)
|
||||
if not ctypes.windll.version.GetFileVersionInfoW(str(exe), wintypes.DWORD(0), r, buf):
|
||||
return ""
|
||||
# 用 subprocess wmic/powershell 更稳,但这里走纯方案:解析 VS_FIXEDFILEINFO 偏移
|
||||
fixed = ctypes.c_ubyte * r
|
||||
out = fixed.from_buffer(buf)
|
||||
# 简单方案:调用 wmic(存在但慢),改用 powershell 取 ProductVersion
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _cloud_info() -> dict | None:
|
||||
"""从中心机取 file_sources(chrome) 登记信息:{url, sha256, version, filename}。"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
try:
|
||||
headers = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/file-sources/chrome",
|
||||
headers=headers, timeout=5)
|
||||
if r.status_code != 200:
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
data = r.json()
|
||||
if not data.get("available"):
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
_STATE["cloud_available"] = True
|
||||
return data
|
||||
except Exception as _exc: # noqa: BLE001 离线/中心机不可达
|
||||
_LOGGER.info("获取浏览器云端信息失败(离线跳过):%s", _exc)
|
||||
_STATE["cloud_available"] = False
|
||||
return None
|
||||
|
||||
|
||||
# ===================== 对外状态 =====================
|
||||
|
||||
def status() -> dict:
|
||||
"""当前浏览器状态快照(供前端展示与轮询)。"""
|
||||
local = detect_local()
|
||||
installed = local["installed"]
|
||||
if installed:
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = local["version"]
|
||||
_STATE["check_error"] = ""
|
||||
else:
|
||||
_STATE["installed"] = False
|
||||
_STATE["version"] = ""
|
||||
pkg_ok = bool(_PENDING_PKG) and _PENDING_PKG.is_file()
|
||||
return {
|
||||
"installed": _STATE["installed"],
|
||||
"version": _STATE["version"],
|
||||
"downloaded": bool(pkg_ok),
|
||||
"cloud_available": bool(_STATE["cloud_available"]),
|
||||
"error": _STATE["check_error"],
|
||||
"installing": bool(_STATE["installing"]),
|
||||
"dl": {
|
||||
"status": _STATE["dl_status"],
|
||||
"received": _STATE.get("dl_received", 0),
|
||||
"total": _STATE.get("dl_total", 0),
|
||||
"pct": _STATE.get("dl_pct", 0),
|
||||
"error": _STATE.get("dl_error", ""),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def refresh() -> None:
|
||||
"""前端手动触发一次检测:拉取云端登记,更新 cloud_available。"""
|
||||
global _STATE
|
||||
_STATE["checking"] = True
|
||||
try:
|
||||
detect_local()
|
||||
_cloud_info()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("浏览器检测异常:%s", _exc)
|
||||
finally:
|
||||
_STATE["checking"] = False
|
||||
|
||||
|
||||
# ===================== 下载 =====================
|
||||
|
||||
def start_download() -> None:
|
||||
"""开始下载 Chrome 安装包(后台线程)。已有下载/已下载则直接沿用。"""
|
||||
if _STATE["dl_status"] == "downloading":
|
||||
return
|
||||
if _STATE["dl_status"] == "downloaded" and _PENDING_PKG and _PENDING_PKG.is_file():
|
||||
return
|
||||
info = _cloud_info()
|
||||
if not info or not info.get("url"):
|
||||
return
|
||||
url = str(info["url"]).strip()
|
||||
expect = (info.get("sha256") or "").lower()
|
||||
filename = (info.get("filename") or "ChromeStandaloneSetup64.exe").strip()
|
||||
_STATE["dl_version"] = info.get("version", "")
|
||||
_STATE["dl_status"] = "downloading"
|
||||
_STATE["dl_received"] = 0
|
||||
_STATE["dl_total"] = 0
|
||||
_STATE["dl_pct"] = 0
|
||||
_STATE["dl_error"] = ""
|
||||
threading.Thread(target=_download, args=(url, expect, filename), daemon=True,
|
||||
name="chrome-download").start()
|
||||
_LOGGER.info("开始下载 Chrome 安装包:%s", url)
|
||||
|
||||
|
||||
def _download(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
try:
|
||||
with _DL_LOCK:
|
||||
_download_locked(url, expect, filename)
|
||||
except Exception as _exc: # noqa: BLE001 异常兜底
|
||||
_LOGGER.exception("下载 Chrome 异常")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
|
||||
|
||||
def _download_locked(url: str, expect: str, filename: str) -> None:
|
||||
import requests
|
||||
tmp = _CHROME_CACHE / f"{filename}.part"
|
||||
pkg = _CHROME_CACHE / filename
|
||||
try:
|
||||
_CHROME_CACHE.mkdir(parents=True, exist_ok=True)
|
||||
with requests.get(url, stream=True, timeout=600) as r:
|
||||
r.raise_for_status()
|
||||
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
|
||||
sha = hashlib.sha256()
|
||||
with open(tmp, "wb") as f:
|
||||
for chunk in r.iter_content(256 * 1024):
|
||||
if not chunk:
|
||||
continue
|
||||
f.write(chunk)
|
||||
sha.update(chunk)
|
||||
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
|
||||
total = _STATE["dl_total"]
|
||||
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载 Chrome 安装包失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
|
||||
_cleanup_part()
|
||||
return
|
||||
if expect and sha.hexdigest() != expect:
|
||||
_LOGGER.error("Chrome 安装包 sha256 校验失败")
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包校验失败,请重试"
|
||||
_cleanup_part()
|
||||
return
|
||||
try:
|
||||
os.replace(tmp, pkg)
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("Chrome 安装包落盘失败:%s", _exc)
|
||||
_STATE["dl_status"] = "failed"
|
||||
_STATE["dl_error"] = "安装包保存失败"
|
||||
_cleanup_part()
|
||||
return
|
||||
global _PENDING_PKG
|
||||
_PENDING_PKG = pkg
|
||||
_STATE["dl_status"] = "downloaded"
|
||||
_STATE["dl_pct"] = 100
|
||||
_STATE["dl_received"] = _STATE["dl_total"]
|
||||
_LOGGER.info("Chrome 安装包下载完成:%s", pkg)
|
||||
|
||||
|
||||
def _cleanup_part() -> None:
|
||||
try:
|
||||
for p in _CHROME_CACHE.glob("*.part"):
|
||||
p.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ===================== 安装 =====================
|
||||
|
||||
def install() -> dict:
|
||||
"""静默安装已下载的 Chrome 安装包。返回立即,安装后台进行。"""
|
||||
pkg = _PENDING_PKG
|
||||
if not pkg or not pkg.is_file():
|
||||
raise FileNotFoundError("未找到已下载的 Chrome 安装包")
|
||||
_STATE["installing"] = True
|
||||
_LOGGER.info("开始静默安装 Chrome:%s", pkg)
|
||||
# Chrome 官方安装器:/silent 静默 + /install 装机(对未登录用户安装)
|
||||
subprocess.Popen(
|
||||
[str(pkg), "/silent", "/install"],
|
||||
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
# 安装完成后由前端轮询 installed 状态感知成功
|
||||
threading.Thread(target=_poll_install, daemon=True, name="chrome-install-watch").start()
|
||||
return {"ok": True, "installing": True}
|
||||
|
||||
|
||||
def _poll_install() -> None:
|
||||
"""轮询等待 Chrome 装好(最长 ~5 分钟),完成后重置 downloading 态供再次检测。"""
|
||||
import time
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
if detect_local()["installed"]:
|
||||
_STATE["installing"] = False
|
||||
_STATE["installed"] = True
|
||||
_STATE["version"] = detect_local()["version"]
|
||||
_LOGGER.info("Chrome 安装完成:%s", _STATE["version"])
|
||||
return
|
||||
_STATE["installing"] = False
|
||||
_LOGGER.warning("等待 Chrome 安装完成超时")
|
||||
@@ -0,0 +1,128 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""环境包版插件执行守护:Job Object 托管 + 内存上限 + 超时强杀。
|
||||
|
||||
Node 壳(electron-shell runner.js)在**便携环境包**模式下不再直接 spawn
|
||||
plugin_runner,而是经由本守护拉起,以获得旧 Python 底座同等的进程托管能力:
|
||||
|
||||
python job_guard.py [--mem <MB>] [--timeout <秒>] -- <python> -u <plugin_runner.py> [args...]
|
||||
|
||||
- Job Object(KILL_ON_JOB_CLOSE + PROCESS_MEMORY_LIMIT,复用 winjob.py)
|
||||
→ 插件及其拉起的浏览器孙进程整体托管,内存超限/超时/宿主退出即整树终止;
|
||||
- stdin/stdout/stderr 三通道逐字节透传(plugin_runner 协议不经过本进程改写,
|
||||
与 Node 直接 spawn 时逐字节一致:fields 单行 JSON → 事件行/诊断行);
|
||||
- 退出码 = 子进程退出码(透传),Node 侧结论判定逻辑不变;
|
||||
- 非 Windows 平台安全降级为直接 spawn 子进程(winjob 内部 no-op)。
|
||||
|
||||
本文件同时进入环境包运行时子集(webhost/backend/core/job_guard.py),
|
||||
不依赖任何第三方包(ctypes 标准库实现)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from webhost.backend.core import winjob # 环境包/仓库内相对解析
|
||||
except Exception: # noqa: BLE001 兜底:直接同目录导入
|
||||
import winjob
|
||||
|
||||
|
||||
def _forward(src, dst, name: str) -> None:
|
||||
"""把 src 的字节流逐块转发到 dst;EOF 后 flush 并结束。"""
|
||||
try:
|
||||
while True:
|
||||
chunk = src.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
dst.write(chunk)
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001 通道关闭即结束
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
dst.flush()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(description="37du 插件执行守护(Job Object 托管)")
|
||||
parser.add_argument("--mem", type=int, default=0, help="作业级内存上限(MB),0=不限")
|
||||
parser.add_argument("--timeout", type=int, default=0, help="超时秒数,0=不限(Node 侧仍有兜底强杀)")
|
||||
parser.add_argument("child", nargs=argparse.REMAINDER, help="-- 之后为真实子进程命令")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if not args.child or args.child[0] != "--":
|
||||
print("用法:python job_guard.py [--mem MB] [--timeout 秒] -- <cmd...>", file=sys.stderr)
|
||||
return 2
|
||||
child_cmd = args.child[1:]
|
||||
if not child_cmd:
|
||||
print("缺少子进程命令", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
# 透传环境(宿主注入的 PLUGINS_ROOT / PLATFORM_ACCOUNT 等原样继承)
|
||||
env = dict(os.environ)
|
||||
|
||||
# 1) 子进程:stdin/stdout/stderr 直接对接父进程(Node 侧),协议零改写
|
||||
try:
|
||||
child = subprocess.Popen(
|
||||
child_cmd,
|
||||
stdin=sys.stdin.buffer,
|
||||
stdout=sys.stdout.buffer,
|
||||
stderr=sys.stderr.buffer,
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
bufsize=0,
|
||||
)
|
||||
except OSError as e:
|
||||
print(f"拉起子进程失败: {e}", file=sys.stderr)
|
||||
return 127
|
||||
|
||||
# 2) Job Object 托管(Windows):整树终止 + 内存上限
|
||||
job = winjob.Job(max_mem_mb=int(args.mem or 0))
|
||||
try:
|
||||
job.assign(child)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 3) 超时守护(兜底;Node 侧 taskkill 仍作为第二道防线)
|
||||
timed_out = {"v": False}
|
||||
|
||||
def _kill_on_timeout() -> None:
|
||||
time.sleep(max(1, int(args.timeout or 0)))
|
||||
timed_out["v"] = True
|
||||
try:
|
||||
job.terminate(1)
|
||||
except Exception: # noqa: BLE001
|
||||
try:
|
||||
child.kill()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
timer = None
|
||||
if int(args.timeout or 0) > 0:
|
||||
timer = threading.Thread(target=_kill_on_timeout, daemon=True)
|
||||
timer.start()
|
||||
|
||||
# 4) 等子进程结束(进程退出/超时终止均在此返回);子进程自身已接管三通道
|
||||
try:
|
||||
code = child.wait()
|
||||
except KeyboardInterrupt:
|
||||
job.terminate(1)
|
||||
try:
|
||||
code = child.wait(timeout=5)
|
||||
except Exception: # noqa: BLE001
|
||||
code = 1
|
||||
|
||||
job.close()
|
||||
if timed_out["v"]:
|
||||
print(f"[job_guard] 插件执行超时({args.timeout}s)已强制终止", file=sys.stderr)
|
||||
return int(code) if code is not None else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,241 +1,242 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
return str(json.loads(mf.read_text(encoding="utf-8")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 插件按账号权限自下载 + 版本更新(执行机主动拉取,非控制面分发)。
|
||||
|
||||
流程:联网时按「当前登录账号」从控制面拉可用插件清单 → 对比本地已装版本,
|
||||
缺失/落后则走 download-ticket 一次性票据下载 zip → sha256 校验 → 解压到
|
||||
plugins/<id>/ 原子替换;更新成功后由宿主重载插件注册表。
|
||||
|
||||
本地清理:云端清单可达时,本地存在但不在清单中的插件(中心机已删除/已收回
|
||||
授权)同步移除本地目录;清单不可达(离线)时不动本地,保证离线可继续运行。
|
||||
|
||||
降级策略:
|
||||
- 控制面不可达/未配置 → 跳过同步,沿用本地已有插件(离线可继续运行)
|
||||
- 单个插件下载/校验/解压失败 → 记 ERROR 跳过,不影响其它插件与本地旧版本
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.plugins import _PLUGINS_ROOT
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DL_TIMEOUT = 300 # 包下载超时(秒);插件包含 ui 资源可达数 MB,留足弱网余量
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024 # 包大小上限,与控制面一致
|
||||
|
||||
# 同步串行锁:启动后台同步 / 登录后同步 / 手动刷新共用,防止并发同步互相覆盖
|
||||
# (后完成的旧账号白名单 set_allowed+reload 会清掉刚同步好的插件清单)
|
||||
SYNC_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _headers() -> dict:
|
||||
h = {}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cloud_plugin_manifest(account: str) -> list | None:
|
||||
"""拉取账号可用插件清单(id/name/version)。控制面不可达/未配置返回 None。"""
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json().get("plugins", [])
|
||||
except Exception as _exc: # noqa: BLE001 离线兜底
|
||||
_LOGGER.warning("拉取插件清单失败(离线用本地插件):%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _local_version(plugin_id: str) -> str:
|
||||
"""本地已装插件版本:读 plugins/<id>/plugin.json.version;无则空串。"""
|
||||
mf = _PLUGINS_ROOT / plugin_id / "plugin.json"
|
||||
if not mf.is_file():
|
||||
return ""
|
||||
try:
|
||||
# utf-8-sig:防 plugin.json 带 UTF-8 BOM(json.loads 遇 BOM 会抛 JSONDecodeError → 误判为新装重下)
|
||||
return str(json.loads(mf.read_text(encoding="utf-8-sig")).get("version") or "")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _version_lt(a: str, b: str) -> bool:
|
||||
"""简单版本比较(数字段按 int 比较)。"""
|
||||
def _key(v: str):
|
||||
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
|
||||
try:
|
||||
return _key(a) < _key(b)
|
||||
except Exception: # noqa: BLE001
|
||||
return a != b and a < b
|
||||
|
||||
|
||||
def _dl_ticket(plugin_id: str, version: str, account: str) -> dict | None:
|
||||
"""向控制面签发一次性下载票据;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{config.CONTROLPLANE_URL}/api/plugins/{plugin_id}/versions/{version}/download-ticket",
|
||||
params={"account": account}, headers=_headers(), timeout=5)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("获取下载票据失败 %s@%s:%s", plugin_id, version, _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_pkg(ticket: str) -> bytes | None:
|
||||
"""凭一次性票据下载插件包 zip;失败返回 None。"""
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/download/{ticket}",
|
||||
headers=_headers(), timeout=_DL_TIMEOUT)
|
||||
r.raise_for_status()
|
||||
return r.content
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("下载插件包失败:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
def _install_pkg(plugin_id: str, content: bytes) -> bool:
|
||||
"""把插件包解压安装到 plugins/<id>/(临时目录 → 原子替换)。
|
||||
|
||||
包根目录需含 plugin.json;解压前校验非法路径防目录穿越。
|
||||
"""
|
||||
if len(content) > _MAX_PKG_BYTES:
|
||||
_LOGGER.error("插件包 %s 超大小上限,拒绝安装", plugin_id)
|
||||
return False
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(content))
|
||||
except zipfile.BadZipFile:
|
||||
_LOGGER.error("插件包 %s 不是合法 ZIP", plugin_id)
|
||||
return False
|
||||
with zf:
|
||||
names = zf.namelist()
|
||||
if "plugin.json" not in names:
|
||||
_LOGGER.error("插件包 %s 缺 plugin.json", plugin_id)
|
||||
return False
|
||||
for m in names:
|
||||
if m.startswith("/") or ".." in m.split("/"):
|
||||
_LOGGER.error("插件包 %s 含非法路径:%s", plugin_id, m)
|
||||
return False
|
||||
tmp = Path(tempfile.mkdtemp(prefix=f".pkg_{plugin_id}_"))
|
||||
try:
|
||||
zf.extractall(tmp)
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("解压插件包 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
# 原子替换:旧目录移除 → 新目录就位
|
||||
target = _PLUGINS_ROOT / plugin_id
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
shutil.move(str(tmp), str(target))
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.error("安装插件 %s 失败:%s", plugin_id, _exc)
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _local_plugin_entries() -> list:
|
||||
"""本地已落盘的插件条目(目录包 + 旧式单文件),发现规则与 plugins._discover_modules 对齐。
|
||||
|
||||
目录包:含 __init__.py 或 plugin.json(后者兜底覆盖下载中断的残缺目录);
|
||||
单文件:排除 __init__/base 与 `_` 前缀私有文件。
|
||||
"""
|
||||
out = []
|
||||
for entry in _PLUGINS_ROOT.iterdir():
|
||||
if entry.name.startswith("_") or entry.name == "__pycache__":
|
||||
continue
|
||||
if entry.is_dir():
|
||||
if (entry / "__init__.py").is_file() or (entry / "plugin.json").is_file():
|
||||
out.append(entry)
|
||||
elif entry.suffix == ".py" and entry.name not in ("__init__.py", "base.py"):
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def _prune_stale(keep_ids: set) -> list:
|
||||
"""清理中心机已删除/已收回授权的本地插件(仅在云端清单成功拉取后调用)。
|
||||
|
||||
设备正有任务执行时整轮跳过(避免动到运行中插件的文件),留待下次同步补删;
|
||||
单个目录删除失败记 WARNING 跳过,不影响其它清理与本次同步。
|
||||
"""
|
||||
from webhost.backend.core import scheduler
|
||||
|
||||
if not _PLUGINS_ROOT.is_dir() or scheduler._is_busy():
|
||||
return []
|
||||
removed = []
|
||||
for entry in _local_plugin_entries():
|
||||
pid = entry.stem if entry.is_file() else entry.name
|
||||
if pid in keep_ids:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir():
|
||||
shutil.rmtree(entry)
|
||||
else:
|
||||
entry.unlink()
|
||||
except OSError as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("清理本地插件 %s 失败:%s", pid, _exc)
|
||||
continue
|
||||
removed.append(pid)
|
||||
_LOGGER.info("插件 %s 已在中心机删除/收回授权,本地目录同步移除", pid)
|
||||
return removed
|
||||
|
||||
|
||||
def sync_plugins(account: str) -> dict:
|
||||
"""按账号权限同步插件(首次下载 + 版本更新 + 清理已删除)。离线/失败静默降级,返回统计。"""
|
||||
result = {"downloaded": [], "updated": [], "up_to_date": [], "failed": [], "removed": []}
|
||||
if not config.CONTROLPLANE_URL or not account:
|
||||
return result
|
||||
manifest = _cloud_plugin_manifest(account)
|
||||
if manifest is None:
|
||||
return result
|
||||
# 中心机已删除/收回授权的插件:本地同步清理(云端清单不可达时不动本地)
|
||||
result["removed"] = _prune_stale({p.get("id", "") for p in manifest})
|
||||
for p in manifest:
|
||||
pid = p.get("id", "")
|
||||
ver = p.get("version", "") or p.get("latest_version", "")
|
||||
if not pid or not ver:
|
||||
continue
|
||||
local = _local_version(pid)
|
||||
if local == ver or (local and not _version_lt(local, ver)):
|
||||
result["up_to_date"].append(pid)
|
||||
continue
|
||||
tkt = _dl_ticket(pid, ver, account)
|
||||
if not tkt:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
content = _fetch_pkg(tkt.get("ticket", ""))
|
||||
if not content:
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
expect = (tkt.get("sha256") or "").lower()
|
||||
if expect and hashlib.sha256(content).hexdigest() != expect:
|
||||
_LOGGER.error("插件包 %s@%s sha256 校验失败,拒绝安装", pid, ver)
|
||||
result["failed"].append(pid)
|
||||
continue
|
||||
if _install_pkg(pid, content):
|
||||
(result["updated"] if local else result["downloaded"]).append(pid)
|
||||
else:
|
||||
result["failed"].append(pid)
|
||||
_LOGGER.info("插件同步完成:下载=%s 更新=%s 最新=%s 清理=%s 失败=%s",
|
||||
result["downloaded"], result["updated"],
|
||||
result["up_to_date"], result["removed"], result["failed"])
|
||||
return result
|
||||
|
||||
@@ -66,12 +66,14 @@ _PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
|
||||
|
||||
|
||||
def local_shell_version() -> str:
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。"""
|
||||
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。
|
||||
用 utf-8-sig 读取:防文件带 UTF-8 BOM(记事本另存 UTF-8 时常见),否则会读到
|
||||
"\\ufeff1.2.0" 导致版本比对永远判为"不大于"(P1 修复:壳子升级失效根因)。"""
|
||||
if not getattr(sys, "frozen", False):
|
||||
return ""
|
||||
vf = Path(sys.executable).resolve().parent / "shell.version"
|
||||
try:
|
||||
return vf.read_text(encoding="utf-8").strip() if vf.is_file() else ""
|
||||
return vf.read_text(encoding="utf-8-sig").strip() if vf.is_file() else ""
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
@@ -19,17 +19,22 @@ from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS # noqa: F401 由 base 构造空注册表
|
||||
|
||||
# 插件目录(源码/打包统一的"单一真源"位置):
|
||||
# 插件目录(源码/打包/环境包统一的"单一真源"位置):
|
||||
# - 环境包/便携运行时:由宿主(Node 壳)显式注入 PLUGINS_ROOT 环境变量(指向插件根)
|
||||
# - 打包运行(frozen)时:exe 同级 plugins/(中心机下发插件包解压到这里)
|
||||
# - 源码运行:仓库根 plugins/(插件源码独立于底座,不随 webhost 发布)
|
||||
# 两种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
if getattr(sys, "frozen", False):
|
||||
# 三种形态都扩展本包搜索路径,使其可按 webhost.backend.plugins.<name> 被 import
|
||||
_env_plugins_root = os.getenv("PLUGINS_ROOT", "").strip()
|
||||
if _env_plugins_root:
|
||||
_PLUGINS_ROOT = pathlib.Path(_env_plugins_root).resolve()
|
||||
elif getattr(sys, "frozen", False):
|
||||
_PLUGINS_ROOT = pathlib.Path(sys.executable).resolve().parent / "plugins"
|
||||
else:
|
||||
# __file__ = desktop/webhost/backend/plugins/__init__.py → parents[4] = 仓库根
|
||||
|
||||
@@ -1,449 +1,455 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: hr_login.py
|
||||
@Description: HR 登录自定义指令(影刀编码版 Python 模块源码)。
|
||||
作为「37duHR登录」影刀自定义指令的模块源码(单一真源),
|
||||
供所有 HR 系统影刀脚本复用,避免每个脚本各自内联滑块登录逻辑。
|
||||
|
||||
如何在影刀中创建指令:
|
||||
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 hr_login,添加 Python 模块;
|
||||
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
|
||||
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
|
||||
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
|
||||
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效 cookies。
|
||||
|
||||
约定(与项目 app 版一致,见 app/common/app_paths.py):
|
||||
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
|
||||
(本地开发时也兼容当前工作目录下的 .env);
|
||||
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\hr_cookies.json,
|
||||
各影刀业务脚本自行用这些 cookies 构建 requests.Session。
|
||||
|
||||
配置(已直接内置在模块源码中,无需 .env / 环境变量):
|
||||
LOGIN_URL=HR 登录页 URL
|
||||
SUCCESS_KEYWORD=HR 登录成功后 URL 关键字
|
||||
USERNAME=用户名
|
||||
PASSWORD=密码
|
||||
hr_validate_url=(可选,.env/系统变量)HR 会话校验接口 URL;默认使用 getCurUserInfo 接口
|
||||
hr_captcha_debug_dir=(可选)滑块调试图片输出目录;不设置则不落盘
|
||||
|
||||
全局变量(在影刀流程中创建,此指令负责写入):
|
||||
login_state 登录成功或缓存的 cookies 有效时写入 True,否则为 False
|
||||
|
||||
依赖(影刀「Python包管理」安装):
|
||||
pip install DrissionPage requests python-dotenv opencv-python numpy Pillow
|
||||
|
||||
入口:
|
||||
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
|
||||
python hr_login.py 独立运行(等价于 main({"force": true}))
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
import random
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
from dotenv import load_dotenv
|
||||
import requests
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ================== 共享路径(与 app 版统一) ==================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
def _load_shared_env():
|
||||
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
|
||||
if os.path.exists(SHARED_ENV_FILE):
|
||||
load_dotenv(SHARED_ENV_FILE)
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# ================== 配置 ==================
|
||||
# 账号密码只从共享 .env 读取(%LOCALAPPDATA%\37duAutomation\.env 或项目 .env),不内置明文,
|
||||
# 避免真实凭据写进源码/git 历史;缺失时登录会提示「登录配置缺失」。
|
||||
_load_shared_env()
|
||||
LOGIN_URL = 'https://hr.37du.co/RedseaPlatform/'
|
||||
SUCCESS_KEYWORD = 'https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic'
|
||||
USERNAME = os.getenv('hr_login_username', '')
|
||||
PASSWORD = os.getenv('hr_login_password', '')
|
||||
|
||||
# HR 会话校验接口:cookies 有效时返回 JSON,失效时返回登录页等非 JSON
|
||||
GET_CUR_USER_INFO_URL = "https://hr.37du.co/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
|
||||
LOGIN_BTN = "@id=login-btn"
|
||||
ACCOUNT_INPUT = "@id=j_username"
|
||||
PASSWORD_INPUT = "@id=j_password_2"
|
||||
CAPTCHA_CONTAINER = ".:comImageValidate"
|
||||
SLIDER_BTN = ".:v_rightBtn"
|
||||
BG_IMG = ".imgBg"
|
||||
SLIDER_IMG = "css:div.imgBg_3 > img"
|
||||
|
||||
RETRY_MAX = 5
|
||||
TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
# ================== Cookies 持久化(登录成功后缓存,下次免登录复用) ==================
|
||||
def save_browser_cookies(page):
|
||||
cookies = page.cookies(all_domains=True)
|
||||
if not cookies:
|
||||
print("未获取到 Cookies,跳过保存")
|
||||
return
|
||||
ensure_dir(_SESSIONS_DIR)
|
||||
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(COOKIE_FILE):
|
||||
return None
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 影刀全局变量 ==================
|
||||
def _set_login_state(value):
|
||||
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
|
||||
try:
|
||||
glv['login_state'] = value
|
||||
print(f"已写入影刀全局变量 login_state={value}")
|
||||
except Exception as e:
|
||||
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
|
||||
|
||||
|
||||
# ================== API 校验 cookies 有效性(无需打开浏览器) ==================
|
||||
def _is_hr_session_valid():
|
||||
"""API 轻量校验 HR cookies:请求 hr_validate_url(默认 getCurUserInfo 接口),
|
||||
返回 JSON 视为 cookies 有效;返回登录页等非 JSON 即视为失效。
|
||||
|
||||
与业务脚本(attendance_abnormal/bank_card_check 等)使用同一套构建方式:
|
||||
requests.Session + Chrome UA/Content-Type + 仅注入 37du.co 域 cookies。
|
||||
"""
|
||||
validate_url = os.getenv('hr_validate_url', '').strip() or GET_CUR_USER_INFO_URL
|
||||
try:
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
resp = session.post(validate_url, data={}, timeout=15)
|
||||
if resp.status_code != 200:
|
||||
print(f"API 校验 cookies 状态码异常:{resp.status_code}")
|
||||
return False
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
print(f"API 校验 cookies 异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 滑块匹配(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def match_slider_dual(bg_bytes, slider_bytes):
|
||||
"""模板匹配滑块缺口,返回物理距离(px)。"""
|
||||
bg_img = cv2.imdecode(np.frombuffer(bg_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
slider_color = cv2.imdecode(np.frombuffer(slider_bytes, np.uint8), cv2.IMREAD_UNCHANGED)
|
||||
if bg_img is None or slider_color is None:
|
||||
raise RuntimeError("无法解码验证码图片")
|
||||
|
||||
bg_h, bg_w = bg_img.shape[:2]
|
||||
x_offset, y_offset = 0, 0
|
||||
if len(slider_color.shape) == 3 and slider_color.shape[2] == 4:
|
||||
alpha = slider_color[:, :, 3]
|
||||
slider_rgb = slider_color[:, :, :3]
|
||||
ys, xs = np.where(alpha > 0)
|
||||
if len(ys) > 0:
|
||||
y_min, y_max = np.min(ys), np.max(ys)
|
||||
x_min, x_max = np.min(xs), np.max(xs)
|
||||
slider_rgb = slider_rgb[y_min:y_max + 1, x_min:x_max + 1]
|
||||
x_offset, y_offset = x_min, y_min
|
||||
else:
|
||||
slider_rgb = slider_color[:, :, :3] if len(slider_color.shape) == 3 else slider_color
|
||||
|
||||
s_h, s_w = slider_rgb.shape[:2]
|
||||
gray_bg = cv2.GaussianBlur(cv2.cvtColor(bg_img, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
gray_slider = cv2.GaussianBlur(cv2.cvtColor(slider_rgb, cv2.COLOR_BGR2GRAY), (3, 3), 0)
|
||||
bg_edges = cv2.Canny(gray_bg, 50, 150)
|
||||
slider_edges = cv2.Canny(gray_slider, 50, 150)
|
||||
result = cv2.matchTemplate(bg_edges, slider_edges, cv2.TM_CCOEFF_NORMED)
|
||||
|
||||
candidates = []
|
||||
temp_result = result.copy()
|
||||
for _ in range(6):
|
||||
_, max_val, _, max_loc = cv2.minMaxLoc(temp_result)
|
||||
if max_val < 0.03:
|
||||
break
|
||||
candidates.append((max_val, max_loc))
|
||||
y0 = max(0, max_loc[1] - s_h // 2); y1 = min(temp_result.shape[0], max_loc[1] + s_h // 2)
|
||||
x0 = max(0, max_loc[0] - s_w // 2); x1 = min(temp_result.shape[1], max_loc[0] + s_w // 2)
|
||||
temp_result[y0:y1, x0:x1] = -2.0
|
||||
|
||||
if not candidates:
|
||||
raise RuntimeError("无有效滑块候选")
|
||||
|
||||
right_limit = bg_w - s_w - max(15, int(bg_w * 0.06))
|
||||
|
||||
def region_whiteness(x, y, w, h):
|
||||
roi = bg_img[y:y + h, x:x + w]
|
||||
if roi.size == 0:
|
||||
return 0.0
|
||||
return float(np.all(roi > 200, axis=2).mean())
|
||||
|
||||
scored = []
|
||||
for val, loc in candidates:
|
||||
x, y = loc
|
||||
if x <= s_w or x > right_limit:
|
||||
continue
|
||||
scored.append((val + 0.5 * region_whiteness(x, y, s_w, s_h), val, loc))
|
||||
|
||||
if scored:
|
||||
scored.sort(key=lambda t: t[0], reverse=True)
|
||||
best_val, best_loc = scored[0][1], scored[0][2]
|
||||
else:
|
||||
best_val, best_loc = candidates[0]
|
||||
|
||||
distance = best_loc[0] - x_offset
|
||||
if distance < 0:
|
||||
distance = 0
|
||||
if distance + s_w > bg_w:
|
||||
distance = bg_w - s_w
|
||||
return distance
|
||||
|
||||
|
||||
# ================== 轨迹生成与滑动 ==================
|
||||
def generate_track(distance):
|
||||
overshoot = random.randint(2, 6) if random.random() < 0.75 else 0
|
||||
aim = distance + overshoot
|
||||
steps = []
|
||||
moved = 0
|
||||
y = 0
|
||||
while moved < aim:
|
||||
remain = aim - moved
|
||||
if remain > 80:
|
||||
dx = min(remain, random.randint(9, 15)); dt = random.uniform(0.010, 0.022)
|
||||
elif remain > 35:
|
||||
dx = min(remain, random.randint(5, 9)); dt = random.uniform(0.012, 0.028)
|
||||
elif remain > 12:
|
||||
dx = min(remain, random.randint(2, 5)); dt = random.uniform(0.016, 0.040)
|
||||
else:
|
||||
dx = min(remain, random.randint(1, 3)); dt = random.uniform(0.020, 0.060)
|
||||
if random.random() < 0.22:
|
||||
y = max(-2, min(2, y + random.choice([-1, 1])))
|
||||
else:
|
||||
y = int(round(y * 0.6))
|
||||
steps.append((dx, y, dt))
|
||||
moved += dx
|
||||
if overshoot > 0:
|
||||
back = overshoot
|
||||
while back > 0:
|
||||
dx = -min(back, random.randint(1, 3))
|
||||
steps.append((dx, random.choice([-1, 0, 1]), random.uniform(0.030, 0.080)))
|
||||
back += dx
|
||||
if random.random() < 0.65:
|
||||
steps.extend([(0, 0, random.uniform(0.060, 0.140)),
|
||||
(1, 0, random.uniform(0.020, 0.050)),
|
||||
(-1, 0, random.uniform(0.020, 0.050))])
|
||||
return steps
|
||||
|
||||
|
||||
def perform_slide(page, btn, distance_css):
|
||||
if distance_css <= 0:
|
||||
return False
|
||||
mid = btn.rect.midpoint
|
||||
steps = generate_track(distance_css)
|
||||
try:
|
||||
page.actions.move_to((mid[0] + random.uniform(-3, 3), mid[1] + random.uniform(-2, 2)),
|
||||
duration=random.uniform(0.25, 0.60))
|
||||
time.sleep(random.uniform(0.18, 0.45))
|
||||
page.actions.hold(on_ele=btn)
|
||||
time.sleep(random.uniform(0.12, 0.28))
|
||||
for dx, dy, dt in steps:
|
||||
if dx == 0 and dy == 0:
|
||||
time.sleep(dt)
|
||||
else:
|
||||
page.actions.move(offset_x=dx, offset_y=dy, duration=dt)
|
||||
time.sleep(random.uniform(0.10, 0.26))
|
||||
page.actions.release()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"拖拽异常:{e}")
|
||||
return False
|
||||
|
||||
|
||||
# ================== 验证码处理(与已验证可用的 bank_card/roster 内联版一致) ==================
|
||||
def handle_captcha(page):
|
||||
for retry in range(RETRY_MAX):
|
||||
print(f"\n--- 第 {retry + 1} 次尝试验证 ---")
|
||||
try:
|
||||
container = page.ele(CAPTCHA_CONTAINER, timeout=TIMEOUT)
|
||||
if not container:
|
||||
print("验证码容器未出现")
|
||||
continue
|
||||
bg_ele = container.ele(BG_IMG) or container.ele('div[style*="background-image"]')
|
||||
slider_ele = container.ele(SLIDER_IMG)
|
||||
if not bg_ele or not slider_ele:
|
||||
print("找不到背景图/滑块小图元素")
|
||||
continue
|
||||
if slider_ele.tag != 'img':
|
||||
inner = slider_ele.ele('tag:img')
|
||||
if inner:
|
||||
slider_ele = inner
|
||||
try:
|
||||
page.run_js('arguments[0].style.display = "none"', slider_ele)
|
||||
time.sleep(0.2)
|
||||
bg_screenshot = bg_ele.get_screenshot(as_bytes='png')
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
time.sleep(0.2)
|
||||
slider_screenshot = slider_ele.get_screenshot(as_bytes='png')
|
||||
except Exception:
|
||||
page.run_js('arguments[0].style.display = ""', slider_ele)
|
||||
continue
|
||||
|
||||
if not bg_screenshot or not slider_screenshot:
|
||||
print("截图数据为空")
|
||||
continue
|
||||
|
||||
distance_phys = match_slider_dual(bg_screenshot, slider_screenshot)
|
||||
dpr = page.run_js('return window.devicePixelRatio') or 1
|
||||
distance_css = distance_phys / dpr
|
||||
print(f" 匹配距离 {distance_phys}px -> CSS {distance_css:.1f}px")
|
||||
|
||||
btn = page.ele(SLIDER_BTN)
|
||||
if btn and perform_slide(page, btn, distance_css):
|
||||
time.sleep(2)
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
if not page.ele(CAPTCHA_CONTAINER, timeout=1):
|
||||
return True
|
||||
time.sleep(2)
|
||||
except Exception as e:
|
||||
print(f"异常:{e}")
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _do_login():
|
||||
"""打开浏览器完成登录(含滑块),成功保存 cookies。"""
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("已登录")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
account = page.ele(ACCOUNT_INPUT)
|
||||
if not account:
|
||||
print("找不到账号输入框")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(USERNAME)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele(PASSWORD_INPUT)
|
||||
if not pwd:
|
||||
print("找不到密码输入框")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(PASSWORD)
|
||||
time.sleep(0.5)
|
||||
|
||||
login_btn = page.ele(LOGIN_BTN)
|
||||
if not login_btn:
|
||||
print("找不到登录按钮")
|
||||
return False
|
||||
login_btn.click()
|
||||
time.sleep(3)
|
||||
|
||||
if SUCCESS_KEYWORD in page.url:
|
||||
print("登录成功(无滑块)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
|
||||
if handle_captcha(page):
|
||||
print("登录成功(验证通过)")
|
||||
save_browser_cookies(page)
|
||||
return True
|
||||
print("登录失败")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(force=False):
|
||||
"""
|
||||
确保存在有效的 HR 登录态并缓存 cookies。
|
||||
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
_load_shared_env()
|
||||
# 默认未登录;登录成功或复用有效 cookies 后再置 True
|
||||
_set_login_state(False)
|
||||
|
||||
if not (LOGIN_URL and SUCCESS_KEYWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_url / hr_target_url_keyword 未配置且无内置默认值)", "relogin": False}
|
||||
if not (USERNAME and PASSWORD):
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录配置缺失(hr_login_username / hr_login_password 未配置且无内置默认值)", "relogin": False}
|
||||
|
||||
# 优先复用已保存的 cookies(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and _is_hr_session_valid():
|
||||
print("已通过缓存的 Cookies 复用 HR 登录态")
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
ok = _do_login()
|
||||
if ok:
|
||||
_set_login_state(True)
|
||||
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": "登录失败(滑块验证未通过)", "relogin": False}
|
||||
|
||||
|
||||
# ================== 影刀自定义指令入口 ==================
|
||||
def main(args):
|
||||
"""
|
||||
影刀自定义指令「37duHR登录」调用入口。
|
||||
args: dict,可选字段 force(bool) 是否强制重新登录
|
||||
返回: dict {success, cookie_path, message, relogin}
|
||||
"""
|
||||
if not args:
|
||||
args = {}
|
||||
force = bool(args.get("force", False))
|
||||
try:
|
||||
return ensure_login(force=force)
|
||||
except Exception as e:
|
||||
return {"success": False, "cookie_path": COOKIE_FILE,
|
||||
"message": f"登录过程异常:{e}", "relogin": False}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = main({"force": False})
|
||||
print("最终结果:", result)
|
||||
|
||||
@@ -48,6 +48,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
|
||||
|
||||
|
||||
@@ -125,6 +125,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
'37duAutomation'
|
||||
)
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 组织维护查询接口(与 app 版 ehr/common/config 一致) ----------
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -90,6 +90,12 @@ _APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
|
||||
# 未设置时沿用共享目录(兼容影刀版/命令行直跑)
|
||||
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
|
||||
if _ACCOUNT:
|
||||
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
|
||||
@@ -1,12 +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>
|
||||
<!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>
|
||||
File diff suppressed because it is too large
Load Diff
+129
-129
@@ -1,130 +1,130 @@
|
||||
// 与 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 checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { 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 async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
// 与 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 checkShellUpdate() {
|
||||
return j('/api/shell/check', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function downloadShellUpdate() {
|
||||
return j('/api/shell/download', { method: 'POST' })
|
||||
}
|
||||
|
||||
export async function applyShellUpdate() {
|
||||
return j('/api/shell/apply', { method: 'POST' })
|
||||
}
|
||||
|
||||
// ===== 浏览器(Chrome)安装 =====
|
||||
export async function getChromeStatus() {
|
||||
return j('/api/chrome/status')
|
||||
}
|
||||
export async function checkChrome() {
|
||||
return j('/api/chrome/check', { method: 'POST' })
|
||||
}
|
||||
export async function downloadChrome() {
|
||||
return j('/api/chrome/download', { method: 'POST' })
|
||||
}
|
||||
export async function installChrome() {
|
||||
return j('/api/chrome/install', { 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 async function listSchedules() {
|
||||
return j('/api/schedules')
|
||||
}
|
||||
export async function createSchedule(body) {
|
||||
return j('/api/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function updateSchedule(sid, body) {
|
||||
return j(`/api/schedules/${sid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
export async function deleteSchedule(sid) {
|
||||
return j(`/api/schedules/${sid}`, { method: 'DELETE' })
|
||||
}
|
||||
export async function toggleSchedule(sid, enabled) {
|
||||
return j(`/api/schedules/${sid}/toggle`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
})
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
export async function adminAvatarUpload(file) {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return j('/api/avatar', { method: 'POST', body: fd })
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,353 +1,353 @@
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<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>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<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-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<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-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } 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()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
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: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.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: var(--text); 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: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.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: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
<template>
|
||||
<el-drawer
|
||||
v-model="visible"
|
||||
title="个人中心"
|
||||
direction="rtl"
|
||||
size="360px"
|
||||
:with-header="true"
|
||||
@close="emit('close')"
|
||||
>
|
||||
<!-- 个人信息:头像 + 昵称(大字)/ 工号(小字),更换头像收进小图标 -->
|
||||
<section class="pcard">
|
||||
<div class="cover"></div>
|
||||
<div class="pcard-main">
|
||||
<div class="avatar-wrap">
|
||||
<el-avatar :size="64" :src="accountAvatar()" @error="onAvatarError" class="avatar">
|
||||
<span>{{ displayName.slice(0, 1) }}</span>
|
||||
</el-avatar>
|
||||
<button class="avatar-pick" title="更换头像" @click="pickAvatar">
|
||||
<el-icon :size="11"><Camera /></el-icon>
|
||||
</button>
|
||||
</div>
|
||||
<div class="pcard-id">
|
||||
<div class="name-line">
|
||||
<strong>{{ displayName }}</strong>
|
||||
</div>
|
||||
<span class="acct mono">{{ store.current }}</span>
|
||||
<span class="dept">{{ store.dept || '未设置部门' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pcard-rows">
|
||||
<div class="crow">
|
||||
<span>工号</span>
|
||||
<span class="mono">{{ store.current }}</span>
|
||||
</div>
|
||||
<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>
|
||||
<p v-if="!store.plugins.length" class="empty-tip">当前账号暂无可用插件</p>
|
||||
<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-item name="password">
|
||||
<template #title>
|
||||
<div class="panel-title">
|
||||
<el-icon><Lock /></el-icon>
|
||||
<span>修改密码</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-form label-position="top" :model="form" :rules="rules" ref="formRef" class="pwd-form">
|
||||
<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-button type="primary" :loading="pwdBusy" @click="changePwd" class="pwd-submit">
|
||||
{{ pwdBusy ? '提交中…' : '保存新密码' }}
|
||||
</el-button>
|
||||
</el-form>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-drawer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { Connection, Box, Lock, Camera } from '@element-plus/icons-vue'
|
||||
import { store, log, clearAvatarCache, accountAvatar } from '../store'
|
||||
import { loginPlatform, logoutPlatform, adminPassword, adminAvatarUpload } 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()
|
||||
}
|
||||
|
||||
// 更换头像:选图上传到中心机(webhost 代理),成功后即显示账号头像
|
||||
const fileInput = (() => {
|
||||
const el = document.createElement('input')
|
||||
el.type = 'file'
|
||||
el.accept = 'image/*'
|
||||
return el
|
||||
})()
|
||||
function pickAvatar() {
|
||||
fileInput.onchange = async () => {
|
||||
const f = fileInput.files && fileInput.files[0]
|
||||
fileInput.value = ''
|
||||
if (!f) return
|
||||
try {
|
||||
const r = await adminAvatarUpload(f)
|
||||
store.avatar = r.avatar || ''
|
||||
ElMessage.success('头像已更新')
|
||||
} catch (e) {
|
||||
ElMessage.error('上传失败:' + (e.message || e))
|
||||
}
|
||||
}
|
||||
fileInput.click()
|
||||
}
|
||||
|
||||
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: 14px;
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.cover {
|
||||
height: 58px;
|
||||
background: linear-gradient(135deg, #dfe7ff 0%, #eef2ff 55%, #f6f8ff 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.pcard-main {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
padding: 0 18px 14px;
|
||||
margin-top: -30px;
|
||||
position: relative;
|
||||
}
|
||||
.avatar-wrap { position: relative; flex: none; }
|
||||
.avatar {
|
||||
border: 3px solid #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 4px 14px -4px rgba(59, 108, 255, .35);
|
||||
background: var(--primary-grad);
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.avatar-pick {
|
||||
position: absolute; right: -2px; bottom: -2px;
|
||||
width: 20px; height: 20px; border-radius: 50%;
|
||||
display: grid; place-items: center;
|
||||
border: 2px solid #fff;
|
||||
background: var(--primary); color: #fff;
|
||||
cursor: pointer; padding: 0;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.avatar-pick:hover { transform: scale(1.12); }
|
||||
.pcard-id { min-width: 0; }
|
||||
.name-line { display: flex; align-items: center; gap: 8px; }
|
||||
.name-line strong {
|
||||
font-size: 17px; font-weight: 700; letter-spacing: .01em; color: var(--text);
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 210px;
|
||||
}
|
||||
.acct { display: block; margin-top: 3px; font-size: 11.5px; color: var(--text-faint); }
|
||||
.dept { display: block; margin-top: 2px; font-size: 12px; color: var(--text-sub); }
|
||||
|
||||
.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: var(--text); 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: var(--primary); }
|
||||
:deep(.el-collapse) { border: none; }
|
||||
:deep(.el-collapse-item__header) {
|
||||
height: 42px; background: #f6f8fd;
|
||||
border: 1px solid var(--border); border-radius: 9px;
|
||||
padding: 0 14px; margin-bottom: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
:deep(.el-collapse-item__header.is-active) { border-color: rgba(59, 108, 255, .45); }
|
||||
:deep(.el-collapse-item__wrap) { border-bottom: none; }
|
||||
:deep(.el-collapse-item__content) { padding: 4px 6px 8px; }
|
||||
|
||||
/* ---------- 平台登录态:编号 + 发丝线 ---------- */
|
||||
.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: var(--primary); }
|
||||
.empty-tip {
|
||||
margin: 2px 0 8px; padding: 14px 0;
|
||||
text-align: center; font-size: 12.5px; color: var(--text-faint);
|
||||
border: 1px dashed var(--border-strong); border-radius: 9px;
|
||||
background: #fafbfe;
|
||||
}
|
||||
|
||||
/* ---------- 修改密码 ---------- */
|
||||
.pwd-form { padding-top: 2px; }
|
||||
.pwd-form :deep(.el-form-item__label) { color: var(--text-sub); font-weight: 500; }
|
||||
.pwd-submit { width: 100%; border-color: transparent; }
|
||||
</style>
|
||||
@@ -1,160 +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); }
|
||||
/* ============ 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; }
|
||||
+248
-248
@@ -1,249 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
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
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
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:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
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())
|
||||
# -*- coding: utf-8 -*-
|
||||
"""(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。
|
||||
|
||||
单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。
|
||||
若 WebView2 不可用则回退到系统浏览器打开。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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"
|
||||
|
||||
# 跨解释器单实例锁:launch.py 可能被 venv 与系统 Python 等不同入口重复启动,
|
||||
# 端口冲突时互相 kill/重建导致卡顿;命名互斥量保证全局只有一份实例。
|
||||
_MUTEX_HANDLE = None
|
||||
|
||||
|
||||
def _acquire_singleton(name: str = "Local\\37duWebhostSingleton") -> bool:
|
||||
"""获取 Windows 命名互斥量;失败(已存在)返回 False,调用方应退出。"""
|
||||
global _MUTEX_HANDLE
|
||||
if sys.platform != "win32":
|
||||
return True
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
import ctypes
|
||||
|
||||
k32 = ctypes.windll.kernel32
|
||||
k32.CreateMutexW.restype = wintypes.HANDLE
|
||||
k32.GetLastError.restype = wintypes.DWORD
|
||||
handle = k32.CreateMutexW(None, False, name)
|
||||
if not handle:
|
||||
return False
|
||||
if k32.GetLastError() == 183: # ERROR_ALREADY_EXISTS
|
||||
k32.CloseHandle(handle)
|
||||
return False
|
||||
_MUTEX_HANDLE = handle # 持有句柄,防止被 GC 释放导致锁失效
|
||||
return True
|
||||
except Exception:
|
||||
return True # 非关键路径,获取失败不阻塞启动
|
||||
|
||||
|
||||
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
|
||||
# frozen 模式无控制台:日志落盘 exe 同级 webhost.log(排查启动失败/运行异常的唯一窗口)
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
handlers=[logging.FileHandler(HERE / "webhost.log", encoding="utf-8")])
|
||||
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:
|
||||
# 单实例锁:已有实例(无论 venv/系统 Python 哪个入口)直接退出,避免端口互杀卡顿
|
||||
if not _acquire_singleton():
|
||||
if not _port_free():
|
||||
print("[webhost] 已有实例在运行,本次启动退出。")
|
||||
return 0
|
||||
# 端口空闲说明旧实例只剩窗口壳、服务已死:接管重启
|
||||
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
|
||||
@@ -5,7 +5,7 @@
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#define MyAppVersion "1.2.1"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.2.0
|
||||
1.2.1
|
||||
Reference in New Issue
Block a user