11 Commits
33 changed files with 1624 additions and 452 deletions

No files matched your search

+2
View File
@@ -15,6 +15,8 @@
## [Unreleased]
## [V3.3.5] — 2026-06-27
## [V3.3.4] — 2026-06-26
### Added
- 引入完整的版本管理体系:
+6
View File
@@ -110,6 +110,12 @@ from douyin.license.license_manager import require_online_license_or_exit
def ensure_adb_in_path() -> None:
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
adb_dir = os.path.dirname(bundled_adb)
os.environ["PATH"] = adb_dir + os.pathsep + os.environ.get("PATH", "")
os.environ.setdefault("ADB_EXECUTABLE", bundled_adb)
return
if shutil.which("adb"):
return
localapp = os.environ.get("LOCALAPPDATA") or ""
@@ -0,0 +1,43 @@
# 兑换链接安全复核 2026-06-24
## 结论
本次复核对象是闲鱼自动发货兑换链路:
- `POST /api/v1/redeem/external/create`
- `GET /redeem`
- `GET /redeem/{token}` 兼容旧链接
- `POST /api/v1/redeem/claim`
线上域名:`https://dy.absfan.cn`。
## 已验证
- 外部创建接口必须使用 `Authorization: Bearer <DYGJ_LICENSE_EXTERNAL_API_TOKEN>`。
- 外部创建接口只返回 `claim_url`,不返回真实 `DG-` 卡密。
- 新 `claim_url` 使用 `/redeem#token`,token 位于 URL fragment,不进入服务器请求路径和 uvicorn 访问日志。
- 兑换接口只允许同一 token 成功兑换一次;重复兑换返回 `409 already_redeemed`。
- 并发兑换已用 SQLite `BEGIN IMMEDIATE` 加写锁,测试确认只会生成一张卡。
- `/docs` 和 `/openapi.json` 线上返回 `404`。
- 未授权创建返回 `403`,坏参数返回 `400`。
- 兑换后的卡密可正常走 `/api/v1/activate`,授权文件可继续走 `/api/v1/verify_license`。
## 修复项
- 修复同一兑换 token 并发兑换可能生成多张卡的问题。
- 为公开兑换接口增加限流:`REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS`。
- 为外部创建接口鉴权失败增加独立限流:`EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS`。
- 新生成兑换链接改为 `/redeem#token`,降低访问日志泄露 token 的概率。
## 验证证据
- 本地回归:`artifacts/redeem_security_full_tests_20260624.log`,结果 `PASS`。
- 本地语法:`python -m py_compile license_server/core.py license_server/api.py douyin/license/license_manager.py`,结果 `PASS`。
- 线上黑盒:`health=200`、`docs=404`、`openapi=404`、`no_auth=403`、`create=200`、`claim_first=200`、`claim_second=409`、`activate=200`。
- 线上日志确认:`GET /redeem HTTP/1.1`,未记录 `/redeem/{token}`。
## 剩余建议
- `DYGJ_LICENSE_EXTERNAL_API_TOKEN` 应定期轮换,且只配置在自动发货服务器侧。
- 如果后续员工/多个渠道并行发货,建议改成每个渠道独立 token,并在数据库记录 `platform`、`external_order_id`、请求 IP 和 staff/source 标识。
- 如果订单量增大,建议在 1Panel/OpenResty 层再加 IP 级限流。
@@ -0,0 +1,165 @@
# 安全审计报告:服务器与反逆向
日期:2026-06-26
范围:`license_server/` 授权与更新服务、在线差量/全量更新链路、V3.3.4 发布包反逆向与分发内容。
## 总体结论
当前授权服务不是裸奔:管理员后台有登录限流、CSRF、会话 Cookie;客户端更新默认启用 HTTPS、manifest 签名和 SHA256 校验;V3.3.4 发布包通过了分发清单检查,核心逻辑已有 Cython `.pyd` 编译层。
但最值得优先处理的风险有两个:管理员 token 暴露后可直接发布任意 EXE 更新;更新安装包上传/下载缺少大文件资源控制。反逆向方面,现在属于“提高脚本级拆包成本”,还不是强对抗级保护。
## P1:必须优先处理
### 1. 管理员 token 本地副本过多,拿到 token 就等于拿到发布权
证据:
- 本机桌面存在多个 token 文件:`C:\Users\12742\Desktop\douyin_admin_token.txt`、`C:\Users\12742\Desktop\douyin_admin_token_open.txt`、`C:\Users\12742\Desktop\douyin_admin_token_可打开.txt`。
- 管理员鉴权使用单一 token:`license_server/api.py:101`、`license_server/api.py:118-135`。
- 发布更新接口在管理员鉴权后直接接受 EXE 并写入 manifest:`license_server/api.py:795-818`、`license_server/core.py:532-562`。
影响:
- 本机恶意软件、聊天软件临时目录泄露、误传文件,都可能让攻击者发布恶意更新。
- 因客户端会信任服务端签名的 manifest,服务器发布权比普通卡密权限高很多。
建议:
- 立刻轮换 `DYGJ_LICENSE_ADMIN_TOKEN`,删除桌面和聊天临时目录里的 token 明文副本。
- 管理后台改为“短期会话 + 二次确认发布 + 可选 TOTP/一次性发布口令”。
- 管理发布接口限制来源 IP,至少只允许固定办公 IP 或 VPN。
- 发布动作记录操作者、IP、文件 SHA256、版本号,并保留不可覆盖审计日志。
### 2. 更新包上传一次性读入内存,缺少大小上限和流式写入
证据:
- `license_server/api.py:809` 使用 `await installer.read()` 一次性读完整上传文件。
- `license_server/core.py:537` 接收 `bytes`,`license_server/core.py:550` 直接 `write_bytes(content)`。
- 当前正式安装包约 214 MB,已经是大对象。
影响:
- 管理 token 被盗或后台被滥用时,可以上传超大文件造成内存/磁盘 DoS。
- 即使没有被盗,误传错误文件也会把服务打满。
建议:
- 服务端增加最大上传大小,例如 300 MB 或 500 MB,超限立即拒绝。
- 改成分块读取、边写临时文件、边计算 SHA256,完成后再原子重命名。
- Nginx/Caddy/Cloudflare 层设置请求体大小限制和上传超时。
### 3. 更新下载接口直出大文件,缺少下载限速/CDN/Range 滥用防护
证据:
- `/api/v1/update/download/{filename}` 直接 `FileResponse` 返回安装包:`license_server/api.py:658-672`。
- 已验证下载端点支持 Range,正式包体积约 214 MB。
影响:
- 任意公网客户端都能拉取大文件,容易被刷带宽。
- Range/并发下载可以把授权服务和更新服务一起拖慢。
建议:
- 安装包放对象存储或 CDN,授权服务只签 manifest,不直接扛大文件流量。
- 给下载接口加 IP 限流、并发限制、带宽限制。
- 如果继续用 ASGI 直出文件,生产依赖必须锁定并定期更新 Starlette/FastAPI;Starlette 历史上出现过 `FileResponse` Range 资源耗尽类公告。
## P2:建议加固
### 4. 生产环境缺少强制 Host 白名单
证据:
- `_public_base_url()` 未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时会回退到 `request.base_url`:`license_server/api.py:245-249`。
- 当前代码没有看到 `TrustedHostMiddleware` 或等价 Host 白名单。
影响:
- 如果生产环境漏配 `DYGJ_LICENSE_PUBLIC_BASE_URL`,错误 Host 头可能影响兑换链接或更新 URL 生成。
建议:
- 生产强制配置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://dy.absfan.cn`。
- 增加 `TrustedHostMiddleware`,只允许 `dy.absfan.cn` 和必要内网域名。
### 5. Cookie secure 默认关闭,生产 HTTPS 容易误配置
证据:
- `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`:`license_server/api.py:472`。
- CSRF 和后台 session cookie 都依赖该状态设置 `secure`:`license_server/api.py:680-686`、`license_server/api.py:707-711`。
影响:
- HTTPS 生产环境如果忘记设置环境变量,后台 Cookie 不会带 Secure 标记。
建议:
- 生产默认改为 Secure,只有本地开发显式关闭。
- README 和部署脚本强制检查该环境变量。
### 6. 管理员 Basic/Bearer 兼容口仍保留,建议收窄
证据:
- `_admin_allowed()` 同时接受 session、Bearer 和 Basic:`license_server/api.py:122-135`。
影响:
- Header token 适合脚本,但也更容易进入命令历史、代理日志或调试日志。
- 增加后台鉴权路径,后续维护更难保证所有入口策略一致。
建议:
- 默认只保留网页登录 session;CLI 发布单独走短期一次性 token。
- 如果必须保留 Bearer,限制到内网/VPN,并要求 CSRF 或发布专用 nonce。
### 7. 更新执行链缺少安装包 Authenticode 发布者校验
证据:
- 客户端更新流程会验证 manifest 签名和 SHA256:`douyin/updater/force_update.py:347-378`。
- 通过后直接启动下载的 installer:`douyin/updater/force_update.py:380-381`。
影响:
- 当前信任根主要是服务端 manifest 私钥和后台发布权。
- 一旦服务器私钥或发布权泄露,客户端无法再用 Windows 发布者签名做第二道拦截。
建议:
- 给正式安装包做 Authenticode 代码签名。
- 客户端启动安装器前校验签名发布者或证书指纹。
### 8. 服务器依赖没有锁定精确版本
证据:
- `license_server/requirements.txt` 使用 `fastapi>=0.124.0`、`uvicorn[standard]>=0.38.0`、`cryptography>=41.0.0`。
- 当前本机运行版本:FastAPI `0.137.2`,Starlette `1.3.1`。
影响:
- 生产重装时可能拿到未经本项目验证的新版本,也可能因为旧环境没有升级而继续运行旧版本。
建议:
- 为服务器单独生成锁定文件,例如 `requirements-server.lock.txt`。
- 发布服务端时记录 `pip freeze` 和镜像 digest。
## P3:反逆向现状与后续增强
### 已有保护
- 构建脚本默认走 Cython staging,除非显式传 `-NoCythonForDevOnly` 或 `-NoObfuscateForDevOnly`:`packaging/pyinstaller/build_windows.ps1:4-6`、`packaging/pyinstaller/build_windows.ps1:54-61`。
- 默认编译核心包:`douyin/fudai`、`douyin/reservation`、`douyin/detection`、`douyin/stage`:`tools/cython_staging.py:16-21`。
- 发布包分发清单阻止项目源码、日志、调试图和多余文件混入:`tools/distribution_manifest.py:120-155`。
- V3.3.4 发布目录检查通过:`logs/security_dist_manifest_check_2026-06-26.log`。
- V3.3.4 发布目录未发现项目核心 `.py` 源码混入;核心路径下 `.pyd` 数量为 93。
- 发布目录未发现私钥、管理员 token、项目私密 pem;只看到第三方 CA bundle:`_internal/certifi/cacert.pem`。
### 仍然薄弱
- GUI 与 WebUI 代码按当前策略仍更多是普通 PyInstaller/PYZ 层,不能按强混淆理解。
- Python/Cython `.pyd` 可以被逆向分析,只是成本高于纯 `.py`。
- 客户端公钥是公开的,这是正确设计;但协议、接口、版本更新逻辑仍能被静态分析。
- 没有运行时完整性校验、调试器检测、虚拟机/注入检测或关键路径反篡改。
建议:
- 短期:正式包固定使用 Cython,不允许 `-NoCythonForDevOnly`;发布前自动跑 `distribution_manifest`。
- 中期:把授权校验、更新校验、核心策略判断也纳入 Cython 或商业混淆。
- 中期:增加运行时自校验,例如关键 `.pyd`/EXE 哈希校验和异常上报。
- 长期:核心逻辑尽量服务端化,客户端只保留必要执行逻辑;反逆向不能替代服务端风控。
## 已验证通过项
- 管理员登录有限流:`license_server/api.py:693-700`。
- 后台修改类表单有 CSRF 校验:`license_server/api.py:805-807`,创建/解绑/禁用也有同类校验。
- 授权激活/验证/兑换接口有限流:`license_server/api.py:486-512`、`license_server/api.py:561-588`。
- 服务端私钥没有内置到客户端;客户端只包含公钥:`douyin/license/public_key.py:1-9`。
- 发布包分发清单 PASS:`logs/security_dist_manifest_check_2026-06-26.log`。
## 参考来源
- GitHub Security Advisory:Starlette `FileResponse` Range 资源耗尽类历史公告,`GHSA-f96h-pmfr-66vw` / `CVE-2024-47874`。
- Starlette 官方文档:`TrustedHostMiddleware` 用于限制 Host header。
+34
View File
@@ -265,6 +265,40 @@ def get_run_cli_command() -> list[str]:
return [sys.executable, get_run_cli_path()]
def get_bundled_platform_tools_dir() -> str:
"""返回随包 Android platform-tools 目录。"""
return os.path.join(PROJECT_ROOT, "platform-tools")
def get_bundled_adb_path() -> str:
"""返回随包 adb 路径。"""
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
return os.path.join(get_bundled_platform_tools_dir(), exe_name)
def find_bundled_adb() -> Optional[str]:
"""若分发包内自带 adb,返回其绝对路径。"""
candidates = [get_bundled_adb_path()]
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
candidates.append(os.path.join(str(meipass), "platform-tools", exe_name))
for path in candidates:
if os.path.exists(path):
return os.path.abspath(path)
return None
def get_bundled_android_tools_dir() -> str:
"""返回随包 Android 辅助工具目录。"""
return os.path.join(PROJECT_ROOT, "android-tools")
def get_bundled_adbkeyboard_apk_path() -> str:
"""返回随包 ADBKeyboard APK 路径。"""
return os.path.join(get_bundled_android_tools_dir(), "ADBKeyboard.apk")
def ensure_dir(path: str) -> None:
"""确保目录存在,不存在则创建"""
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
+1 -1
View File
@@ -178,7 +178,7 @@ class underlying_operations:
)
@staticmethod
def _adb() -> str:
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
adb = _impl_adb_path()
# 始终加引号,避免路径带空格 / 版本混用
if adb.startswith('"') and adb.endswith('"'):
return adb
@@ -8,12 +8,18 @@ from __future__ import annotations
import os
from typing import List
from douyin.core import path_config
def _adb_path() -> str:
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
if adb.startswith('"') and adb.endswith('"'):
adb = adb[1:-1]
if adb == "adb":
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
return adb
@@ -3,6 +3,7 @@
from __future__ import annotations
import base64
import os
import shlex
import subprocess
import time as time_module
@@ -116,6 +117,20 @@ def ensure_adbkeyboard_ime(
return True, prev, prev
imes = self.list_imes(device_id)
if not self._pick_adbkeyboard_ime(imes):
apk_path = path_config.get_bundled_adbkeyboard_apk_path()
if os.path.exists(apk_path):
try:
subprocess.run(
[self._adb_path(), "-s", str(device_id), "install", "-r", apk_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=20.0,
check=False,
)
imes = self.list_imes(device_id)
except Exception:
pass
adb_ime = ""
pref = str(preferred_ime or "").strip()
+2 -2
View File
@@ -10,8 +10,8 @@
from typing import Optional
APP_NAME = "douyin_guaji"
APP_VERSION = "V3.3.3"
APP_BUILD_DATE = "2025-12-28"
APP_VERSION = "V3.3.5"
APP_BUILD_DATE = "2026-06-27"
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
@@ -32,10 +32,13 @@ def _scaled_point(analyser: Any, point: tuple[int, int]) -> tuple[int, int]:
def _fast_delay(analyser: Any, attr_name: str, default_seconds: float) -> None:
try:
seconds = float(getattr(analyser, attr_name, default_seconds) or default_seconds)
raw = getattr(analyser, attr_name, default_seconds)
if not isinstance(raw, (int, float, str)):
raw = default_seconds
seconds = float(raw or default_seconds)
except Exception:
seconds = default_seconds
seconds = max(0.0, min(seconds, 1.2))
seconds = max(0.0, min(seconds, 3.0))
try:
analyser.operation.delay(seconds)
except Exception:
@@ -74,7 +77,7 @@ def handle_reservation_prejoin_fansclub(
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_participate_wait_seconds", 0.6)
_fast_delay(analyser, "reservation_prejoin_fansclub_participate_wait_seconds", 1.2)
click_point = FANSCLUB_JOIN_CLICK
click_x, click_y = _scaled_point(analyser, click_point)
@@ -118,7 +121,7 @@ def handle_reservation_prejoin_fansclub(
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_confirm_wait_seconds", 0.8)
_fast_delay(analyser, "reservation_prejoin_fansclub_confirm_wait_seconds", 1.6)
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
@@ -33,6 +33,10 @@ _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
"发表",
"一键",
)
_DIRECT_ATTEND_FANSCLUB_TEXT_SNIPPETS = (
"粉丝团",
"关注主播",
)
# 错误处理工具占位(与原文件保持兼容降级)
try:
@@ -321,6 +325,33 @@ def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, An
return False, button_text, button_status
def _normalize_direct_button_text(text: str) -> str:
return "".join(ch for ch in str(text or "") if ch not in " \t\r\n·。.,,、::||-_")
def _looks_like_fansclub_button_text(button_text: str, button_status: str = "") -> bool:
joined = _normalize_direct_button_text(button_text) + _normalize_direct_button_text(
button_status
)
if not joined:
return False
if "粉丝团" in joined:
return True
if "关注主播" in joined and ("加入" in joined or "加人" in joined):
return True
if "需要加入粉丝" in joined:
return True
return False
def _reservation_may_need_fansclub_flow(item: Dict[str, Any]) -> bool:
button_text = str(item.get("button_text") or item.get("button_text_raw") or "")
button_status = str(item.get("button_status") or "")
if bool(item.get("prejoined_fansclub_before_reservation")):
return True
return _looks_like_fansclub_button_text(button_text, button_status)
def _ocr_current_attend_button_if_actionable(analyser: Any, item: Dict[str, Any]) -> tuple[bool, str, str]:
try:
from douyin.fudai.core.coords import get_fudai_detail_profile
@@ -817,6 +848,29 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
except Exception:
pass
if has_button and _reservation_may_need_fansclub_flow(first_reservation):
current_ok, current_button_text, current_button_status = (
_ocr_current_attend_button_if_actionable(analyser, first_reservation)
)
if current_button_text and _looks_like_fansclub_button_text(
current_button_text,
current_button_status,
):
try:
analyser._log_kv(
"预约",
"[预约] 预约直参检测到当前仍是粉丝团任务按钮,交给详情页正常流程",
button_info=button_info,
button_text=current_button_text[:80],
button_status=current_button_status,
ocr_actionable=bool(current_ok),
reason="direct_attend_fansclub_button_semantic_guard",
)
except Exception:
pass
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
if not has_button:
fallback_ok, fallback_button_text, fallback_button_status = (
_reservation_button_fallback_is_actionable(analyser, first_reservation)
+197 -93
View File
@@ -17,6 +17,8 @@ from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.dashboard_app import theme
from gui.dashboard_app.widgets import button, rounded_surface
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
@@ -35,6 +37,64 @@ from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
TITLE_FONT = ("Microsoft YaHei UI", 20, "bold")
SUBTITLE_FONT = ("Microsoft YaHei UI", 12)
LABEL_FONT = ("Microsoft YaHei UI", 13, "bold")
BODY_FONT = ("Microsoft YaHei UI", 13)
HELP_FONT = ("Microsoft YaHei UI", 12)
def _setup_wifi_dialog_styles(dialog: tk.Toplevel) -> None:
try:
style = ttk.Style(dialog)
style.configure("WifiADB.TCombobox", padding=(10, 8), font=BODY_FONT)
style.configure("WifiADB.TEntry", padding=(10, 8), font=BODY_FONT)
except Exception:
# Headless tests may provide a lightweight fake Toplevel without a tk handle.
return
def _card(parent: tk.Misc, title: str, subtitle: str = "") -> tuple[tk.Frame, tk.Frame]:
outer = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
head = tk.Frame(outer, bg=theme.SURFACE)
head.pack(fill="x", padx=22, pady=(18, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 15, "bold")).pack(side="left")
if subtitle:
tk.Label(head, text=subtitle, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(side="left", padx=(12, 0))
body = tk.Frame(outer, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=22, pady=(0, 20))
return outer, body
def _status_pill(parent: tk.Misc, text: str, *, ok: bool, active: bool = True) -> tk.Label:
if ok:
fg, bg = theme.GREEN, theme.GREEN_SOFT
elif active:
fg, bg = theme.AMBER, theme.AMBER_SOFT
else:
fg, bg = theme.MUTED, theme.SURFACE_ALT
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 12, "bold"), padx=12, pady=5)
def _field_group(parent: tk.Misc, title: str) -> tk.Frame:
box = tk.Frame(parent, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tk.Label(box, text=title, bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor="w", padx=14, pady=(12, 8))
return box
def _action_grid(parent: tk.Misc, actions: tuple[tuple[str, Callable[[], None], str, int], ...], *, columns: int = 3) -> None:
for col in range(columns):
parent.grid_columnconfigure(col, weight=1, uniform="action")
for idx, (text, command, kind, width) in enumerate(actions):
button(parent, text, command, kind=kind, width=width).grid(
row=idx // columns,
column=idx % columns,
sticky="ew",
padx=(0 if idx % columns == 0 else 10, 0),
pady=4,
)
def open_wifi_adb_dialog(
parent: tk.Misc,
*,
@@ -45,36 +105,70 @@ def open_wifi_adb_dialog(
"""打开WiFi ADB设置对话框"""
dialog = tk.Toplevel(parent)
dialog.title("WiFi ADB 设置")
dialog.geometry("500x450")
dialog.geometry("900x820")
dialog.configure(bg=theme.BG)
_setup_wifi_dialog_styles(dialog)
# 允许用户调整对话框大小,避免窗口内容被裁剪
dialog.resizable(True, True)
dialog.minsize(420, 320)
dialog.minsize(780, 640)
if not hasattr(dialog, "tk"):
ttk.Button(dialog, text="放大/恢复", command=lambda: None)
return
# 获取设备列表并分类
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
canvas = tk.Canvas(dialog, bg=theme.BG, highlightthickness=0, bd=0)
scroll = ttk.Scrollbar(dialog, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scroll.set)
canvas.pack(side="left", fill="both", expand=True)
scroll.pack(side="right", fill="y")
shell = tk.Frame(canvas, bg=theme.BG)
shell_window = canvas.create_window((0, 0), window=shell, anchor="nw")
shell.bind("<Configure>", lambda _e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(shell_window, width=e.width))
content = tk.Frame(shell, bg=theme.BG)
content.pack(fill="both", expand=True, padx=22, pady=18)
header = tk.Frame(content, bg=theme.BG)
header.pack(fill="x", pady=(0, 14))
title_box = tk.Frame(header, bg=theme.BG)
title_box.pack(side="left", fill="x", expand=True)
tk.Label(title_box, text="WiFi ADB 设置", bg=theme.BG, fg=theme.TEXT, font=TITLE_FONT).pack(anchor="w")
tk.Label(
title_box,
text="保留原有连接流程,优化设备选择与操作可读性",
bg=theme.BG,
fg=theme.MUTED,
font=SUBTITLE_FONT,
).pack(anchor="w", pady=(3, 0))
_status_pill(header, f"USB {len(usb_devices)}", ok=bool(usb_devices)).pack(side="right", padx=(8, 0))
_status_pill(header, f"WiFi {len(wifi_devices)}", ok=bool(wifi_devices), active=False).pack(side="right", padx=(8, 0))
# 创建设备选择区域
device_frame = ttk.LabelFrame(dialog, text="设备选择", padding=10)
device_frame.pack(fill=X, padx=10, pady=10)
# 使内部 grid 列随窗口宽度伸缩
device_frame.grid_columnconfigure(0, weight=3)
device_frame.grid_columnconfigure(1, weight=1)
device_card, device_frame = _card(content, "设备选择", "首次启用需要 USB,日常可直接选择 WiFi 设备")
device_card.pack(fill="x", pady=(0, 14))
device_frame.grid_columnconfigure(0, weight=1, uniform="device")
device_frame.grid_columnconfigure(1, weight=1, uniform="device")
# USB设备选择
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
row=0, column=0, sticky=W, pady=(0, 5)
)
usb_group = _field_group(device_frame, "USB设备(用于首次启用)")
usb_group.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
usb_combo = ttk.Combobox(
device_frame,
usb_group,
textvariable=usb_device_var,
values=usb_devices,
width=25,
width=34,
state="readonly" if not usb_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
usb_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示USB设备状态
usb_status_text = (
@@ -82,27 +176,23 @@ def open_wifi_adb_dialog(
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label = ttk.Label(
device_frame,
text=usb_status_text,
font=("Arial", 8),
foreground="red" if not usb_devices else "green",
)
usb_status_label.grid(row=2, column=0, sticky=W, pady=(0, 10))
usb_status_label = _status_pill(usb_group, usb_status_text, ok=bool(usb_devices))
usb_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# WiFi设备选择
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
wifi_group = _field_group(device_frame, "WiFi设备(已连接)")
wifi_group.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
wifi_combo = ttk.Combobox(
device_frame,
wifi_group,
textvariable=wifi_device_var,
values=wifi_devices,
width=25,
width=34,
state="readonly" if not wifi_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
wifi_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示WiFi设备状态
wifi_status_text = (
@@ -110,38 +200,32 @@ def open_wifi_adb_dialog(
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label = ttk.Label(
device_frame,
text=wifi_status_text,
font=("Arial", 8),
foreground="blue" if wifi_devices else "gray",
)
wifi_status_label.grid(row=2, column=1, sticky=W, pady=(0, 10))
wifi_status_label = _status_pill(wifi_group, wifi_status_text, ok=bool(wifi_devices), active=False)
wifi_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# IP地址输入区域
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
# 使 IP/端口 输入框随窗口宽度伸缩
ip_card, ip_frame = _card(content, "连接信息", "手动连接时填写设备 IP 与端口")
ip_card.pack(fill=X, pady=(0, 14))
ip_frame.grid_columnconfigure(0, weight=3)
ip_frame.grid_columnconfigure(1, weight=1)
ttk.Label(ip_frame, text="设备IP地址:").grid(
row=0, column=0, sticky=W, pady=(0, 5)
tk.Label(ip_frame, text="设备IP地址", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=0, sticky=W, pady=(0, 8)
)
ip_var = tk.StringVar()
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=25)
ip_entry.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=30, style="WifiADB.TEntry", font=BODY_FONT)
ip_entry.grid(row=1, column=0, padx=(0, 14), pady=(0, 2), sticky="we", ipady=7)
ttk.Label(ip_frame, text="端口(默认5555):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
tk.Label(ip_frame, text="端口(默认5555)", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=1, sticky=W, pady=(0, 8)
)
port_var = tk.StringVar(value="5555")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=25)
port_entry.grid(row=1, column=1, pady=(0, 10), sticky="we")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=16, style="WifiADB.TEntry", font=BODY_FONT)
port_entry.grid(row=1, column=1, pady=(0, 2), sticky="we", ipady=7)
# 按钮区域
button_frame = ttk.Frame(dialog)
button_frame.pack(fill=X, padx=10, pady=10)
action_card, button_frame = _card(content, "设备操作", "按当前连接方式选择对应动作")
action_card.pack(fill=X, pady=(0, 14))
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
is_maximized = False
@@ -350,63 +434,83 @@ def open_wifi_adb_dialog(
on_line("[WiFi ADB] 设备列表已刷新")
# USB设备操作按钮
usb_button_frame = ttk.Frame(button_frame)
usb_button_frame.pack(fill=X, pady=(0, 10))
button_frame.grid_columnconfigure(0, weight=1, uniform="actions")
button_frame.grid_columnconfigure(1, weight=1, uniform="actions")
button_frame.grid_columnconfigure(2, weight=1, uniform="actions")
usb_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
usb_button_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
ttk.Label(usb_button_frame, text="USB设备操作:").pack(anchor=W)
usb_buttons_frame = ttk.Frame(usb_button_frame)
usb_buttons_frame.pack(fill=X, pady=(5, 0))
tk.Label(usb_button_frame, text="USB首次启用", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
usb_buttons_frame = tk.Frame(usb_button_frame, bg=theme.SURFACE_ALT)
usb_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
ttk.Button(usb_buttons_frame, text="自动连接", command=auto_connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="启用WiFi ADB", command=enable_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="连接", command=connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(
usb_buttons_frame, text="刷新设备", command=refresh_device_lists
).pack(side=LEFT)
# 如果窗口无法通过边框调整,提供放大/恢复按钮作为备用
ttk.Button(usb_buttons_frame, text="放大/恢复", command=toggle_maximize).pack(
side=LEFT, padx=(8, 0)
_action_grid(
usb_buttons_frame,
(
("自动连接", auto_connect_wifi, "primary", 150),
("启用WiFi ADB", enable_wifi, "soft", 170),
),
columns=1,
)
# WiFi设备操作按钮
wifi_button_frame = ttk.Frame(button_frame)
wifi_button_frame.pack(fill=X, pady=(10, 0))
wifi_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
wifi_button_frame.grid(row=0, column=1, sticky="nsew", padx=(10, 10))
ttk.Label(wifi_button_frame, text="WiFi设备操作:").pack(anchor=W)
wifi_buttons_frame = ttk.Frame(wifi_button_frame)
wifi_buttons_frame.pack(fill=X, pady=(5, 0))
tk.Label(wifi_button_frame, text="WiFi连接操作", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
wifi_buttons_frame = tk.Frame(wifi_button_frame, bg=theme.SURFACE_ALT)
wifi_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
side=LEFT
)
ttk.Button(
_action_grid(
wifi_buttons_frame,
text="扫描局域网",
command=lambda: open_scan_dialog(
dialog, adb_exe, ip_var, on_line, refresh_device_lists
(
("连接", connect_wifi, "primary", 124),
("断开连接", disconnect_wifi, "soft", 132),
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists), "soft", 142),
),
).pack(side=LEFT, padx=(10, 0))
columns=1,
)
# 通用工具
tools_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tools_button_frame.grid(row=0, column=2, sticky="nsew", padx=(10, 0))
tk.Label(tools_button_frame, text="通用工具", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
tools_buttons_frame = tk.Frame(tools_button_frame, bg=theme.SURFACE_ALT)
tools_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
_action_grid(
tools_buttons_frame,
(
("刷新设备", refresh_device_lists, "soft", 132),
("放大/恢复", toggle_maximize, "soft", 132),
),
columns=1,
)
# 说明文本
info_text = """重要说明:
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
help_card, help_body = _card(content, "重要说明", "为什么首次必须接 USB")
help_card.pack(fill="both", expand=True)
help_body.grid_columnconfigure(0, weight=1)
help_body.grid_columnconfigure(1, weight=1)
使用方法:
1. 连接Android设备到电脑(USB)
2. 点击"刷新设备"确保设备被检测到
3. 选择USB设备,点击"自动连接"或手动操作
4. 等待设备重启后即可通过WiFi使用"""
notes = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
notes.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
steps = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
steps.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
info_label = ttk.Label(
dialog, text=info_text, justify=LEFT, font=("Arial", 9), wraplength=460
)
info_label.pack(pady=(10, 0), padx=20, anchor="w")
tk.Label(notes, text="连接规则", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"Android 首次启用 WiFi ADB 必须通过 USB 连接",
"流程:USB连接 -> 启用WiFi ADB -> 设备重启 -> WiFi连接",
"设置完成后,设备会出现在 WiFi 设备列表中",
"设备重启后 WiFi ADB 模式会保持,可继续通过 WiFi 使用",
):
tk.Label(notes, text=f"• {line}", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
tk.Label(steps, text="使用方法", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"1. 连接 Android 设备到电脑(USB)",
"2. 点击“刷新设备”确保设备被检测到",
"3. 选择 USB 设备,点击“自动连接”或手动操作",
"4. 等待设备重启后即可通过 WiFi 使用",
):
tk.Label(steps, text=line, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
+66 -30
View File
@@ -19,7 +19,7 @@ from . import theme
from .data import load_dashboard_data
from .page_context import PageContext
from .page_registry import PAGES
from .widgets import ScrollFrame, button, clear, nav_button, rounded_surface, status_pill
from .widgets import ScrollFrame, button, clear, field_shell, nav_button, rounded_surface, status_pill
class DashboardApp:
@@ -30,8 +30,8 @@ class DashboardApp:
except Exception:
pass
self.root.title("抖音自动化助手 - 数据看板")
self.root.geometry("1280x860")
self.root.minsize(1080, 720)
self.root.geometry("1360x900")
self.root.minsize(1160, 760)
theme.setup_styles(self.root)
disable_spinbox_mousewheel(self.root)
@@ -66,40 +66,76 @@ class DashboardApp:
shell = ttk.Frame(self.root, style="Dashboard.TFrame")
shell.pack(fill="both", expand=True)
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
top.pack(fill="x", padx=18, pady=(14, 8))
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
top.pack(fill="x", padx=20, pady=(12, 6))
brand = tk.Frame(top, bg=theme.SURFACE)
brand.pack(fill="x", padx=18, pady=(12, 5))
brand.pack(fill="x", padx=20, pady=(10, 4))
brand.grid_columnconfigure(1, weight=1)
mark = tk.Frame(brand, bg=theme.TEAL, width=34, height=34)
mark.pack(side="left", padx=(0, 12))
mark.grid(row=0, column=0, sticky="w", padx=(0, 12))
mark.pack_propagate(False)
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 15, "bold")).pack(expand=True)
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 17, "bold")).pack(expand=True)
title_box = tk.Frame(brand, bg=theme.SURFACE)
title_box.pack(side="left")
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 17, "bold")).pack(anchor="w")
title_box.grid(row=0, column=1, sticky="w")
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 20, "bold")).pack(anchor="w")
tk.Label(title_box, text="轻量数据看板入口", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w")
quick_state = tk.Frame(brand, bg=theme.SURFACE)
quick_state.grid(row=0, column=2, sticky="e")
tk.Label(
quick_state,
textvariable=self.status_var,
bg=theme.TEAL_SOFT,
fg=theme.TEAL_DARK,
font=("Microsoft YaHei UI", 13, "bold"),
padx=16,
pady=8,
).pack(side="right")
tk.Label(
quick_state,
text="当前状态",
bg=theme.SURFACE,
fg=theme.MUTED,
font=theme.FONT_SMALL,
).pack(side="right", padx=(0, 8))
tool_row = tk.Frame(top, bg=theme.SURFACE)
tool_row.pack(fill="x", padx=18, pady=(0, 12))
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left")
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=28, state="readonly")
self.device_combo.pack(side="left", padx=(4, 8))
button(tool_row, "刷新设备", self.refresh_devices, width=126).pack(side="left", padx=3)
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=128)
self.scan_button.pack(side="left", padx=4)
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=118).pack(side="left", padx=3)
ttk.Label(tool_row, text="Y偏移:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left", padx=(8, 3))
ttk.Entry(tool_row, textvariable=self.y_var, width=7).pack(side="left")
button(tool_row, "保存配置", self.save_config, width=126).pack(side="right", padx=3)
button(tool_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=132).pack(side="right", padx=3)
tool_row.pack(fill="x", padx=20, pady=(0, 10))
for col in (1, 6):
tool_row.grid_columnconfigure(col, weight=1)
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 13, "bold")).grid(row=0, column=0, sticky="w")
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=44, state="readonly")
self.device_combo.grid(row=0, column=1, sticky="ew", padx=(8, 18), pady=(0, 10))
button(tool_row, "刷新设备", self.refresh_devices, width=150).grid(row=0, column=2, sticky="e", padx=5, pady=(0, 10))
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=136)
self.scan_button.grid(row=0, column=3, sticky="e", padx=5, pady=(0, 10))
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=132).grid(row=0, column=4, sticky="e", padx=5, pady=(0, 10))
y_shell = field_shell(tool_row, "Y偏移")
y_shell.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(0, 2), padx=(0, 18))
y_entry = tk.Entry(
y_shell,
textvariable=self.y_var,
width=12,
bg=theme.SURFACE_ALT,
fg=theme.TEXT,
insertbackground=theme.TEAL,
relief="flat",
bd=0,
font=theme.FONT_UI,
)
y_entry.pack(fill="x", padx=11, pady=(0, 9))
actions = tk.Frame(tool_row, bg=theme.SURFACE)
actions.grid(row=1, column=2, columnspan=4, sticky="w")
button(actions, "保存配置", self.save_config, width=150).pack(side="left", padx=(0, 10))
button(actions, "截图+OCR", self.screenshot_ocr, kind="primary", width=164).pack(side="left", padx=(0, 10))
main = ttk.Frame(shell, style="Dashboard.TFrame")
main.pack(fill="both", expand=True, padx=18, pady=(6, 8))
main.pack(fill="both", expand=True, padx=20, pady=(6, 6))
main.grid_columnconfigure(1, weight=1)
main.grid_rowconfigure(0, weight=1)
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 16))
sidebar.configure(width=204)
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 18))
sidebar.configure(width=218)
sidebar.grid_propagate(False)
sidebar.pack_propagate(False)
nav_canvas = tk.Canvas(sidebar, bg=theme.SURFACE, highlightthickness=0, bd=0)
@@ -134,10 +170,10 @@ class DashboardApp:
("数据", ["运行日志", "行为日志", "实时状态", "截图预览", "统计信息", "预约队列", "高价值房间", "OCR结果", "中奖记录", "映射表"]),
("连接", ["WiFi ADB"]),
]:
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=14, pady=(13, 5))
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 10, "bold")).pack(anchor="w", padx=16, pady=(14, 6))
for name in names:
btn = nav_button(nav_inner, name, lambda n=name: self.show_page(n), active=name == self.current_page)
btn.pack(fill="x", padx=10, pady=1)
btn.pack(fill="x", padx=12, pady=2)
self.nav_buttons[name] = btn
_bind_nav_wheel(sidebar)
@@ -145,8 +181,8 @@ class DashboardApp:
self.content_scroll.grid(row=0, column=1, sticky="nsew")
self.content = self.content_scroll.inner
bottom = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
bottom.pack(fill="x", padx=18, pady=(4, 14))
bottom = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
bottom.pack(fill="x", padx=20, pady=(6, 16))
inner_bottom = tk.Frame(bottom, bg=theme.SURFACE)
inner_bottom.pack(fill="x", padx=14, pady=11)
button(inner_bottom, "开始运行", self.start_run, kind="primary", width=132).pack(side="left", padx=(0, 8))
+4 -3
View File
@@ -190,12 +190,13 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
]
for idx, item in enumerate(values):
tile = stat_tile(metrics, *item[:3], color=item[3], soft=item[4], compact=True)
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=4, pady=4)
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=6, pady=5)
body = tk.Frame(parent, bg=theme.BG)
body.pack(fill="both", expand=True)
body.pack(fill="both", expand=True, pady=(4, 0))
body.grid_columnconfigure(0, weight=3, minsize=540)
body.grid_columnconfigure(1, weight=2, minsize=380)
body.grid_rowconfigure(0, weight=1)
left = tk.Frame(body, bg=theme.BG)
right = tk.Frame(body, bg=theme.BG)
@@ -215,7 +216,7 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
include_created=False,
).pack(side="left")
preview_panel(right, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True)
preview_panel(right, data.current_screenshot_path, "实时截图", max_size=(430, 620)).pack(fill="both", expand=True)
def _statistics_values(data: DashboardData, ctx: PageContext) -> tuple[dict[str, Any], str, str]:
+16 -194
View File
@@ -47,56 +47,6 @@ def _last_log_time(stats: dict[str, Any]) -> str:
return "-"
def _group(parent: tk.Misc, title: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.pack(fill="both", expand=True)
head = tk.Frame(box, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(14, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
body = tk.Frame(box, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
return body
def _metric_row(parent: tk.Misc, label: str, value: object, hint: str = "", color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=4)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
tk.Label(row, text=str(value), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
if hint:
tk.Label(parent, text=hint, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
def _kpi_tile(parent: tk.Misc, title: str, value: object, hint: str, color: str, soft: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.configure(height=104)
box.pack_propagate(False)
accent = tk.Frame(box, bg=color, width=4)
accent.pack(side="left", fill="y")
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
return box
def _bar_row(parent: tk.Misc, label: str, value: int, total: int, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=5)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
tk.Label(row, text=f"{value} {_fmt_rate(value, total)}", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
track.pack(fill="x", pady=(0, 4))
pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total))
fill = tk.Frame(track, bg=color, height=8)
fill.place(relx=0, rely=0, relwidth=pct, relheight=1)
class StatsDashboardView:
def __init__(self, parent: tk.Misc) -> None:
self.root = tk.Frame(parent, bg=theme.BG)
@@ -112,35 +62,34 @@ class StatsDashboardView:
def _kpi_tile(self, parent: tk.Misc, key: str, title: str, color: str, soft: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.configure(height=104)
box.configure(height=112)
box.pack_propagate(False)
tk.Frame(box, bg=color, width=4).pack(side="left", fill="y")
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
inner.pack(fill="both", expand=True, padx=16, pady=12)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 22, "bold")).pack(anchor="w", pady=(5, 0))
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3).pack(anchor="w", pady=(7, 0))
return box
def _metric_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=4)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
row = tk.Frame(parent, bg=theme.SURFACE_ALT)
row.pack(fill="x", pady=5)
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_UI, anchor="w").pack(side="left", fill="x", expand=True, padx=(10, 6), pady=(8, 2))
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE_ALT, fg=color, font=("Microsoft YaHei UI", 16, "bold")).pack(side="right", padx=10, pady=(8, 2))
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 5), padx=2)
def _bar_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=5)
row.pack(fill="x", pady=(7, 3))
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
value_var = self._var(f"{key}.value")
tk.Label(row, textvariable=value_var, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
track = tk.Frame(parent, bg=theme.BG_ALT, height=10)
track.pack(fill="x", pady=(0, 4))
fill = tk.Frame(track, bg=color, height=8)
fill = tk.Frame(track, bg=color, height=10)
fill.place(relx=0, rely=0, relwidth=0, relheight=1)
self.bars[key] = (value_var, fill)
@@ -148,11 +97,11 @@ class StatsDashboardView:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.pack(fill="both", expand=True)
head = tk.Frame(box, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(14, 8))
head.pack(fill="x", padx=18, pady=(16, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
body = tk.Frame(box, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
body.pack(fill="both", expand=True, padx=18, pady=(0, 16))
return body
def _build(self) -> None:
@@ -168,7 +117,7 @@ class StatsDashboardView:
("total_run", "总运行", theme.BLUE, theme.BLUE_SOFT),
]
for idx, (key, title, color, soft) in enumerate(kpis):
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=6, pady=5)
panels = tk.Frame(self.root, bg=theme.BG)
panels.pack(fill="both", expand=True)
@@ -180,7 +129,7 @@ class StatsDashboardView:
slots = []
for idx in range(6):
slot = tk.Frame(panels, bg=theme.BG)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 10, 10 if idx % 2 == 0 else 0), pady=7)
slots.append(slot)
core = self._group(slots[0], "核心流程")
@@ -309,130 +258,3 @@ class StatsDashboardView:
self._set("last_countdown", last.get("countdown") or "-", "")
self._set("last_value", last.get("prize_value_yuan") or "-", "元")
self._set("last_people", f"{last.get('participants') or '-'} / {last.get('copies') or '-'}", "")
def _build_top_cards(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> None:
uptime = int(stats.get("uptime_seconds") or 0)
if uptime > 0:
current_run = _fmt_duration(uptime)
grid = flow_grid(parent, 4)
values = [
("运行状态", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}", theme.TEAL, theme.TEAL_SOFT),
("本次运行", current_run, "当前轮次", theme.BLUE, theme.BLUE_SOFT),
("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重口径", theme.GREEN, theme.GREEN_SOFT),
("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT),
("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT),
("打开详情", _counter(stats, "fudai_open_detail_unique"), "详情页", theme.BLUE, theme.BLUE_SOFT),
("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT),
("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT),
]
for idx, item in enumerate(values):
tile = _kpi_tile(grid, *item[:3], color=item[3], soft=item[4])
tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
def _build_core_flow(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "核心流程")
seen = _counter(stats, "fudai_seen_unique")
open_detail = _counter(stats, "fudai_open_detail_unique")
click = _counter(stats, "fudai_click_attend_unique")
attend = _counter(stats, "fudai_attend_ok_unique")
win = _counter(stats, "fudai_result_win")
no_win = _counter(stats, "fudai_result_no_win")
_bar_row(body, "识别福袋", seen, max(seen, 1), theme.TEAL)
_bar_row(body, "打开详情", open_detail, max(seen, 1), theme.BLUE)
_bar_row(body, "点击参与", click, max(open_detail, 1), theme.AMBER)
_bar_row(body, "参与成功", attend, max(click, attend, 1), theme.GREEN)
_metric_row(body, "中奖率", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}", theme.RED)
def _build_efficiency(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "效率与动作")
uptime = int(stats.get("uptime_seconds") or 0)
_metric_row(body, "识别效率", _per_hour(_counter(stats, "fudai_seen_unique"), uptime), "每小时识别福袋", theme.TEAL)
_metric_row(body, "参与效率", _per_hour(_counter(stats, "fudai_attend_ok_unique"), uptime), "每小时成功参与", theme.GREEN)
_metric_row(body, "切换频率", _per_hour(_counter(stats, "switch_room"), uptime), "每小时切换直播间", theme.AMBER)
ocr_attempt = _counter(stats, "ocr_attempt")
_metric_row(body, "OCR成功率", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}", theme.BLUE)
def _build_skip(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "过滤与跳过")
items = [
("价值过低", "fudai_skip_value_low", theme.AMBER),
("人数过少", "fudai_skip_participants_low", theme.BLUE),
("人数过多", "fudai_skip_participants_high", theme.BLUE),
("内容过滤", "fudai_skip_content", theme.TEAL),
("倒计时太短", "fudai_skip_countdown_short", theme.RED),
("倒计时太长", "fudai_skip_countdown_long", theme.AMBER),
("需要看播", "fudai_skip_watch_required", theme.RED),
]
total = sum(_counter(stats, key) for _, key, _ in items)
if total <= 0:
tk.Label(body, text="暂无跳过记录", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
return
for label, key, color in items:
value = _counter(stats, key)
if value > 0:
_bar_row(body, label, value, total, color)
def _build_reservation(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "预约与回访")
recorded = _counter(stats, "reservation_recorded")
back_success = _counter(stats, "reservation_back_success")
verify_ok = _counter(stats, "reservation_back_verify_ok")
verify_fail = _counter(stats, "reservation_back_verify_fail")
_metric_row(body, "记录预约", recorded, "累计写入预约队列", theme.TEAL)
_metric_row(body, "回退成功", back_success, f"成功率 {_fmt_rate(back_success, recorded)}", theme.GREEN)
_metric_row(body, "回退校验", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}", theme.BLUE)
_metric_row(body, "高价值预约", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高", theme.AMBER)
def _build_health(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "运行健康")
total = _counter(stats, "error_total")
detail_errors = _counter(stats, "error_read_detail") + _counter(stats, "fudai_open_error")
vision_errors = _counter(stats, "error_ocr") + _counter(stats, "error_screenshot") + _counter(stats, "error_detection")
_metric_row(body, "总错误数", total, "运行日志异常计数", theme.RED if total else theme.GREEN)
_metric_row(body, "识别/截图异常", vision_errors, "OCR、截图、识别", theme.RED if vision_errors else theme.GREEN)
_metric_row(body, "详情异常", detail_errors, "读详情或打开失败", theme.RED if detail_errors else theme.GREEN)
_metric_row(body, "慢操作", _counter(stats, "slow_operation"), ">5秒操作", theme.AMBER)
def _build_latest(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "最近福袋")
last = stats.get("fudai_last", {}) or {}
if not (last.get("content") or last.get("countdown")):
tk.Label(body, text="暂无最近福袋信息", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
return
_metric_row(body, "内容", last.get("content") or "-", color=theme.TEXT)
_metric_row(body, "倒计时", last.get("countdown") or "-", color=theme.BLUE)
_metric_row(body, "价值", f"{last.get('prize_value_yuan') or '-'}", "元", theme.AMBER)
participants = last.get("participants")
copies = last.get("copies")
_metric_row(body, "人数/份数", f"{participants or '-'} / {copies or '-'}", color=theme.TEAL)
def build_stats_dashboard(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> tk.Frame:
_build_top_cards(parent, stats, current_run, total_run)
grid = tk.Frame(parent, bg=theme.BG)
grid.pack(fill="both", expand=True)
for col in range(2):
grid.grid_columnconfigure(col, weight=1, uniform="stats")
for row in range(3):
grid.grid_rowconfigure(row, weight=1)
panels = [
_build_core_flow,
_build_efficiency,
_build_skip,
_build_reservation,
_build_health,
_build_latest,
]
for idx, builder in enumerate(panels):
slot = tk.Frame(grid, bg=theme.BG)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
builder(slot, stats)
return grid
+39 -39
View File
@@ -3,39 +3,39 @@ from __future__ import annotations
from tkinter import ttk
BG = "#f3f6f8"
BG_ALT = "#e8eef2"
BG = "#f6f8fb"
BG_ALT = "#edf2f7"
SURFACE = "#ffffff"
SURFACE_ALT = "#f7fafc"
SURFACE_HOVER = "#edf7f5"
BORDER = "#d9e3e8"
BORDER_DARK = "#b9c8d0"
TEXT = "#10201f"
MUTED = "#5d6f78"
SUBTLE = "#94a4ad"
SURFACE_ALT = "#f8fafc"
SURFACE_HOVER = "#eef7f6"
BORDER = "#dde7ee"
BORDER_DARK = "#b8c7d3"
TEXT = "#111827"
MUTED = "#5f7285"
SUBTLE = "#94a3b8"
TEAL = "#0f9488"
TEAL_DARK = "#087368"
TEAL_SOFT = "#e6f7f3"
AMBER = "#a76707"
AMBER_SOFT = "#fff4dd"
RED = "#c74454"
RED_SOFT = "#fff0f2"
TEAL_DARK = "#08756e"
TEAL_SOFT = "#e5f7f4"
AMBER = "#b26a00"
AMBER_SOFT = "#fff4dc"
RED = "#cf4057"
RED_SOFT = "#fff0f3"
GREEN = "#15805a"
GREEN_SOFT = "#e5f5ee"
BLUE = "#2e6fd8"
GREEN_SOFT = "#e7f7ef"
BLUE = "#2f6fda"
BLUE_SOFT = "#eaf2ff"
SHADOW = "#e7edf1"
SHADOW = "#d9e2ea"
RADIUS_SM = 8
RADIUS_MD = 12
RADIUS_LG = 16
RADIUS_SM = 12
RADIUS_MD = 18
RADIUS_LG = 24
FONT_UI = ("Microsoft YaHei UI", 12)
FONT_SMALL = ("Microsoft YaHei UI", 11)
FONT_READ = ("Microsoft YaHei UI", 13)
FONT_TITLE = ("Microsoft YaHei UI", 18, "bold")
FONT_H2 = ("Microsoft YaHei UI", 14, "bold")
FONT_MONO = ("Consolas", 13)
FONT_UI = ("Microsoft YaHei UI", 14)
FONT_SMALL = ("Microsoft YaHei UI", 12)
FONT_READ = ("Microsoft YaHei UI", 14)
FONT_TITLE = ("Microsoft YaHei UI", 21, "bold")
FONT_H2 = ("Microsoft YaHei UI", 16, "bold")
FONT_MONO = ("Consolas", 14)
def setup_styles(root) -> None:
@@ -51,23 +51,23 @@ def setup_styles(root) -> None:
style.configure("Toolbar.TFrame", background=SURFACE)
style.configure("Surface.TFrame", background=SURFACE)
style.configure("Alt.TFrame", background=SURFACE_ALT)
style.configure("Card.TFrame", background=SURFACE, borderwidth=1, relief="solid")
style.configure("Card.TFrame", background=SURFACE, borderwidth=0, relief="flat")
style.configure("Muted.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
style.configure("Title.TLabel", background=BG, foreground=TEXT, font=FONT_TITLE)
style.configure("H2.TLabel", background=SURFACE, foreground=TEXT, font=FONT_H2)
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 22, "bold"))
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 26, "bold"))
style.configure("Small.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
style.configure("Sidebar.TButton", padding=(12, 8), anchor="w")
style.configure("Primary.TButton", padding=(14, 8), foreground="#ffffff", background=TEAL, borderwidth=0)
style.configure("Sidebar.TButton", padding=(14, 10), anchor="w")
style.configure("Primary.TButton", padding=(16, 10), foreground="#ffffff", background=TEAL, borderwidth=0)
style.map("Primary.TButton", background=[("active", TEAL_DARK)])
style.configure("Danger.TButton", padding=(14, 8), foreground=RED)
style.configure("Soft.TButton", padding=(12, 7))
style.configure("Danger.TButton", padding=(16, 10), foreground=RED)
style.configure("Soft.TButton", padding=(14, 9))
style.configure("Dashboard.TNotebook", background=BG, borderwidth=0)
style.configure("Dashboard.TNotebook.Tab", padding=(16, 9), font=FONT_SMALL)
style.configure(
"Treeview",
font=("Microsoft YaHei UI", 13),
rowheight=38,
font=("Microsoft YaHei UI", 15),
rowheight=48,
background=SURFACE,
fieldbackground=SURFACE,
borderwidth=0,
@@ -76,8 +76,8 @@ def setup_styles(root) -> None:
style.map("Treeview", background=[("selected", TEAL_SOFT)], foreground=[("selected", TEXT)])
style.configure(
"Treeview.Heading",
font=("Microsoft YaHei UI", 12, "bold"),
background="#edf3f1",
font=("Microsoft YaHei UI", 14, "bold"),
background="#eef4f7",
foreground=TEXT,
relief="flat",
)
@@ -88,7 +88,7 @@ def setup_styles(root) -> None:
foreground=TEXT,
bordercolor=BORDER,
arrowcolor=MUTED,
padding=(8, 4),
padding=(10, 7),
)
style.map(
"TCombobox",
@@ -102,6 +102,6 @@ def setup_styles(root) -> None:
foreground=TEXT,
bordercolor=BORDER,
arrowcolor=MUTED,
padding=(6, 3),
padding=(9, 6),
)
style.map("TSpinbox", bordercolor=[("focus", TEAL), ("active", TEAL)])
+49 -37
View File
@@ -126,6 +126,17 @@ class RoundedSurface(tk.Frame):
width = max(2, self.winfo_width())
height = max(2, self.winfo_height())
self._canvas.delete("all")
if self._outline != self._fill:
rounded_rect(
self._canvas,
3,
4,
width - 2,
height - 1,
self._radius,
fill=theme.SHADOW,
outline=theme.SHADOW,
)
rounded_rect(
self._canvas,
1,
@@ -165,15 +176,15 @@ class RoundedButton(tk.Canvas):
self.kind = kind
self._state = "normal"
colors = {
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK),
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2"),
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8"),
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER),
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT),
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK, theme.TEAL),
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2", "#f2ccd1"),
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8", "#f0d6a0"),
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER, theme.BORDER),
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT, theme.SURFACE),
}
self.bg_color, self.fg_color, self.hover_color = colors.get(kind, colors["soft"])
w = width or max(98, len(self.text) * 14 + 34)
super().__init__(parent, width=w, height=38, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
self.bg_color, self.fg_color, self.hover_color, self.outline_color = colors.get(kind, colors["soft"])
w = width or max(118, len(self.text) * 16 + 42)
super().__init__(parent, width=w, height=46, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
self._draw(self.bg_color)
self.bind("<Button-1>", self._click)
self.bind("<Enter>", lambda _e: self._draw(self.hover_color))
@@ -181,10 +192,10 @@ class RoundedButton(tk.Canvas):
def _draw(self, fill: str) -> None:
self.delete("all")
outline = theme.TEAL if self.kind == "primary" else theme.BORDER
outline = self.outline_color
fg = self.fg_color if self._state != "disabled" else theme.SUBTLE
rounded_rect(self, 1, 1, int(self["width"]) - 2, int(self["height"]) - 2, theme.RADIUS_SM, fill=fill, outline=outline)
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 12, "bold") if self.kind == "primary" else theme.FONT_UI)
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 14, "bold") if self.kind == "primary" else theme.FONT_UI)
def _click(self, _event) -> None:
if self.command and self._state != "disabled":
@@ -211,7 +222,7 @@ class RoundedNavButton(tk.Canvas):
self.text = _with_icon(text, NAV_ICONS.get(text))
self.command = command
self.active = active
super().__init__(parent, height=34, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
super().__init__(parent, height=46, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
self.bind("<Configure>", lambda _e: self._draw())
self.bind("<Button-1>", lambda _e: self.command())
self.bind("<Enter>", lambda _e: self._draw(hover=True))
@@ -226,10 +237,10 @@ class RoundedNavButton(tk.Canvas):
width = max(1, self.winfo_width())
bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE)
fg = theme.TEAL_DARK if self.active else theme.TEXT
rounded_rect(self, 1, 2, width - 2, 32, theme.RADIUS_SM, fill=bg, outline=bg)
rounded_rect(self, 1, 4, width - 2, 42, theme.RADIUS_SM, fill=bg, outline=bg)
if self.active:
rounded_rect(self, 3, 8, 8, 26, 4, fill=theme.TEAL, outline=theme.TEAL)
self.create_text(18 if self.active else 13, 17, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 11, "bold") if self.active else theme.FONT_UI)
rounded_rect(self, 4, 12, 10, 34, 4, fill=theme.TEAL, outline=theme.TEAL)
self.create_text(22 if self.active else 15, 23, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 13, "bold") if self.active else theme.FONT_UI)
def clear(frame: tk.Misc) -> None:
@@ -246,19 +257,19 @@ def nav_button(parent, text: str, command: Callable[[], None], *, active: bool =
def pill(parent, text: str, *, fg: str = theme.TEAL, bg: str = theme.TEAL_SOFT) -> tk.Label:
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3)
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=4)
def status_pill(parent, text: str, *, color: str = theme.GREEN, bg: str = theme.GREEN_SOFT) -> tk.Label:
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=14, pady=5)
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=15, pady=6)
def card(parent, title: str | None = None, *, padding: int = 14) -> tk.Frame:
frame = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
if title:
head = tk.Frame(frame, bg=theme.SURFACE)
head.pack(fill="x", padx=padding + 2, pady=(padding, 7))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
head.pack(fill="x", padx=padding + 4, pady=(padding + 2, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 11))
ttk.Label(head, text=title, style="H2.TLabel").pack(side="left")
return frame
@@ -277,26 +288,25 @@ def metric(parent, title: str, value: object, hint: str = "", color: str = theme
def stat_tile(parent, title: str, value: object, hint: str, *, color: str, soft: str, compact: bool = False) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
if compact:
box.configure(height=72)
accent = tk.Frame(box, bg=color, width=4)
accent.pack(side="left", fill="y")
box.configure(height=104)
box.pack_propagate(False)
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True)
inner.pack(fill="both", expand=True, padx=18, pady=14)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(10, 2))
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 10, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 19, "bold")).pack(anchor="w", padx=16)
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=3).pack(anchor="w", padx=16, pady=(6, 10))
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 11, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 24 if compact else 25, "bold")).pack(anchor="w", pady=(5, 0))
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=12, pady=4).pack(anchor="w", pady=(7, 0))
return box
def section(parent, title: str, subtitle: str = "") -> tk.Frame:
row = tk.Frame(parent, bg=theme.BG)
row.pack(fill="x", pady=(2, 10))
row.pack(fill="x", pady=(2, 12))
ttk.Label(row, text=title, style="Title.TLabel").pack(side="left")
if subtitle:
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=12, pady=4).pack(side="left", padx=(12, 0))
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=14, pady=7).pack(side="left", padx=(14, 0))
return row
@@ -333,8 +343,8 @@ def text_panel(parent, title: str, lines: Iterable[str], height: int = 10) -> tk
def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tuple[tk.Frame, tk.Text]:
box = card(parent, title)
wrap = tk.Frame(box, bg=theme.SURFACE_ALT)
wrap.pack(fill="both", expand=True, padx=11, pady=(4, 11))
wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
wrap.pack(fill="both", expand=True, padx=13, pady=(4, 13))
wrap.grid_rowconfigure(0, weight=1)
wrap.grid_columnconfigure(0, weight=1)
text = tk.Text(
@@ -377,18 +387,20 @@ def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tup
def table_panel(parent, title: str, columns: Sequence[tuple[str, str, int]], rows: Sequence[dict], height: int = 8) -> tk.Frame:
box = card(parent, title)
table_wrap = tk.Frame(box, bg=theme.SURFACE)
table_wrap.pack(fill="both", expand=True, padx=14, pady=(4, 14))
table_wrap.pack(fill="both", expand=True, padx=16, pady=(4, 16))
table_wrap.grid_rowconfigure(0, weight=1)
table_wrap.grid_columnconfigure(0, weight=1)
tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height)
tree.tag_configure("odd", background=theme.SURFACE)
tree.tag_configure("even", background=theme.SURFACE_ALT)
ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview)
xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set)
for key, label, width in columns:
tree.heading(key, text=label)
tree.column(key, width=width, minwidth=min(width, 90), anchor="w", stretch=False)
for row in rows:
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
for idx, row in enumerate(rows):
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns], tags=("even" if idx % 2 else "odd",))
if not rows:
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
tree.grid(row=0, column=0, sticky="nsew")
@@ -417,7 +429,7 @@ def mini_table(parent, title: str, rows: Sequence[tuple[str, str, str]], *, colo
def field_shell(parent, label: str) -> tk.Frame:
row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM)
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=9, pady=(7, 1))
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=11, pady=(8, 2))
return row
@@ -493,8 +505,8 @@ def switch_row(parent, label: str, variable: tk.Variable | None = None, value: b
bd=0,
anchor="w",
justify="left",
font=theme.FONT_SMALL,
).pack(fill="x", padx=9, pady=6)
font=theme.FONT_UI,
).pack(fill="x", padx=10, pady=8)
return row
@@ -513,7 +525,7 @@ def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]
def preview_panel(parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560)) -> tk.Frame:
box = card(parent, title)
body = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
body.pack(fill="both", expand=True, padx=14, pady=(4, 14))
body.pack(fill="both", expand=True, padx=16, pady=(4, 16))
if image_path and image_path.exists():
try:
from PIL import Image, ImageTk
+19 -3
View File
@@ -11,14 +11,30 @@ import shutil
import subprocess
from typing import Optional
from douyin.core import path_config
def _normalize_adb_path(adb: str | None) -> str:
value = str(adb or "").strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
return value
def find_adb_executable() -> str:
"""返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。"""
"""返回可用的 adb 可执行文件路径。"""
env_adb = _normalize_adb_path(os.environ.get("ADB_EXECUTABLE"))
if env_adb and os.path.exists(env_adb):
return os.path.abspath(env_adb)
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
adb = shutil.which("adb")
if adb:
return adb
# 默认安装目录(我们之前下载的 platform-tools)
# 默认安装目录(本机开发/打包机常用 platform-tools 位置)
localapp = os.environ.get("LOCALAPPDATA") or ""
candidates = []
if localapp:
@@ -33,7 +49,7 @@ def find_adb_executable() -> str:
for p in candidates:
if os.path.exists(p):
return p
return os.path.abspath(p)
return ""
+44
View File
@@ -16,6 +16,9 @@ GET /api/v1/health
POST /api/v1/activate
POST /api/v1/verify
POST /api/v1/verify_license
POST /api/v1/redeem/external/create
POST /api/v1/redeem/claim
GET /redeem/{token}
GET /api/v1/update/manifest
GET /api/v1/update/download/{filename}
GET /admin
@@ -32,6 +35,47 @@ GET /admin
成功后返回 `license` 字段,客户端本地验签通过才会写入 `license.dat`。
## 闲鱼自动发货接入
自动发货系统不要直接拿真实卡密,只调用服务端生成一次性兑换链接。买家打开兑换链接后,服务端才生成正式 `DG-` 卡密。
服务端先配置外部接口 token:
```bash
export DYGJ_LICENSE_EXTERNAL_API_TOKEN="一段足够长的随机密钥"
```
外部自动发货系统请求:
```text
POST /api/v1/redeem/external/create
Authorization: Bearer 一段足够长的随机密钥
```
```json
{
"platform": "xianyu",
"external_order_id": "闲鱼订单号",
"customer": "买家备注",
"days": 30,
"max_devices": 1,
"expires_hours": 72
}
```
返回只包含 `claim_url`,不返回真实卡密:
```json
{
"ok": true,
"claim_url": "https://dy.absfan.cn/redeem/xxxx",
"token_hint": "xxxx...xxxx",
"expires_at": "2026-06-24T12:00:00Z"
}
```
把 `claim_url` 通过闲鱼聊天自动发给买家即可。这个设计可以避免员工、闲鱼自动发货项目或聊天日志直接接触真实卡密库存。
## Docker 部署
```bash
+175
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
import hmac
import hashlib
import json
import os
import secrets
import time
@@ -22,6 +23,8 @@ RATE_LIMIT_WINDOW_SECONDS = 60
RATE_LIMIT_MAX_REQUESTS = 30
ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS = 10
VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS = 600
EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS = 10
REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS = 60
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
ADMIN_SESSION_COOKIE = "dygj_admin_session"
ADMIN_SESSION_SECONDS = 12 * 60 * 60
@@ -41,6 +44,19 @@ class VerifyLicenseRequest(BaseModel):
license: dict[str, Any]
class CreateRedeemRequest(BaseModel):
days: int
max_devices: int = 1
customer: str = ""
platform: str = ""
external_order_id: str = ""
expires_hours: int = 72
class ClaimRedeemRequest(BaseModel):
token: str
def result_response(result: LicenseActionResult) -> JSONResponse:
body: dict[str, Any] = {
"ok": result.ok,
@@ -86,6 +102,10 @@ def admin_token_from_env() -> str:
return str(os.environ.get("DYGJ_LICENSE_ADMIN_TOKEN") or "").strip()
def external_api_token_from_env() -> str:
return str(os.environ.get("DYGJ_LICENSE_EXTERNAL_API_TOKEN") or "").strip()
def _env_bool(name: str, default: bool = False) -> bool:
raw = str(os.environ.get(name) or "").strip().lower()
if raw in {"1", "true", "yes", "y", "on"}:
@@ -119,6 +139,17 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
return hmac.compare_digest(supplied, expected)
def _bearer_token_allowed(request: Request, expected_token: str) -> bool:
expected = str(expected_token or "").strip()
if not expected:
return False
auth = str(request.headers.get("authorization") or "").strip()
if not auth.lower().startswith("bearer "):
return False
supplied = auth.split(" ", 1)[1].strip()
return hmac.compare_digest(supplied, expected)
def _session_hash(raw: str) -> str:
return hashlib.sha256(str(raw or "").encode("utf-8")).hexdigest()
@@ -424,6 +455,7 @@ def create_app(
*,
service: LicenseService | None = None,
admin_token: str | None = None,
external_api_token: str | None = None,
) -> FastAPI:
docs_enabled = _env_bool("DYGJ_LICENSE_ENABLE_DOCS", default=False)
app = FastAPI(
@@ -434,6 +466,9 @@ def create_app(
)
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.external_api_token = (
external_api_token if external_api_token is not None else external_api_token_from_env()
)
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=False)
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
app.state.rate_limit_buckets = {}
@@ -476,6 +511,146 @@ def create_app(
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
return result_response(get_service().verify_license_doc(req.license))
@app.post("/api/v1/redeem/external/create")
def redeem_external_create(request: Request, req: CreateRedeemRequest) -> JSONResponse:
if not _bearer_token_allowed(request, app.state.external_api_token):
if _rate_limited(
request,
"redeem_create_auth",
max_requests=EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS,
):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
return JSONResponse(
{"ok": False, "reason": "forbidden", "message": "外部接口 token 无效"},
status_code=403,
)
if _rate_limited(request, "redeem_create"):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
try:
token = get_service().create_redeem_token(
days=req.days,
max_devices=req.max_devices,
customer=req.customer,
platform=req.platform,
external_order_id=req.external_order_id,
expires_hours=req.expires_hours,
)
except ValueError as exc:
return JSONResponse(
{"ok": False, "reason": "invalid_params", "message": str(exc)},
status_code=400,
)
claim_path = f"/redeem#{token.token}"
claim_url = urljoin(_public_base_url(request) + "/", claim_path.lstrip("/"))
return JSONResponse(
{
"ok": True,
"reason": "ok",
"claim_url": claim_url,
"token_hint": token.token_hint,
"expires_at": token.expires_at.isoformat().replace("+00:00", "Z"),
}
)
@app.post("/api/v1/redeem/claim")
def redeem_claim(request: Request, req: ClaimRedeemRequest) -> JSONResponse:
if _rate_limited(
request,
"redeem_claim",
max_requests=REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS,
):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
result = get_service().claim_redeem_token(req.token)
if result.ok and result.card is not None:
return JSONResponse(
{
"ok": True,
"reason": "ok",
"message": result.message,
"card_key": result.card.code,
"days": result.card.days,
"max_devices": result.card.max_devices,
}
)
status = 409 if result.reason == "already_redeemed" else _status_for_reason(result.reason)
return JSONResponse(
{"ok": False, "reason": result.reason, "message": result.message},
status_code=status,
)
@app.get("/redeem")
def redeem_page() -> HTMLResponse:
return _redeem_page_html()
@app.get("/redeem/{token}")
def redeem_legacy_page(token: str) -> HTMLResponse:
script_token = json.dumps(str(token or ""))
return HTMLResponse(
f"""<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8" /><title>兑换授权</title></head>
<body><script>location.replace("/redeem#" + encodeURIComponent({script_token}));</script></body></html>"""
)
def _redeem_page_html() -> HTMLResponse:
html = f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>兑换授权</title>
<style>
body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: linear-gradient(135deg, #0f172a, #1e293b); color: #0f172a; }}
main {{ width: min(520px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(0, 0, 0, .35); }}
h1 {{ margin: 0 0 8px; font-size: 28px; }}
p {{ color: #64748b; line-height: 1.7; }}
code {{ display: block; word-break: break-all; background: #f1f5f9; padding: 12px; border-radius: 12px; }}
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
#result {{ margin-top: 14px; padding: 12px; border-radius: 12px; background: #f8fafc; min-height: 24px; }}
</style>
</head>
<body>
<main>
<h1>兑换软件授权</h1>
<p>点击兑换后会生成正式卡密。卡密只显示一次,请妥善保存。</p>
<code id="tokenPreview">正在读取兑换链接...</code>
<button id="claim">立即兑换</button>
<div id="result"></div>
</main>
<script>
const token = decodeURIComponent((location.hash || "").replace(/^#/, ""));
document.getElementById("tokenPreview").textContent = token ? token : "兑换链接缺少 token";
document.getElementById("claim").addEventListener("click", async () => {{
const result = document.getElementById("result");
if (!token) {{
result.textContent = "兑换链接缺少 token";
return;
}}
result.textContent = "正在兑换...";
const resp = await fetch("/api/v1/redeem/claim", {{
method: "POST",
headers: {{ "content-type": "application/json" }},
body: JSON.stringify({{ token }})
}});
const data = await resp.json();
if (data.ok) {{
result.innerHTML = "兑换成功,卡密:<code>" + data.card_key + "</code>";
}} else {{
result.textContent = data.message || data.reason || "兑换失败";
}}
}});
</script>
</body>
</html>"""
return HTMLResponse(html)
@app.get("/api/v1/update/manifest")
def update_manifest(request: Request) -> JSONResponse:
return JSONResponse(_signed_update_manifest(get_service(), request))
+189 -18
View File
@@ -19,6 +19,9 @@ MAX_CARD_DAYS = 3660
MAX_CREATE_COUNT = 100
MAX_CARD_DEVICES = 20
MAX_CUSTOMER_LENGTH = 120
MAX_REDEEM_EXPIRES_HOURS = 24 * 30
MAX_PLATFORM_LENGTH = 40
MAX_EXTERNAL_ORDER_LENGTH = 120
@dataclass(frozen=True)
@@ -29,6 +32,27 @@ class CreatedCard:
customer: str
@dataclass(frozen=True)
class CreatedRedeemToken:
token: str
token_hint: str
days: int
max_devices: int
customer: str
platform: str
external_order_id: str
expires_at: datetime
@dataclass(frozen=True)
class RedeemClaimResult:
ok: bool
reason: str
message: str
card: CreatedCard | None = None
expires_at: datetime | None = None
@dataclass(frozen=True)
class LicenseActionResult:
ok: bool
@@ -130,6 +154,14 @@ def generate_card_code() -> str:
return f"DG-{groups}"
def generate_redeem_token() -> str:
return secrets.token_urlsafe(32)
def hash_redeem_token(token: str) -> str:
return hashlib.sha256(str(token or "").strip().encode("utf-8")).hexdigest()
def sanitize_update_filename(filename: str, *, version: str = "") -> str:
raw = Path(str(filename or "")).name.strip()
if not raw.lower().endswith(".exe"):
@@ -181,6 +213,12 @@ class LicenseService:
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def _connect_immediate(self) -> sqlite3.Connection:
conn = self._connect()
conn.isolation_level = None
conn.execute("BEGIN IMMEDIATE")
return conn
def _init_db(self) -> None:
with self._connect() as conn:
conn.execute("PRAGMA journal_mode = WAL")
@@ -217,6 +255,23 @@ class LicenseService:
reason TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS redeem_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT NOT NULL UNIQUE,
token_hint TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
days INTEGER NOT NULL,
max_devices INTEGER NOT NULL DEFAULT 1,
customer TEXT NOT NULL DEFAULT '',
platform TEXT NOT NULL DEFAULT '',
external_order_id TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
redeemed_at TEXT,
license_id INTEGER,
FOREIGN KEY(license_id) REFERENCES license_keys(id)
);
"""
)
@@ -235,31 +290,115 @@ class LicenseService:
cards: list[CreatedCard] = []
with self._connect() as conn:
for _ in range(count):
code = generate_card_code()
card = CreatedCard(
code=code,
card, _license_id = self._insert_card(
conn,
days=days,
max_devices=max_devices,
customer=customer,
)
conn.execute(
"""
INSERT INTO license_keys
(code_hash, code_hint, status, days, max_devices, customer, created_at)
VALUES (?, ?, 'active', ?, ?, ?, ?)
""",
(
hash_card_code(code),
mask_card_code(code),
days,
max_devices,
card.customer,
iso_utc(utcnow()),
),
)
cards.append(card)
return cards
def create_redeem_token(
self,
*,
days: int,
max_devices: int = 1,
customer: str = "",
platform: str = "",
external_order_id: str = "",
expires_hours: int = 72,
) -> CreatedRedeemToken:
days = _bounded_int(days, name="days", minimum=1, maximum=MAX_CARD_DAYS)
max_devices = _bounded_int(max_devices, name="max_devices", minimum=1, maximum=MAX_CARD_DEVICES)
expires_hours = _bounded_int(
expires_hours,
name="expires_hours",
minimum=1,
maximum=MAX_REDEEM_EXPIRES_HOURS,
)
customer = str(customer or "").strip()[:MAX_CUSTOMER_LENGTH]
platform = str(platform or "").strip()[:MAX_PLATFORM_LENGTH]
external_order_id = str(external_order_id or "").strip()[:MAX_EXTERNAL_ORDER_LENGTH]
token = generate_redeem_token()
token_hint = mask_card_code(token)
expires_at = utcnow() + timedelta(hours=expires_hours)
with self._connect() as conn:
conn.execute(
"""
INSERT INTO redeem_tokens
(token_hash, token_hint, status, days, max_devices, customer, platform,
external_order_id, created_at, expires_at)
VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?)
""",
(
hash_redeem_token(token),
token_hint,
days,
max_devices,
customer,
platform,
external_order_id,
iso_utc(utcnow()),
iso_utc(expires_at),
),
)
self._audit(conn, "redeem_create", token, "", "ok")
return CreatedRedeemToken(
token=token,
token_hint=token_hint,
days=days,
max_devices=max_devices,
customer=customer,
platform=platform,
external_order_id=external_order_id,
expires_at=expires_at,
)
def claim_redeem_token(self, token: str) -> RedeemClaimResult:
raw_token = str(token or "").strip()
if not raw_token:
return RedeemClaimResult(False, "missing_token", "缺少兑换码")
with self._connect_immediate() as conn:
row = conn.execute(
"SELECT * FROM redeem_tokens WHERE token_hash = ?",
(hash_redeem_token(raw_token),),
).fetchone()
if row is None:
self._audit(conn, "redeem_claim", raw_token, "", "not_found")
return RedeemClaimResult(False, "not_found", "兑换链接不存在")
status = str(row["status"] or "").strip().lower()
if status == "redeemed":
self._audit(conn, "redeem_claim", raw_token, "", "already_redeemed")
return RedeemClaimResult(False, "already_redeemed", "兑换链接已使用")
if status != "pending":
self._audit(conn, "redeem_claim", raw_token, "", status or "inactive")
return RedeemClaimResult(False, status or "inactive", "兑换链接不可用")
expires_at = parse_utc(row["expires_at"])
if utcnow() > expires_at:
conn.execute(
"UPDATE redeem_tokens SET status = 'expired' WHERE id = ?",
(row["id"],),
)
self._audit(conn, "redeem_claim", raw_token, "", "expired")
return RedeemClaimResult(False, "expired", "兑换链接已过期", expires_at=expires_at)
card, license_id = self._insert_card(
conn,
days=int(row["days"]),
max_devices=int(row["max_devices"]),
customer=str(row["customer"] or ""),
)
conn.execute(
"""
UPDATE redeem_tokens
SET status = 'redeemed', redeemed_at = ?, license_id = ?
WHERE id = ?
""",
(iso_utc(utcnow()), license_id, row["id"]),
)
self._audit(conn, "redeem_claim", raw_token, "", "ok")
return RedeemClaimResult(True, "ok", "兑换成功", card=card, expires_at=expires_at)
def revoke(self, code: str) -> bool:
with self._connect() as conn:
cur = conn.execute(
@@ -605,6 +744,38 @@ class LicenseService:
(str(code_hash or "").strip().lower(),),
).fetchone()
def _insert_card(
self,
conn: sqlite3.Connection,
*,
days: int,
max_devices: int,
customer: str,
) -> tuple[CreatedCard, int]:
code = generate_card_code()
card = CreatedCard(
code=code,
days=int(days),
max_devices=int(max_devices),
customer=str(customer or "").strip()[:MAX_CUSTOMER_LENGTH],
)
cur = conn.execute(
"""
INSERT INTO license_keys
(code_hash, code_hint, status, days, max_devices, customer, created_at)
VALUES (?, ?, 'active', ?, ?, ?, ?)
""",
(
hash_card_code(code),
mask_card_code(code),
card.days,
card.max_devices,
card.customer,
iso_utc(utcnow()),
),
)
return card, int(cur.lastrowid)
def _invalid_card_reason(self, card: sqlite3.Row) -> str:
status = str(card["status"] or "").strip().lower()
if status == "revoked":
+10 -2
View File
@@ -27,6 +27,12 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_
该流程会生成 `build\cythonized-src\`,其中核心模块以 `.pyd` 形式存在。该目录是中间产物,不要直接分发;最终仍然只分发 `dist\DouyinGuaji-<version>\` 或 Inno 生成的安装包。
如果只是小更新、想复用 PyInstaller 缓存来加快打包,可以额外加 `-ReuseCache`。注意:改到 `douyin/fudai`、`douyin/reservation`、`douyin/detection` 或 `douyin/stage` 时,Cython 核心仍会重新编译;`-ReuseCache` 主要复用 PyInstaller 的分析/收集缓存。
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -ReuseCache
```
如果需要继续使用旧的 PyArmor 路线,可额外加 `-UsePyArmor`。注意:PyArmor 试用版会在混淆文件头部留下 trial 标记,正式分发前建议购买/配置正式授权后重新打包。若 PyArmor 授权不可用,旧路线会失败并停止。
仅本机开发调试需要生成明文包时,才显式加 `-NoCythonForDevOnly`:
@@ -63,6 +69,8 @@ dist\DouyinGuaji-<version>\
- `web_gui.exe`:Web GUI 服务入口
- `run_cli.exe`:后台运行入口,桌面 GUI / Web GUI 会调用它
- `assets/`、`webui/`、`config/`:运行所需资源
- `platform-tools/`:随包 ADB 运行组件,至少包含 `adb.exe`、`AdbWinApi.dll`、`AdbWinUsbApi.dll`
- `android-tools/`:随包手机侧辅助组件,当前包含 `ADBKeyboard.apk`
- `logs/`、`pic/`、`state/`:运行时输出目录
- `license.dat`:默认不随包分发;仅本地测试包需要时才使用 `-IncludeLicense` 显式复制
@@ -89,8 +97,8 @@ dist\installer\DouyinGuaji-3.3.3-Setup.exe
## 发给别人前检查
- 打包脚本会自动运行 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>`,防止源码、调试产物、个人配置和旧日志混入分发目录。
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
- 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`platform-tools/` 中的 ADB 白名单文件、`android-tools/ADBKeyboard.apk`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
- 正式包会自带 ADB,不要求目标电脑额外安装 Android platform-tools 或配置 PATH。程序在需要中文输入且设备未安装 ADBKeyboard 时,会尝试从随包 `android-tools/ADBKeyboard.apk` 自动安装到手机。新电脑仍需要在手机上开启开发者选项/USB 调试并允许本机 RSA 授权;部分品牌手机首次 USB 识别还需要 Windows 能正确安装对应 USB 驱动。
- 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。
- `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。
- 默认 Cython 编译后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。使用 `-NoCythonForDevOnly` 生成的明文包禁止分发。
+80 -20
View File
@@ -7,6 +7,8 @@ param(
[switch]$PackExe,
[switch]$PackExeForce,
[switch]$IncludeLicense,
[switch]$ReuseCache,
[string]$PlatformToolsDir = "",
[string]$UpxDir = ""
)
@@ -61,7 +63,6 @@ if ($UsePyArmor -and -not $NoObfuscateForDevOnly) {
}
$CommonArgs = @(
"--clean",
"--noconfirm",
"--distpath", $DistRoot,
"--workpath", (Join-Path $Root "build\pyinstaller"),
@@ -72,6 +73,9 @@ $CommonArgs = @(
"--hidden-import", "logging.handlers",
"--hidden-import", "cryptography.hazmat.primitives.serialization"
)
if (-not $ReuseCache) {
$CommonArgs = @("--clean") + $CommonArgs
}
$GuiArgs = @(
"--collect-submodules", "gui"
@@ -128,30 +132,19 @@ foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
Remove-Item -LiteralPath $srcDir -Recurse -Force
}
$RuntimeAssets = @(
"coupon.png",
"fav.png",
"fudai.png",
"fudai_icon_countdown_v20260618.png",
"fudai_icon_pending_v20260618.png",
"fudai_icon_purple_left_v20260618.png",
"fudai_icon_red_left_v20260618.png",
"fudai_task_status_dacheng_shape.png",
"like.png",
"x.png",
"xin.png"
)
$AssetsTarget = Join-Path $DistRoot "assets"
if (Test-Path $AssetsTarget) {
Remove-Item -LiteralPath $AssetsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $AssetsTarget | Out-Null
foreach ($name in $RuntimeAssets) {
$src = Join-Path $Root "assets\$name"
if (-not (Test-Path $src)) {
throw "Missing runtime asset: assets\$name"
}
Copy-Item -LiteralPath $src -Destination (Join-Path $AssetsTarget $name) -Force
$RuntimeAssetFiles = Get-ChildItem -LiteralPath (Join-Path $Root "assets") -File | Where-Object {
$_.Extension -ieq ".png"
}
if (-not $RuntimeAssetFiles) {
throw "Missing runtime assets: assets\*.png"
}
foreach ($asset in $RuntimeAssetFiles) {
Copy-Item -LiteralPath $asset.FullName -Destination (Join-Path $AssetsTarget $asset.Name) -Force
}
$WebuiTarget = Join-Path $DistRoot "webui"
@@ -182,6 +175,73 @@ foreach ($dir in @("logs", "pic", "state")) {
New-Item -ItemType File -Force (Join-Path $runtimeDir ".keep") | Out-Null
}
$PlatformToolCandidates = @()
if ($PlatformToolsDir) {
$PlatformToolCandidates += $PlatformToolsDir
}
foreach ($envName in @("ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT")) {
$envValue = [Environment]::GetEnvironmentVariable($envName)
if (-not $envValue) {
continue
}
if ($envName -eq "ANDROID_PLATFORM_TOOLS") {
$PlatformToolCandidates += $envValue
} else {
$PlatformToolCandidates += (Join-Path $envValue "platform-tools")
}
}
if ($env:LOCALAPPDATA) {
$PlatformToolCandidates += (Join-Path $env:LOCALAPPDATA "platform-tools")
}
$PlatformToolCandidates += (Join-Path $Root "platform-tools")
$ResolvedPlatformTools = ""
foreach ($candidate in $PlatformToolCandidates) {
if (-not $candidate) {
continue
}
$adbCandidate = Join-Path $candidate "adb.exe"
if (Test-Path $adbCandidate) {
$ResolvedPlatformTools = (Resolve-Path $candidate).Path
break
}
}
if (-not $ResolvedPlatformTools) {
throw "Missing Android platform-tools. Provide -PlatformToolsDir or install it under LOCALAPPDATA\platform-tools."
}
$PlatformToolsTarget = Join-Path $DistRoot "platform-tools"
if (Test-Path $PlatformToolsTarget) {
Remove-Item -LiteralPath $PlatformToolsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $PlatformToolsTarget | Out-Null
$PlatformToolFiles = @(
"adb.exe",
"AdbWinApi.dll",
"AdbWinUsbApi.dll",
"NOTICE.txt",
"source.properties"
)
foreach ($name in $PlatformToolFiles) {
$src = Join-Path $ResolvedPlatformTools $name
if ($name -in @("adb.exe", "AdbWinApi.dll", "AdbWinUsbApi.dll") -and -not (Test-Path $src)) {
throw "Missing required platform-tools file: $name"
}
if (Test-Path $src) {
Copy-Item -LiteralPath $src -Destination (Join-Path $PlatformToolsTarget $name) -Force
}
}
$AndroidToolsTarget = Join-Path $DistRoot "android-tools"
if (Test-Path $AndroidToolsTarget) {
Remove-Item -LiteralPath $AndroidToolsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $AndroidToolsTarget | Out-Null
$AdbKeyboardApk = Join-Path $Root "tools\adb\ADBKeyboard.apk"
if (-not (Test-Path $AdbKeyboardApk)) {
throw "Missing Android helper: tools\adb\ADBKeyboard.apk"
}
Copy-Item -LiteralPath $AdbKeyboardApk -Destination (Join-Path $AndroidToolsTarget "ADBKeyboard.apk") -Force
$licensePath = Join-Path $Root "license.dat"
if ($IncludeLicense -and (Test-Path $licensePath)) {
Copy-Item -LiteralPath $licensePath -Destination (Join-Path $DistRoot "license.dat") -Force
+1 -1
View File
@@ -3,7 +3,7 @@
# 这里的 version 由 tools/dev/bump_version.py 与 version.py 同步维护。
# 注意:为兼容 PEP 440,这里去掉 "V" 前缀,仅保留数字部分(如 V3.3.3 → 3.3.3)。
name = "douyin_guaji"
version = "3.3.3"
version = "3.3.5"
description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具"
readme = "README.md"
requires-python = ">=3.10"
+67 -2
View File
@@ -11,6 +11,7 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
"DouyinGuajiGUI.exe",
"_internal/python310.dll",
"assets/fudai_task_count_v2_one_task.png",
"assets/README.txt",
"README.md",
"douyin/core/douyin_fudai.py",
"artifacts/debug.png",
@@ -18,7 +19,6 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
"logs/unified.log",
"pic/debug_captures/a.png",
"license.dat",
"assets/README.txt",
"webui/debug.html",
"webui/js/README.md",
"DouyinGuajiGUI/_internal/base_library.zip",
@@ -37,7 +37,7 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
assert "license.dat" in blocked
assert "README.md" in blocked
assert "assets/README.txt" in blocked
assert "assets/fudai_task_count_v2_one_task.png" in blocked
assert "assets/fudai_task_count_v2_one_task.png" not in blocked
assert "webui/debug.html" in blocked
assert "webui/js/README.md" in blocked
assert "DouyinGuajiGUI/_internal/base_library.zip" in blocked
@@ -60,6 +60,10 @@ def test_distribution_manifest_blocks_project_native_binaries_outside_core_allow
"_internal/douyin/fudai/core/compiled.cp312-win_amd64.pyd",
"_internal/numpy/core/runtime.pyd",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -84,11 +88,19 @@ def test_distribution_manifest_allows_expected_runtime_shape():
"_internal/base_library.zip",
"_internal/python312.dll",
"assets/fudai.png",
"assets/desktop.png",
"assets/fudai_task_count_v2_one_task.png",
"assets/fudai_task_status_dacheng_shape.png",
"assets/fudai_icon_red_left_v20260618.png",
"webui/index.html",
"webui/css/base.css",
"webui/js/api_client.js",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"platform-tools/NOTICE.txt",
"platform-tools/source.properties",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -98,6 +110,22 @@ def test_distribution_manifest_allows_expected_runtime_shape():
assert find_distribution_issues(entries) == []
def test_distribution_manifest_blocks_unexpected_platform_tools_files():
from tools.distribution_manifest import find_forbidden_distribution_entries
entries = [
"platform-tools/adb.exe",
"platform-tools/fastboot.exe",
"platform-tools/mke2fs.conf",
]
blocked = find_forbidden_distribution_entries(entries)
assert "platform-tools/adb.exe" not in blocked
assert "platform-tools/fastboot.exe" in blocked
assert "platform-tools/mke2fs.conf" in blocked
def test_distribution_manifest_can_allow_license_for_local_test_package():
from tools.distribution_manifest import find_distribution_issues
@@ -109,6 +137,10 @@ def test_distribution_manifest_can_allow_license_for_local_test_package():
"_internal/python312.dll",
"assets/fudai.png",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -130,6 +162,10 @@ def test_distribution_manifest_requires_python_runtime_dll():
"_internal/base_library.zip",
"assets/fudai.png",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -141,6 +177,31 @@ def test_distribution_manifest_requires_python_runtime_dll():
assert "_internal/python*.dll" in issues
def test_distribution_manifest_requires_bundled_android_runtime():
from tools.distribution_manifest import find_distribution_issues
entries = [
"DouyinGuajiGUI.exe",
"web_gui.exe",
"run_cli.exe",
"_internal/base_library.zip",
"_internal/python312.dll",
"assets/fudai.png",
"webui/index.html",
"config/README.md",
"logs/.keep",
"pic/.keep",
"state/.keep",
]
issues = find_distribution_issues(entries)
assert "platform-tools/adb.exe" in issues
assert "platform-tools/AdbWinApi.dll" in issues
assert "platform-tools/AdbWinUsbApi.dll" in issues
assert "android-tools/ADBKeyboard.apk" in issues
def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
dist = tmp_path / "dist"
for rel in [
@@ -154,6 +215,10 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
"webui/css/base.css",
"webui/js/api_client.js",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
+8
View File
@@ -167,3 +167,11 @@ class TestReservationPrejoinFansclub:
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
assert delay_args == [0.2, 0.3]
def test_fast_prejoin_default_delays_wait_for_join_page_and_result(self):
a = _mk_analyser(auto_join_fansclub=True)
handle_reservation_prejoin_fansclub(a, "加入直播粉丝团并关注主播")
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
assert delay_args == [1.2, 1.6]
+1 -1
View File
@@ -176,7 +176,7 @@ class TestFudaiDetailOcrGuiConfig:
vars_ = build_config_vars({})
assert vars_["fudai_detail_regions_legacy_content_x1_var"].get() == 389
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1410
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1368
assert vars_["fudai_detail_regions_v2_0_one_task_info_line_x1_var"].get() == 430
assert vars_["pixel_regions_fudai_task_status_x1_var"].get() == 820
assert vars_["pixel_regions_live_room_icon_bbox_x1_var"].get() == 999
+137
View File
@@ -373,3 +373,140 @@ def test_api_rate_limits_repeated_failed_activation(tmp_path, monkeypatch):
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
def test_external_redeem_create_requires_bearer_token(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
resp = client.post(
"/api/v1/redeem/external/create",
json={
"platform": "xianyu",
"external_order_id": "ORDER-1",
"customer": "buyer-a",
"days": 30,
"max_devices": 1,
},
)
assert resp.status_code == 403
assert resp.json()["reason"] == "forbidden"
def test_external_redeem_create_returns_claim_url_without_card_key(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
resp = client.post(
"/api/v1/redeem/external/create",
headers={"authorization": "Bearer external-secret"},
json={
"platform": "xianyu",
"external_order_id": "ORDER-1",
"customer": "buyer-a",
"days": 30,
"max_devices": 1,
},
)
body = resp.json()
assert resp.status_code == 200
assert body["ok"] is True
assert body["claim_url"].startswith("https://dy.absfan.cn/redeem#")
assert "card_key" not in body
assert service.stats()["total"] == 0
def test_redeem_claim_exchanges_token_for_card_once(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=30,
max_devices=1,
customer="buyer-a",
platform="xianyu",
external_order_id="ORDER-1",
)
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
first = client.post("/api/v1/redeem/claim", json={"token": token.token})
second = client.post("/api/v1/redeem/claim", json={"token": token.token})
assert first.status_code == 200
assert first.json()["ok"] is True
assert first.json()["card_key"].startswith("DG-")
assert second.status_code == 409
assert second.json()["reason"] == "already_redeemed"
def test_redeem_claim_is_rate_limited(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS", 2)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
for _ in range(2):
assert client.post("/api/v1/redeem/claim", json={"token": "missing"}).status_code == 404
limited = client.post("/api/v1/redeem/claim", json={"token": "missing"})
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
def test_external_redeem_auth_failures_are_rate_limited(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS", 2)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
for _ in range(2):
assert client.post(
"/api/v1/redeem/external/create",
json={"days": 1},
).status_code == 403
limited = client.post(
"/api/v1/redeem/external/create",
json={"days": 1},
)
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
+86
View File
@@ -100,3 +100,89 @@ def test_license_server_verify_license_doc_requires_card_hash(tmp_path):
assert result.ok is False
assert result.reason == "invalid_signature"
def test_license_server_redeem_token_creates_card_only_when_claimed(tmp_path):
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=14,
max_devices=2,
customer="xianyu-order-1",
platform="xianyu",
external_order_id="ORDER-1",
)
before = service.stats()
claimed = service.claim_redeem_token(token.token)
second = service.claim_redeem_token(token.token)
assert before["total"] == 0
assert claimed.ok is True
assert claimed.card is not None
assert claimed.card.code.startswith("DG-")
assert claimed.card.days == 14
assert claimed.card.max_devices == 2
assert claimed.card.customer == "xianyu-order-1"
assert second.ok is False
assert second.reason == "already_redeemed"
assert service.stats()["total"] == 1
def test_license_server_redeem_token_rejects_expired_token(tmp_path, monkeypatch):
from datetime import timedelta
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
start = core.utcnow()
monkeypatch.setattr(core, "utcnow", lambda: start)
token = service.create_redeem_token(
days=7,
max_devices=1,
customer="expired-order",
platform="xianyu",
external_order_id="ORDER-EXPIRED",
expires_hours=1,
)
monkeypatch.setattr(core, "utcnow", lambda: start + timedelta(hours=2))
result = service.claim_redeem_token(token.token)
assert result.ok is False
assert result.reason == "expired"
assert service.stats()["total"] == 0
def test_license_server_redeem_token_is_single_use_under_concurrency(tmp_path, monkeypatch):
from concurrent.futures import ThreadPoolExecutor
import time
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=7,
max_devices=1,
customer="race-order",
platform="xianyu",
external_order_id="ORDER-RACE",
)
original_insert_card = service._insert_card
def slow_insert(*args, **kwargs):
time.sleep(0.2)
return original_insert_card(*args, **kwargs)
monkeypatch.setattr(service, "_insert_card", slow_insert)
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _idx: service.claim_redeem_token(token.token), range(2)))
assert sorted(result.reason for result in results) == ["already_redeemed", "ok"]
assert sum(1 for result in results if result.ok) == 1
assert service.stats()["total"] == 1
+9 -2
View File
@@ -259,11 +259,18 @@ def test_windows_packaging_script_protects_core_modules_by_default():
assert "[switch]$IncludeLicense" in script
assert '"--add-data", "assets;assets"' not in script
assert '"--add-data", "webui;webui"' not in script
assert "$RuntimeAssets = @(" in script
assert 'assets\$name' in script
assert "$RuntimeAssetFiles = Get-ChildItem" in script
assert 'assets\*.png' in script
assert "tools\\adb\\ADBKeyboard.apk" in script
assert "$IncludeLicense -and" in script
assert '$ManifestArgs += "--allow-license"' in script
assert "Get-ChildItem -LiteralPath $srcInternal -Force | Copy-Item" in script
assert "Join-Path $BuildSourceRoot \"gui\\gui_dashboard_app_entry.py\"" in script
assert "Join-Path $BuildSourceRoot \"gui\\web_gui_entry.py\"" in script
assert "Join-Path $BuildSourceRoot \"bin\\run_cli_entry.py\"" in script
assert '[string]$PlatformToolsDir = ""' in script
assert '"ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT"' in script
assert '$PlatformToolFiles = @(' in script
assert '"adb.exe"' in script
assert '"AdbWinApi.dll"' in script
assert '"AdbWinUsbApi.dll"' in script
+5
View File
@@ -119,6 +119,11 @@ class TestSpecificPaths:
os.path.join(PROJECT_ROOT, "run_cli.exe")
]
def test_bundled_adb_path_uses_project_root(self):
assert path_config.get_bundled_adb_path() == os.path.join(
PROJECT_ROOT, "platform-tools", "adb.exe"
)
# ============================================================
# 路径间不应互相重复
+56
View File
@@ -27,6 +27,10 @@ class TestAdbPath:
def test_default_returns_adb(self, monkeypatch):
# 默认走 ADB_EXECUTABLE 环境变量;如果未设,应返回 'adb'
monkeypatch.delenv("ADB_EXECUTABLE", raising=False)
monkeypatch.setattr(
"douyin.core.underlying_operations_pkg.adb_helpers.path_config.find_bundled_adb",
lambda: None,
)
assert _adb_path() == "adb"
def test_env_override(self, monkeypatch):
@@ -38,6 +42,14 @@ class TestAdbPath:
# 包了引号的应当去引号返回 raw 路径
assert _adb_path() == "C:\\Program Files\\adb.exe"
def test_uses_bundled_adb_when_env_missing(self, monkeypatch):
monkeypatch.delenv("ADB_EXECUTABLE", raising=False)
monkeypatch.setattr(
"douyin.core.underlying_operations_pkg.adb_helpers.path_config.find_bundled_adb",
lambda: r"C:\App\platform-tools\adb.exe",
)
assert _adb_path() == r"C:\App\platform-tools\adb.exe"
class TestAdbArgs:
def test_basic(self):
@@ -74,6 +86,50 @@ class TestPickAdbKeyboardIme:
assert result in ("", None)
def test_ensure_adbkeyboard_installs_bundled_apk_when_missing(monkeypatch, tmp_path):
from douyin.core.underlying_operations_pkg import text_input
apk = tmp_path / "ADBKeyboard.apk"
apk.write_bytes(b"apk")
calls = []
class Ops:
def __init__(self):
self.list_count = 0
def get_current_ime(self, _device_id):
return "com.example/.Ime"
def list_imes(self, _device_id):
self.list_count += 1
if self.list_count == 1:
return ["com.example/.Ime"]
return ["com.android.adbkeyboard/.AdbIME"]
def _pick_adbkeyboard_ime(self, imes):
return _pick_adbkeyboard_ime(imes)
def _adb_path(self):
return "adb"
def try_set_ime(self, _device_id, ime_id):
return ime_id == "com.android.adbkeyboard/.AdbIME"
def fake_run(cmd, **_kwargs):
calls.append(cmd)
return type("Proc", (), {"returncode": 0})()
monkeypatch.setattr(text_input.path_config, "get_bundled_adbkeyboard_apk_path", lambda: str(apk))
monkeypatch.setattr(text_input.subprocess, "run", fake_run)
ok, prev, ime = text_input.ensure_adbkeyboard_ime(Ops(), "device1")
assert ok is True
assert prev == "com.example/.Ime"
assert ime == "com.android.adbkeyboard/.AdbIME"
assert calls and calls[0][-2:] == ["-r", str(apk)]
# ============================================================
# bounds.py — _parse_bounds
# ============================================================
+31
View File
@@ -46,15 +46,22 @@ FORBIDDEN_EXACT = {
ALLOWED_ASSET_FILES = {
"assets/coupon.png",
"assets/desktop.png",
"assets/fav.png",
"assets/fudai.png",
"assets/fudai_icon_countdown_v20260618.png",
"assets/fudai_icon_pending_v20260618.png",
"assets/fudai_icon_purple_left_v20260618.png",
"assets/fudai_icon_red_left_v20260618.png",
"assets/fudai_task_count_digit_1.png",
"assets/fudai_task_count_digit_2.png",
"assets/fudai_task_count_v2_one_task.png",
"assets/fudai_task_count_v2_two_task.png",
"assets/fudai_task_status_dacheng_shape.png",
"assets/like.png",
"assets/quan.png",
"assets/x.png",
"assets/xiangqing.png",
"assets/xin.png",
}
@@ -76,6 +83,18 @@ ALLOWED_WEBUI_SUFFIXES = {
".js",
}
ALLOWED_PLATFORM_TOOLS_FILES = {
"platform-tools/adb.exe",
"platform-tools/adbwinapi.dll",
"platform-tools/adbwinusbapi.dll",
"platform-tools/notice.txt",
"platform-tools/source.properties",
}
ALLOWED_ANDROID_TOOLS_FILES = {
"android-tools/adbkeyboard.apk",
}
FORBIDDEN_SUFFIXES = (
".py",
".pyc",
@@ -150,6 +169,10 @@ def is_forbidden_distribution_entry(entry: str, *, allow_license: bool = False)
if not any(lower.startswith(prefix) for prefix in ALLOWED_WEBUI_DIRS):
return True
return Path(lower).suffix not in ALLOWED_WEBUI_SUFFIXES
if lower.startswith("platform-tools/"):
return lower not in ALLOWED_PLATFORM_TOOLS_FILES
if lower.startswith("android-tools/"):
return lower not in ALLOWED_ANDROID_TOOLS_FILES
if any(lower.startswith(prefix.lower()) for prefix in FORBIDDEN_PREFIXES):
return True
return any(lower.endswith(suffix) for suffix in FORBIDDEN_SUFFIXES)
@@ -173,6 +196,14 @@ def find_missing_required_runtime_entries(entries: list[str]) -> list[str]:
for required in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
if required.lower() not in normalized:
missing.append(required)
for required in (
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
):
if required.lower() not in normalized:
missing.append(required)
if not any(entry.startswith("_internal/") and entry.startswith("_internal/python") and entry.endswith(".dll") for entry in normalized):
missing.append("_internal/python*.dll")
if "_internal/base_library.zip" not in normalized: