Compare commits
72
Commits
d81e00ddbc
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1202dffa32 | ||
|
|
e24b0bdd1e | ||
|
|
1c686a6595 | ||
|
|
9c8a037c4e | ||
|
|
94e0c6432f | ||
|
|
51c1c2da39 | ||
|
|
60306dd4e0 | ||
|
|
329b7756f4 | ||
|
|
16019ee649 | ||
|
|
60332db82b | ||
|
|
c2cbee9592 | ||
|
|
ab37165baf | ||
|
|
c0cb274728 | ||
|
|
a870e0cbf9 | ||
|
|
13aa60c06a | ||
|
|
f010853b97 | ||
|
|
ee3424cd9e | ||
|
|
7c6189fd5e | ||
|
|
7745f9a57f | ||
|
|
f5a77867ee | ||
|
|
407c3b37c2 | ||
|
|
e315aaf80b | ||
|
|
7234bf0cac | ||
|
|
39996405d5 | ||
|
|
383c947a03 | ||
|
|
63c726ddea | ||
|
|
f257c4e3fc | ||
|
|
ecbd07cea0 | ||
|
|
5aeeef4aee | ||
|
|
9a75b9b481 | ||
|
|
872d114a0f | ||
|
|
a7d6bc87b6 | ||
|
|
cf2b71f831 | ||
|
|
3ab15e69f9 | ||
|
|
8e8a14cf69 | ||
|
|
164f76658c | ||
|
|
ffebc8d0dc | ||
|
|
61d3ad5d83 | ||
|
|
df46d723c3 | ||
|
|
e41796d43a | ||
|
|
2b12ddbec3 | ||
|
|
d0166d27d3 | ||
|
|
9062ee7204 | ||
|
|
008d7f82b3 | ||
|
|
4dea1328ec | ||
|
|
dc34b7484b | ||
|
|
ed0aca5f28 | ||
|
|
33c6f7a54f | ||
|
|
91a3aa5abf | ||
|
|
a2a899bb9f | ||
|
|
3ace80dcca | ||
|
|
ab664e4da8 | ||
|
|
7086ab1d6e | ||
|
|
5ebca337eb | ||
|
|
7890320ff7 | ||
|
|
18908aeff7 | ||
|
|
bd762f6be6 | ||
|
|
1bef130e51 | ||
|
|
5d3d58a2f9 | ||
|
|
25df550304 | ||
|
|
4af2adc4d6 | ||
|
|
77413fa7d1 | ||
|
|
aeeabd8ba2 | ||
|
|
25876bd25a | ||
|
|
a449b7634c | ||
|
|
0efdc83d0b | ||
|
|
920c51d460 | ||
|
|
ba9ac4cb0e | ||
|
|
f95832579a | ||
|
|
5c7d341d9b | ||
|
|
ba2e159cad | ||
|
|
fe53debeb1 |
No files matched your search
@@ -0,0 +1,87 @@
|
||||
name: Windows Package CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "bin/**"
|
||||
- "douyin/**"
|
||||
- "gui/**"
|
||||
- "operations/**"
|
||||
- "packaging/**"
|
||||
- "tools/**"
|
||||
- "tests/**"
|
||||
- "webui/**"
|
||||
- "pyproject.toml"
|
||||
- "requirements.txt"
|
||||
- ".github/workflows/windows-package-ci.yml"
|
||||
|
||||
jobs:
|
||||
package-fresh-install:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "pip"
|
||||
|
||||
- name: Install Inno Setup
|
||||
shell: powershell
|
||||
run: choco install innosetup --yes --no-progress
|
||||
|
||||
- name: Install Python dependencies
|
||||
shell: powershell
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install pyinstaller cython setuptools wheel
|
||||
|
||||
- name: Run fast regression tests
|
||||
shell: powershell
|
||||
run: >
|
||||
python -m pytest
|
||||
tests/test_web_gui_routes_logic.py
|
||||
tests/test_startup_update_bootstrap.py
|
||||
tests/test_distribution_manifest.py
|
||||
tests/test_exe_packing.py
|
||||
tests/test_auto_update.py
|
||||
tests/test_version_consistency.py
|
||||
tests/test_tools_dev.py
|
||||
tests/test_ci_fresh_install.py
|
||||
|
||||
- name: Build portable package
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -ReuseCache
|
||||
|
||||
- name: Build installer
|
||||
shell: powershell
|
||||
run: |
|
||||
$version = python -c "from douyin.core.version import APP_VERSION; print(str(APP_VERSION).lstrip('Vv'))"
|
||||
$iscc = @(
|
||||
"${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
|
||||
"${env:ProgramFiles}\Inno Setup 6\ISCC.exe",
|
||||
"${env:LOCALAPPDATA}\Programs\Inno Setup 6\ISCC.exe"
|
||||
) | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
if (-not $iscc) { throw "ISCC.exe not found" }
|
||||
& $iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$version
|
||||
|
||||
- name: Fresh install smoke test
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File tools\ci\fresh_install_smoke.ps1
|
||||
|
||||
- name: Upload package and smoke report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: douyin-guaji-windows-package
|
||||
path: |
|
||||
dist/installer/*.exe
|
||||
artifacts/fresh_install_ci/**
|
||||
if-no-files-found: ignore
|
||||
@@ -62,11 +62,14 @@ time_analysis_result.txt
|
||||
|
||||
# Test/diagnostic outputs
|
||||
output/
|
||||
artifacts/*
|
||||
!artifacts/webui_checks/
|
||||
artifacts/ocr_check/
|
||||
artifacts/fudai_regression_runs/
|
||||
artifacts/fudai_regression_samples/
|
||||
artifacts/webui_checks/**/*.png
|
||||
artifacts/webui_checks/**/*.txt
|
||||
artifacts/webui_checks/**/*.json
|
||||
|
||||
# Local runtime state and generated caches
|
||||
state/
|
||||
@@ -102,6 +105,7 @@ license.dat
|
||||
*~
|
||||
|
||||
# Generated tool reports and samples
|
||||
*.spec
|
||||
tools/coords_report*.csv
|
||||
tools/*_report*.csv
|
||||
tools/*_report*.csv.gz
|
||||
|
||||
@@ -15,6 +15,47 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [V3.3.11] — 2026-06-29
|
||||
## [V3.3.10] — 2026-06-29
|
||||
## [V3.3.9] — 2026-06-28
|
||||
### Fixed
|
||||
|
||||
- 自动更新差量包下载、校验或启动失败时自动回退完整安装包,避免旧版本反复卡在失败的 delta 更新上。
|
||||
- 记录已启动的差量更新尝试;如果下次启动仍停留在旧版本,则跳过同一个 delta 并改用完整安装包。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 顶部新增“检查更新”按钮,可手动触发在线更新检查。
|
||||
|
||||
### Changed
|
||||
|
||||
- 自动更新默认启用;未配置更新地址时默认使用官方更新服务器,仍可通过配置或环境变量关闭。
|
||||
|
||||
## [V3.3.8] — 2026-06-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复部分荣耀/华为设备上 `adb exec-out screencap -p` 返回 `4294967295` 或损坏 PNG 后,截图链路未继续尝试 shell stdout 兜底的问题。
|
||||
- 打包时收集 `paddlex` / `paddleocr` / Paddle / OpenCV / NumPy / PIL / pyclipper / shapely 运行依赖,避免新电脑上 OCR 初始化缺少 `_internal\paddlex\.version` 或相关二进制组件。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 新增“上传诊断日志”,客户端只打包有限大小的日志片段;服务端按卡密覆盖保存一份,便于远程排查问题。
|
||||
|
||||
## [V3.3.7] — 2026-06-28
|
||||
|
||||
### Changed
|
||||
|
||||
- Dashboard 首次启动未授权时锁定在“授权”页,验证卡密成功后再进入数据看板。
|
||||
- WebGUI 未授权访问首页时先显示卡密验证门禁页,验证成功后再加载完整控制台。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 保留运行接口的授权拦截,避免未输入卡密时通过接口直接启动运行。
|
||||
|
||||
## [V3.3.6] — 2026-06-27
|
||||
## [V3.3.5] — 2026-06-27
|
||||
## [V3.3.4] — 2026-06-26
|
||||
### Added
|
||||
|
||||
- 引入完整的版本管理体系:
|
||||
|
||||
@@ -1,707 +1,305 @@
|
||||
# 抖音福袋挂机脚本
|
||||
# 抖音自动化助手 - 数据看板版使用说明
|
||||
|
||||
<div align="center">
|
||||
这是打包成 exe 后给普通用户使用的说明。正常使用时不需要安装 Python,也不需要打开源码文件。
|
||||
|
||||
**基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具**
|
||||
## 文件说明
|
||||
|
||||
[](douyin/core/version.py)
|
||||
[](https://www.python.org/)
|
||||
[](https://www.microsoft.com/windows)
|
||||
解压或安装后,主要会看到这些文件:
|
||||
|
||||
</div>
|
||||
|
||||
> ⚠️ **本工具仅供学习交流使用**。使用产生的任何后果(账号风控、数据丢失等)由使用者自行承担。完整免责条款见文末 [免责声明](#免责声明)。
|
||||
|
||||
---
|
||||
|
||||
## 📖 目录
|
||||
|
||||
- [项目简介](#项目简介)
|
||||
- [核心功能](#核心功能)
|
||||
- [技术架构](#技术架构)
|
||||
- [环境要求与安装](#环境要求与安装)
|
||||
- [快速开始](#快速开始)
|
||||
- [详细配置说明](#详细配置说明)
|
||||
- [使用指南](#使用指南)
|
||||
- [工作原理](#工作原理)
|
||||
- [代码结构](#代码结构)
|
||||
- [测试](#测试)
|
||||
- [开发指南](#开发指南)
|
||||
- [故障排查](#故障排查)
|
||||
- [常见问题](#常见问题)
|
||||
- [版本更新日志](#版本更新日志)
|
||||
- [贡献与反馈](#贡献与反馈)
|
||||
- [免责声明](#免责声明)
|
||||
|
||||
---
|
||||
|
||||
## 项目简介
|
||||
|
||||
通过 ADB 连接安卓设备,结合像素检测 / 模板匹配 / OCR 三种技术识别抖音直播间状态,自动完成福袋发现、参与、领奖、人机验证、推荐页养号等操作。
|
||||
|
||||
适用场景:长时间挂机抢福袋、多账号管理、定时养号。**不适用**于商业用途。
|
||||
|
||||
更详细的内部技术资料:[`docs/完整技术文档.md`](docs/完整技术文档.md)、[`docs/archive/AI_PROJECT_SUMMARY.md`](docs/archive/AI_PROJECT_SUMMARY.md)(归档)。
|
||||
|
||||
---
|
||||
|
||||
## 核心功能
|
||||
|
||||
| # | 功能 | 说明 |
|
||||
|---|------|------|
|
||||
| 1 | **福袋检测** | 在直播间内通过模板匹配定位福袋图标,自动打开详情页 |
|
||||
| 2 | **信息识别** | OCR 提取福袋内容、倒计时、价值(元)、参与人数 |
|
||||
| 3 | **筛选参与** | 价值/人数/关键词三维筛选,命中黑白名单后决策是否参与 |
|
||||
| 4 | **自动领奖** | 识别开奖结果,中奖后自动领取并处理订单确认页 |
|
||||
| 5 | **高价值预约** | 价值 ≥ 阈值的福袋记录开奖时间,提前回退到目标直播间参与(需 `needswitch=true`) |
|
||||
| 6 | **高价值回访** | 持久化记录高价值直播间,定时回访 |
|
||||
| 7 | **推荐页养号** | 按概率点赞 / 收藏 / 评论,模拟真实用户行为 |
|
||||
| 8 | **人机验证** | 自动处理滑块验证、图片点击、人脸识别(失败可重试) |
|
||||
| 9 | **弹窗处理** | 自动关闭优惠券、购物红包等干扰弹窗 |
|
||||
| 10 | **直播间切换** | 上划切换、N 次后回到首播、智能处理直播结束 |
|
||||
| 11 | **超时保护** | 30 分钟未参与则自动返回推荐页重启流程,避免卡死 |
|
||||
|
||||
---
|
||||
|
||||
## 技术架构
|
||||
|
||||
### 核心技术栈
|
||||
|
||||
- **Python 3.10+** — 主语言
|
||||
- **ADB**(Android Debug Bridge)— 设备控制
|
||||
- **PaddleOCR**(>= 3.0.0)— OCR 文字识别
|
||||
- **OpenCV** — 模板匹配 / 图像处理
|
||||
- **Pillow / NumPy** — 图像 IO 与数值计算
|
||||
- **tkinter + ttkbootstrap** — 桌面 GUI
|
||||
- **内置 http.server** — Web GUI 服务
|
||||
|
||||
### 检测层次
|
||||
|
||||
| 技术 | 用途 | 速度 / 准确度 |
|
||||
|------|------|---------------|
|
||||
| 像素检测 | 弹窗背景色、按钮区域 | 极快 / 中 |
|
||||
| 模板匹配(OpenCV) | 图标、按钮等 UI 元素 | 快 / 高 |
|
||||
| OCR(PaddleOCR) | 文字识别(福袋内容、倒计时、人数) | 慢 / 高 |
|
||||
| 阶段诊断 | 综合三种技术判断当前页面状态 | 可调 / 高 |
|
||||
|
||||
### 架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ GUI / Web GUI / CLI(用户界面层) │
|
||||
│ bin/gui_app.py / bin/webgui_launcher │
|
||||
│ bin/run_cli.py │
|
||||
└──────────────┬──────────────────────────┘
|
||||
│
|
||||
┌──────────────▼──────────────────────────┐
|
||||
│ douyin/core/douyin_fudai.py │
|
||||
│ class fudai_analyse(Mixin 组合) │
|
||||
│ 核心调度器 - 主流程控制 │
|
||||
└──────────────┬──────────────────────────┘
|
||||
│
|
||||
┌──────────┼──────────┐
|
||||
│ │ │
|
||||
┌───▼────┐ ┌───▼────┐ ┌──▼─────┐
|
||||
│阶段诊断│ │福袋核心│ │弹窗处理│
|
||||
│stage/ │ │fudai/ │ │handlers│
|
||||
└────────┘ └────────┘ └────────┘
|
||||
│ │ │
|
||||
└──────────┼──────────┘
|
||||
│
|
||||
┌──────────────▼──────────────────────────┐
|
||||
│ douyin/core/underlying_operations.py │
|
||||
│ 底层 ADB / 截图 / OCR 封装 │
|
||||
└──────────────┬──────────────────────────┘
|
||||
│
|
||||
┌──────────────▼──────────────────────────┐
|
||||
│ douyin/core/path_config.py │
|
||||
│ 统一路径配置(config / state / logs) │
|
||||
└─────────────────────────────────────────┘
|
||||
```text
|
||||
DouyinGuajiGUI.exe 数据看板版主程序,优先打开这个
|
||||
web_gui.exe Web 控制台服务,一般不用手动打开
|
||||
run_cli.exe 后台运行程序,由主程序自动调用
|
||||
assets/ 识别模板资源,不要删除
|
||||
config/ 配置目录
|
||||
logs/ 日志目录
|
||||
pic/ 截图目录
|
||||
state/ 运行状态目录
|
||||
```
|
||||
|
||||
**设计要点**:
|
||||
- **Mixin 组合**:`fudai_analyse` 把功能拆到 [`douyin/core/fudai_modules/`](douyin/core/fudai_modules) 各 Mixin
|
||||
- **路径统一**:所有运行时路径通过 [`douyin/core/path_config.py`](douyin/core/path_config.py) 集中管理
|
||||
- **日志分层**:统一日志 + 行为日志(`actions.log`)分离,便于性能分析
|
||||
日常只需要双击:
|
||||
|
||||
---
|
||||
|
||||
## 环境要求与安装
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 项 | 要求 |
|
||||
|----|------|
|
||||
| 操作系统 | Windows 10/11 (64-bit) |
|
||||
| Python | 3.10–3.12(推荐 3.10) |
|
||||
| 内存 | 至少 4 GB(推荐 8 GB+) |
|
||||
| 存储 | 至少 2 GB 可用空间 |
|
||||
| 安卓设备 | Android 5.0+,已开启 USB 调试 |
|
||||
|
||||
### 必需软件
|
||||
|
||||
1. **Python 3.10+** — [下载](https://www.python.org/downloads/),安装时勾选 *Add Python to PATH*
|
||||
2. **ADB(platform-tools)** — [下载](https://developer.android.com/studio/releases/platform-tools),解压加入 PATH,验证 `adb version`
|
||||
3. **抖音 APP** — 安装在已开启 USB 调试的安卓设备
|
||||
|
||||
### 安装步骤
|
||||
|
||||
```bash
|
||||
# 1. 克隆仓库
|
||||
git clone <repository-url>
|
||||
cd douyi_guaji
|
||||
|
||||
# 2. 创建虚拟环境(推荐)
|
||||
python -m venv .venv
|
||||
.venv\Scripts\activate # Windows CMD
|
||||
# .venv\Scripts\Activate.ps1 # Windows PowerShell
|
||||
|
||||
# 3. 安装核心依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 如 paddlepaddle 安装失败,可指定清华源:
|
||||
pip install "paddlepaddle>=3.0.0" -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
# GPU 版本(需 CUDA):
|
||||
pip install "paddlepaddle-gpu>=3.0.0" -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
# 4. 验证
|
||||
python --version
|
||||
adb version
|
||||
adb devices # 应能看到设备,状态为 "device"
|
||||
```text
|
||||
DouyinGuajiGUI.exe
|
||||
```
|
||||
|
||||
### 设备配置
|
||||
## 第一次使用
|
||||
|
||||
1. 进入「设置 → 关于手机」连续点击「版本号」7 次开启**开发者模式**
|
||||
2. 在「开发者选项」中开启 **USB 调试**(部分机型还需开启 *USB 安装*)
|
||||
3. USB 连接电脑,选择 *文件传输/MTP* 模式,**首次连接**手机会弹授权对话框,选择「允许」
|
||||
4. 运行 `adb devices` 应输出 `<device-id> device`
|
||||
1. 手机或模拟器开启 USB 调试,具体方法见下面“开启 ADB 调试”。
|
||||
2. 用数据线连接电脑,手机弹出授权时选择允许。
|
||||
3. 先在手机或模拟器里调出底部导航栏,具体方法见下面“调出底部导航栏”。
|
||||
4. 双击 `DouyinGuajiGUI.exe`。
|
||||
5. 在顶部设备下拉框选择设备。
|
||||
6. 如果没有设备,点击“刷新设备”。
|
||||
7. 进入“授权”页面,输入卡密并验证。
|
||||
8. 回到“运行设置”“筛选设置”填写参数。
|
||||
9. 点击底部“开始运行”。
|
||||
|
||||
---
|
||||
## 开启 ADB 调试
|
||||
|
||||
## 快速开始
|
||||
### 安卓手机
|
||||
|
||||
三种启动方式,按场景选择:
|
||||
1. 打开手机“设置”。
|
||||
2. 进入“关于手机”。
|
||||
3. 连续点击“版本号”或“软件版本号”7 次,直到提示已进入开发者模式。
|
||||
4. 返回设置首页,进入“系统”“更多设置”或“其他设置”。
|
||||
5. 打开“开发者选项”。
|
||||
6. 开启“USB 调试”。
|
||||
7. 用数据线连接电脑。
|
||||
8. 手机弹出“允许 USB 调试”时,勾选“始终允许使用这台计算机进行调试”,再点“允许”。
|
||||
9. 回到软件,点击“刷新设备”。
|
||||
|
||||
### 方式一:桌面 GUI(推荐新手)
|
||||
如果找不到入口,可以在手机设置顶部搜索:
|
||||
|
||||
```bash
|
||||
python bin/gui_app.py
|
||||
```text
|
||||
开发者选项
|
||||
USB 调试
|
||||
```
|
||||
|
||||
1. 在「设备」下拉选择设备
|
||||
2. 在「运行设置」/「筛选设置」配置参数
|
||||
3. 点击「开始运行」,右侧日志窗口实时显示状态
|
||||
4. 通过「截图」按钮查看实时截图,「停止」/「强制停止」终止运行
|
||||
### 常见品牌路径
|
||||
|
||||
### 方式二:命令行(高级用户)
|
||||
- 小米/红米:设置 -> 我的设备 -> 全部参数 -> 连点 MIUI 版本;然后设置 -> 更多设置 -> 开发者选项 -> USB 调试。
|
||||
- 华为/荣耀:设置 -> 关于手机 -> 连点版本号;然后设置 -> 系统和更新 -> 开发人员选项 -> USB 调试。
|
||||
- OPPO/一加:设置 -> 关于本机 -> 版本信息 -> 连点版本号;然后设置 -> 系统设置 -> 开发者选项 -> USB 调试。
|
||||
- vivo/iQOO:设置 -> 系统管理 -> 关于手机 -> 连点软件版本号;然后设置 -> 系统管理 -> 开发者选项 -> USB 调试。
|
||||
|
||||
```bash
|
||||
# 基本用法
|
||||
python bin/run_cli.py --needswitch --wait-minutes 5
|
||||
### 安卓模拟器
|
||||
|
||||
# 完整参数示例
|
||||
python bin/run_cli.py \
|
||||
--device-id MB75DEFQZHZTGMLJ \
|
||||
--y-pianyi 0 \
|
||||
--needswitch \
|
||||
--wait-minutes 5 \
|
||||
--min-prize-value-yuan 200.0 \
|
||||
--min-participants 100 \
|
||||
--skip-if-countdown-lt-seconds 5
|
||||
1. 打开模拟器。
|
||||
2. 进入模拟器的“设置中心”或右上角菜单。
|
||||
3. 找到“ADB 调试”“Android 调试”或“开发者模式”。
|
||||
4. 选择“开启”或“本地连接”。
|
||||
5. 保存设置后重启模拟器。
|
||||
6. 回到软件,点击“刷新设备”。
|
||||
|
||||
不同模拟器入口名字会略有不同,可以优先在模拟器设置里搜索:
|
||||
|
||||
```text
|
||||
ADB
|
||||
调试
|
||||
开发者
|
||||
```
|
||||
|
||||
| 常用参数 | 说明 |
|
||||
|---------|------|
|
||||
| `--device-id` | 设备 ID(省略则取第一个) |
|
||||
| `--y-pianyi` | Y 偏移(-200~200,常用 -50~50) |
|
||||
| `--needswitch` | 允许切换直播间 |
|
||||
| `--wait-minutes` | 倒计时超过 N 分钟时切换直播间 |
|
||||
| `--min-prize-value-yuan` | 最低奖品价值(元) |
|
||||
| `--min-participants` | 最少参与人数 |
|
||||
| `--skip-if-countdown-lt-seconds` | 跳过倒计时小于 N 秒的福袋 |
|
||||
## 调出底部导航栏
|
||||
|
||||
### 方式三:Web GUI(远程控制)
|
||||
自动化运行必须能看到底部返回、主页、多任务按钮。不要使用隐藏导航条或纯手势导航。
|
||||
|
||||
```bash
|
||||
python bin/webgui_launcher.py
|
||||
```
|
||||
### 安卓手机
|
||||
|
||||
打开浏览器访问 `http://127.0.0.1:8000/`,通过页面配置参数、查看实时日志/截图,远程访问改用机器 IP。
|
||||
1. 打开手机“设置”。
|
||||
2. 搜索“系统导航方式”或“导航方式”。
|
||||
3. 进入后选择“三键导航”“经典导航键”或“屏幕内三键导航”。
|
||||
4. 回到桌面或抖音页面,确认屏幕底部能看到返回、主页、多任务按钮。
|
||||
|
||||
---
|
||||
常见品牌路径:
|
||||
|
||||
## 详细配置说明
|
||||
- 小米/红米:设置 -> 桌面 -> 系统导航方式 -> 经典导航键。
|
||||
- 华为/荣耀:设置 -> 系统和更新 -> 系统导航方式 -> 屏幕内三键导航。
|
||||
- OPPO/一加:设置 -> 系统设置 -> 系统导航方式 -> 虚拟按键。
|
||||
- vivo/iQOO:设置 -> 系统导航 -> 导航键。
|
||||
|
||||
所有配置在 [`config/config.json`](config/config.json) 中,可通过 GUI 修改或直接编辑 JSON。运行时通过 `path_config.get_config_path()` 读取。
|
||||
### 安卓模拟器
|
||||
|
||||
1. 打开模拟器设置。
|
||||
2. 找到“导航栏”“虚拟按键”“系统导航”或“显示底部导航栏”。
|
||||
3. 开启底部导航栏。
|
||||
4. 如果模拟器底部按钮被隐藏,先把鼠标移到窗口底部,或在侧边工具栏里点“返回”“主页”按钮确认可用。
|
||||
5. 回到抖音画面,确认底部能看到返回、主页、多任务按钮。
|
||||
|
||||
## 主界面怎么用
|
||||
|
||||
### 顶部区域
|
||||
|
||||
- 设备:选择当前要控制的手机或模拟器。
|
||||
- 刷新设备:重新检测 ADB 设备。
|
||||
- 扫描 WiFi:用于 WiFi ADB 连接。
|
||||
- WiFi ADB:打开 WiFi 连接工具。
|
||||
- Y偏移:点击位置有偏差时填写,普通文本输入即可。
|
||||
- 截图+OCR:手动截图并识别当前画面。
|
||||
- 保存配置:保存当前界面参数。
|
||||
|
||||
### 底部按钮
|
||||
|
||||
- 开始运行:启动自动化流程。
|
||||
- 暂停/继续:临时暂停或恢复当前运行。
|
||||
- 停止:正常停止。
|
||||
- 强制停止:进程卡住时使用。
|
||||
- 发送返回键:向手机发送一次返回键。
|
||||
|
||||
## 常用页面
|
||||
|
||||
### 数据看板
|
||||
|
||||
默认首页,主要看:
|
||||
|
||||
- 本次运行时间
|
||||
- 总运行时间
|
||||
- 中奖截图数量
|
||||
- 预约队列
|
||||
- 实时截图
|
||||
|
||||
### 运行设置
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `needswitch` | bool | `true` | 允许上划切换直播间 |
|
||||
| `wait_minutes` | int | `5` | 倒计时超过该值(分钟)时切换(仅 `needswitch=true` 生效) |
|
||||
| `skip_if_countdown_lt_seconds` | int | `5` | 倒计时小于该值时不参与(高价值仍可预约) |
|
||||
| `reset_after_swipes_enabled` | bool | `true` | 启用「切换 N 次后回到首播」 |
|
||||
| `reset_after_swipes` | int | `30` | 触发回到首播的切换次数 |
|
||||
| `fudai_find_max_attempts` | int | `10` | 找福袋图标的最大重试次数 |
|
||||
| `fudai_icon_retry_delay_seconds` | float | `0.6` | 找福袋图标的重试间隔(秒) |
|
||||
| `fudai_icon_max_wait_seconds` | float | `5.0` | 找福袋图标的最大等待(秒) |
|
||||
| `live_room_match_threshold` | float | `0.8` | 直播间检测阈值(0~1,越高越严格,建议 ≥ 0.8) |
|
||||
| `stage_diag_max_time` | float | `15.0` | 阶段诊断最大耗时(秒) |
|
||||
| `stage_diag_max_step_time` | float | `4.0` | 阶段诊断单步最大耗时(秒) |
|
||||
| `no_attend_timeout_minutes` | float | `30.0` | 30 分钟超时保护:超过该值未成功参与则返回推荐页(0 = 禁用) |
|
||||
设置运行方式,例如:
|
||||
|
||||
### 福袋筛选
|
||||
- 是否允许切换直播间
|
||||
- 运行时长
|
||||
- 倒计时大于多少秒时跳过
|
||||
- 连续无福袋退出阈值
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `min_prize_value_yuan` | float | `0.0` | 最低奖品价值(元),0 = 不启用 |
|
||||
| `min_participants` | int | `0` | 最少参与人数,0 = 不启用 |
|
||||
| `max_participants` | int | `0` | 最多参与人数,0 = 不启用 |
|
||||
| `contains_want` | array | `[]` | 想要的关键词白名单 |
|
||||
| `contains_not_want` | array | `[]` | 不想要的关键词黑名单 |
|
||||
### 筛选设置
|
||||
|
||||
```json
|
||||
{
|
||||
"min_prize_value_yuan": 200.0,
|
||||
"min_participants": 100,
|
||||
"max_participants": 10000,
|
||||
"contains_want": ["手机", "现金", "红包"],
|
||||
"contains_not_want": ["袜子", "优惠券", "代金券"]
|
||||
}
|
||||
```
|
||||
设置福袋筛选条件,例如:
|
||||
|
||||
### 高价值福袋预约
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `high_value_fudai_enabled` | bool | `true` | 启用预约功能 |
|
||||
| `high_value_fudai_threshold_yuan` | float | `500.0` | 预约阈值(元),价值 ≥ 该值则预约 |
|
||||
| `high_value_fudai_join_ahead_seconds` | int | `300` | 提前 N 秒返回直播间参与 |
|
||||
| `high_value_fudai_max_swipe_back` | int | `35` | 最多回退次数(防止过远) |
|
||||
| `high_value_fudai_max_reservations` | int | `3` | 最多同时预约数 |
|
||||
| `high_value_fudai_after_action` | string | `"continue"` | 完成预约后:`stay`(停留)或 `continue`(继续抢) |
|
||||
| `reservation_back_verify_enabled` | bool | `false` | 启用回退验证 |
|
||||
| `reservation_back_swipe_delay` | float | `0.6` | 回退滑动延迟(秒) |
|
||||
|
||||
> **重要**:预约回退需 `needswitch=true`。单间模式下预约会在当前直播间自动识别参与,无需回退。
|
||||
|
||||
### 高价值直播间回访
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `high_value_room_revisit_enabled` | bool | `false` | 启用高价值直播间回访 |
|
||||
| `high_value_room_revisit_only_current_run` | bool | `false` | 仅本次运行回访(true)或持久化(false) |
|
||||
|
||||
### 粉丝团
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `auto_join_fansclub` | bool | `true` | 自动加入粉丝团(**可能消耗钻石**) |
|
||||
| `fansclub_fail_action` | string | `"switch"` | 加入失败后:`stay` 或 `switch` |
|
||||
|
||||
### 推荐页养号
|
||||
|
||||
养号参数较多(约 30 项),完整列表见 [`docs/完整技术文档.md`](docs/完整技术文档.md) 的「推荐页养号设置」段。常用:
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `yanghao_enabled` | bool | `false` | 启用养号 |
|
||||
| `yanghao_enable_actions` | bool | `false` | 启用养号动作(点赞/收藏/评论) |
|
||||
| `yanghao_recommend_duration_seconds` | int | `216` | 推荐页停留时长(秒) |
|
||||
| `yanghao_recommend_interval_seconds` | int | `600` | 推荐页养号间隔(秒),0 = 不间隔 |
|
||||
| `yanghao_like_prob` | float | `1.0` | 点赞概率 |
|
||||
| `yanghao_fav_prob` | float | `0.85` | 收藏概率 |
|
||||
| `yanghao_comment_prob` | float | `1.0` | 评论概率 |
|
||||
|
||||
### 静默时段
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `fudai_quiet_hours_enabled` | bool | `true` | 启用静默时段(不抢福袋,仍可养号) |
|
||||
| `fudai_quiet_start_hour` | int | `2` | 起始小时(0–23) |
|
||||
| `fudai_quiet_end_hour` | int | `6` | 结束小时(0–23) |
|
||||
|
||||
---
|
||||
|
||||
## 使用指南
|
||||
|
||||
### 首次使用
|
||||
|
||||
1. 通过 GUI 启动,便于观察日志
|
||||
2. 调整 Y 偏移(通常 -50~50),通过「截图」核对点击位置
|
||||
3. 设置较宽松的筛选条件,观察实际效果再收紧
|
||||
4. 关注是否触发人机验证;频繁出现说明运行频率过高,应启用养号或缩短运行时段
|
||||
|
||||
### 日常建议
|
||||
|
||||
- **查日志**:[`logs/unified.log`](logs/) 总览、[`logs/actions.log`](logs/) 关键操作
|
||||
- **稳定连接**:USB 3.0 + 不掉线手机,定期检查 `adb devices`
|
||||
- **风控防御**:启用养号 + 配置静默时段;账号疑似限制立即停止并人工操作
|
||||
|
||||
### 高级用法
|
||||
|
||||
- **多账号**:每账号独立 `config/` 目录或通过 `--device-id` 区分
|
||||
- **定时**:Windows 任务计划程序 + 静默时段
|
||||
- **远程**:Web GUI 端口转发到外网(注意安全)
|
||||
- **性能调优**:调小 OCR 区域、降低截图频率、用 GPU 版 PaddleOCR
|
||||
|
||||
---
|
||||
|
||||
## 工作原理
|
||||
|
||||
### 主流程
|
||||
|
||||
```
|
||||
开始
|
||||
│
|
||||
├─> 初始化(加载配置、连接设备)
|
||||
│
|
||||
├─> 30 分钟超时检查
|
||||
│ └─ 超时 → 返回推荐页面重新开始
|
||||
│
|
||||
├─> 阶段诊断(判断当前页面)
|
||||
│ ├─> 直播间 → 检测福袋图标 → 打开详情页
|
||||
│ ├─> 福袋详情页 → 读取信息 → 筛选 → 参与
|
||||
│ ├─> 抽奖结果页 → 中奖领取 / 关闭弹窗
|
||||
│ └─> 其他 → 导航回直播间
|
||||
│
|
||||
├─> 处理弹窗(优惠券、红包、人机验证)
|
||||
│
|
||||
└─> 循环执行
|
||||
```
|
||||
|
||||
### 阶段诊断
|
||||
|
||||
按优先级判断当前页面:
|
||||
|
||||
1. **直播间检测**(最高优先级):模板匹配右上角关闭/心形图标,阈值默认 0.8
|
||||
2. **像素检测**(并行):弹窗背景色、参与按钮红色、粉丝团红色等
|
||||
3. **OCR 检测**(按需):识别推荐页 / 关注列表 / 直播列表 / 福袋详情等
|
||||
4. **综合判断**:返回当前阶段(`IN_LIVE_ROOM` / `RECOMMEND_PAGE` / `FUDai_DETAIL` / `FUDai_RESULT` / ...)
|
||||
|
||||
### 福袋筛选
|
||||
|
||||
```
|
||||
福袋信息
|
||||
│
|
||||
├─> 价值 < min_prize_value_yuan → 跳过
|
||||
├─> 人数不在 [min_participants, max_participants] → 跳过
|
||||
├─> 倒计时 < skip_if_countdown_lt_seconds → 不参与(高价值可预约)
|
||||
├─> 命中 contains_not_want → 跳过
|
||||
├─> contains_want 非空且未命中 → 跳过
|
||||
└─> 全部通过 → 参与抽奖
|
||||
```
|
||||
- 最低价值
|
||||
- 参与人数最小
|
||||
- 参与人数最大
|
||||
- 倒计时太短时跳过
|
||||
- 粉丝团失败策略
|
||||
|
||||
### 高价值预约
|
||||
|
||||
1. **识别**:价值 ≥ `high_value_fudai_threshold_yuan` → 记录到 `douyin/core/state/reservations.json`
|
||||
2. **继续**:不立即参与,继续切换直播间(需 `needswitch=true`)
|
||||
3. **回退**:开奖前 `high_value_fudai_join_ahead_seconds` 秒,从状态文件加载,按直播间标题匹配回退
|
||||
4. **持久化**:最多 `high_value_fudai_max_reservations` 个,超出丢弃最晚开奖的;重启后自动加载
|
||||
用于价值较高、开奖时间较晚的福袋。
|
||||
|
||||
更详细:[`docs/预约系统详细流程.md`](docs/预约系统详细流程.md)。
|
||||
常用项:
|
||||
|
||||
---
|
||||
- 启用预约
|
||||
- 价值阈值
|
||||
- 提前参与秒数
|
||||
- 最多记录数量
|
||||
- 预约回退校验
|
||||
|
||||
## 代码结构
|
||||
### 运行日志
|
||||
|
||||
显示完整运行输出。运行异常时优先看这里。
|
||||
|
||||
### 行为日志
|
||||
|
||||
显示更简洁的关键动作,例如:
|
||||
|
||||
- 进入直播间
|
||||
- 识别福袋
|
||||
- 点击参与
|
||||
- 切换直播间
|
||||
- 预约记录
|
||||
- 中奖结果
|
||||
|
||||
### 截图预览
|
||||
|
||||
显示当前截图。识别不准时先看这里确认画面是否正常。
|
||||
|
||||
### 预约队列
|
||||
|
||||
显示已记录的预约福袋。该页面会自动刷新,首页里的预约队列也会自动更新。
|
||||
|
||||
### 统计信息
|
||||
|
||||
显示本次运行的数据统计,比日志更方便查看。
|
||||
|
||||
### 映射表
|
||||
|
||||
显示运行过程中记录的直播间位置和标题映射。可开启自动刷新。
|
||||
|
||||
## 推荐使用流程
|
||||
|
||||
1. 打开 `DouyinGuajiGUI.exe`。
|
||||
2. 先把手机或模拟器底部导航栏调出来。
|
||||
3. 刷新并选择设备。
|
||||
4. 点击“截图+OCR”,确认截图能正常显示。
|
||||
5. 在“筛选设置”填好最低价值、人数范围。
|
||||
6. 如果要切换直播间,在“运行设置”开启允许切换直播间。
|
||||
7. 如需高价值预约,在“高价值预约”开启预约并设置价值阈值。
|
||||
8. 点击“保存配置”。
|
||||
9. 点击“开始运行”。
|
||||
10. 运行中观察“数据看板”“运行日志”“行为日志”。
|
||||
11. 需要临时停一下时点“暂停/继续”,结束时点“停止”。
|
||||
|
||||
## 日志和截图位置
|
||||
|
||||
如果需要排查问题,可以打开这些文件:
|
||||
|
||||
```text
|
||||
logs/unified.log 完整运行日志
|
||||
logs/actions.log 关键行为日志
|
||||
pic/screenshot.png 当前截图
|
||||
pic/lottery/ 中奖截图
|
||||
state/ 运行状态
|
||||
```
|
||||
<项目根>/
|
||||
├── bin/ # 入口脚本
|
||||
│ ├── run_cli.py # 命令行入口
|
||||
│ ├── gui_app.py # 桌面 GUI launcher
|
||||
│ ├── webgui_launcher.py # Web GUI launcher
|
||||
│ └── manage_logs.py # 日志管理 CLI
|
||||
├── douyin/ # 核心业务逻辑
|
||||
│ ├── core/ # 核心调度
|
||||
│ │ ├── douyin_fudai.py # fudai_analyse(Mixin 组合)
|
||||
│ │ ├── douyin_main_flow.py # 主流程控制
|
||||
│ │ ├── douyin_flow_control.py
|
||||
│ │ ├── path_config.py # 路径配置
|
||||
│ │ ├── underlying_operations.py # 底层 ADB/截图/OCR
|
||||
│ │ ├── io_utils.py # 文件 IO 辅助
|
||||
│ │ ├── version.py
|
||||
│ │ └── fudai_modules/ # 7 个 Mixin
|
||||
│ ├── detection/ # 像素 + 模板检测
|
||||
│ ├── stage/ # 阶段诊断
|
||||
│ ├── fudai/ # 福袋核心
|
||||
│ │ └── core/ # detail_reader / filter / attend / coords / ...
|
||||
│ ├── handlers/ # 截图 / 滑动 / 弹窗处理
|
||||
│ ├── reservation/ # 预约状态文件 / 逻辑 / 回退校验
|
||||
│ ├── logging/ # 9 个日志模块(unified / wrapper / action / ...)
|
||||
│ ├── other/ # 养号 / 人机校验 / 高价值房间 / ...
|
||||
│ └── utils/ # 配置 / 文本 / 时间 / OCR 预处理
|
||||
├── operations/ # 兼容层:re-export 给老代码
|
||||
├── gui/ # GUI 实现(桌面 + Web)
|
||||
│ ├── gui_app.py / web_gui.py / gui_core.py
|
||||
│ ├── components/ # 桌面 GUI 子组件
|
||||
│ └── web_components/ # Web GUI 子组件
|
||||
├── webui/ # Web GUI 前端(HTML/CSS/JS)
|
||||
├── tools/ # 47 个开发/调试脚本(按 adb/coords/dev/diagnostics/logs 分组)
|
||||
├── tests/ # pytest 单元/冒烟测试(242 用例)
|
||||
├── docs/ # 项目文档
|
||||
│ ├── 完整技术文档.md # 7000+ 行内部技术参考
|
||||
│ └── archive/ # 已过时文档归档
|
||||
├── config/config.json # 用户配置
|
||||
├── assets/ # 模板图片(x.png / xin.png / like.png / fav.png 等)
|
||||
├── pic/ # 运行时截图(.gitignored)
|
||||
├── logs/ # 运行时日志(.gitignored)
|
||||
└── state/ # 运行时状态(.gitignored)
|
||||
```
|
||||
|
||||
### 核心模块速查
|
||||
|
||||
| 模块 / 文件 | 职责 |
|
||||
|-------------|------|
|
||||
| [`douyin/core/douyin_fudai.py`](douyin/core/douyin_fudai.py) | 主类 `fudai_analyse`,Mixin 组合,主入口 |
|
||||
| [`douyin/core/path_config.py`](douyin/core/path_config.py) | 统一路径配置(config / state / logs / pic) |
|
||||
| [`douyin/core/underlying_operations.py`](douyin/core/underlying_operations.py) | 底层 ADB/截图/OCR 封装 |
|
||||
| [`douyin/stage/douyin_stage.py`](douyin/stage/douyin_stage.py) | 阶段诊断核心 |
|
||||
| [`douyin/fudai/core/fudai_filter.py`](douyin/fudai/core/fudai_filter.py) | 福袋筛选决策(含黑白名单) |
|
||||
| [`douyin/reservation/douyin_reservation.py`](douyin/reservation/douyin_reservation.py) | 预约状态文件原子读写 |
|
||||
| [`douyin/logging/unified_logger.py`](douyin/logging/unified_logger.py) | MDC(Mapped Diagnostic Context)+ 装饰器 |
|
||||
| [`gui/gui_app.py`](gui/gui_app.py) / [`gui/web_gui.py`](gui/web_gui.py) | 桌面 / Web GUI 实现 |
|
||||
| [`bin/run_cli.py`](bin/run_cli.py) | 命令行入口(含参数解析、shim 加载) |
|
||||
|
||||
资源目录:
|
||||
|
||||
- [`assets/`](assets/) — 模板图片:`x.png`(关闭)、`xin.png`(心形)、`like.png`、`fav.png`、`desktop.png`
|
||||
- `pic/` — 运行时截图(`screenshot.png` 是最新;`ocr/` 子目录为 OCR 区域示例)
|
||||
- `logs/` — `unified.log`(全部)+ `actions.log`(关键操作)
|
||||
- `state/` — `high_value_rooms.json`;预约状态实际写入 `douyin/core/state/reservations.json`
|
||||
|
||||
---
|
||||
|
||||
## 测试
|
||||
|
||||
`tests/` 是 pytest 风格的单元测试 + 业务冒烟,覆盖路径配置、文本解析、福袋筛选决策、logger helper、MDC 上下文、io_utils 等核心纯函数链路。**242 用例 / < 1 秒**,不依赖 ADB / 真实设备 / OCR 引擎。
|
||||
|
||||
```bash
|
||||
pip install pytest
|
||||
|
||||
# 全量
|
||||
pytest
|
||||
|
||||
# 单文件 / 单用例
|
||||
pytest tests/test_filter_logging.py
|
||||
pytest tests/test_path_config.py::TestSpecificPaths::test_reservations_path_in_douyin_core_state -v
|
||||
|
||||
# 跑较慢的性能对比脚本(需 paddleocr/easyocr/psutil)
|
||||
pytest -m slow
|
||||
```
|
||||
|
||||
测试约定:
|
||||
- [`tests/conftest.py`](tests/conftest.py) 自动把项目根加入 `sys.path`
|
||||
- 性能脚本用 `pytest.importorskip` 自动跳过缺失依赖
|
||||
- 自定义 marker:`smoke`(业务关键链路)/ `slow`(慢测试);新增需先在 [`pyproject.toml`](pyproject.toml) 注册
|
||||
|
||||
---
|
||||
|
||||
## 开发指南
|
||||
|
||||
### 开发环境
|
||||
|
||||
```bash
|
||||
# 创建并激活虚拟环境
|
||||
python -m venv .venv
|
||||
.venv\Scripts\activate
|
||||
|
||||
# 安装运行依赖 + 开发工具
|
||||
pip install -r requirements.txt
|
||||
pip install pytest black ruff mypy
|
||||
```
|
||||
|
||||
### 代码规范
|
||||
|
||||
- **风格**:PEP 8;类名 `CamelCase`;函数/变量 `snake_case`;常量 `UPPER_SNAKE_CASE`
|
||||
- **类型注解**:尽量加,特别是公共函数
|
||||
- **注释**:默认不写;仅在 *为什么* 非显然时(隐藏约束、变通方案、会让读者意外的行为)添加一行
|
||||
- **不写多行 docstring**:一行总结即可
|
||||
|
||||
### 工作流
|
||||
|
||||
1. **新功能** — 在 `douyin/<module>/` 创建模块;`douyin/core/douyin_fudai.py` 中调用;如需配置项,更新 `config/config.json` + GUI/WebUI 同步
|
||||
2. **GUI 同步检查** — 运行 [`tools/diagnostics/check_web_gui_config_sync.py`](tools/diagnostics/check_web_gui_config_sync.py),确保桌面 GUI 与 WebUI 的配置 key 一致
|
||||
3. **测试** — 修改纯函数 / 业务逻辑后补 [`tests/`](tests/) 用例,跑 `pytest`
|
||||
4. **提交** — 提交信息中文,格式:`<类型>: <简短描述>`;类型有 `feat` / `fix` / `refactor` / `docs` / `chore` 等
|
||||
|
||||
### 调试技巧
|
||||
|
||||
- **业务日志**:`analyser._log_kv("分类", "消息", key=value)` 走统一日志体系
|
||||
- **截图调试**:`analyser.operation.get_screenshot(self.device_id)` → 查看 `pic/screenshot.png`
|
||||
- **GUI 即时截图**:桌面 GUI 「截图」按钮 → 实时截图 + OCR 结果
|
||||
- **测试模式**:`python bin/run_cli.py --test-yanghao-flow` 单独跑养号流程
|
||||
|
||||
更多文档:[`docs/完整技术文档.md`](docs/完整技术文档.md)、[`docs/DEBUG_IMAGE_SYSTEM.md`](docs/DEBUG_IMAGE_SYSTEM.md)。
|
||||
|
||||
---
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 设备连接
|
||||
|
||||
| 症状 | 处理 |
|
||||
|------|------|
|
||||
| `adb devices` 显示 `unauthorized` | 手机授权对话框选「允许」 |
|
||||
| 显示 `offline` | 重新插拔 USB;`adb kill-server && adb start-server` |
|
||||
| 列表为空 | 检查 USB 调试 / 数据线 / USB 接口;选择「文件传输/MTP」模式 |
|
||||
|
||||
### 识别错误
|
||||
|
||||
| 症状 | 处理 |
|
||||
|------|------|
|
||||
| 点击位置不准 | 调整 Y 偏移(`--y-pianyi`);查看 `pic/screenshot.png` |
|
||||
| 找不到福袋图标 | 增加 `fudai_icon_max_wait_seconds`;确认 `assets/` 模板存在 |
|
||||
| 阶段诊断错误 | 调整 `live_room_match_threshold`;查看 `pic/ocr/` 调试图片 |
|
||||
|
||||
### OCR
|
||||
|
||||
| 症状 | 处理 |
|
||||
|------|------|
|
||||
| OCR 失败 | 重装 PaddleOCR;确认截图清晰;检查识别区域配置 |
|
||||
| OCR 慢 | 启用 GPU 版 PaddleOCR;调小识别区域;降低截图频率 |
|
||||
|
||||
### 风控
|
||||
|
||||
| 症状 | 处理 |
|
||||
|------|------|
|
||||
| 频繁人机验证 | 启用养号;缩短运行时段;调宽筛选条件 |
|
||||
| 账号被限制 | **立即停止脚本**;手动操作账号恢复正常 |
|
||||
|
||||
### 性能
|
||||
|
||||
| 症状 | 处理 |
|
||||
|------|------|
|
||||
| CPU 高 | 降低截图频率;优化 OCR 区域;用 GPU 版 PaddleOCR |
|
||||
| 内存高 | 限制日志文件大小;定期重启脚本 |
|
||||
|
||||
---
|
||||
|
||||
## 常见问题
|
||||
|
||||
**Q: 支持 iOS 设备吗?**
|
||||
A: 不支持,iOS 需要越狱。
|
||||
### 检测不到设备
|
||||
|
||||
**Q: 需要 Root 权限吗?**
|
||||
A: 不需要,仅需 USB 调试。
|
||||
1. 确认手机开启 USB 调试。
|
||||
2. 重新插拔数据线。
|
||||
3. 手机授权弹窗选择允许。
|
||||
4. 点击主界面“刷新设备”。
|
||||
|
||||
**Q: 可以同时运行多个账号吗?**
|
||||
A: 可以。每账号独立设备 + 独立 `config/` 目录,命令行用 `--device-id` 区分。
|
||||
### 截图为空或不更新
|
||||
|
||||
**Q: 脚本会被检测吗?**
|
||||
A: 任何自动化都有风控风险。建议:启用养号、合理配置静默时段、定期手动操作账号。
|
||||
1. 先确认设备已连接。
|
||||
2. 确认手机或模拟器底部导航栏已经调出。
|
||||
3. 点击“截图+OCR”手动刷新。
|
||||
4. 检查 `pic/screenshot.png` 是否生成。
|
||||
5. 仍不正常时重启程序和设备。
|
||||
|
||||
**Q: 如何提高中奖率?**
|
||||
A: 中奖率取决于福袋本身。可通过筛选小参与人数福袋 + 多账号并行提高总中奖期望。
|
||||
### 点击位置不准
|
||||
|
||||
**Q: 脚本卡住怎么办?**
|
||||
A: 查 `logs/unified.log` 确认卡在哪一步;用「截图」按钮看当前页面;点击「强制停止」;必要时重启脚本/设备。30 分钟超时保护会自动恢复。
|
||||
先确认底部导航栏已经调出,再在顶部 `Y偏移` 输入框调整数值,然后再次截图确认。
|
||||
|
||||
**Q: 高价值预约不生效?**
|
||||
A: 检查:
|
||||
- `config.json` 中 `needswitch=true` 且 `high_value_fudai_enabled=true`
|
||||
- `douyin/core/state/reservations.json` 中是否有预约数据
|
||||
- 日志中搜 `[预约] run_once_basic:检查预约回退触发条件`
|
||||
### 运行卡住
|
||||
|
||||
**Q: 如何更新脚本?**
|
||||
A: 备份 `config/config.json` 与 `state/` 目录 → `git pull`(或重新下载)→ 检查 `config.json` 是否需要补新配置项。
|
||||
1. 先点“停止”。
|
||||
2. 如果没有反应,再点“强制停止”。
|
||||
3. 查看 `logs/unified.log` 和 `logs/actions.log`。
|
||||
|
||||
---
|
||||
### 预约队列没有内容
|
||||
|
||||
## 版本更新日志
|
||||
只有识别到符合高价值预约条件的福袋后才会出现内容。请检查:
|
||||
|
||||
完整变更见 [CHANGELOG.md](CHANGELOG.md)(Keep a Changelog 格式)。
|
||||
所有发布都打了 git tag,可以通过 `git tag -l` 查看,或访问 [git tags 页面](../../tags)。
|
||||
1. 是否启用预约。
|
||||
2. 价值阈值是否过高。
|
||||
3. 是否允许切换直播间。
|
||||
4. 运行日志里是否出现预约相关记录。
|
||||
|
||||
最近 3 个版本:
|
||||
### 授权失败
|
||||
|
||||
### V3.3.3 (2025-12-28) — 当前
|
||||
- ✨ 新增:30 分钟超时保护机制
|
||||
- 🐛 修复:模板与截图路径配置统一,使用 [`path_config.py`](douyin/core/path_config.py)
|
||||
- 🔧 优化:行为日志路径统一为 `path_config.get_actions_log_path()`
|
||||
1. 检查网络是否正常。
|
||||
2. 确认卡密没有复制多余空格。
|
||||
3. 点击“刷新状态”后再验证。
|
||||
4. 仍失败请联系发卡方。
|
||||
|
||||
### V3.3.2 (2025-12-25)
|
||||
- 🐛 修复:预约回退功能不生效(`needswitch` 与 `self.reservations` 加载问题)
|
||||
- 🔧 优化:每次 `run_once_basic` 自动从状态文件加载预约队列
|
||||
## 不要删除的文件夹
|
||||
|
||||
### V3.3.1 (2025-12-14)
|
||||
- ✨ 新增:直播间检测阈值可配置(`live_room_match_threshold`)
|
||||
- ✨ 新增:福袋图标检测等待时间可配置
|
||||
- 🔧 优化:阶段检测优先使用像素检测;合并阶段 1.5 与阶段 3 的 OCR
|
||||
这些目录不要删除:
|
||||
|
||||
### 发布流程
|
||||
|
||||
新版本发布走 [`tools/dev/bump_version.py`](tools/dev/bump_version.py):
|
||||
|
||||
```bash
|
||||
python tools/dev/bump_version.py patch # V3.3.3 → V3.3.4
|
||||
python tools/dev/bump_version.py minor # V3.3.3 → V3.4.0
|
||||
python tools/dev/bump_version.py major # V3.3.3 → V4.0.0
|
||||
python tools/dev/bump_version.py --dry-run patch # 只看会改什么
|
||||
```text
|
||||
assets/
|
||||
config/
|
||||
webui/
|
||||
```
|
||||
|
||||
脚本会自动同步 `version.py` / `pyproject.toml` / `CHANGELOG.md` 顶部并创建 git tag。
|
||||
[`tests/test_version_consistency.py`](tests/test_version_consistency.py) 9 个用例守住三处版本号一致。
|
||||
这些目录可以清理旧内容,但不建议删除目录本身:
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 贡献与反馈
|
||||
|
||||
### 提交 Issue
|
||||
|
||||
请包含:
|
||||
- **标题**:一句话概述
|
||||
- **环境**:操作系统、Python、ADB、设备型号
|
||||
- **复现步骤**:最小复现命令 / 点击顺序
|
||||
- **日志/截图**(可选但推荐):`logs/unified.log` 片段、错误截图
|
||||
- **期望 vs 实际**
|
||||
|
||||
### 贡献 PR
|
||||
|
||||
```bash
|
||||
# 1. fork + 新分支
|
||||
git checkout -b fix/your-change
|
||||
|
||||
# 2. 改动 + 测试
|
||||
pytest
|
||||
|
||||
# 3. 提交(中文,type: 描述)
|
||||
git commit -m "fix: 修复 OCR 识别问题"
|
||||
|
||||
# 4. PR 描述写清变更细节、测试方法、影响范围
|
||||
```text
|
||||
logs/
|
||||
pic/
|
||||
state/
|
||||
```
|
||||
|
||||
代码风格保持现有约定,避免大面积重构而不提前沟通。
|
||||
## 更新版本
|
||||
|
||||
---
|
||||
如果你拿到新的安装包:
|
||||
|
||||
## 免责声明
|
||||
1. 先关闭正在运行的程序。
|
||||
2. 备份旧目录里的 `config/` 和 `state/`。
|
||||
3. 安装或解压新版本。
|
||||
4. 如需保留旧配置,把备份的 `config/` 和 `state/` 放回新目录。
|
||||
5. 重新打开 `DouyinGuajiGUI.exe`。
|
||||
|
||||
1. **本工具仅供学习交流使用**,请勿用于商业用途。
|
||||
2. **使用本工具产生的任何后果由使用者自行承担**,包括但不限于:
|
||||
- 账号被封禁或限制
|
||||
- 数据丢失或泄露
|
||||
- 设备损坏
|
||||
- 其他法律风险
|
||||
3. **请遵守抖音平台相关规则**,不要使用本工具进行违法违规操作。
|
||||
4. **作者不对使用本工具造成的任何损失负责**。
|
||||
5. **使用本工具即表示您已阅读并同意本免责声明**。
|
||||
## 注意事项
|
||||
|
||||
---
|
||||
|
||||
## 许可
|
||||
|
||||
仓库当前未添加明确的开源许可文件(LICENSE)。如需对外发布或在项目中使用本代码,请先在 Issue 中联系作者或为仓库添加合适的许可证(MIT / Apache-2.0 / GPL-3.0 等)。
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**感谢使用抖音福袋挂机脚本**
|
||||
|
||||
如果这个项目对你有帮助,欢迎 ⭐
|
||||
|
||||
</div>
|
||||
- 自动化运行期间不要手动频繁操作手机。
|
||||
- 账号风控风险自行承担。
|
||||
- 运行异常时先保存日志和截图,再重启程序。
|
||||
- 如果杀毒软件提示拦截,请把程序目录加入信任后再试。
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -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 ""
|
||||
|
||||
+236
-10
@@ -15,18 +15,18 @@
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 300.0,
|
||||
"min_prize_value_yuan": 100.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 118,
|
||||
"skip_if_countdown_gt_seconds": 10,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 20,
|
||||
"reset_after_swipes_action": "swipe",
|
||||
"reenter_live_entry_mode": "follow_list",
|
||||
"reenter_live_entry_mode": "screen_center",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 500.0,
|
||||
"high_value_fudai_threshold_yuan": 150.0,
|
||||
"high_value_fudai_join_ahead_seconds": 100,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
@@ -43,7 +43,7 @@
|
||||
"yanghao_fallback_enter_live_x": 540,
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_max_wait_seconds": 6.5,
|
||||
"fudai_icon_max_wait_seconds": 7.0,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_exit_after_misses": 7,
|
||||
"enable_back_on_misses": false,
|
||||
@@ -193,9 +193,9 @@
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "detailed",
|
||||
"debug_detail_level": "normal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "detailed",
|
||||
"action_log_format": "concise",
|
||||
"log_format_mode": "simple",
|
||||
"stage_diag_verbose": true,
|
||||
"color_output": true,
|
||||
@@ -259,7 +259,7 @@
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"high_value_fudai_poll_before_seconds": 10.0,
|
||||
"high_value_room_revisit_min_interval_seconds": 300,
|
||||
"high_value_room_revisit_max_per_run": 9999,
|
||||
"high_value_room_revisit_max_per_run": 20,
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
@@ -269,8 +269,234 @@
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"last_wifi_target": {
|
||||
"target": "192.168.10.105:39021",
|
||||
"target": "192.168.10.102:39783",
|
||||
"model": "PEPM00",
|
||||
"saved_at": 1780417101
|
||||
"saved_at": 1782148222
|
||||
},
|
||||
"region_coords_edit_enabled": false,
|
||||
"fudai_detail_body_bluepurple_threshold": 0.45,
|
||||
"fudai_detail_body_dark_threshold": 0.35,
|
||||
"fudai_task_status_template_threshold": 0.26,
|
||||
"fudai_detail_regions": {
|
||||
"legacy": {
|
||||
"content": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"value": [
|
||||
643,
|
||||
1466,
|
||||
769,
|
||||
1656
|
||||
],
|
||||
"countdown_full": [
|
||||
390,
|
||||
1110,
|
||||
690,
|
||||
1230
|
||||
],
|
||||
"task_list": [
|
||||
50,
|
||||
1621,
|
||||
1032,
|
||||
1960
|
||||
],
|
||||
"task_count": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"participants": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"button": [
|
||||
306,
|
||||
2030,
|
||||
780,
|
||||
2180
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_two_task": {
|
||||
"content": [
|
||||
360,
|
||||
1410,
|
||||
1035,
|
||||
1495
|
||||
],
|
||||
"value": [
|
||||
300,
|
||||
1585,
|
||||
650,
|
||||
1685
|
||||
],
|
||||
"countdown_full": [
|
||||
760,
|
||||
1328,
|
||||
1038,
|
||||
1398
|
||||
],
|
||||
"task_list": [
|
||||
60,
|
||||
1840,
|
||||
1030,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
860,
|
||||
1770,
|
||||
1035,
|
||||
1875
|
||||
],
|
||||
"participants": [
|
||||
520,
|
||||
1325,
|
||||
760,
|
||||
1415
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2020,
|
||||
1010,
|
||||
2165
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"content": [
|
||||
360,
|
||||
1460,
|
||||
1035,
|
||||
1545
|
||||
],
|
||||
"value": [
|
||||
350,
|
||||
1640,
|
||||
760,
|
||||
1735
|
||||
],
|
||||
"countdown_full": [
|
||||
700,
|
||||
1390,
|
||||
990,
|
||||
1470
|
||||
],
|
||||
"info_line": [
|
||||
430,
|
||||
1315,
|
||||
1055,
|
||||
1435
|
||||
],
|
||||
"task_list": [
|
||||
61,
|
||||
1845,
|
||||
885,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
889,
|
||||
1855,
|
||||
1040,
|
||||
1960
|
||||
],
|
||||
"participants": [
|
||||
516,
|
||||
1396,
|
||||
743,
|
||||
1443
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2050,
|
||||
1010,
|
||||
2195
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
}
|
||||
},
|
||||
"pixel_regions": {
|
||||
"lottery_result": {
|
||||
"button": [
|
||||
250,
|
||||
1275,
|
||||
825,
|
||||
1435
|
||||
],
|
||||
"pixel": [
|
||||
290,
|
||||
1300,
|
||||
790,
|
||||
1415
|
||||
],
|
||||
"click": [
|
||||
540,
|
||||
1360,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"attend_button": [
|
||||
200,
|
||||
2000,
|
||||
880,
|
||||
2120
|
||||
],
|
||||
"fansclub_join": [
|
||||
200,
|
||||
1940,
|
||||
880,
|
||||
2140
|
||||
],
|
||||
"coupon_popup": [
|
||||
9,
|
||||
1173,
|
||||
1079,
|
||||
2255
|
||||
],
|
||||
"shopping_redpacket": [
|
||||
200,
|
||||
300,
|
||||
880,
|
||||
1400
|
||||
],
|
||||
"fudai_detail_body": [
|
||||
0,
|
||||
1160,
|
||||
1080,
|
||||
2250
|
||||
],
|
||||
"fudai_task_status": [
|
||||
820,
|
||||
1815,
|
||||
1050,
|
||||
2035
|
||||
],
|
||||
"live_room_icon_bbox": [
|
||||
999,
|
||||
172,
|
||||
1028,
|
||||
202
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
{
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"auto_update": {
|
||||
"enabled": true,
|
||||
"manifest_url": "",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"timeout_seconds": 20,
|
||||
"installer_args": [
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 100.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 10,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 20,
|
||||
"reset_after_swipes_action": "swipe",
|
||||
"reenter_live_entry_mode": "screen_center",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 150.0,
|
||||
"high_value_fudai_join_ahead_seconds": 100,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": false,
|
||||
"high_value_room_revisit_only_current_run": false,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.1,
|
||||
"reservation_back_verify_wait_seconds": 3.0,
|
||||
"desktop_icon_x": 153,
|
||||
"desktop_icon_y": 260,
|
||||
"yanghao_fallback_live_x": 540,
|
||||
"yanghao_fallback_live_y": 2000,
|
||||
"yanghao_fallback_enter_live_x": 540,
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_max_wait_seconds": 7.0,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_exit_after_misses": 7,
|
||||
"enable_back_on_misses": false,
|
||||
"fudai_click_wait_seconds": 1.5,
|
||||
"fudai_detail_initial_wait_seconds": 0.8,
|
||||
"fudai_detail_verified_wait_seconds": 0.2,
|
||||
"fudai_detail_retry_delay_seconds": 0.5,
|
||||
"fudai_detail_save_debug_images": true,
|
||||
"fudai_detail_ui_mode": "auto",
|
||||
"fudai_detail_ocr_content_enabled": true,
|
||||
"fudai_detail_ocr_value_enabled": true,
|
||||
"fudai_detail_ocr_countdown_enabled": true,
|
||||
"fudai_detail_ocr_task_enabled": true,
|
||||
"fudai_detail_ocr_task_count_enabled": true,
|
||||
"fudai_detail_ocr_button_enabled": true,
|
||||
"fudai_detail_ocr_participants_enabled": false,
|
||||
"fudai_detail_ocr_live_title_enabled": true,
|
||||
"pixel_detect_fudai_icon_enabled": true,
|
||||
"pixel_detect_coupon_popup_enabled": true,
|
||||
"pixel_detect_shopping_redpacket_enabled": true,
|
||||
"pixel_detect_lottery_result_enabled": true,
|
||||
"pixel_detect_attend_button_enabled": true,
|
||||
"pixel_detect_fansclub_join_enabled": true,
|
||||
"pixel_detect_fudai_detail_enabled": true,
|
||||
"pixel_detect_live_room_enabled": true,
|
||||
"ocr_lottery_result_enabled": true,
|
||||
"ocr_coupon_popup_enabled": true,
|
||||
"ocr_shopping_redpacket_enabled": false,
|
||||
"ocr_stage_page_enabled": true,
|
||||
"fudai_disable_content_recognition": false,
|
||||
"fudai_disable_task_recognition": false,
|
||||
"yanghao_recommend_duration_seconds": 180,
|
||||
"yanghao_recommend_interval_seconds": 600,
|
||||
"yanghao_like_prob": 0.1,
|
||||
"yanghao_fav_prob": 0.05,
|
||||
"yanghao_comment_prob": 0.25,
|
||||
"yanghao_icon_roi_size": 240,
|
||||
"yanghao_icon_match_threshold": 0.77,
|
||||
"yanghao_step_screenshot": true,
|
||||
"yanghao_like_roi_offset_x": 0,
|
||||
"yanghao_like_roi_offset_y": -50,
|
||||
"yanghao_like_roi_scale": 1.0,
|
||||
"yanghao_fav_roi_offset_x": 40,
|
||||
"yanghao_fav_roi_offset_y": 0,
|
||||
"yanghao_fav_roi_scale": 1.0,
|
||||
"yanghao_like_rect_x1": 933,
|
||||
"yanghao_like_rect_y1": 1164,
|
||||
"yanghao_like_rect_x2": 1042,
|
||||
"yanghao_like_rect_y2": 1262,
|
||||
"yanghao_fav_rect_x1": 938,
|
||||
"yanghao_fav_rect_y1": 1567,
|
||||
"yanghao_fav_rect_x2": 1036,
|
||||
"yanghao_fav_rect_y2": 1665,
|
||||
"contains_want": [],
|
||||
"contains_not_want": [
|
||||
"首饰盒",
|
||||
"袜子"
|
||||
],
|
||||
"fudai_quiet_hours_enabled": true,
|
||||
"fudai_quiet_start_hour": 2,
|
||||
"fudai_quiet_end_hour": 9,
|
||||
"yanghao_enabled": false,
|
||||
"yanghao_enable_actions": true,
|
||||
"yanghao_like_icon_x": 988,
|
||||
"yanghao_like_icon_y": 1218,
|
||||
"yanghao_fav_icon_x": 988,
|
||||
"yanghao_fav_icon_y": 1616,
|
||||
"yanghao_like_template_path": "assets/like.png",
|
||||
"yanghao_fav_template_path": "assets/fav.png",
|
||||
"yanghao_after_dwell_swipe_direction": "up",
|
||||
"yanghao_after_dwell_swipe_distance_px": 900,
|
||||
"yanghao_comment_btn_x": 988,
|
||||
"yanghao_comment_btn_y": 1410,
|
||||
"yanghao_dwell_on_action_min_seconds": 5.0,
|
||||
"yanghao_dwell_on_action_max_seconds": 20.0,
|
||||
"yanghao_comment_input_x": 0,
|
||||
"yanghao_comment_input_y": 0,
|
||||
"yanghao_comment_send_x": 0,
|
||||
"yanghao_comment_send_y": -1,
|
||||
"yanghao_comment_close_x": 0,
|
||||
"yanghao_comment_close_y": 0,
|
||||
"yanghao_comment_texts": [
|
||||
"好看!",
|
||||
"赞一个",
|
||||
"真不错",
|
||||
"喜欢这个风格",
|
||||
"太棒了",
|
||||
"很有创意",
|
||||
"支持一下",
|
||||
"笑死我了",
|
||||
"学习了",
|
||||
"被圈粉了",
|
||||
"期待更多",
|
||||
"必须收藏",
|
||||
"这也太治愈了",
|
||||
"质量很高",
|
||||
"简直绝了",
|
||||
"画面太美了",
|
||||
"配色好舒服",
|
||||
"氛围感满分",
|
||||
"做得很用心",
|
||||
"好想试试这个",
|
||||
"安利给朋友",
|
||||
"收藏备用",
|
||||
"太有意思了",
|
||||
"这音乐选得太绝",
|
||||
"太会了",
|
||||
"入坑了",
|
||||
"好惊喜",
|
||||
"真有参考价值",
|
||||
"好暖心的一条",
|
||||
"笑哭,我服了",
|
||||
"细节处理得很好",
|
||||
"太有才了",
|
||||
"看着就治愈",
|
||||
"学习到新方法",
|
||||
"大家都来看看",
|
||||
"点赞支持",
|
||||
"完美",
|
||||
"好看到不行"
|
||||
],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": [],
|
||||
"stage_diag_max_time": 2.0,
|
||||
"stage_diag_max_step_time": 0.5,
|
||||
"live_room_match_threshold": 0.8,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
"lucky_draw_red_ratio_threshold": 0.8,
|
||||
"shopping_redpacket_red_ratio_threshold": 0.2,
|
||||
"y_pianyi": 0,
|
||||
"skip_if_countdown_lt_seconds": 5,
|
||||
"no_attend_timeout_minutes": 30.0,
|
||||
"logging": {
|
||||
"level": "DEBUG",
|
||||
"file_path": "logs/unified.log",
|
||||
"keep_days": 1,
|
||||
"use_dated_logs": true,
|
||||
"rotation": {
|
||||
"enabled": true,
|
||||
"max_bytes": 10485760,
|
||||
"backup_count": 5,
|
||||
"when": "midnight",
|
||||
"interval": 1
|
||||
},
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "normal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "concise",
|
||||
"log_format_mode": "simple",
|
||||
"stage_diag_verbose": true,
|
||||
"color_output": true,
|
||||
"max_log_lines_display": 1000,
|
||||
"auto_scroll_logs": true,
|
||||
"performance_tracking": {
|
||||
"enabled": true,
|
||||
"track_function_calls": true,
|
||||
"track_database_queries": false,
|
||||
"slow_operation_threshold_ms": 100
|
||||
},
|
||||
"error_logging": {
|
||||
"capture_stack_traces": true,
|
||||
"include_context": true,
|
||||
"max_error_logs": 1000,
|
||||
"error_categories": [
|
||||
"ocr",
|
||||
"network",
|
||||
"validation",
|
||||
"system",
|
||||
"user_action"
|
||||
]
|
||||
},
|
||||
"compress_logs": true,
|
||||
"max_total_size_gb": 0.2,
|
||||
"compress_after_days": 1,
|
||||
"max_bytes": 104857600,
|
||||
"backup_count": 10,
|
||||
"enable_monitor": true,
|
||||
"monitor_warning_mb": 60.0,
|
||||
"monitor_critical_mb": 200.0
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"keep_days": 1,
|
||||
"max_files": 1000,
|
||||
"auto_cleanup": true,
|
||||
"async_save": false,
|
||||
"log_on_complete": false
|
||||
},
|
||||
"fudai_detail_template_threshold": 0.52,
|
||||
"switch_room_wait_after_stage_diag_seconds": 7.5,
|
||||
"coupon_template_match_threshold": 0.35,
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"shopping_redpacket_ocr_confidence_threshold": 0.35,
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 250,
|
||||
"gui": {
|
||||
"theme": "litera",
|
||||
"realtime_status": {
|
||||
"refresh_interval_ms": 1000,
|
||||
"tail_items": 50
|
||||
}
|
||||
},
|
||||
"fansclub_click_delay": 0.6,
|
||||
"fansclub_auto_join_wait_seconds": 5.0,
|
||||
"fansclub_manual_wait_seconds": 3.0,
|
||||
"enable_streaming_screenshot": false,
|
||||
"yanghao_only": false,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"high_value_fudai_poll_before_seconds": 10.0,
|
||||
"high_value_room_revisit_min_interval_seconds": 300,
|
||||
"high_value_room_revisit_max_per_run": 20,
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
"swipe_up_end_y": 600,
|
||||
"swipe_down_back_enabled": false,
|
||||
"swipe_down_back_count": 3,
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"region_coords_edit_enabled": false,
|
||||
"fudai_detail_body_bluepurple_threshold": 0.45,
|
||||
"fudai_detail_body_dark_threshold": 0.35,
|
||||
"fudai_task_status_template_threshold": 0.26,
|
||||
"fudai_detail_regions": {
|
||||
"legacy": {
|
||||
"content": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"value": [
|
||||
643,
|
||||
1466,
|
||||
769,
|
||||
1656
|
||||
],
|
||||
"countdown_full": [
|
||||
390,
|
||||
1110,
|
||||
690,
|
||||
1230
|
||||
],
|
||||
"task_list": [
|
||||
50,
|
||||
1621,
|
||||
1032,
|
||||
1960
|
||||
],
|
||||
"task_count": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"participants": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"button": [
|
||||
306,
|
||||
2030,
|
||||
780,
|
||||
2180
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_two_task": {
|
||||
"content": [
|
||||
360,
|
||||
1410,
|
||||
1035,
|
||||
1495
|
||||
],
|
||||
"value": [
|
||||
300,
|
||||
1585,
|
||||
650,
|
||||
1685
|
||||
],
|
||||
"countdown_full": [
|
||||
760,
|
||||
1328,
|
||||
1038,
|
||||
1398
|
||||
],
|
||||
"task_list": [
|
||||
60,
|
||||
1840,
|
||||
1030,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
860,
|
||||
1770,
|
||||
1035,
|
||||
1875
|
||||
],
|
||||
"participants": [
|
||||
520,
|
||||
1325,
|
||||
760,
|
||||
1415
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2020,
|
||||
1010,
|
||||
2165
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"content": [
|
||||
360,
|
||||
1460,
|
||||
1035,
|
||||
1545
|
||||
],
|
||||
"value": [
|
||||
350,
|
||||
1640,
|
||||
760,
|
||||
1735
|
||||
],
|
||||
"countdown_full": [
|
||||
700,
|
||||
1390,
|
||||
990,
|
||||
1470
|
||||
],
|
||||
"info_line": [
|
||||
430,
|
||||
1315,
|
||||
1055,
|
||||
1435
|
||||
],
|
||||
"task_list": [
|
||||
61,
|
||||
1845,
|
||||
885,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
889,
|
||||
1855,
|
||||
1040,
|
||||
1960
|
||||
],
|
||||
"participants": [
|
||||
516,
|
||||
1396,
|
||||
743,
|
||||
1443
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2050,
|
||||
1010,
|
||||
2195
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
}
|
||||
},
|
||||
"pixel_regions": {
|
||||
"lottery_result": {
|
||||
"button": [
|
||||
250,
|
||||
1275,
|
||||
825,
|
||||
1435
|
||||
],
|
||||
"pixel": [
|
||||
290,
|
||||
1300,
|
||||
790,
|
||||
1415
|
||||
],
|
||||
"click": [
|
||||
540,
|
||||
1360,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"attend_button": [
|
||||
200,
|
||||
2000,
|
||||
880,
|
||||
2120
|
||||
],
|
||||
"fansclub_join": [
|
||||
200,
|
||||
1940,
|
||||
880,
|
||||
2140
|
||||
],
|
||||
"coupon_popup": [
|
||||
9,
|
||||
1173,
|
||||
1079,
|
||||
2255
|
||||
],
|
||||
"shopping_redpacket": [
|
||||
200,
|
||||
300,
|
||||
880,
|
||||
1400
|
||||
],
|
||||
"fudai_detail_body": [
|
||||
0,
|
||||
1160,
|
||||
1080,
|
||||
2250
|
||||
],
|
||||
"fudai_task_status": [
|
||||
820,
|
||||
1815,
|
||||
1050,
|
||||
2035
|
||||
],
|
||||
"live_room_icon_bbox": [
|
||||
999,
|
||||
172,
|
||||
1028,
|
||||
202
|
||||
]
|
||||
},
|
||||
"license": {
|
||||
"activation_url": "https://dy.absfan.cn/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
# 全量安全审计报告(2026-06-28)
|
||||
|
||||
## 结论摘要
|
||||
|
||||
本次审计覆盖客户端授权、自动更新、差量更新、服务端卡密/API、后台发布、WebGUI、本地打包、CI/CD 和仓库敏感信息暴露面。总体判断:
|
||||
|
||||
- 授权与更新主链路已有基础可信链:服务端签名授权/更新 manifest,客户端只内置公钥并校验 manifest 签名与文件 SHA256 后再执行更新。
|
||||
- 当前最需要优先修的是服务端发布面与分发面:后台 token 权限过大、上传包一次性读入内存、下载包直出服务端。
|
||||
- WebGUI 默认本机监听、POST 有 CSRF、未授权时拦截运行类接口,基础边界合理;但安全响应头和 CSP 仍缺失。
|
||||
- 打包已包含 Cython/分发清单/新环境冒烟测试,但依赖安装仍是浮动版本,正式发布需要锁版本、记录 SBOM,并加入签名校验。
|
||||
|
||||
## 审计范围
|
||||
|
||||
- 服务端:`license_server/api.py`、`license_server/core.py`、`license_server/requirements.txt`、`license_server/docker-compose.yml`、`license_server/Dockerfile`
|
||||
- 客户端授权:`douyin/license/license_manager.py`、`douyin/license/public_key.py`
|
||||
- 自动更新:`douyin/updater/force_update.py`、`douyin/updater/bootstrap.py`、`tools/update_delta.py`
|
||||
- WebGUI:`gui/web_gui.py`、`gui/web_gui_pkg/*`、`webui/**/*`
|
||||
- 打包与 CI:`packaging/pyinstaller/build_windows.ps1`、`.github/workflows/windows-package-ci.yml`、`tools/ci/fresh_install_smoke.ps1`
|
||||
- 仓库敏感信息:源代码、文档、测试、配置模板,排除 `artifacts/`、`dist/`、`build/`、`output/`、`logs/` 等生成物。
|
||||
|
||||
## 高风险
|
||||
|
||||
### H1. 后台发布权限仍集中在单个 admin token
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:118-139` 中 `_admin_allowed()` 接受三种管理员凭据:Session Cookie、`Bearer <token>`、Basic Auth 密码。
|
||||
- `license_server/api.py:823-873` 的全量包和差量包发布接口只要通过管理员鉴权和 CSRF 即可发布更新。
|
||||
|
||||
影响:
|
||||
|
||||
- 一旦 `DYGJ_LICENSE_ADMIN_TOKEN` 泄露,攻击者可以发布全量安装包或差量包。
|
||||
- 现有 manifest 签名能防止“客户端绕过服务端伪造更新”,但不能防止“拿到后台权限后用合法服务端签名发布恶意更新”。
|
||||
|
||||
建议:
|
||||
|
||||
- 立即轮换历史 admin token,清理桌面、聊天临时目录、部署机器 shell history 中的明文 token。
|
||||
- 将“登录后台”和“发布更新”拆成两级权限:普通后台 token 不能发布更新,发布更新需要短时一次性 publish token 或 TOTP。
|
||||
- 发布接口加 IP 白名单、审计日志、版本回滚记录和人工确认。
|
||||
- 正式包必须做 Authenticode 签名,客户端启动安装器前校验发行者证书指纹。
|
||||
|
||||
### H2. 后台上传全量包/差量包会一次性读入内存
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:835` 对安装包执行 `content = await installer.read()`。
|
||||
- `license_server/api.py:862` 对差量包执行 `content = await delta_file.read()`。
|
||||
- `license_server/core.py:555-588` 的 `publish_update()` 接收完整 `bytes` 后写盘。
|
||||
- `license_server/core.py:590-624` 的 `publish_delta_update()` 同样接收完整 `bytes` 后写盘。
|
||||
|
||||
影响:
|
||||
|
||||
- 大文件或异常 multipart 请求会直接放大服务端内存压力。
|
||||
- 管理员误操作、token 泄露或代理层限流配置缺失时,容易造成授权服务器不可用。
|
||||
|
||||
建议:
|
||||
|
||||
- 上传接口加显式大小上限,例如全量包 500MB、差量包 200MB,超限立即拒绝。
|
||||
- 改成流式写入临时文件,并边写边计算 SHA256。
|
||||
- 反向代理加 `client_max_body_size` / request body size limit。
|
||||
- 发布前校验文件类型、扩展名、hash、版本号和可执行文件签名。
|
||||
|
||||
### H3. 更新包下载由授权服务直接 `FileResponse` 暴露
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:681-698` 使用 `FileResponse` 直接返回全量包或差量包。
|
||||
- `license_server/api.py:686-690` 已限制只能下载当前 manifest 允许的文件名,这是正向控制。
|
||||
|
||||
影响:
|
||||
|
||||
- 安装包/差量包通常较大,未加下载鉴权、限速或 CDN 时,服务端可被下载流量拖垮。
|
||||
- Starlette `FileResponse` 是真实攻击面。外部公告显示,历史上 Starlette `FileResponse` Range 处理出现过 CPU DoS(CVE-2025-62727,修复于 0.49.1),multipart/form-data 也出现过内存 DoS(CVE-2024-47874,修复于 0.40.0)。
|
||||
- 当前本机 Starlette 为 `1.3.1`,不落在上述受影响范围内;但生产环境如果不锁版本,仍存在依赖漂移和部署不可复现风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 更新包放对象存储/CDN,授权服务只签发短期下载 URL。
|
||||
- 服务端保留 manifest 和授权 API,不承担大文件分发。
|
||||
- 若继续直出文件,固定 `starlette>=0.49.1`,并在依赖扫描中阻断已知 CVE。
|
||||
|
||||
## 中风险
|
||||
|
||||
### M1. 生产环境 Host header 仍依赖配置自觉
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:245-249`:未设置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时,manifest 下载 URL 从 `request.base_url` 推导。
|
||||
- `license_server/api.py:484-499`:创建 FastAPI app 时未添加 `TrustedHostMiddleware`。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果生产代理透传恶意 Host,且未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL`,生成的 manifest 下载链接可能被 Host header 污染。
|
||||
- 客户端有 HTTPS、同源、签名和 SHA256 校验,能降低恶意包执行风险;但错误下载源仍会造成更新失败或服务可用性问题。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产环境强制要求 `DYGJ_LICENSE_PUBLIC_BASE_URL`,缺失即启动失败。
|
||||
- 加 `TrustedHostMiddleware`,只允许正式域名和本地健康检查域名。
|
||||
- 在部署文档中明确 Nginx/Cloudflare 的 Host 转发策略。
|
||||
|
||||
### M2. 管理后台 Cookie 默认未开启 Secure
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:495` 中 `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`。
|
||||
- `license_server/api.py:706-712` 和 `license_server/api.py:733-740` 根据该开关设置 CSRF Cookie 和后台 Session Cookie 的 `secure`。
|
||||
|
||||
影响:
|
||||
|
||||
- 生产 HTTPS 场景如果忘记设置环境变量,后台 Cookie 不带 Secure 标记。
|
||||
- `HttpOnly` 和 `SameSite=Lax` 已存在,风险主要来自生产配置遗漏。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产模式默认 Secure=true,开发模式才允许关闭。
|
||||
- 启动时检测 `DYGJ_LICENSE_PUBLIC_BASE_URL` 为 `https://` 时强制 Secure Cookie。
|
||||
|
||||
### M3. 客户端执行安装器前缺少 Authenticode 校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:143-158` 会校验 manifest 签名。
|
||||
- `douyin/updater/force_update.py:556-566` 校验安装包 SHA256 后直接构造命令并启动安装器。
|
||||
- 当前未看到对 Windows Authenticode 签名、发行者证书指纹或时间戳的校验。
|
||||
|
||||
影响:
|
||||
|
||||
- SHA256 只能证明“下载到的文件与签名 manifest 中声明一致”。
|
||||
- 如果服务端私钥或发布后台被攻破,攻击者仍可能发布一个“合法签名 manifest + 恶意 exe”。
|
||||
|
||||
建议:
|
||||
|
||||
- 正式发布包使用 Authenticode 签名。
|
||||
- 客户端在 `launch_installer()` 前验证 exe 签名主体和证书指纹。
|
||||
- CI/CD 记录签名证书指纹、安装包 SHA256 和 SBOM。
|
||||
|
||||
### M4. 差量更新应用脚本缺少二次解包后校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:318-356` 下载后会校验差量包 manifest、文件路径和每个文件 SHA256。
|
||||
- `douyin/updater/force_update.py:434-463` 真正应用更新时,PowerShell `Expand-Archive` 后直接按 manifest 删除/复制文件。
|
||||
|
||||
影响:
|
||||
|
||||
- 主进程校验和应用更新是两个阶段,中间若本地文件被替换,应用脚本不会再次校验。
|
||||
- 对普通用户机器来说攻击门槛较高,但对本地恶意软件或被篡改的更新目录仍是风险点。
|
||||
|
||||
建议:
|
||||
|
||||
- 在 PowerShell 应用脚本里二次校验 delta zip SHA256,解包后再校验 manifest 中每个文件 SHA256。
|
||||
- 应用前将 `$root`、`$work`、目标路径做规范化并确认都在安装目录内。
|
||||
|
||||
### M5. WebGUI 缺少安全响应头和 CSP
|
||||
|
||||
证据:
|
||||
|
||||
- `gui/web_gui_pkg/static_handler.py:67-73` 只设置 `Content-Type`、`Content-Length`、`Cache-Control`、`ETag`。
|
||||
- `gui/web_gui_pkg/routes.py:161-169` GET API 仅允许本机访问并暴露 CSRF token。
|
||||
- `gui/web_gui_pkg/routes.py:389-399` POST API 有本机限制、CSRF 校验和授权门禁。
|
||||
|
||||
影响:
|
||||
|
||||
- WebGUI 默认 `127.0.0.1` 监听,且 POST 有 CSRF,基础边界是好的。
|
||||
- 但没有 `Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy` 等安全头;一旦未来某个日志/接口字段进入 DOM 时漏转义,XSS 的后果会扩大到本机控制面。
|
||||
|
||||
建议:
|
||||
|
||||
- 给 HTML/JS 响应加安全头:`X-Content-Type-Options: nosniff`、`Referrer-Policy: no-referrer`、最小 CSP。
|
||||
- 逐步减少内联脚本,或者使用 nonce/hash CSP。
|
||||
|
||||
## 低风险与观察项
|
||||
|
||||
### L1. 前端使用 `innerHTML` 较多,但核心动态数据大多已转义
|
||||
|
||||
证据:
|
||||
|
||||
- `webui/js/dom_utils.js:83-90` 提供 `escapeHtml()`。
|
||||
- `webui/js/runtime_actions.js:318-325`、`360-372`、`441-454` 对直播间、内容、原因等 API 字段使用 `escapeHtml()`。
|
||||
- `webui/js/dashboard_renderers.js:65-110` 对榜单 key、中奖内容、时间和值做了转义。
|
||||
- `license_server/api.py:667` 的兑换页把 `data.card_key` 拼入 `innerHTML`,卡密格式由服务端生成,当前风险较低。
|
||||
|
||||
建议:
|
||||
|
||||
- 新增 ESLint/简单 grep 门禁:所有拼接 API 数据的 `innerHTML` 必须经过 `escapeHtml()` 或改用 `textContent`。
|
||||
- 兑换页成功展示卡密可改为创建 `code` 节点并设置 `textContent`。
|
||||
|
||||
### L2. CI/CD 依赖安装未锁定 hash
|
||||
|
||||
证据:
|
||||
|
||||
- `.github/workflows/windows-package-ci.yml:42-44` 使用 `pip install -r requirements.txt` 和未固定的 `pyinstaller cython setuptools wheel`。
|
||||
- `packaging/pyinstaller/build_windows.ps1:31-38` 本地打包也会安装浮动版本依赖。
|
||||
- `license_server/requirements.txt:1-4` 使用 `>=` 范围。
|
||||
|
||||
影响:
|
||||
|
||||
- 复用缓存打包时结果可能随 PyPI 最新版本变化。
|
||||
- 安全修复会自动进来,但也可能引入供应链回归或打包不一致。
|
||||
|
||||
建议:
|
||||
|
||||
- 增加 `requirements-lock.txt` / `constraints.txt`,正式打包用锁定版本。
|
||||
- CI 增加 `pip-audit` 或 GitHub Dependabot,发现高危 CVE 直接失败。
|
||||
- 发布产物附带 SBOM、SHA256 和构建日志。
|
||||
|
||||
### L3. 仓库未发现真实私钥明文,但历史 token 文档仍提示需要清理本机副本
|
||||
|
||||
证据:
|
||||
|
||||
- 敏感信息扫描未发现真实生产私钥 PEM;测试私钥仅在 `tests/` 中使用。
|
||||
- `license_server/api.py:86-93` 生产私钥从环境变量或服务器文件读取。
|
||||
- 旧审计文档中记录过桌面存在多个 admin token 明文副本,需要按运维动作清理。
|
||||
|
||||
建议:
|
||||
|
||||
- 本机和服务器执行 token 文件清理,并确认 `.gitignore` 覆盖 `secrets/`、`*.pem`、`admin_token*.txt`。
|
||||
- 把生产 secret 全部放服务器 secret 管理或部署平台环境变量,不放桌面、微信临时目录和仓库。
|
||||
|
||||
## 已有保护点
|
||||
|
||||
- 授权文件签名:`license_server/core.py:872-889` 服务端签名授权,客户端使用公钥验签。
|
||||
- 机器码只保存 hash:`douyin/license/license_manager.py:66-76` 本机指纹 hash 化。
|
||||
- 在线复核:`douyin/license/license_manager.py:260-340` 使用服务器状态复核本地授权。
|
||||
- 更新 manifest 签名:`license_server/core.py:656-658` 服务端签名,`douyin/updater/force_update.py:143-158` 客户端验签。
|
||||
- 更新下载约束:`douyin/updater/force_update.py:212-237` 要求 HTTPS 和同源,除非配置允许跨源。
|
||||
- 更新文件完整性:`douyin/updater/force_update.py:547-563` 校验全量包 SHA256,`318-356` 校验差量包路径和文件 SHA256。
|
||||
- WebGUI 本机限制与 CSRF:`gui/web_gui_pkg/routes.py:57-62`、`389-399`。
|
||||
- 首次授权门禁:`gui/web_gui.py:912-918` 未授权时不直接进入运行态,`tools/ci/fresh_install_smoke.ps1:180-239` 已覆盖新环境授权门禁冒烟。
|
||||
- 打包分发清单:`packaging/pyinstaller/build_windows.ps1:55-63` 默认 Cython/PyArmor staging,`270-287` 执行 distribution manifest 检查。
|
||||
|
||||
## 依赖与外部公告核对
|
||||
|
||||
本机当前版本:
|
||||
|
||||
- `fastapi==0.137.2`
|
||||
- `starlette==1.3.1`
|
||||
- `uvicorn==0.49.0`
|
||||
- `python-multipart==0.0.32`
|
||||
- `cryptography==47.0.0`
|
||||
- `PyInstaller==6.12.0`
|
||||
|
||||
外部公告核对:
|
||||
|
||||
- Starlette multipart/form-data DoS:GHSA-f96h-pmfr-66vw / CVE-2024-47874,Starlette `0.40.0` 修复。
|
||||
- Starlette FileResponse Range DoS:GHSA-7f5h-v6xp-fcq8 / CVE-2025-62727,Starlette `0.49.1` 修复。
|
||||
- 当前本机 Starlette `1.3.1` 高于上述修复版本;生产仍建议锁版本并加入自动漏洞扫描。
|
||||
|
||||
## 修复优先级
|
||||
|
||||
1. 轮换 admin token,清理本机和服务器明文 token,后台发布增加二次授权。
|
||||
2. 上传接口改流式写入并加大小限制,反向代理同步限流。
|
||||
3. 更新包改 CDN/对象存储分发,授权服务只发短期 URL。
|
||||
4. 正式包 Authenticode 签名,客户端校验证书指纹后再启动安装器。
|
||||
5. 生产强制 `DYGJ_LICENSE_PUBLIC_BASE_URL`、`TrustedHostMiddleware`、Secure Cookie。
|
||||
6. WebGUI 加安全响应头和 CSP,继续收敛 `innerHTML`。
|
||||
7. CI/CD 增加锁版本、SBOM、pip-audit/Dependabot。
|
||||
|
||||
## 本次验证
|
||||
|
||||
- `git status --short --branch`:工作区除用户本地 `config/config.json` 外无其他未提交改动。
|
||||
- 静态证据扫描:授权、服务端 API、更新、WebGUI、打包、CI 均完成。
|
||||
- 敏感信息扫描:未发现生产私钥 PEM;扫描到的 `secret` 主要位于测试用例和历史审计文档。
|
||||
- 依赖版本核对:本机 Starlette/FastAPI 版本高于已核对 Starlette DoS 修复版本。
|
||||
|
||||
## 参考资料
|
||||
|
||||
- GitHub Advisory:Starlette multipart/form-data DoS,GHSA-f96h-pmfr-66vw,https://github.com/advisories/GHSA-f96h-pmfr-66vw
|
||||
- GitHub Advisory:Starlette FileResponse Range DoS,GHSA-7f5h-v6xp-fcq8,https://github.com/advisories/GHSA-7f5h-v6xp-fcq8
|
||||
- Starlette Release Notes,https://www.starlette.io/release-notes/
|
||||
- Starlette Responses 文档:`FileResponse` 支持 Range 请求,https://www.starlette.io/responses/
|
||||
@@ -0,0 +1,228 @@
|
||||
# 全量安全审查报告
|
||||
|
||||
日期:2026-06-23
|
||||
|
||||
审查方式:结合 `security-best-practices`、`security-threat-model`、`code-review-and-quality` 思路,对客户端、本地 Web GUI、卡密服务端、自动更新、打包分发和 Git/配置暴露面做静态审查与最小运行验证。
|
||||
|
||||
## 结论
|
||||
|
||||
当前版本已经具备一批关键安全地基:客户端默认走 `https://dy.absfan.cn`,自动更新 manifest 有签名和安装包 sha256 校验;卡密服务使用服务端时间和 SQLite 参数化查询;后台登录使用 HttpOnly 会话 cookie 与 CSRF;本地 Web GUI 默认只监听 `127.0.0.1`;当前 tracked 文件未发现服务器真实 IP、私钥或管理员 token 明文。
|
||||
|
||||
但仍有 5 个需要优先处理的风险:
|
||||
|
||||
- P0:Git 历史提交里仍可检索到服务器源站 IP 字面量,若仓库外发或公开,历史会继续泄露源站。
|
||||
- P1:服务端限流信任客户端传入的 `x-forwarded-for`,可能被绕过并造成 rate-limit bucket 增长。
|
||||
- P1:后台登录未接入限流/锁定;同时仍保留 Bearer/Basic token 后门入口,公网后台暴露时爆破面偏大。
|
||||
- P1:后台发布更新时一次性 `await installer.read()` 读取上传文件,缺少上传大小限制,可能导致内存或磁盘 DoS。
|
||||
- P1:本地 Web GUI 虽默认本机监听,但一旦配置成 `0.0.0.0`,WiFi ADB、启动/停止、日志读取等接口没有二次认证。
|
||||
|
||||
## 范围与资产
|
||||
|
||||
核心资产:
|
||||
|
||||
- 卡密数据库、激活记录、审计记录。
|
||||
- 服务端私钥、管理员 token、更新安装包、更新 manifest。
|
||||
- 客户端内置公钥、授权文件、本地配置。
|
||||
- 本地 Web GUI 对 ADB、设备、日志和运行进程的控制能力。
|
||||
|
||||
主要入口:
|
||||
|
||||
- 公网:`/api/v1/activate`、`/api/v1/verify_license`、`/api/v1/update/manifest`、`/api/v1/update/download/{filename}`、`/admin/*`。
|
||||
- 本机:`/api/wifi/*`、`/api/config`、日志/运行控制相关 Web GUI 接口。
|
||||
- 分发:PyInstaller/安装包、自动更新下载的 EXE。
|
||||
|
||||
## 已有安全控制
|
||||
|
||||
- 客户端默认更新地址是 `https://dy.absfan.cn/api/v1/update/manifest`。
|
||||
- 自动更新默认要求 manifest 签名,安装包 URL 默认同源,安装包下载后做 sha256 校验。
|
||||
- 服务端 license 和 update manifest 使用 Ed25519 签名。
|
||||
- SQLite 操作使用参数化 SQL,未看到直接字符串拼接 SQL 的主路径。
|
||||
- 后台登录成功后写入 HttpOnly、SameSite=Lax 的 session cookie,后台写操作有 CSRF token。
|
||||
- 卡密校验以服务器端激活记录和服务端时间为准,客户端本地时间不能直接绕过在线校验。
|
||||
- 本地 Web GUI 默认监听 `127.0.0.1:8000`,不是默认公网暴露。
|
||||
- 当前 tracked 文件扫描未发现真实源站 IP、服务器密码、管理员 token、私钥 PEM。
|
||||
|
||||
## 发现与建议
|
||||
|
||||
### P0-1 Git 历史仍包含源站 IP
|
||||
|
||||
证据:
|
||||
|
||||
- 当前 tracked 文件未命中真实源站 IP、管理员 token 或私钥。
|
||||
- `git log --all -S` 仍能在历史提交中找到源站 IP 字面量,涉及提交包括 `25876bd`、`0efdc83`、`5c7d341`、`cb74a23` 等。
|
||||
|
||||
影响:
|
||||
|
||||
- 即使当前代码改成域名,仓库被发给别人或推到公开仓库时,历史仍会暴露源站。
|
||||
- 攻击者可绕过域名层防护,直接打源站端口或做扫描。
|
||||
|
||||
建议:
|
||||
|
||||
- 若仓库已经外发或公开:立即做 Git 历史改写,清除源站 IP、旧 server 默认值和任何敏感片段,然后 force push。
|
||||
- 同步轮换公网源站或至少限制源站只接受可信代理/防火墙来源。
|
||||
- 报告、文档、提交信息里后续只写域名或 `[REDACTED_ORIGIN]`。
|
||||
|
||||
### P1-1 限流信任 `x-forwarded-for`
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:182-185` 使用请求头 `x-forwarded-for` 第一段作为限流 key。
|
||||
- `_rate_limited` 对 activate、verify_license 生效,但 bucket key 由该 header 决定。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果反代/CDN 未强制覆盖该 header,客户端可以伪造不同 IP 绕过限流。
|
||||
- 大量伪造 header 会让 `rate_limit_buckets` 增长,形成内存型 DoS。
|
||||
|
||||
建议:
|
||||
|
||||
- 只在请求来自可信代理 IP 时读取 `x-forwarded-for`,否则使用 `request.client.host`。
|
||||
- 增加 bucket 总量上限和周期性清理。
|
||||
- 部署层确保反代覆盖而不是透传用户自带的 XFF。
|
||||
|
||||
### P1-2 后台登录缺少限流/锁定,且保留多种 token 入口
|
||||
|
||||
证据:
|
||||
|
||||
- `/admin/login` 在 `license_server/api.py:492-497` 直接比较 token,失败返回 403,未调用 `_rate_limited`。
|
||||
- `_admin_allowed` 在 `license_server/api.py:88-109` 同时接受 session cookie、Bearer token、Basic auth。
|
||||
|
||||
影响:
|
||||
|
||||
- 公网后台可被持续爆破或撞库,尤其管理员 token 如果不够长会变成高风险。
|
||||
- Bearer/Basic 让 token 更容易出现在代理日志、浏览器插件、命令历史或误贴日志中。
|
||||
|
||||
建议:
|
||||
|
||||
- 给 `/admin/login` 加 IP + 用户维度限流、指数退避和失败审计。
|
||||
- 默认禁用 Basic auth;Bearer token 仅保留给受控 CLI,或通过环境变量显式开启。
|
||||
- 管理员 token 要求至少 32 字节随机值,并增加启动时弱 token 检查。
|
||||
|
||||
### P1-3 更新发布上传无大小限制
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:586-606` 中 `UploadFile` 直接 `await installer.read()`,随后写入发布目录。
|
||||
- 未见文件大小、后缀白名单、Content-Length 上限或流式落盘控制。
|
||||
|
||||
影响:
|
||||
|
||||
- 管理员误操作、token 泄露或 CSRF 以外的后台入口被利用时,可以上传超大文件导致内存、磁盘或进程不可用。
|
||||
- 更新发布链路是高权限供应链入口,风险高于普通文件上传。
|
||||
|
||||
建议:
|
||||
|
||||
- 增加最大上传大小,例如 300 MB 或按实际安装包体积上限配置。
|
||||
- 使用流式写临时文件,边读边计算 sha256,超限立即中断并删除临时文件。
|
||||
- 限制后缀为 `.exe`,发布前校验 Windows Authenticode 签名或至少校验内部版本号。
|
||||
|
||||
### P1-4 本地 Web GUI 非 localhost 暴露时缺少认证
|
||||
|
||||
证据:
|
||||
|
||||
- 默认监听 `127.0.0.1`:`douyin/core/path_config.py:31`。
|
||||
- 环境变量或配置可覆盖 host:`douyin/core/path_config.py:96-103`。
|
||||
- Web GUI 暴露 WiFi ADB 启用、连接、断开、扫描和自动重连:`gui/web_gui_pkg/routes.py:717-824`、`863-940`。
|
||||
|
||||
影响:
|
||||
|
||||
- 默认本机使用问题不大。
|
||||
- 如果用户为了局域网访问改成 `0.0.0.0`,同网段其他人可未授权控制 ADB 连接、扫描局域网、读取部分状态或影响挂机运行。
|
||||
|
||||
建议:
|
||||
|
||||
- 当 host 不是 localhost 时强制启用 Web GUI token。
|
||||
- 对 `/api/wifi/*`、运行控制、配置写入、日志读取加认证。
|
||||
- UI 上显示“当前监听地址”和“局域网暴露风险”。
|
||||
|
||||
### P2-1 HTTPS 开关默认逻辑不够稳
|
||||
|
||||
证据:
|
||||
|
||||
- 默认 manifest URL 是 HTTPS:`douyin/updater/force_update.py:31`。
|
||||
- frozen 默认 manifest 下 `require_https` 默认值为 `not using_default_manifest`,即默认 false:`douyin/updater/force_update.py:192-195`。
|
||||
- 同时默认签名是开启的。
|
||||
|
||||
影响:
|
||||
|
||||
- 当前域名是 HTTPS,实际链路可用。
|
||||
- 但“默认 manifest 不强制 HTTPS”的逻辑容易在以后改默认地址时退化,签名不能完全替代传输层保护。
|
||||
|
||||
建议:
|
||||
|
||||
- `require_https` 默认始终为 true,除非显式开发环境关闭。
|
||||
- 对自动更新增加环境分层:dev 可放宽,release 必须 HTTPS + signed manifest + sha256。
|
||||
|
||||
### P2-2 license 和 update manifest 共用签名密钥
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/core.py:444-446` 提供通用 `sign_payload`。
|
||||
- license 文档签名在 `license_server/core.py:626-644`,update manifest 也由同一服务私钥签名。
|
||||
|
||||
影响:
|
||||
|
||||
- 单一私钥泄露会同时影响授权文件与更新供应链。
|
||||
- 后续密钥轮换时两个系统耦合,恢复复杂。
|
||||
|
||||
建议:
|
||||
|
||||
- 分离 license signing key 与 update signing key。
|
||||
- 客户端分别内置 license public key 和 update public key,支持 key id 与滚动轮换。
|
||||
|
||||
### P2-3 依赖版本没有锁定
|
||||
|
||||
证据:
|
||||
|
||||
- `requirements.txt` 多数依赖使用 `>=`,例如 `Pillow>=9.0.0`、`opencv-python>=4.5.0`、`cryptography>=41.0.0`。
|
||||
|
||||
影响:
|
||||
|
||||
- 构建复现性弱,新版本依赖可能引入兼容问题或供应链风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 为 release 打包生成锁定文件,例如 `requirements-lock.txt` 或 `pip-tools` 输出。
|
||||
- CI/打包只使用锁定依赖,开发环境可继续宽松。
|
||||
|
||||
### P2-4 shell 调用需要继续收敛
|
||||
|
||||
证据:
|
||||
|
||||
- 聚焦扫描显示存在若干 `subprocess.run`/`Popen`,多数 ADB 调用为列表参数。
|
||||
- 仍存在少量 `shell=True` 或 `/bin/sh -c` 用法,主要用于平台命令探测或 ADB 降级路径。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果参数未来从 UI 或配置直通,可能扩大命令注入风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 对所有 `shell=True` 建立 allowlist,逐个替换成 list 参数。
|
||||
- 对确实需要 shell 的命令增加注释和单元测试覆盖。
|
||||
|
||||
## 验证
|
||||
|
||||
已执行:
|
||||
|
||||
- `python -m pytest tests/test_license_server_api.py tests/test_license_server_core.py tests/test_license_manager.py tests/test_auto_update.py tests/test_web_gui_routes_logic.py -q`
|
||||
- 结果:PASS。
|
||||
- 日志:`artifacts/security_audit_tests.log`。
|
||||
|
||||
公网最小验证:
|
||||
|
||||
- `https://dy.absfan.cn/api/v1/health` 返回 `{"ok": true, "service": "douyin-license-server"}`。
|
||||
- `https://dy.absfan.cn/api/v1/update/manifest` 返回 `enabled=false`、`version=0.0.0`,并包含签名字段。
|
||||
|
||||
当前 secret 扫描:
|
||||
|
||||
- tracked 文件未发现真实源站 IP、私钥 PEM、管理员 token、服务器密码明文。
|
||||
- Git 历史仍包含源站 IP,需要单独处理。
|
||||
|
||||
## 建议修复顺序
|
||||
|
||||
1. 先修服务端 P1:可信代理 IP/XFF、后台登录限流、上传大小限制、Secure cookie。
|
||||
2. 再修本地 P1:Web GUI 非 localhost 强制 token,敏感接口鉴权。
|
||||
3. 然后做 P0 历史清理:确认仓库是否已外发/公开,必要时 history rewrite + force push + 源站访问限制。
|
||||
4. 最后做供应链增强:分离签名密钥、release 依赖锁定、自动更新 HTTPS 强制。
|
||||
|
||||
@@ -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。
|
||||
@@ -77,20 +77,23 @@ def _close_wrong_fudai_target(
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.click_back(device_id)
|
||||
except Exception:
|
||||
stage_text = str(stage or "")
|
||||
if stage_text in ("IN_LIVE_ROOM", "UNKNOWN", ""):
|
||||
try:
|
||||
analyser.operation.back(device_id)
|
||||
analyser._log_kv(
|
||||
"流程",
|
||||
"find_and_open_fudai_detail:误入口仍处于直播间,不执行关闭点击或返回键",
|
||||
stage=stage_text,
|
||||
decision="skip_close_action_same_live_room",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
analyser.operation.click_back(device_id)
|
||||
except Exception:
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
analyser.operation.click(
|
||||
device_id,
|
||||
int(520 * rx / 1080),
|
||||
int(505 * ry / 2400),
|
||||
)
|
||||
analyser.operation.back(device_id)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
|
||||
@@ -518,16 +518,22 @@ def step4_make_join_decision(
|
||||
remain_seconds = int(future_timestamp - current_time)
|
||||
|
||||
if remain_seconds > 0:
|
||||
try:
|
||||
current_prize_value = float(detail[4] or 0.0)
|
||||
except Exception:
|
||||
current_prize_value = 0.0
|
||||
# 设置等待开奖标志和预期开奖时间
|
||||
self._waiting_for_lottery_result = True
|
||||
self._lottery_result_expected_ts = future_timestamp
|
||||
self._lottery_wait_start_ts = time.time()
|
||||
self._lottery_wait_prize_value_yuan = current_prize_value
|
||||
|
||||
self._log_kv(
|
||||
"参与",
|
||||
"参与成功,设置等待开奖标志,停止其他行为",
|
||||
remain_seconds=remain_seconds,
|
||||
future_ts=int(future_timestamp),
|
||||
prize_value_yuan=current_prize_value,
|
||||
)
|
||||
|
||||
# 检查是否是预约福袋,如果是处理锁定期和移除预约
|
||||
|
||||
@@ -179,6 +179,7 @@ def apply_fudai_defaults(self: Any) -> None:
|
||||
self._fudai_detail_consecutive_failures = 0
|
||||
self._detail_closed_by_attend = False
|
||||
self._lottery_result_expected_ts = 0.0
|
||||
self._lottery_wait_prize_value_yuan = 0.0
|
||||
self._lottery_wait_start_ts = 0.0
|
||||
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float)
|
||||
if current_ts >= timeout_ts:
|
||||
self._waiting_for_lottery_result = False
|
||||
self._current_attending_reservation_fudai = False
|
||||
self._lottery_wait_prize_value_yuan = 0.0
|
||||
timeout_seconds = int(current_ts - future_ts)
|
||||
self._log_kv(
|
||||
"参与",
|
||||
@@ -107,6 +108,7 @@ def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float)
|
||||
if result:
|
||||
self._waiting_for_lottery_result = False
|
||||
self._current_attending_reservation_fudai = False
|
||||
self._lottery_wait_prize_value_yuan = 0.0
|
||||
try:
|
||||
self._log_kv(
|
||||
"参与",
|
||||
@@ -151,6 +153,7 @@ def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float)
|
||||
|
||||
self._waiting_for_lottery_result = False
|
||||
self._current_attending_reservation_fudai = False
|
||||
self._lottery_wait_prize_value_yuan = 0.0
|
||||
try:
|
||||
self._log_kv(
|
||||
"参与",
|
||||
@@ -192,6 +195,7 @@ def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float)
|
||||
self._log_kv("参与", "等待开奖检测时出错", error=str(exc))
|
||||
self._waiting_for_lottery_result = False
|
||||
self._current_attending_reservation_fudai = False
|
||||
self._lottery_wait_prize_value_yuan = 0.0
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,26 @@ if TYPE_CHECKING:
|
||||
from ..douyin_fudai import fudai_analyse
|
||||
|
||||
|
||||
def _safe_float_attr(obj, name: str, default: float) -> float:
|
||||
try:
|
||||
value = getattr(obj, name, default)
|
||||
if not isinstance(value, (int, float, str)):
|
||||
return float(default)
|
||||
return float(value if value is not None else default)
|
||||
except Exception:
|
||||
return float(default)
|
||||
|
||||
|
||||
def _safe_int_attr(obj, name: str, default: int) -> int:
|
||||
try:
|
||||
value = getattr(obj, name, default)
|
||||
if not isinstance(value, (int, float, str)):
|
||||
return int(default)
|
||||
return int(value if value is not None else default)
|
||||
except Exception:
|
||||
return int(default)
|
||||
|
||||
|
||||
def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool:
|
||||
"""0.1 高价值预约检查:清空队列 / 处理队列已满 / 调 process_reservation_attend_window。"""
|
||||
try:
|
||||
@@ -218,14 +238,18 @@ def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) ->
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
max_reservations = int(getattr(self, "high_value_fudai_max_reservations", 3) or 3)
|
||||
if getattr(self, "_waiting_for_lottery_result", False):
|
||||
if not _should_allow_reservation_preempt_waiting_lottery(self):
|
||||
return False
|
||||
|
||||
max_reservations = _safe_int_attr(self, "high_value_fudai_max_reservations", 3)
|
||||
if len(self.reservations) >= max_reservations and not self.queue_full_waiting_at_earliest:
|
||||
waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest(
|
||||
analyser=self,
|
||||
reservations=self.reservations,
|
||||
room_pos=int(getattr(self, "room_pos", 0) or 0),
|
||||
reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6),
|
||||
reservation_back_swipe_delay_s=_safe_float_attr(self, "reservation_back_swipe_delay", 0.6),
|
||||
swipe_down_back_callback=_swipe_down_once,
|
||||
seek_reservation_room_callback=_seek_reservation_room,
|
||||
sort_reservations_callback=_sort_reservations,
|
||||
@@ -239,12 +263,7 @@ def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) ->
|
||||
self._log_kv("流程", "run_once_basic完成(预约队列满等待)", elapsed_seconds=round(elapsed, 2))
|
||||
return True
|
||||
|
||||
if getattr(self, "_waiting_for_lottery_result", False):
|
||||
try:
|
||||
self._log_kv("预约", "[预约] 正在等待开奖,跳过预约回退检查", waiting_for_lottery=True)
|
||||
except Exception:
|
||||
pass
|
||||
elif getattr(self, "_current_attending_reservation_fudai", False):
|
||||
if getattr(self, "_current_attending_reservation_fudai", False):
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
@@ -303,7 +322,7 @@ def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) ->
|
||||
room_pos=int(getattr(self, "room_pos", 0) or 0),
|
||||
reservation_focus_until_ts_ref=focus_ref,
|
||||
reservation_after_action_pending_ref=after_action_ref,
|
||||
reservation_back_swipe_delay_s=float(self.reservation_back_swipe_delay or 0.6),
|
||||
reservation_back_swipe_delay_s=_safe_float_attr(self, "reservation_back_swipe_delay", 0.6),
|
||||
swipe_down_back_callback=_swipe_down_once,
|
||||
seek_reservation_room_callback=_seek_reservation_room,
|
||||
sort_reservations_callback=_sort_reservations,
|
||||
@@ -353,6 +372,150 @@ def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) ->
|
||||
return False
|
||||
|
||||
|
||||
def _should_allow_reservation_preempt_waiting_lottery(self: "fudai_analyse") -> bool:
|
||||
"""等待开奖期间只允许明显更高价值的预约抢占。"""
|
||||
try:
|
||||
current_value = float(getattr(self, "_lottery_wait_prize_value_yuan", 0.0) or 0.0)
|
||||
except Exception:
|
||||
current_value = 0.0
|
||||
try:
|
||||
current_future_ts = float(getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0)
|
||||
except Exception:
|
||||
current_future_ts = 0.0
|
||||
try:
|
||||
reservations = list(getattr(self, "reservations", []) or [])
|
||||
except Exception:
|
||||
reservations = []
|
||||
|
||||
if not reservations:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 正在等待开奖,预约队列为空,跳过预约回退检查",
|
||||
waiting_for_lottery=True,
|
||||
current_wait_value=current_value,
|
||||
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
now_ts = time.time()
|
||||
try:
|
||||
poll_before = _safe_float_attr(self, "high_value_fudai_poll_before_seconds", 10.0)
|
||||
except Exception:
|
||||
poll_before = 10.0
|
||||
join_ahead = _safe_float_attr(self, "high_value_fudai_join_ahead_seconds", 100.0)
|
||||
swipe_delay = _safe_float_attr(self, "reservation_back_swipe_delay", 0.6)
|
||||
try:
|
||||
room_pos = int(getattr(self, "room_pos", 0) or 0)
|
||||
except Exception:
|
||||
room_pos = 0
|
||||
|
||||
try:
|
||||
from douyin.reservation.reservation_logic.attend_window_helpers import compute_dynamic_ahead
|
||||
from douyin.reservation.reservation_logic.helpers import (
|
||||
_select_reservation_target_for_window,
|
||||
)
|
||||
|
||||
def _dynamic_ahead_for_item(item: dict) -> float:
|
||||
dynamic_ahead, _est = compute_dynamic_ahead(
|
||||
self,
|
||||
item,
|
||||
room_pos,
|
||||
swipe_delay,
|
||||
join_ahead,
|
||||
)
|
||||
return dynamic_ahead
|
||||
|
||||
selected_idx, target = _select_reservation_target_for_window(
|
||||
reservations,
|
||||
now_ts,
|
||||
_dynamic_ahead_for_item,
|
||||
poll_before,
|
||||
)
|
||||
except Exception:
|
||||
selected_idx, target = 0, reservations[0]
|
||||
|
||||
try:
|
||||
target_future_ts = float(target.get("future_ts") or 0.0)
|
||||
except Exception:
|
||||
target_future_ts = 0.0
|
||||
try:
|
||||
target_value = float(target.get("prize_value_yuan") or 0.0)
|
||||
except Exception:
|
||||
target_value = 0.0
|
||||
|
||||
# 若选择器没有命中当前窗口,会返回队头;此时不要用未来预约打断等待开奖。
|
||||
in_window = False
|
||||
try:
|
||||
from douyin.reservation.reservation_logic.attend_window_helpers import compute_dynamic_ahead
|
||||
|
||||
dynamic_ahead, _est = compute_dynamic_ahead(
|
||||
self,
|
||||
target,
|
||||
room_pos,
|
||||
swipe_delay,
|
||||
join_ahead,
|
||||
)
|
||||
in_window = (target_future_ts > 0) and (
|
||||
now_ts >= target_future_ts - max(0.0, dynamic_ahead)
|
||||
) and (now_ts <= target_future_ts + max(0.0, poll_before))
|
||||
except Exception:
|
||||
in_window = False
|
||||
|
||||
if not in_window:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 正在等待开奖,预约未到参与窗口,跳过预约回退检查",
|
||||
waiting_for_lottery=True,
|
||||
current_wait_value=current_value,
|
||||
target_value=target_value,
|
||||
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
|
||||
decision="skip_reservation_back",
|
||||
reason="waiting_lottery_target_window_not_reached",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
if target_value <= current_value:
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 正在等待开奖,当前已参与福袋价值不低于预约,跳过预约回退检查",
|
||||
waiting_for_lottery=True,
|
||||
current_wait_value=current_value,
|
||||
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
|
||||
target_value=target_value,
|
||||
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
|
||||
selected_index=int(selected_idx),
|
||||
decision="skip_reservation_back",
|
||||
reason="waiting_lottery_current_value_ge_target",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
try:
|
||||
self._log_kv(
|
||||
"预约",
|
||||
"[预约] 正在等待开奖,但预约价值更高,允许抢占当前等待",
|
||||
waiting_for_lottery=True,
|
||||
current_wait_value=current_value,
|
||||
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
|
||||
target_value=target_value,
|
||||
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
|
||||
selected_index=int(selected_idx),
|
||||
decision="allow_reservation_back",
|
||||
reason="waiting_lottery_target_value_gt_current",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _write_reservations_state(self: "fudai_analyse") -> None:
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -28,10 +28,18 @@ if TYPE_CHECKING:
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
|
||||
def _uo_log(msg: str) -> None:
|
||||
def _uo_log(msg: str, level: str = "INFO") -> None:
|
||||
"""与 underlying_operations._uo_log 一致:默认 INFO 级别。"""
|
||||
try:
|
||||
logging.info(msg)
|
||||
lv = str(level or "INFO").upper()
|
||||
if lv == "WARNING":
|
||||
logging.warning(msg)
|
||||
elif lv == "ERROR":
|
||||
logging.error(msg)
|
||||
elif lv == "DEBUG":
|
||||
logging.debug(msg)
|
||||
else:
|
||||
logging.info(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -89,6 +97,66 @@ def _valid_png(path0: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _adb_shell_png_variants(data: bytes) -> list[bytes]:
|
||||
"""Return safe candidates for ``adb shell screencap -p`` stdout.
|
||||
|
||||
Some Android/Windows ADB combinations route shell stdout through a text-ish
|
||||
path and duplicate carriage returns in PNG line endings. Try the raw bytes
|
||||
first, then the common CRLF repairs without changing the primary exec-out
|
||||
path.
|
||||
"""
|
||||
if not data:
|
||||
return []
|
||||
variants: list[bytes] = []
|
||||
|
||||
def _add(candidate: bytes) -> None:
|
||||
if candidate and candidate not in variants:
|
||||
variants.append(candidate)
|
||||
|
||||
marker = b"\x89PNG"
|
||||
idx = data.find(marker)
|
||||
if idx > 0:
|
||||
data = data[idx:]
|
||||
|
||||
_add(data)
|
||||
_add(data.replace(b"\r\r\n", b"\r\n"))
|
||||
_add(data.replace(b"\r\n", b"\n"))
|
||||
return variants
|
||||
|
||||
|
||||
def _write_valid_png_bytes(tmp_file: str, data: bytes) -> bool:
|
||||
for candidate in _adb_shell_png_variants(data):
|
||||
try:
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
f.write(candidate)
|
||||
if _valid_png(tmp_file):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _stderr_tail(stderr: bytes | str | None, limit: int = 800) -> str:
|
||||
if stderr is None:
|
||||
return ""
|
||||
if isinstance(stderr, bytes):
|
||||
text = stderr.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = str(stderr)
|
||||
return text.strip()[-limit:]
|
||||
|
||||
|
||||
def _format_completed_error(error: subprocess.CalledProcessError) -> str:
|
||||
parts = [f"returncode={error.returncode}"]
|
||||
stderr = _stderr_tail(getattr(error, "stderr", None))
|
||||
stdout = _stderr_tail(getattr(error, "output", None))
|
||||
if stderr:
|
||||
parts.append(f"stderr={stderr}")
|
||||
if stdout:
|
||||
parts.append(f"stdout={stdout}")
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def capture_screenshot_direct(
|
||||
self: "underlying_operations", device_id, path: str = "pic"
|
||||
) -> bool:
|
||||
@@ -128,6 +196,61 @@ def capture_screenshot_direct(
|
||||
|
||||
adb = self._adb_path()
|
||||
|
||||
def _commit_valid_tmp(success_kind: str, start_ts: float) -> bool:
|
||||
if not _valid_png(tmp_file):
|
||||
return False
|
||||
if not _safe_replace_file(tmp_file, out_file):
|
||||
return False
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
if not _valid_png(out_file):
|
||||
return False
|
||||
overall_dur = (time_module.time() - overall_start) * 1000.0
|
||||
part_dur = (time_module.time() - start_ts) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (%s成功, 回退部分耗时=%.1fms)",
|
||||
overall_dur,
|
||||
success_kind,
|
||||
part_dur,
|
||||
)
|
||||
return True
|
||||
|
||||
def _try_shell_stdout_fallback() -> bool:
|
||||
stdout_fallback_start = time_module.time()
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
if _write_valid_png_bytes(tmp_file, result.stdout or b""):
|
||||
return _commit_valid_tmp("shell stdout回退", stdout_fallback_start)
|
||||
try:
|
||||
size = len(result.stdout or b"")
|
||||
_uo_log(f"[截图] shell stdout回退输出无效:bytes={size}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except subprocess.CalledProcessError as stdout_error:
|
||||
try:
|
||||
_uo_log(
|
||||
"[截图] shell stdout回退失败:" + _format_completed_error(stdout_error),
|
||||
"WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as stdout_error:
|
||||
try:
|
||||
_uo_log(
|
||||
f"[截图] shell stdout回退失败:{type(stdout_error).__name__}: {stdout_error}",
|
||||
"WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 优先走 exec-out
|
||||
try:
|
||||
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
|
||||
@@ -167,7 +290,7 @@ def capture_screenshot_direct(
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
)
|
||||
|
||||
@@ -206,7 +329,7 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
done_event = None
|
||||
|
||||
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
|
||||
stdout_data, stderr_data = process.communicate(timeout=execout_timeout_sec)
|
||||
if done_event is not None:
|
||||
done_event.set()
|
||||
|
||||
@@ -214,6 +337,8 @@ def capture_screenshot_direct(
|
||||
raise subprocess.CalledProcessError(
|
||||
process.returncode,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
output=stdout_data,
|
||||
stderr=stderr_data,
|
||||
)
|
||||
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
@@ -334,7 +459,10 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
if isinstance(e, subprocess.CalledProcessError):
|
||||
_uo_log(f"[截图] exec-out 异常:{_format_completed_error(e)}")
|
||||
else:
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -347,7 +475,7 @@ def capture_screenshot_direct(
|
||||
shell_screencap_start = time_module.time()
|
||||
remote_shot = path_config.get_android_screenshot_path()
|
||||
remote_shot_alt = path_config.get_android_screenshot_alt_path()
|
||||
subprocess.run(
|
||||
shell_result = subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
@@ -358,10 +486,13 @@ def capture_screenshot_direct(
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
shell_stderr = _stderr_tail(getattr(shell_result, "stderr", None))
|
||||
if shell_stderr:
|
||||
logging.info("[截图] 回退方案-shell screencap stderr=%s", shell_stderr)
|
||||
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
|
||||
@@ -370,13 +501,16 @@ def capture_screenshot_direct(
|
||||
)
|
||||
|
||||
pull_start = time_module.time()
|
||||
subprocess.run(
|
||||
pull_result = subprocess.run(
|
||||
[adb, "-s", device_id, "pull", remote_shot, tmp_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
pull_stderr = _stderr_tail(getattr(pull_result, "stderr", None))
|
||||
if pull_stderr:
|
||||
logging.info("[截图] 回退方案-adb pull stderr=%s", pull_stderr)
|
||||
pull_dur = (time_module.time() - pull_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
|
||||
@@ -466,70 +600,64 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
try:
|
||||
stdout_fallback_start = time_module.time()
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
f.write(result.stdout or b"")
|
||||
if _valid_png(tmp_file) and _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
if _valid_png(out_file):
|
||||
overall_dur = (time_module.time() - overall_start) * 1000.0
|
||||
fallback_total_dur = (
|
||||
time_module.time() - stdout_fallback_start
|
||||
) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (shell stdout回退成功, 回退部分耗时=%.1fms)",
|
||||
overall_dur,
|
||||
fallback_total_dur,
|
||||
)
|
||||
return True
|
||||
except Exception as stdout_error:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
_uo_log(
|
||||
f"[截图] shell stdout回退失败:{type(stdout_error).__name__}: {stdout_error}",
|
||||
"WARNING",
|
||||
f"[截图] 回退方案截图无效,继续尝试 shell stdout 回退: size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
remote_shot_alt,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"mv",
|
||||
remote_shot_alt,
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return self.get_screenshot(device_id, path)
|
||||
except Exception:
|
||||
return False
|
||||
pass
|
||||
except subprocess.CalledProcessError as fallback_error:
|
||||
try:
|
||||
_uo_log(
|
||||
"[截图] 回退方案失败,继续尝试 shell stdout 回退:"
|
||||
+ _format_completed_error(fallback_error)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as fallback_error:
|
||||
try:
|
||||
_uo_log(f"[截图] 回退方案失败,继续尝试 shell stdout 回退:{fallback_error}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if _try_shell_stdout_fallback():
|
||||
return True
|
||||
|
||||
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
|
||||
try:
|
||||
if "remote_shot" not in locals():
|
||||
remote_shot = path_config.get_android_screenshot_path()
|
||||
remote_shot_alt = path_config.get_android_screenshot_alt_path()
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
remote_shot_alt,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"mv",
|
||||
remote_shot_alt,
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return self.get_screenshot(device_id, path)
|
||||
except Exception:
|
||||
return False
|
||||
@@ -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()
|
||||
|
||||
@@ -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.11"
|
||||
APP_BUILD_DATE = "2026-06-29"
|
||||
|
||||
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
|
||||
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
|
||||
|
||||
@@ -19,6 +19,14 @@ from typing import Any, Optional
|
||||
from ._common import _safe_open_screenshot_rgb
|
||||
|
||||
|
||||
def _read_rgb_pixel(pic_rgb: Image.Image, x: int, y: int) -> tuple[int, int, int]:
|
||||
pixel = pic_rgb.getpixel((x, y))
|
||||
if isinstance(pixel, tuple):
|
||||
return int(pixel[0]), int(pixel[1]), int(pixel[2])
|
||||
value = int(pixel)
|
||||
return value, value, value
|
||||
|
||||
|
||||
def detect_attend_button_red_area(
|
||||
pic_rgb: Image.Image,
|
||||
return_info: bool = False,
|
||||
@@ -86,7 +94,7 @@ def detect_attend_button_red_area(
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
|
||||
# 检测红色:R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
red_count += 1
|
||||
@@ -253,7 +261,7 @@ def detect_fansclub_join_red_area(
|
||||
for y in range(y1, y2, step_y):
|
||||
for x in range(x1, x2, step_x):
|
||||
try:
|
||||
r, g, b = pic_rgb.getpixel((x, y))
|
||||
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
|
||||
# 检测红色:R值高,G和B相对较低
|
||||
if r > 200 and (r - g) > 50 and (r - b) > 50:
|
||||
red_count += 1
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Diagnostic helpers for packaged clients."""
|
||||
@@ -0,0 +1,346 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import time
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib import request
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import get_default_license_path, get_default_verify_url
|
||||
|
||||
DEFAULT_MAX_ARCHIVE_BYTES = 500 * 1024 * 1024
|
||||
DEFAULT_MAX_SOURCE_BYTES = 64 * 1024 * 1024
|
||||
DEFAULT_MAX_FILES = 32
|
||||
DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
SENSITIVE_KEY_PARTS = ("key", "token", "secret", "password", "license", "card")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogUploadResult:
|
||||
ok: bool
|
||||
message: str
|
||||
reason: str = ""
|
||||
archive_path: str = ""
|
||||
size: int = 0
|
||||
|
||||
|
||||
def get_default_log_upload_url() -> str:
|
||||
raw = str(os.environ.get("DOUYIN_LOG_UPLOAD_URL") or "").strip()
|
||||
if raw:
|
||||
return raw
|
||||
verify_url = get_default_verify_url()
|
||||
if verify_url.endswith("/verify_license"):
|
||||
return verify_url[: -len("/verify_license")] + "/logs/upload"
|
||||
return verify_url.rstrip("/") + "/logs/upload"
|
||||
|
||||
|
||||
def _candidate_log_files(logs_dir: Path) -> list[Path]:
|
||||
suffixes = {".log", ".jsonl", ".txt"}
|
||||
if not logs_dir.exists():
|
||||
return []
|
||||
files = [
|
||||
p
|
||||
for p in logs_dir.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in suffixes and p.name != ".keep"
|
||||
]
|
||||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def _tail_bytes(path: Path, limit: int) -> bytes:
|
||||
size = path.stat().st_size
|
||||
with path.open("rb") as f:
|
||||
if size > limit:
|
||||
f.seek(size - limit)
|
||||
return f.read(limit)
|
||||
|
||||
|
||||
def _safe_rel(path: Path, base: Path) -> str:
|
||||
try:
|
||||
return path.relative_to(base).as_posix()
|
||||
except Exception:
|
||||
return path.name
|
||||
|
||||
|
||||
def _redact_value(key: str, value: Any) -> Any:
|
||||
key_l = str(key or "").lower()
|
||||
if isinstance(value, dict):
|
||||
return {str(k): _redact_value(str(k), v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_redact_value(key, item) for item in value]
|
||||
if any(part in key_l for part in SENSITIVE_KEY_PARTS):
|
||||
return "<redacted>"
|
||||
return value
|
||||
|
||||
|
||||
def _read_redacted_config() -> dict[str, Any] | None:
|
||||
try:
|
||||
path = Path(path_config.get_config_path())
|
||||
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
if not isinstance(obj, dict):
|
||||
return None
|
||||
return {str(k): _redact_value(str(k), v) for k, v in obj.items()}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _candidate_state_files(state_dir: Path) -> list[Path]:
|
||||
if not state_dir.exists():
|
||||
return []
|
||||
names = {
|
||||
"reservations.json",
|
||||
"room_pos_map.json",
|
||||
"high_value_rooms.json",
|
||||
"runtime_stats.json",
|
||||
"dashboard_stats.json",
|
||||
}
|
||||
files = [p for p in state_dir.rglob("*.json") if p.is_file() and p.name in names]
|
||||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def _candidate_pic_files(pic_dir: Path) -> list[Path]:
|
||||
if not pic_dir.exists():
|
||||
return []
|
||||
preferred = []
|
||||
for name in (
|
||||
"screenshot.png",
|
||||
"screenshot.png.tmp",
|
||||
"screenshot.jpg",
|
||||
"latest.png",
|
||||
"last_match.png",
|
||||
):
|
||||
p = pic_dir / name
|
||||
if p.is_file():
|
||||
preferred.append(p)
|
||||
|
||||
def _is_diagnostic_pic(path: Path) -> bool:
|
||||
suffix = path.suffix.lower()
|
||||
if suffix in {".png", ".jpg", ".jpeg"}:
|
||||
return True
|
||||
return path.name.lower().endswith(".png.tmp")
|
||||
|
||||
recent = sorted(
|
||||
[p for p in pic_dir.rglob("*") if p.is_file() and _is_diagnostic_pic(p)],
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
result: list[Path] = []
|
||||
for item in [*preferred, *recent]:
|
||||
if item not in result:
|
||||
result.append(item)
|
||||
if len(result) >= 12:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _run_command(cmd: list[str], timeout: int = 5) -> dict[str, Any]:
|
||||
try:
|
||||
proc = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout)
|
||||
return {
|
||||
"cmd": cmd,
|
||||
"returncode": proc.returncode,
|
||||
"stdout": (proc.stdout or "")[-4000:],
|
||||
"stderr": (proc.stderr or "")[-2000:],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"cmd": cmd, "error": f"{type(exc).__name__}: {exc}"}
|
||||
|
||||
|
||||
def _diagnostic_environment() -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"created_at": int(time.time()),
|
||||
"platform": platform.platform(),
|
||||
"python": platform.python_version(),
|
||||
"cwd": os.getcwd(),
|
||||
"project_root": path_config.get_project_root(),
|
||||
"logs_dir": path_config.get_logs_dir(),
|
||||
"pic_dir": path_config.get_pic_dir(),
|
||||
"state_dir": path_config.get_state_dir(),
|
||||
}
|
||||
adb = ""
|
||||
try:
|
||||
from gui.gui_core import find_adb_executable
|
||||
|
||||
adb = str(find_adb_executable() or "")
|
||||
except Exception:
|
||||
adb = str(os.environ.get("ADB") or "adb")
|
||||
payload["adb"] = adb
|
||||
payload["adb_version"] = _run_command([adb, "version"]) if adb else {"error": "adb not found"}
|
||||
payload["adb_devices"] = _run_command([adb, "devices", "-l"]) if adb else {"error": "adb not found"}
|
||||
return payload
|
||||
|
||||
|
||||
def build_diagnostic_log_archive(
|
||||
*,
|
||||
output_dir: str | os.PathLike[str] | None = None,
|
||||
max_archive_bytes: int = DEFAULT_MAX_ARCHIVE_BYTES,
|
||||
max_source_bytes: int = DEFAULT_MAX_SOURCE_BYTES,
|
||||
max_files: int = DEFAULT_MAX_FILES,
|
||||
) -> Path:
|
||||
logs_dir = Path(path_config.get_logs_dir())
|
||||
out_dir = Path(output_dir) if output_dir is not None else logs_dir
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive = out_dir / f"diagnostic_logs_{int(time.time())}.zip"
|
||||
files = _candidate_log_files(logs_dir)[: max(1, int(max_files))]
|
||||
if not files:
|
||||
raise FileNotFoundError("没有找到可上传的日志文件")
|
||||
|
||||
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
|
||||
manifest: dict[str, Any] = {
|
||||
"created_at": int(time.time()),
|
||||
"source": "douyin_guaji",
|
||||
"truncated_each_file_bytes": int(max_source_bytes),
|
||||
"files": [],
|
||||
}
|
||||
for file in files:
|
||||
rel = _safe_rel(file, logs_dir)
|
||||
data = _tail_bytes(file, max_source_bytes)
|
||||
zf.writestr(f"logs/{rel}", data)
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"logs/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": len(data),
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
try:
|
||||
pic_dir = Path(path_config.get_pic_dir())
|
||||
for file in _candidate_pic_files(pic_dir):
|
||||
if file.stat().st_size > DEFAULT_MAX_IMAGE_BYTES:
|
||||
continue
|
||||
rel = _safe_rel(file, pic_dir)
|
||||
zf.write(file, f"pic/{rel}")
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"pic/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": file.stat().st_size,
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
manifest["pic_error"] = str(exc)
|
||||
try:
|
||||
state_dir = Path(path_config.get_state_dir())
|
||||
for file in _candidate_state_files(state_dir):
|
||||
rel = _safe_rel(file, state_dir)
|
||||
data = _tail_bytes(file, max_source_bytes)
|
||||
zf.writestr(f"state/{rel}", data)
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"state/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": len(data),
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
manifest["state_error"] = str(exc)
|
||||
redacted_cfg = _read_redacted_config()
|
||||
if redacted_cfg is not None:
|
||||
zf.writestr(
|
||||
"config/config.redacted.json",
|
||||
json.dumps(redacted_cfg, ensure_ascii=False, indent=2),
|
||||
)
|
||||
zf.writestr(
|
||||
"diagnostics/environment.json",
|
||||
json.dumps(_diagnostic_environment(), ensure_ascii=False, indent=2),
|
||||
)
|
||||
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
|
||||
if archive.stat().st_size > max_archive_bytes:
|
||||
try:
|
||||
archive.unlink()
|
||||
finally:
|
||||
raise ValueError(f"诊断日志包超过大小限制(最大 {max_archive_bytes // (1024 * 1024)} MB)")
|
||||
return archive
|
||||
|
||||
|
||||
def upload_diagnostic_logs(
|
||||
*,
|
||||
upload_url: str = "",
|
||||
timeout_seconds: int = 120,
|
||||
http_post_file=None,
|
||||
) -> LogUploadResult:
|
||||
license_path = get_default_license_path()
|
||||
if not license_path.exists():
|
||||
return LogUploadResult(False, "缺少授权文件,无法上传日志", "missing_license")
|
||||
try:
|
||||
license_doc = json.loads(license_path.read_text(encoding="utf-8"))
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, f"授权文件读取失败: {exc}", "invalid_license")
|
||||
|
||||
try:
|
||||
archive = build_diagnostic_log_archive()
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, str(exc), "archive_failed")
|
||||
|
||||
url = str(upload_url or "").strip() or get_default_log_upload_url()
|
||||
try:
|
||||
post = http_post_file or _default_http_post_file
|
||||
data = post(
|
||||
url,
|
||||
license_doc=license_doc,
|
||||
file_path=archive,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, f"上传失败: {exc}", "upload_failed", str(archive), archive.stat().st_size)
|
||||
if not bool(data.get("ok")):
|
||||
return LogUploadResult(
|
||||
False,
|
||||
str(data.get("message") or data.get("error") or "上传失败"),
|
||||
str(data.get("reason") or "rejected"),
|
||||
str(archive),
|
||||
archive.stat().st_size,
|
||||
)
|
||||
return LogUploadResult(True, "日志上传成功", "ok", str(archive), archive.stat().st_size)
|
||||
|
||||
|
||||
def _default_http_post_file(
|
||||
url: str,
|
||||
*,
|
||||
license_doc: dict[str, Any],
|
||||
file_path: Path,
|
||||
timeout_seconds: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
boundary = f"----DYGJ{int(time.time() * 1000)}"
|
||||
payload = json.dumps(license_doc, ensure_ascii=False).encode("utf-8")
|
||||
file_data = file_path.read_bytes()
|
||||
body = bytearray()
|
||||
|
||||
def add_field(name: str, value: bytes, content_type: str = "text/plain") -> None:
|
||||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||||
body.extend(f'Content-Disposition: form-data; name="{name}"\r\n'.encode("ascii"))
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode("ascii"))
|
||||
body.extend(value)
|
||||
body.extend(b"\r\n")
|
||||
|
||||
add_field("license", payload, "application/json")
|
||||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||||
body.extend(
|
||||
f'Content-Disposition: form-data; name="log_file"; filename="{file_path.name}"\r\n'.encode("ascii")
|
||||
)
|
||||
body.extend(b"Content-Type: application/zip\r\n\r\n")
|
||||
body.extend(file_data)
|
||||
body.extend(b"\r\n")
|
||||
body.extend(f"--{boundary}--\r\n".encode("ascii"))
|
||||
|
||||
req = request.Request(
|
||||
url,
|
||||
data=bytes(body),
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
method="POST",
|
||||
)
|
||||
with request.urlopen(req, timeout=max(1, int(timeout_seconds))) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
obj = json.loads(raw)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("server response is not an object")
|
||||
return obj
|
||||
@@ -138,7 +138,7 @@ DETAIL_UI_V2_0_ONE_TASK = {
|
||||
"variant": "one_task",
|
||||
"content": (360, 1460, 1035, 1545),
|
||||
"value": (350, 1640, 760, 1735),
|
||||
"countdown_full": (730, 1338, 1038, 1418),
|
||||
"countdown_full": (700, 1390, 990, 1470),
|
||||
"info_line": (430, 1315, 1055, 1435),
|
||||
"task_list": (60, 1845, 885, 2005),
|
||||
"task_count": (890, 1855, 1040, 1960),
|
||||
@@ -159,6 +159,19 @@ STALE_DETAIL_REGION_DEFAULTS = {
|
||||
"value": (300, 1585, 650, 1685),
|
||||
"countdown_full": (760, 1328, 1038, 1398),
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"countdown_full": (700, 1320, 930, 1415),
|
||||
},
|
||||
}
|
||||
|
||||
STALE_DETAIL_REGION_OVERRIDES = {
|
||||
"v2_0_one_task": {
|
||||
"countdown_full": (
|
||||
(730, 1338, 1038, 1418),
|
||||
(769, 1384, 1029, 1442),
|
||||
(700, 1320, 930, 1415),
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
PIXEL_REGION_DEFAULTS = {
|
||||
@@ -211,20 +224,27 @@ def _apply_region_overrides(defaults: dict[str, Any], overrides: Any) -> dict[st
|
||||
parsed = _tuple4(candidate)
|
||||
if parsed is not None:
|
||||
merged[key] = parsed
|
||||
else:
|
||||
elif key in overrides and candidate is not None:
|
||||
merged[key] = candidate
|
||||
return merged
|
||||
|
||||
|
||||
def _drop_stale_region_overrides(profile_key: str, overrides: dict[str, Any]) -> dict[str, Any]:
|
||||
stale = STALE_DETAIL_REGION_DEFAULTS.get(profile_key, {})
|
||||
if not stale:
|
||||
stale_overrides = STALE_DETAIL_REGION_OVERRIDES.get(profile_key, {})
|
||||
if not stale and not stale_overrides:
|
||||
return dict(overrides)
|
||||
cleaned = dict(overrides)
|
||||
for key, old_value in stale.items():
|
||||
parsed = _tuple4(cleaned.get(key))
|
||||
if parsed is not None and parsed == tuple(old_value):
|
||||
cleaned.pop(key, None)
|
||||
for key, old_values in stale_overrides.items():
|
||||
parsed = _tuple4(cleaned.get(key))
|
||||
if parsed is None:
|
||||
continue
|
||||
if any(parsed == tuple(old_value) for old_value in old_values):
|
||||
cleaned.pop(key, None)
|
||||
return cleaned
|
||||
|
||||
|
||||
@@ -295,5 +315,5 @@ DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
|
||||
|
||||
DETAIL_OUTSIDE_CLICK = (500, 470)
|
||||
PARTICIPATE_BTN_CLICK = (543, 2070)
|
||||
FANSCLUB_JOIN_CLICK = (540, 2006)
|
||||
FANSCLUB_JOIN_FALLBACK_CLICK = (500, 2060)
|
||||
FANSCLUB_JOIN_CLICK = (550, 2050)
|
||||
FANSCLUB_JOIN_FALLBACK_CLICK = (540, 2006)
|
||||
@@ -11,6 +11,10 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
|
||||
decide_button_status,
|
||||
is_button_text_non_actionable,
|
||||
)
|
||||
|
||||
from .coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK
|
||||
|
||||
@@ -102,26 +106,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
if candidate:
|
||||
bt = str(candidate or "").strip()
|
||||
if bt:
|
||||
# 推断按钮状态(与并行OCR的判断逻辑保持一致)
|
||||
if (
|
||||
"参与成功" in bt
|
||||
or "等待开奖" in bt
|
||||
or "失去抽奖" in bt
|
||||
or "否则会失去" in bt
|
||||
):
|
||||
bs = "已参与"
|
||||
elif "加入粉丝团" in bt or "粉丝团" in bt:
|
||||
bs = "需要加入粉丝团"
|
||||
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
|
||||
bs = "需要评论"
|
||||
elif "还需看播" in bt or "开始观看" in bt:
|
||||
bs = "需要观看"
|
||||
elif "未达成" in bt:
|
||||
bs = "未达成要求"
|
||||
elif "参与抽奖" in bt or "参与" in bt:
|
||||
bs = "可以参与"
|
||||
else:
|
||||
bs = "未知状态"
|
||||
bs = decide_button_status(bt)
|
||||
|
||||
try:
|
||||
analyser._fudai_button_status = bs
|
||||
@@ -234,6 +219,32 @@ def attend_choujiang(analyser) -> bool:
|
||||
return False
|
||||
|
||||
# 基于并行OCR结果进行决策
|
||||
if attend_button_text and is_button_text_non_actionable(attend_button_text):
|
||||
analyser.last_attend_fail_reason = "button_not_actionable"
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"按钮文案不可参与,直接放弃",
|
||||
result="不参与",
|
||||
reason="button_not_actionable",
|
||||
button_text=attend_button_text[:120],
|
||||
button_status=str(button_status or ""),
|
||||
decision="close_detail_without_attend",
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"统计",
|
||||
"metric",
|
||||
metric="fudai_attend",
|
||||
metric_type="fail",
|
||||
reason="button_not_actionable",
|
||||
run_id=getattr(analyser, "_run_id", ""),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
return False
|
||||
|
||||
if attend_button_text and "不满足参与条件" in attend_button_text:
|
||||
analyser.last_attend_fail_reason = "condition_not_met"
|
||||
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
|
||||
@@ -352,11 +363,21 @@ def attend_choujiang(analyser) -> bool:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
try:
|
||||
analyser._lottery_wait_prize_value_yuan = float(
|
||||
prize_value_yuan or 0.0
|
||||
)
|
||||
except Exception:
|
||||
analyser._lottery_wait_prize_value_yuan = 0.0
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"参与成功,设置等待开奖标志",
|
||||
remain_seconds=int(remain_seconds),
|
||||
future_ts=int(future_ts),
|
||||
prize_value_yuan=float(
|
||||
getattr(analyser, "_lottery_wait_prize_value_yuan", 0.0)
|
||||
or 0.0
|
||||
),
|
||||
lottery_result_expected_ts=int(
|
||||
analyser._lottery_result_expected_ts
|
||||
),
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .fansclub_handler_impl import handle_fansclub_branch
|
||||
|
||||
__all__ = ["handle_fansclub_branch"]
|
||||
from .fansclub_handler_impl import (
|
||||
handle_fansclub_branch,
|
||||
handle_reservation_prejoin_fansclub,
|
||||
)
|
||||
|
||||
__all__ = ["handle_fansclub_branch", "handle_reservation_prejoin_fansclub"]
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.fudai.core.coords import (
|
||||
DETAIL_OUTSIDE_CLICK,
|
||||
PARTICIPATE_BTN_CLICK,
|
||||
@@ -21,3 +20,143 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
|
||||
|
||||
return _legacy_impl(analyser, attend_button_text)
|
||||
|
||||
|
||||
def _scaled_point(analyser: Any, point: tuple[int, int]) -> tuple[int, int]:
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
return int(point[0] * rx // 1080), int(point[1] * ry // 2400)
|
||||
|
||||
|
||||
def _fast_delay(
|
||||
analyser: Any,
|
||||
attr_name: str,
|
||||
default_seconds: float,
|
||||
*,
|
||||
min_seconds: float = 0.0,
|
||||
) -> None:
|
||||
try:
|
||||
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(float(min_seconds or 0.0), min(seconds, 3.0))
|
||||
try:
|
||||
analyser.operation.delay(seconds)
|
||||
except Exception:
|
||||
time.sleep(seconds)
|
||||
|
||||
|
||||
def handle_reservation_prejoin_fansclub(
|
||||
analyser: Any, attend_button_text: str
|
||||
) -> bool:
|
||||
"""预约记录前的粉丝团快路径:固定坐标点击,不做OCR和详情恢复。"""
|
||||
start_ts = time.time()
|
||||
try:
|
||||
analyser.last_attend_fail_reason = "fansclub_required"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.click(*PARTICIPATE_BTN_CLICK)
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:先点击参与按钮",
|
||||
button_text=str(attend_button_text or "")[:80],
|
||||
base_x=PARTICIPATE_BTN_CLICK[0],
|
||||
base_y=PARTICIPATE_BTN_CLICK[1],
|
||||
)
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:点击参与按钮失败",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
_fast_delay(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub_participate_wait_seconds",
|
||||
1.2,
|
||||
min_seconds=0.8,
|
||||
)
|
||||
|
||||
click_point = FANSCLUB_JOIN_CLICK
|
||||
click_x, click_y = _scaled_point(analyser, click_point)
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, click_x, click_y)
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:点击加入粉丝团固定坐标",
|
||||
x=click_x,
|
||||
y=click_y,
|
||||
base_x=click_point[0],
|
||||
base_y=click_point[1],
|
||||
strategy="fixed_coord_no_ocr",
|
||||
)
|
||||
except Exception as exc:
|
||||
fallback_point = FANSCLUB_JOIN_FALLBACK_CLICK
|
||||
fallback_x, fallback_y = _scaled_point(analyser, fallback_point)
|
||||
try:
|
||||
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:固定坐标失败后使用备用坐标",
|
||||
x=fallback_x,
|
||||
y=fallback_y,
|
||||
base_x=fallback_point[0],
|
||||
base_y=fallback_point[1],
|
||||
first_error=str(exc),
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception as fallback_exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:点击加入粉丝团失败",
|
||||
error=str(fallback_exc),
|
||||
error_type=type(fallback_exc).__name__,
|
||||
first_error=str(exc),
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
_fast_delay(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub_confirm_wait_seconds",
|
||||
1.6,
|
||||
min_seconds=1.2,
|
||||
)
|
||||
|
||||
try:
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:关闭详情并跳过详情恢复",
|
||||
action="close_detail_after_fast_prejoin",
|
||||
elapsed_seconds=round(time.time() - start_ts, 2),
|
||||
)
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团快速预处理:关闭详情失败",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
elapsed_seconds=round(time.time() - start_ts, 2),
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
@@ -323,10 +323,6 @@ def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
|
||||
except Exception as e:
|
||||
analyser._log_kv("参与", "点击加入粉丝团按钮失败", error=str(e))
|
||||
|
||||
# 第三步:关闭详情页
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击详情页旁边位置关闭详情页
|
||||
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
|
||||
|
||||
if not analyser.auto_join_fansclub:
|
||||
analyser._log_kv(
|
||||
"参与", "未启用自动加粉丝团:等待手动确认", wait_seconds=15
|
||||
|
||||
@@ -25,12 +25,39 @@ def recover_to_fudai_detail_after_fansclub(
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
st, seen = "", ""
|
||||
st = str(getattr(analyser, "_last_diag_stage", "") or "")
|
||||
seen = str(getattr(analyser, "_last_diag_seen", "") or "")
|
||||
except Exception:
|
||||
st, seen = "", ""
|
||||
|
||||
if st == "FUDai_DETAIL":
|
||||
return True
|
||||
try:
|
||||
analyser._fansclub_joined_detail_recheck_pending = True
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"粉丝团加入后仍在详情页,保留详情页等待重新读取阈值后再决策",
|
||||
stage=st,
|
||||
seen=seen,
|
||||
attempt=i + 1,
|
||||
action="keep_detail_for_recheck_after_fansclub",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
if st in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
|
||||
try:
|
||||
analyser._fansclub_joined_detail_recheck_pending = True
|
||||
analyser._skip_stage_diagnosis_and_find_fudai = True
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"粉丝团加入后回到直播间,下一轮优先重新打开福袋详情并按阈值决策",
|
||||
stage=st,
|
||||
seen=seen,
|
||||
attempt=i + 1,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
if st == "FANSCLUB_JOIN":
|
||||
analyser._log_kv(
|
||||
@@ -313,5 +340,4 @@ def recover_to_fudai_detail_after_fansclub(
|
||||
analyser.operation.delay(1.0)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -517,7 +517,7 @@ def read_fudai_detail_once(analyser: Any) -> Tuple[str, Tuple, dict]:
|
||||
|
||||
# 解析倒计时 -> (剩余秒数, 未来时间戳)
|
||||
countdown_start = time.time()
|
||||
countdown_end = countdown_start + 60.0
|
||||
countdown_end = countdown_start
|
||||
total_seconds_from_ocr = None # 保存OCR识别到的原始秒数
|
||||
try:
|
||||
_cd0 = time.time()
|
||||
|
||||
@@ -308,7 +308,7 @@ def read_fudai_detail_with_retries(
|
||||
|
||||
if last_tuple is None:
|
||||
now = time.time()
|
||||
last_tuple = ("", "", 0, 0, 0.0, (now, now + 60.0))
|
||||
last_tuple = ("", "", 0, 0, 0.0, (now, now, None))
|
||||
|
||||
content, time_text, participants, copies, prize_value_yuan, cd = last_tuple
|
||||
cd_start, cd_end = None, None
|
||||
|
||||
@@ -236,8 +236,6 @@ def validate_fudai_detail(detail: Tuple, analyser: Any = None) -> Tuple[bool, st
|
||||
value_raw = str(getattr(analyser, "value_raw", "") or "").strip()
|
||||
if value_raw and prize_value_yuan > 0:
|
||||
# 检查原始文本是否包含合理的价值信息
|
||||
import re
|
||||
|
||||
# 查找所有可能金额。营销文案常见“0元带走¥999参考价值”,
|
||||
# 不能只看第一个数字,否则会把已正确解析出的参考价值误判失败。
|
||||
value_patterns = [
|
||||
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Tuple
|
||||
|
||||
from .helpers import _is_short_countdown_text, is_watch_task_fudai
|
||||
@@ -54,6 +55,142 @@ def _has_valid_countdown(detail: Tuple) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
_FANSCLUB_BUTTON_CANONICALS = (
|
||||
"加入粉丝团",
|
||||
"加入直播粉丝团",
|
||||
"加入购物粉丝团",
|
||||
"加入直播粉丝团并关注主播",
|
||||
"加入购物粉丝团并关注主播",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_button_text_for_match(text: str) -> str:
|
||||
return re.sub(r"[\s·。.,,、::||\-—_]+", "", str(text or ""))
|
||||
|
||||
|
||||
def _looks_like_fansclub_join_button(button_text: str, button_status: str = "") -> bool:
|
||||
"""判断按钮是否是加入粉丝团任务,兼容直播/购物粉丝团和轻微 OCR 差异。"""
|
||||
text_norm = _normalize_button_text_for_match(button_text)
|
||||
status_norm = _normalize_button_text_for_match(button_status)
|
||||
joined = text_norm + status_norm
|
||||
if not joined:
|
||||
return False
|
||||
if "粉丝团" in joined or "需要加入粉丝团" in status_norm:
|
||||
return True
|
||||
if ("加入" in joined or "加人" in joined) and "关注主播" in joined and "粉丝" in joined:
|
||||
return True
|
||||
|
||||
for canonical in _FANSCLUB_BUTTON_CANONICALS:
|
||||
canonical_norm = _normalize_button_text_for_match(canonical)
|
||||
score = SequenceMatcher(None, text_norm, canonical_norm).ratio()
|
||||
if score >= 0.78 and (
|
||||
"关注主播" in joined
|
||||
or "粉丝" in joined
|
||||
or "加入" in joined
|
||||
or "加人" in joined
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _prejoin_fansclub_before_reservation(
|
||||
analyser: Any,
|
||||
button_text: str,
|
||||
button_status: str,
|
||||
remain_seconds: float | int | None,
|
||||
) -> bool:
|
||||
"""高价值预约前尽量先完成粉丝团任务,回退时减少临开奖动作。"""
|
||||
text = str(button_text or "").strip()
|
||||
status = str(button_status or "").strip()
|
||||
try:
|
||||
setattr(analyser, "_reservation_prejoined_fansclub", False)
|
||||
setattr(analyser, "_reservation_prejoin_fansclub_button_text", text)
|
||||
setattr(analyser, "_reservation_prejoin_fansclub_ts", 0.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not _looks_like_fansclub_join_button(text, status):
|
||||
return False
|
||||
|
||||
if not bool(getattr(analyser, "auto_join_fansclub", False)):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团预处理跳过:未启用自动加入粉丝团",
|
||||
button_text=text[:80],
|
||||
button_status=status[:40],
|
||||
reason="auto_join_fansclub_disabled",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团预处理:检测到粉丝团任务,先尝试加入",
|
||||
button_text=text[:80],
|
||||
button_status=status[:40],
|
||||
remain_seconds=(
|
||||
int(remain_seconds) if remain_seconds is not None else None
|
||||
),
|
||||
reason="fansclub_required_before_high_value_reservation",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
|
||||
handle_reservation_prejoin_fansclub,
|
||||
)
|
||||
|
||||
ok = bool(handle_reservation_prejoin_fansclub(analyser, text))
|
||||
try:
|
||||
setattr(analyser, "_reservation_prejoined_fansclub", ok)
|
||||
setattr(analyser, "_reservation_prejoin_fansclub_button_text", text)
|
||||
setattr(analyser, "_reservation_prejoin_fansclub_ts", time.time())
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团预处理完成",
|
||||
result=ok,
|
||||
button_text=text[:80],
|
||||
button_status=status[:40],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
_emit_flow_flag(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub",
|
||||
"done" if ok else "failed",
|
||||
button_text=text[:80],
|
||||
button_status=status[:40],
|
||||
)
|
||||
return ok
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"预约前粉丝团预处理异常,继续保留预约",
|
||||
error=str(exc),
|
||||
error_type=type(exc).__name__,
|
||||
button_text=text[:80],
|
||||
button_status=status[:40],
|
||||
level="WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
_emit_flow_flag(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub",
|
||||
"error",
|
||||
error_type=type(exc).__name__,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
"""基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。
|
||||
|
||||
@@ -661,7 +798,7 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
# 剩余秒数大于"预约参与阈值",记录预约(真实写入队列)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"参与",
|
||||
"预约",
|
||||
"basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约",
|
||||
reason=reason,
|
||||
value_yuan=prize_value_yuan,
|
||||
@@ -750,6 +887,13 @@ def basic_join_decision(analyser: Any, detail: Tuple) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_prejoin_fansclub_before_reservation(
|
||||
analyser,
|
||||
button_text,
|
||||
str(getattr(analyser, "_fudai_button_status", "") or ""),
|
||||
remain_seconds,
|
||||
)
|
||||
|
||||
queue_full = bool(
|
||||
reservation_record.record_high_value_reservation(
|
||||
analyser=analyser,
|
||||
|
||||
@@ -14,6 +14,10 @@ import re
|
||||
import time
|
||||
from typing import Any, Tuple
|
||||
|
||||
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
|
||||
NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS,
|
||||
)
|
||||
|
||||
from .helpers import (
|
||||
_is_short_countdown_text,
|
||||
check_contain,
|
||||
@@ -463,6 +467,7 @@ def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str
|
||||
if button_text:
|
||||
# 检查是否包含无法参与的关键词
|
||||
unable_to_participate_keywords = [
|
||||
*NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS,
|
||||
"无法参与",
|
||||
"不能参与",
|
||||
"不可参与",
|
||||
|
||||
@@ -201,17 +201,13 @@ def _should_schedule_task_list_ocr(analyser: Any, ocr_switches: Any) -> bool:
|
||||
|
||||
|
||||
def _should_schedule_countdown_full_ocr(analyser: Any, ocr_switches: Any) -> bool:
|
||||
"""Use split minute/second OCR by default; full-line OCR is an opt-in fallback."""
|
||||
"""Use full-line countdown OCR as the only countdown source."""
|
||||
try:
|
||||
if not bool(getattr(ocr_switches, "countdown", False)):
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
return _get_bool_setting(
|
||||
analyser,
|
||||
"fudai_detail_countdown_full_ocr_in_critical_path_enabled",
|
||||
False,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def _should_schedule_info_line_ocr(analyser: Any, ocr_switches: Any) -> bool:
|
||||
@@ -334,8 +330,9 @@ def _parse_mmss_from_full_text(text: Any) -> Tuple[str, str]:
|
||||
return mm, ss
|
||||
|
||||
# 2) 紧凑格式:1340后开奖 / 940后开奖
|
||||
# 紧凑 3/4 位数字必须带开奖语境,否则商品编号如 G4939 会被误判成 49:39。
|
||||
compact = re.search(
|
||||
r"(?<!\d)(\d{3,4})(?=\D*(?:后开奖|开奖|后|$))",
|
||||
r"(?<!\d)(\d{3,4})(?=\D*(?:后开奖|开奖|后))",
|
||||
raw,
|
||||
)
|
||||
if compact:
|
||||
@@ -537,6 +534,39 @@ def _normalize_countdown_pair(mm_raw: Any, ss_raw: Any) -> Tuple[str, str]:
|
||||
return "", ""
|
||||
|
||||
|
||||
def _apply_countdown_text_fallback(
|
||||
analyser: Any,
|
||||
countdown_mm_raw: Any,
|
||||
countdown_ss_raw: Any,
|
||||
sources: Tuple[Tuple[str, Any], ...],
|
||||
) -> Tuple[Any, Any]:
|
||||
"""Use already-recognized text as a cheap countdown fallback before extra OCR."""
|
||||
mm_norm, ss_norm = _normalize_countdown_pair(countdown_mm_raw, countdown_ss_raw)
|
||||
if mm_norm and ss_norm:
|
||||
return countdown_mm_raw, countdown_ss_raw
|
||||
allowed_sources = {"info_line", "countdown_full"}
|
||||
for source_name, source_text in sources:
|
||||
if source_name not in allowed_sources:
|
||||
continue
|
||||
mm_text, ss_text = _parse_mmss_from_full_text(source_text)
|
||||
if not (mm_text and ss_text):
|
||||
continue
|
||||
if _detail_verbose_logs(analyser):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
"已有OCR文本命中倒计时fallback",
|
||||
source=source_name,
|
||||
text=str(source_text or "")[:80],
|
||||
mm=mm_text,
|
||||
ss=ss_text,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return mm_text, ss_text
|
||||
return countdown_mm_raw, countdown_ss_raw
|
||||
|
||||
|
||||
def _select_countdown_from_candidates(
|
||||
analyser: Any,
|
||||
candidate_meta: List[Dict[str, Any]],
|
||||
@@ -667,10 +697,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
ui_version = str(profile.get("version") or "v2_0")
|
||||
ocr_switches = FudaiDetailOcrSwitches()
|
||||
|
||||
countdown_full_ocr_in_critical_path = _should_schedule_countdown_full_ocr(
|
||||
analyser,
|
||||
ocr_switches,
|
||||
)
|
||||
info_line_ocr_in_critical_path = _should_schedule_info_line_ocr(
|
||||
analyser,
|
||||
ocr_switches,
|
||||
@@ -757,69 +783,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 额外整行倒计时图:默认不进关键路径;需要专项兜底时显式开启。
|
||||
try:
|
||||
if countdown_full_ocr_in_critical_path:
|
||||
analyser.cut_pic(*countdown_box, "", "福袋倒计时_整行", analyser.y_pianyi)
|
||||
elif ocr_switches.countdown:
|
||||
analyser._log_kv(
|
||||
"性能",
|
||||
"跳过倒计时整行OCR关键路径",
|
||||
reason="countdown_full_ocr_not_in_critical_path",
|
||||
enable_key="fudai_detail_countdown_full_ocr_in_critical_path_enabled",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 额外切割倒计时候选区域(用于并行多候选OCR,根治分钟框偏移)
|
||||
countdown_candidate_meta: List[Dict[str, Any]] = []
|
||||
try:
|
||||
candidate_boxes = [tuple(countdown_box)] if ui_version == "v2_0" else _build_countdown_candidate_boxes(renwu)
|
||||
for idx, box in enumerate(candidate_boxes):
|
||||
is_primary = (tuple(box) == tuple(countdown_box))
|
||||
if is_primary:
|
||||
# 主候选沿用原始“福袋倒计时_分钟/秒”命名,兼容现有OCR与调试图像链路
|
||||
mm_name = "福袋倒计时_分钟"
|
||||
ss_name = "福袋倒计时_秒"
|
||||
mm_key = "countdown_mm"
|
||||
ss_key = "countdown_ss"
|
||||
else:
|
||||
mm_name = f"福袋倒计时_候选{idx}_分钟"
|
||||
ss_name = f"福袋倒计时_候选{idx}_秒"
|
||||
mm_key = f"countdown_mm_c{idx}"
|
||||
ss_key = f"countdown_ss_c{idx}"
|
||||
if ocr_switches.countdown:
|
||||
_cut_countdown_candidate_regions(
|
||||
analyser,
|
||||
tuple(box),
|
||||
mm_name,
|
||||
ss_name,
|
||||
save_debug_images=False,
|
||||
)
|
||||
|
||||
countdown_candidate_meta.append(
|
||||
{
|
||||
"idx": idx,
|
||||
"box": tuple(box),
|
||||
"is_primary": is_primary,
|
||||
"mm_name": mm_name,
|
||||
"ss_name": ss_name,
|
||||
"mm_result_key": mm_key,
|
||||
"ss_result_key": ss_key,
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
countdown_candidate_meta = [
|
||||
{
|
||||
"idx": 0,
|
||||
"box": tuple(countdown_box),
|
||||
"is_primary": True,
|
||||
"mm_name": "福袋倒计时_分钟",
|
||||
"ss_name": "福袋倒计时_秒",
|
||||
"mm_result_key": "countdown_mm",
|
||||
"ss_result_key": "countdown_ss",
|
||||
}
|
||||
]
|
||||
|
||||
# 准备任务列表区域的截图(用于并行OCR)
|
||||
try:
|
||||
task_list_ocr_in_critical_path = _should_schedule_task_list_ocr(
|
||||
@@ -941,8 +904,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
)
|
||||
ocr_task_list = _ocr_runner.ocr_task_list
|
||||
ocr_content = _ocr_runner.ocr_content
|
||||
ocr_countdown_mm = _ocr_runner.ocr_countdown_mm
|
||||
ocr_countdown_ss = _ocr_runner.ocr_countdown_ss
|
||||
ocr_countdown_full = _ocr_runner.ocr_countdown_full
|
||||
ocr_value = _ocr_runner.ocr_value
|
||||
ocr_button = _ocr_runner.ocr_button
|
||||
@@ -966,10 +927,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
if _should_schedule_task_list_ocr(analyser, ocr_switches):
|
||||
task_funcs["task_list"] = ocr_task_list
|
||||
if ocr_switches.countdown:
|
||||
task_funcs["countdown_mm"] = ocr_countdown_mm
|
||||
task_funcs["countdown_ss"] = ocr_countdown_ss
|
||||
if countdown_full_ocr_in_critical_path:
|
||||
task_funcs["countdown_full"] = ocr_countdown_full
|
||||
task_funcs["countdown_full"] = ocr_countdown_full
|
||||
if ocr_switches.value:
|
||||
task_funcs["value"] = ocr_value
|
||||
if ocr_switches.button:
|
||||
@@ -995,35 +953,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
reason="info_line_ocr_not_in_critical_path",
|
||||
enable_key="fudai_detail_info_line_ocr_in_critical_path_enabled",
|
||||
)
|
||||
# 并行补充倒计时额外候选(保持并行,不降级)
|
||||
for meta in countdown_candidate_meta:
|
||||
if meta.get("is_primary"):
|
||||
continue
|
||||
mm_name = str(meta.get("mm_name") or "")
|
||||
ss_name = str(meta.get("ss_name") or "")
|
||||
mm_key = str(meta.get("mm_result_key") or "")
|
||||
ss_key = str(meta.get("ss_result_key") or "")
|
||||
if not mm_name or not ss_name or not mm_key or not ss_key:
|
||||
continue
|
||||
if ocr_switches.countdown:
|
||||
task_funcs[mm_key] = (
|
||||
lambda name=mm_name: "".join(
|
||||
ch
|
||||
for ch in str(
|
||||
analyser.operation.analyse_pic_digits(name, 0) or ""
|
||||
)
|
||||
if ch.isdigit()
|
||||
)
|
||||
)
|
||||
task_funcs[ss_key] = (
|
||||
lambda name=ss_name: "".join(
|
||||
ch
|
||||
for ch in str(
|
||||
analyser.operation.analyse_pic_digits(name, 0) or ""
|
||||
)
|
||||
if ch.isdigit()
|
||||
)
|
||||
)
|
||||
# 如果配置启用,避免把 content 任务加入并行队列,彻底不调度该OCR
|
||||
if ocr_switches.content:
|
||||
task_funcs["content"] = ocr_content
|
||||
@@ -1035,7 +964,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
|
||||
# 收集结果并记录耗时
|
||||
results, durations = run_parallel_tasks(task_funcs, executor)
|
||||
extra_countdown_results: Dict[str, Any] = {}
|
||||
for name, res in results.items():
|
||||
if name == "task_list":
|
||||
task_list_raw = res
|
||||
@@ -1057,35 +985,25 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
info_line_raw = res
|
||||
elif name == "live_room_title":
|
||||
live_room_title_raw, live_room_title_text_raw = res
|
||||
elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"):
|
||||
extra_countdown_results[name] = res
|
||||
|
||||
try:
|
||||
if not ocr_switches.countdown:
|
||||
raise RuntimeError("countdown_ocr_disabled")
|
||||
countdown_mm_raw, countdown_ss_raw, picked = _select_countdown_from_candidates(
|
||||
analyser,
|
||||
countdown_candidate_meta,
|
||||
countdown_mm_raw,
|
||||
countdown_ss_raw,
|
||||
extra_countdown_results,
|
||||
room_title_hint=str(live_room_title_text_raw or live_room_title_raw or ""),
|
||||
)
|
||||
mm_full, ss_full = _parse_mmss_from_full_text(countdown_full_raw)
|
||||
if countdown_full_ocr_in_critical_path and mm_full and ss_full:
|
||||
if mm_full and ss_full:
|
||||
countdown_mm_raw, countdown_ss_raw = mm_full, ss_full
|
||||
if _detail_verbose_logs(analyser):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
"倒计时整行优先命中,覆盖分割候选结果",
|
||||
"倒计时整行命中",
|
||||
full_text=str(countdown_full_raw or "")[:80],
|
||||
mm=mm_full,
|
||||
ss=ss_full,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elif renwu == 1 and info_line_raw:
|
||||
if renwu == 1 and info_line_raw:
|
||||
mm_line, ss_line = _parse_mmss_from_full_text(info_line_raw)
|
||||
if mm_line and ss_line:
|
||||
countdown_mm_raw, countdown_ss_raw = mm_line, ss_line
|
||||
@@ -1100,26 +1018,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if picked:
|
||||
picked_idx = int(picked.get("idx", -1))
|
||||
if _detail_verbose_logs(analyser):
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
(
|
||||
"倒计时候选选择结果"
|
||||
f" idx={picked_idx}"
|
||||
f" mm={str(picked.get('mm') or '')}"
|
||||
f" ss={str(picked.get('ss') or '')}"
|
||||
f" valid={bool(picked.get('valid'))}"
|
||||
),
|
||||
chosen_idx=picked_idx,
|
||||
chosen_is_primary=bool(picked.get("is_primary")),
|
||||
chosen_mm=str(picked.get("mm") or ""),
|
||||
chosen_ss=str(picked.get("ss") or ""),
|
||||
chosen_score=int(picked.get("score", 0) or 0),
|
||||
chosen_valid=bool(picked.get("valid")),
|
||||
candidates=len(countdown_candidate_meta),
|
||||
)
|
||||
# 回写连续性状态:供下一次候选评分使用(同直播间递减约束)。
|
||||
try:
|
||||
room_for_state = str(live_room_title_text_raw or live_room_title_raw or "").strip()
|
||||
@@ -1182,8 +1080,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
allowed_heavy_fields: set[str] = set()
|
||||
if ocr_switches.content:
|
||||
allowed_heavy_fields.add("content")
|
||||
if ocr_switches.countdown:
|
||||
allowed_heavy_fields.update({"countdown_mm", "countdown_ss"})
|
||||
if ocr_switches.value:
|
||||
allowed_heavy_fields.add("value")
|
||||
if ocr_switches.task:
|
||||
@@ -1194,51 +1090,19 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
|
||||
if heavy_fields:
|
||||
heavy_res = run_heavy_ocr(analyser, heavy_fields)
|
||||
picked_heavy = None
|
||||
|
||||
def _prefer(new_val: Any, old_val: Any):
|
||||
return new_val if not is_blank_text(new_val) else old_val
|
||||
|
||||
task_list_raw = _prefer(heavy_res.get("task_list"), task_list_raw)
|
||||
fudai_content_raw = _prefer(heavy_res.get("content"), fudai_content_raw)
|
||||
countdown_mm_raw = _prefer(heavy_res.get("countdown_mm"), countdown_mm_raw)
|
||||
countdown_ss_raw = _prefer(heavy_res.get("countdown_ss"), countdown_ss_raw)
|
||||
value_raw = _prefer(heavy_res.get("value"), value_raw)
|
||||
button_text_raw = _prefer(heavy_res.get("button"), button_text_raw)
|
||||
|
||||
try:
|
||||
if ("countdown_mm" in heavy_fields) or ("countdown_ss" in heavy_fields):
|
||||
countdown_mm_raw, countdown_ss_raw, picked_heavy = _select_countdown_from_candidates(
|
||||
analyser,
|
||||
countdown_candidate_meta,
|
||||
countdown_mm_raw,
|
||||
countdown_ss_raw,
|
||||
extra_countdown_results,
|
||||
room_title_hint=str(live_room_title_text_raw or live_room_title_raw or ""),
|
||||
)
|
||||
mm_full_h, ss_full_h = _parse_mmss_from_full_text(countdown_full_raw)
|
||||
if countdown_full_ocr_in_critical_path and mm_full_h and ss_full_h:
|
||||
if mm_full_h and ss_full_h:
|
||||
countdown_mm_raw, countdown_ss_raw = mm_full_h, ss_full_h
|
||||
if picked_heavy:
|
||||
picked_heavy_idx = int(picked_heavy.get("idx", -1))
|
||||
if _detail_verbose_logs(analyser):
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
(
|
||||
"重OCR后倒计时候选复选结果"
|
||||
f" idx={picked_heavy_idx}"
|
||||
f" mm={str(picked_heavy.get('mm') or '')}"
|
||||
f" ss={str(picked_heavy.get('ss') or '')}"
|
||||
f" valid={bool(picked_heavy.get('valid'))}"
|
||||
),
|
||||
chosen_idx=picked_heavy_idx,
|
||||
chosen_is_primary=bool(picked_heavy.get("is_primary")),
|
||||
chosen_mm=str(picked_heavy.get("mm") or ""),
|
||||
chosen_ss=str(picked_heavy.get("ss") or ""),
|
||||
chosen_score=int(picked_heavy.get("score", 0) or 0),
|
||||
chosen_valid=bool(picked_heavy.get("valid")),
|
||||
candidates=len(countdown_candidate_meta),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1381,8 +1245,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
)
|
||||
ocr_task_list_fallback = _fb_runner.ocr_task_list
|
||||
ocr_content_fallback = _fb_runner.ocr_content
|
||||
ocr_countdown_mm_fallback = _fb_runner.ocr_countdown_mm
|
||||
ocr_countdown_ss_fallback = _fb_runner.ocr_countdown_ss
|
||||
ocr_countdown_full_fallback = _fb_runner.ocr_countdown_full
|
||||
ocr_value_fallback = _fb_runner.ocr_value
|
||||
ocr_button_fallback = _fb_runner.ocr_button
|
||||
@@ -1400,10 +1262,7 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
if _should_schedule_task_list_ocr(analyser, ocr_switches):
|
||||
task_funcs["task_list"] = ocr_task_list_fallback
|
||||
if ocr_switches.countdown:
|
||||
task_funcs["countdown_mm"] = ocr_countdown_mm_fallback
|
||||
task_funcs["countdown_ss"] = ocr_countdown_ss_fallback
|
||||
if countdown_full_ocr_in_critical_path:
|
||||
task_funcs["countdown_full"] = ocr_countdown_full_fallback
|
||||
task_funcs["countdown_full"] = ocr_countdown_full_fallback
|
||||
if ocr_switches.value:
|
||||
task_funcs["value"] = ocr_value_fallback
|
||||
if ocr_switches.button:
|
||||
@@ -1412,35 +1271,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
task_funcs["participants"] = (
|
||||
lambda: analyser.operation.analyse_pic_word("福袋参与人数", 0)
|
||||
)
|
||||
# 备用并行中也加入倒计时额外候选
|
||||
for meta in countdown_candidate_meta:
|
||||
if meta.get("is_primary"):
|
||||
continue
|
||||
mm_name = str(meta.get("mm_name") or "")
|
||||
ss_name = str(meta.get("ss_name") or "")
|
||||
mm_key = str(meta.get("mm_result_key") or "")
|
||||
ss_key = str(meta.get("ss_result_key") or "")
|
||||
if not mm_name or not ss_name or not mm_key or not ss_key:
|
||||
continue
|
||||
if ocr_switches.countdown:
|
||||
task_funcs[mm_key] = (
|
||||
lambda name=mm_name: "".join(
|
||||
ch
|
||||
for ch in str(
|
||||
analyser.operation.analyse_pic_digits(name, 0) or ""
|
||||
)
|
||||
if ch.isdigit()
|
||||
)
|
||||
)
|
||||
task_funcs[ss_key] = (
|
||||
lambda name=ss_name: "".join(
|
||||
ch
|
||||
for ch in str(
|
||||
analyser.operation.analyse_pic_digits(name, 0) or ""
|
||||
)
|
||||
if ch.isdigit()
|
||||
)
|
||||
)
|
||||
# 如果配置允许,则加入备用 content OCR,否则不调度
|
||||
if ocr_switches.content:
|
||||
task_funcs["content"] = ocr_content_fallback
|
||||
@@ -1450,7 +1280,6 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
participants_raw = None
|
||||
countdown_full_raw_fb = None
|
||||
results, durations = run_parallel_tasks(task_funcs, executor)
|
||||
extra_countdown_results_fb: Dict[str, Any] = {}
|
||||
for name, res in results.items():
|
||||
if name == "task_list":
|
||||
task_list_raw = res
|
||||
@@ -1468,45 +1297,13 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo
|
||||
button_text_raw = res
|
||||
elif name == "participants":
|
||||
participants_raw = res
|
||||
elif name.startswith("countdown_mm_c") or name.startswith("countdown_ss_c"):
|
||||
extra_countdown_results_fb[name] = res
|
||||
|
||||
try:
|
||||
if not ocr_switches.countdown:
|
||||
raise RuntimeError("countdown_ocr_disabled")
|
||||
countdown_mm_raw, countdown_ss_raw, picked_fb = _select_countdown_from_candidates(
|
||||
analyser,
|
||||
countdown_candidate_meta,
|
||||
countdown_mm_raw,
|
||||
countdown_ss_raw,
|
||||
extra_countdown_results_fb,
|
||||
room_title_hint=str(
|
||||
getattr(analyser, "current_room_title_raw", "") or ""
|
||||
),
|
||||
)
|
||||
mm_fb, ss_fb = _parse_mmss_from_full_text(countdown_full_raw_fb)
|
||||
if countdown_full_ocr_in_critical_path and mm_fb and ss_fb:
|
||||
if mm_fb and ss_fb:
|
||||
countdown_mm_raw, countdown_ss_raw = mm_fb, ss_fb
|
||||
if picked_fb:
|
||||
picked_fb_idx = int(picked_fb.get("idx", -1))
|
||||
if _detail_verbose_logs(analyser):
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
(
|
||||
"备用并行倒计时候选选择结果"
|
||||
f" idx={picked_fb_idx}"
|
||||
f" mm={str(picked_fb.get('mm') or '')}"
|
||||
f" ss={str(picked_fb.get('ss') or '')}"
|
||||
f" valid={bool(picked_fb.get('valid'))}"
|
||||
),
|
||||
chosen_idx=picked_fb_idx,
|
||||
chosen_is_primary=bool(picked_fb.get("is_primary")),
|
||||
chosen_mm=str(picked_fb.get("mm") or ""),
|
||||
chosen_ss=str(picked_fb.get("ss") or ""),
|
||||
chosen_score=int(picked_fb.get("score", 0) or 0),
|
||||
chosen_valid=bool(picked_fb.get("valid")),
|
||||
candidates=len(countdown_candidate_meta),
|
||||
)
|
||||
try:
|
||||
mm_state, ss_state = _normalize_countdown_pair(countdown_mm_raw, countdown_ss_raw)
|
||||
room_for_state = str(
|
||||
|
||||
@@ -6,8 +6,33 @@ import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
|
||||
"抽奖剩余时间不足",
|
||||
"剩余时间不足",
|
||||
"下次再来参与",
|
||||
"下次再来",
|
||||
"还没到时间",
|
||||
"无法参与",
|
||||
"不能参与",
|
||||
"不可参与",
|
||||
"活动已结束",
|
||||
"活动结束",
|
||||
"已结束",
|
||||
"已过期",
|
||||
"已截止",
|
||||
"时长不足",
|
||||
)
|
||||
|
||||
|
||||
def is_button_text_non_actionable(button_text: str) -> bool:
|
||||
txt = str(button_text or "").strip()
|
||||
return bool(txt and any(snippet in txt for snippet in NON_ACTIONABLE_BUTTON_TEXT_SNIPPETS))
|
||||
|
||||
|
||||
def decide_button_status(button_text: str) -> str:
|
||||
txt = str(button_text or "").strip()
|
||||
if is_button_text_non_actionable(txt):
|
||||
return "不可参与"
|
||||
# 新版按钮文案:“直播间,否则会失去抽奖机会” 实际语义等价于已参与后等待开奖。
|
||||
if "失去抽奖" in txt or "否则会失去" in txt:
|
||||
return "已参与"
|
||||
|
||||
@@ -5,8 +5,14 @@ from __future__ import annotations
|
||||
|
||||
def extract_countdown_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取倒计时数字,最多 max_digits 位。"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
raw = str(text or "")
|
||||
normalized = raw.translate(str.maketrans({"O": "0", "o": "0", "U": "0", "u": "0"}))
|
||||
digits = "".join(ch for ch in normalized if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
candidate = digits[:max_digits]
|
||||
if set(candidate) == {"0"} and digits.lstrip("0"):
|
||||
actual = digits.lstrip("0")[:max_digits]
|
||||
return actual.zfill(max_digits)
|
||||
# 倒计时分钟/秒区域偶发会混入噪声数字(如 "601"、"0123")。
|
||||
# 对 2 位提取场景,优先尝试滑窗中第一个“合法”候选(00~59),
|
||||
# 若都不合法再回退到原有左侧截取策略。
|
||||
@@ -19,10 +25,6 @@ def extract_countdown_digits(text: str, max_digits: int = 2) -> str:
|
||||
continue
|
||||
if 0 <= v <= 59:
|
||||
return win
|
||||
candidate = digits[:max_digits]
|
||||
if set(candidate) == {"0"} and digits.lstrip("0"):
|
||||
actual = digits.lstrip("0")[:max_digits]
|
||||
return actual.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
|
||||
@@ -16,17 +16,12 @@ from typing import Tuple
|
||||
|
||||
|
||||
def _extract_digits(text: str, max_digits: int = 2) -> str:
|
||||
"""提取数字,最多 max_digits 位,取前 max_digits 位优先。"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) > max_digits:
|
||||
candidate = digits[:max_digits]
|
||||
if set(candidate) == {"0"} and digits.lstrip("0"):
|
||||
actual = digits.lstrip("0")[:max_digits]
|
||||
return actual.zfill(max_digits)
|
||||
return candidate
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return digits
|
||||
"""提取倒计时数字,兼容 OCR 把 00 识别成 UU/OO 的噪声。"""
|
||||
from douyin.fudai.douyin_fudai_core_pkg.countdown_parse import (
|
||||
extract_countdown_digits,
|
||||
)
|
||||
|
||||
return extract_countdown_digits(text, max_digits=max_digits)
|
||||
|
||||
|
||||
def read_countdown_split(
|
||||
|
||||
@@ -64,37 +64,8 @@ def cut_detail_regions(
|
||||
if not countdown_enabled:
|
||||
return countdown_box
|
||||
|
||||
# 2. 倒计时区域分割(与候选切图保持一致,避免分钟框吃到前缀噪声)
|
||||
x1, y1, x2, y2 = countdown_box
|
||||
w = max(1, int(x2 - x1))
|
||||
h = max(1, int(y2 - y1))
|
||||
# 纵向只取倒计时 chip 的数字行,避免把上方黑底或下方商品标题混入分钟/秒 OCR。
|
||||
digit_y1 = min(y2 - 2, y1 + max(1, int(h * 0.34)))
|
||||
digit_y2 = min(y2, max(digit_y1 + 2, y1 + max(2, int(h * 0.92))))
|
||||
mm_x1 = x1
|
||||
mm_x2 = min(x2, x1 + max(1, int(w * 0.26)))
|
||||
ss_x1 = min(x2 - 1, x1 + max(1, int(w * 0.38)))
|
||||
ss_x2 = min(x2, max(ss_x1 + 1, x1 + max(2, int(w * 0.64))))
|
||||
|
||||
analyser.cut_pic(
|
||||
mm_x1,
|
||||
digit_y1,
|
||||
mm_x2,
|
||||
digit_y2,
|
||||
"",
|
||||
"福袋倒计时_分钟",
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
|
||||
analyser.cut_pic(
|
||||
ss_x1,
|
||||
digit_y1,
|
||||
ss_x2,
|
||||
digit_y2,
|
||||
"",
|
||||
"福袋倒计时_秒",
|
||||
analyser.y_pianyi,
|
||||
)
|
||||
# 2. 倒计时只保留整行图,避免分钟/秒小框裁偏后误触发提前参与。
|
||||
analyser.cut_pic(*countdown_box, "", "福袋倒计时_整行", analyser.y_pianyi)
|
||||
|
||||
# 3. 福袋价值
|
||||
if value_enabled:
|
||||
|
||||
@@ -150,16 +150,20 @@ def _ocr_digits_with_fallback(analyser, picname: str) -> str:
|
||||
|
||||
返回提取到的数字字符串;都失败返回 ""。
|
||||
"""
|
||||
from douyin.fudai.douyin_fudai_core_pkg.countdown_parse import (
|
||||
extract_countdown_digits,
|
||||
)
|
||||
|
||||
digits = ""
|
||||
try:
|
||||
raw = analyser.operation.analyse_pic_digits(picname, 1)
|
||||
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
|
||||
digits = extract_countdown_digits(raw, max_digits=2)
|
||||
except Exception:
|
||||
pass
|
||||
if not digits:
|
||||
try:
|
||||
raw = analyser.operation.analyse_pic_word(picname, 1)
|
||||
digits = "".join(ch for ch in str(raw or "") if ch.isdigit())
|
||||
digits = extract_countdown_digits(raw, max_digits=2)
|
||||
except Exception:
|
||||
pass
|
||||
return digits
|
||||
@@ -18,7 +18,7 @@ from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from typing import Any, Dict, Optional, Sequence, Tuple
|
||||
|
||||
|
||||
# OCR 按钮关键词列表(识别到任一即可短路返回,省 50% 时间)
|
||||
@@ -48,6 +48,184 @@ def _safe_preprocess(analyser, name: str) -> str:
|
||||
return name
|
||||
|
||||
|
||||
def _valid_countdown_digits(text: Any) -> str:
|
||||
"""提取合法倒计时两位数字;非法或越界返回空。"""
|
||||
from douyin.fudai.douyin_fudai_core_pkg.countdown_parse import (
|
||||
extract_countdown_digits,
|
||||
)
|
||||
|
||||
digits = extract_countdown_digits(str(text or ""), max_digits=2)
|
||||
if not digits:
|
||||
return ""
|
||||
try:
|
||||
value = int(digits)
|
||||
except Exception:
|
||||
return ""
|
||||
return digits if 0 <= value <= 59 else ""
|
||||
|
||||
|
||||
def _choose_countdown_vote(votes: Sequence[str]) -> str:
|
||||
"""按多数票选择倒计时数字;最高票并列时返回空,避免错识别误参与。"""
|
||||
if not votes:
|
||||
return ""
|
||||
counts: Dict[str, int] = {}
|
||||
for value in votes:
|
||||
counts[value] = counts.get(value, 0) + 1
|
||||
max_count = max(counts.values())
|
||||
winners = [value for value, count in counts.items() if count == max_count]
|
||||
return winners[0] if len(winners) == 1 else ""
|
||||
|
||||
|
||||
def _cv_detect_two_zero_digits(picname: str) -> str:
|
||||
"""用简单像素组件检测倒计时分钟图中的粉色 00。"""
|
||||
try:
|
||||
from PIL import Image
|
||||
from douyin.core.path_config import get_cut_pic_path
|
||||
|
||||
path = get_cut_pic_path(picname)
|
||||
img_raw = Image.open(path)
|
||||
try:
|
||||
img_raw.load()
|
||||
img = img_raw.convert("RGB")
|
||||
finally:
|
||||
img_raw.close()
|
||||
w, h = img.size
|
||||
if w <= 0 or h <= 0:
|
||||
return ""
|
||||
|
||||
mask = set()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r, g, b = img.getpixel((x, y))
|
||||
if r > 180 and g < 140 and b > 110 and (r - g) > 70:
|
||||
mask.add((x, y))
|
||||
|
||||
components = []
|
||||
while mask:
|
||||
start = mask.pop()
|
||||
stack = [start]
|
||||
xs = []
|
||||
ys = []
|
||||
while stack:
|
||||
x, y = stack.pop()
|
||||
xs.append(x)
|
||||
ys.append(y)
|
||||
for nx in (x - 1, x, x + 1):
|
||||
for ny in (y - 1, y, y + 1):
|
||||
if (nx, ny) in mask:
|
||||
mask.remove((nx, ny))
|
||||
stack.append((nx, ny))
|
||||
if len(xs) >= 20:
|
||||
components.append((len(xs), (min(xs), min(ys), max(xs), max(ys))))
|
||||
|
||||
components = sorted(components, key=lambda item: item[0], reverse=True)[:2]
|
||||
if len(components) != 2:
|
||||
return ""
|
||||
areas = [item[0] for item in components]
|
||||
boxes = [item[1] for item in components]
|
||||
if min(areas) / max(areas) < 0.70:
|
||||
return ""
|
||||
widths = [box[2] - box[0] + 1 for box in boxes]
|
||||
heights = [box[3] - box[1] + 1 for box in boxes]
|
||||
if min(widths) < 8 or min(heights) < 10:
|
||||
return ""
|
||||
if max(abs(heights[0] - heights[1]), abs(widths[0] - widths[1])) > 8:
|
||||
return ""
|
||||
return "00"
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _read_countdown_digits(
|
||||
analyser,
|
||||
picname: str,
|
||||
*,
|
||||
fallback_picnames: Sequence[str] = (),
|
||||
) -> str:
|
||||
"""读取倒计时分/秒小图,使用多预处理 OCR 投票降低单次识别歪斜。"""
|
||||
picnames = []
|
||||
for name in (picname, *tuple(fallback_picnames or ())):
|
||||
if name and name not in picnames:
|
||||
picnames.append(str(name))
|
||||
|
||||
votes = []
|
||||
raw_results = []
|
||||
last_exc: Optional[BaseException] = None
|
||||
successful_call = False
|
||||
|
||||
for name in picnames:
|
||||
for mode in (0, 1, 2):
|
||||
try:
|
||||
raw = str(analyser.operation.analyse_pic_digits(name, mode) or "")
|
||||
successful_call = True
|
||||
except Exception as exc:
|
||||
last_exc = exc
|
||||
continue
|
||||
digits = _valid_countdown_digits(raw)
|
||||
raw_results.append((name, mode, raw, digits))
|
||||
if digits:
|
||||
votes.append(digits)
|
||||
|
||||
chosen = _choose_countdown_vote(votes)
|
||||
if chosen:
|
||||
if chosen != "00":
|
||||
for name in reversed(picnames):
|
||||
cv_digits = _cv_detect_two_zero_digits(name)
|
||||
if cv_digits == "00":
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
"倒计时数字OCR非00,忽略CV的00覆盖结果",
|
||||
picname=name,
|
||||
ocr_chosen=chosen,
|
||||
votes=list(votes),
|
||||
raw_results=raw_results[:8],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
if len(set(votes)) > 1:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
"倒计时数字OCR投票存在分歧,已选择多数/优先结果",
|
||||
picname=picname,
|
||||
chosen=chosen,
|
||||
votes=list(votes),
|
||||
raw_results=raw_results[:8],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return chosen
|
||||
|
||||
if not successful_call and last_exc is not None:
|
||||
raise last_exc
|
||||
|
||||
if votes:
|
||||
if picnames:
|
||||
primary_votes = [
|
||||
digits
|
||||
for name, _mode, _raw, digits in raw_results
|
||||
if name == picnames[0] and digits
|
||||
]
|
||||
if primary_votes and len(set(primary_votes)) == 1:
|
||||
primary_chosen = primary_votes[0]
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"倒计时",
|
||||
"倒计时数字OCR投票打平,优先采用预处理图一致结果",
|
||||
picname=picnames[0],
|
||||
chosen=primary_chosen,
|
||||
votes=list(votes),
|
||||
raw_results=raw_results[:8],
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return primary_chosen
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
class OcrTaskRunner:
|
||||
"""7 个并行 OCR 子任务的运行器。
|
||||
|
||||
@@ -149,13 +327,16 @@ class OcrTaskRunner:
|
||||
self._record_duration("ocr_content", start)
|
||||
|
||||
def ocr_countdown_mm(self) -> Optional[str]:
|
||||
"""OCR 识别福袋倒计时分钟(纯数字模型,无回退)。"""
|
||||
"""OCR 识别福袋倒计时分钟。"""
|
||||
start = time.time()
|
||||
try:
|
||||
raw = str(
|
||||
self.analyser.operation.analyse_pic_digits("福袋倒计时_分钟", 0) or ""
|
||||
raw_name = "福袋倒计时_分钟"
|
||||
picname = _safe_preprocess(self.analyser, raw_name)
|
||||
return _read_countdown_digits(
|
||||
self.analyser,
|
||||
picname,
|
||||
fallback_picnames=(raw_name,),
|
||||
)
|
||||
return "".join(ch for ch in raw if ch.isdigit())
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别倒计时分钟失败", e)
|
||||
return None
|
||||
@@ -163,13 +344,16 @@ class OcrTaskRunner:
|
||||
self._record_duration("ocr_countdown_mm", start)
|
||||
|
||||
def ocr_countdown_ss(self) -> Optional[str]:
|
||||
"""OCR 识别福袋倒计时秒(纯数字模型,无回退)。"""
|
||||
"""OCR 识别福袋倒计时秒。"""
|
||||
start = time.time()
|
||||
try:
|
||||
raw = str(
|
||||
self.analyser.operation.analyse_pic_digits("福袋倒计时_秒", 0) or ""
|
||||
raw_name = "福袋倒计时_秒"
|
||||
picname = _safe_preprocess(self.analyser, raw_name)
|
||||
return _read_countdown_digits(
|
||||
self.analyser,
|
||||
picname,
|
||||
fallback_picnames=(raw_name,),
|
||||
)
|
||||
return "".join(ch for ch in raw if ch.isdigit())
|
||||
except Exception as e:
|
||||
self._log_warn("OCR识别倒计时秒失败", e)
|
||||
return None
|
||||
|
||||
@@ -67,8 +67,7 @@ class FudaiDetector:
|
||||
真机样本显示可点击入口集中在左侧;右侧福利/消费券横幅也会出现相同礼物色,
|
||||
不能进入福袋详情,避免纳入搜索。
|
||||
"""
|
||||
# 旧区域 X=153..561/Y=348..451 里右侧已被直播间营销券横幅污染。
|
||||
# 2026-06-18 真机 light6 成功点击集中在 x=83..209,失败券条候选出现在 x=366。
|
||||
# 只扫描左上真实小福袋入口热区;下方大福袋动画/背景挂件不能参与入口判断。
|
||||
self.search_regions = [
|
||||
{
|
||||
"name": "实际福袋区域",
|
||||
@@ -76,9 +75,9 @@ class FudaiDetector:
|
||||
"x1": 20 * self.rx // 1080,
|
||||
"x2": 280 * self.rx // 1080,
|
||||
"y_top": 348 * self.ry // 2400 + self.y_pianyi,
|
||||
"y_bottom": 540 * self.ry // 2400 + self.y_pianyi,
|
||||
"y": (348 + 540) // 2 * self.ry // 2400 + self.y_pianyi,
|
||||
"y_range": (540 - 348) // 2 + 1,
|
||||
"y_bottom": 455 * self.ry // 2400 + self.y_pianyi,
|
||||
"y": (348 + 455) // 2 * self.ry // 2400 + self.y_pianyi,
|
||||
"y_range": (455 - 348) // 2 + 1,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -557,7 +556,7 @@ class FudaiDetector:
|
||||
x1 = max(0, detected_x_scaled - 180)
|
||||
x2 = min(width, detected_x_scaled + 180)
|
||||
y1 = max(0, int(300 * self.ry / 2400) + self.y_pianyi)
|
||||
y2 = min(height, int(540 * self.ry / 2400) + self.y_pianyi)
|
||||
y2 = min(height, int(455 * self.ry / 2400) + self.y_pianyi)
|
||||
if x1 >= x2 or y1 >= y2:
|
||||
return False
|
||||
roi_gray = cv2.cvtColor( # type: ignore[attr-defined]
|
||||
|
||||
@@ -72,6 +72,13 @@ def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool:
|
||||
except Exception:
|
||||
window_s = 8.0
|
||||
allow_back = (now_ts - last_ts) >= max(1.0, window_s)
|
||||
try:
|
||||
reservation_direct_attend = bool(
|
||||
getattr(analyser, "_current_attending_reservation_fudai", False)
|
||||
or getattr(analyser, "reservation_after_action_pending", False)
|
||||
)
|
||||
except Exception:
|
||||
reservation_direct_attend = False
|
||||
|
||||
try:
|
||||
if douyin_screenshot_manager is not None:
|
||||
@@ -84,6 +91,7 @@ def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool:
|
||||
"reason": "coupon_popup_before_fudai_click",
|
||||
"coupon_info": info,
|
||||
"allow_back": allow_back,
|
||||
"reservation_direct_attend": reservation_direct_attend,
|
||||
},
|
||||
annotate=True,
|
||||
background=True,
|
||||
@@ -94,7 +102,37 @@ def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool:
|
||||
|
||||
close_sent = False
|
||||
skipped_reason = None
|
||||
if allow_back:
|
||||
if reservation_direct_attend:
|
||||
try:
|
||||
operation = getattr(analyser, "operation", None)
|
||||
click = getattr(operation, "click", None)
|
||||
delay = getattr(operation, "delay", None)
|
||||
if callable(click):
|
||||
try:
|
||||
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
|
||||
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
|
||||
except Exception:
|
||||
rx, ry = 1080, 2400
|
||||
click(
|
||||
getattr(analyser, "device_id", ""),
|
||||
int(540 * rx // 1080),
|
||||
int(2006 * ry // 2400),
|
||||
)
|
||||
close_sent = True
|
||||
if callable(delay):
|
||||
delay(0.2)
|
||||
skipped_reason = "reservation_direct_attend_coupon_click_close"
|
||||
except Exception as close_error:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"[福袋查找] 优惠券关闭异常",
|
||||
"预约直参期间优惠券预检命中后点击关闭失败",
|
||||
reason="coupon_popup_before_fudai_click",
|
||||
error=str(close_error),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
elif allow_back:
|
||||
try:
|
||||
operation = getattr(analyser, "operation", None)
|
||||
click_back = getattr(operation, "click_back", None)
|
||||
@@ -133,6 +171,7 @@ def is_coupon_popup_before_fudai_click(analyser: Any, pic: Image.Image) -> bool:
|
||||
coupon_info=info,
|
||||
close_sent=close_sent,
|
||||
skipped_reason=skipped_reason,
|
||||
reservation_direct_attend=reservation_direct_attend,
|
||||
since_last_back_seconds=round(now_ts - last_ts, 2) if last_ts > 0 else None,
|
||||
back_window_seconds=window_s,
|
||||
)
|
||||
|
||||
@@ -24,7 +24,7 @@ from douyin.license.public_key import PUBLIC_KEY_PEM
|
||||
|
||||
LICENSE_FILENAME = "license.dat"
|
||||
ACTIVATION_CODE_PREFIX = "DYGJ-"
|
||||
DEFAULT_ACTIVATION_URL = "http://103.236.55.219:18100/api/v1/activate"
|
||||
DEFAULT_ACTIVATION_URL = "https://dy.absfan.cn/api/v1/activate"
|
||||
DEFAULT_VERIFY_INTERVAL_SECONDS = 600
|
||||
DEFAULT_VERIFY_FAILURES_BEFORE_EXIT = 3
|
||||
|
||||
|
||||
@@ -4,6 +4,6 @@
|
||||
"""
|
||||
|
||||
PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEA3g7inE/9SRkEDseJIp7j5J6vWlvSgitHErypisMY29o=
|
||||
MCowBQYDK2VwAyEA4qs1m9tv6c4lyLzkgBBM0GW0wZfWkHaUKkerts2Hh4c=
|
||||
-----END PUBLIC KEY-----
|
||||
"""
|
||||
@@ -165,23 +165,32 @@ def write_reservations_state(
|
||||
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else ""
|
||||
except Exception:
|
||||
ft_str = ""
|
||||
items.append(
|
||||
{
|
||||
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
|
||||
"content": str(r.get("content") or ""),
|
||||
"future_ts": ft,
|
||||
"future_str": ft_str,
|
||||
"pos_seen": int(r.get("pos_seen") or 0),
|
||||
"room_title": str(r.get("room_title") or ""),
|
||||
"room_title_raw": str(r.get("room_title_raw") or ""),
|
||||
"task_count": int(r.get("task_count") or 2),
|
||||
"time_text": str(r.get("time_text") or ""),
|
||||
"participants": int(r.get("participants") or 0),
|
||||
"copies": int(r.get("copies") or 0),
|
||||
"button_text": str(r.get("button_text") or ""),
|
||||
"button_status": str(r.get("button_status") or ""),
|
||||
}
|
||||
)
|
||||
item = {
|
||||
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
|
||||
"content": str(r.get("content") or ""),
|
||||
"future_ts": ft,
|
||||
"future_str": ft_str,
|
||||
"pos_seen": int(r.get("pos_seen") or 0),
|
||||
"room_title": str(r.get("room_title") or ""),
|
||||
"room_title_raw": str(r.get("room_title_raw") or ""),
|
||||
"task_count": int(r.get("task_count") or 2),
|
||||
"time_text": str(r.get("time_text") or ""),
|
||||
"participants": int(r.get("participants") or 0),
|
||||
"copies": int(r.get("copies") or 0),
|
||||
"button_text": str(r.get("button_text") or ""),
|
||||
"button_status": str(r.get("button_status") or ""),
|
||||
}
|
||||
if "prejoined_fansclub_before_reservation" in r:
|
||||
item["prejoined_fansclub_before_reservation"] = bool(
|
||||
r.get("prejoined_fansclub_before_reservation")
|
||||
)
|
||||
item["prejoin_fansclub_button_text"] = str(
|
||||
r.get("prejoin_fansclub_button_text") or ""
|
||||
)
|
||||
item["prejoin_fansclub_ts"] = float(
|
||||
r.get("prejoin_fansclub_ts") or 0.0
|
||||
)
|
||||
items.append(item)
|
||||
|
||||
data = {
|
||||
"updated_ts": time.time(),
|
||||
|
||||
@@ -14,6 +14,10 @@ from typing import Any, Dict, Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.fudai import douyin_fudai_detail
|
||||
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
|
||||
decide_button_status,
|
||||
is_button_text_non_actionable,
|
||||
)
|
||||
from douyin.handlers import douyin_swipe_handler
|
||||
from douyin.reservation import douyin_reservation_logic
|
||||
|
||||
@@ -29,6 +33,10 @@ _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
|
||||
"发表",
|
||||
"一键",
|
||||
)
|
||||
_DIRECT_ATTEND_FANSCLUB_TEXT_SNIPPETS = (
|
||||
"粉丝团",
|
||||
"关注主播",
|
||||
)
|
||||
|
||||
# 错误处理工具占位(与原文件保持兼容降级)
|
||||
try:
|
||||
@@ -105,6 +113,17 @@ def _direct_attend_open_max_wait_seconds(analyser: Any) -> float:
|
||||
return value
|
||||
|
||||
|
||||
def _direct_attend_retry_open_max_wait_seconds(analyser: Any, base_seconds: float) -> float:
|
||||
try:
|
||||
global_wait = float(getattr(analyser, "fudai_icon_max_wait_seconds", 4.5) or 4.5)
|
||||
except Exception:
|
||||
global_wait = 4.5
|
||||
retry_wait = min(global_wait, 4.5)
|
||||
if retry_wait < base_seconds:
|
||||
retry_wait = base_seconds
|
||||
return retry_wait
|
||||
|
||||
|
||||
def _reservation_key(item: Dict[str, Any]) -> str:
|
||||
try:
|
||||
ft = int(float(item.get("future_ts") or 0.0))
|
||||
@@ -297,6 +316,8 @@ def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, An
|
||||
or getattr(analyser, "button_status", "")
|
||||
or ""
|
||||
)
|
||||
if is_button_text_non_actionable(button_text):
|
||||
return False, button_text, button_status
|
||||
if button_status in _DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES:
|
||||
return True, button_text, button_status
|
||||
if button_text and any(snippet in button_text for snippet in _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS):
|
||||
@@ -304,6 +325,85 @@ 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
|
||||
from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import _BUTTON_KEYWORDS
|
||||
from douyin.utils.ocr_preprocess import preprocess_for_ocr
|
||||
|
||||
try:
|
||||
task_count = int(item.get("task_count") or 2)
|
||||
except Exception:
|
||||
task_count = 2
|
||||
profile = get_fudai_detail_profile("auto", task_count=task_count)
|
||||
button_box = tuple(profile.get("button") or (70, 2020, 1010, 2165))
|
||||
if len(button_box) != 4:
|
||||
return False, "", ""
|
||||
y_pianyi = int(getattr(analyser, "y_pianyi", 0) or 0)
|
||||
analyser.cut_pic(*button_box, "", "参与按钮", y_pianyi)
|
||||
picname = preprocess_for_ocr(analyser, "参与按钮")
|
||||
button_text = str(analyser.operation.analyse_pic_word(picname, 0) or "").strip()
|
||||
if button_text and not any(k in button_text for k in _BUTTON_KEYWORDS):
|
||||
retry_text = str(analyser.operation.analyse_pic_word(picname, 0) or "").strip()
|
||||
if retry_text:
|
||||
button_text = retry_text
|
||||
button_status = decide_button_status(button_text)
|
||||
ok = not is_button_text_non_actionable(button_text) and (
|
||||
button_status in _DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES
|
||||
or any(snippet in button_text for snippet in _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS)
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约直参当前按钮OCR兜底",
|
||||
button_text=button_text[:80],
|
||||
button_status=button_status,
|
||||
result=bool(ok),
|
||||
reason="reservation_button_ocr_fallback_checked",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return bool(ok), button_text, button_status
|
||||
except Exception as exc:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约直参当前按钮OCR兜底异常",
|
||||
error=str(exc),
|
||||
reason="reservation_button_ocr_fallback_exception",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False, "", ""
|
||||
|
||||
|
||||
def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
"""预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。
|
||||
|
||||
@@ -579,6 +679,70 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not opened:
|
||||
retry_open_max_wait_seconds = _direct_attend_retry_open_max_wait_seconds(
|
||||
analyser,
|
||||
open_max_wait_seconds,
|
||||
)
|
||||
try:
|
||||
remain_after_first_scan = future_ts - time.time() if future_ts > 0 else 0.0
|
||||
except Exception:
|
||||
remain_after_first_scan = 0.0
|
||||
retry_allowed = (
|
||||
retry_open_max_wait_seconds > open_max_wait_seconds
|
||||
and future_ts > 0
|
||||
and remain_after_first_scan
|
||||
>= (min_action_seconds + retry_open_max_wait_seconds + 3.0)
|
||||
)
|
||||
if retry_allowed:
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约直参首轮未找到福袋,剩余时间充足,延长一次稳定重扫",
|
||||
reason="direct_attend_icon_retry_after_verified_return",
|
||||
first_open_max_wait_seconds=round(open_max_wait_seconds, 3),
|
||||
retry_open_max_wait_seconds=round(
|
||||
retry_open_max_wait_seconds,
|
||||
3,
|
||||
),
|
||||
remain_seconds_before_retry=round(
|
||||
remain_after_first_scan,
|
||||
3,
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
analyser.operation.delay(0.3)
|
||||
except Exception:
|
||||
time.sleep(0.3)
|
||||
retry_open_start_ts = time.time()
|
||||
opened = douyin_flow_control.find_and_open_fudai_detail(
|
||||
analyser,
|
||||
room_pos_ref,
|
||||
max_wait_seconds=retry_open_max_wait_seconds,
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约直参延长重扫打开详情耗时",
|
||||
direct_open_retry_elapsed=round(
|
||||
time.time() - retry_open_start_ts,
|
||||
3,
|
||||
),
|
||||
open_max_wait_seconds=round(
|
||||
retry_open_max_wait_seconds,
|
||||
3,
|
||||
),
|
||||
remain_seconds_before_retry=round(
|
||||
remain_after_first_scan,
|
||||
3,
|
||||
),
|
||||
opened=bool(opened),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not opened:
|
||||
_log_direct_attend_marker(analyser, "fallback", reason="fudai_icon_not_found")
|
||||
failure_count = _record_direct_attend_failure(
|
||||
@@ -684,10 +848,41 @@ 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)
|
||||
)
|
||||
fallback_source = "reservation_button_text"
|
||||
fallback_reason = "reservation_button_text_fallback_click_sent"
|
||||
if not fallback_ok:
|
||||
fallback_ok, fallback_button_text, fallback_button_status = (
|
||||
_ocr_current_attend_button_if_actionable(analyser, first_reservation)
|
||||
)
|
||||
fallback_source = "current_button_ocr"
|
||||
fallback_reason = "reservation_button_ocr_fallback_click_sent"
|
||||
if fallback_ok:
|
||||
try:
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
@@ -696,13 +891,14 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
button_info=button_info,
|
||||
button_text=fallback_button_text,
|
||||
button_status=fallback_button_status,
|
||||
reason="reservation_button_text_fallback_click_sent",
|
||||
fallback_source=fallback_source,
|
||||
reason=fallback_reason,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
button_info = {
|
||||
**(button_info or {}),
|
||||
"fallback": "reservation_button_text",
|
||||
"fallback": fallback_source,
|
||||
"button_text": fallback_button_text,
|
||||
"button_status": fallback_button_status,
|
||||
}
|
||||
@@ -890,6 +1086,7 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
analyser._waiting_for_lottery_result = True
|
||||
analyser._lottery_result_expected_ts = future_ts
|
||||
analyser._lottery_wait_start_ts = current_time
|
||||
analyser._lottery_wait_prize_value_yuan = prize_value_yuan
|
||||
analyser._current_attending_reservation_fudai = (
|
||||
True # 标记当前正在参与预约福袋
|
||||
)
|
||||
@@ -898,6 +1095,7 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
"[预约] 预约回退后参与成功,设置开奖等待状态",
|
||||
remain_seconds=int(remain_seconds),
|
||||
future_ts=int(future_ts),
|
||||
prize_value_yuan=float(prize_value_yuan or 0.0),
|
||||
lottery_result_expected_ts=int(
|
||||
analyser._lottery_result_expected_ts
|
||||
),
|
||||
|
||||
@@ -47,6 +47,28 @@ def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _looks_like_non_live_tab_title(title: str, raw_title: str = "") -> bool:
|
||||
"""Detect recommendation/top-tab OCR text that must not pollute room_pos_map."""
|
||||
text = f"{title or ''}{raw_title or ''}"
|
||||
normalized = (
|
||||
str(text or "")
|
||||
.replace(" ", "")
|
||||
.replace("·", "")
|
||||
.replace(".", "")
|
||||
.replace("。", "")
|
||||
.replace("=", "")
|
||||
.strip()
|
||||
)
|
||||
if not normalized:
|
||||
return False
|
||||
tab_keywords = ("购精选", "精选商城", "商城关注", "关注直播推荐", "商城关注直播推荐")
|
||||
if any(keyword in normalized for keyword in tab_keywords):
|
||||
return True
|
||||
if normalized in ("购精选商城", "精选商城关注直播推荐", "商城关注直播推荐"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _merge_room_info(base: dict[str, Any], extra: dict[str, Any]) -> dict[str, Any]:
|
||||
"""把 extra 信息合并到 base,优先保留已有强信息。"""
|
||||
try:
|
||||
@@ -402,6 +424,30 @@ def record_room_title_and_pos(analyser: Any) -> bool:
|
||||
room_title = str(existing_info.get("title", "") or "").strip()
|
||||
room_title_raw = str(existing_info.get("title_raw", "") or "").strip()
|
||||
|
||||
if _looks_like_non_live_tab_title(room_title, room_title_raw):
|
||||
try:
|
||||
analyser.current_room_title = ""
|
||||
analyser.current_room_title_raw = ""
|
||||
except Exception:
|
||||
pass
|
||||
analyser._log_kv( # type: ignore[attr-defined]
|
||||
"预约",
|
||||
"[预约] 跳过映射表记录:识别到非直播间标签栏标题",
|
||||
room_pos=room_pos,
|
||||
room_title=room_title,
|
||||
room_title_raw=room_title_raw,
|
||||
reason="non_live_tab_title",
|
||||
level="WARNING",
|
||||
)
|
||||
_emit_flow_flag(
|
||||
analyser,
|
||||
"room_map_record",
|
||||
"skip_non_live_tab_title",
|
||||
room_pos=room_pos,
|
||||
room_title=room_title[:50],
|
||||
)
|
||||
return False
|
||||
|
||||
room_info["title"] = room_title
|
||||
room_info["title_raw"] = room_title_raw
|
||||
|
||||
|
||||
@@ -271,6 +271,14 @@ def add_reservation_core_logic(
|
||||
pass
|
||||
reservations[same_idx].update(dict(item))
|
||||
else:
|
||||
if item.get("prejoined_fansclub_before_reservation"):
|
||||
reservations[same_idx]["prejoined_fansclub_before_reservation"] = True
|
||||
reservations[same_idx]["prejoin_fansclub_button_text"] = str(
|
||||
item.get("prejoin_fansclub_button_text") or ""
|
||||
)
|
||||
reservations[same_idx]["prejoin_fansclub_ts"] = float(
|
||||
item.get("prejoin_fansclub_ts") or 0.0
|
||||
)
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
@@ -283,6 +291,9 @@ def add_reservation_core_logic(
|
||||
if ft > 0
|
||||
else "未知"
|
||||
),
|
||||
prejoined_fansclub_preserved=bool(
|
||||
item.get("prejoined_fansclub_before_reservation")
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -22,6 +22,7 @@ from .helpers import (
|
||||
_extract_content_core,
|
||||
_normalize_room_title_for_matching,
|
||||
_now_ts,
|
||||
_select_reservation_target_for_window,
|
||||
_sort_reservations_inplace,
|
||||
)
|
||||
from .attend_window_helpers import (
|
||||
@@ -273,8 +274,45 @@ def process_reservation_attend_window(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标)
|
||||
target = reservations[0]
|
||||
# 取目标预约:默认最早开奖;若多个预约窗口同时命中,则优先价值更高的。
|
||||
def _dynamic_ahead_for_item(item: ReservationItem) -> float:
|
||||
dynamic_ahead_i, _est_back_times_i = compute_dynamic_ahead(
|
||||
analyser,
|
||||
item,
|
||||
room_pos,
|
||||
reservation_back_swipe_delay_s,
|
||||
join_ahead=float(
|
||||
getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100
|
||||
),
|
||||
)
|
||||
return dynamic_ahead_i
|
||||
|
||||
selected_idx, target = _select_reservation_target_for_window(
|
||||
reservations,
|
||||
now_ts,
|
||||
_dynamic_ahead_for_item,
|
||||
poll_before,
|
||||
)
|
||||
if selected_idx != 0:
|
||||
try:
|
||||
selected_item = reservations.pop(selected_idx)
|
||||
reservations.insert(0, selected_item)
|
||||
target = selected_item
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 多预约窗口冲突,优先选择价值更高预约",
|
||||
selected_index=int(selected_idx),
|
||||
selected_future_ts=int(float(target.get("future_ts") or 0.0)),
|
||||
selected_value=float(target.get("prize_value_yuan") or 0.0),
|
||||
earliest_future_ts=int(float(reservations[1].get("future_ts") or 0.0))
|
||||
if len(reservations) > 1
|
||||
else 0,
|
||||
earliest_value=float(reservations[1].get("prize_value_yuan") or 0.0)
|
||||
if len(reservations) > 1
|
||||
else 0.0,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
ft = float(target.get("future_ts") or 0.0)
|
||||
except Exception:
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import List
|
||||
from typing import List, Tuple
|
||||
|
||||
from ._common import ReservationItem
|
||||
|
||||
@@ -128,3 +128,51 @@ def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None:
|
||||
reservations.sort(key=_key)
|
||||
|
||||
|
||||
def _select_reservation_target_for_window(
|
||||
reservations: List[ReservationItem],
|
||||
now_ts: float,
|
||||
dynamic_ahead_for_item,
|
||||
poll_before: float,
|
||||
) -> Tuple[int, ReservationItem]:
|
||||
"""Pick the highest-value reservation among items whose attend windows overlap now.
|
||||
|
||||
The normal queue order remains earliest-first. This selector only changes behavior
|
||||
when multiple reservations are already actionable at the same time.
|
||||
"""
|
||||
if not reservations:
|
||||
raise IndexError("empty reservations")
|
||||
|
||||
actionable = []
|
||||
for idx, item in enumerate(reservations):
|
||||
try:
|
||||
ft = float(item.get("future_ts") or 0.0)
|
||||
except Exception:
|
||||
ft = 0.0
|
||||
if ft <= 0:
|
||||
continue
|
||||
try:
|
||||
dynamic_ahead = float(dynamic_ahead_for_item(item) or 0.0)
|
||||
except Exception:
|
||||
dynamic_ahead = 0.0
|
||||
window_start = ft - max(0.0, dynamic_ahead)
|
||||
window_end = ft + max(0.0, poll_before)
|
||||
if now_ts < window_start or now_ts > window_end:
|
||||
continue
|
||||
try:
|
||||
value = float(item.get("prize_value_yuan") or 0.0)
|
||||
except Exception:
|
||||
value = 0.0
|
||||
try:
|
||||
created = float(item.get("created_ts") or 0.0)
|
||||
except Exception:
|
||||
created = 0.0
|
||||
actionable.append((idx, value, ft, created, item))
|
||||
|
||||
if not actionable:
|
||||
return 0, reservations[0]
|
||||
|
||||
actionable.sort(key=lambda row: (-row[1], row[2], row[3], row[0]))
|
||||
idx, _value, _ft, _created, item = actionable[0]
|
||||
return idx, item
|
||||
|
||||
|
||||
@@ -172,6 +172,16 @@ def record_high_value_reservation(
|
||||
),
|
||||
"button_status": str(getattr(analyser, "_fudai_button_status", "") or ""),
|
||||
}
|
||||
if bool(getattr(analyser, "_reservation_prejoined_fansclub", False)):
|
||||
item["prejoined_fansclub_before_reservation"] = True
|
||||
item["prejoin_fansclub_button_text"] = str(
|
||||
getattr(analyser, "_reservation_prejoin_fansclub_button_text", "")
|
||||
or ""
|
||||
)
|
||||
item["prejoin_fansclub_ts"] = float(
|
||||
getattr(analyser, "_reservation_prejoin_fansclub_ts", 0.0)
|
||||
or 0.0
|
||||
)
|
||||
except Exception as e:
|
||||
if _RESERVATION_ERROR_UTILS_AVAILABLE:
|
||||
log_reservation_error(
|
||||
|
||||
@@ -71,6 +71,7 @@ def run_startup_update_check_early(
|
||||
app_name: str,
|
||||
*,
|
||||
update_check: Callable[..., object] | None = None,
|
||||
progress_callback: Callable[[dict[str, object]], None] | None = None,
|
||||
) -> None:
|
||||
"""Run the updater before importing the heavier app modules."""
|
||||
try:
|
||||
@@ -80,7 +81,10 @@ def run_startup_update_check_early(
|
||||
check = run_startup_update_check
|
||||
else:
|
||||
check = update_check
|
||||
check(app_name=app_name)
|
||||
if progress_callback is None:
|
||||
check(app_name=app_name)
|
||||
else:
|
||||
check(app_name=app_name, progress_callback=progress_callback)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
|
||||
+496
-37
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -7,22 +8,27 @@ import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
import zipfile
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urljoin, urlparse
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from cryptography.exceptions import InvalidSignature
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.core.version import VERSION
|
||||
from douyin.license.public_key import PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
DEFAULT_INSTALLER_ARGS = (
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER",
|
||||
)
|
||||
DEFAULT_UPDATE_MANIFEST_URL = "https://dy.absfan.cn/api/v1/update/manifest"
|
||||
|
||||
|
||||
class UpdateError(RuntimeError):
|
||||
@@ -40,6 +46,8 @@ class UpdateSettings:
|
||||
require_sha256: bool = True
|
||||
require_https: bool = True
|
||||
allow_cross_origin: bool = False
|
||||
require_signed_manifest: bool = False
|
||||
allow_delta: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,11 +57,14 @@ class UpdateResult:
|
||||
exit_required: bool = False
|
||||
version: str = ""
|
||||
installer_path: Path | None = None
|
||||
delta_path: Path | None = None
|
||||
|
||||
|
||||
FetchManifest = Callable[[str, float], dict[str, Any]]
|
||||
DownloadFile = Callable[[str, Path, float], None]
|
||||
LaunchInstaller = Callable[[list[str]], None]
|
||||
LaunchDeltaUpdate = Callable[[Path, str], None]
|
||||
ProgressCallback = Callable[[dict[str, Any]], None]
|
||||
|
||||
|
||||
def _to_bool(value: Any, default: bool = False) -> bool:
|
||||
@@ -121,6 +132,33 @@ def _as_installer_args(value: Any) -> tuple[str, ...]:
|
||||
return DEFAULT_INSTALLER_ARGS
|
||||
|
||||
|
||||
def _canonical_payload_bytes(payload: dict[str, Any]) -> bytes:
|
||||
return json.dumps(
|
||||
payload,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
def _verify_manifest_signature(manifest: dict[str, Any]) -> None:
|
||||
signature_raw = manifest.get("signature")
|
||||
if not isinstance(signature_raw, str) or not signature_raw.strip():
|
||||
raise UpdateError("manifest 缺少签名")
|
||||
payload = dict(manifest)
|
||||
payload.pop("signature", None)
|
||||
try:
|
||||
signature = base64.b64decode(signature_raw.encode("ascii"), validate=True)
|
||||
public_key = serialization.load_pem_public_key(PUBLIC_KEY_PEM)
|
||||
public_key.verify(signature, _canonical_payload_bytes(payload))
|
||||
except InvalidSignature as exc:
|
||||
raise UpdateError("manifest 签名校验失败") from exc
|
||||
except UpdateError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise UpdateError(f"manifest 签名校验异常:{exc}") from exc
|
||||
|
||||
|
||||
def load_update_settings() -> UpdateSettings:
|
||||
cfg = _read_config()
|
||||
section = cfg.get("auto_update") if isinstance(cfg.get("auto_update"), dict) else {}
|
||||
@@ -130,10 +168,13 @@ def load_update_settings() -> UpdateSettings:
|
||||
or str(cfg.get("update_manifest_url", "") or "")
|
||||
).strip()
|
||||
env_enabled = os.environ.get("DOUYIN_AUTO_UPDATE_ENABLED")
|
||||
enabled = _to_bool(env_enabled, default=_to_bool(section.get("enabled"), False))
|
||||
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
||||
enabled = False
|
||||
using_default_manifest = False
|
||||
if not manifest_url:
|
||||
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
|
||||
using_default_manifest = True
|
||||
enabled_default = _to_bool(section.get("enabled"), True)
|
||||
enabled = _to_bool(env_enabled, default=enabled_default)
|
||||
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
||||
enabled = False
|
||||
|
||||
default_download_dir = Path(path_config.get_state_dir()) / "updates"
|
||||
@@ -151,11 +192,26 @@ def load_update_settings() -> UpdateSettings:
|
||||
timeout_seconds=timeout_seconds,
|
||||
fail_closed=_to_bool(section.get("fail_closed"), True),
|
||||
require_sha256=_to_bool(section.get("require_sha256"), True),
|
||||
require_https=_to_bool(section.get("require_https"), True),
|
||||
require_https=_to_bool(section.get("require_https"), not using_default_manifest),
|
||||
allow_cross_origin=_to_bool(section.get("allow_cross_origin"), False),
|
||||
require_signed_manifest=_to_bool(section.get("require_signed_manifest"), using_default_manifest),
|
||||
allow_delta=_to_bool(
|
||||
os.environ.get("DOUYIN_UPDATE_ALLOW_DELTA", section.get("allow_delta")),
|
||||
False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def load_manual_update_settings() -> UpdateSettings:
|
||||
"""Load settings for an explicit user-triggered update check.
|
||||
|
||||
The manual button should report errors in the UI instead of exiting the
|
||||
process through the startup fail-closed path.
|
||||
"""
|
||||
settings = load_update_settings()
|
||||
return replace(settings, enabled=True, fail_closed=False)
|
||||
|
||||
|
||||
def _origin(value: str) -> tuple[str, str, int]:
|
||||
parsed = urlparse(value)
|
||||
scheme = (parsed.scheme or "").lower()
|
||||
@@ -184,6 +240,16 @@ def _validate_installer_url(settings: UpdateSettings, download_url: str) -> None
|
||||
raise UpdateError("安装包 URL 必须与 manifest 同源")
|
||||
|
||||
|
||||
def _validate_download_url(settings: UpdateSettings, download_url: str, label: str) -> None:
|
||||
parsed = urlparse(download_url)
|
||||
if settings.require_https and parsed.scheme.lower() != "https":
|
||||
raise UpdateError(f"{label} URL 必须使用 HTTPS")
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise UpdateError(f"{label} URL 必须是完整 URL")
|
||||
if not settings.allow_cross_origin and _origin(download_url) != _origin(settings.manifest_url):
|
||||
raise UpdateError(f"{label} URL 必须与 manifest 同源")
|
||||
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
@@ -194,18 +260,35 @@ def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
return obj
|
||||
|
||||
|
||||
def download_file(url: str, dest: Path, timeout: float) -> None:
|
||||
def download_file(
|
||||
url: str,
|
||||
dest: Path,
|
||||
timeout: float,
|
||||
progress_callback: Callable[[int, int], None] | None = None,
|
||||
) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = dest.with_name(dest.name + ".download")
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp, tmp.open("wb") as f:
|
||||
total = 0
|
||||
try:
|
||||
total = int(resp.headers.get("Content-Length") or 0)
|
||||
except Exception:
|
||||
total = 0
|
||||
done = 0
|
||||
while True:
|
||||
chunk = resp.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
done += len(chunk)
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(done, total)
|
||||
except Exception:
|
||||
pass
|
||||
if dest.exists():
|
||||
dest.unlink()
|
||||
tmp.replace(dest)
|
||||
@@ -226,6 +309,153 @@ def _safe_installer_name(manifest: dict[str, Any], download_url: str, version: s
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def _safe_delta_name(delta: dict[str, Any], download_url: str, version: str) -> str:
|
||||
raw = str(delta.get("filename") or Path(urlparse(download_url).path).name or "").strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
raw = f"DouyinGuaji-delta-{version}.zip"
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def _delta_attempt_state_path(settings: UpdateSettings) -> Path:
|
||||
return settings.download_dir / "delta_attempt_state.json"
|
||||
|
||||
|
||||
def _delta_attempt_key(delta: dict[str, Any], current_version: str, latest_version: str) -> str:
|
||||
filename = str(delta.get("filename") or delta.get("url") or "").strip()
|
||||
sha = str(delta.get("sha256") or "").strip().lower()
|
||||
return "|".join([str(current_version), str(latest_version), filename, sha])
|
||||
|
||||
|
||||
def _read_delta_attempt_state(settings: UpdateSettings) -> dict[str, Any]:
|
||||
path = _delta_attempt_state_path(settings)
|
||||
try:
|
||||
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _write_delta_attempt_state(settings: UpdateSettings, payload: dict[str, Any]) -> None:
|
||||
path = _delta_attempt_state_path(settings)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _clear_delta_attempt_state(settings: UpdateSettings) -> None:
|
||||
try:
|
||||
_delta_attempt_state_path(settings).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _should_skip_delta_after_previous_attempt(
|
||||
settings: UpdateSettings,
|
||||
delta: dict[str, Any],
|
||||
current_version: str,
|
||||
latest_version: str,
|
||||
) -> bool:
|
||||
state = _read_delta_attempt_state(settings)
|
||||
if state.get("status") != "started":
|
||||
return False
|
||||
if state.get("key") != _delta_attempt_key(delta, current_version, latest_version):
|
||||
return False
|
||||
return compare_versions(current_version, latest_version) < 0
|
||||
|
||||
|
||||
def _mark_delta_attempt_started(
|
||||
settings: UpdateSettings,
|
||||
delta: dict[str, Any],
|
||||
current_version: str,
|
||||
latest_version: str,
|
||||
delta_path: Path,
|
||||
) -> None:
|
||||
_write_delta_attempt_state(
|
||||
settings,
|
||||
{
|
||||
"status": "started",
|
||||
"key": _delta_attempt_key(delta, current_version, latest_version),
|
||||
"from_version": current_version,
|
||||
"to_version": latest_version,
|
||||
"filename": delta_path.name,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _safe_delta_path(raw_path: Any) -> str:
|
||||
rel = str(raw_path or "").replace("\\", "/").strip("/")
|
||||
parts = [part for part in rel.split("/") if part]
|
||||
if not parts or any(part in {".", ".."} for part in parts):
|
||||
raise UpdateError(f"差量包包含非法路径:{raw_path}")
|
||||
if Path(rel).is_absolute() or ":" in parts[0]:
|
||||
raise UpdateError(f"差量包包含非法路径:{raw_path}")
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def _matching_delta(manifest: dict[str, Any], current_version: str, latest_version: str) -> dict[str, Any] | None:
|
||||
raw = manifest.get("delta")
|
||||
candidates: list[Any]
|
||||
if isinstance(raw, list):
|
||||
candidates = raw
|
||||
elif isinstance(raw, dict):
|
||||
candidates = [raw]
|
||||
else:
|
||||
return None
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
from_version = str(item.get("from_version") or "").strip().lstrip("Vv")
|
||||
to_version = str(item.get("to_version") or latest_version).strip().lstrip("Vv")
|
||||
if compare_versions(from_version, current_version) == 0 and compare_versions(to_version, latest_version) == 0:
|
||||
return dict(item)
|
||||
return None
|
||||
|
||||
|
||||
def validate_delta_package(delta_path: Path, *, current_version: str, latest_version: str) -> dict[str, Any]:
|
||||
try:
|
||||
with zipfile.ZipFile(delta_path) as zf:
|
||||
for info in zf.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
if name.endswith("/"):
|
||||
continue
|
||||
if name != "manifest.json" and not name.startswith("files/"):
|
||||
raise UpdateError(f"差量包包含未知条目:{info.filename}")
|
||||
if name.startswith("files/"):
|
||||
_safe_delta_path(name[len("files/"):])
|
||||
try:
|
||||
manifest = json.loads(zf.read("manifest.json").decode("utf-8-sig"))
|
||||
except KeyError as exc:
|
||||
raise UpdateError("差量包缺少 manifest.json") from exc
|
||||
except Exception as exc:
|
||||
raise UpdateError(f"差量包 manifest 读取失败:{exc}") from exc
|
||||
if not isinstance(manifest, dict):
|
||||
raise UpdateError("差量包 manifest 格式错误")
|
||||
if compare_versions(str(manifest.get("from_version") or ""), current_version) != 0:
|
||||
raise UpdateError("差量包来源版本不匹配")
|
||||
if compare_versions(str(manifest.get("to_version") or ""), latest_version) != 0:
|
||||
raise UpdateError("差量包目标版本不匹配")
|
||||
for item in manifest.get("files") or []:
|
||||
if not isinstance(item, dict):
|
||||
raise UpdateError("差量包文件列表格式错误")
|
||||
rel = _safe_delta_path(item.get("path"))
|
||||
zip_name = f"files/{rel}"
|
||||
if zip_name not in zf.namelist():
|
||||
raise UpdateError(f"差量包缺少文件:{rel}")
|
||||
expected = str(item.get("sha256") or "").strip().lower()
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{64}", expected):
|
||||
raise UpdateError(f"差量包文件缺少有效 sha256:{rel}")
|
||||
actual = hashlib.sha256(zf.read(zip_name)).hexdigest()
|
||||
if actual.lower() != expected:
|
||||
raise UpdateError(f"差量包文件校验失败:{rel}")
|
||||
for rel in manifest.get("delete") or []:
|
||||
_safe_delta_path(rel)
|
||||
return manifest
|
||||
except zipfile.BadZipFile as exc:
|
||||
raise UpdateError("差量包不是有效 zip") from exc
|
||||
|
||||
|
||||
def _installer_log_arg(version: str) -> str:
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
@@ -286,6 +516,96 @@ def launch_installer(cmd: list[str]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _install_root() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(path_config.get_project_root()).resolve()
|
||||
|
||||
|
||||
def _delta_log_path(version: str) -> Path:
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return log_dir / f"delta-{safe_version}.log"
|
||||
|
||||
|
||||
def _update_client_log_path() -> Path:
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return log_dir / "update-client.log"
|
||||
|
||||
|
||||
def _append_update_log(event: str, **fields: Any) -> None:
|
||||
try:
|
||||
payload = {
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"event": event,
|
||||
**fields,
|
||||
}
|
||||
with _update_client_log_path().open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def launch_delta_update(delta_path: Path, version: str) -> None:
|
||||
install_root = _install_root()
|
||||
work_dir = delta_path.parent / f"{delta_path.stem}.apply"
|
||||
log_path = _delta_log_path(version)
|
||||
parent_pid = os.getpid()
|
||||
script = (
|
||||
"$ErrorActionPreference = 'Stop'; "
|
||||
f"Wait-Process -Id {parent_pid} -ErrorAction SilentlyContinue; "
|
||||
f"$zip = {_ps_quote(str(delta_path))}; "
|
||||
f"$root = {_ps_quote(str(install_root))}; "
|
||||
f"$work = {_ps_quote(str(work_dir))}; "
|
||||
f"$log = {_ps_quote(str(log_path))}; "
|
||||
"New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null; "
|
||||
"try { "
|
||||
" ('delta update started ' + (Get-Date -Format o) + ' zip=' + $zip + ' root=' + $root) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }; "
|
||||
" New-Item -ItemType Directory -Force -Path $work | Out-Null; "
|
||||
" Expand-Archive -LiteralPath $zip -DestinationPath $work -Force; "
|
||||
" $manifest = Get-Content -LiteralPath (Join-Path $work 'manifest.json') -Raw | ConvertFrom-Json; "
|
||||
" foreach ($rel in $manifest.delete) { "
|
||||
" $target = Join-Path $root $rel; "
|
||||
" if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } "
|
||||
" }; "
|
||||
" foreach ($file in $manifest.files) { "
|
||||
" $src = Join-Path (Join-Path $work 'files') $file.path; "
|
||||
" $dst = Join-Path $root $file.path; "
|
||||
" New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null; "
|
||||
" Copy-Item -LiteralPath $src -Destination $dst -Force "
|
||||
" }; "
|
||||
" 'delta update applied' | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" Remove-Item -LiteralPath $work -Recurse -Force; "
|
||||
" exit 0 "
|
||||
"} catch { "
|
||||
" ('delta update failed ' + (Get-Date -Format o) + ' error=' + $_.Exception.Message) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" if ($_.ScriptStackTrace) { $_.ScriptStackTrace | Out-File -LiteralPath $log -Encoding utf8 -Append }; "
|
||||
" exit 1 "
|
||||
"}"
|
||||
)
|
||||
subprocess.Popen(
|
||||
[
|
||||
"powershell",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-WindowStyle",
|
||||
"Hidden",
|
||||
"-Command",
|
||||
script,
|
||||
],
|
||||
cwd=str(install_root),
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
|
||||
)
|
||||
|
||||
|
||||
def _ps_quote(value: str) -> str:
|
||||
text = str(value)
|
||||
if sys.platform.startswith("win"):
|
||||
@@ -300,50 +620,181 @@ def perform_forced_update(
|
||||
fetch_manifest: FetchManifest = fetch_manifest,
|
||||
download_file: DownloadFile = download_file,
|
||||
launch_installer: LaunchInstaller = launch_installer,
|
||||
launch_delta_update: LaunchDeltaUpdate = launch_delta_update,
|
||||
progress_callback: ProgressCallback | None = None,
|
||||
) -> UpdateResult:
|
||||
def emit_progress(stage: str, **fields: Any) -> None:
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback({"stage": stage, **fields})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def call_download_file(
|
||||
url: str,
|
||||
dest: Path,
|
||||
timeout: float,
|
||||
*,
|
||||
kind: str,
|
||||
) -> None:
|
||||
def on_bytes(done: int, total: int) -> None:
|
||||
emit_progress("download_progress", kind=kind, done=done, total=total, path=str(dest), url=url)
|
||||
|
||||
try:
|
||||
download_file(url, dest, timeout, on_bytes) # type: ignore[misc]
|
||||
except TypeError:
|
||||
download_file(url, dest, timeout)
|
||||
|
||||
if not settings.enabled:
|
||||
return UpdateResult("disabled", "未配置更新服务器")
|
||||
|
||||
_validate_manifest_url(settings)
|
||||
emit_progress("manifest_fetch", message="正在连接更新服务器")
|
||||
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
||||
if settings.require_signed_manifest:
|
||||
emit_progress("manifest_verify", message="正在校验更新签名")
|
||||
_verify_manifest_signature(manifest)
|
||||
latest_version = str(manifest.get("version", "") or "").strip()
|
||||
if not latest_version:
|
||||
raise UpdateError("manifest 缺少 version")
|
||||
if compare_versions(latest_version, current_version) <= 0:
|
||||
_clear_delta_attempt_state(settings)
|
||||
return UpdateResult("up_to_date", "已是最新版本", version=latest_version)
|
||||
|
||||
raw_url = str(manifest.get("url") or manifest.get("installer_url") or "").strip()
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
_validate_installer_url(settings, download_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
def launch_full_installer() -> UpdateResult:
|
||||
emit_progress("full_prepare", message="准备下载完整安装包")
|
||||
raw_url = str(manifest.get("url") or manifest.get("installer_url") or "").strip()
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
_validate_installer_url(settings, download_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
|
||||
installer_name = _safe_installer_name(manifest, download_url, latest_version)
|
||||
installer_path = settings.download_dir / installer_name
|
||||
installer_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
download_file(download_url, installer_path, settings.timeout_seconds)
|
||||
installer_name = _safe_installer_name(manifest, download_url, latest_version)
|
||||
installer_path = settings.download_dir / installer_name
|
||||
installer_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
emit_progress("full_download_start", kind="full", message=f"正在下载完整安装包 {installer_name}", path=str(installer_path), url=download_url)
|
||||
call_download_file(download_url, installer_path, settings.timeout_seconds, kind="full")
|
||||
|
||||
if expected_sha:
|
||||
actual_sha = _sha256(installer_path)
|
||||
if actual_sha.lower() != expected_sha.lower():
|
||||
if expected_sha:
|
||||
emit_progress("full_verify", message="正在校验完整安装包")
|
||||
actual_sha = _sha256(installer_path)
|
||||
if actual_sha.lower() != expected_sha.lower():
|
||||
try:
|
||||
installer_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
|
||||
cmd = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
|
||||
emit_progress("full_launch", message="正在启动安装器")
|
||||
launch_installer(cmd)
|
||||
_clear_delta_attempt_state(settings)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
f"发现新版本 {latest_version},已启动安装器",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
installer_path=installer_path,
|
||||
)
|
||||
|
||||
delta = _matching_delta(manifest, current_version, latest_version) if settings.allow_delta else None
|
||||
if not delta:
|
||||
unavailable_message = (
|
||||
"未找到当前版本可用的差量包,准备下载完整安装包"
|
||||
if settings.allow_delta
|
||||
else "准备下载完整安装包"
|
||||
)
|
||||
emit_progress(
|
||||
"delta_unavailable",
|
||||
message=unavailable_message,
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
)
|
||||
skip_delta = bool(delta and _should_skip_delta_after_previous_attempt(settings, delta, current_version, latest_version))
|
||||
if delta and skip_delta:
|
||||
emit_progress(
|
||||
"delta_skipped",
|
||||
message="上次差量更新未完成,准备回退完整安装包",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
)
|
||||
_append_update_log(
|
||||
"delta_skip_after_previous_started_attempt",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
delta_filename=delta.get("filename") or delta.get("url"),
|
||||
)
|
||||
if delta and not skip_delta:
|
||||
raw_delta_url = str(delta.get("url") or "").strip()
|
||||
delta_sha = str(delta.get("sha256") or "").strip().lower()
|
||||
if raw_delta_url and (not settings.require_sha256 or re.fullmatch(r"[0-9a-fA-F]{64}", delta_sha)):
|
||||
try:
|
||||
installer_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
delta_url = urljoin(settings.manifest_url, raw_delta_url)
|
||||
_validate_download_url(settings, delta_url, "差量包")
|
||||
delta_name = _safe_delta_name(delta, delta_url, latest_version)
|
||||
delta_path = settings.download_dir / delta_name
|
||||
delta_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
emit_progress("delta_download_start", kind="delta", message=f"正在下载差量包 {delta_name}", path=str(delta_path), url=delta_url)
|
||||
_append_update_log(
|
||||
"delta_download_start",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
url=delta_url,
|
||||
path=str(delta_path),
|
||||
)
|
||||
call_download_file(delta_url, delta_path, settings.timeout_seconds, kind="delta")
|
||||
if delta_sha:
|
||||
emit_progress("delta_verify", message="正在校验差量包")
|
||||
actual_sha = _sha256(delta_path)
|
||||
if actual_sha.lower() != delta_sha:
|
||||
try:
|
||||
delta_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"差量包 sha256 校验失败: expected={delta_sha} actual={actual_sha}")
|
||||
emit_progress("delta_validate", message="正在检查差量包内容")
|
||||
validate_delta_package(delta_path, current_version=current_version, latest_version=latest_version)
|
||||
_mark_delta_attempt_started(settings, delta, current_version, latest_version, delta_path)
|
||||
_append_update_log(
|
||||
"delta_launch_start",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
path=str(delta_path),
|
||||
sha256=delta_sha,
|
||||
)
|
||||
emit_progress("delta_launch", message="正在应用差量更新")
|
||||
launch_delta_update(delta_path, latest_version)
|
||||
return UpdateResult(
|
||||
"delta_update_started",
|
||||
f"发现新版本 {latest_version},已启动差量更新",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
delta_path=delta_path,
|
||||
)
|
||||
except Exception as exc:
|
||||
emit_progress("delta_failed", message="差量更新失败,准备回退完整安装包", error=f"{type(exc).__name__}: {exc}")
|
||||
_append_update_log(
|
||||
"delta_failed_fallback_full",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
delta_filename=delta.get("filename") or delta.get("url"),
|
||||
error=f"{type(exc).__name__}: {exc}",
|
||||
)
|
||||
_write_delta_attempt_state(
|
||||
settings,
|
||||
{
|
||||
"status": "failed",
|
||||
"key": _delta_attempt_key(delta, current_version, latest_version),
|
||||
"from_version": current_version,
|
||||
"to_version": latest_version,
|
||||
"error": f"{type(exc).__name__}: {exc}",
|
||||
},
|
||||
)
|
||||
|
||||
cmd = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
|
||||
launch_installer(cmd)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
f"发现新版本 {latest_version},已启动安装器",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
installer_path=installer_path,
|
||||
)
|
||||
return launch_full_installer()
|
||||
|
||||
|
||||
def run_startup_update_check(
|
||||
@@ -351,10 +802,18 @@ def run_startup_update_check(
|
||||
app_name: str,
|
||||
current_version: str = VERSION,
|
||||
perform_update: Callable[..., UpdateResult] = perform_forced_update,
|
||||
progress_callback: ProgressCallback | None = None,
|
||||
) -> UpdateResult:
|
||||
settings = load_update_settings()
|
||||
try:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
if progress_callback is None:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
else:
|
||||
result = perform_update(
|
||||
settings=settings,
|
||||
current_version=current_version,
|
||||
progress_callback=progress_callback,
|
||||
)
|
||||
except UpdateError as exc:
|
||||
message = f"[更新] {app_name} 强制更新失败:{exc}"
|
||||
print(message, file=sys.stderr)
|
||||
|
||||
@@ -246,6 +246,15 @@ class ConfigManager:
|
||||
else:
|
||||
analyser.fansclub_manual_wait_seconds = 3.0
|
||||
|
||||
analyser.reservation_prejoin_fansclub_participate_wait_seconds = float(
|
||||
config.get("reservation_prejoin_fansclub_participate_wait_seconds", 0.6)
|
||||
or 0.6
|
||||
)
|
||||
analyser.reservation_prejoin_fansclub_confirm_wait_seconds = float(
|
||||
config.get("reservation_prejoin_fansclub_confirm_wait_seconds", 0.8)
|
||||
or 0.8
|
||||
)
|
||||
|
||||
# 其他配置项(根据实际需要添加)
|
||||
if "no_attend_timeout_minutes" in config:
|
||||
analyser._no_attend_timeout_minutes = float(
|
||||
|
||||
@@ -47,11 +47,15 @@ def preprocess_for_ocr(analyser: Any, cut_pic_name: str) -> str:
|
||||
img = _raw.convert("L")
|
||||
finally:
|
||||
_raw.close()
|
||||
# 放大两倍(Lanczos)
|
||||
img = img.resize((img.width * 2, img.height * 2), Image.LANCZOS)
|
||||
is_countdown_digit = str(cut_pic_name or "").startswith("福袋倒计时_")
|
||||
# 倒计时分秒小图通常只有几十像素宽,2x 仍容易把 00 识别成空。
|
||||
scale = 4 if is_countdown_digit else 2
|
||||
img = img.resize((img.width * scale, img.height * scale), Image.LANCZOS)
|
||||
# 自动对比并锐化
|
||||
img = ImageOps.autocontrast(img)
|
||||
img = img.filter(ImageFilter.SHARPEN)
|
||||
if is_countdown_digit:
|
||||
img = ImageOps.expand(img, border=max(4, scale * 2), fill=255)
|
||||
# 保存为目标路径(覆盖或新文件)
|
||||
img.save(dst)
|
||||
return pre_name
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable
|
||||
|
||||
from douyin.updater.bootstrap import load_update_settings, run_startup_update_check_early
|
||||
from gui.dashboard_app import theme
|
||||
from gui.dashboard_app.widgets import rounded_surface
|
||||
|
||||
|
||||
class UpdateProgressWindow:
|
||||
"""Small standalone update progress window used before the main GUI exists."""
|
||||
|
||||
def __init__(self, title: str = "软件更新") -> None:
|
||||
self.root = tk.Tk()
|
||||
self.root.title(title)
|
||||
self.root.resizable(False, False)
|
||||
self.root.configure(bg=theme.BG)
|
||||
theme.setup_styles(self.root)
|
||||
self.root.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
|
||||
frame = tk.Frame(self.root, bg=theme.BG, padx=28, pady=26)
|
||||
frame.pack(fill="both", expand=True)
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=26, pady=24)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
top,
|
||||
text="正在更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 19, "bold"),
|
||||
).pack(side="left")
|
||||
self.mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.BLUE_SOFT,
|
||||
fg=theme.BLUE,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
self.mode.pack(side="right")
|
||||
|
||||
self.stage = tk.Label(
|
||||
inner,
|
||||
text="正在连接更新服务器",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
self.stage.pack(anchor="w", pady=(20, 5))
|
||||
self.detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
self.detail.pack(anchor="w", pady=(0, 14))
|
||||
self.percent = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 24, "bold"),
|
||||
)
|
||||
self.percent.pack(anchor="e")
|
||||
self.bar = ttk.Progressbar(inner, mode="determinate", length=460, maximum=100)
|
||||
self.bar.pack(fill="x", pady=(3, 10), ipady=4)
|
||||
self.sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
self.sub.pack(anchor="w")
|
||||
|
||||
self.root.update_idletasks()
|
||||
w, h = self.root.winfo_width(), self.root.winfo_height()
|
||||
sw, sh = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
|
||||
self.root.geometry(f"+{max(0, (sw - w) // 2)}+{max(0, (sh - h) // 2)}")
|
||||
|
||||
def callback(self) -> Callable[[dict[str, Any]], None]:
|
||||
return lambda event: self.root.after(0, lambda event=event: self.update(event))
|
||||
|
||||
def update(self, event: dict[str, Any]) -> None:
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=self.mode,
|
||||
stage_label=self.stage,
|
||||
detail_label=self.detail,
|
||||
percent_label=self.percent,
|
||||
bar=self.bar,
|
||||
sub_label=self.sub,
|
||||
)
|
||||
self.root.update_idletasks()
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.root.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_gui_startup_update_check_early(app_name: str) -> None:
|
||||
"""Run startup updater with a visible GUI progress window when enabled."""
|
||||
try:
|
||||
settings = load_update_settings()
|
||||
except Exception:
|
||||
settings = None
|
||||
if settings is None or not settings.enabled:
|
||||
run_startup_update_check_early(app_name=app_name)
|
||||
return
|
||||
|
||||
progress = UpdateProgressWindow()
|
||||
try:
|
||||
run_startup_update_check_early(
|
||||
app_name=app_name,
|
||||
progress_callback=progress.callback(),
|
||||
)
|
||||
finally:
|
||||
progress.close()
|
||||
|
||||
|
||||
def apply_update_progress_event(
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
mode_label: tk.Label,
|
||||
stage_label: tk.Label,
|
||||
detail_label: tk.Label,
|
||||
percent_label: tk.Label,
|
||||
bar: ttk.Progressbar,
|
||||
sub_label: tk.Label,
|
||||
) -> None:
|
||||
stage = str(event.get("stage") or "")
|
||||
message = str(event.get("message") or "")
|
||||
kind = str(event.get("kind") or "")
|
||||
stage_text = message or {
|
||||
"manifest_fetch": "正在连接更新服务器",
|
||||
"manifest_verify": "正在校验更新签名",
|
||||
"delta_download_start": "正在下载差量包",
|
||||
"delta_verify": "正在校验差量包",
|
||||
"delta_validate": "正在检查差量包内容",
|
||||
"delta_launch": "正在应用差量更新",
|
||||
"delta_failed": "差量更新失败,准备回退完整安装包",
|
||||
"delta_unavailable": "未找到当前版本可用的差量包",
|
||||
"delta_skipped": "上次差量更新未完成",
|
||||
"full_prepare": "准备下载完整安装包",
|
||||
"full_download_start": "正在下载完整安装包",
|
||||
"full_verify": "正在校验完整安装包",
|
||||
"full_launch": "正在启动安装器",
|
||||
}.get(stage, "正在处理更新")
|
||||
|
||||
if kind == "delta" or stage.startswith("delta_"):
|
||||
mode_text = "差量更新"
|
||||
mode_bg, mode_fg = theme.TEAL_SOFT, theme.TEAL_DARK
|
||||
elif kind == "full" or stage.startswith("full_"):
|
||||
mode_text = "完整安装包"
|
||||
mode_bg, mode_fg = theme.AMBER_SOFT, theme.AMBER
|
||||
else:
|
||||
mode_text = "检查中"
|
||||
mode_bg, mode_fg = theme.BLUE_SOFT, theme.BLUE
|
||||
|
||||
mode_label.config(text=mode_text, bg=mode_bg, fg=mode_fg)
|
||||
stage_label.config(text=stage_text)
|
||||
|
||||
done = int(event.get("done") or 0)
|
||||
total = int(event.get("total") or 0)
|
||||
if stage == "download_progress" and total > 0:
|
||||
percent = max(0, min(100, round(done * 100 / total)))
|
||||
bar.config(value=percent)
|
||||
percent_label.config(text=f"{percent}%")
|
||||
detail_label.config(text=f"已下载 {done // (1024 * 1024)} MB / {max(1, total // (1024 * 1024))} MB")
|
||||
elif stage.endswith("_start"):
|
||||
bar.config(value=5)
|
||||
percent_label.config(text="0%")
|
||||
detail_label.config(text="正在建立下载任务")
|
||||
elif stage in {"delta_verify", "delta_validate", "full_verify"}:
|
||||
bar.config(value=92)
|
||||
percent_label.config(text="92%")
|
||||
detail_label.config(text="下载完成,正在校验完整性")
|
||||
elif stage in {"delta_launch", "full_launch"}:
|
||||
bar.config(value=100)
|
||||
percent_label.config(text="100%")
|
||||
detail_label.config(text="校验完成,正在启动更新器")
|
||||
elif stage in {"delta_failed", "delta_unavailable", "delta_skipped"}:
|
||||
bar.config(value=0)
|
||||
percent_label.config(text="回退")
|
||||
detail_label.config(text=str(event.get("error") or "将下载完整安装包"))
|
||||
else:
|
||||
bar.config(value=max(8, int(float(bar["value"] or 0))))
|
||||
percent_label.config(text="")
|
||||
|
||||
sub_label.config(text=str(event.get("path") or event.get("url") or ""))
|
||||
@@ -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
|
||||
@@ -214,13 +298,14 @@ def open_wifi_adb_dialog(
|
||||
if not device_id:
|
||||
on_line("[WiFi ADB] 请先选择WiFi设备")
|
||||
return
|
||||
# 从设备ID中提取IP地址
|
||||
ip_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", device_id)
|
||||
if not ip_match:
|
||||
# WiFi 设备通常是 ip:port。保留端口,避免随机无线调试端口被误断成 5555。
|
||||
target_match = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d{1,5}))?", device_id)
|
||||
if not target_match:
|
||||
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
|
||||
return
|
||||
ip = ip_match.group(1)
|
||||
success, msg = disconnect_wifi_adb(adb_exe, ip, "5555")
|
||||
ip = target_match.group(1)
|
||||
port = target_match.group(2) or "5555"
|
||||
success, msg = disconnect_wifi_adb(adb_exe, ip, port)
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 如果断开的就是上次记住的设备,清掉记录避免下次启动徒劳重试
|
||||
@@ -350,63 +435,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, port_var), "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)
|
||||
@@ -27,6 +27,7 @@ def open_scan_dialog(
|
||||
ip_var: tk.StringVar,
|
||||
on_line_local: Callable[[str], None],
|
||||
refresh_cb: Callable[[], None],
|
||||
port_var: tk.StringVar | None = None,
|
||||
) -> None:
|
||||
"""打开"扫描局域网"对话框:自动推子网或手动输入 → 后台扫描 → 列表展示。"""
|
||||
scan_dlg = tk.Toplevel(parent)
|
||||
@@ -130,9 +131,12 @@ def open_scan_dialog(
|
||||
f"[扫描] {target} 未授权,请先在手机上确认 ADB 调试授权再选"
|
||||
)
|
||||
return
|
||||
# 把 IP 部分填回主对话框
|
||||
ip_part = str(target).split(":")[0]
|
||||
# 把 IP 和端口填回主对话框。Android 11+ 无线调试常用随机端口,
|
||||
# 丢掉端口会导致用户选中后仍按默认 5555 连接失败。
|
||||
ip_part, port_part = split_target_for_fields(target)
|
||||
ip_var.set(ip_part)
|
||||
if port_var is not None and port_part:
|
||||
port_var.set(port_part)
|
||||
on_line_local(f"[扫描] 已选中 {target},可在主对话框点'连接'或它已在 adb devices 中")
|
||||
try:
|
||||
refresh_cb()
|
||||
@@ -229,3 +233,16 @@ def open_scan_dialog(
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
scan_btn.config(command=do_scan)
|
||||
|
||||
|
||||
def split_target_for_fields(target: object) -> tuple[str, str]:
|
||||
"""Return (host, port) for an adb target string, preserving random WiFi ports."""
|
||||
text = str(target or "").strip()
|
||||
if not text:
|
||||
return "", ""
|
||||
if ":" not in text:
|
||||
return text, ""
|
||||
host, port = text.rsplit(":", 1)
|
||||
if host and port.isdigit():
|
||||
return host, port
|
||||
return text, ""
|
||||
+469
-42
@@ -1,14 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
from douyin.core.version import print_version_banner
|
||||
from douyin.diagnostics.log_upload import upload_diagnostic_logs
|
||||
from douyin.license.license_manager import (
|
||||
check_license,
|
||||
get_default_activation_url,
|
||||
install_license_or_activate,
|
||||
require_online_license_or_exit,
|
||||
start_online_license_monitor,
|
||||
)
|
||||
from douyin.updater.force_update import (
|
||||
UpdateError,
|
||||
load_manual_update_settings,
|
||||
perform_forced_update,
|
||||
)
|
||||
from gui.components.config_io import save_ui_to_config
|
||||
from gui.components.config_vars import build_config_vars
|
||||
from gui.components.mousewheel_guard import disable_spinbox_mousewheel
|
||||
from gui.components.run_params_builder import get_params as build_run_params
|
||||
from gui.components.screenshot_action import do_screenshot
|
||||
from gui.components.update_progress import apply_update_progress_event
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog
|
||||
from gui.components.wifi_adb_one_click_scan import on_scan_one_click
|
||||
from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog
|
||||
@@ -19,19 +35,23 @@ 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, SlimScrollbar, button, clear, nav_button, rounded_surface, status_pill
|
||||
|
||||
|
||||
def enforce_dashboard_license_required() -> None:
|
||||
os.environ["DOUYIN_LICENSE_REQUIRED"] = "1"
|
||||
|
||||
|
||||
class DashboardApp:
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, *, initial_page: str = "数据看板", license_locked: bool = False) -> None:
|
||||
self.root = tk.Tk()
|
||||
try:
|
||||
self.root.tk.call("tk", "scaling", 1.12)
|
||||
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)
|
||||
|
||||
@@ -46,8 +66,10 @@ class DashboardApp:
|
||||
"yg_like_keywords_text": self.data.cfg.get("yanghao_like_keywords", []) or [],
|
||||
"yg_fav_keywords_text": self.data.cfg.get("yanghao_fav_keywords", []) or [],
|
||||
}
|
||||
self.current_page = "数据看板"
|
||||
self.status_var = tk.StringVar(value="就绪")
|
||||
self.license_locked = bool(license_locked)
|
||||
self.current_page = "授权" if self.license_locked else (initial_page if initial_page in PAGES else "数据看板")
|
||||
self._license_monitor_started = False
|
||||
self.status_var = tk.StringVar(value="请先验证卡密" if self.license_locked else "就绪")
|
||||
self.adb_exe = find_adb_executable()
|
||||
self.device_var = tk.StringVar(value="")
|
||||
self.y_var = self.config_vars.get("y_var", tk.IntVar(value=0))
|
||||
@@ -55,6 +77,7 @@ class DashboardApp:
|
||||
self.ocr_results: list = []
|
||||
self._scan_busy = {"flag": False}
|
||||
self.nav_buttons: dict[str, tk.Widget] = {}
|
||||
self._startup_progress: tk.Toplevel | None = None
|
||||
|
||||
self._build_shell()
|
||||
self.status_var.trace_add("write", lambda *_: self._sync_status_pill())
|
||||
@@ -62,53 +85,130 @@ class DashboardApp:
|
||||
self.root.after(300, self._try_reconnect_last_wifi)
|
||||
self.show_page(self.current_page)
|
||||
|
||||
def _ensure_license_ready(self) -> bool:
|
||||
if not self.license_locked:
|
||||
return True
|
||||
self.status_var.set("请先验证卡密")
|
||||
try:
|
||||
self.show_page("授权")
|
||||
except Exception:
|
||||
pass
|
||||
messagebox.showwarning("需要授权", "请先在“授权”页面输入卡密并验证成功。", parent=self.root)
|
||||
return False
|
||||
|
||||
def _start_license_monitor_once(self) -> None:
|
||||
if self._license_monitor_started:
|
||||
return
|
||||
start_online_license_monitor(on_line=self._on_runner_line)
|
||||
self._license_monitor_started = True
|
||||
|
||||
def _build_shell(self) -> None:
|
||||
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")
|
||||
button(
|
||||
quick_state,
|
||||
"检查更新",
|
||||
self.check_update,
|
||||
width=124,
|
||||
).pack(side="right", padx=(8, 0))
|
||||
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.Spinbox(tool_row, from_=-200, to=200, textvariable=self.y_var, width=6).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=(4, 14))
|
||||
tool_row.grid_columnconfigure(0, minsize=350)
|
||||
tool_row.grid_columnconfigure(1, weight=1)
|
||||
tool_row.grid_columnconfigure(2, minsize=318)
|
||||
|
||||
device_group = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
device_group.grid(row=0, column=0, sticky="ew", padx=(0, 16))
|
||||
tk.Label(
|
||||
device_group,
|
||||
text="设备",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="w", pady=(0, 7))
|
||||
self.device_combo = ttk.Combobox(device_group, textvariable=self.device_var, values=[], width=38, state="readonly")
|
||||
self.device_combo.pack(fill="x")
|
||||
|
||||
device_actions = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
device_actions.grid(row=0, column=1, sticky="w", padx=(0, 12))
|
||||
tk.Label(
|
||||
device_actions,
|
||||
text="设备工具",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="w", pady=(0, 7))
|
||||
device_button_row = tk.Frame(device_actions, bg=theme.SURFACE)
|
||||
device_button_row.pack(anchor="w")
|
||||
button(device_button_row, "刷新设备", self.refresh_devices, width=120).pack(side="left", padx=(0, 6))
|
||||
self.scan_button = button(device_button_row, "扫描 WiFi", self.scan_wifi, width=124)
|
||||
self.scan_button.pack(side="left", padx=(0, 6))
|
||||
button(device_button_row, "WiFi ADB", self.open_wifi_adb, width=112).pack(side="left", padx=(0, 6))
|
||||
button(device_button_row, "上传日志", self.upload_logs, width=112).pack(side="left")
|
||||
|
||||
primary_actions = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
primary_actions.grid(row=0, column=2, sticky="e")
|
||||
tk.Label(
|
||||
primary_actions,
|
||||
text="主操作",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="e", pady=(0, 7))
|
||||
primary_button_row = tk.Frame(primary_actions, bg=theme.SURFACE)
|
||||
primary_button_row.pack(anchor="e")
|
||||
button(primary_button_row, "保存配置", self.save_config, width=130).pack(side="left", padx=(0, 8))
|
||||
button(primary_button_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=148).pack(side="left")
|
||||
|
||||
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)
|
||||
nav_scroll = ttk.Scrollbar(sidebar, orient="vertical", command=nav_canvas.yview)
|
||||
nav_scroll = SlimScrollbar(sidebar, command=lambda *args: nav_canvas.yview(*[a for a in args if a is not None]))
|
||||
nav_inner = tk.Frame(nav_canvas, bg=theme.SURFACE)
|
||||
nav_window = nav_canvas.create_window((0, 0), window=nav_inner, anchor="nw")
|
||||
nav_canvas.configure(yscrollcommand=nav_scroll.set)
|
||||
nav_canvas.pack(side="left", fill="both", expand=True, padx=(0, 2), pady=8)
|
||||
nav_scroll.pack(side="right", fill="y", pady=10)
|
||||
nav_scroll.pack(side="right", fill="y", padx=(0, 8), pady=12)
|
||||
nav_canvas.pack(side="left", fill="both", expand=True, padx=(0, 4), pady=8)
|
||||
nav_inner.bind("<Configure>", lambda _e: nav_canvas.configure(scrollregion=nav_canvas.bbox("all")))
|
||||
nav_canvas.bind("<Configure>", lambda e: nav_canvas.itemconfigure(nav_window, width=e.width))
|
||||
|
||||
@@ -134,10 +234,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 +245,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))
|
||||
@@ -160,6 +260,8 @@ class DashboardApp:
|
||||
def _sync_nav(self) -> None:
|
||||
for name, btn in self.nav_buttons.items():
|
||||
active = name == self.current_page
|
||||
if hasattr(btn, "set_enabled"):
|
||||
btn.set_enabled((not self.license_locked) or name == "授权")
|
||||
if hasattr(btn, "set_active"):
|
||||
btn.set_active(active)
|
||||
|
||||
@@ -187,6 +289,9 @@ class DashboardApp:
|
||||
"screenshot_ocr": self.screenshot_ocr,
|
||||
"scan_wifi": self.scan_wifi,
|
||||
"wifi_adb": self.open_wifi_adb,
|
||||
"verify_license": self.verify_license,
|
||||
"upload_logs": self.upload_logs,
|
||||
"check_update": self.check_update,
|
||||
"show_run_log": lambda: self.show_page("运行日志"),
|
||||
"show_actions_log": lambda: self.show_page("行为日志"),
|
||||
}
|
||||
@@ -273,6 +378,8 @@ class DashboardApp:
|
||||
self.status_var.set(f"刷新设备失败:{exc}")
|
||||
|
||||
def open_wifi_adb(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.show_page("WiFi ADB")
|
||||
open_wifi_adb_dialog(
|
||||
self.root,
|
||||
@@ -291,6 +398,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def scan_wifi(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
on_scan_one_click(
|
||||
adb_exe=self.adb_exe,
|
||||
scan_btn=self.scan_button,
|
||||
@@ -303,6 +412,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def _try_reconnect_last_wifi(self) -> None:
|
||||
if self.license_locked:
|
||||
return
|
||||
try_reconnect_last_wifi(
|
||||
self.root,
|
||||
adb_exe=self.adb_exe,
|
||||
@@ -312,6 +423,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def screenshot_ocr(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
do_screenshot(
|
||||
device_id=self._selected_device(),
|
||||
y_offset=int(self.y_var.get() or 0),
|
||||
@@ -327,16 +440,100 @@ class DashboardApp:
|
||||
self.status_var.set(f"OCR结果已更新:{len(results)} 项")
|
||||
|
||||
def start_run(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
if self.runner.is_running():
|
||||
self.status_var.set("已在运行中")
|
||||
return
|
||||
progress = self._show_startup_progress()
|
||||
try:
|
||||
self._update_startup_progress(progress, 12, "保存配置", "正在写入当前界面参数")
|
||||
self.save_config()
|
||||
self.runner.start(self._params())
|
||||
self._update_startup_progress(progress, 38, "解析设备", "正在确认 ADB 与目标设备")
|
||||
params = self._params()
|
||||
self._update_startup_progress(progress, 68, "启动主进程", "正在加载运行核心")
|
||||
self.root.update_idletasks()
|
||||
self.runner.start(params)
|
||||
self._update_startup_progress(progress, 90, "等待运行日志", "主进程已启动,正在等待初始化输出")
|
||||
self.status_var.set("运行中")
|
||||
self.refresh_data()
|
||||
self.data = load_dashboard_data()
|
||||
except Exception as exc:
|
||||
self._close_startup_progress(progress)
|
||||
self.status_var.set(f"启动失败:{exc}")
|
||||
return
|
||||
self.root.after(600, lambda: self._finish_startup_progress(progress))
|
||||
|
||||
def _show_startup_progress(self) -> tk.Toplevel:
|
||||
win = tk.Toplevel(self.root)
|
||||
win.title("启动运行")
|
||||
win.transient(self.root)
|
||||
win.resizable(False, False)
|
||||
win.configure(bg=theme.BG)
|
||||
win.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
frame = tk.Frame(win, bg=theme.BG, padx=24, pady=22)
|
||||
frame.pack(fill="both", expand=True)
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=24, pady=21)
|
||||
inner.pack(fill="both", expand=True)
|
||||
tk.Label(inner, text="正在初始化运行", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w")
|
||||
stage = tk.Label(inner, text="准备中", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 14, "bold"))
|
||||
stage.pack(anchor="w", pady=(17, 4))
|
||||
detail = tk.Label(inner, text="正在准备启动环境", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL)
|
||||
detail.pack(anchor="w", pady=(0, 13))
|
||||
pct = tk.Label(inner, text="0%", bg=theme.SURFACE, fg=theme.TEAL_DARK, font=("Microsoft YaHei UI", 20, "bold"))
|
||||
pct.pack(anchor="e")
|
||||
bar = ttk.Progressbar(inner, mode="determinate", length=420, maximum=100)
|
||||
bar.pack(fill="x", pady=(3, 4), ipady=3)
|
||||
win._startup_labels = {"stage": stage, "detail": detail, "pct": pct, "bar": bar} # type: ignore[attr-defined]
|
||||
self._update_startup_progress(win, 5, "准备中", "正在准备启动环境")
|
||||
try:
|
||||
win.update_idletasks()
|
||||
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
|
||||
y = self.root.winfo_rooty() + (self.root.winfo_height() - win.winfo_height()) // 2
|
||||
win.geometry(f"+{max(0, x)}+{max(0, y)}")
|
||||
win.grab_set()
|
||||
except Exception:
|
||||
pass
|
||||
self._startup_progress = win
|
||||
return win
|
||||
|
||||
def _update_startup_progress(self, progress: tk.Toplevel, percent: int, stage: str, detail: str) -> None:
|
||||
labels = getattr(progress, "_startup_labels", None)
|
||||
if not labels:
|
||||
return
|
||||
value = max(0, min(100, int(percent)))
|
||||
labels["stage"].configure(text=stage)
|
||||
labels["detail"].configure(text=detail)
|
||||
labels["pct"].configure(text=f"{value}%")
|
||||
labels["bar"].configure(value=value)
|
||||
try:
|
||||
progress.update_idletasks()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _close_startup_progress(self, progress: tk.Toplevel | None) -> None:
|
||||
if progress is None:
|
||||
return
|
||||
try:
|
||||
progress.grab_release()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
progress.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
if self._startup_progress is progress:
|
||||
self._startup_progress = None
|
||||
|
||||
def _finish_startup_progress(self, progress: tk.Toplevel | None) -> None:
|
||||
if progress is None:
|
||||
return
|
||||
try:
|
||||
self._update_startup_progress(progress, 100, "启动完成", "运行进程已开始")
|
||||
except Exception:
|
||||
pass
|
||||
self._close_startup_progress(progress)
|
||||
|
||||
def stop_run(self) -> None:
|
||||
self.runner.stop()
|
||||
@@ -358,22 +555,242 @@ class DashboardApp:
|
||||
self.status_var.set("已停止(强制)")
|
||||
|
||||
def send_back_key(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
ok = self.runner.send_back_key(self._selected_device())
|
||||
self.status_var.set("返回键已发送" if ok else "发送返回键失败")
|
||||
|
||||
def verify_license(self) -> None:
|
||||
var = self.config_vars.get("license_key_var")
|
||||
raw = str(var.get() if var is not None else "").strip()
|
||||
if not raw:
|
||||
self.status_var.set("请输入卡密")
|
||||
messagebox.showwarning("卡密验证", "请输入卡密后再验证。", parent=self.root)
|
||||
return
|
||||
try:
|
||||
cfg = read_config()
|
||||
section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {}
|
||||
activation_url = str(section.get("activation_url") or "").strip() or get_default_activation_url()
|
||||
timeout_seconds = int(section.get("timeout_seconds") or 10)
|
||||
except Exception:
|
||||
activation_url = get_default_activation_url()
|
||||
timeout_seconds = 10
|
||||
status = install_license_or_activate(
|
||||
raw,
|
||||
activation_url=activation_url,
|
||||
timeout_seconds=max(1, timeout_seconds),
|
||||
)
|
||||
if status.ok:
|
||||
if var is not None:
|
||||
var.set("")
|
||||
self.license_locked = False
|
||||
self.status_var.set("卡密验证成功")
|
||||
self._start_license_monitor_once()
|
||||
messagebox.showinfo("卡密验证", "验证成功,授权已写入本机。", parent=self.root)
|
||||
self.show_page("数据看板")
|
||||
else:
|
||||
self.status_var.set(f"卡密验证失败:{status.message}")
|
||||
messagebox.showerror(
|
||||
"卡密验证失败",
|
||||
f"{status.message}\n\n原因:{status.reason}",
|
||||
parent=self.root,
|
||||
)
|
||||
|
||||
def upload_logs(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.status_var.set("正在上传诊断日志")
|
||||
self.root.update_idletasks()
|
||||
result = upload_diagnostic_logs()
|
||||
if result.ok:
|
||||
self.status_var.set("诊断日志上传成功")
|
||||
messagebox.showinfo(
|
||||
"上传诊断日志",
|
||||
f"上传成功。\n大小:{result.size // 1024} KB",
|
||||
parent=self.root,
|
||||
)
|
||||
else:
|
||||
self.status_var.set(f"日志上传失败:{result.message}")
|
||||
messagebox.showerror(
|
||||
"上传诊断日志失败",
|
||||
f"{result.message}\n\n原因:{result.reason}",
|
||||
parent=self.root,
|
||||
)
|
||||
|
||||
def check_update(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.status_var.set("正在检查更新")
|
||||
progress = self._show_update_progress("正在连接更新服务器")
|
||||
|
||||
def worker() -> None:
|
||||
try:
|
||||
result = perform_forced_update(
|
||||
settings=load_manual_update_settings(),
|
||||
progress_callback=lambda event: self.root.after(
|
||||
0,
|
||||
lambda event=event: self._update_progress_window(progress, event),
|
||||
),
|
||||
)
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_result(result)))
|
||||
except UpdateError as exc:
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(str(exc))))
|
||||
except Exception as exc:
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(f"检查更新异常:{exc}")))
|
||||
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
def _show_update_progress(self, message: str) -> tk.Toplevel:
|
||||
win = tk.Toplevel(self.root)
|
||||
win.title("检查更新")
|
||||
win.transient(self.root)
|
||||
win.resizable(False, False)
|
||||
win.configure(bg=theme.BG)
|
||||
win.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
frame = tk.Frame(win, bg=theme.BG, padx=26, pady=24)
|
||||
frame.pack(fill="both", expand=True)
|
||||
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=24, pady=22)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
top,
|
||||
text="软件更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 18, "bold"),
|
||||
).pack(side="left")
|
||||
mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.TEAL_SOFT,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
mode.pack(side="right")
|
||||
|
||||
stage = tk.Label(
|
||||
inner,
|
||||
text=message,
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
stage.pack(anchor="w", pady=(18, 4))
|
||||
detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
detail.pack(anchor="w", pady=(0, 14))
|
||||
pct = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 22, "bold"),
|
||||
)
|
||||
pct.pack(anchor="e")
|
||||
bar = ttk.Progressbar(inner, mode="determinate", length=420, maximum=100)
|
||||
bar.pack(fill="x", pady=(3, 10), ipady=3)
|
||||
sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
sub.pack(anchor="w")
|
||||
|
||||
win._update_labels = { # type: ignore[attr-defined]
|
||||
"mode": mode,
|
||||
"stage": stage,
|
||||
"detail": detail,
|
||||
"pct": pct,
|
||||
"bar": bar,
|
||||
"sub": sub,
|
||||
}
|
||||
self._update_progress_window(win, {"stage": "manifest_fetch", "message": message})
|
||||
|
||||
try:
|
||||
win.update_idletasks()
|
||||
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
|
||||
y = self.root.winfo_rooty() + (self.root.winfo_height() - win.winfo_height()) // 2
|
||||
win.geometry(f"+{max(0, x)}+{max(0, y)}")
|
||||
win.grab_set()
|
||||
except Exception:
|
||||
pass
|
||||
return win
|
||||
|
||||
def _update_progress_window(self, progress: tk.Toplevel, event: dict) -> None:
|
||||
labels = getattr(progress, "_update_labels", None)
|
||||
if not labels:
|
||||
return
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=labels["mode"],
|
||||
stage_label=labels["stage"],
|
||||
detail_label=labels["detail"],
|
||||
percent_label=labels["pct"],
|
||||
bar=labels["bar"],
|
||||
sub_label=labels["sub"],
|
||||
)
|
||||
|
||||
def _finish_update_progress(self, progress: tk.Toplevel, callback) -> None:
|
||||
try:
|
||||
progress.grab_release()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
progress.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
callback()
|
||||
|
||||
def _show_update_result(self, result) -> None:
|
||||
self.status_var.set(result.message or "更新检查完成")
|
||||
if result.exit_required:
|
||||
messagebox.showinfo(
|
||||
"检查更新",
|
||||
f"{result.message}\n\n程序会交给更新器处理,请按提示完成更新。",
|
||||
parent=self.root,
|
||||
)
|
||||
try:
|
||||
self.root.after(300, self.root.destroy)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
messagebox.showinfo("检查更新", result.message or "已是最新版本。", parent=self.root)
|
||||
|
||||
def _show_update_error(self, message: str) -> None:
|
||||
self.status_var.set(f"检查更新失败:{message}")
|
||||
messagebox.showerror("检查更新失败", message, parent=self.root)
|
||||
|
||||
def refresh_data(self) -> None:
|
||||
self.data = load_dashboard_data()
|
||||
self.status_var.set("已刷新")
|
||||
self.show_page(self.current_page)
|
||||
|
||||
def show_page(self, name: str) -> None:
|
||||
self.current_page = name
|
||||
target = name if name in PAGES else "数据看板"
|
||||
if self.license_locked and target != "授权":
|
||||
target = "授权"
|
||||
self.status_var.set("请先验证卡密")
|
||||
self.current_page = target
|
||||
self._sync_nav()
|
||||
self._capture_text_widgets()
|
||||
self._apply_text_cache_to_data()
|
||||
self._ensure_text_widgets()
|
||||
clear(self.content)
|
||||
builder = PAGES.get(name, PAGES["数据看板"])
|
||||
builder = PAGES.get(target, PAGES["数据看板"])
|
||||
builder(self.content, self.data, PageContext(self.config_vars, self.text_widgets, self._actions(), self.status_var, self.runner))
|
||||
try:
|
||||
self.content_scroll.canvas.yview_moveto(0)
|
||||
@@ -385,11 +802,21 @@ class DashboardApp:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
enforce_dashboard_license_required()
|
||||
local_status = check_license()
|
||||
if local_status.ok:
|
||||
require_online_license_or_exit()
|
||||
try:
|
||||
print_version_banner("gui_dashboard_app")
|
||||
except Exception:
|
||||
pass
|
||||
DashboardApp().run()
|
||||
app = DashboardApp(
|
||||
initial_page="数据看板" if local_status.ok else "授权",
|
||||
license_locked=not local_status.ok,
|
||||
)
|
||||
if local_status.ok:
|
||||
app._start_license_monitor_once()
|
||||
app.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
|
||||
from douyin.license.license_manager import get_license_status_payload
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, cfg_get
|
||||
from .page_context import PageContext
|
||||
@@ -166,7 +169,32 @@ def build_license(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
|
||||
section(parent, "授权", "输入卡密后自动联网验证")
|
||||
box = card(parent, "卡密验证")
|
||||
box.pack(fill="x")
|
||||
if "license_key_var" not in ctx.vars:
|
||||
ctx.vars["license_key_var"] = tk.StringVar(value="")
|
||||
pack_fields(box, ctx, [("输入卡密", "license_key_var", "")], columns=1)
|
||||
try:
|
||||
os.environ["DOUYIN_LICENSE_REQUIRED"] = "1"
|
||||
payload = get_license_status_payload()
|
||||
except Exception as exc:
|
||||
payload = {"ok": False, "message": f"读取授权状态失败:{exc}", "reason": "status_error"}
|
||||
ok = bool(payload.get("ok"))
|
||||
message = str(payload.get("message") or payload.get("reason") or "未知状态")
|
||||
status = tk.Frame(box, bg=theme.GREEN_SOFT if ok else theme.AMBER_SOFT)
|
||||
status.pack(fill="x", padx=20, pady=(0, 12))
|
||||
tk.Label(
|
||||
status,
|
||||
text=("当前授权有效" if ok else "当前授权未通过"),
|
||||
bg=status["bg"],
|
||||
fg=theme.GREEN if ok else theme.AMBER,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(side="left", padx=12, pady=8)
|
||||
tk.Label(
|
||||
status,
|
||||
text=message,
|
||||
bg=status["bg"],
|
||||
fg=theme.TEXT,
|
||||
font=theme.FONT_SMALL,
|
||||
).pack(side="left", padx=(8, 12), pady=8)
|
||||
row = tk.Frame(box, bg=theme.SURFACE)
|
||||
row.pack(fill="x", padx=20, pady=(0, 16))
|
||||
button(row, "验证卡密", None, kind="primary").pack(side="left", padx=(0, 8))
|
||||
button(row, "验证卡密", ctx.action("verify_license"), kind="primary").pack(side="left", padx=(0, 8))
|
||||
+148
-14
@@ -2,10 +2,13 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import ttk
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, fmt_ts
|
||||
from .data import DashboardData, fmt_ts, load_dashboard_data
|
||||
from .page_context import PageContext
|
||||
from .page_helpers import reservation_rows
|
||||
from .widgets import flow_grid, log_panel, preview_panel, section, stat_tile, table_panel, text_panel, toolbar
|
||||
@@ -189,22 +192,147 @@ def build_run_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
|
||||
def build_preview(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
section(parent, "截图预览", "选择图片 / 打开pic目录 / 刷新预览")
|
||||
toolbar(parent, [("刷新预览", ctx.action("refresh"), "soft"), ("截图+OCR", ctx.action("screenshot_ocr"), "primary"), "打开pic目录"])
|
||||
preview_panel(parent, data.current_screenshot_path, "当前截图").pack(fill="both", expand=True)
|
||||
preview_panel(
|
||||
parent,
|
||||
data.current_screenshot_path,
|
||||
"当前截图",
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
RESERVATION_COLUMNS = (
|
||||
("idx", "#", 40), ("pos", "位置", 70), ("title", "直播间", 220), ("raw_title", "原始标题", 240),
|
||||
("content", "内容", 220), ("value", "价值", 80), ("countdown", "倒计时/开奖", 120),
|
||||
("participants", "人数", 74), ("copies", "份数", 70), ("task_count", "任务数", 74),
|
||||
("status", "状态", 90), ("target_time", "开奖时间", 160), ("created_time", "记录时间", 160),
|
||||
)
|
||||
|
||||
|
||||
HOME_RESERVATION_COLUMNS = (
|
||||
("idx", "#", 32), ("pos", "位置", 48), ("title", "直播间", 112), ("content", "内容", 214),
|
||||
("value", "价值", 60), ("status", "状态", 72),
|
||||
)
|
||||
|
||||
|
||||
def _reservation_rows_for_display(data: DashboardData, *, include_created: bool) -> list[dict]:
|
||||
rows = reservation_rows(data)
|
||||
for row in rows:
|
||||
row["target_time"] = fmt_ts(row["target_time"])
|
||||
if include_created:
|
||||
row["created_time"] = fmt_ts(row["created_time"])
|
||||
return rows
|
||||
|
||||
|
||||
def _reservation_auto_refresh_var(ctx: PageContext) -> tk.BooleanVar:
|
||||
var = ctx.vars.get("reservation_auto_refresh")
|
||||
if isinstance(var, tk.BooleanVar):
|
||||
return var
|
||||
var = tk.BooleanVar(value=True)
|
||||
ctx.vars["reservation_auto_refresh"] = var
|
||||
return var
|
||||
|
||||
|
||||
def _replace_table_rows(tree: ttk.Treeview, columns: tuple[tuple[str, str, int], ...], rows: list[dict]) -> None:
|
||||
try:
|
||||
yview = tree.yview()
|
||||
top_pos = yview[0]
|
||||
except Exception:
|
||||
top_pos = 0.0
|
||||
for item_id in tree.get_children(""):
|
||||
tree.delete(item_id)
|
||||
if rows:
|
||||
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",),
|
||||
)
|
||||
else:
|
||||
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)], tags=("empty",))
|
||||
try:
|
||||
tree.yview_moveto(top_pos)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _schedule_reservation_table_refresh(
|
||||
table_box: tk.Misc,
|
||||
ctx: PageContext,
|
||||
columns: tuple[tuple[str, str, int], ...],
|
||||
*,
|
||||
include_created: bool,
|
||||
interval_ms: int = 5000,
|
||||
) -> None:
|
||||
enabled_var = _reservation_auto_refresh_var(ctx)
|
||||
if getattr(table_box, "_reservation_refresh_scheduled", False):
|
||||
return
|
||||
setattr(table_box, "_reservation_refresh_scheduled", True)
|
||||
|
||||
def tick() -> None:
|
||||
setattr(table_box, "_reservation_refresh_scheduled", False)
|
||||
try:
|
||||
if not table_box.winfo_exists():
|
||||
return
|
||||
except Exception:
|
||||
return
|
||||
if bool(enabled_var.get()):
|
||||
tree = getattr(table_box, "tree", None)
|
||||
if tree is not None:
|
||||
latest = load_dashboard_data()
|
||||
rows = _reservation_rows_for_display(latest, include_created=include_created)
|
||||
_replace_table_rows(tree, columns, rows)
|
||||
_schedule_reservation_table_refresh(
|
||||
table_box,
|
||||
ctx,
|
||||
columns,
|
||||
include_created=include_created,
|
||||
interval_ms=interval_ms,
|
||||
)
|
||||
|
||||
try:
|
||||
table_box.after(interval_ms, tick)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def reservation_auto_refresh_control(parent: tk.Misc, ctx: PageContext, table_box: tk.Misc, columns, *, include_created: bool) -> tk.Checkbutton:
|
||||
auto_refresh_var = _reservation_auto_refresh_var(ctx)
|
||||
check = tk.Checkbutton(
|
||||
parent,
|
||||
text="自动刷新(5s)",
|
||||
variable=auto_refresh_var,
|
||||
bg=theme.BG,
|
||||
fg=theme.TEXT,
|
||||
activebackground=theme.BG,
|
||||
activeforeground=theme.TEXT,
|
||||
selectcolor=theme.SURFACE,
|
||||
relief="flat",
|
||||
bd=0,
|
||||
font=theme.FONT_UI,
|
||||
cursor="hand2",
|
||||
)
|
||||
check.configure(
|
||||
command=lambda: _schedule_reservation_table_refresh(
|
||||
table_box,
|
||||
ctx,
|
||||
columns,
|
||||
include_created=include_created,
|
||||
)
|
||||
)
|
||||
if bool(auto_refresh_var.get()):
|
||||
_schedule_reservation_table_refresh(table_box, ctx, columns, include_created=include_created)
|
||||
return check
|
||||
|
||||
|
||||
def build_reservation_queue(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
section(parent, "预约队列", "预约队列总览与等待状态")
|
||||
toolbar(parent, [("刷新", ctx.action("refresh"), "soft")])
|
||||
rows = reservation_rows(data)
|
||||
for row in rows:
|
||||
row["target_time"] = fmt_ts(row["target_time"])
|
||||
row["created_time"] = fmt_ts(row["created_time"])
|
||||
table_panel(parent, "预约队列", (
|
||||
("idx", "#", 40), ("pos", "位置", 70), ("title", "直播间", 220), ("raw_title", "原始标题", 240),
|
||||
("content", "内容", 220), ("value", "价值", 80), ("countdown", "倒计时/开奖", 120),
|
||||
("participants", "人数", 74), ("copies", "份数", 70), ("task_count", "任务数", 74),
|
||||
("status", "状态", 90), ("target_time", "开奖时间", 160), ("created_time", "记录时间", 160),
|
||||
), rows, height=18).pack(fill="both", expand=True)
|
||||
tools = toolbar(parent, [("刷新", ctx.action("refresh"), "soft")])
|
||||
rows = _reservation_rows_for_display(data, include_created=True)
|
||||
table = table_panel(parent, "预约队列", RESERVATION_COLUMNS, rows, height=18)
|
||||
table.pack(fill="both", expand=True)
|
||||
reservation_auto_refresh_control(tools, ctx, table, RESERVATION_COLUMNS, include_created=True).pack(side="left", padx=(4, 0))
|
||||
|
||||
|
||||
def build_high_value(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
@@ -260,7 +388,13 @@ def build_realtime(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> No
|
||||
body = tk.Frame(parent, bg=theme.BG)
|
||||
body.pack(fill="both", expand=True)
|
||||
text_panel(body, "动作流", data.action_log[-120:], height=16).pack(fill="both", expand=True, pady=(0, 12))
|
||||
preview_panel(body, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True)
|
||||
preview_panel(
|
||||
body,
|
||||
data.current_screenshot_path,
|
||||
"实时截图",
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
def build_ocr(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
|
||||
@@ -4,13 +4,16 @@ import re
|
||||
import tkinter as tk
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, fmt_ts, load_dashboard_data
|
||||
from .page_data import HOME_RESERVATION_COLUMNS, _reservation_rows_for_display, reservation_auto_refresh_control
|
||||
from .page_context import PageContext
|
||||
from .page_helpers import reservation_rows
|
||||
from .stats_view import StatsDashboardView
|
||||
from .widgets import flow_grid, preview_panel, section, stat_tile, table_panel
|
||||
|
||||
@@ -190,27 +193,40 @@ 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.grid_columnconfigure(0, weight=3, minsize=540)
|
||||
body.grid_columnconfigure(1, weight=2, minsize=380)
|
||||
body.pack(fill="both", expand=True, pady=(4, 0))
|
||||
body.grid_columnconfigure(0, weight=4, minsize=620)
|
||||
body.grid_columnconfigure(1, weight=2, minsize=360)
|
||||
body.grid_rowconfigure(0, weight=1)
|
||||
|
||||
left = tk.Frame(body, bg=theme.BG)
|
||||
right = tk.Frame(body, bg=theme.BG)
|
||||
left.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
||||
right.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
||||
|
||||
rows = reservation_rows(data)
|
||||
for row in rows:
|
||||
row["target_time"] = fmt_ts(row["target_time"])
|
||||
table_panel(left, "预约队列", (
|
||||
("idx", "#", 32), ("pos", "位置", 54), ("title", "直播间", 120), ("content", "内容", 160),
|
||||
("value", "价值", 58), ("countdown", "倒计时", 76), ("status", "状态", 68), ("target_time", "开奖时间", 132),
|
||||
), rows, height=18).pack(fill="both", expand=True)
|
||||
rows = _reservation_rows_for_display(data, include_created=False)
|
||||
reservation_table = table_panel(left, "预约队列", HOME_RESERVATION_COLUMNS, rows, height=18)
|
||||
reservation_table.pack(fill="both", expand=True)
|
||||
control_row = tk.Frame(left, bg=theme.BG)
|
||||
control_row.pack(fill="x", pady=(6, 0))
|
||||
reservation_auto_refresh_control(
|
||||
control_row,
|
||||
ctx,
|
||||
reservation_table,
|
||||
HOME_RESERVATION_COLUMNS,
|
||||
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),
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
def _statistics_values(data: DashboardData, ctx: PageContext) -> tuple[dict[str, Any], str, str]:
|
||||
|
||||
+16
-194
@@ -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
|
||||
+64
-40
@@ -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,35 +51,59 @@ 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", 14),
|
||||
rowheight=44,
|
||||
background=SURFACE,
|
||||
fieldbackground=SURFACE,
|
||||
borderwidth=0,
|
||||
relief="flat",
|
||||
)
|
||||
style.map("Treeview", background=[("selected", TEAL_SOFT)], foreground=[("selected", TEXT)])
|
||||
style.map("Treeview", background=[("selected", TEAL_DARK)], foreground=[("selected", "#ffffff")])
|
||||
style.configure(
|
||||
"Treeview.Heading",
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
background="#edf3f1",
|
||||
font=("Microsoft YaHei UI", 13, "bold"),
|
||||
background="#eaf1f4",
|
||||
foreground=TEXT,
|
||||
relief="flat",
|
||||
padding=(10, 10),
|
||||
)
|
||||
style.configure(
|
||||
"Dashboard.Treeview",
|
||||
font=("Microsoft YaHei UI", 14),
|
||||
rowheight=46,
|
||||
background=SURFACE,
|
||||
fieldbackground=SURFACE,
|
||||
foreground=TEXT,
|
||||
borderwidth=0,
|
||||
relief="flat",
|
||||
)
|
||||
style.map(
|
||||
"Dashboard.Treeview",
|
||||
background=[("selected", TEAL_DARK)],
|
||||
foreground=[("selected", "#ffffff")],
|
||||
)
|
||||
style.configure(
|
||||
"Dashboard.Treeview.Heading",
|
||||
font=("Microsoft YaHei UI", 13, "bold"),
|
||||
background="#eaf1f4",
|
||||
foreground=TEXT,
|
||||
relief="flat",
|
||||
padding=(10, 11),
|
||||
)
|
||||
style.configure(
|
||||
"TCombobox",
|
||||
@@ -88,7 +112,7 @@ def setup_styles(root) -> None:
|
||||
foreground=TEXT,
|
||||
bordercolor=BORDER,
|
||||
arrowcolor=MUTED,
|
||||
padding=(8, 4),
|
||||
padding=(10, 7),
|
||||
)
|
||||
style.map(
|
||||
"TCombobox",
|
||||
@@ -102,6 +126,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)])
|
||||
+256
-83
@@ -27,6 +27,9 @@ BUTTON_ICONS = {
|
||||
"打开pic目录": "□",
|
||||
"打开目录": "□",
|
||||
"验证卡密": "✓",
|
||||
"上传诊断日志": "⇧",
|
||||
"上传日志": "⇧",
|
||||
"检查更新": "↻",
|
||||
"刷新状态": "⟳",
|
||||
"保存日志配置": "✓",
|
||||
"查看大图": "▢",
|
||||
@@ -126,6 +129,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 +179,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 +195,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,25 +225,126 @@ 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")
|
||||
self.enabled = True
|
||||
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("<Button-1>", lambda _e: self._invoke())
|
||||
self.bind("<Enter>", lambda _e: self._draw(hover=True))
|
||||
self.bind("<Leave>", lambda _e: self._draw())
|
||||
|
||||
def _invoke(self) -> None:
|
||||
if self.enabled:
|
||||
self.command()
|
||||
|
||||
def set_active(self, active: bool) -> None:
|
||||
self.active = active
|
||||
self._draw()
|
||||
|
||||
def set_enabled(self, enabled: bool) -> None:
|
||||
self.enabled = bool(enabled)
|
||||
self.configure(cursor="hand2" if self.enabled else "arrow")
|
||||
self._draw()
|
||||
|
||||
def _draw(self, hover: bool = False) -> None:
|
||||
self.delete("all")
|
||||
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)
|
||||
if not self.enabled:
|
||||
bg = theme.SURFACE
|
||||
fg = theme.MUTED
|
||||
else:
|
||||
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, 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)
|
||||
|
||||
|
||||
class SlimScrollbar(tk.Canvas):
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
*,
|
||||
command: Callable[[str, int | float, str | None], None] | None = None,
|
||||
orient: str = "vertical",
|
||||
) -> None:
|
||||
self.orient = "horizontal" if str(orient).startswith("h") else "vertical"
|
||||
super().__init__(
|
||||
parent,
|
||||
width=14 if self.orient == "vertical" else 1,
|
||||
height=14 if self.orient == "horizontal" else 1,
|
||||
bg=theme.SURFACE,
|
||||
highlightthickness=0,
|
||||
bd=0,
|
||||
cursor="hand2",
|
||||
)
|
||||
self.command = command
|
||||
self.first = 0.0
|
||||
self.last = 1.0
|
||||
self._drag_y: int | None = None
|
||||
self.bind("<Configure>", lambda _e: self._draw())
|
||||
self.bind("<Button-1>", self._jump)
|
||||
self.bind("<B1-Motion>", self._drag)
|
||||
self.bind("<ButtonRelease-1>", lambda _e: setattr(self, "_drag_y", None))
|
||||
|
||||
def set(self, first: float | str, last: float | str) -> None:
|
||||
self.first = max(0.0, min(1.0, float(first)))
|
||||
self.last = max(self.first, min(1.0, float(last)))
|
||||
self._draw()
|
||||
|
||||
def _track_length(self) -> int:
|
||||
size = self.winfo_width() if self.orient == "horizontal" else self.winfo_height()
|
||||
return max(1, int(size))
|
||||
|
||||
def _thumb_bounds(self) -> tuple[int, int, int]:
|
||||
length = self._track_length()
|
||||
track_start = 10
|
||||
track_end = max(track_start + 1, length - 10)
|
||||
track_len = track_end - track_start
|
||||
min_thumb = 46 if self.orient == "horizontal" else 42
|
||||
thumb_len = max(min_thumb, int(track_len * max(0.08, self.last - self.first)))
|
||||
travel = max(1, track_len - thumb_len)
|
||||
start = track_start + int(travel * self.first)
|
||||
return start, min(track_end, start + thumb_len), travel
|
||||
|
||||
def _draw(self) -> None:
|
||||
self.delete("all")
|
||||
length = self._track_length()
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.BG_ALT, width=8, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.BG_ALT, width=8, capstyle="round")
|
||||
if self.last - self.first >= 0.995:
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.TEAL_SOFT, width=8, capstyle="round")
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.BORDER_DARK, width=3, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.TEAL_SOFT, width=8, capstyle="round")
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.BORDER_DARK, width=3, capstyle="round")
|
||||
return
|
||||
start, end, _travel = self._thumb_bounds()
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(start, 7, end, 7, fill=theme.TEAL, width=8, capstyle="round")
|
||||
self.create_line(start + 5, 7, end - 5, 7, fill=theme.TEAL_DARK, width=3, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, start, 7, end, fill=theme.TEAL, width=8, capstyle="round")
|
||||
self.create_line(7, start + 5, 7, end - 5, fill=theme.TEAL_DARK, width=3, capstyle="round")
|
||||
|
||||
def _moveto_from_position(self, pos: int) -> None:
|
||||
if not self.command:
|
||||
return
|
||||
start, end, travel = self._thumb_bounds()
|
||||
thumb_len = max(1, end - start)
|
||||
target = (pos - 10 - thumb_len / 2) / max(1, travel)
|
||||
self.command("moveto", max(0.0, min(1.0, target)), None)
|
||||
|
||||
def _jump(self, event) -> None:
|
||||
self._drag_y = int(event.x if self.orient == "horizontal" else event.y)
|
||||
self._moveto_from_position(self._drag_y)
|
||||
|
||||
def _drag(self, event) -> None:
|
||||
self._drag_y = int(event.x if self.orient == "horizontal" else event.y)
|
||||
self._moveto_from_position(self._drag_y)
|
||||
|
||||
|
||||
def clear(frame: tk.Misc) -> None:
|
||||
@@ -246,19 +361,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 +392,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 +447,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(
|
||||
@@ -351,12 +465,12 @@ def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tup
|
||||
spacing1=3,
|
||||
spacing3=4,
|
||||
)
|
||||
yscroll = ttk.Scrollbar(wrap, orient="vertical", command=text.yview)
|
||||
xscroll = ttk.Scrollbar(wrap, orient="horizontal", command=text.xview)
|
||||
yscroll = SlimScrollbar(wrap, orient="vertical", command=lambda *args: text.yview(*[a for a in args if a is not None]))
|
||||
xscroll = SlimScrollbar(wrap, orient="horizontal", command=lambda *args: text.xview(*[a for a in args if a is not None]))
|
||||
text.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set)
|
||||
text.grid(row=0, column=0, sticky="nsew")
|
||||
yscroll.grid(row=0, column=1, sticky="ns")
|
||||
xscroll.grid(row=1, column=0, sticky="ew")
|
||||
yscroll.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8)
|
||||
xscroll.grid(row=1, column=0, sticky="ew", padx=8, pady=(4, 6))
|
||||
content = "\n".join(list(lines)[-1000:]) or "暂无数据"
|
||||
text.insert("1.0", content)
|
||||
text.configure(state="disabled")
|
||||
@@ -376,24 +490,46 @@ 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 = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1, bd=0)
|
||||
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)
|
||||
ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview)
|
||||
xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview)
|
||||
tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height, style="Dashboard.Treeview")
|
||||
tree.tag_configure("odd", background=theme.SURFACE)
|
||||
tree.tag_configure("even", background="#f7fbfc")
|
||||
tree.tag_configure("empty", background=theme.SURFACE_ALT, foreground=theme.MUTED)
|
||||
ybar = SlimScrollbar(table_wrap, orient="vertical", command=lambda *args: tree.yview(*[a for a in args if a is not None]))
|
||||
xbar = SlimScrollbar(table_wrap, orient="horizontal", command=lambda *args: tree.xview(*[a for a in args if a is not None]))
|
||||
tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set)
|
||||
for key, label, width in columns:
|
||||
total_width = sum(width for _key, _label, width in columns)
|
||||
compact_table = total_width <= 640
|
||||
for idx, (key, label, width) in enumerate(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])
|
||||
anchor = "center" if width <= 90 or key in {"idx", "pos", "value", "status"} else "w"
|
||||
stretch = compact_table or len(columns) <= 5 or idx == len(columns) - 1
|
||||
min_width = min(width, 76) if width <= 90 else min(width, 120)
|
||||
tree.column(key, width=width, minwidth=min_width, anchor=anchor, stretch=stretch)
|
||||
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.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)], tags=("empty",))
|
||||
tree.grid(row=0, column=0, sticky="nsew")
|
||||
ybar.grid(row=0, column=1, sticky="ns")
|
||||
xbar.grid(row=1, column=0, sticky="ew")
|
||||
ybar.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8)
|
||||
xbar.grid(row=1, column=0, sticky="ew", padx=10, pady=(4, 7))
|
||||
|
||||
def _wheel(event):
|
||||
tree.yview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
return "break"
|
||||
|
||||
def _shift_wheel(event):
|
||||
tree.xview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
return "break"
|
||||
|
||||
tree.bind("<MouseWheel>", _wheel)
|
||||
tree.bind("<Shift-MouseWheel>", _shift_wheel)
|
||||
table_wrap.configure(width=max(1, min(total_width + 36, 980)))
|
||||
box.tree = tree # type: ignore[attr-defined]
|
||||
box.columns_spec = list(columns) # type: ignore[attr-defined]
|
||||
return box
|
||||
|
||||
|
||||
@@ -415,7 +551,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
|
||||
|
||||
|
||||
@@ -472,20 +608,7 @@ def spin_field(
|
||||
width: int | None = None,
|
||||
state: str = "normal",
|
||||
) -> tk.Frame:
|
||||
row = field_shell(parent, label)
|
||||
if variable is None:
|
||||
variable = tk.StringVar(value=str(value))
|
||||
spin = ttk.Spinbox(
|
||||
row,
|
||||
from_=from_,
|
||||
to=to,
|
||||
increment=increment,
|
||||
textvariable=variable,
|
||||
width=width,
|
||||
state=state,
|
||||
)
|
||||
spin.pack(fill="x", padx=9, pady=(0, 8))
|
||||
return row
|
||||
return field(parent, label, variable, value=value)
|
||||
|
||||
|
||||
def switch_row(parent, label: str, variable: tk.Variable | None = None, value: bool = False) -> tk.Frame:
|
||||
@@ -504,8 +627,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
|
||||
|
||||
|
||||
@@ -521,25 +644,75 @@ def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]
|
||||
return row
|
||||
|
||||
|
||||
def preview_panel(parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560)) -> tk.Frame:
|
||||
def _preview_signature(image_path: Path | None) -> tuple[str, int, int] | None:
|
||||
try:
|
||||
if not image_path or not image_path.exists():
|
||||
return None
|
||||
st = image_path.stat()
|
||||
return (str(image_path), int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))), int(st.st_size))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def preview_panel(
|
||||
parent,
|
||||
image_path: Path | None,
|
||||
title: str = "截图预览",
|
||||
max_size: tuple[int, int] = (360, 560),
|
||||
*,
|
||||
auto_refresh_ms: int = 0,
|
||||
path_getter: Callable[[], Path | None] | None = None,
|
||||
) -> 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))
|
||||
if image_path and image_path.exists():
|
||||
try:
|
||||
from PIL import Image, ImageTk
|
||||
body.pack(fill="both", expand=True, padx=16, pady=(4, 16))
|
||||
box._preview_signature = object() # type: ignore[attr-defined]
|
||||
|
||||
img = Image.open(image_path).convert("RGB")
|
||||
img.thumbnail(max_size)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT)
|
||||
label.image = photo
|
||||
label.pack(expand=True, pady=12)
|
||||
ttk.Label(body, text=os.path.basename(str(image_path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8))
|
||||
return box
|
||||
def _render(path: Path | None, signature: tuple[str, int, int] | None) -> None:
|
||||
box._preview_signature = signature # type: ignore[attr-defined]
|
||||
for child in body.winfo_children():
|
||||
child.destroy()
|
||||
if path and path.exists():
|
||||
try:
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
img = Image.open(path).convert("RGB")
|
||||
img.thumbnail(max_size)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT)
|
||||
label.image = photo
|
||||
label.pack(expand=True, pady=12)
|
||||
ttk.Label(body, text=os.path.basename(str(path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True)
|
||||
|
||||
def _current_path() -> Path | None:
|
||||
if path_getter is not None:
|
||||
try:
|
||||
return path_getter()
|
||||
except Exception:
|
||||
return image_path
|
||||
return image_path
|
||||
|
||||
def _refresh() -> None:
|
||||
try:
|
||||
if not box.winfo_exists():
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True)
|
||||
return
|
||||
path = _current_path()
|
||||
signature = _preview_signature(path)
|
||||
if signature != getattr(box, "_preview_signature", None):
|
||||
_render(path, signature)
|
||||
if auto_refresh_ms > 0:
|
||||
try:
|
||||
box.after(auto_refresh_ms, _refresh)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_refresh()
|
||||
return box
|
||||
|
||||
|
||||
@@ -547,12 +720,12 @@ class ScrollFrame(ttk.Frame):
|
||||
def __init__(self, parent):
|
||||
super().__init__(parent, style="Dashboard.TFrame")
|
||||
self.canvas = tk.Canvas(self, bg=theme.BG, highlightthickness=0, bd=0)
|
||||
self.scroll = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
|
||||
self.scroll = SlimScrollbar(self, orient="vertical", command=lambda *args: self.canvas.yview(*[a for a in args if a is not None]))
|
||||
self.inner = tk.Frame(self.canvas, bg=theme.BG)
|
||||
self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
|
||||
self.canvas.configure(yscrollcommand=self.scroll.set)
|
||||
self.canvas.pack(side="left", fill="both", expand=True)
|
||||
self.scroll.pack(side="right", fill="y")
|
||||
self.scroll.pack(side="right", fill="y", padx=(6, 0), pady=6)
|
||||
self.inner.bind("<Configure>", lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
|
||||
self.canvas.bind("<Configure>", lambda e: self.canvas.itemconfigure(self.window_id, width=e.width))
|
||||
self.canvas.bind_all("<MouseWheel>", self._wheel)
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_app")
|
||||
|
||||
from douyin.core.version import print_version_banner # noqa: E402
|
||||
from gui.gui_app import main # noqa: E402
|
||||
|
||||
+136
-6
@@ -7,18 +7,100 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
DEFAULT_ADB_SERVER_PORT = "5037"
|
||||
FALLBACK_ADB_SERVER_PORTS = ("5038", "5039", "5040")
|
||||
_ADB_SERVER_PROBED_FOR: set[str] = set()
|
||||
|
||||
|
||||
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 _adb_env(port: str | None = None) -> dict[str, str]:
|
||||
env = os.environ.copy()
|
||||
if port:
|
||||
env["ANDROID_ADB_SERVER_PORT"] = str(port)
|
||||
# Windows 上 adb 的 Bonjour backend 经常没有 daemon;openscreen 更稳定。
|
||||
env.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
return env
|
||||
|
||||
|
||||
def _adb_server_responds(adb_exe: str, port: str, timeout: float = 4.0) -> bool:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "devices"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
env=_adb_env(port),
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
out = ((proc.stdout or "") + "\n" + (proc.stderr or "")).lower()
|
||||
if proc.returncode != 0:
|
||||
return False
|
||||
return "failed to start daemon" not in out and "cannot connect to daemon" not in out
|
||||
|
||||
|
||||
def ensure_adb_server_port(adb_exe: str) -> None:
|
||||
"""Ensure later adb subprocesses inherit a working server port.
|
||||
|
||||
On some Windows machines the default 5037 daemon fails to start while a
|
||||
fallback port works. The GUI gets the adb path once and every later
|
||||
operation inherits this process environment, so doing the probe here keeps
|
||||
dashboard / legacy GUI / web GUI consistent.
|
||||
"""
|
||||
adb_path = os.path.abspath(str(adb_exe or ""))
|
||||
if not adb_path or adb_path in _ADB_SERVER_PROBED_FOR:
|
||||
return
|
||||
_ADB_SERVER_PROBED_FOR.add(adb_path)
|
||||
|
||||
os.environ.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
if os.environ.get("ANDROID_ADB_SERVER_PORT"):
|
||||
return
|
||||
|
||||
if _adb_server_responds(adb_path, DEFAULT_ADB_SERVER_PORT):
|
||||
return
|
||||
for port in FALLBACK_ADB_SERVER_PORTS:
|
||||
if _adb_server_responds(adb_path, port):
|
||||
os.environ["ANDROID_ADB_SERVER_PORT"] = port
|
||||
return
|
||||
|
||||
|
||||
def _prepare_adb_path(adb: str) -> str:
|
||||
path = os.path.abspath(adb)
|
||||
ensure_adb_server_port(path)
|
||||
return path
|
||||
|
||||
|
||||
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 _prepare_adb_path(env_adb)
|
||||
|
||||
bundled_adb = path_config.find_bundled_adb()
|
||||
if bundled_adb:
|
||||
return _prepare_adb_path(bundled_adb)
|
||||
|
||||
adb = shutil.which("adb")
|
||||
if adb:
|
||||
return adb
|
||||
return _prepare_adb_path(adb)
|
||||
|
||||
# 默认安装目录(我们之前下载的 platform-tools)
|
||||
# 默认安装目录(本机开发/打包机常用 platform-tools 位置)
|
||||
localapp = os.environ.get("LOCALAPPDATA") or ""
|
||||
candidates = []
|
||||
if localapp:
|
||||
@@ -33,7 +115,7 @@ def find_adb_executable() -> str:
|
||||
|
||||
for p in candidates:
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
return _prepare_adb_path(p)
|
||||
return ""
|
||||
|
||||
|
||||
@@ -50,15 +132,63 @@ def list_adb_devices(adb_exe: str) -> list[str]:
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=5,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
return []
|
||||
devices: list[str] = []
|
||||
for line in (proc.stdout or "").splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == "device":
|
||||
devices.append(parts[0])
|
||||
return devices
|
||||
return _normalize_mdns_device_serials(adb_exe, devices)
|
||||
|
||||
|
||||
def _normalize_mdns_device_serials(adb_exe: str, devices: list[str]) -> list[str]:
|
||||
"""Convert Android wireless-debug mDNS serials to stable ip:port targets."""
|
||||
mdns_serials = [d for d in devices if "._adb" in d or d.startswith("adb-")]
|
||||
if not mdns_serials:
|
||||
return devices
|
||||
mdns_targets: list[str] = []
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "mdns", "services"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=2,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
if "_adb-tls-pairing" in line or "_adb" not in line:
|
||||
continue
|
||||
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})", line)
|
||||
if m:
|
||||
mdns_targets.append(f"{m.group(1)}:{m.group(2)}")
|
||||
except Exception:
|
||||
mdns_targets = []
|
||||
|
||||
out: list[str] = []
|
||||
has_ip_target = any(_is_ip_port_device(d) for d in devices) or bool(mdns_targets)
|
||||
for device in devices:
|
||||
if device in mdns_serials and mdns_targets:
|
||||
for target in mdns_targets:
|
||||
if target not in out:
|
||||
out.append(target)
|
||||
continue
|
||||
if device in mdns_serials and has_ip_target:
|
||||
continue
|
||||
if device not in out:
|
||||
out.append(device)
|
||||
return out
|
||||
|
||||
|
||||
def _is_ip_port_device(device: str) -> bool:
|
||||
return bool(re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}:\d{1,5}", str(device or "").strip()))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import subprocess
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from .adb import find_adb_executable, list_adb_devices
|
||||
from .adb import _adb_env, find_adb_executable, list_adb_devices
|
||||
|
||||
|
||||
def _discover_mdns_connect_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
@@ -38,6 +38,7 @@ def _connect_wifi_adb_once(adb_exe: str, target: str) -> tuple[bool, str, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
output = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
|
||||
@@ -142,6 +143,7 @@ def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
if proc.returncode == 0:
|
||||
@@ -241,6 +243,7 @@ def disconnect_wifi_adb(
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||||
@@ -281,6 +284,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "获取设备IP超时"
|
||||
@@ -315,6 +319,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except Exception:
|
||||
proc2 = None
|
||||
@@ -352,6 +357,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
if proc3.returncode == 0:
|
||||
m = re.search(r"inet\s+addr:?\s*(\d+\.\d+\.\d+\.\d+)", proc3.stdout or "")
|
||||
|
||||
@@ -17,6 +17,8 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Iterable, Optional
|
||||
|
||||
from .adb import _adb_env, list_adb_devices
|
||||
|
||||
|
||||
DEFAULT_ADB_PORT = 5555
|
||||
HI_PORT_MIN = 37000
|
||||
@@ -665,10 +667,6 @@ def scan_open_ports(
|
||||
|
||||
def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int, str]:
|
||||
"""运行 adb 命令,返回 (returncode, stdout+stderr)。"""
|
||||
env = os.environ.copy()
|
||||
# Windows 常见:Bonjour backend 无 daemon,mDNS 发现始终为空。
|
||||
# 默认强制 openscreen,除非用户显式覆盖。
|
||||
env.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, *args],
|
||||
@@ -678,7 +676,7 @@ def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int,
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
env=env,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return -1, "timeout"
|
||||
@@ -730,6 +728,21 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
return targets
|
||||
|
||||
|
||||
def discover_connected_wifi_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
"""Return already-connected WiFi ADB targets from adb devices as scan fallback."""
|
||||
targets: list[tuple[str, int]] = []
|
||||
seen: set[tuple[str, int]] = set()
|
||||
for device in list_adb_devices(adb_exe):
|
||||
parsed = _parse_target_ip_port(device)
|
||||
if not parsed:
|
||||
continue
|
||||
if parsed in seen:
|
||||
continue
|
||||
seen.add(parsed)
|
||||
targets.append(parsed)
|
||||
return targets
|
||||
|
||||
|
||||
def verify_adb_target(adb_exe: str, target: str, timeout: float = 5.0) -> tuple[str, str]:
|
||||
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
|
||||
|
||||
@@ -888,11 +901,17 @@ def discover_adb_devices(
|
||||
|
||||
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
|
||||
mdns_targets = discover_mdns_targets(adb_exe)
|
||||
connected_wifi_targets = discover_connected_wifi_targets(adb_exe)
|
||||
if on_phase and mdns_targets:
|
||||
try:
|
||||
on_phase(f"mDNS 发现 {len(mdns_targets)} 个 ADB 候选目标")
|
||||
except Exception:
|
||||
pass
|
||||
if on_phase and connected_wifi_targets:
|
||||
try:
|
||||
on_phase(f"已连接设备兜底发现 {len(connected_wifi_targets)} 个 WiFi ADB 目标")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
quick_open_targets: list[tuple[str, int]] = []
|
||||
quick_hosts: list[str] = []
|
||||
@@ -956,7 +975,8 @@ def discover_adb_devices(
|
||||
all_open_targets.extend(open_targets)
|
||||
|
||||
# 合并 mDNS + 网段扫描,并去重
|
||||
all_targets = list(mdns_targets)
|
||||
all_targets = list(connected_wifi_targets)
|
||||
all_targets.extend(mdns_targets)
|
||||
all_targets.extend(quick_open_targets)
|
||||
all_targets.extend(all_open_targets)
|
||||
uniq_open: list[tuple[str, int]] = []
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
|
||||
from gui.dashboard_app.app import main # noqa: E402
|
||||
|
||||
|
||||
+7
-3
@@ -24,7 +24,7 @@ if __name__ == "__main__":
|
||||
run_startup_update_check_early(app_name="web_gui")
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import require_online_license_or_exit, start_online_license_monitor
|
||||
from douyin.license.license_manager import check_license, require_online_license_or_exit, start_online_license_monitor
|
||||
|
||||
# 从子包 re-export 顶层 helper(保持兼容)
|
||||
from gui.web_gui_pkg import (
|
||||
@@ -910,8 +910,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
require_online_license_or_exit()
|
||||
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
|
||||
local_status = check_license()
|
||||
if local_status.ok:
|
||||
require_online_license_or_exit()
|
||||
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
|
||||
else:
|
||||
print(f"[LICENSE] 等待授权: {local_status.reason} - {local_status.message}", flush=True)
|
||||
host = get_web_gui_host()
|
||||
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
|
||||
port = get_web_gui_port()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def render_license_gate_html(csrf_token: str) -> str:
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>卡密验证 - 抖音自动化助手</title>
|
||||
<style>
|
||||
:root {{
|
||||
color-scheme: light;
|
||||
--bg: #f5f8fb;
|
||||
--surface: #ffffff;
|
||||
--text: #16202a;
|
||||
--muted: #6f7f8f;
|
||||
--border: #dce7ef;
|
||||
--teal: #13998f;
|
||||
--teal-dark: #08746d;
|
||||
--teal-soft: #e6f7f5;
|
||||
--danger: #c83a4b;
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 28px;
|
||||
font: 16px/1.55 "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(circle at 18% 12%, rgba(19, 153, 143, .12), transparent 30%),
|
||||
linear-gradient(135deg, #fbfdff 0%, var(--bg) 100%);
|
||||
}}
|
||||
.gate {{
|
||||
width: min(520px, 100%);
|
||||
padding: 34px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 22px;
|
||||
background: rgba(255, 255, 255, .92);
|
||||
box-shadow: 0 24px 70px rgba(22, 32, 42, .10);
|
||||
}}
|
||||
.brand {{ display: flex; gap: 16px; align-items: center; margin-bottom: 28px; }}
|
||||
.mark {{
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 14px;
|
||||
color: #fff;
|
||||
background: var(--teal);
|
||||
font-size: 23px;
|
||||
font-weight: 800;
|
||||
}}
|
||||
h1 {{ margin: 0; font-size: 26px; line-height: 1.2; }}
|
||||
p {{ margin: 7px 0 0; color: var(--muted); }}
|
||||
label {{ display: block; margin: 0 0 10px; font-weight: 700; }}
|
||||
input {{
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
padding: 0 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
outline: none;
|
||||
font: inherit;
|
||||
background: #fbfdff;
|
||||
}}
|
||||
input:focus {{
|
||||
border-color: var(--teal);
|
||||
box-shadow: 0 0 0 4px var(--teal-soft);
|
||||
background: #fff;
|
||||
}}
|
||||
button {{
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
margin-top: 18px;
|
||||
border: 0;
|
||||
border-radius: 14px;
|
||||
color: #fff;
|
||||
background: var(--teal);
|
||||
font: inherit;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
}}
|
||||
button:disabled {{ cursor: wait; opacity: .75; }}
|
||||
.msg {{
|
||||
min-height: 24px;
|
||||
margin-top: 14px;
|
||||
color: var(--muted);
|
||||
font-size: 15px;
|
||||
}}
|
||||
.msg.error {{ color: var(--danger); }}
|
||||
.msg.ok {{ color: var(--teal-dark); }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="gate" aria-labelledby="title">
|
||||
<div class="brand">
|
||||
<div class="mark">抖</div>
|
||||
<div>
|
||||
<h1 id="title">卡密验证</h1>
|
||||
<p>首次启动需要先验证卡密,成功后进入控制台。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="license-form">
|
||||
<label for="license-input">输入卡密</label>
|
||||
<input id="license-input" name="license_text" autocomplete="off" autofocus>
|
||||
<button id="submit-btn" type="submit">验证并进入</button>
|
||||
<div id="message" class="msg" role="status"></div>
|
||||
</form>
|
||||
</main>
|
||||
<script>
|
||||
const csrfToken = {csrf_token!r};
|
||||
const form = document.getElementById("license-form");
|
||||
const input = document.getElementById("license-input");
|
||||
const button = document.getElementById("submit-btn");
|
||||
const message = document.getElementById("message");
|
||||
form.addEventListener("submit", async (event) => {{
|
||||
event.preventDefault();
|
||||
const licenseText = input.value.trim();
|
||||
message.className = "msg";
|
||||
if (!licenseText) {{
|
||||
message.textContent = "请先输入卡密。";
|
||||
message.classList.add("error");
|
||||
input.focus();
|
||||
return;
|
||||
}}
|
||||
button.disabled = true;
|
||||
message.textContent = "正在验证...";
|
||||
try {{
|
||||
const res = await fetch("/api/license", {{
|
||||
method: "POST",
|
||||
headers: {{
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": csrfToken
|
||||
}},
|
||||
body: JSON.stringify({{ license_text: licenseText }})
|
||||
}});
|
||||
const data = await res.json().catch(() => ({{}}));
|
||||
if (!res.ok || !data.ok) {{
|
||||
throw new Error(data.message || data.error || "卡密验证失败");
|
||||
}}
|
||||
message.textContent = "验证成功,正在进入...";
|
||||
message.classList.add("ok");
|
||||
window.location.reload();
|
||||
}} catch (err) {{
|
||||
message.textContent = err && err.message ? err.message : "卡密验证失败";
|
||||
message.classList.add("error");
|
||||
}} finally {{
|
||||
button.disabled = false;
|
||||
}}
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>"""
|
||||
@@ -2,12 +2,33 @@ import json
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
|
||||
SECURITY_HEADERS = (
|
||||
("X-Content-Type-Options", "nosniff"),
|
||||
("Referrer-Policy", "no-referrer"),
|
||||
("X-Frame-Options", "DENY"),
|
||||
)
|
||||
|
||||
|
||||
def send_security_headers(handler: BaseHTTPRequestHandler) -> None:
|
||||
for key, value in SECURITY_HEADERS:
|
||||
handler.send_header(key, value)
|
||||
|
||||
|
||||
def send_html_security_headers(handler: BaseHTTPRequestHandler) -> None:
|
||||
send_security_headers(handler)
|
||||
handler.send_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
|
||||
)
|
||||
|
||||
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
try:
|
||||
handler.wfile.write(data)
|
||||
|
||||
@@ -7,10 +7,12 @@ from urllib.parse import parse_qs
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import (
|
||||
check_license,
|
||||
get_default_activation_url,
|
||||
get_license_status_payload,
|
||||
install_license_or_activate,
|
||||
)
|
||||
from gui.web_gui_pkg.license_gate import render_license_gate_html
|
||||
from gui.web_gui_pkg import (
|
||||
_wg_log,
|
||||
find_adb_executable,
|
||||
@@ -19,6 +21,7 @@ from gui.web_gui_pkg import (
|
||||
write_config,
|
||||
proc_runner_ops as _proc_ops,
|
||||
)
|
||||
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
|
||||
|
||||
BASE_DIR = (
|
||||
path_config.PROJECT_ROOT
|
||||
@@ -33,6 +36,23 @@ _EMPTY_PNG_BYTES = bytes.fromhex(
|
||||
"1f15c4890000000a49444154789c636000000200015dc1b2ea00000000"
|
||||
"49454e44ae426082"
|
||||
)
|
||||
_LICENSE_REQUIRED_POST_PATHS = {
|
||||
"/api/start-run",
|
||||
"/api/force-stop",
|
||||
"/api/pause",
|
||||
"/api/resume",
|
||||
"/api/back-key",
|
||||
"/api/wifi/enable",
|
||||
"/api/wifi/connect",
|
||||
"/api/wifi/disconnect",
|
||||
"/api/wifi/scan",
|
||||
"/api/wifi/last/clear",
|
||||
"/api/wifi/auto-reconnect",
|
||||
"/api/test-yanghao",
|
||||
"/api/test-comment",
|
||||
"/api/stop",
|
||||
"/api/screenshot",
|
||||
}
|
||||
|
||||
|
||||
def _is_local_request(handler) -> bool:
|
||||
@@ -72,6 +92,31 @@ def _license_activation_settings() -> tuple[str, int]:
|
||||
return activation_url, max(1, timeout_seconds)
|
||||
|
||||
|
||||
def _license_gate_payload() -> dict:
|
||||
status = check_license()
|
||||
payload = get_license_status_payload()
|
||||
payload.update(
|
||||
{
|
||||
"ok": False,
|
||||
"error": "license_required",
|
||||
"reason": status.reason,
|
||||
"message": status.message,
|
||||
}
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def _send_html(handler, html: str, status: int = 200) -> None:
|
||||
data = html.encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_html_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
|
||||
|
||||
def _is_invalid_ports_spec(spec) -> bool:
|
||||
"""判断端口规格是否为明确非法输入。"""
|
||||
if spec is None:
|
||||
@@ -312,6 +357,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_header("Content-Type", "image/png")
|
||||
handler.send_header("Content-Length", str(len(_EMPTY_PNG_BYTES)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(_EMPTY_PNG_BYTES)
|
||||
return
|
||||
@@ -329,6 +375,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
return
|
||||
@@ -337,6 +384,9 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
|
||||
if u.path in {"/", "/index.html"} and not check_license().ok:
|
||||
return _send_html(handler, render_license_gate_html(csrf_token))
|
||||
|
||||
handler._serve_static(u.path)
|
||||
|
||||
|
||||
@@ -349,6 +399,8 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
||||
return handler._send_json(
|
||||
{"ok": False, "error": "Invalid CSRF token"}, status=403
|
||||
)
|
||||
if u.path in _LICENSE_REQUIRED_POST_PATHS and not check_license().ok:
|
||||
return handler._send_json(_license_gate_payload(), status=403)
|
||||
|
||||
if u.path == "/api/config":
|
||||
body = handler._read_json()
|
||||
|
||||
@@ -3,6 +3,8 @@ from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from typing import Callable
|
||||
|
||||
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
|
||||
|
||||
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
@@ -60,6 +62,7 @@ def serve_static(
|
||||
handler.send_response(HTTPStatus.NOT_MODIFIED)
|
||||
handler.send_header("ETag", etag)
|
||||
handler.send_header("Cache-Control", cache_control)
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
return
|
||||
except Exception:
|
||||
@@ -68,6 +71,10 @@ def serve_static(
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", cache_control)
|
||||
if ext == ".html":
|
||||
send_html_security_headers(handler)
|
||||
else:
|
||||
send_security_headers(handler)
|
||||
if etag:
|
||||
handler.send_header("ETag", etag)
|
||||
handler.end_headers()
|
||||
|
||||
@@ -15,6 +15,12 @@ python -m license_server.manage --db data/app.db unbind DG-XXXX-XXXX-XXXX-XXXX-X
|
||||
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
|
||||
```
|
||||
|
||||
@@ -29,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
|
||||
@@ -78,3 +125,51 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
|
||||
```
|
||||
|
||||
不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。
|
||||
生产环境默认关闭 `/docs`、`/redoc` 和 `/openapi.json`;确实需要临时查看时设置 `DYGJ_LICENSE_ENABLE_DOCS=1`。
|
||||
生产环境建议显式设置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://你的域名`,服务会用它生成兑换链接和更新下载地址。
|
||||
设置 HTTPS 的 `DYGJ_LICENSE_PUBLIC_BASE_URL` 后,后台 Cookie 会默认带 `Secure`;如需手动覆盖,可设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
|
||||
服务端会校验 Host 头,默认允许 `dy.absfan.cn`、`127.0.0.1`、`localhost` 和测试域名;自定义域名可设置 `DYGJ_LICENSE_ALLOWED_HOSTS=你的域名,备用域名`。
|
||||
只有在前面有可信反向代理时,才设置 `DYGJ_LICENSE_TRUST_FORWARDED_FOR=1`。
|
||||
|
||||
## 自动更新
|
||||
|
||||
卡密后台同一个网站也负责发布客户端更新,不需要额外端口:
|
||||
|
||||
```text
|
||||
http://服务器IP:18100/admin
|
||||
```
|
||||
|
||||
登录后在“在线更新”区域先上传新版安装包 `.exe`,填写版本号(例如 `3.3.4`)后点击“上传并发布”。服务端会:
|
||||
|
||||
- 保存安装包到 `data/updates/`
|
||||
- 自动计算安装包 SHA256
|
||||
- 生成 `/api/v1/update/manifest`
|
||||
- 使用服务端私钥给 manifest 签名
|
||||
|
||||
默认上传大小限制:完整安装包最大 700 MB,差量包最大 250 MB。需要调整时设置:
|
||||
|
||||
```bash
|
||||
export DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB=700
|
||||
export DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB=250
|
||||
```
|
||||
|
||||
如果要发布差量更新,再上传 `DouyinGuaji-旧版本_to_新版本_delta.zip`,并填写来源版本和目标版本。新客户端会优先下载匹配自己当前版本的差量包;没有匹配差量包时,才回退下载完整安装包。
|
||||
|
||||
生成差量包示例:
|
||||
|
||||
```bash
|
||||
python -m tools.update_delta build \
|
||||
--old dist/DouyinGuaji-3.3.5 \
|
||||
--new dist/DouyinGuaji-3.3.6 \
|
||||
--out dist/delta/DouyinGuaji-3.3.5_to_3.3.6_delta.zip \
|
||||
--from-version 3.3.5 \
|
||||
--to-version 3.3.6
|
||||
```
|
||||
|
||||
打包后的客户端默认读取:
|
||||
|
||||
```text
|
||||
https://dy.absfan.cn/api/v1/update/manifest
|
||||
```
|
||||
|
||||
如果后台未发布更新,manifest 返回 `version=0.0.0`,客户端不会下载。发布高于客户端当前版本的更新后,客户端启动时会校验 manifest 签名、下载并校验 SHA256,然后退出旧进程执行差量更新或完整安装。
|
||||
+641
-8
@@ -3,26 +3,37 @@ from __future__ import annotations
|
||||
import base64
|
||||
import hmac
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import tempfile
|
||||
import time
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
from fastapi import FastAPI, Form, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
from fastapi import FastAPI, File, Form, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
|
||||
from license_server.core import LicenseActionResult, LicenseService
|
||||
from license_server.core import LicenseActionResult, LicenseService, UpdateManifest
|
||||
|
||||
|
||||
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
|
||||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES = 700 * 1024 * 1024
|
||||
DEFAULT_MAX_DELTA_UPLOAD_BYTES = 250 * 1024 * 1024
|
||||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES = 500 * 1024 * 1024
|
||||
UPLOAD_CHUNK_BYTES = 1024 * 1024
|
||||
|
||||
|
||||
class ActivateRequest(BaseModel):
|
||||
@@ -39,6 +50,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,
|
||||
@@ -84,6 +108,97 @@ 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"}:
|
||||
return True
|
||||
if raw in {"0", "false", "no", "n", "off"}:
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = str(os.environ.get(name) or "").strip()
|
||||
if not raw:
|
||||
return int(default)
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
return int(default)
|
||||
return value if value > 0 else int(default)
|
||||
|
||||
|
||||
def _configured_public_base_url() -> str:
|
||||
return str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
|
||||
|
||||
|
||||
def _default_secure_cookies() -> bool:
|
||||
return _configured_public_base_url().lower().startswith("https://")
|
||||
|
||||
|
||||
def _allowed_hosts_from_env() -> list[str]:
|
||||
raw = str(os.environ.get("DYGJ_LICENSE_ALLOWED_HOSTS") or "").strip()
|
||||
hosts = [h.strip() for h in raw.split(",") if h.strip()]
|
||||
configured = _configured_public_base_url()
|
||||
if configured:
|
||||
parsed = urlparse(configured)
|
||||
if parsed.hostname:
|
||||
hosts.append(parsed.hostname)
|
||||
hosts.extend(["dy.absfan.cn", "127.0.0.1", "localhost", "testserver"])
|
||||
result: list[str] = []
|
||||
for host in hosts:
|
||||
if host and host not in result:
|
||||
result.append(host)
|
||||
return result
|
||||
|
||||
|
||||
async def _save_upload_to_temp(
|
||||
upload: UploadFile,
|
||||
*,
|
||||
upload_dir: Path,
|
||||
max_bytes: int,
|
||||
suffix: str,
|
||||
) -> Path:
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
tmp_name = ""
|
||||
total = 0
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
"wb",
|
||||
delete=False,
|
||||
dir=str(upload_dir),
|
||||
suffix=suffix,
|
||||
) as tmp:
|
||||
tmp_name = tmp.name
|
||||
while True:
|
||||
chunk = await upload.read(UPLOAD_CHUNK_BYTES)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
raise ValueError(f"上传文件超过大小限制(最大 {max_bytes // (1024 * 1024)} MB)")
|
||||
tmp.write(chunk)
|
||||
if total <= 0:
|
||||
raise ValueError("上传文件为空")
|
||||
return Path(tmp_name)
|
||||
except Exception:
|
||||
if tmp_name:
|
||||
try:
|
||||
Path(tmp_name).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
await upload.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _admin_allowed(request: Request, admin_token: str) -> bool:
|
||||
expected = str(admin_token or "").strip()
|
||||
if not expected:
|
||||
@@ -108,6 +223,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()
|
||||
|
||||
@@ -179,8 +305,10 @@ def _csrf_allowed(request: Request, token: str) -> bool:
|
||||
|
||||
|
||||
def _rate_limit_key(request: Request, scope: str) -> str:
|
||||
forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
|
||||
host = forwarded or (request.client.host if request.client else "unknown")
|
||||
host = request.client.host if request.client else "unknown"
|
||||
if getattr(request.app.state, "trust_forwarded_for", False):
|
||||
forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
|
||||
host = forwarded or host
|
||||
return f"{scope}:{host}"
|
||||
|
||||
|
||||
@@ -198,6 +326,90 @@ def _rate_limited(request: Request, scope: str, *, max_requests: int | None = No
|
||||
return False
|
||||
|
||||
|
||||
def _public_base_url(request: Request) -> str:
|
||||
configured = _configured_public_base_url()
|
||||
if configured:
|
||||
return configured.rstrip("/")
|
||||
return str(request.base_url).rstrip("/")
|
||||
|
||||
|
||||
def _signed_update_manifest(service: LicenseService, request: Request) -> dict[str, Any]:
|
||||
manifest = service.load_update_manifest()
|
||||
if not manifest.enabled:
|
||||
payload: dict[str, Any] = {
|
||||
"enabled": False,
|
||||
"version": "0.0.0",
|
||||
"force": False,
|
||||
"message": "no update published",
|
||||
}
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
download_path = f"/api/v1/update/download/{manifest.filename}"
|
||||
payload = {
|
||||
"enabled": True,
|
||||
"version": manifest.version,
|
||||
"url": urljoin(_public_base_url(request) + "/", download_path.lstrip("/")),
|
||||
"filename": manifest.filename,
|
||||
"sha256": manifest.sha256,
|
||||
"force": manifest.force,
|
||||
"notes": manifest.notes,
|
||||
"published_at": manifest.published_at,
|
||||
}
|
||||
if manifest.delta:
|
||||
raw_deltas = manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]
|
||||
deltas: list[dict[str, Any]] = []
|
||||
for raw_delta in raw_deltas:
|
||||
if not isinstance(raw_delta, dict):
|
||||
continue
|
||||
delta = dict(raw_delta)
|
||||
delta_filename = str(delta.get("filename") or "")
|
||||
if delta_filename:
|
||||
delta_path = f"/api/v1/update/download/{delta_filename}"
|
||||
delta["url"] = urljoin(_public_base_url(request) + "/", delta_path.lstrip("/"))
|
||||
deltas.append(delta)
|
||||
payload["delta"] = deltas[0] if len(deltas) == 1 else deltas
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
|
||||
def _update_summary_html(manifest: UpdateManifest) -> str:
|
||||
status = "已开启" if manifest.enabled else "未发布/已关闭"
|
||||
sha = manifest.sha256[:12] + "..." if manifest.sha256 else "-"
|
||||
file_name = manifest.filename or "-"
|
||||
published = manifest.published_at or "-"
|
||||
raw_delta = manifest.delta or {}
|
||||
delta_text = "-"
|
||||
if raw_delta:
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta_text = "<br>".join(
|
||||
f"{escape(str(delta.get('from_version') or ''))}"
|
||||
f" -> {escape(str(delta.get('to_version') or ''))} / "
|
||||
f"<code>{escape(str(delta.get('filename') or '-'))}</code>"
|
||||
for delta in deltas
|
||||
if isinstance(delta, dict)
|
||||
)
|
||||
return (
|
||||
"<div class='update-state'>"
|
||||
f"<b>{escape(status)}</b>"
|
||||
f"<span>版本:<code>{escape(manifest.version or '0.0.0')}</code></span>"
|
||||
f"<span>文件:<code>{escape(file_name)}</code></span>"
|
||||
f"<span>SHA256:<code>{escape(sha)}</code></span>"
|
||||
f"<span>差量包:{delta_text}</span>"
|
||||
f"<span>发布时间:{escape(published)}</span>"
|
||||
"</div>"
|
||||
)
|
||||
|
||||
|
||||
def _format_bytes(size: int) -> str:
|
||||
value = float(size or 0)
|
||||
for unit in ("B", "KB", "MB", "GB"):
|
||||
if value < 1024 or unit == "GB":
|
||||
return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B"
|
||||
value /= 1024
|
||||
return f"{int(size)} B"
|
||||
|
||||
|
||||
def _admin_page(
|
||||
service: LicenseService,
|
||||
csrf_token: str,
|
||||
@@ -208,6 +420,9 @@ def _admin_page(
|
||||
stats = service.stats()
|
||||
card_rows = service.list_cards(limit=50)
|
||||
audit_rows = service.audit_logs(limit=30)
|
||||
diagnostic_rows = service.list_diagnostic_logs(limit=30)
|
||||
update_manifest = service.load_update_manifest()
|
||||
update_html = _update_summary_html(update_manifest)
|
||||
created_rows = "".join(
|
||||
f"<li><code>{escape(card)}</code></li>" for card in (cards or [])
|
||||
)
|
||||
@@ -234,6 +449,18 @@ def _admin_page(
|
||||
"</tr>"
|
||||
for row in audit_rows
|
||||
)
|
||||
diagnostic_html = "".join(
|
||||
"<tr>"
|
||||
f"<td>{escape(row.uploaded_at)}</td>"
|
||||
f"<td><code>{escape(row.code_hint)}</code></td>"
|
||||
f"<td><code>{escape(row.machine_fingerprint[:16])}</code></td>"
|
||||
f"<td>{escape(row.filename)}</td>"
|
||||
f"<td>{escape(_format_bytes(row.size))}</td>"
|
||||
f"<td><code>{escape(row.sha256[:12])}...</code></td>"
|
||||
f"<td><a href='/admin/logs/download/{escape(row.key)}'>下载</a></td>"
|
||||
"</tr>"
|
||||
for row in diagnostic_rows
|
||||
)
|
||||
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
|
||||
html = f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
@@ -252,6 +479,7 @@ def _admin_page(
|
||||
.stat b {{ display: block; font-size: 28px; margin-top: 8px; }}
|
||||
section {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 16px; padding: 18px; margin: 14px 0; box-shadow: 0 12px 30px rgba(15, 23, 42, .06); }}
|
||||
form.inline {{ display: grid; grid-template-columns: repeat(5, minmax(120px, 1fr)); gap: 10px; align-items: end; }}
|
||||
form.update {{ display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; align-items: end; }}
|
||||
label {{ display: block; color: #475569; font-size: 13px; }}
|
||||
input {{ width: 100%; box-sizing: border-box; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 10px; margin-top: 5px; }}
|
||||
button {{ padding: 10px 16px; cursor: pointer; border: 0; border-radius: 10px; background: #2563eb; color: white; font-weight: 700; }}
|
||||
@@ -266,7 +494,9 @@ def _admin_page(
|
||||
.status.revoked {{ background: #fee2e2; color: #991b1b; }}
|
||||
.msg {{ padding: 10px 12px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; }}
|
||||
.cards {{ display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }}
|
||||
@media (max-width: 860px) {{ .grid, .cards, form.inline {{ grid-template-columns: 1fr; }} }}
|
||||
.update-state {{ display: flex; flex-wrap: wrap; gap: 10px 16px; padding: 12px; border-radius: 12px; background: #f8fafc; border: 1px solid #e2e8f0; margin-bottom: 12px; }}
|
||||
.help {{ margin-top: 8px; color: #64748b; font-size: 13px; }}
|
||||
@media (max-width: 860px) {{ .grid, .cards, form.inline, form.update {{ grid-template-columns: 1fr; }} }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -315,6 +545,30 @@ def _admin_page(
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<section>
|
||||
<h2>在线更新</h2>
|
||||
{update_html}
|
||||
<form class="update" method="post" action="/admin/update/publish" enctype="multipart/form-data">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<label>新版本号 <input name="version" placeholder="例如 3.3.4" /></label>
|
||||
<label>说明 <input name="notes" placeholder="更新内容,可留空" /></label>
|
||||
<label>安装包 exe <input name="installer" type="file" accept=".exe" /></label>
|
||||
<label>强制更新 <input name="force" value="1" /></label>
|
||||
<button type="submit">上传并发布</button>
|
||||
</form>
|
||||
<form class="update" method="post" action="/admin/update/publish-delta" enctype="multipart/form-data" style="margin-top:10px">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<label>来源版本 <input name="from_version" placeholder="例如 3.3.5" /></label>
|
||||
<label>目标版本 <input name="to_version" placeholder="例如 3.3.6" /></label>
|
||||
<label>差量 zip <input name="delta_file" type="file" accept=".zip" /></label>
|
||||
<button class="secondary" type="submit">上传差量包</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/update/disable" style="margin-top:10px">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<button class="secondary" type="submit">关闭更新</button>
|
||||
</form>
|
||||
<div class="help">新客户端优先读取差量包,版本不匹配时自动回退完整安装包;manifest、安装包和差量包都会校验签名与 SHA256。</div>
|
||||
</section>
|
||||
<section>
|
||||
<h2>最近卡密</h2>
|
||||
<table>
|
||||
@@ -322,6 +576,14 @@ def _admin_page(
|
||||
<tbody>{table_rows}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section>
|
||||
<h2>客户端诊断日志</h2>
|
||||
<div class="help">同一卡密只保留最新一份日志包,新上传会覆盖旧包。</div>
|
||||
<table>
|
||||
<thead><tr><th>上传时间</th><th>卡密</th><th>机器</th><th>文件名</th><th>大小</th><th>SHA256</th><th>操作</th></tr></thead>
|
||||
<tbody>{diagnostic_html}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section>
|
||||
<h2>最近审计日志</h2>
|
||||
<table>
|
||||
@@ -339,10 +601,35 @@ def create_app(
|
||||
*,
|
||||
service: LicenseService | None = None,
|
||||
admin_token: str | None = None,
|
||||
external_api_token: str | None = None,
|
||||
) -> FastAPI:
|
||||
app = FastAPI(title="Douyin Guaji License Server")
|
||||
docs_enabled = _env_bool("DYGJ_LICENSE_ENABLE_DOCS", default=False)
|
||||
app = FastAPI(
|
||||
title="Douyin Guaji License Server",
|
||||
docs_url="/docs" if docs_enabled else None,
|
||||
redoc_url="/redoc" if docs_enabled else None,
|
||||
openapi_url="/openapi.json" if docs_enabled else None,
|
||||
)
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=_allowed_hosts_from_env())
|
||||
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=_default_secure_cookies())
|
||||
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
|
||||
app.state.max_installer_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB",
|
||||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.max_delta_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB",
|
||||
DEFAULT_MAX_DELTA_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.max_diagnostic_log_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_DIAGNOSTIC_LOG_UPLOAD_MB",
|
||||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.rate_limit_buckets = {}
|
||||
app.state.admin_sessions = {}
|
||||
|
||||
@@ -383,21 +670,263 @@ def create_app(
|
||||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||||
return result_response(get_service().verify_license_doc(req.license))
|
||||
|
||||
@app.post("/api/v1/logs/upload")
|
||||
async def upload_logs(
|
||||
request: Request,
|
||||
license: str = Form(""),
|
||||
log_file: UploadFile = File(...),
|
||||
) -> JSONResponse:
|
||||
if _rate_limited(request, "logs_upload", max_requests=10):
|
||||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||||
try:
|
||||
license_doc = json.loads(str(license or ""))
|
||||
if not isinstance(license_doc, dict):
|
||||
raise ValueError("license must be object")
|
||||
except Exception:
|
||||
return JSONResponse({"ok": False, "reason": "invalid_license", "message": "授权数据格式无效"}, status_code=400)
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
log_file,
|
||||
upload_dir=get_service().diagnostic_log_dir / ".uploads",
|
||||
max_bytes=app.state.max_diagnostic_log_upload_bytes,
|
||||
suffix=".zip.upload",
|
||||
)
|
||||
entry = get_service().save_diagnostic_log_file(
|
||||
license_doc=license_doc,
|
||||
filename=str(log_file.filename or "diagnostic-logs.zip"),
|
||||
file_path=tmp_path,
|
||||
)
|
||||
return JSONResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"message": "日志上传成功",
|
||||
"filename": entry.filename,
|
||||
"size": entry.size,
|
||||
"uploaded_at": entry.uploaded_at,
|
||||
}
|
||||
)
|
||||
except ValueError as exc:
|
||||
reason = str(exc) or "upload_failed"
|
||||
status_code = 413 if "超过大小限制" in reason else 403
|
||||
return JSONResponse({"ok": False, "reason": reason, "message": reason}, status_code=status_code)
|
||||
except Exception as exc:
|
||||
return JSONResponse({"ok": False, "reason": "upload_failed", "message": str(exc)}, status_code=500)
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@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.textContent = "兑换成功,卡密:";
|
||||
const code = document.createElement("code");
|
||||
code.textContent = data.card_key || "";
|
||||
result.appendChild(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))
|
||||
|
||||
@app.get("/api/v1/update/download/{filename}")
|
||||
def update_download(filename: str) -> Response:
|
||||
service = get_service()
|
||||
manifest = service.load_update_manifest()
|
||||
safe_name = Path(str(filename or "")).name
|
||||
allowed_names = {manifest.filename}
|
||||
if manifest.delta:
|
||||
for delta in manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]:
|
||||
if isinstance(delta, dict) and delta.get("filename"):
|
||||
allowed_names.add(str(delta.get("filename")))
|
||||
if not manifest.enabled or safe_name not in allowed_names:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
target = service.update_dir / safe_name
|
||||
if not target.exists():
|
||||
return JSONResponse({"ok": False, "reason": "file_missing"}, status_code=404)
|
||||
return FileResponse(
|
||||
target,
|
||||
media_type="application/octet-stream",
|
||||
filename=safe_name,
|
||||
)
|
||||
|
||||
@app.get("/admin")
|
||||
def admin(request: Request) -> Response:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return RedirectResponse("/admin/login", status_code=303)
|
||||
csrf = _csrf_token(request)
|
||||
response = _admin_page(get_service(), csrf)
|
||||
response.set_cookie(ADMIN_CSRF_COOKIE, csrf, httponly=True, samesite="lax")
|
||||
response.set_cookie(
|
||||
ADMIN_CSRF_COOKIE,
|
||||
csrf,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=bool(app.state.secure_cookies),
|
||||
)
|
||||
return response
|
||||
|
||||
@app.get("/admin/logs/download/{key}")
|
||||
def admin_log_download(request: Request, key: str) -> Response:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return RedirectResponse("/admin/login", status_code=303)
|
||||
target = get_service().diagnostic_log_path(key)
|
||||
if target is None:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
return FileResponse(
|
||||
target,
|
||||
media_type="application/zip",
|
||||
filename=f"diagnostic-{key[:12]}.zip",
|
||||
)
|
||||
|
||||
@app.get("/admin/login")
|
||||
def admin_login_page() -> HTMLResponse:
|
||||
return _login_page()
|
||||
|
||||
@app.post("/admin/login")
|
||||
def admin_login(request: Request, admin_token: str = Form("")) -> HTMLResponse:
|
||||
if _rate_limited(
|
||||
request,
|
||||
"admin_login",
|
||||
max_requests=ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS,
|
||||
):
|
||||
return _login_page("登录尝试过于频繁,请稍后再试。", status_code=429)
|
||||
expected = str(app.state.admin_token or "").strip()
|
||||
supplied = str(admin_token or "").strip()
|
||||
if not expected or not hmac.compare_digest(supplied, expected):
|
||||
@@ -410,6 +939,7 @@ def create_app(
|
||||
max_age=ADMIN_SESSION_SECONDS,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=bool(app.state.secure_cookies),
|
||||
)
|
||||
return response
|
||||
|
||||
@@ -490,6 +1020,109 @@ def create_app(
|
||||
message=f"已解绑 {count} 台设备",
|
||||
)
|
||||
|
||||
@app.post("/admin/update/publish")
|
||||
async def admin_update_publish(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
version: str = Form(""),
|
||||
notes: str = Form(""),
|
||||
force: str = Form("1"),
|
||||
installer: UploadFile = File(...),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
service = get_service()
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
installer,
|
||||
upload_dir=service.update_dir / ".uploads",
|
||||
max_bytes=app.state.max_installer_upload_bytes,
|
||||
suffix=".exe.upload",
|
||||
)
|
||||
manifest = service.publish_update_file(
|
||||
version=version,
|
||||
filename=installer.filename or "",
|
||||
file_path=tmp_path,
|
||||
force=str(force).strip() not in {"0", "false", "False", "否"},
|
||||
notes=notes,
|
||||
)
|
||||
msg = f"已发布更新 V{manifest.version},文件={manifest.filename}"
|
||||
except Exception as exc:
|
||||
msg = f"发布更新失败:{exc}"
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
return _admin_page(get_service(), csrf, message=msg)
|
||||
|
||||
@app.post("/admin/update/publish-delta")
|
||||
async def admin_update_publish_delta(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
from_version: str = Form(""),
|
||||
to_version: str = Form(""),
|
||||
delta_file: UploadFile = File(...),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
service = get_service()
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
delta_file,
|
||||
upload_dir=service.update_dir / ".uploads",
|
||||
max_bytes=app.state.max_delta_upload_bytes,
|
||||
suffix=".zip.upload",
|
||||
)
|
||||
manifest = service.publish_delta_update_file(
|
||||
from_version=from_version,
|
||||
to_version=to_version,
|
||||
filename=delta_file.filename or "",
|
||||
file_path=tmp_path,
|
||||
)
|
||||
raw_delta = manifest.delta or {}
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta = next(
|
||||
(
|
||||
item for item in deltas
|
||||
if isinstance(item, dict)
|
||||
and str(item.get("from_version") or "") == str(from_version).strip().lstrip("Vv")
|
||||
),
|
||||
deltas[-1] if deltas else {},
|
||||
)
|
||||
msg = f"已发布差量更新 {delta.get('from_version')} -> {delta.get('to_version')},文件={delta.get('filename')}"
|
||||
except Exception as exc:
|
||||
msg = f"发布差量更新失败:{exc}"
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
return _admin_page(get_service(), csrf, message=msg)
|
||||
|
||||
@app.post("/admin/update/disable")
|
||||
def admin_update_disable(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
get_service().disable_update()
|
||||
return _admin_page(get_service(), csrf, message="已关闭自动更新发布")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
|
||||
+594
-18
@@ -3,7 +3,9 @@ from __future__ import annotations
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -18,6 +20,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)
|
||||
@@ -28,6 +33,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
|
||||
@@ -71,6 +97,29 @@ class AuditLogEntry:
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiagnosticLogEntry:
|
||||
key: str
|
||||
code_hint: str
|
||||
machine_fingerprint: str
|
||||
filename: str
|
||||
size: int
|
||||
sha256: str
|
||||
uploaded_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateManifest:
|
||||
enabled: bool
|
||||
version: str
|
||||
filename: str
|
||||
sha256: str
|
||||
force: bool
|
||||
notes: str
|
||||
published_at: str
|
||||
delta: dict[str, Any] | list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
@@ -118,6 +167,53 @@ 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"):
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "latest"))
|
||||
raw = f"DouyinGuaji-{safe_version}-Setup.exe"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "DouyinGuaji-Setup.exe"
|
||||
|
||||
|
||||
def sanitize_delta_filename(filename: str, *, from_version: str = "", to_version: str = "") -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
safe_from = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(from_version or "old"))
|
||||
safe_to = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(to_version or "latest"))
|
||||
raw = f"DouyinGuaji-{safe_from}_to_{safe_to}_delta.zip"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "DouyinGuaji-delta.zip"
|
||||
|
||||
|
||||
def sanitize_diagnostic_log_filename(filename: str) -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
raw = "diagnostic-logs.zip"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "diagnostic-logs.zip"
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path: str | Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int:
|
||||
parsed = int(value)
|
||||
if parsed < minimum or parsed > maximum:
|
||||
@@ -139,6 +235,22 @@ class LicenseService:
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_db()
|
||||
|
||||
@property
|
||||
def update_dir(self) -> Path:
|
||||
path = self.db_path.parent / "updates"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
@property
|
||||
def update_manifest_path(self) -> Path:
|
||||
return self.db_path.parent / "update_manifest.json"
|
||||
|
||||
@property
|
||||
def diagnostic_log_dir(self) -> Path:
|
||||
path = self.db_path.parent / "diagnostic_logs"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(self.db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -146,6 +258,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")
|
||||
@@ -182,6 +300,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)
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -200,31 +335,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(
|
||||
@@ -335,6 +554,316 @@ class LicenseService:
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def load_update_manifest(self) -> UpdateManifest:
|
||||
try:
|
||||
raw = json.loads(self.update_manifest_path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "", "")
|
||||
except Exception:
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 读取失败", "")
|
||||
if not isinstance(raw, dict):
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 格式错误", "")
|
||||
raw_filename = str(raw.get("filename") or "").strip()
|
||||
delta = self._normalize_manifest_delta(raw.get("delta"), to_version=str(raw.get("version") or ""))
|
||||
return UpdateManifest(
|
||||
enabled=bool(raw.get("enabled")),
|
||||
version=str(raw.get("version") or "0.0.0").strip() or "0.0.0",
|
||||
filename=sanitize_update_filename(raw_filename, version=str(raw.get("version") or "")) if raw_filename else "",
|
||||
sha256=str(raw.get("sha256") or "").strip().lower(),
|
||||
force=bool(raw.get("force")),
|
||||
notes=str(raw.get("notes") or ""),
|
||||
published_at=str(raw.get("published_at") or ""),
|
||||
delta=delta,
|
||||
)
|
||||
|
||||
def _normalize_manifest_delta(
|
||||
self,
|
||||
raw_delta: Any,
|
||||
*,
|
||||
to_version: str,
|
||||
) -> dict[str, Any] | list[dict[str, Any]] | None:
|
||||
candidates = raw_delta if isinstance(raw_delta, list) else [raw_delta] if isinstance(raw_delta, dict) else []
|
||||
out: list[dict[str, Any]] = []
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
delta = dict(item)
|
||||
delta_filename = str(delta.get("filename") or "").strip()
|
||||
if delta_filename:
|
||||
delta["filename"] = sanitize_delta_filename(
|
||||
delta_filename,
|
||||
from_version=str(delta.get("from_version") or ""),
|
||||
to_version=str(delta.get("to_version") or to_version),
|
||||
)
|
||||
out.append(delta)
|
||||
if not out:
|
||||
return None
|
||||
return out[0] if len(out) == 1 else out
|
||||
|
||||
def _append_delta_to_manifest(
|
||||
self,
|
||||
existing: UpdateManifest,
|
||||
delta: dict[str, Any],
|
||||
) -> UpdateManifest:
|
||||
raw_existing = existing.delta
|
||||
deltas = list(raw_existing) if isinstance(raw_existing, list) else [raw_existing] if isinstance(raw_existing, dict) else []
|
||||
next_deltas = [
|
||||
item for item in deltas
|
||||
if str(item.get("from_version") or "") != str(delta.get("from_version") or "")
|
||||
]
|
||||
next_deltas.append(delta)
|
||||
next_deltas.sort(key=lambda item: str(item.get("from_version") or ""))
|
||||
manifest = UpdateManifest(
|
||||
enabled=existing.enabled,
|
||||
version=existing.version,
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=existing.force,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=next_deltas[0] if len(next_deltas) == 1 else next_deltas,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_update(
|
||||
self,
|
||||
*,
|
||||
version: str,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
force: bool = True,
|
||||
notes: str = "",
|
||||
) -> UpdateManifest:
|
||||
version = str(version or "").strip().lstrip("Vv")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version):
|
||||
raise ValueError("version must look like 3.3.4")
|
||||
if not content:
|
||||
raise ValueError("installer file is empty")
|
||||
safe_filename = sanitize_update_filename(filename, version=version)
|
||||
if not safe_filename.lower().endswith(".exe"):
|
||||
raise ValueError("installer must be an .exe file")
|
||||
target = self.update_dir / safe_filename
|
||||
target.write_bytes(content)
|
||||
manifest = UpdateManifest(
|
||||
enabled=True,
|
||||
version=version,
|
||||
filename=safe_filename,
|
||||
sha256=sha256_bytes(content),
|
||||
force=bool(force),
|
||||
notes=str(notes or "").strip()[:500],
|
||||
published_at=iso_utc(utcnow()),
|
||||
delta=None,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_update_file(
|
||||
self,
|
||||
*,
|
||||
version: str,
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
force: bool = True,
|
||||
notes: str = "",
|
||||
) -> UpdateManifest:
|
||||
version = str(version or "").strip().lstrip("Vv")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version):
|
||||
raise ValueError("version must look like 3.3.4")
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("installer file is empty")
|
||||
safe_filename = sanitize_update_filename(filename, version=version)
|
||||
if not safe_filename.lower().endswith(".exe"):
|
||||
raise ValueError("installer must be an .exe file")
|
||||
target = self.update_dir / safe_filename
|
||||
shutil.copyfile(source, target)
|
||||
manifest = UpdateManifest(
|
||||
enabled=True,
|
||||
version=version,
|
||||
filename=safe_filename,
|
||||
sha256=sha256_file(target),
|
||||
force=bool(force),
|
||||
notes=str(notes or "").strip()[:500],
|
||||
published_at=iso_utc(utcnow()),
|
||||
delta=None,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_delta_update(
|
||||
self,
|
||||
*,
|
||||
from_version: str,
|
||||
to_version: str,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
if not existing.enabled:
|
||||
raise ValueError("publish full installer before delta")
|
||||
to_version = str(to_version or "").strip().lstrip("Vv")
|
||||
from_version = str(from_version or "").strip().lstrip("Vv")
|
||||
if existing.version != to_version:
|
||||
raise ValueError("delta target version must match current manifest version")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", from_version):
|
||||
raise ValueError("from_version must look like 3.3.4")
|
||||
if not content:
|
||||
raise ValueError("delta file is empty")
|
||||
safe_filename = sanitize_delta_filename(filename, from_version=from_version, to_version=to_version)
|
||||
if not safe_filename.lower().endswith(".zip"):
|
||||
raise ValueError("delta must be a .zip file")
|
||||
target = self.update_dir / safe_filename
|
||||
target.write_bytes(content)
|
||||
delta = {
|
||||
"schema": 1,
|
||||
"from_version": from_version,
|
||||
"to_version": to_version,
|
||||
"filename": safe_filename,
|
||||
"sha256": sha256_bytes(content),
|
||||
"size": len(content),
|
||||
}
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def publish_delta_update_file(
|
||||
self,
|
||||
*,
|
||||
from_version: str,
|
||||
to_version: str,
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
if not existing.enabled:
|
||||
raise ValueError("publish full installer before delta")
|
||||
to_version = str(to_version or "").strip().lstrip("Vv")
|
||||
from_version = str(from_version or "").strip().lstrip("Vv")
|
||||
if existing.version != to_version:
|
||||
raise ValueError("delta target version must match current manifest version")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", from_version):
|
||||
raise ValueError("from_version must look like 3.3.4")
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("delta file is empty")
|
||||
safe_filename = sanitize_delta_filename(filename, from_version=from_version, to_version=to_version)
|
||||
if not safe_filename.lower().endswith(".zip"):
|
||||
raise ValueError("delta must be a .zip file")
|
||||
target = self.update_dir / safe_filename
|
||||
shutil.copyfile(source, target)
|
||||
delta = {
|
||||
"schema": 1,
|
||||
"from_version": from_version,
|
||||
"to_version": to_version,
|
||||
"filename": safe_filename,
|
||||
"sha256": sha256_file(target),
|
||||
"size": target.stat().st_size,
|
||||
}
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def save_diagnostic_log_file(
|
||||
self,
|
||||
*,
|
||||
license_doc: dict[str, Any],
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
) -> DiagnosticLogEntry:
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("diagnostic log file is empty")
|
||||
payload = self._validated_license_payload_for_upload(license_doc)
|
||||
card_hash = str(payload.get("card_hash") or "").strip().lower()
|
||||
raw_machine = str(payload.get("machine_fingerprint") or "").strip()
|
||||
safe_original = sanitize_diagnostic_log_filename(filename)
|
||||
key = hashlib.sha256(card_hash.encode("ascii")).hexdigest()
|
||||
target = self.diagnostic_log_dir / f"{key}.zip"
|
||||
shutil.copyfile(source, target)
|
||||
uploaded_at = iso_utc(utcnow())
|
||||
meta = {
|
||||
"key": key,
|
||||
"code_hint": f"{card_hash[:8]}...{card_hash[-4:]}",
|
||||
"machine_fingerprint": raw_machine,
|
||||
"filename": safe_original,
|
||||
"stored_filename": target.name,
|
||||
"size": target.stat().st_size,
|
||||
"sha256": sha256_file(target),
|
||||
"uploaded_at": uploaded_at,
|
||||
}
|
||||
target.with_suffix(".json").write_text(
|
||||
json.dumps(meta, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return DiagnosticLogEntry(
|
||||
key=key,
|
||||
code_hint=str(meta["code_hint"]),
|
||||
machine_fingerprint=raw_machine,
|
||||
filename=safe_original,
|
||||
size=int(meta["size"]),
|
||||
sha256=str(meta["sha256"]),
|
||||
uploaded_at=uploaded_at,
|
||||
)
|
||||
|
||||
def list_diagnostic_logs(self, *, limit: int = 30) -> list[DiagnosticLogEntry]:
|
||||
rows: list[DiagnosticLogEntry] = []
|
||||
for meta_path in sorted(
|
||||
self.diagnostic_log_dir.glob("*.json"),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)[: max(1, int(limit))]:
|
||||
try:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
rows.append(
|
||||
DiagnosticLogEntry(
|
||||
key=str(meta.get("key") or meta_path.stem),
|
||||
code_hint=str(meta.get("code_hint") or ""),
|
||||
machine_fingerprint=str(meta.get("machine_fingerprint") or ""),
|
||||
filename=str(meta.get("filename") or ""),
|
||||
size=int(meta.get("size") or 0),
|
||||
sha256=str(meta.get("sha256") or ""),
|
||||
uploaded_at=str(meta.get("uploaded_at") or ""),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
return rows
|
||||
|
||||
def diagnostic_log_path(self, key: str) -> Path | None:
|
||||
raw = str(key or "").strip()
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", raw):
|
||||
return None
|
||||
target = self.diagnostic_log_dir / f"{raw}.zip"
|
||||
return target if target.is_file() else None
|
||||
|
||||
def disable_update(self) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
manifest = UpdateManifest(
|
||||
enabled=False,
|
||||
version=existing.version or "0.0.0",
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=False,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=existing.delta,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def sign_payload(self, payload: dict[str, Any]) -> str:
|
||||
signature = self.private_key.sign(canonical_payload_bytes(payload))
|
||||
return base64.b64encode(signature).decode("ascii")
|
||||
|
||||
def activate(self, code: str, *, machine_fingerprint: str) -> LicenseActionResult:
|
||||
raw_machine = str(machine_fingerprint or "").strip()
|
||||
if not raw_machine:
|
||||
@@ -443,6 +972,21 @@ class LicenseService:
|
||||
touch_last_seen=False,
|
||||
)
|
||||
|
||||
def _validated_license_payload_for_upload(self, license_doc: dict[str, Any]) -> dict[str, Any]:
|
||||
result = self.verify_license_doc(license_doc)
|
||||
if not result.ok:
|
||||
raise ValueError(result.reason)
|
||||
payload = license_doc.get("payload") if isinstance(license_doc, dict) else None
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("invalid_format")
|
||||
card_hash = str(payload.get("card_hash") or "").strip().lower()
|
||||
raw_machine = str(payload.get("machine_fingerprint") or "").strip()
|
||||
if len(card_hash) != 64 or any(ch not in "0123456789abcdef" for ch in card_hash):
|
||||
raise ValueError("invalid_card_hash")
|
||||
if not raw_machine:
|
||||
raise ValueError("missing_machine")
|
||||
return payload
|
||||
|
||||
def _verify_card_row(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
@@ -495,6 +1039,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":
|
||||
|
||||
@@ -45,6 +45,26 @@ def _ops_log(msg: str, level: str = "INFO") -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _adb_shell_png_variants(data: bytes) -> list[bytes]:
|
||||
if not data:
|
||||
return []
|
||||
variants: list[bytes] = []
|
||||
|
||||
def _add(candidate: bytes) -> None:
|
||||
if candidate and candidate not in variants:
|
||||
variants.append(candidate)
|
||||
|
||||
marker = b"\x89PNG"
|
||||
idx = data.find(marker)
|
||||
if idx > 0:
|
||||
data = data[idx:]
|
||||
|
||||
_add(data)
|
||||
_add(data.replace(b"\r\r\n", b"\r\n"))
|
||||
_add(data.replace(b"\r\n", b"\n"))
|
||||
return variants
|
||||
|
||||
|
||||
|
||||
|
||||
class ScreenshotOperations:
|
||||
@@ -169,60 +189,119 @@ class ScreenshotOperations:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _write_valid_png_bytes(data: bytes) -> bool:
|
||||
for candidate in _adb_shell_png_variants(data):
|
||||
try:
|
||||
with open(tmp_file, "wb") as f:
|
||||
f.write(candidate)
|
||||
if _valid_png(tmp_file):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def _try_shell_stdout_fallback() -> bool:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
if _write_valid_png_bytes(result.stdout or b"") and _safe_replace_file(tmp_file, out_file):
|
||||
if _valid_png(out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
elapsed = (time.time() - direct_start) * 1000
|
||||
_ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (shell stdout回退,耗时: {elapsed:.0f}ms)")
|
||||
return True
|
||||
_ops_log(f"[截图] shell stdout回退输出无效: bytes={len(result.stdout or b'')}")
|
||||
except subprocess.CalledProcessError as e:
|
||||
_ops_log(f"[截图] shell stdout回退失败:ADB命令错误 (返回码: {e.returncode})")
|
||||
except subprocess.TimeoutExpired:
|
||||
_ops_log(f"[截图] shell stdout回退失败:操作超时 (设备ID: {device_id})")
|
||||
except Exception as e:
|
||||
_ops_log(f"[截图] shell stdout回退失败:{e}")
|
||||
return False
|
||||
|
||||
def _format_adb_stderr(value: bytes | str | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, bytes):
|
||||
text = value.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = str(value)
|
||||
text = " ".join(text.strip().split())
|
||||
return text[-500:]
|
||||
|
||||
adb_recovered = False
|
||||
|
||||
def _recover_adb_once(reason: str) -> None:
|
||||
nonlocal adb_recovered
|
||||
if adb_recovered:
|
||||
return
|
||||
adb_recovered = True
|
||||
_ops_log(f"[截图] ADB截图输出异常,尝试重启ADB服务后重试: {reason}", "WARNING")
|
||||
for args, timeout in (
|
||||
([adb, "kill-server"], 5),
|
||||
([adb, "start-server"], 8),
|
||||
):
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
err = _format_adb_stderr(proc.stderr or proc.stdout)
|
||||
_ops_log(f"[截图] ADB恢复命令返回异常 rc={proc.returncode} err={err}", "WARNING")
|
||||
except Exception as exc:
|
||||
_ops_log(f"[截图] ADB恢复命令执行失败: {exc}", "WARNING")
|
||||
time.sleep(0.5)
|
||||
|
||||
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
|
||||
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
|
||||
for _ in range(2):
|
||||
for attempt in range(2):
|
||||
try:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
# 使用 Popen 流式读取,边接收数据边写入文件,提高性能
|
||||
t_exec_start = time.time()
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
exec_ms = (time.time() - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
out = result.stdout or b""
|
||||
err = _format_adb_stderr(result.stderr)
|
||||
if result.returncode != 0:
|
||||
reason = f"rc={result.returncode} bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(f"[截图] exec-out 返回异常: {reason}", "WARNING")
|
||||
if result.returncode == 4294967295:
|
||||
_ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
if not _write_valid_png_bytes(out):
|
||||
reason = f"rc=0 bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(
|
||||
f"[截图] exec-out 输出无效: {reason} attempt={attempt + 1}/2",
|
||||
"WARNING",
|
||||
)
|
||||
|
||||
# 流式写入文件,避免等待整个命令完成
|
||||
with open(tmp_file, "wb") as f:
|
||||
while True:
|
||||
chunk = process.stdout.read(65536) # 64KB 缓冲
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
# 确保数据落盘,避免后续读取到半写文件
|
||||
try:
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待进程完成并检查返回码
|
||||
return_code = process.wait(timeout=10)
|
||||
if return_code != 0:
|
||||
# 特殊处理常见的adb错误码
|
||||
if return_code == 4294967295: # 0xFFFFFFFF
|
||||
raise subprocess.CalledProcessError(
|
||||
return_code,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
f"设备连接失败或ADB服务异常 (错误码: {return_code})"
|
||||
)
|
||||
else:
|
||||
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
|
||||
|
||||
t_exec_end = time.time()
|
||||
exec_ms = (t_exec_end - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
_ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})")
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
# Popen 超时,记录并重新抛出异常
|
||||
_ops_log(f"[截图] exec-out 流式读取超时")
|
||||
raise
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
_ops_log(
|
||||
f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms bytes={len(out)} (device_id={device_id})"
|
||||
)
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
@@ -246,7 +325,10 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案")
|
||||
except subprocess.TimeoutExpired:
|
||||
# 超时异常,记录并继续重试
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案")
|
||||
reason = f"timeout device_id={device_id}"
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案", "WARNING")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -314,7 +396,7 @@ class ScreenshotOperations:
|
||||
return False
|
||||
else:
|
||||
_ops_log("[截图] 回退方案截图无效")
|
||||
return False
|
||||
return _try_shell_stdout_fallback()
|
||||
except subprocess.CalledProcessError as e:
|
||||
# 特殊处理adb错误
|
||||
if e.returncode == 4294967295:
|
||||
@@ -325,6 +407,8 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})")
|
||||
except Exception as e:
|
||||
_ops_log(f"[截图] 回退方案失败:{e}")
|
||||
if _try_shell_stdout_fallback():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
|
||||
+50
-11
@@ -19,23 +19,35 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall
|
||||
```
|
||||
|
||||
如果要生成混淆后的分发包,加 `-Obfuscate`:
|
||||
正式打包默认会先通过 Cython 编译 `douyin/` 和 `operations/` 核心模块,再让 PyInstaller 从 `build\cythonized-src\` 打包:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -Obfuscate
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall
|
||||
```
|
||||
|
||||
混淆流程会先生成 `build\obfuscated-src\`,再让 PyInstaller 从该目录打包。该目录是中间产物,不要直接分发;最终仍然只分发 `dist\DouyinGuaji-<version>\` 或 Inno 生成的安装包。
|
||||
该流程会生成 `build\cythonized-src\`,其中核心模块以 `.pyd` 形式存在。该目录是中间产物,不要直接分发;最终仍然只分发 `dist\DouyinGuaji-<version>\` 或 Inno 生成的安装包。
|
||||
|
||||
注意:PyArmor 试用版会在混淆文件头部留下 trial 标记,正式分发前建议购买/配置正式授权后重新打包。
|
||||
如果只是小更新、想复用 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`:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -NoCythonForDevOnly
|
||||
```
|
||||
|
||||
如果要尝试对根目录 exe 做 UPX 加壳/压缩,可额外加 `-PackExe -UpxDir <UPX目录>`:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -Obfuscate -PackExe -UpxDir C:\path\to\upx
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -PackExe -UpxDir C:\path\to\upx
|
||||
```
|
||||
|
||||
当前 PyInstaller 生成的 exe 带 `GUARD_CF`,UPX 默认会拒绝压缩。脚本提供 `-PackExeForce` 仅用于实验;验证中它会导致 exe 启动失败并报 `Failed to load Python DLL`,脚本已加入加壳后 smoke 检查,失败会中止打包。正式分发目前建议使用 `-Obfuscate`,不要启用 `-PackExeForce`。
|
||||
当前 PyInstaller 生成的 exe 带 `GUARD_CF`,UPX 默认会拒绝压缩。脚本提供 `-PackExeForce` 仅用于实验;验证中它会导致 exe 启动失败并报 `Failed to load Python DLL`,脚本已加入加壳后 smoke 检查,失败会中止打包。正式分发不要启用 `-PackExeForce`。
|
||||
|
||||
如果要生成带本地授权的测试包,先生成当前机器的 `license.dat`:
|
||||
|
||||
@@ -53,13 +65,24 @@ dist\DouyinGuaji-<version>\
|
||||
|
||||
主要文件:
|
||||
|
||||
- `DouyinGuajiGUI.exe`:桌面 GUI 主入口
|
||||
- `DouyinGuajiGUI.exe`:数据看板版桌面 GUI 主入口
|
||||
- `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`
|
||||
- `drivers/HiSuite/`:默认不随包;仅在显式传入华为/荣耀 HiSuite 官方安装器时复制
|
||||
- `logs/`、`pic/`、`state/`:运行时输出目录
|
||||
- `license.dat`:默认不随包分发;仅本地测试包需要时才使用 `-IncludeLicense` 显式复制
|
||||
|
||||
华为/荣耀手机如果在新电脑上 MTP 或 ADB 识别异常,可先从华为官方页面下载 HiSuite 安装器,再在打包时显式带入:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -HiSuiteInstallerPath "C:\path\to\HiSuite.exe"
|
||||
```
|
||||
|
||||
该参数只把安装器放入 `drivers\HiSuite\` 方便目标电脑手动安装,不会静默安装第三方驱动。
|
||||
|
||||
测试包如需临时带入本地 `license.dat`:
|
||||
|
||||
```powershell
|
||||
@@ -80,11 +103,27 @@ iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=3.3.3
|
||||
dist\installer\DouyinGuaji-3.3.3-Setup.exe
|
||||
```
|
||||
|
||||
## 从零安装验收
|
||||
|
||||
打完便携包和安装包后,运行:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\ci\fresh_install_smoke.ps1
|
||||
```
|
||||
|
||||
脚本会静默安装到 `artifacts\fresh_install_ci\DouyinGuajiApp`,并检查默认配置、随包 ADB、ADBKeyboard、WebGUI 首次卡密门禁、未授权运行接口拦截、Dashboard 首次启动不闪退。
|
||||
|
||||
验收报告:
|
||||
|
||||
```text
|
||||
artifacts\fresh_install_ci\fresh_install_report.json
|
||||
```
|
||||
|
||||
## 发给别人前检查
|
||||
|
||||
- 打包脚本会自动运行 `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 中保存配置。
|
||||
- 启用 `-Obfuscate` 后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。
|
||||
- `config/default_config.json` 会随安装包复制为 `config/config.json`,只放正式默认值,不放个人设备、卡密或运行状态。
|
||||
- 默认 Cython 编译后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。使用 `-NoCythonForDevOnly` 生成的明文包禁止分发。
|
||||
@@ -1,10 +1,15 @@
|
||||
param(
|
||||
[string]$Version = "",
|
||||
[switch]$SkipInstall,
|
||||
[switch]$Obfuscate,
|
||||
[switch]$NoCythonForDevOnly,
|
||||
[switch]$UsePyArmor,
|
||||
[switch]$NoObfuscateForDevOnly,
|
||||
[switch]$PackExe,
|
||||
[switch]$PackExeForce,
|
||||
[switch]$IncludeLicense,
|
||||
[switch]$ReuseCache,
|
||||
[string]$PlatformToolsDir = "",
|
||||
[string]$HiSuiteInstallerPath = "",
|
||||
[string]$UpxDir = ""
|
||||
)
|
||||
|
||||
@@ -27,8 +32,10 @@ if (-not $SkipInstall) {
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install pyinstaller
|
||||
if ($Obfuscate) {
|
||||
if ($UsePyArmor) {
|
||||
python -m pip install pyarmor
|
||||
} elseif (-not $NoCythonForDevOnly -and -not $NoObfuscateForDevOnly) {
|
||||
python -m pip install cython setuptools wheel
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,16 +47,23 @@ New-Item -ItemType Directory -Force $DistRoot | Out-Null
|
||||
|
||||
$BuildSourceRoot = $Root
|
||||
$HiddenImportsFile = Join-Path $Root "build\obfuscation-hidden-imports.json"
|
||||
if ($Obfuscate) {
|
||||
if ($UsePyArmor -and -not $NoObfuscateForDevOnly) {
|
||||
$BuildSourceRoot = Join-Path $Root "build\obfuscated-src"
|
||||
python -m tools.obfuscation_staging --source-root $Root --staging-root $BuildSourceRoot --hidden-imports-output $HiddenImportsFile
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "PyArmor obfuscation failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
} elseif (-not $NoCythonForDevOnly -and -not $NoObfuscateForDevOnly) {
|
||||
$BuildSourceRoot = Join-Path $Root "build\cythonized-src"
|
||||
python -m tools.cython_staging --source-root $Root --staging-root $BuildSourceRoot --hidden-imports-output $HiddenImportsFile
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Cython core compile failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
} else {
|
||||
Write-Warning "Development plaintext build requested. Do not distribute this package."
|
||||
}
|
||||
|
||||
$CommonArgs = @(
|
||||
"--clean",
|
||||
"--noconfirm",
|
||||
"--distpath", $DistRoot,
|
||||
"--workpath", (Join-Path $Root "build\pyinstaller"),
|
||||
@@ -58,8 +72,27 @@ $CommonArgs = @(
|
||||
"--hidden-import", "PIL._tkinter_finder",
|
||||
"--hidden-import", "ttkbootstrap",
|
||||
"--hidden-import", "logging.handlers",
|
||||
"--hidden-import", "cryptography.hazmat.primitives.serialization"
|
||||
"--hidden-import", "cryptography.hazmat.primitives.serialization",
|
||||
"--collect-submodules", "cv2",
|
||||
"--collect-submodules", "numpy",
|
||||
"--collect-submodules", "PIL",
|
||||
"--collect-submodules", "paddle",
|
||||
"--collect-submodules", "paddleocr",
|
||||
"--collect-submodules", "paddlex",
|
||||
"--collect-submodules", "pyclipper",
|
||||
"--collect-submodules", "shapely",
|
||||
"--collect-binaries", "cv2",
|
||||
"--collect-binaries", "numpy",
|
||||
"--collect-binaries", "paddle",
|
||||
"--collect-binaries", "pyclipper",
|
||||
"--collect-binaries", "shapely",
|
||||
"--collect-data", "PIL",
|
||||
"--collect-data", "paddlex",
|
||||
"--collect-data", "paddleocr"
|
||||
)
|
||||
if (-not $ReuseCache) {
|
||||
$CommonArgs = @("--clean") + $CommonArgs
|
||||
}
|
||||
|
||||
$GuiArgs = @(
|
||||
"--collect-submodules", "gui"
|
||||
@@ -86,7 +119,7 @@ foreach ($name in $ExcludedOptionalModules) {
|
||||
$CommonArgs += @("--exclude-module", $name)
|
||||
}
|
||||
|
||||
if ($Obfuscate -and (Test-Path $HiddenImportsFile)) {
|
||||
if ((-not $NoObfuscateForDevOnly) -and (-not $NoCythonForDevOnly -or $UsePyArmor) -and (Test-Path $HiddenImportsFile)) {
|
||||
$HiddenImports = Get-Content -LiteralPath $HiddenImportsFile -Raw | ConvertFrom-Json
|
||||
$CliOnlyHiddenImportRoots = @("cv2", "numpy", "paddleocr", "paddle")
|
||||
foreach ($name in $HiddenImports) {
|
||||
@@ -100,7 +133,7 @@ if ($Obfuscate -and (Test-Path $HiddenImportsFile)) {
|
||||
}
|
||||
}
|
||||
|
||||
python -m PyInstaller @CommonArgs @GuiArgs --name DouyinGuajiGUI --windowed (Join-Path $BuildSourceRoot "gui\gui_app_entry.py")
|
||||
python -m PyInstaller @CommonArgs @GuiArgs --name DouyinGuajiGUI --windowed (Join-Path $BuildSourceRoot "gui\gui_dashboard_app_entry.py")
|
||||
python -m PyInstaller @CommonArgs @GuiArgs --name web_gui --console (Join-Path $BuildSourceRoot "gui\web_gui_entry.py")
|
||||
python -m PyInstaller @CommonArgs @CliArgs --name run_cli --console (Join-Path $BuildSourceRoot "bin\run_cli_entry.py")
|
||||
|
||||
@@ -116,30 +149,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"
|
||||
@@ -162,14 +184,107 @@ foreach ($dir in @("css", "js", "partials")) {
|
||||
} | Copy-Item -Destination $dstDir -Force
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force (Join-Path $DistRoot "config") | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $DistRoot "config\README.md") -Force
|
||||
$ConfigTarget = Join-Path $DistRoot "config"
|
||||
New-Item -ItemType Directory -Force $ConfigTarget | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $ConfigTarget "README.md") -Force
|
||||
$DefaultConfig = Join-Path $Root "config\default_config.json"
|
||||
if (-not (Test-Path $DefaultConfig)) {
|
||||
throw "Missing default runtime config: config\default_config.json"
|
||||
}
|
||||
Copy-Item -LiteralPath $DefaultConfig -Destination (Join-Path $ConfigTarget "config.json") -Force
|
||||
foreach ($dir in @("logs", "pic", "state")) {
|
||||
$runtimeDir = Join-Path $DistRoot $dir
|
||||
New-Item -ItemType Directory -Force $runtimeDir | Out-Null
|
||||
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
|
||||
|
||||
if ($HiSuiteInstallerPath) {
|
||||
if (-not (Test-Path -LiteralPath $HiSuiteInstallerPath)) {
|
||||
throw "HiSuite installer not found: $HiSuiteInstallerPath"
|
||||
}
|
||||
$DriverTarget = Join-Path $DistRoot "drivers\HiSuite"
|
||||
if (Test-Path $DriverTarget) {
|
||||
Remove-Item -LiteralPath $DriverTarget -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $DriverTarget | Out-Null
|
||||
$installerItem = Get-Item -LiteralPath $HiSuiteInstallerPath
|
||||
Copy-Item -LiteralPath $installerItem.FullName -Destination (Join-Path $DriverTarget $installerItem.Name) -Force
|
||||
@"
|
||||
Huawei / Honor USB driver helper
|
||||
|
||||
If Windows cannot show the phone as MTP or ADB is unstable, install HiSuite on the computer, reconnect the phone, choose File Transfer / MTP on the phone, and allow USB debugging authorization.
|
||||
|
||||
This third-party installer is provided only when explicitly passed to the build script.
|
||||
"@ | Set-Content -LiteralPath (Join-Path $DriverTarget "README.txt") -Encoding UTF8
|
||||
}
|
||||
|
||||
$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
@@ -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.11"
|
||||
description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -13,6 +13,7 @@ opencv-python>=4.5.0
|
||||
|
||||
# OCR识别 - PaddleOCR(主要OCR引擎)
|
||||
paddleocr>=3.0.0
|
||||
paddlex>=3.0.0
|
||||
|
||||
# 深度学习框架(PaddleOCR的依赖)
|
||||
# 注意:PaddleOCR 3.0 需要 PaddlePaddle 3.0+
|
||||
|
||||
+467
-3
@@ -5,6 +5,9 @@ import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM, TEST_PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
def test_compare_versions_handles_v_prefix_and_patch_order():
|
||||
@@ -15,19 +18,77 @@ def test_compare_versions_handles_v_prefix_and_patch_order():
|
||||
assert compare_versions("3.3.2", "3.3.3") < 0
|
||||
|
||||
|
||||
def test_load_settings_is_disabled_without_manifest_url(tmp_path, monkeypatch):
|
||||
def test_load_settings_uses_default_server_without_manifest_url(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.manifest_url == force_update.DEFAULT_UPDATE_MANIFEST_URL
|
||||
assert settings.require_signed_manifest is True
|
||||
|
||||
|
||||
def test_load_settings_can_disable_default_auto_update(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": True}}), encoding="utf-8")
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": False}}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is False
|
||||
assert settings.manifest_url == ""
|
||||
assert settings.manifest_url
|
||||
|
||||
|
||||
def test_manual_update_settings_enable_check_without_fail_closed(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import load_manual_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": False}}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_manual_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.fail_closed is False
|
||||
assert settings.manifest_url
|
||||
|
||||
|
||||
def test_load_settings_uses_default_server_for_frozen_exe(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.setattr(force_update.sys, "frozen", True, raising=False)
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.manifest_url == force_update.DEFAULT_UPDATE_MANIFEST_URL
|
||||
assert settings.require_https is False
|
||||
assert settings.require_signed_manifest is True
|
||||
|
||||
|
||||
def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
@@ -81,6 +142,409 @@ def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
assert any(arg.startswith("/LOG=") for arg in launched[0])
|
||||
|
||||
|
||||
def test_default_update_settings_launch_visible_installer_and_disable_delta(tmp_path):
|
||||
from douyin.updater.force_update import DEFAULT_INSTALLER_ARGS, UpdateSettings
|
||||
|
||||
settings = UpdateSettings(enabled=True, manifest_url="https://example.test/update.json", download_dir=tmp_path)
|
||||
|
||||
assert "/VERYSILENT" not in DEFAULT_INSTALLER_ARGS
|
||||
assert "/SILENT" not in DEFAULT_INSTALLER_ARGS
|
||||
assert "/SUPPRESSMSGBOXES" not in DEFAULT_INSTALLER_ARGS
|
||||
assert settings.allow_delta is False
|
||||
|
||||
|
||||
def test_forced_update_prefers_matching_delta_package(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
file_payload = b"new exe bytes"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
launched: list[Path] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/full.exe",
|
||||
"sha256": "0" * 64,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(delta_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("should not launch full installer"),
|
||||
launch_delta_update=lambda path, version: launched.append(path),
|
||||
)
|
||||
|
||||
assert result.status == "delta_update_started"
|
||||
assert result.exit_required is True
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert launched == [tmp_path / "DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert result.delta_path == launched[0]
|
||||
|
||||
|
||||
def test_forced_update_picks_matching_delta_from_list(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
file_payload = b"latest bytes"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(delta_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.7",
|
||||
fetch_manifest=lambda url, timeout: {
|
||||
"version": "3.3.9",
|
||||
"url": "https://example.test/full.exe",
|
||||
"sha256": "0" * 64,
|
||||
"delta": [
|
||||
{
|
||||
"from_version": "3.3.8",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
{
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
],
|
||||
},
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("should not launch full installer"),
|
||||
launch_delta_update=lambda path, version: None,
|
||||
)
|
||||
|
||||
assert result.status == "delta_update_started"
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip"]
|
||||
|
||||
|
||||
def test_forced_update_falls_back_to_full_installer_when_delta_download_fails(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
launched: list[list[str]] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
if url.endswith("_delta.zip"):
|
||||
raise OSError("network interrupted")
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: launched.append(cmd),
|
||||
launch_delta_update=lambda path, version: pytest.fail("should not launch broken delta"),
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert downloaded == [
|
||||
"https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
]
|
||||
assert launched
|
||||
assert launched[0][0] == str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe")
|
||||
|
||||
|
||||
def test_forced_update_logs_delta_failure_before_full_fallback(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
logs_dir = tmp_path / "logs"
|
||||
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
if url.endswith("_delta.zip"):
|
||||
raise OSError("network interrupted")
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: None,
|
||||
launch_delta_update=lambda path, version: pytest.fail("should not launch broken delta"),
|
||||
)
|
||||
|
||||
log_path = logs_dir / "updates" / "update-client.log"
|
||||
lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()]
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert any(item["event"] == "delta_download_start" for item in lines)
|
||||
failed = [item for item in lines if item["event"] == "delta_failed_fallback_full"]
|
||||
assert failed
|
||||
assert "network interrupted" in failed[0]["error"]
|
||||
|
||||
|
||||
def test_forced_update_skips_delta_after_previous_started_attempt_still_old_version(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
file_payload = b"new exe"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
launched_installers: list[list[str]] = []
|
||||
launched_deltas: list[Path] = []
|
||||
|
||||
manifest = {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
if url.endswith("_delta.zip"):
|
||||
dest.write_bytes(delta_payload)
|
||||
else:
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
first = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("first attempt should prefer delta"),
|
||||
launch_delta_update=lambda path, version: launched_deltas.append(path),
|
||||
)
|
||||
|
||||
second = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: launched_installers.append(cmd),
|
||||
launch_delta_update=lambda path, version: pytest.fail("second attempt should skip failed delta"),
|
||||
)
|
||||
|
||||
assert first.status == "delta_update_started"
|
||||
assert launched_deltas == [tmp_path / "DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert second.status == "update_started"
|
||||
assert launched_installers
|
||||
|
||||
|
||||
def test_forced_update_accepts_signed_manifest(tmp_path, monkeypatch):
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
private_key = serialization.load_pem_private_key(TEST_PRIVATE_KEY_PEM, password=None)
|
||||
monkeypatch.setattr(force_update, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
|
||||
payload = b"signed installer"
|
||||
expected_sha = hashlib.sha256(payload).hexdigest()
|
||||
manifest = {
|
||||
"enabled": True,
|
||||
"version": "3.3.4",
|
||||
"url": "https://dy.absfan.cn/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": expected_sha,
|
||||
"force": True,
|
||||
}
|
||||
manifest["signature"] = force_update.base64.b64encode(
|
||||
private_key.sign(force_update._canonical_payload_bytes(dict(manifest)))
|
||||
).decode("ascii")
|
||||
launched: list[list[str]] = []
|
||||
|
||||
result = perform_forced_update(
|
||||
UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://dy.absfan.cn/api/v1/update/manifest",
|
||||
download_dir=tmp_path,
|
||||
require_https=False,
|
||||
require_signed_manifest=True,
|
||||
),
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=lambda url, dest, timeout: dest.write_bytes(payload),
|
||||
launch_installer=lambda cmd: launched.append(cmd),
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert launched
|
||||
|
||||
|
||||
def test_forced_update_rejects_bad_signed_manifest(tmp_path, monkeypatch):
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import UpdateError, UpdateSettings, perform_forced_update
|
||||
|
||||
monkeypatch.setattr(force_update, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
|
||||
manifest = {
|
||||
"version": "3.3.4",
|
||||
"url": "https://dy.absfan.cn/api/v1/update/download/app.exe",
|
||||
"sha256": "0" * 64,
|
||||
"signature": "bad",
|
||||
}
|
||||
|
||||
with pytest.raises(UpdateError, match="签名"):
|
||||
perform_forced_update(
|
||||
UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://dy.absfan.cn/api/v1/update/manifest",
|
||||
download_dir=tmp_path,
|
||||
require_https=False,
|
||||
require_signed_manifest=True,
|
||||
),
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=lambda url, dest, timeout: None,
|
||||
launch_installer=lambda cmd: None,
|
||||
)
|
||||
|
||||
|
||||
def test_launch_installer_on_windows_waits_for_parent_before_setup(monkeypatch, tmp_path):
|
||||
from douyin.updater import force_update
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_fresh_install_smoke_script_covers_new_machine_contract():
|
||||
script = Path("tools/ci/fresh_install_smoke.ps1").read_text(encoding="utf-8")
|
||||
|
||||
assert "tools.distribution_manifest" in script
|
||||
assert "tools.exe_packing" in script
|
||||
assert "Start-Process -FilePath $Installer" in script
|
||||
assert "config\\config.json" in script
|
||||
assert "platform-tools\\adb.exe" in script
|
||||
assert "android-tools\\ADBKeyboard.apk" in script
|
||||
assert "adb.exe\") `\n -Arguments @(\"version\")" in script
|
||||
assert "run_cli.exe\") `\n -Arguments @(\"--help\")" in script
|
||||
assert "cli_fails_closed_without_license" in script
|
||||
assert "web_gui.exe" in script
|
||||
assert "license-form" in script
|
||||
assert "license-input" in script
|
||||
assert "/api/license" in script
|
||||
assert "/api/start-run" in script
|
||||
assert "license_required" in script
|
||||
assert "DouyinGuajiGUI.exe" in script
|
||||
assert "fresh_install_report.json" in script
|
||||
assert "DOUYIN_DISABLE_AUTO_UPDATE" in script
|
||||
assert "Assert-UnderDirectory $WorkRoot $ArtifactsRoot" in script
|
||||
|
||||
|
||||
def test_windows_package_ci_builds_installer_then_runs_fresh_install_smoke():
|
||||
workflow = Path(".github/workflows/windows-package-ci.yml").read_text(encoding="utf-8")
|
||||
|
||||
assert "runs-on: windows-latest" in workflow
|
||||
assert "choco install innosetup" in workflow
|
||||
assert "packaging\\pyinstaller\\build_windows.ps1 -SkipInstall -ReuseCache" in workflow
|
||||
assert "packaging\\inno\\douyin_guaji.iss" in workflow
|
||||
assert "tools\\ci\\fresh_install_smoke.ps1" in workflow
|
||||
assert "actions/upload-artifact@v4" in workflow
|
||||
@@ -289,6 +289,25 @@ class TestFudaiDetectionDefaults:
|
||||
assert analyser.reservation_direct_attend_max_failures == 3
|
||||
assert analyser.reservation_direct_attend_open_max_wait_seconds == 2.25
|
||||
|
||||
def test_config_loader_loads_reservation_prejoin_fansclub_delays(self):
|
||||
from douyin.utils.douyin_config import ConfigManager
|
||||
|
||||
analyser = SimpleNamespace()
|
||||
config = {
|
||||
"reservation_prejoin_fansclub_participate_wait_seconds": 0.25,
|
||||
"reservation_prejoin_fansclub_confirm_wait_seconds": 0.35,
|
||||
}
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
|
||||
json.dump(config, f)
|
||||
tmp_path = f.name
|
||||
try:
|
||||
ConfigManager.load_config_from_file(analyser, tmp_path)
|
||||
finally:
|
||||
os.unlink(tmp_path)
|
||||
|
||||
assert analyser.reservation_prejoin_fansclub_participate_wait_seconds == 0.25
|
||||
assert analyser.reservation_prejoin_fansclub_confirm_wait_seconds == 0.35
|
||||
|
||||
|
||||
class TestCoreModules:
|
||||
"""core 子模块存在性测试。"""
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from douyin.fudai.douyin_fudai_contain_impl import (
|
||||
_apply_countdown_text_fallback,
|
||||
_build_countdown_candidate_boxes,
|
||||
_parse_mmss_from_full_text,
|
||||
_select_countdown_from_candidates,
|
||||
@@ -97,6 +99,14 @@ def test_parse_countdown_sliding_window_filters_noise_digits():
|
||||
assert time_text == "01:53"
|
||||
|
||||
|
||||
def test_parse_countdown_treats_ocr_uo_noise_as_zero_for_minute():
|
||||
analyser = _mk_analyser()
|
||||
|
||||
time_text = parse_countdown_time_text(analyser, "UU", "41")
|
||||
|
||||
assert time_text == "00:41"
|
||||
|
||||
|
||||
def test_select_countdown_uses_sliding_window_for_candidate_validity():
|
||||
analyser = _mk_analyser()
|
||||
candidate_meta = [
|
||||
@@ -186,3 +196,37 @@ def test_parse_mmss_from_full_text_ignores_non_countdown_text():
|
||||
mm, ss = _parse_mmss_from_full_text("直播间,否则会失去抽奖机会")
|
||||
assert mm == ""
|
||||
assert ss == ""
|
||||
|
||||
|
||||
def test_parse_mmss_from_full_text_ignores_product_model_digits_without_countdown_hint():
|
||||
mm, ss = _parse_mmss_from_full_text("G4939-敦煌飞天帝王黄茶叶罐")
|
||||
assert mm == ""
|
||||
assert ss == ""
|
||||
|
||||
|
||||
def test_countdown_text_fallback_ignores_content_product_digits_without_countdown_hint():
|
||||
analyser = SimpleNamespace(fudai_detail_verbose_logs=False)
|
||||
|
||||
mm, ss = _apply_countdown_text_fallback(
|
||||
analyser,
|
||||
"",
|
||||
"",
|
||||
(("content", "G4939-敦煌飞天帝王黄茶叶罐"),),
|
||||
)
|
||||
|
||||
assert mm == ""
|
||||
assert ss == ""
|
||||
|
||||
|
||||
def test_countdown_text_fallback_does_not_use_content_even_with_countdown_text():
|
||||
analyser = SimpleNamespace(fudai_detail_verbose_logs=False)
|
||||
|
||||
mm, ss = _apply_countdown_text_fallback(
|
||||
analyser,
|
||||
"",
|
||||
"",
|
||||
(("content", "免费购129人已参与00 : 00后开奖"),),
|
||||
)
|
||||
|
||||
assert mm == ""
|
||||
assert ss == ""
|
||||
+25
-38
@@ -2,8 +2,8 @@
|
||||
|
||||
覆盖:
|
||||
- _select_countdown_box 4 种 renwu 值返回正确常量
|
||||
- cut_detail_regions 调用 cut_pic 4 次(内容 + 分钟 + 秒 + 价值)
|
||||
- 倒计时分割坐标(分钟 0~26%,秒 38%~64%)正确
|
||||
- cut_detail_regions 调用 cut_pic 3 次(内容 + 整行倒计时 + 价值)
|
||||
- 倒计时不再分割小框,避免裁偏误识别
|
||||
- save_debug_images 开关效果
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -60,11 +60,11 @@ class TestCutDetailRegions:
|
||||
result = cut_detail_regions(a, renwu=2)
|
||||
assert result == COUNTDOWN_1110_1230
|
||||
|
||||
def test_calls_cut_pic_4_times(self):
|
||||
"""内容 + 分钟 + 秒 + 价值 = 4 次 cut_pic 调用。"""
|
||||
def test_calls_cut_pic_3_times(self):
|
||||
"""内容 + 整行倒计时 + 价值 = 3 次 cut_pic 调用。"""
|
||||
a = _mk_analyser()
|
||||
cut_detail_regions(a, renwu=2)
|
||||
assert a.cut_pic.call_count == 4
|
||||
assert a.cut_pic.call_count == 3
|
||||
|
||||
def test_cut_names_in_order(self):
|
||||
a = _mk_analyser()
|
||||
@@ -72,55 +72,38 @@ class TestCutDetailRegions:
|
||||
# 第 1 个 positional arg 是坐标,第 6 个是 name
|
||||
# 调用签名:cut_pic(x1, y1, x2, y2, target, name, y_pianyi)
|
||||
names = [c.args[5] for c in a.cut_pic.call_args_list]
|
||||
assert names == ["福袋内容", "福袋倒计时_分钟", "福袋倒计时_秒", "福袋价值"]
|
||||
assert names == ["福袋内容", "福袋倒计时_整行", "福袋价值"]
|
||||
|
||||
def test_countdown_split_ratio(self):
|
||||
"""倒计时 box 应按分钟 0~26%,秒 38%~64% 切分。"""
|
||||
def test_countdown_uses_full_line_region(self):
|
||||
"""倒计时只切整行,不再分割分钟/秒小框。"""
|
||||
a = _mk_analyser()
|
||||
from douyin.fudai.core.coords import COUNTDOWN_1110_1230
|
||||
x1, y1, x2, y2 = COUNTDOWN_1110_1230
|
||||
w = x2 - x1
|
||||
mm_x2 = x1 + int(w * 0.26)
|
||||
ss_x1 = x1 + int(w * 0.38)
|
||||
ss_x2 = x1 + int(w * 0.64)
|
||||
|
||||
cut_detail_regions(a, renwu=2)
|
||||
|
||||
# 倒计时分钟 = 第 2 次 cut_pic 调用
|
||||
mm_call = a.cut_pic.call_args_list[1]
|
||||
assert mm_call.args[0] == x1
|
||||
assert mm_call.args[2] == mm_x2
|
||||
countdown_call = a.cut_pic.call_args_list[1]
|
||||
assert countdown_call.args[:4] == COUNTDOWN_1110_1230
|
||||
assert countdown_call.args[5] == "福袋倒计时_整行"
|
||||
|
||||
# 倒计时秒 = 第 3 次调用
|
||||
ss_call = a.cut_pic.call_args_list[2]
|
||||
assert ss_call.args[0] == ss_x1
|
||||
assert ss_call.args[2] == ss_x2
|
||||
|
||||
def test_profile_countdown_vertical_crop_is_narrower_and_higher(self):
|
||||
def test_profile_countdown_uses_full_line_for_v2_chip(self):
|
||||
a = _mk_analyser()
|
||||
profile = {"countdown_full": (760, 1328, 1038, 1398)}
|
||||
|
||||
cut_detail_regions(a, renwu=2, profile=profile)
|
||||
|
||||
mm_call = a.cut_pic.call_args_list[1]
|
||||
ss_call = a.cut_pic.call_args_list[2]
|
||||
assert mm_call.args[1] == 1351
|
||||
assert mm_call.args[3] == 1392
|
||||
assert ss_call.args[1] == 1351
|
||||
assert ss_call.args[3] == 1392
|
||||
countdown_call = a.cut_pic.call_args_list[1]
|
||||
assert countdown_call.args[:4] == (760, 1328, 1038, 1398)
|
||||
assert countdown_call.args[5] == "福袋倒计时_整行"
|
||||
|
||||
def test_v2_two_task_tall_profile_uses_lower_digit_band(self):
|
||||
def test_v2_two_task_tall_profile_uses_full_line(self):
|
||||
a = _mk_analyser()
|
||||
profile = {"countdown_full": (760, 1265, 1040, 1398)}
|
||||
|
||||
cut_detail_regions(a, renwu=2, profile=profile)
|
||||
|
||||
mm_call = a.cut_pic.call_args_list[1]
|
||||
ss_call = a.cut_pic.call_args_list[2]
|
||||
assert mm_call.args[1] >= 1310
|
||||
assert mm_call.args[3] >= 1385
|
||||
assert ss_call.args[1] == mm_call.args[1]
|
||||
assert ss_call.args[3] == mm_call.args[3]
|
||||
countdown_call = a.cut_pic.call_args_list[1]
|
||||
assert countdown_call.args[:4] == (760, 1265, 1040, 1398)
|
||||
assert countdown_call.args[5] == "福袋倒计时_整行"
|
||||
|
||||
def test_save_debug_images_disabled_default(self):
|
||||
a = _mk_analyser()
|
||||
@@ -147,9 +130,13 @@ class TestCutDetailRegions:
|
||||
|
||||
def test_one_task_profile_countdown_box_uses_new_coords(self):
|
||||
a = _mk_analyser()
|
||||
profile = {"countdown_full": (730, 1338, 1038, 1418)}
|
||||
profile = {"countdown_full": (700, 1390, 990, 1470)}
|
||||
result = cut_detail_regions(a, renwu=1, profile=profile)
|
||||
assert result == (730, 1338, 1038, 1418)
|
||||
assert result == (700, 1390, 990, 1470)
|
||||
|
||||
countdown_call = a.cut_pic.call_args_list[1]
|
||||
assert countdown_call.args[:4] == (700, 1390, 990, 1470)
|
||||
assert countdown_call.args[5] == "福袋倒计时_整行"
|
||||
|
||||
def test_renwu_3_uses_correct_box(self):
|
||||
a = _mk_analyser()
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _write(path: Path, text: str = "x = 1\n") -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
def _make_minimal_project(root: Path) -> None:
|
||||
_write(root / "douyin" / "__init__.py")
|
||||
_write(root / "douyin" / "fudai" / "__init__.py")
|
||||
_write(root / "douyin" / "fudai" / "logic.py", "def answer():\n return 42\n")
|
||||
_write(root / "douyin" / "core" / "__init__.py")
|
||||
_write(root / "douyin" / "core" / "support.py", "def support():\n return 'plain support'\n")
|
||||
_write(root / "operations" / "__init__.py")
|
||||
_write(root / "operations" / "ocr_operations.py", "def read():\n return 'ok'\n")
|
||||
_write(root / "gui" / "gui_dashboard_app_entry.py")
|
||||
_write(root / "gui" / "web_gui_entry.py")
|
||||
_write(root / "bin" / "run_cli.py")
|
||||
_write(root / "bin" / "run_cli_entry.py")
|
||||
_write(root / "tools" / "license_dev.py", "PRIVATE_KEY = 'must-not-ship'\n")
|
||||
|
||||
|
||||
def test_create_cython_staging_compiles_core_modules(tmp_path, monkeypatch):
|
||||
from tools import cython_staging
|
||||
|
||||
root = tmp_path / "project"
|
||||
staging = tmp_path / "stage"
|
||||
_make_minimal_project(root)
|
||||
calls: list[list[str]] = []
|
||||
|
||||
def fake_runner(cmd, *, cwd, check, env=None):
|
||||
calls.append([str(x) for x in cmd])
|
||||
assert cwd == staging
|
||||
assert check is True
|
||||
assert env is not None
|
||||
_write(staging / "douyin" / "fudai" / "logic.cp312-win_amd64.pyd", "binary")
|
||||
return subprocess.CompletedProcess(cmd, 0)
|
||||
|
||||
result = cython_staging.create_cython_staging(root, staging, runner=fake_runner)
|
||||
|
||||
assert result.staging_root == staging
|
||||
assert result.compiled_count == 1
|
||||
assert calls[0][1] == "_cython_build_setup.py"
|
||||
assert "build_ext" in calls[0]
|
||||
assert not (staging / "douyin" / "fudai" / "logic.py").exists()
|
||||
assert (staging / "douyin" / "core" / "support.py").exists()
|
||||
assert (staging / "operations" / "ocr_operations.py").exists()
|
||||
assert (staging / "douyin" / "__init__.py").exists()
|
||||
assert (staging / "gui" / "gui_dashboard_app_entry.py").exists()
|
||||
assert not (staging / "tools" / "license_dev.py").exists()
|
||||
|
||||
|
||||
def test_validate_cython_staging_rejects_plain_compiled_source(tmp_path):
|
||||
from tools.cython_staging import validate_cython_staging
|
||||
|
||||
staging = tmp_path / "stage"
|
||||
_write(staging / "douyin" / "__init__.py")
|
||||
_write(staging / "douyin" / "fudai" / "__init__.py")
|
||||
_write(staging / "douyin" / "fudai" / "logic.py", "def leaked():\n return 'plain'\n")
|
||||
_write(staging / "douyin" / "fudai" / "logic.cp312-win_amd64.pyd", "binary")
|
||||
_write(staging / "operations" / "__init__.py")
|
||||
_write(staging / "gui" / "gui_dashboard_app_entry.py")
|
||||
_write(staging / "bin" / "run_cli.py")
|
||||
_write(staging / "bin" / "run_cli_entry.py")
|
||||
|
||||
with pytest.raises(RuntimeError, match="plain compiled runtime source"):
|
||||
validate_cython_staging(staging)
|
||||
|
||||
|
||||
def test_validate_cython_staging_rejects_forbidden_entries(tmp_path):
|
||||
from tools.cython_staging import validate_cython_staging
|
||||
|
||||
staging = tmp_path / "stage"
|
||||
_write(staging / "douyin" / "__init__.py")
|
||||
_write(staging / "douyin" / "fudai" / "__init__.py")
|
||||
_write(staging / "douyin" / "fudai" / "logic.cp312-win_amd64.pyd", "binary")
|
||||
_write(staging / "operations" / "__init__.py")
|
||||
_write(staging / "gui" / "gui_dashboard_app_entry.py")
|
||||
_write(staging / "bin" / "run_cli.py")
|
||||
_write(staging / "bin" / "run_cli_entry.py")
|
||||
_write(staging / "tools" / "license_dev.py", "PRIVATE_KEY = 'leak'\n")
|
||||
|
||||
with pytest.raises(RuntimeError, match="forbidden"):
|
||||
validate_cython_staging(staging)
|
||||
|
||||
|
||||
def test_windows_packaging_script_uses_cython_by_default():
|
||||
script = Path("packaging/pyinstaller/build_windows.ps1").read_text(encoding="utf-8")
|
||||
|
||||
assert "[switch]$NoCythonForDevOnly" in script
|
||||
assert "[switch]$UsePyArmor" in script
|
||||
assert "tools.cython_staging" in script
|
||||
assert "build\\cythonized-src" in script
|
||||
assert "Cython core compile failed" in script
|
||||
assert "Development plaintext build requested" in script
|
||||
@@ -80,7 +80,7 @@ def test_find_open_retries_same_room_after_wrong_target(tmp_path):
|
||||
assert find_and_open_fudai_detail(analyser) is True
|
||||
|
||||
assert analyser.operation.click.call_count == 2
|
||||
analyser.operation.click_back.assert_called_once_with("MOCK")
|
||||
analyser.operation.click_back.assert_not_called()
|
||||
verdicts = [
|
||||
kwargs.get("verdict")
|
||||
for args, kwargs in analyser._log_kv.call_args_list
|
||||
@@ -88,3 +88,5 @@ def test_find_open_retries_same_room_after_wrong_target(tmp_path):
|
||||
]
|
||||
assert "wrong_target_retry_same_room" in verdicts
|
||||
assert "detail_recognized" in verdicts
|
||||
flow_msgs = [args[1] for args, _kwargs in analyser._log_kv.call_args_list if args and args[0] == "流程"]
|
||||
assert "find_and_open_fudai_detail:误入口仍处于直播间,不执行关闭点击或返回键" in flow_msgs
|
||||
@@ -240,11 +240,49 @@ class TestPixelButtons:
|
||||
params = list(sig.parameters.keys())
|
||||
assert "pic_rgb" in params or len(params) >= 1
|
||||
|
||||
def test_detect_attend_button_accepts_rgba_image(self):
|
||||
from PIL import Image
|
||||
|
||||
from douyin.detection.pixel.buttons import detect_attend_button_red_area
|
||||
|
||||
img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255))
|
||||
for x in range(200, 880):
|
||||
for y in range(2000, 2120):
|
||||
img.putpixel((x, y), (255, 80, 120, 255))
|
||||
|
||||
detected, info = detect_attend_button_red_area(
|
||||
img,
|
||||
return_info=True,
|
||||
red_ratio_threshold=0.25,
|
||||
)
|
||||
|
||||
assert detected is True
|
||||
assert info["red_ratio"] >= 0.25
|
||||
|
||||
def test_detect_fansclub_join_exists(self):
|
||||
from douyin.detection.pixel.buttons import detect_fansclub_join_red_area
|
||||
|
||||
assert callable(detect_fansclub_join_red_area)
|
||||
|
||||
def test_detect_fansclub_join_accepts_rgba_image(self):
|
||||
from PIL import Image
|
||||
|
||||
from douyin.detection.pixel.buttons import detect_fansclub_join_red_area
|
||||
|
||||
img = Image.new("RGBA", (1080, 2400), (0, 0, 0, 255))
|
||||
for x in range(200, 880):
|
||||
for y in range(1940, 2140):
|
||||
img.putpixel((x, y), (255, 80, 120, 255))
|
||||
|
||||
detected, info = detect_fansclub_join_red_area(
|
||||
img,
|
||||
return_info=True,
|
||||
red_ratio_threshold=0.25,
|
||||
)
|
||||
|
||||
assert detected is True
|
||||
assert info["red_ratio"] >= 0.25
|
||||
|
||||
|
||||
class TestPixelStage:
|
||||
"""pixel/stage 模块测试。"""
|
||||
|
||||
@@ -11,18 +11,19 @@ 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",
|
||||
"config/config.json",
|
||||
"config/private.tmp",
|
||||
"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",
|
||||
"_internal/douyin/core/douyin_fudai.py",
|
||||
"_internal/douyin/fudai/douyin_fudai_core.cp312-win_amd64.pyd",
|
||||
"_internal/cv2/__init__.py",
|
||||
]
|
||||
|
||||
@@ -30,20 +31,57 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
|
||||
|
||||
assert "douyin/core/douyin_fudai.py" in blocked
|
||||
assert "artifacts/debug.png" in blocked
|
||||
assert "config/config.json" in blocked
|
||||
assert "config/config.json" not in blocked
|
||||
assert "config/private.tmp" in blocked
|
||||
assert "logs/unified.log" in blocked
|
||||
assert "pic/debug_captures/a.png" in blocked
|
||||
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
|
||||
assert "_internal/douyin/core/douyin_fudai.py" in blocked
|
||||
assert "_internal/douyin/fudai/douyin_fudai_core.cp312-win_amd64.pyd" not in blocked
|
||||
assert "_internal/cv2/__init__.py" not in blocked
|
||||
|
||||
|
||||
def test_distribution_manifest_blocks_project_native_binaries_outside_core_allowlist():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"_internal/tests/evil.pyd",
|
||||
"_internal/tools/helper.dll",
|
||||
"_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",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
]
|
||||
|
||||
issues = find_distribution_issues(entries)
|
||||
|
||||
assert "_internal/tests/evil.pyd" in issues
|
||||
assert "_internal/tools/helper.dll" in issues
|
||||
assert "_internal/douyin/fudai/core/compiled.cp312-win_amd64.pyd" not in issues
|
||||
assert "_internal/numpy/core/runtime.pyd" not in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
@@ -53,13 +91,24 @@ def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"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",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -68,6 +117,40 @@ 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_allows_explicit_hisuite_driver_bundle_only():
|
||||
from tools.distribution_manifest import find_forbidden_distribution_entries
|
||||
|
||||
entries = [
|
||||
"drivers/HiSuite/HiSuite_Installer.exe",
|
||||
"drivers/HiSuite/README.txt",
|
||||
"drivers/HiSuite/debug.log",
|
||||
"drivers/OtherDriver/setup.exe",
|
||||
]
|
||||
|
||||
blocked = find_forbidden_distribution_entries(entries)
|
||||
|
||||
assert "drivers/HiSuite/HiSuite_Installer.exe" not in blocked
|
||||
assert "drivers/HiSuite/README.txt" not in blocked
|
||||
assert "drivers/HiSuite/debug.log" in blocked
|
||||
assert "drivers/OtherDriver/setup.exe" in blocked
|
||||
|
||||
|
||||
def test_distribution_manifest_can_allow_license_for_local_test_package():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
@@ -77,9 +160,16 @@ def test_distribution_manifest_can_allow_license_for_local_test_package():
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"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",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -100,7 +190,12 @@ 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",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -111,6 +206,60 @@ 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",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"webui/index.html",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"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_requires_bundled_ocr_runtime_data():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
]
|
||||
|
||||
issues = find_distribution_issues(entries)
|
||||
|
||||
assert "_internal/paddlex/.version" in issues
|
||||
assert "_internal/paddle/*" in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
dist = tmp_path / "dist"
|
||||
for rel in [
|
||||
@@ -119,12 +268,19 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"assets/fudai_task_status_dacheng_shape.png",
|
||||
"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",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""douyin/fudai/core/fudai_attend_pkg/fansclub_handler 单元测试。
|
||||
|
||||
主要验证:
|
||||
- handle_fansclub_branch 总是返回 True
|
||||
- handle_fansclub_branch 会处理粉丝团门槛并返回是否已经参与
|
||||
- 设置 analyser.last_attend_fail_reason = "fansclub_required"
|
||||
- 在路径上点击参与按钮 (543, 2070)
|
||||
- 在路径上点击关闭详情 (500, 470)
|
||||
- 普通粉丝团加入后不伪造参与成功;若仍在详情页,保留详情重新读详情/阈值
|
||||
- 异常路径不抛
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -15,10 +15,11 @@ import pytest
|
||||
|
||||
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
|
||||
handle_fansclub_branch,
|
||||
handle_reservation_prejoin_fansclub,
|
||||
)
|
||||
|
||||
|
||||
def _mk_analyser(*, auto_join_fansclub: bool = False):
|
||||
def _mk_analyser(*, auto_join_fansclub: bool = False, diag_stage: str = "FUDai_DETAIL"):
|
||||
"""构造一个 attend 流程能跑通的 mock analyser。"""
|
||||
a = MagicMock()
|
||||
a.last_attend_fail_reason = ""
|
||||
@@ -44,15 +45,19 @@ def _mk_analyser(*, auto_join_fansclub: bool = False):
|
||||
a.cut_pic = MagicMock(return_value=True)
|
||||
a.click = MagicMock(return_value=None)
|
||||
a._log_kv = MagicMock(return_value=None)
|
||||
a._shot_and_diagnose = MagicMock(return_value=None)
|
||||
def _diag(*_args, **_kwargs):
|
||||
a._last_diag_stage = diag_stage
|
||||
a._last_diag_seen = "mock_detail"
|
||||
|
||||
a._shot_and_diagnose = MagicMock(side_effect=_diag)
|
||||
return a
|
||||
|
||||
|
||||
class TestHandleFansclubBranch:
|
||||
def test_returns_true(self):
|
||||
def test_returns_false_after_closing_detail_for_normal_flow(self):
|
||||
a = _mk_analyser()
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
assert result is True
|
||||
assert result is False
|
||||
|
||||
def test_sets_fail_reason(self):
|
||||
a = _mk_analyser()
|
||||
@@ -69,27 +74,48 @@ class TestHandleFansclubBranch:
|
||||
]
|
||||
assert len(attend_calls) >= 1
|
||||
|
||||
def test_closes_detail_at_500_470(self):
|
||||
"""第三步必须点 (500, 470) 关闭详情。"""
|
||||
def test_keeps_detail_after_recovery_confirms_still_on_detail(self):
|
||||
"""普通粉丝团路径不算参与成功;若仍在详情页,留给下一轮重新读详情/阈值。"""
|
||||
a = _mk_analyser()
|
||||
handle_fansclub_branch(a, "加入粉丝团")
|
||||
close_calls = [
|
||||
c for c in a.click.call_args_list if c.args == (500, 470)
|
||||
]
|
||||
assert len(close_calls) >= 1
|
||||
assert close_calls == []
|
||||
assert a._fansclub_joined_detail_recheck_pending is True
|
||||
|
||||
def test_does_not_mark_success_when_recovery_sees_detail_page(self):
|
||||
a = _mk_analyser()
|
||||
|
||||
handle_fansclub_branch(a, "加入粉丝团")
|
||||
|
||||
assert "_last_successful_attend_ts" not in a.__dict__
|
||||
|
||||
def test_returns_false_without_close_when_recovery_is_already_live_room(self):
|
||||
a = _mk_analyser(diag_stage="IN_LIVE_ROOM")
|
||||
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
|
||||
assert result is False
|
||||
assert a._fansclub_joined_detail_recheck_pending is True
|
||||
assert a._skip_stage_diagnosis_and_find_fudai is True
|
||||
close_calls = [
|
||||
c for c in a.click.call_args_list if c.args == (500, 470)
|
||||
]
|
||||
assert close_calls == []
|
||||
|
||||
def test_handles_粉丝团_text_only(self):
|
||||
"""attend_button_text 含 "粉丝团" 但不含 "加入" 也走该分支。"""
|
||||
a = _mk_analyser()
|
||||
result = handle_fansclub_branch(a, "粉丝团门槛")
|
||||
assert result is True
|
||||
assert result is False
|
||||
|
||||
def test_does_not_raise_when_screenshot_missing(self):
|
||||
"""path_config.get_screenshot_path 不存在时不应抛。"""
|
||||
a = _mk_analyser()
|
||||
with patch("os.path.exists", return_value=False):
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
assert result is True
|
||||
assert result is False
|
||||
|
||||
def test_does_not_raise_when_ocr_throws(self):
|
||||
"""OCR 全部抛异常时仍正常返回 True(不传播)。"""
|
||||
@@ -98,13 +124,13 @@ class TestHandleFansclubBranch:
|
||||
a.operation.ocr.ocr = MagicMock(side_effect=RuntimeError("ocr fail"))
|
||||
a.operation.ocr.readtext = MagicMock(side_effect=RuntimeError("ocr fail"))
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
assert result is True
|
||||
assert result is False
|
||||
|
||||
def test_auto_join_disabled_does_not_wait_long(self):
|
||||
"""未启用自动加入时也走完整流程,返回 True。"""
|
||||
a = _mk_analyser(auto_join_fansclub=False)
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
assert result is True
|
||||
assert result is False
|
||||
# auto_join 关闭时应当走"等待手动确认"日志
|
||||
log_msgs = [str(c) for c in a._log_kv.call_args_list]
|
||||
assert any("未启用自动加粉丝团" in m for m in log_msgs)
|
||||
@@ -112,4 +138,50 @@ class TestHandleFansclubBranch:
|
||||
def test_auto_join_enabled(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
result = handle_fansclub_branch(a, "加入粉丝团")
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestReservationPrejoinFansclub:
|
||||
def test_fast_prejoin_uses_fixed_clicks_without_ocr_or_recovery(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
|
||||
result = handle_reservation_prejoin_fansclub(a, "加入直播粉丝团并关注主播")
|
||||
|
||||
assert result is True
|
||||
assert a.last_attend_fail_reason == "fansclub_required"
|
||||
assert any(c.args == (543, 2070) for c in a.click.call_args_list)
|
||||
assert any(c.args == (500, 470) for c in a.click.call_args_list)
|
||||
assert any(c.args == ("MOCK", 550, 2050) for c in a.operation.click.call_args_list)
|
||||
a.cut_pic.assert_not_called()
|
||||
a.operation.analyse_pic_word.assert_not_called()
|
||||
a._shot_and_diagnose.assert_not_called()
|
||||
log_msgs = [str(c) for c in a._log_kv.call_args_list]
|
||||
assert any("快速预处理" in m for m in log_msgs)
|
||||
|
||||
def test_fast_prejoin_clamps_too_short_configured_delays(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
a.reservation_prejoin_fansclub_participate_wait_seconds = 0.2
|
||||
a.reservation_prejoin_fansclub_confirm_wait_seconds = 0.3
|
||||
|
||||
handle_reservation_prejoin_fansclub(a, "加入购物粉丝团并关注主播")
|
||||
|
||||
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
|
||||
assert delay_args == [0.8, 1.2]
|
||||
|
||||
def test_fast_prejoin_keeps_safe_configured_delays(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
a.reservation_prejoin_fansclub_participate_wait_seconds = 0.9
|
||||
a.reservation_prejoin_fansclub_confirm_wait_seconds = 1.3
|
||||
|
||||
handle_reservation_prejoin_fansclub(a, "加入购物粉丝团并关注主播")
|
||||
|
||||
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
|
||||
assert delay_args == [0.9, 1.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]
|
||||
@@ -57,6 +57,32 @@ def test_attend_choujiang_treat_notice_text_as_attended() -> None:
|
||||
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
|
||||
def test_attend_choujiang_blocks_insufficient_time_text_even_if_status_actionable() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "可以参与"
|
||||
analyser._fudai_button_text = "抽奖剩余时间不足,下次再来参与吧"
|
||||
analyser._fudai_button_ocr_time = 25_000.0
|
||||
analyser._fudai_button_room_pos = 0
|
||||
analyser.room_pos = 0
|
||||
analyser.click = MagicMock()
|
||||
analyser._log_kv = MagicMock()
|
||||
analyser.operation = MagicMock()
|
||||
analyser.operation.delay = MagicMock()
|
||||
|
||||
import time as _time
|
||||
|
||||
old_time = _time.time
|
||||
_time.time = lambda: 25_001.0
|
||||
try:
|
||||
ok = attend_choujiang(analyser)
|
||||
finally:
|
||||
_time.time = old_time
|
||||
|
||||
assert ok is False
|
||||
assert analyser.last_attend_fail_reason == "button_not_actionable"
|
||||
analyser.click.assert_called_once_with(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
|
||||
def test_attend_choujiang_does_not_reuse_fresh_button_cache_from_other_room() -> None:
|
||||
analyser = MagicMock()
|
||||
analyser._fudai_button_status = "可以参与"
|
||||
|
||||
@@ -12,6 +12,10 @@ def test_decide_button_status_attended_for_notice_text() -> None:
|
||||
assert decide_button_status("直播间,否则会失去抽奖机会") == "已参与"
|
||||
|
||||
|
||||
def test_decide_button_status_blocks_insufficient_time_text() -> None:
|
||||
assert decide_button_status("抽奖剩余时间不足,下次再来参与吧") == "不可参与"
|
||||
|
||||
|
||||
def test_apply_button_ocr_result_records_room_pos_when_enabled() -> None:
|
||||
log_calls = []
|
||||
analyser = SimpleNamespace(room_pos=12)
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user