49 Commits
Author SHA1 Message Date
Your Name 63c726ddea build: include android runtime helpers 2026-06-27 19:33:27 +08:00
Your Name f257c4e3fc build: bundle adb platform tools 2026-06-27 17:59:36 +08:00
Your Name ecbd07cea0 style: tune dashboard typography 2026-06-27 17:59:19 +08:00
Your Name 5aeeef4aee style: polish dashboard wifi adb ui 2026-06-27 13:00:03 +08:00
Your Name 9a75b9b481 docs: audit server and anti-reverse security 2026-06-26 21:50:34 +08:00
Your Name 872d114a0f chore(release): bump version to V3.3.4 2026-06-26 21:11:36 +08:00
Your Name a7d6bc87b6 style: polish dashboard app UI 2026-06-25 08:49:52 +08:00
Your Name cf2b71f831 fix: harden redeem link flow 2026-06-24 22:03:04 +08:00
Your Name 3ab15e69f9 feat: add redeem links for external sales 2026-06-24 18:49:21 +08:00
Your Name 8e8a14cf69 build: allow reusing pyinstaller cache 2026-06-24 03:47:38 +08:00
Your Name 164f76658c fix reservation fansclub prejoin timing 2026-06-24 02:20:20 +08:00
Your Name ffebc8d0dc add direct attend button ocr fallback 2026-06-24 00:56:36 +08:00
Your Name 61d3ad5d83 fix pixel button detection for rgba screenshots 2026-06-24 00:47:55 +08:00
Your Name df46d723c3 avoid back exit during reservation direct attend 2026-06-24 00:17:45 +08:00
Your Name e41796d43a keep reservation after coupon popup during direct attend 2026-06-24 00:10:20 +08:00
Your Name 2b12ddbec3 fix reservation action log tag 2026-06-23 23:54:03 +08:00
Your Name d0166d27d3 security: harden license server and packaging checks 2026-06-23 23:47:19 +08:00
Your Name 9062ee7204 fix fudai countdown full-line ocr 2026-06-23 23:32:20 +08:00
Your Name 008d7f82b3 build: package dashboard with cythonized core 2026-06-23 23:30:29 +08:00
Your Name 4dea1328ec fix one-task countdown config crop 2026-06-23 22:49:30 +08:00
Your Name dc34b7484b fix one-task countdown box root cause 2026-06-23 22:18:54 +08:00
Your Name ed0aca5f28 fix fansclub recheck and countdown fallback 2026-06-23 22:00:31 +08:00
Your Name 33c6f7a54f fix normal fansclub recovery flow 2026-06-23 20:28:41 +08:00
Your Name 91a3aa5abf fix fansclub join wait protection 2026-06-23 20:10:13 +08:00
Your Name a2a899bb9f fix countdown frame fallback 2026-06-23 19:54:40 +08:00
Your Name 3ace80dcca add countdown OCR voting fallback 2026-06-23 19:18:12 +08:00
Your Name ab664e4da8 fix countdown digit extraction regression 2026-06-23 19:05:07 +08:00
Your Name 7086ab1d6e fix: stabilize fudai countdown OCR crops 2026-06-23 15:11:29 +08:00
Your Name 5ebca337eb fix: require obfuscation for release packaging 2026-06-23 15:11:29 +08:00
Your Name 7890320ff7 docs: explain adb and navigation setup 2026-06-23 14:34:37 +08:00
Your Name 18908aeff7 docs: require mobile navigation bar in exe guide 2026-06-23 14:14:50 +08:00
Your Name bd762f6be6 docs: write dashboard exe readme 2026-06-23 13:52:51 +08:00
Your Name 1bef130e51 docs: simplify readme usage guide 2026-06-23 13:47:53 +08:00
Your Name 5d3d58a2f9 fix: retry reservation direct attend icon scan 2026-06-23 12:07:36 +08:00
Your Name 25df550304 fix: prioritize reservation conflicts by value 2026-06-23 11:46:02 +08:00
Your Name 4af2adc4d6 fix: preserve fudai detail countdown detection 2026-06-23 11:22:23 +08:00
Your Name 77413fa7d1 docs: add full security review 2026-06-23 11:15:57 +08:00
Your Name aeeabd8ba2 security: use domain for license endpoints 2026-06-23 10:57:35 +08:00
Your Name 25876bd25a update server defaults and package assets 2026-06-23 10:48:02 +08:00
Your Name a449b7634c fix: speed up fansclub reservation prejoin 2026-06-23 10:43:17 +08:00
Your Name 0efdc83d0b chore: migrate license server defaults 2026-06-23 10:11:45 +08:00
Your Name 920c51d460 fix: broaden fansclub reservation prejoin match 2026-06-23 10:00:56 +08:00
Your Name ba9ac4cb0e fix: prejoin fansclub before reservation 2026-06-23 09:57:06 +08:00
Your Name f95832579a fix: avoid live-room back on fudai retry 2026-06-23 03:09:14 +08:00
Your Name 5c7d341d9b feat: add server managed auto updates 2026-06-23 03:06:55 +08:00
Your Name ba2e159cad use text inputs for dashboard numeric fields 2026-06-23 03:00:06 +08:00
Your Name fe53debeb1 auto refresh dashboard reservations 2026-06-23 02:45:54 +08:00
Your Name d81e00ddbc add pause resume controls to ui 2026-06-23 02:38:08 +08:00
Your Name 3c7cb45bec fix: parse paddle live tab ocr boxes 2026-06-23 02:30:10 +08:00
112 changed files with 6326 additions and 1679 deletions

No files matched your search

+4
View File
@@ -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
+2
View File
@@ -15,6 +15,8 @@
## [Unreleased]
## [V3.3.5] — 2026-06-27
## [V3.3.4] — 2026-06-26
### Added
- 引入完整的版本管理体系:
+235 -637
View File
@@ -1,707 +1,305 @@
# 抖音福袋挂机脚本
# 抖音自动化助手 - 数据看板版使用说明
<div align="center">
这是打包成 exe 后给普通用户使用的说明。正常使用时不需要安装 Python,也不需要打开源码文件。
**基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具**
## 文件说明
[![Version](https://img.shields.io/badge/version-V3.3.3-blue.svg)](douyin/core/version.py)
[![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/)
[![Platform](https://img.shields.io/badge/platform-Windows-lightgrey.svg)](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

+6
View File
@@ -110,6 +110,12 @@ from douyin.license.license_manager import require_online_license_or_exit
def ensure_adb_in_path() -> None:
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
adb_dir = os.path.dirname(bundled_adb)
os.environ["PATH"] = adb_dir + os.pathsep + os.environ.get("PATH", "")
os.environ.setdefault("ADB_EXECUTABLE", bundled_adb)
return
if shutil.which("adb"):
return
localapp = os.environ.get("LOCALAPPDATA") or ""
+236 -10
View File
@@ -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,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
+34
View File
@@ -265,6 +265,40 @@ def get_run_cli_command() -> list[str]:
return [sys.executable, get_run_cli_path()]
def get_bundled_platform_tools_dir() -> str:
"""返回随包 Android platform-tools 目录。"""
return os.path.join(PROJECT_ROOT, "platform-tools")
def get_bundled_adb_path() -> str:
"""返回随包 adb 路径。"""
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
return os.path.join(get_bundled_platform_tools_dir(), exe_name)
def find_bundled_adb() -> Optional[str]:
"""若分发包内自带 adb,返回其绝对路径。"""
candidates = [get_bundled_adb_path()]
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
candidates.append(os.path.join(str(meipass), "platform-tools", exe_name))
for path in candidates:
if os.path.exists(path):
return os.path.abspath(path)
return None
def get_bundled_android_tools_dir() -> str:
"""返回随包 Android 辅助工具目录。"""
return os.path.join(PROJECT_ROOT, "android-tools")
def get_bundled_adbkeyboard_apk_path() -> str:
"""返回随包 ADBKeyboard APK 路径。"""
return os.path.join(get_bundled_android_tools_dir(), "ADBKeyboard.apk")
def ensure_dir(path: str) -> None:
"""确保目录存在,不存在则创建"""
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
+1 -1
View File
@@ -178,7 +178,7 @@ class underlying_operations:
)
@staticmethod
def _adb() -> str:
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
adb = _impl_adb_path()
# 始终加引号,避免路径带空格 / 版本混用
if adb.startswith('"') and adb.endswith('"'):
return adb
@@ -8,12 +8,18 @@ from __future__ import annotations
import os
from typing import List
from douyin.core import path_config
def _adb_path() -> str:
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
if adb.startswith('"') and adb.endswith('"'):
adb = adb[1:-1]
if adb == "adb":
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
return adb
@@ -3,6 +3,7 @@
from __future__ import annotations
import base64
import os
import shlex
import subprocess
import time as time_module
@@ -116,6 +117,20 @@ def ensure_adbkeyboard_ime(
return True, prev, prev
imes = self.list_imes(device_id)
if not self._pick_adbkeyboard_ime(imes):
apk_path = path_config.get_bundled_adbkeyboard_apk_path()
if os.path.exists(apk_path):
try:
subprocess.run(
[self._adb_path(), "-s", str(device_id), "install", "-r", apk_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=20.0,
check=False,
)
imes = self.list_imes(device_id)
except Exception:
pass
adb_ime = ""
pref = str(preferred_ime or "").strip()
+2 -2
View File
@@ -10,8 +10,8 @@
from typing import Optional
APP_NAME = "douyin_guaji"
APP_VERSION = "V3.3.3"
APP_BUILD_DATE = "2025-12-28"
APP_VERSION = "V3.3.5"
APP_BUILD_DATE = "2026-06-27"
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
+10 -2
View File
@@ -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
+23 -3
View File
@@ -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
+41 -20
View File
@@ -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,127 @@ 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) -> 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(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)
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)
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,
"无法参与",
"不能参与",
"不可参与",
+44 -247
View File
@@ -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
+193 -9
View File
@@ -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]
+40 -1
View File
@@ -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,
)
+110 -4
View File
@@ -12,6 +12,8 @@ from PIL import Image
from douyin.fudai.core.coords import RECOMMEND_TAB
LIVE_TAB_LAYOUT_CENTER_X_1080 = 718
@dataclass(frozen=True)
class OcrTextBox:
@@ -28,13 +30,25 @@ def _iter_ocr_items(raw: Any) -> Iterable[Any]:
return raw
def _plain(value: Any) -> Any:
"""Convert numpy/PaddleOCR array-like values into regular Python lists."""
try:
if hasattr(value, "tolist"):
return value.tolist()
except Exception:
pass
return value
def _bbox_to_rect(box: Any) -> tuple[float, float, float, float] | None:
try:
box = _plain(box)
if not isinstance(box, (list, tuple)) or not box:
return None
xs: list[float] = []
ys: list[float] = []
for point in box:
point = _plain(point)
if isinstance(point, (list, tuple)) and len(point) >= 2:
xs.append(float(point[0]))
ys.append(float(point[1]))
@@ -49,6 +63,7 @@ def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]:
"""Parse EasyOCR/PaddleOCR style OCR output into text boxes."""
boxes: list[OcrTextBox] = []
for item in _iter_ocr_items(raw):
item = _plain(item)
text = ""
confidence = None
rect = None
@@ -72,9 +87,12 @@ def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]:
break
confidence = second.get("confidence") or second.get("score")
elif isinstance(item, dict):
boxes_data = item.get("rec_boxes") or item.get("boxes") or item.get("dt_polys")
texts = item.get("rec_texts") or item.get("texts") or item.get("text_list")
scores = item.get("rec_scores") or item.get("scores")
boxes_data = _first_present(item, "rec_boxes", "boxes", "dt_polys", "rec_polys")
texts = _first_present(item, "rec_texts", "texts", "text_list")
scores = _first_present(item, "rec_scores", "scores")
boxes_data = _plain(boxes_data)
texts = _plain(texts)
scores = _plain(scores)
if isinstance(texts, list) and isinstance(boxes_data, list):
for idx, text_item in enumerate(texts):
if not isinstance(text_item, str):
@@ -93,7 +111,17 @@ def parse_ocr_text_boxes(raw: Any) -> list[OcrTextBox]:
return boxes
def _first_present(item: dict[str, Any], *keys: str) -> Any:
for key in keys:
if key in item:
value = item.get(key)
if value is not None:
return value
return None
def _rect_from_axis_aligned_or_poly(raw_box: Any) -> tuple[float, float, float, float] | None:
raw_box = _plain(raw_box)
if isinstance(raw_box, (list, tuple)) and len(raw_box) == 4 and all(
isinstance(v, (int, float)) for v in raw_box
):
@@ -111,6 +139,35 @@ def _to_float(value: Any) -> float | None:
return None
def _extract_texts_from_raw(raw: Any) -> list[str]:
texts: list[str] = []
for item in _iter_ocr_items(raw):
item = _plain(item)
if isinstance(item, (list, tuple)) and len(item) >= 2:
second = _plain(item[1])
if isinstance(second, str):
texts.append(second)
elif isinstance(second, (list, tuple)) and second and isinstance(second[0], str):
texts.append(second[0])
elif isinstance(second, dict):
for key in ("text", "rec_text", "transcription"):
value = second.get(key)
if isinstance(value, str):
texts.append(value)
break
elif isinstance(item, dict):
item_texts = _plain(_first_present(item, "rec_texts", "texts", "text_list"))
if isinstance(item_texts, list):
texts.extend(str(text) for text in item_texts if isinstance(text, str))
else:
for key in ("text", "rec_text", "transcription"):
value = item.get(key)
if isinstance(value, str):
texts.append(value)
break
return texts
@dataclass(frozen=True)
class LiveTabCandidate:
box: OcrTextBox
@@ -132,7 +189,7 @@ def choose_live_tab_candidate(boxes: Iterable[OcrTextBox]) -> LiveTabCandidate |
continue
if "直播广场" in text:
continue
if len(text) > 12:
if len(text) > 20:
continue
x1, y1, x2, y2 = box.bbox
width = max(0.0, x2 - x1)
@@ -165,24 +222,50 @@ def choose_live_tab_box(boxes: Iterable[OcrTextBox]) -> OcrTextBox | None:
return candidate.box if candidate else None
def _choose_text_only_live_tab(text: str, image_width: int, image_height: int) -> LiveTabCandidate | None:
cleaned = str(text or "").strip().replace(" ", "")
if "直播" not in cleaned or "直播广场" in cleaned or len(cleaned) > 20:
return None
center_x = float(image_width) * LIVE_TAB_LAYOUT_CENTER_X_1080 / 1080.0
center_y = float(image_height) / 2.0
return LiveTabCandidate(
box=OcrTextBox(
text=cleaned,
bbox=(0.0, 0.0, float(image_width), float(image_height)),
confidence=None,
),
center_x=center_x,
center_y=center_y,
)
def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str, Any]] | None:
"""Find the recommendation-page live tab click point using OCR bbox."""
start = time.time()
x1, y1, x2, y2 = RECOMMEND_TAB
debug: dict[str, Any] = {"region": [x1, y1, x2, y2]}
try:
setattr(analyser, "_last_live_tab_ocr_debug", debug)
except Exception:
pass
try:
analyser.cut_pic(x1, y1, x2, y2, "", "推荐页直播标签")
pic_path = analyser.operation._find_pic_path("推荐页直播标签")
if not pic_path or not os.path.exists(pic_path):
debug["reason"] = "pic_missing"
return None
with Image.open(pic_path) as img:
img_rgb = img.convert("RGB")
img_width, img_height = img_rgb.size
img_np = np.array(img_rgb)
ocr_obj = getattr(analyser.operation, "ocr", None)
ocr_type = getattr(analyser.operation, "ocr_type", None)
if ocr_obj is None:
debug["reason"] = "ocr_unavailable"
return None
debug["ocr_type"] = ocr_type
if ocr_type == "easyocr":
raw = ocr_obj.readtext(img_np)
else:
@@ -192,8 +275,28 @@ def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str,
raw = []
boxes = parse_ocr_text_boxes(raw)
raw_texts = _extract_texts_from_raw(raw)
selected = choose_live_tab_candidate(boxes)
fallback_text = ""
if selected is None:
fallback_text = "".join(raw_texts)
if not fallback_text:
try:
fallback_text = str(analyser.operation.analyse_pic_word("推荐页直播标签", 0) or "")
except Exception:
fallback_text = ""
if fallback_text:
selected = _choose_text_only_live_tab(fallback_text, img_width, img_height)
debug.update(
{
"parsed_count": len(boxes),
"raw_texts": raw_texts[:5],
"fallback_text": fallback_text[:80],
"ocr_elapsed_ms": round((time.time() - start) * 1000, 1),
}
)
if selected is None:
debug["reason"] = "live_text_not_selected"
return None
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
@@ -207,6 +310,7 @@ def find_live_tab_click_point_by_ocr(analyser: Any) -> tuple[int, int, dict[str,
"ocr_elapsed_ms": round((time.time() - start) * 1000, 1),
}
except Exception:
debug["reason"] = "exception"
return None
@@ -218,12 +322,14 @@ def click_live_tab_on_recommend_page(analyser: Any) -> tuple[int, int, str]:
if result is None:
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
try:
debug = getattr(analyser, "_last_live_tab_ocr_debug", {}) or {}
analyser._log_kv(
"流程",
"推荐页OCR直播入口未命中,回退固定坐标",
x=fallback_x,
y=fallback_y,
reason="ocr_not_found",
ocr_debug=debug,
)
except Exception:
pass
+1 -1
View File
@@ -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
+1 -1
View File
@@ -4,6 +4,6 @@
"""
PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA3g7inE/9SRkEDseJIp7j5J6vWlvSgitHErypisMY29o=
MCowBQYDK2VwAyEA4qs1m9tv6c4lyLzkgBBM0GW0wZfWkHaUKkerts2Hh4c=
-----END PUBLIC KEY-----
"""
+26 -17
View File
@@ -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(
+44 -2
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import base64
import hashlib
import json
import os
@@ -13,8 +14,12 @@ 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 = (
@@ -23,6 +28,7 @@ DEFAULT_INSTALLER_ARGS = (
"/NORESTART",
"/CURRENTUSER",
)
DEFAULT_UPDATE_MANIFEST_URL = "https://dy.absfan.cn/api/v1/update/manifest"
class UpdateError(RuntimeError):
@@ -40,6 +46,7 @@ class UpdateSettings:
require_sha256: bool = True
require_https: bool = True
allow_cross_origin: bool = False
require_signed_manifest: bool = False
@dataclass(frozen=True)
@@ -121,6 +128,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,7 +164,12 @@ 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))
using_default_manifest = False
if not manifest_url and getattr(sys, "frozen", False):
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
using_default_manifest = True
enabled_default = True if using_default_manifest else _to_bool(section.get("enabled"), False)
enabled = _to_bool(env_enabled, default=enabled_default)
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
enabled = False
if not manifest_url:
@@ -151,8 +190,9 @@ 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),
)
@@ -306,6 +346,8 @@ def perform_forced_update(
_validate_manifest_url(settings)
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
if settings.require_signed_manifest:
_verify_manifest_signature(manifest)
latest_version = str(manifest.get("version", "") or "").strip()
if not latest_version:
raise UpdateError("manifest 缺少 version")
+9
View File
@@ -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(
+6 -2
View File
@@ -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
+17 -2
View File
@@ -1,4 +1,4 @@
"""底部操作按钮区(开始运行 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
"""底部操作按钮区(开始运行 / 暂停继续 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
@@ -24,7 +24,7 @@ def setup_action_buttons(
save_ui_to_config: Callable[[], None],
get_params: Callable[[], Any],
) -> None:
"""构建底部操作按钮区(开始/停止/强制停止/发送返回键 + 状态标签)。"""
"""构建底部操作按钮区(开始/暂停继续/停止/强制停止/发送返回键 + 状态标签)。"""
def start_run() -> None:
if runner.is_running():
@@ -65,6 +65,18 @@ def setup_action_buttons(
runner.stop()
status_var.set("已停止")
def pause_resume_run() -> None:
if not runner.is_running():
on_line("[暂停] 当前没有正在运行的进程")
status_var.set("未运行")
return
if getattr(runner, "is_paused", lambda: False)():
ok = runner.resume()
status_var.set("运行中" if ok else "继续失败")
else:
ok = runner.pause()
status_var.set("已暂停" if ok else "暂停失败")
def force_stop_run() -> None:
"""强制终止后台进程(包括可能残留的子进程)。"""
runner.force_stop()
@@ -78,6 +90,9 @@ def setup_action_buttons(
on_line(f"[错误] 发送返回键失败: {e}")
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
ttk.Button(actions, text="暂停/继续", command=pause_resume_run).pack(
side=LEFT, padx=(0, 4)
)
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
side=LEFT, padx=(0, 8)
+197 -93
View File
@@ -17,6 +17,8 @@ from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.dashboard_app import theme
from gui.dashboard_app.widgets import button, rounded_surface
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
@@ -35,6 +37,64 @@ from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
TITLE_FONT = ("Microsoft YaHei UI", 20, "bold")
SUBTITLE_FONT = ("Microsoft YaHei UI", 12)
LABEL_FONT = ("Microsoft YaHei UI", 13, "bold")
BODY_FONT = ("Microsoft YaHei UI", 13)
HELP_FONT = ("Microsoft YaHei UI", 12)
def _setup_wifi_dialog_styles(dialog: tk.Toplevel) -> None:
try:
style = ttk.Style(dialog)
style.configure("WifiADB.TCombobox", padding=(10, 8), font=BODY_FONT)
style.configure("WifiADB.TEntry", padding=(10, 8), font=BODY_FONT)
except Exception:
# Headless tests may provide a lightweight fake Toplevel without a tk handle.
return
def _card(parent: tk.Misc, title: str, subtitle: str = "") -> tuple[tk.Frame, tk.Frame]:
outer = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
head = tk.Frame(outer, bg=theme.SURFACE)
head.pack(fill="x", padx=22, pady=(18, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 15, "bold")).pack(side="left")
if subtitle:
tk.Label(head, text=subtitle, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(side="left", padx=(12, 0))
body = tk.Frame(outer, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=22, pady=(0, 20))
return outer, body
def _status_pill(parent: tk.Misc, text: str, *, ok: bool, active: bool = True) -> tk.Label:
if ok:
fg, bg = theme.GREEN, theme.GREEN_SOFT
elif active:
fg, bg = theme.AMBER, theme.AMBER_SOFT
else:
fg, bg = theme.MUTED, theme.SURFACE_ALT
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 12, "bold"), padx=12, pady=5)
def _field_group(parent: tk.Misc, title: str) -> tk.Frame:
box = tk.Frame(parent, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tk.Label(box, text=title, bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor="w", padx=14, pady=(12, 8))
return box
def _action_grid(parent: tk.Misc, actions: tuple[tuple[str, Callable[[], None], str, int], ...], *, columns: int = 3) -> None:
for col in range(columns):
parent.grid_columnconfigure(col, weight=1, uniform="action")
for idx, (text, command, kind, width) in enumerate(actions):
button(parent, text, command, kind=kind, width=width).grid(
row=idx // columns,
column=idx % columns,
sticky="ew",
padx=(0 if idx % columns == 0 else 10, 0),
pady=4,
)
def open_wifi_adb_dialog(
parent: tk.Misc,
*,
@@ -45,36 +105,70 @@ def open_wifi_adb_dialog(
"""打开WiFi ADB设置对话框"""
dialog = tk.Toplevel(parent)
dialog.title("WiFi ADB 设置")
dialog.geometry("500x450")
dialog.geometry("900x820")
dialog.configure(bg=theme.BG)
_setup_wifi_dialog_styles(dialog)
# 允许用户调整对话框大小,避免窗口内容被裁剪
dialog.resizable(True, True)
dialog.minsize(420, 320)
dialog.minsize(780, 640)
if not hasattr(dialog, "tk"):
ttk.Button(dialog, text="放大/恢复", command=lambda: None)
return
# 获取设备列表并分类
current_devices = list_adb_devices(adb_exe)
wifi_devices = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in current_devices if d not in wifi_devices]
canvas = tk.Canvas(dialog, bg=theme.BG, highlightthickness=0, bd=0)
scroll = ttk.Scrollbar(dialog, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=scroll.set)
canvas.pack(side="left", fill="both", expand=True)
scroll.pack(side="right", fill="y")
shell = tk.Frame(canvas, bg=theme.BG)
shell_window = canvas.create_window((0, 0), window=shell, anchor="nw")
shell.bind("<Configure>", lambda _e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(shell_window, width=e.width))
content = tk.Frame(shell, bg=theme.BG)
content.pack(fill="both", expand=True, padx=22, pady=18)
header = tk.Frame(content, bg=theme.BG)
header.pack(fill="x", pady=(0, 14))
title_box = tk.Frame(header, bg=theme.BG)
title_box.pack(side="left", fill="x", expand=True)
tk.Label(title_box, text="WiFi ADB 设置", bg=theme.BG, fg=theme.TEXT, font=TITLE_FONT).pack(anchor="w")
tk.Label(
title_box,
text="保留原有连接流程,优化设备选择与操作可读性",
bg=theme.BG,
fg=theme.MUTED,
font=SUBTITLE_FONT,
).pack(anchor="w", pady=(3, 0))
_status_pill(header, f"USB {len(usb_devices)}", ok=bool(usb_devices)).pack(side="right", padx=(8, 0))
_status_pill(header, f"WiFi {len(wifi_devices)}", ok=bool(wifi_devices), active=False).pack(side="right", padx=(8, 0))
# 创建设备选择区域
device_frame = ttk.LabelFrame(dialog, text="设备选择", padding=10)
device_frame.pack(fill=X, padx=10, pady=10)
# 使内部 grid 列随窗口宽度伸缩
device_frame.grid_columnconfigure(0, weight=3)
device_frame.grid_columnconfigure(1, weight=1)
device_card, device_frame = _card(content, "设备选择", "首次启用需要 USB,日常可直接选择 WiFi 设备")
device_card.pack(fill="x", pady=(0, 14))
device_frame.grid_columnconfigure(0, weight=1, uniform="device")
device_frame.grid_columnconfigure(1, weight=1, uniform="device")
# USB设备选择
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
row=0, column=0, sticky=W, pady=(0, 5)
)
usb_group = _field_group(device_frame, "USB设备(用于首次启用)")
usb_group.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
usb_combo = ttk.Combobox(
device_frame,
usb_group,
textvariable=usb_device_var,
values=usb_devices,
width=25,
width=34,
state="readonly" if not usb_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
usb_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示USB设备状态
usb_status_text = (
@@ -82,27 +176,23 @@ def open_wifi_adb_dialog(
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label = ttk.Label(
device_frame,
text=usb_status_text,
font=("Arial", 8),
foreground="red" if not usb_devices else "green",
)
usb_status_label.grid(row=2, column=0, sticky=W, pady=(0, 10))
usb_status_label = _status_pill(usb_group, usb_status_text, ok=bool(usb_devices))
usb_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# WiFi设备选择
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
wifi_group = _field_group(device_frame, "WiFi设备(已连接)")
wifi_group.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
wifi_combo = ttk.Combobox(
device_frame,
wifi_group,
textvariable=wifi_device_var,
values=wifi_devices,
width=25,
width=34,
state="readonly" if not wifi_devices else "normal",
style="WifiADB.TCombobox",
font=BODY_FONT,
)
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
wifi_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
# 显示WiFi设备状态
wifi_status_text = (
@@ -110,38 +200,32 @@ def open_wifi_adb_dialog(
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label = ttk.Label(
device_frame,
text=wifi_status_text,
font=("Arial", 8),
foreground="blue" if wifi_devices else "gray",
)
wifi_status_label.grid(row=2, column=1, sticky=W, pady=(0, 10))
wifi_status_label = _status_pill(wifi_group, wifi_status_text, ok=bool(wifi_devices), active=False)
wifi_status_label.pack(anchor="w", padx=14, pady=(0, 14))
# IP地址输入区域
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
# 使 IP/端口 输入框随窗口宽度伸缩
ip_card, ip_frame = _card(content, "连接信息", "手动连接时填写设备 IP 与端口")
ip_card.pack(fill=X, pady=(0, 14))
ip_frame.grid_columnconfigure(0, weight=3)
ip_frame.grid_columnconfigure(1, weight=1)
ttk.Label(ip_frame, text="设备IP地址:").grid(
row=0, column=0, sticky=W, pady=(0, 5)
tk.Label(ip_frame, text="设备IP地址", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=0, sticky=W, pady=(0, 8)
)
ip_var = tk.StringVar()
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=25)
ip_entry.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=30, style="WifiADB.TEntry", font=BODY_FONT)
ip_entry.grid(row=1, column=0, padx=(0, 14), pady=(0, 2), sticky="we", ipady=7)
ttk.Label(ip_frame, text="端口(默认5555):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
tk.Label(ip_frame, text="端口(默认5555)", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
row=0, column=1, sticky=W, pady=(0, 8)
)
port_var = tk.StringVar(value="5555")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=25)
port_entry.grid(row=1, column=1, pady=(0, 10), sticky="we")
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=16, style="WifiADB.TEntry", font=BODY_FONT)
port_entry.grid(row=1, column=1, pady=(0, 2), sticky="we", ipady=7)
# 按钮区域
button_frame = ttk.Frame(dialog)
button_frame.pack(fill=X, padx=10, pady=10)
action_card, button_frame = _card(content, "设备操作", "按当前连接方式选择对应动作")
action_card.pack(fill=X, pady=(0, 14))
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
is_maximized = False
@@ -350,63 +434,83 @@ def open_wifi_adb_dialog(
on_line("[WiFi ADB] 设备列表已刷新")
# USB设备操作按钮
usb_button_frame = ttk.Frame(button_frame)
usb_button_frame.pack(fill=X, pady=(0, 10))
button_frame.grid_columnconfigure(0, weight=1, uniform="actions")
button_frame.grid_columnconfigure(1, weight=1, uniform="actions")
button_frame.grid_columnconfigure(2, weight=1, uniform="actions")
usb_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
usb_button_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
ttk.Label(usb_button_frame, text="USB设备操作:").pack(anchor=W)
usb_buttons_frame = ttk.Frame(usb_button_frame)
usb_buttons_frame.pack(fill=X, pady=(5, 0))
tk.Label(usb_button_frame, text="USB首次启用", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
usb_buttons_frame = tk.Frame(usb_button_frame, bg=theme.SURFACE_ALT)
usb_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
ttk.Button(usb_buttons_frame, text="自动连接", command=auto_connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="启用WiFi ADB", command=enable_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(usb_buttons_frame, text="连接", command=connect_wifi).pack(
side=LEFT, padx=(0, 10)
)
ttk.Button(
usb_buttons_frame, text="刷新设备", command=refresh_device_lists
).pack(side=LEFT)
# 如果窗口无法通过边框调整,提供放大/恢复按钮作为备用
ttk.Button(usb_buttons_frame, text="放大/恢复", command=toggle_maximize).pack(
side=LEFT, padx=(8, 0)
_action_grid(
usb_buttons_frame,
(
("自动连接", auto_connect_wifi, "primary", 150),
("启用WiFi ADB", enable_wifi, "soft", 170),
),
columns=1,
)
# WiFi设备操作按钮
wifi_button_frame = ttk.Frame(button_frame)
wifi_button_frame.pack(fill=X, pady=(10, 0))
wifi_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
wifi_button_frame.grid(row=0, column=1, sticky="nsew", padx=(10, 10))
ttk.Label(wifi_button_frame, text="WiFi设备操作:").pack(anchor=W)
wifi_buttons_frame = ttk.Frame(wifi_button_frame)
wifi_buttons_frame.pack(fill=X, pady=(5, 0))
tk.Label(wifi_button_frame, text="WiFi连接操作", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
wifi_buttons_frame = tk.Frame(wifi_button_frame, bg=theme.SURFACE_ALT)
wifi_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
side=LEFT
)
ttk.Button(
_action_grid(
wifi_buttons_frame,
text="扫描局域网",
command=lambda: open_scan_dialog(
dialog, adb_exe, ip_var, on_line, refresh_device_lists
(
("连接", connect_wifi, "primary", 124),
("断开连接", disconnect_wifi, "soft", 132),
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists), "soft", 142),
),
).pack(side=LEFT, padx=(10, 0))
columns=1,
)
# 通用工具
tools_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
tools_button_frame.grid(row=0, column=2, sticky="nsew", padx=(10, 0))
tk.Label(tools_button_frame, text="通用工具", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
tools_buttons_frame = tk.Frame(tools_button_frame, bg=theme.SURFACE_ALT)
tools_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
_action_grid(
tools_buttons_frame,
(
("刷新设备", refresh_device_lists, "soft", 132),
("放大/恢复", toggle_maximize, "soft", 132),
),
columns=1,
)
# 说明文本
info_text = """重要说明:
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
help_card, help_body = _card(content, "重要说明", "为什么首次必须接 USB")
help_card.pack(fill="both", expand=True)
help_body.grid_columnconfigure(0, weight=1)
help_body.grid_columnconfigure(1, weight=1)
使用方法:
1. 连接Android设备到电脑(USB)
2. 点击"刷新设备"确保设备被检测到
3. 选择USB设备,点击"自动连接"或手动操作
4. 等待设备重启后即可通过WiFi使用"""
notes = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
notes.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
steps = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
steps.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
info_label = ttk.Label(
dialog, text=info_text, justify=LEFT, font=("Arial", 9), wraplength=460
)
info_label.pack(pady=(10, 0), padx=20, anchor="w")
tk.Label(notes, text="连接规则", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"Android 首次启用 WiFi ADB 必须通过 USB 连接",
"流程:USB连接 -> 启用WiFi ADB -> 设备重启 -> WiFi连接",
"设置完成后,设备会出现在 WiFi 设备列表中",
"设备重启后 WiFi ADB 模式会保持,可继续通过 WiFi 使用",
):
tk.Label(notes, text=f"• {line}", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
tk.Label(steps, text="使用方法", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
for line in (
"1. 连接 Android 设备到电脑(USB)",
"2. 点击“刷新设备”确保设备被检测到",
"3. 选择 USB 设备,点击“自动连接”或手动操作",
"4. 等待设备重启后即可通过 WiFi 使用",
):
tk.Label(steps, text=line, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
+80 -30
View File
@@ -19,7 +19,7 @@ from . import theme
from .data import load_dashboard_data
from .page_context import PageContext
from .page_registry import PAGES
from .widgets import ScrollFrame, button, clear, nav_button, rounded_surface, status_pill
from .widgets import ScrollFrame, button, clear, field_shell, nav_button, rounded_surface, status_pill
class DashboardApp:
@@ -30,8 +30,8 @@ class DashboardApp:
except Exception:
pass
self.root.title("抖音自动化助手 - 数据看板")
self.root.geometry("1280x860")
self.root.minsize(1080, 720)
self.root.geometry("1360x900")
self.root.minsize(1160, 760)
theme.setup_styles(self.root)
disable_spinbox_mousewheel(self.root)
@@ -66,40 +66,76 @@ class DashboardApp:
shell = ttk.Frame(self.root, style="Dashboard.TFrame")
shell.pack(fill="both", expand=True)
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
top.pack(fill="x", padx=18, pady=(14, 8))
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
top.pack(fill="x", padx=20, pady=(12, 6))
brand = tk.Frame(top, bg=theme.SURFACE)
brand.pack(fill="x", padx=18, pady=(12, 5))
brand.pack(fill="x", padx=20, pady=(10, 4))
brand.grid_columnconfigure(1, weight=1)
mark = tk.Frame(brand, bg=theme.TEAL, width=34, height=34)
mark.pack(side="left", padx=(0, 12))
mark.grid(row=0, column=0, sticky="w", padx=(0, 12))
mark.pack_propagate(False)
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 15, "bold")).pack(expand=True)
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 17, "bold")).pack(expand=True)
title_box = tk.Frame(brand, bg=theme.SURFACE)
title_box.pack(side="left")
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 17, "bold")).pack(anchor="w")
title_box.grid(row=0, column=1, sticky="w")
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 20, "bold")).pack(anchor="w")
tk.Label(title_box, text="轻量数据看板入口", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w")
quick_state = tk.Frame(brand, bg=theme.SURFACE)
quick_state.grid(row=0, column=2, sticky="e")
tk.Label(
quick_state,
textvariable=self.status_var,
bg=theme.TEAL_SOFT,
fg=theme.TEAL_DARK,
font=("Microsoft YaHei UI", 13, "bold"),
padx=16,
pady=8,
).pack(side="right")
tk.Label(
quick_state,
text="当前状态",
bg=theme.SURFACE,
fg=theme.MUTED,
font=theme.FONT_SMALL,
).pack(side="right", padx=(0, 8))
tool_row = tk.Frame(top, bg=theme.SURFACE)
tool_row.pack(fill="x", padx=18, pady=(0, 12))
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left")
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=28, state="readonly")
self.device_combo.pack(side="left", padx=(4, 8))
button(tool_row, "刷新设备", self.refresh_devices, width=126).pack(side="left", padx=3)
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=128)
self.scan_button.pack(side="left", padx=4)
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=118).pack(side="left", padx=3)
ttk.Label(tool_row, text="Y偏移:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left", padx=(8, 3))
ttk.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=(0, 10))
for col in (1, 6):
tool_row.grid_columnconfigure(col, weight=1)
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 13, "bold")).grid(row=0, column=0, sticky="w")
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=44, state="readonly")
self.device_combo.grid(row=0, column=1, sticky="ew", padx=(8, 18), pady=(0, 10))
button(tool_row, "刷新设备", self.refresh_devices, width=150).grid(row=0, column=2, sticky="e", padx=5, pady=(0, 10))
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=136)
self.scan_button.grid(row=0, column=3, sticky="e", padx=5, pady=(0, 10))
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=132).grid(row=0, column=4, sticky="e", padx=5, pady=(0, 10))
y_shell = field_shell(tool_row, "Y偏移")
y_shell.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(0, 2), padx=(0, 18))
y_entry = tk.Entry(
y_shell,
textvariable=self.y_var,
width=12,
bg=theme.SURFACE_ALT,
fg=theme.TEXT,
insertbackground=theme.TEAL,
relief="flat",
bd=0,
font=theme.FONT_UI,
)
y_entry.pack(fill="x", padx=11, pady=(0, 9))
actions = tk.Frame(tool_row, bg=theme.SURFACE)
actions.grid(row=1, column=2, columnspan=4, sticky="w")
button(actions, "保存配置", self.save_config, width=150).pack(side="left", padx=(0, 10))
button(actions, "截图+OCR", self.screenshot_ocr, kind="primary", width=164).pack(side="left", padx=(0, 10))
main = ttk.Frame(shell, style="Dashboard.TFrame")
main.pack(fill="both", expand=True, padx=18, pady=(6, 8))
main.pack(fill="both", expand=True, padx=20, pady=(6, 6))
main.grid_columnconfigure(1, weight=1)
main.grid_rowconfigure(0, weight=1)
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 16))
sidebar.configure(width=204)
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 18))
sidebar.configure(width=218)
sidebar.grid_propagate(False)
sidebar.pack_propagate(False)
nav_canvas = tk.Canvas(sidebar, bg=theme.SURFACE, highlightthickness=0, bd=0)
@@ -134,10 +170,10 @@ class DashboardApp:
("数据", ["运行日志", "行为日志", "实时状态", "截图预览", "统计信息", "预约队列", "高价值房间", "OCR结果", "中奖记录", "映射表"]),
("连接", ["WiFi ADB"]),
]:
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=14, pady=(13, 5))
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 10, "bold")).pack(anchor="w", padx=16, pady=(14, 6))
for name in names:
btn = nav_button(nav_inner, name, lambda n=name: self.show_page(n), active=name == self.current_page)
btn.pack(fill="x", padx=10, pady=1)
btn.pack(fill="x", padx=12, pady=2)
self.nav_buttons[name] = btn
_bind_nav_wheel(sidebar)
@@ -145,11 +181,12 @@ 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))
button(inner_bottom, "暂停/继续", self.pause_resume_run, width=124).pack(side="left", padx=4)
button(inner_bottom, "停止", self.stop_run, width=96).pack(side="left", padx=4)
button(inner_bottom, "强制停止", self.force_stop_run, kind="danger", width=132).pack(side="left", padx=4)
button(inner_bottom, "发送返回键", self.send_back_key, width=146).pack(side="left", padx=8)
@@ -172,6 +209,8 @@ class DashboardApp:
color, bg = theme.RED, theme.RED_SOFT
elif "运行" in text or "扫描" in text:
color, bg = theme.TEAL, theme.TEAL_SOFT
elif "暂停" in text:
color, bg = theme.AMBER, theme.AMBER_SOFT
elif "未" in text:
color, bg = theme.AMBER, theme.AMBER_SOFT
self.status_pill.configure(text=text, fg=color, bg=bg)
@@ -339,6 +378,17 @@ class DashboardApp:
self.runner.stop()
self.status_var.set("已停止")
def pause_resume_run(self) -> None:
if not self.runner.is_running():
self.status_var.set("未运行")
return
if self.runner.is_paused():
ok = self.runner.resume()
self.status_var.set("运行中" if ok else "继续失败")
else:
ok = self.runner.pause()
self.status_var.set("已暂停" if ok else "暂停失败")
def force_stop_run(self) -> None:
self.runner.force_stop()
self.status_var.set("已停止(强制)")
+125 -11
View File
@@ -5,7 +5,7 @@ import tkinter as tk
from tkinter import ttk
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
@@ -192,19 +192,133 @@ def build_preview(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
preview_panel(parent, data.current_screenshot_path, "当前截图").pack(fill="both", expand=True)
def build_reservation_queue(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
section(parent, "预约队列", "预约队列总览与等待状态")
toolbar(parent, [("刷新", ctx.action("refresh"), "soft")])
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", "位置", 54), ("title", "直播间", 120), ("content", "内容", 160),
("value", "价值", 58), ("countdown", "倒计时", 76), ("status", "状态", 68), ("target_time", "开奖时间", 132),
)
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"])
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)
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 row in rows:
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
else:
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
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, "预约队列", "预约队列总览与等待状态")
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:
+17 -11
View File
@@ -9,8 +9,8 @@ from typing import Any
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 +190,33 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
]
for idx, item in enumerate(values):
tile = stat_tile(metrics, *item[:3], color=item[3], soft=item[4], compact=True)
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=4, pady=4)
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=6, pady=5)
body = tk.Frame(parent, bg=theme.BG)
body.pack(fill="both", expand=True)
body.pack(fill="both", expand=True, pady=(4, 0))
body.grid_columnconfigure(0, weight=3, minsize=540)
body.grid_columnconfigure(1, weight=2, minsize=380)
body.grid_rowconfigure(0, weight=1)
left = tk.Frame(body, bg=theme.BG)
right = tk.Frame(body, bg=theme.BG)
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)).pack(fill="both", expand=True)
def _statistics_values(data: DashboardData, ctx: PageContext) -> tuple[dict[str, Any], str, str]:
+16 -194
View File
@@ -47,56 +47,6 @@ def _last_log_time(stats: dict[str, Any]) -> str:
return "-"
def _group(parent: tk.Misc, title: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.pack(fill="both", expand=True)
head = tk.Frame(box, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(14, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
body = tk.Frame(box, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
return body
def _metric_row(parent: tk.Misc, label: str, value: object, hint: str = "", color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=4)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
tk.Label(row, text=str(value), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
if hint:
tk.Label(parent, text=hint, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
def _kpi_tile(parent: tk.Misc, title: str, value: object, hint: str, color: str, soft: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.configure(height=104)
box.pack_propagate(False)
accent = tk.Frame(box, bg=color, width=4)
accent.pack(side="left", fill="y")
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
return box
def _bar_row(parent: tk.Misc, label: str, value: int, total: int, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=5)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
tk.Label(row, text=f"{value} {_fmt_rate(value, total)}", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
track.pack(fill="x", pady=(0, 4))
pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total))
fill = tk.Frame(track, bg=color, height=8)
fill.place(relx=0, rely=0, relwidth=pct, relheight=1)
class StatsDashboardView:
def __init__(self, parent: tk.Misc) -> None:
self.root = tk.Frame(parent, bg=theme.BG)
@@ -112,35 +62,34 @@ class StatsDashboardView:
def _kpi_tile(self, parent: tk.Misc, key: str, title: str, color: str, soft: str) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.configure(height=104)
box.configure(height=112)
box.pack_propagate(False)
tk.Frame(box, bg=color, width=4).pack(side="left", fill="y")
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
inner.pack(fill="both", expand=True, padx=16, pady=12)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 22, "bold")).pack(anchor="w", pady=(5, 0))
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3).pack(anchor="w", pady=(7, 0))
return box
def _metric_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=4)
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
row = tk.Frame(parent, bg=theme.SURFACE_ALT)
row.pack(fill="x", pady=5)
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_UI, anchor="w").pack(side="left", fill="x", expand=True, padx=(10, 6), pady=(8, 2))
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE_ALT, fg=color, font=("Microsoft YaHei UI", 16, "bold")).pack(side="right", padx=10, pady=(8, 2))
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 5), padx=2)
def _bar_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
row = tk.Frame(parent, bg=theme.SURFACE)
row.pack(fill="x", pady=5)
row.pack(fill="x", pady=(7, 3))
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
value_var = self._var(f"{key}.value")
tk.Label(row, textvariable=value_var, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
track = tk.Frame(parent, bg=theme.BG_ALT, height=10)
track.pack(fill="x", pady=(0, 4))
fill = tk.Frame(track, bg=color, height=8)
fill = tk.Frame(track, bg=color, height=10)
fill.place(relx=0, rely=0, relwidth=0, relheight=1)
self.bars[key] = (value_var, fill)
@@ -148,11 +97,11 @@ class StatsDashboardView:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
box.pack(fill="both", expand=True)
head = tk.Frame(box, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(14, 8))
head.pack(fill="x", padx=18, pady=(16, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
body = tk.Frame(box, bg=theme.SURFACE)
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
body.pack(fill="both", expand=True, padx=18, pady=(0, 16))
return body
def _build(self) -> None:
@@ -168,7 +117,7 @@ class StatsDashboardView:
("total_run", "总运行", theme.BLUE, theme.BLUE_SOFT),
]
for idx, (key, title, color, soft) in enumerate(kpis):
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=6, pady=5)
panels = tk.Frame(self.root, bg=theme.BG)
panels.pack(fill="both", expand=True)
@@ -180,7 +129,7 @@ class StatsDashboardView:
slots = []
for idx in range(6):
slot = tk.Frame(panels, bg=theme.BG)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 10, 10 if idx % 2 == 0 else 0), pady=7)
slots.append(slot)
core = self._group(slots[0], "核心流程")
@@ -309,130 +258,3 @@ class StatsDashboardView:
self._set("last_countdown", last.get("countdown") or "-", "")
self._set("last_value", last.get("prize_value_yuan") or "-", "元")
self._set("last_people", f"{last.get('participants') or '-'} / {last.get('copies') or '-'}", "")
def _build_top_cards(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> None:
uptime = int(stats.get("uptime_seconds") or 0)
if uptime > 0:
current_run = _fmt_duration(uptime)
grid = flow_grid(parent, 4)
values = [
("运行状态", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}", theme.TEAL, theme.TEAL_SOFT),
("本次运行", current_run, "当前轮次", theme.BLUE, theme.BLUE_SOFT),
("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重口径", theme.GREEN, theme.GREEN_SOFT),
("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT),
("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT),
("打开详情", _counter(stats, "fudai_open_detail_unique"), "详情页", theme.BLUE, theme.BLUE_SOFT),
("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT),
("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT),
]
for idx, item in enumerate(values):
tile = _kpi_tile(grid, *item[:3], color=item[3], soft=item[4])
tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
def _build_core_flow(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "核心流程")
seen = _counter(stats, "fudai_seen_unique")
open_detail = _counter(stats, "fudai_open_detail_unique")
click = _counter(stats, "fudai_click_attend_unique")
attend = _counter(stats, "fudai_attend_ok_unique")
win = _counter(stats, "fudai_result_win")
no_win = _counter(stats, "fudai_result_no_win")
_bar_row(body, "识别福袋", seen, max(seen, 1), theme.TEAL)
_bar_row(body, "打开详情", open_detail, max(seen, 1), theme.BLUE)
_bar_row(body, "点击参与", click, max(open_detail, 1), theme.AMBER)
_bar_row(body, "参与成功", attend, max(click, attend, 1), theme.GREEN)
_metric_row(body, "中奖率", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}", theme.RED)
def _build_efficiency(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "效率与动作")
uptime = int(stats.get("uptime_seconds") or 0)
_metric_row(body, "识别效率", _per_hour(_counter(stats, "fudai_seen_unique"), uptime), "每小时识别福袋", theme.TEAL)
_metric_row(body, "参与效率", _per_hour(_counter(stats, "fudai_attend_ok_unique"), uptime), "每小时成功参与", theme.GREEN)
_metric_row(body, "切换频率", _per_hour(_counter(stats, "switch_room"), uptime), "每小时切换直播间", theme.AMBER)
ocr_attempt = _counter(stats, "ocr_attempt")
_metric_row(body, "OCR成功率", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}", theme.BLUE)
def _build_skip(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "过滤与跳过")
items = [
("价值过低", "fudai_skip_value_low", theme.AMBER),
("人数过少", "fudai_skip_participants_low", theme.BLUE),
("人数过多", "fudai_skip_participants_high", theme.BLUE),
("内容过滤", "fudai_skip_content", theme.TEAL),
("倒计时太短", "fudai_skip_countdown_short", theme.RED),
("倒计时太长", "fudai_skip_countdown_long", theme.AMBER),
("需要看播", "fudai_skip_watch_required", theme.RED),
]
total = sum(_counter(stats, key) for _, key, _ in items)
if total <= 0:
tk.Label(body, text="暂无跳过记录", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
return
for label, key, color in items:
value = _counter(stats, key)
if value > 0:
_bar_row(body, label, value, total, color)
def _build_reservation(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "预约与回访")
recorded = _counter(stats, "reservation_recorded")
back_success = _counter(stats, "reservation_back_success")
verify_ok = _counter(stats, "reservation_back_verify_ok")
verify_fail = _counter(stats, "reservation_back_verify_fail")
_metric_row(body, "记录预约", recorded, "累计写入预约队列", theme.TEAL)
_metric_row(body, "回退成功", back_success, f"成功率 {_fmt_rate(back_success, recorded)}", theme.GREEN)
_metric_row(body, "回退校验", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}", theme.BLUE)
_metric_row(body, "高价值预约", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高", theme.AMBER)
def _build_health(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "运行健康")
total = _counter(stats, "error_total")
detail_errors = _counter(stats, "error_read_detail") + _counter(stats, "fudai_open_error")
vision_errors = _counter(stats, "error_ocr") + _counter(stats, "error_screenshot") + _counter(stats, "error_detection")
_metric_row(body, "总错误数", total, "运行日志异常计数", theme.RED if total else theme.GREEN)
_metric_row(body, "识别/截图异常", vision_errors, "OCR、截图、识别", theme.RED if vision_errors else theme.GREEN)
_metric_row(body, "详情异常", detail_errors, "读详情或打开失败", theme.RED if detail_errors else theme.GREEN)
_metric_row(body, "慢操作", _counter(stats, "slow_operation"), ">5秒操作", theme.AMBER)
def _build_latest(parent: tk.Misc, stats: dict[str, Any]) -> None:
body = _group(parent, "最近福袋")
last = stats.get("fudai_last", {}) or {}
if not (last.get("content") or last.get("countdown")):
tk.Label(body, text="暂无最近福袋信息", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
return
_metric_row(body, "内容", last.get("content") or "-", color=theme.TEXT)
_metric_row(body, "倒计时", last.get("countdown") or "-", color=theme.BLUE)
_metric_row(body, "价值", f"{last.get('prize_value_yuan') or '-'}", "元", theme.AMBER)
participants = last.get("participants")
copies = last.get("copies")
_metric_row(body, "人数/份数", f"{participants or '-'} / {copies or '-'}", color=theme.TEAL)
def build_stats_dashboard(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> tk.Frame:
_build_top_cards(parent, stats, current_run, total_run)
grid = tk.Frame(parent, bg=theme.BG)
grid.pack(fill="both", expand=True)
for col in range(2):
grid.grid_columnconfigure(col, weight=1, uniform="stats")
for row in range(3):
grid.grid_rowconfigure(row, weight=1)
panels = [
_build_core_flow,
_build_efficiency,
_build_skip,
_build_reservation,
_build_health,
_build_latest,
]
for idx, builder in enumerate(panels):
slot = tk.Frame(grid, bg=theme.BG)
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
builder(slot, stats)
return grid
+39 -39
View File
@@ -3,39 +3,39 @@ from __future__ import annotations
from tkinter import ttk
BG = "#f3f6f8"
BG_ALT = "#e8eef2"
BG = "#f6f8fb"
BG_ALT = "#edf2f7"
SURFACE = "#ffffff"
SURFACE_ALT = "#f7fafc"
SURFACE_HOVER = "#edf7f5"
BORDER = "#d9e3e8"
BORDER_DARK = "#b9c8d0"
TEXT = "#10201f"
MUTED = "#5d6f78"
SUBTLE = "#94a4ad"
SURFACE_ALT = "#f8fafc"
SURFACE_HOVER = "#eef7f6"
BORDER = "#dde7ee"
BORDER_DARK = "#b8c7d3"
TEXT = "#111827"
MUTED = "#5f7285"
SUBTLE = "#94a3b8"
TEAL = "#0f9488"
TEAL_DARK = "#087368"
TEAL_SOFT = "#e6f7f3"
AMBER = "#a76707"
AMBER_SOFT = "#fff4dd"
RED = "#c74454"
RED_SOFT = "#fff0f2"
TEAL_DARK = "#08756e"
TEAL_SOFT = "#e5f7f4"
AMBER = "#b26a00"
AMBER_SOFT = "#fff4dc"
RED = "#cf4057"
RED_SOFT = "#fff0f3"
GREEN = "#15805a"
GREEN_SOFT = "#e5f5ee"
BLUE = "#2e6fd8"
GREEN_SOFT = "#e7f7ef"
BLUE = "#2f6fda"
BLUE_SOFT = "#eaf2ff"
SHADOW = "#e7edf1"
SHADOW = "#d9e2ea"
RADIUS_SM = 8
RADIUS_MD = 12
RADIUS_LG = 16
RADIUS_SM = 12
RADIUS_MD = 18
RADIUS_LG = 24
FONT_UI = ("Microsoft YaHei UI", 12)
FONT_SMALL = ("Microsoft YaHei UI", 11)
FONT_READ = ("Microsoft YaHei UI", 13)
FONT_TITLE = ("Microsoft YaHei UI", 18, "bold")
FONT_H2 = ("Microsoft YaHei UI", 14, "bold")
FONT_MONO = ("Consolas", 13)
FONT_UI = ("Microsoft YaHei UI", 14)
FONT_SMALL = ("Microsoft YaHei UI", 12)
FONT_READ = ("Microsoft YaHei UI", 14)
FONT_TITLE = ("Microsoft YaHei UI", 21, "bold")
FONT_H2 = ("Microsoft YaHei UI", 16, "bold")
FONT_MONO = ("Consolas", 14)
def setup_styles(root) -> None:
@@ -51,23 +51,23 @@ def setup_styles(root) -> None:
style.configure("Toolbar.TFrame", background=SURFACE)
style.configure("Surface.TFrame", background=SURFACE)
style.configure("Alt.TFrame", background=SURFACE_ALT)
style.configure("Card.TFrame", background=SURFACE, borderwidth=1, relief="solid")
style.configure("Card.TFrame", background=SURFACE, borderwidth=0, relief="flat")
style.configure("Muted.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
style.configure("Title.TLabel", background=BG, foreground=TEXT, font=FONT_TITLE)
style.configure("H2.TLabel", background=SURFACE, foreground=TEXT, font=FONT_H2)
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 22, "bold"))
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 26, "bold"))
style.configure("Small.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
style.configure("Sidebar.TButton", padding=(12, 8), anchor="w")
style.configure("Primary.TButton", padding=(14, 8), foreground="#ffffff", background=TEAL, borderwidth=0)
style.configure("Sidebar.TButton", padding=(14, 10), anchor="w")
style.configure("Primary.TButton", padding=(16, 10), foreground="#ffffff", background=TEAL, borderwidth=0)
style.map("Primary.TButton", background=[("active", TEAL_DARK)])
style.configure("Danger.TButton", padding=(14, 8), foreground=RED)
style.configure("Soft.TButton", padding=(12, 7))
style.configure("Danger.TButton", padding=(16, 10), foreground=RED)
style.configure("Soft.TButton", padding=(14, 9))
style.configure("Dashboard.TNotebook", background=BG, borderwidth=0)
style.configure("Dashboard.TNotebook.Tab", padding=(16, 9), font=FONT_SMALL)
style.configure(
"Treeview",
font=("Microsoft YaHei UI", 13),
rowheight=38,
font=("Microsoft YaHei UI", 15),
rowheight=48,
background=SURFACE,
fieldbackground=SURFACE,
borderwidth=0,
@@ -76,8 +76,8 @@ def setup_styles(root) -> None:
style.map("Treeview", background=[("selected", TEAL_SOFT)], foreground=[("selected", TEXT)])
style.configure(
"Treeview.Heading",
font=("Microsoft YaHei UI", 12, "bold"),
background="#edf3f1",
font=("Microsoft YaHei UI", 14, "bold"),
background="#eef4f7",
foreground=TEXT,
relief="flat",
)
@@ -88,7 +88,7 @@ def setup_styles(root) -> None:
foreground=TEXT,
bordercolor=BORDER,
arrowcolor=MUTED,
padding=(8, 4),
padding=(10, 7),
)
style.map(
"TCombobox",
@@ -102,6 +102,6 @@ def setup_styles(root) -> None:
foreground=TEXT,
bordercolor=BORDER,
arrowcolor=MUTED,
padding=(6, 3),
padding=(9, 6),
)
style.map("TSpinbox", bordercolor=[("focus", TEAL), ("active", TEAL)])
+53 -51
View File
@@ -16,6 +16,7 @@ BUTTON_ICONS = {
"保存配置": "✓",
"截图+OCR": "▧",
"开始运行": "▶",
"暂停/继续": "Ⅱ",
"停止": "■",
"强制停止": "!",
"发送返回键": "↩",
@@ -125,6 +126,17 @@ class RoundedSurface(tk.Frame):
width = max(2, self.winfo_width())
height = max(2, self.winfo_height())
self._canvas.delete("all")
if self._outline != self._fill:
rounded_rect(
self._canvas,
3,
4,
width - 2,
height - 1,
self._radius,
fill=theme.SHADOW,
outline=theme.SHADOW,
)
rounded_rect(
self._canvas,
1,
@@ -164,15 +176,15 @@ class RoundedButton(tk.Canvas):
self.kind = kind
self._state = "normal"
colors = {
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK),
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2"),
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8"),
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER),
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT),
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK, theme.TEAL),
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2", "#f2ccd1"),
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8", "#f0d6a0"),
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER, theme.BORDER),
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT, theme.SURFACE),
}
self.bg_color, self.fg_color, self.hover_color = colors.get(kind, colors["soft"])
w = width or max(98, len(self.text) * 14 + 34)
super().__init__(parent, width=w, height=38, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
self.bg_color, self.fg_color, self.hover_color, self.outline_color = colors.get(kind, colors["soft"])
w = width or max(118, len(self.text) * 16 + 42)
super().__init__(parent, width=w, height=46, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
self._draw(self.bg_color)
self.bind("<Button-1>", self._click)
self.bind("<Enter>", lambda _e: self._draw(self.hover_color))
@@ -180,10 +192,10 @@ class RoundedButton(tk.Canvas):
def _draw(self, fill: str) -> None:
self.delete("all")
outline = theme.TEAL if self.kind == "primary" else theme.BORDER
outline = self.outline_color
fg = self.fg_color if self._state != "disabled" else theme.SUBTLE
rounded_rect(self, 1, 1, int(self["width"]) - 2, int(self["height"]) - 2, theme.RADIUS_SM, fill=fill, outline=outline)
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 12, "bold") if self.kind == "primary" else theme.FONT_UI)
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 14, "bold") if self.kind == "primary" else theme.FONT_UI)
def _click(self, _event) -> None:
if self.command and self._state != "disabled":
@@ -210,7 +222,7 @@ class RoundedNavButton(tk.Canvas):
self.text = _with_icon(text, NAV_ICONS.get(text))
self.command = command
self.active = active
super().__init__(parent, height=34, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
super().__init__(parent, height=46, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
self.bind("<Configure>", lambda _e: self._draw())
self.bind("<Button-1>", lambda _e: self.command())
self.bind("<Enter>", lambda _e: self._draw(hover=True))
@@ -225,10 +237,10 @@ class RoundedNavButton(tk.Canvas):
width = max(1, self.winfo_width())
bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE)
fg = theme.TEAL_DARK if self.active else theme.TEXT
rounded_rect(self, 1, 2, width - 2, 32, theme.RADIUS_SM, fill=bg, outline=bg)
rounded_rect(self, 1, 4, width - 2, 42, theme.RADIUS_SM, fill=bg, outline=bg)
if self.active:
rounded_rect(self, 3, 8, 8, 26, 4, fill=theme.TEAL, outline=theme.TEAL)
self.create_text(18 if self.active else 13, 17, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 11, "bold") if self.active else theme.FONT_UI)
rounded_rect(self, 4, 12, 10, 34, 4, fill=theme.TEAL, outline=theme.TEAL)
self.create_text(22 if self.active else 15, 23, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 13, "bold") if self.active else theme.FONT_UI)
def clear(frame: tk.Misc) -> None:
@@ -245,19 +257,19 @@ def nav_button(parent, text: str, command: Callable[[], None], *, active: bool =
def pill(parent, text: str, *, fg: str = theme.TEAL, bg: str = theme.TEAL_SOFT) -> tk.Label:
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3)
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=4)
def status_pill(parent, text: str, *, color: str = theme.GREEN, bg: str = theme.GREEN_SOFT) -> tk.Label:
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=14, pady=5)
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=15, pady=6)
def card(parent, title: str | None = None, *, padding: int = 14) -> tk.Frame:
frame = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
if title:
head = tk.Frame(frame, bg=theme.SURFACE)
head.pack(fill="x", padx=padding + 2, pady=(padding, 7))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
head.pack(fill="x", padx=padding + 4, pady=(padding + 2, 8))
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 11))
ttk.Label(head, text=title, style="H2.TLabel").pack(side="left")
return frame
@@ -276,26 +288,25 @@ def metric(parent, title: str, value: object, hint: str = "", color: str = theme
def stat_tile(parent, title: str, value: object, hint: str, *, color: str, soft: str, compact: bool = False) -> tk.Frame:
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
if compact:
box.configure(height=72)
accent = tk.Frame(box, bg=color, width=4)
accent.pack(side="left", fill="y")
box.configure(height=104)
box.pack_propagate(False)
inner = tk.Frame(box, bg=theme.SURFACE)
inner.pack(side="left", fill="both", expand=True)
inner.pack(fill="both", expand=True, padx=18, pady=14)
head = tk.Frame(inner, bg=theme.SURFACE)
head.pack(fill="x", padx=16, pady=(10, 2))
head.pack(fill="x")
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 10, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 19, "bold")).pack(anchor="w", padx=16)
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=3).pack(anchor="w", padx=16, pady=(6, 10))
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 11, "bold")).pack(side="right")
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 24 if compact else 25, "bold")).pack(anchor="w", pady=(5, 0))
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=12, pady=4).pack(anchor="w", pady=(7, 0))
return box
def section(parent, title: str, subtitle: str = "") -> tk.Frame:
row = tk.Frame(parent, bg=theme.BG)
row.pack(fill="x", pady=(2, 10))
row.pack(fill="x", pady=(2, 12))
ttk.Label(row, text=title, style="Title.TLabel").pack(side="left")
if subtitle:
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=12, pady=4).pack(side="left", padx=(12, 0))
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=14, pady=7).pack(side="left", padx=(14, 0))
return row
@@ -332,8 +343,8 @@ def text_panel(parent, title: str, lines: Iterable[str], height: int = 10) -> tk
def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tuple[tk.Frame, tk.Text]:
box = card(parent, title)
wrap = tk.Frame(box, bg=theme.SURFACE_ALT)
wrap.pack(fill="both", expand=True, padx=11, pady=(4, 11))
wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
wrap.pack(fill="both", expand=True, padx=13, pady=(4, 13))
wrap.grid_rowconfigure(0, weight=1)
wrap.grid_columnconfigure(0, weight=1)
text = tk.Text(
@@ -376,23 +387,27 @@ def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tup
def table_panel(parent, title: str, columns: Sequence[tuple[str, str, int]], rows: Sequence[dict], height: int = 8) -> tk.Frame:
box = card(parent, title)
table_wrap = tk.Frame(box, bg=theme.SURFACE)
table_wrap.pack(fill="both", expand=True, padx=14, pady=(4, 14))
table_wrap.pack(fill="both", expand=True, padx=16, pady=(4, 16))
table_wrap.grid_rowconfigure(0, weight=1)
table_wrap.grid_columnconfigure(0, weight=1)
tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height)
tree.tag_configure("odd", background=theme.SURFACE)
tree.tag_configure("even", background=theme.SURFACE_ALT)
ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview)
xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set)
for key, label, width in columns:
tree.heading(key, text=label)
tree.column(key, width=width, minwidth=min(width, 90), anchor="w", stretch=False)
for row in rows:
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
for idx, row in enumerate(rows):
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns], tags=("even" if idx % 2 else "odd",))
if not rows:
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
tree.grid(row=0, column=0, sticky="nsew")
ybar.grid(row=0, column=1, sticky="ns")
xbar.grid(row=1, column=0, sticky="ew")
box.tree = tree # type: ignore[attr-defined]
box.columns_spec = list(columns) # type: ignore[attr-defined]
return box
@@ -414,7 +429,7 @@ def mini_table(parent, title: str, rows: Sequence[tuple[str, str, str]], *, colo
def field_shell(parent, label: str) -> tk.Frame:
row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM)
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=9, pady=(7, 1))
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=11, pady=(8, 2))
return row
@@ -471,20 +486,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:
@@ -503,8 +505,8 @@ def switch_row(parent, label: str, variable: tk.Variable | None = None, value: b
bd=0,
anchor="w",
justify="left",
font=theme.FONT_SMALL,
).pack(fill="x", padx=9, pady=6)
font=theme.FONT_UI,
).pack(fill="x", padx=10, pady=8)
return row
@@ -523,7 +525,7 @@ def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]
def preview_panel(parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560)) -> tk.Frame:
box = card(parent, title)
body = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
body.pack(fill="both", expand=True, padx=14, pady=(4, 14))
body.pack(fill="both", expand=True, padx=16, pady=(4, 16))
if image_path and image_path.exists():
try:
from PIL import Image, ImageTk
+66
View File
@@ -21,6 +21,7 @@ from dataclasses import dataclass
from typing import Optional
from douyin.core import path_config
from gui.process_pause import resume_process_tree, suspend_process_tree
# 从子包 re-export 顶层符号(保持兼容)
from gui.gui_core_pkg import (
@@ -55,6 +56,7 @@ class Runner:
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = None
self._paused: bool = False
self._counters: dict[str, int] = {}
self._fudai_last: dict[str, object] = {
"content": "",
@@ -88,6 +90,10 @@ class Runner:
def is_running(self) -> bool:
return self._proc is not None and self._proc.poll() is None
def is_paused(self) -> bool:
with self._lock:
return bool(self._paused and self._proc is not None and self._proc.poll() is None)
def _append_log_line(self, line: str) -> None:
if line is None:
return
@@ -163,6 +169,7 @@ class Runner:
start_ts = self._start_ts
last_log_ts = self._last_log_ts
exit_code = self._exit_code
paused = bool(self._paused and self._proc is not None and self._proc.poll() is None)
counters = dict(self._counters)
fudai_last = dict(self._fudai_last)
wins = list(self._wins[-20:]) # 只返回最近20条
@@ -175,6 +182,7 @@ class Runner:
return {
"running": bool(running),
"paused": paused,
"pid": pid,
"start_ts": start_ts,
"last_log_ts": last_log_ts,
@@ -383,6 +391,7 @@ class Runner:
with self._lock:
self._proc = p
self._pid = p.pid
self._paused = False
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
@@ -420,6 +429,7 @@ class Runner:
rc = self._proc.wait()
with self._lock:
self._exit_code = rc
self._paused = False
# 如果进程立即退出且没有输出,说明可能有问题
if not has_output and rc != 0:
@@ -437,6 +447,7 @@ class Runner:
if rc is not None:
with self._lock:
self._exit_code = rc
self._paused = False
self._emit_line(f"[进程结束] exit_code={rc}")
except Exception:
pass
@@ -496,10 +507,58 @@ class Runner:
self._emit_line(f"[错误] 发送返回键异常: {str(e)}")
return False
def pause(self) -> bool:
with self._lock:
proc = self._proc
pid = self._pid or (proc.pid if proc is not None else None)
already_paused = self._paused
if proc is None or proc.poll() is not None or not pid:
self._emit_line("[暂停] 当前没有正在运行的进程")
with self._lock:
self._paused = False
return False
if already_paused:
self._emit_line("[暂停] 当前已经是暂停状态")
return True
try:
suspend_process_tree(int(pid))
with self._lock:
self._paused = True
self._emit_line("[暂停] 已暂停运行进程")
return True
except Exception as e:
self._emit_line(f"[暂停] 暂停失败: {e}")
return False
def resume(self) -> bool:
with self._lock:
proc = self._proc
pid = self._pid or (proc.pid if proc is not None else None)
already_paused = self._paused
if proc is None or proc.poll() is not None or not pid:
self._emit_line("[继续] 当前没有可恢复的运行进程")
with self._lock:
self._paused = False
return False
if not already_paused:
self._emit_line("[继续] 当前不在暂停状态")
return True
try:
resume_process_tree(int(pid))
with self._lock:
self._paused = False
self._emit_line("[继续] 已恢复运行进程")
return True
except Exception as e:
self._emit_line(f"[继续] 恢复失败: {e}")
return False
def stop(self) -> None:
if not self.is_running():
return
assert self._proc is not None
if self.is_paused():
self.resume()
self._emit_line("[停止] 正在终止进程...")
self._proc.terminate()
try:
@@ -519,6 +578,12 @@ class Runner:
self._emit_line(f"[停止] 强制终止进程 (pid={pid}) ...")
if self.is_paused() and pid:
try:
resume_process_tree(int(pid))
except Exception:
pass
# 先尝试通过 Popen 对象 kill
try:
if proc is not None and proc.poll() is None:
@@ -552,3 +617,4 @@ class Runner:
with self._lock:
self._proc = None
self._pid = None
self._paused = False
+19 -3
View File
@@ -11,14 +11,30 @@ import shutil
import subprocess
from typing import Optional
from douyin.core import path_config
def _normalize_adb_path(adb: str | None) -> str:
value = str(adb or "").strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
return value
def find_adb_executable() -> str:
"""返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。"""
"""返回可用的 adb 可执行文件路径。"""
env_adb = _normalize_adb_path(os.environ.get("ADB_EXECUTABLE"))
if env_adb and os.path.exists(env_adb):
return os.path.abspath(env_adb)
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
adb = shutil.which("adb")
if adb:
return adb
# 默认安装目录(我们之前下载的 platform-tools)
# 默认安装目录(本机开发/打包机常用 platform-tools 位置)
localapp = os.environ.get("LOCALAPPDATA") or ""
candidates = []
if localapp:
@@ -33,7 +49,7 @@ def find_adb_executable() -> str:
for p in candidates:
if os.path.exists(p):
return p
return os.path.abspath(p)
return ""
+98
View File
@@ -0,0 +1,98 @@
"""Process-tree pause/resume helpers shared by the desktop and Web UI."""
from __future__ import annotations
import os
import subprocess
def _run_powershell_tree_action(pid: int, action: str) -> None:
if action not in {"suspend", "resume"}:
raise ValueError(f"unsupported process action: {action}")
native_call = "[NativeMethods]::SuspendProcess($_)" if action == "suspend" else "[NativeMethods]::ResumeProcess($_)"
script = f"""
$ErrorActionPreference = 'Stop'
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class NativeMethods {{
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("ntdll.dll")]
public static extern int NtSuspendProcess(IntPtr processHandle);
[DllImport("ntdll.dll")]
public static extern int NtResumeProcess(IntPtr processHandle);
public static void SuspendProcess(int pid) {{
IntPtr h = OpenProcess(0x0800, false, pid);
if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid);
try {{
int rc = NtSuspendProcess(h);
if (rc != 0) throw new InvalidOperationException("NtSuspendProcess failed: " + rc);
}} finally {{
CloseHandle(h);
}}
}}
public static void ResumeProcess(int pid) {{
IntPtr h = OpenProcess(0x0800, false, pid);
if (h == IntPtr.Zero) throw new InvalidOperationException("OpenProcess failed: " + pid);
try {{
int rc = NtResumeProcess(h);
if (rc != 0) throw new InvalidOperationException("NtResumeProcess failed: " + rc);
}} finally {{
CloseHandle(h);
}}
}}
}}
"@
$ids = New-Object System.Collections.Generic.List[int]
function Add-Tree([int]$p) {{
if ($ids.Contains($p)) {{ return }}
$ids.Add($p) | Out-Null
Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |
ForEach-Object {{ Add-Tree ([int]$_.ProcessId) }}
}}
Add-Tree {int(pid)}
$ids | Sort-Object -Unique | ForEach-Object {{ {native_call} }}
"""
proc = subprocess.run(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=8,
check=False,
)
if proc.returncode != 0:
detail = (proc.stderr or proc.stdout or "").strip()
raise RuntimeError(detail or f"{action} failed for pid={pid}")
def suspend_process_tree(pid: int) -> None:
"""Pause a process and its children."""
pid = int(pid or 0)
if pid <= 0:
raise ValueError("missing pid")
if os.name == "nt":
_run_powershell_tree_action(pid, "suspend")
return
import signal
os.kill(pid, signal.SIGSTOP)
def resume_process_tree(pid: int) -> None:
"""Resume a process and its children."""
pid = int(pid or 0)
if pid <= 0:
raise ValueError("missing pid")
if os.name == "nt":
_run_powershell_tree_action(pid, "resume")
return
import signal
os.kill(pid, signal.SIGCONT)
+64
View File
@@ -47,6 +47,7 @@ from gui.web_gui_pkg.net_config import get_web_gui_host, get_web_gui_port
from gui.web_gui_pkg.routes import handle_get, handle_post
from gui.web_gui_pkg import proc_runner_ops as _proc_ops
from gui.web_gui_pkg import proc_runner_stats as _proc_stats
from gui.process_pause import resume_process_tree, suspend_process_tree
BASE_DIR = path_config.PROJECT_ROOT
CONFIG_PATH = path_config.get_config_path()
@@ -92,6 +93,7 @@ class ProcRunner:
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = None
self._paused: bool = False
self._owned_run_cli_pids: set[int] = set()
# 运行统计(基于 stdout 日志解析)
@@ -215,6 +217,10 @@ class ProcRunner:
with self._lock:
return self._proc is not None and self._proc.poll() is None
def is_paused(self) -> bool:
with self._lock:
return bool(self._paused and self._proc is not None and self._proc.poll() is None)
def _list_project_run_cli_processes(self) -> list[tuple[int, str]]:
"""列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。"""
entries: list[tuple[int, str]] = []
@@ -363,6 +369,11 @@ class ProcRunner:
pid = self._pid
p = self._proc
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
if self.is_paused() and pid:
try:
resume_process_tree(int(pid))
except Exception:
pass
try:
if p is not None and p.poll() is None:
p.kill()
@@ -379,6 +390,7 @@ class ProcRunner:
with self._lock:
self._proc = None
self._pid = None
self._paused = False
if pid:
self._owned_run_cli_pids.discard(int(pid))
self._exit_code = self._exit_code if self._exit_code is not None else -9
@@ -395,6 +407,8 @@ class ProcRunner:
p = self._proc
if p is None or p.poll() is not None:
return
if self.is_paused():
self.resume()
self._append_log("[网页] 停止:终止进程")
try:
p.terminate()
@@ -409,12 +423,59 @@ class ProcRunner:
try:
self._proc = None
self._pid = None
self._paused = False
if getattr(p, "pid", None):
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
def pause(self) -> bool:
with self._lock:
p = self._proc
pid = self._pid or (p.pid if p is not None else None)
already_paused = self._paused
if p is None or p.poll() is not None or not pid:
self._append_log("[网页] 暂停:当前没有正在运行的进程")
with self._lock:
self._paused = False
return False
if already_paused:
self._append_log("[网页] 暂停:当前已经是暂停状态")
return True
try:
suspend_process_tree(int(pid))
with self._lock:
self._paused = True
self._append_log("[网页] 暂停:已暂停运行进程")
return True
except Exception as e:
self._append_log(f"[网页] 暂停失败:{e}")
return False
def resume(self) -> bool:
with self._lock:
p = self._proc
pid = self._pid or (p.pid if p is not None else None)
already_paused = self._paused
if p is None or p.poll() is not None or not pid:
self._append_log("[网页] 继续:当前没有可恢复的运行进程")
with self._lock:
self._paused = False
return False
if not already_paused:
self._append_log("[网页] 继续:当前不在暂停状态")
return True
try:
resume_process_tree(int(pid))
with self._lock:
self._paused = False
self._append_log("[网页] 继续:已恢复运行进程")
return True
except Exception as e:
self._append_log(f"[网页] 继续失败:{e}")
return False
def _append_log(self, line: str) -> None:
# 清理ANSI转义序列,避免在Web界面显示异常字符
line = strip_ansi_escape_codes(line)
@@ -739,6 +800,7 @@ class ProcRunner:
with self._lock:
self._proc = p
self._pid = p.pid
self._paused = False
self._owned_run_cli_pids.add(int(p.pid))
self._start_ts = time.time()
self._exit_code = None
@@ -772,6 +834,7 @@ class ProcRunner:
self._append_log(f"[网页] 进程退出(无输出):退出码={rc}")
with self._lock:
self._exit_code = rc
self._paused = False
return
try:
@@ -810,6 +873,7 @@ class ProcRunner:
try:
self._proc = None
self._pid = None
self._paused = False
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
+2 -1
View File
@@ -13,6 +13,7 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
start_ts = self._start_ts
last_log_ts = self._last_log_ts
exit_code = self._exit_code
paused = bool(getattr(self, "_paused", False) and self._proc is not None and self._proc.poll() is None)
log_len = len(self._log)
counters = dict(self._counters)
fudai_last = dict(self._fudai_last)
@@ -125,6 +126,7 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
payload = {
"running": bool(running),
"paused": paused,
"pid": pid,
"start_ts": start_ts,
"last_log_ts": last_log_ts,
@@ -145,4 +147,3 @@ def get_stats(self: Any, include_events: bool = False) -> dict:
payload["events"] = events[-200:]
return payload
+46 -4
View File
@@ -182,7 +182,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
qlow = q.lower()
filtered = [l for l in cand if qlow in (l or "").lower()]
return handler._send_json(
{"next": total, "lines": filtered, "running": runner.is_running()}
{
"next": total,
"lines": filtered,
"running": runner.is_running(),
"paused": runner.is_paused(),
}
)
except Exception as e:
import traceback
@@ -192,7 +197,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
level="ERROR",
)
return handler._send_json(
{"next": 0, "lines": [], "running": runner.is_running()}
{
"next": 0,
"lines": [],
"running": runner.is_running(),
"paused": runner.is_paused(),
}
)
since = 0
try:
@@ -202,7 +212,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
try:
next_idx, lines = runner.get_logs_since(since)
return handler._send_json(
{"next": next_idx, "lines": lines, "running": runner.is_running()}
{
"next": next_idx,
"lines": lines,
"running": runner.is_running(),
"paused": runner.is_paused(),
}
)
except Exception as e:
import traceback
@@ -212,7 +227,12 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
level="ERROR",
)
return handler._send_json(
{"next": 0, "lines": [], "running": runner.is_running()}
{
"next": 0,
"lines": [],
"running": runner.is_running(),
"paused": runner.is_paused(),
}
)
if u.path == "/api/logfile-tail":
qs = parse_qs(u.query)
@@ -657,6 +677,28 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
if u.path == "/api/force-stop":
runner.force_stop()
return handler._send_json({"ok": True, "message": "已执行强制停止"})
if u.path == "/api/pause":
ok = runner.pause()
return handler._send_json(
{
"ok": bool(ok),
"running": runner.is_running(),
"paused": runner.is_paused(),
"message": "已暂停" if ok else "暂停失败",
},
status=200 if ok else 409,
)
if u.path == "/api/resume":
ok = runner.resume()
return handler._send_json(
{
"ok": bool(ok),
"running": runner.is_running(),
"paused": runner.is_paused(),
"message": "已继续" if ok else "继续失败",
},
status=200 if ok else 409,
)
if u.path == "/api/back-key":
body = handler._read_json()
requested_device_id = str(body.get("device_id") or "").strip()
+73
View File
@@ -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,29 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
```
不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。
生产环境默认关闭 `/docs`、`/redoc` 和 `/openapi.json`;确实需要临时查看时设置 `DYGJ_LICENSE_ENABLE_DOCS=1`。
如果服务通过 HTTPS 访问,建议设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
只有在前面有可信反向代理时,才设置 `DYGJ_LICENSE_TRUST_FORWARDED_FOR=1`。
## 自动更新
卡密后台同一个网站也负责发布客户端更新,不需要额外端口:
```text
http://服务器IP:18100/admin
```
登录后在“在线更新”区域上传新版安装包 `.exe`,填写版本号(例如 `3.3.4`)后点击“上传并发布”。服务端会:
- 保存安装包到 `data/updates/`
- 自动计算安装包 SHA256
- 生成 `/api/v1/update/manifest`
- 使用服务端私钥给 manifest 签名
打包后的客户端默认读取:
```text
https://dy.absfan.cn/api/v1/update/manifest
```
如果后台未发布更新,manifest 返回 `version=0.0.0`,客户端不会下载。发布高于客户端当前版本的安装包后,客户端启动时会下载、校验签名和 SHA256,然后启动安装器并退出旧进程。
+350 -8
View File
@@ -3,23 +3,28 @@ from __future__ import annotations
import base64
import hmac
import hashlib
import json
import os
import secrets
import time
from html import escape
from pathlib import Path
from typing import Any
from urllib.parse import urljoin
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 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
@@ -39,6 +44,19 @@ class VerifyLicenseRequest(BaseModel):
license: dict[str, Any]
class CreateRedeemRequest(BaseModel):
days: int
max_devices: int = 1
customer: str = ""
platform: str = ""
external_order_id: str = ""
expires_hours: int = 72
class ClaimRedeemRequest(BaseModel):
token: str
def result_response(result: LicenseActionResult) -> JSONResponse:
body: dict[str, Any] = {
"ok": result.ok,
@@ -84,6 +102,19 @@ 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 _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
@@ -108,6 +139,17 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
return hmac.compare_digest(supplied, expected)
def _bearer_token_allowed(request: Request, expected_token: str) -> bool:
expected = str(expected_token or "").strip()
if not expected:
return False
auth = str(request.headers.get("authorization") or "").strip()
if not auth.lower().startswith("bearer "):
return False
supplied = auth.split(" ", 1)[1].strip()
return hmac.compare_digest(supplied, expected)
def _session_hash(raw: str) -> str:
return hashlib.sha256(str(raw or "").encode("utf-8")).hexdigest()
@@ -179,8 +221,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 +242,56 @@ def _rate_limited(request: Request, scope: str, *, max_requests: int | None = No
return False
def _public_base_url(request: Request) -> str:
configured = str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
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,
}
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 "-"
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>发布时间:{escape(published)}</span>"
"</div>"
)
def _admin_page(
service: LicenseService,
csrf_token: str,
@@ -208,6 +302,8 @@ def _admin_page(
stats = service.stats()
card_rows = service.list_cards(limit=50)
audit_rows = service.audit_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 [])
)
@@ -252,6 +348,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 +363,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 +414,23 @@ 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 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">客户端读取 <code>/api/v1/update/manifest</code>,manifest 会用服务端私钥签名,安装包下载后再做 SHA256 校验。</div>
</section>
<section>
<h2>最近卡密</h2>
<table>
@@ -339,10 +455,22 @@ 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.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.external_api_token = (
external_api_token if external_api_token is not None else external_api_token_from_env()
)
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=False)
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
app.state.rate_limit_buckets = {}
app.state.admin_sessions = {}
@@ -383,13 +511,179 @@ def create_app(
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
return result_response(get_service().verify_license_doc(req.license))
@app.post("/api/v1/redeem/external/create")
def redeem_external_create(request: Request, req: CreateRedeemRequest) -> JSONResponse:
if not _bearer_token_allowed(request, app.state.external_api_token):
if _rate_limited(
request,
"redeem_create_auth",
max_requests=EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS,
):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
return JSONResponse(
{"ok": False, "reason": "forbidden", "message": "外部接口 token 无效"},
status_code=403,
)
if _rate_limited(request, "redeem_create"):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
try:
token = get_service().create_redeem_token(
days=req.days,
max_devices=req.max_devices,
customer=req.customer,
platform=req.platform,
external_order_id=req.external_order_id,
expires_hours=req.expires_hours,
)
except ValueError as exc:
return JSONResponse(
{"ok": False, "reason": "invalid_params", "message": str(exc)},
status_code=400,
)
claim_path = f"/redeem#{token.token}"
claim_url = urljoin(_public_base_url(request) + "/", claim_path.lstrip("/"))
return JSONResponse(
{
"ok": True,
"reason": "ok",
"claim_url": claim_url,
"token_hint": token.token_hint,
"expires_at": token.expires_at.isoformat().replace("+00:00", "Z"),
}
)
@app.post("/api/v1/redeem/claim")
def redeem_claim(request: Request, req: ClaimRedeemRequest) -> JSONResponse:
if _rate_limited(
request,
"redeem_claim",
max_requests=REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS,
):
return JSONResponse(
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
status_code=429,
)
result = get_service().claim_redeem_token(req.token)
if result.ok and result.card is not None:
return JSONResponse(
{
"ok": True,
"reason": "ok",
"message": result.message,
"card_key": result.card.code,
"days": result.card.days,
"max_devices": result.card.max_devices,
}
)
status = 409 if result.reason == "already_redeemed" else _status_for_reason(result.reason)
return JSONResponse(
{"ok": False, "reason": result.reason, "message": result.message},
status_code=status,
)
@app.get("/redeem")
def redeem_page() -> HTMLResponse:
return _redeem_page_html()
@app.get("/redeem/{token}")
def redeem_legacy_page(token: str) -> HTMLResponse:
script_token = json.dumps(str(token or ""))
return HTMLResponse(
f"""<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8" /><title>兑换授权</title></head>
<body><script>location.replace("/redeem#" + encodeURIComponent({script_token}));</script></body></html>"""
)
def _redeem_page_html() -> HTMLResponse:
html = f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>兑换授权</title>
<style>
body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: linear-gradient(135deg, #0f172a, #1e293b); color: #0f172a; }}
main {{ width: min(520px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(0, 0, 0, .35); }}
h1 {{ margin: 0 0 8px; font-size: 28px; }}
p {{ color: #64748b; line-height: 1.7; }}
code {{ display: block; word-break: break-all; background: #f1f5f9; padding: 12px; border-radius: 12px; }}
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
#result {{ margin-top: 14px; padding: 12px; border-radius: 12px; background: #f8fafc; min-height: 24px; }}
</style>
</head>
<body>
<main>
<h1>兑换软件授权</h1>
<p>点击兑换后会生成正式卡密。卡密只显示一次,请妥善保存。</p>
<code id="tokenPreview">正在读取兑换链接...</code>
<button id="claim">立即兑换</button>
<div id="result"></div>
</main>
<script>
const token = decodeURIComponent((location.hash || "").replace(/^#/, ""));
document.getElementById("tokenPreview").textContent = token ? token : "兑换链接缺少 token";
document.getElementById("claim").addEventListener("click", async () => {{
const result = document.getElementById("result");
if (!token) {{
result.textContent = "兑换链接缺少 token";
return;
}}
result.textContent = "正在兑换...";
const resp = await fetch("/api/v1/redeem/claim", {{
method: "POST",
headers: {{ "content-type": "application/json" }},
body: JSON.stringify({{ token }})
}});
const data = await resp.json();
if (data.ok) {{
result.innerHTML = "兑换成功,卡密:<code>" + data.card_key + "</code>";
}} else {{
result.textContent = data.message || data.reason || "兑换失败";
}}
}});
</script>
</body>
</html>"""
return HTMLResponse(html)
@app.get("/api/v1/update/manifest")
def update_manifest(request: Request) -> JSONResponse:
return JSONResponse(_signed_update_manifest(get_service(), request))
@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
if not manifest.enabled or safe_name != manifest.filename:
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
target = service.update_dir / manifest.filename
if not target.exists():
return JSONResponse({"ok": False, "reason": "file_missing"}, status_code=404)
return FileResponse(
target,
media_type="application/octet-stream",
filename=manifest.filename,
)
@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/login")
@@ -398,6 +692,12 @@ def create_app(
@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 +710,7 @@ def create_app(
max_age=ADMIN_SESSION_SECONDS,
httponly=True,
samesite="lax",
secure=bool(app.state.secure_cookies),
)
return response
@@ -490,6 +791,47 @@ 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 校验失败,请刷新后台页面后重试")
try:
content = await installer.read()
manifest = get_service().publish_update(
version=version,
filename=installer.filename or "",
content=content,
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}"
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
+299 -18
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import base64
import hashlib
import json
import re
import secrets
import sqlite3
from dataclasses import dataclass
@@ -18,6 +19,9 @@ MAX_CARD_DAYS = 3660
MAX_CREATE_COUNT = 100
MAX_CARD_DEVICES = 20
MAX_CUSTOMER_LENGTH = 120
MAX_REDEEM_EXPIRES_HOURS = 24 * 30
MAX_PLATFORM_LENGTH = 40
MAX_EXTERNAL_ORDER_LENGTH = 120
@dataclass(frozen=True)
@@ -28,6 +32,27 @@ class CreatedCard:
customer: str
@dataclass(frozen=True)
class CreatedRedeemToken:
token: str
token_hint: str
days: int
max_devices: int
customer: str
platform: str
external_order_id: str
expires_at: datetime
@dataclass(frozen=True)
class RedeemClaimResult:
ok: bool
reason: str
message: str
card: CreatedCard | None = None
expires_at: datetime | None = None
@dataclass(frozen=True)
class LicenseActionResult:
ok: bool
@@ -71,6 +96,17 @@ class AuditLogEntry:
created_at: str
@dataclass(frozen=True)
class UpdateManifest:
enabled: bool
version: str
filename: str
sha256: str
force: bool
notes: str
published_at: str
def utcnow() -> datetime:
return datetime.now(timezone.utc)
@@ -118,6 +154,27 @@ 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 sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int:
parsed = int(value)
if parsed < minimum or parsed > maximum:
@@ -139,6 +196,16 @@ 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"
def _connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(self.db_path, timeout=10)
conn.row_factory = sqlite3.Row
@@ -146,6 +213,12 @@ class LicenseService:
conn.execute("PRAGMA busy_timeout = 10000")
return conn
def _connect_immediate(self) -> sqlite3.Connection:
conn = self._connect()
conn.isolation_level = None
conn.execute("BEGIN IMMEDIATE")
return conn
def _init_db(self) -> None:
with self._connect() as conn:
conn.execute("PRAGMA journal_mode = WAL")
@@ -182,6 +255,23 @@ class LicenseService:
reason TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS redeem_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT NOT NULL UNIQUE,
token_hint TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
days INTEGER NOT NULL,
max_devices INTEGER NOT NULL DEFAULT 1,
customer TEXT NOT NULL DEFAULT '',
platform TEXT NOT NULL DEFAULT '',
external_order_id TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
redeemed_at TEXT,
license_id INTEGER,
FOREIGN KEY(license_id) REFERENCES license_keys(id)
);
"""
)
@@ -200,31 +290,115 @@ class LicenseService:
cards: list[CreatedCard] = []
with self._connect() as conn:
for _ in range(count):
code = generate_card_code()
card = CreatedCard(
code=code,
card, _license_id = self._insert_card(
conn,
days=days,
max_devices=max_devices,
customer=customer,
)
conn.execute(
"""
INSERT INTO license_keys
(code_hash, code_hint, status, days, max_devices, customer, created_at)
VALUES (?, ?, 'active', ?, ?, ?, ?)
""",
(
hash_card_code(code),
mask_card_code(code),
days,
max_devices,
card.customer,
iso_utc(utcnow()),
),
)
cards.append(card)
return cards
def create_redeem_token(
self,
*,
days: int,
max_devices: int = 1,
customer: str = "",
platform: str = "",
external_order_id: str = "",
expires_hours: int = 72,
) -> CreatedRedeemToken:
days = _bounded_int(days, name="days", minimum=1, maximum=MAX_CARD_DAYS)
max_devices = _bounded_int(max_devices, name="max_devices", minimum=1, maximum=MAX_CARD_DEVICES)
expires_hours = _bounded_int(
expires_hours,
name="expires_hours",
minimum=1,
maximum=MAX_REDEEM_EXPIRES_HOURS,
)
customer = str(customer or "").strip()[:MAX_CUSTOMER_LENGTH]
platform = str(platform or "").strip()[:MAX_PLATFORM_LENGTH]
external_order_id = str(external_order_id or "").strip()[:MAX_EXTERNAL_ORDER_LENGTH]
token = generate_redeem_token()
token_hint = mask_card_code(token)
expires_at = utcnow() + timedelta(hours=expires_hours)
with self._connect() as conn:
conn.execute(
"""
INSERT INTO redeem_tokens
(token_hash, token_hint, status, days, max_devices, customer, platform,
external_order_id, created_at, expires_at)
VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?)
""",
(
hash_redeem_token(token),
token_hint,
days,
max_devices,
customer,
platform,
external_order_id,
iso_utc(utcnow()),
iso_utc(expires_at),
),
)
self._audit(conn, "redeem_create", token, "", "ok")
return CreatedRedeemToken(
token=token,
token_hint=token_hint,
days=days,
max_devices=max_devices,
customer=customer,
platform=platform,
external_order_id=external_order_id,
expires_at=expires_at,
)
def claim_redeem_token(self, token: str) -> RedeemClaimResult:
raw_token = str(token or "").strip()
if not raw_token:
return RedeemClaimResult(False, "missing_token", "缺少兑换码")
with self._connect_immediate() as conn:
row = conn.execute(
"SELECT * FROM redeem_tokens WHERE token_hash = ?",
(hash_redeem_token(raw_token),),
).fetchone()
if row is None:
self._audit(conn, "redeem_claim", raw_token, "", "not_found")
return RedeemClaimResult(False, "not_found", "兑换链接不存在")
status = str(row["status"] or "").strip().lower()
if status == "redeemed":
self._audit(conn, "redeem_claim", raw_token, "", "already_redeemed")
return RedeemClaimResult(False, "already_redeemed", "兑换链接已使用")
if status != "pending":
self._audit(conn, "redeem_claim", raw_token, "", status or "inactive")
return RedeemClaimResult(False, status or "inactive", "兑换链接不可用")
expires_at = parse_utc(row["expires_at"])
if utcnow() > expires_at:
conn.execute(
"UPDATE redeem_tokens SET status = 'expired' WHERE id = ?",
(row["id"],),
)
self._audit(conn, "redeem_claim", raw_token, "", "expired")
return RedeemClaimResult(False, "expired", "兑换链接已过期", expires_at=expires_at)
card, license_id = self._insert_card(
conn,
days=int(row["days"]),
max_devices=int(row["max_devices"]),
customer=str(row["customer"] or ""),
)
conn.execute(
"""
UPDATE redeem_tokens
SET status = 'redeemed', redeemed_at = ?, license_id = ?
WHERE id = ?
""",
(iso_utc(utcnow()), license_id, row["id"]),
)
self._audit(conn, "redeem_claim", raw_token, "", "ok")
return RedeemClaimResult(True, "ok", "兑换成功", card=card, expires_at=expires_at)
def revoke(self, code: str) -> bool:
with self._connect() as conn:
cur = conn.execute(
@@ -335,6 +509,81 @@ 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()
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 ""),
)
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()),
)
self.update_manifest_path.write_text(
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return manifest
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,
)
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:
@@ -495,6 +744,38 @@ class LicenseService:
(str(code_hash or "").strip().lower(),),
).fetchone()
def _insert_card(
self,
conn: sqlite3.Connection,
*,
days: int,
max_devices: int,
customer: str,
) -> tuple[CreatedCard, int]:
code = generate_card_code()
card = CreatedCard(
code=code,
days=int(days),
max_devices=int(max_devices),
customer=str(customer or "").strip()[:MAX_CUSTOMER_LENGTH],
)
cur = conn.execute(
"""
INSERT INTO license_keys
(code_hash, code_hint, status, days, max_devices, customer, created_at)
VALUES (?, ?, 'active', ?, ?, ?, ?)
""",
(
hash_card_code(code),
mask_card_code(code),
card.days,
card.max_devices,
card.customer,
iso_utc(utcnow()),
),
)
return card, int(cur.lastrowid)
def _invalid_card_reason(self, card: sqlite3.Row) -> str:
status = str(card["status"] or "").strip().lower()
if status == "revoked":
+24 -10
View File
@@ -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,10 +65,12 @@ 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`
- `logs/`、`pic/`、`state/`:运行时输出目录
- `license.dat`:默认不随包分发;仅本地测试包需要时才使用 `-IncludeLicense` 显式复制
@@ -83,8 +97,8 @@ dist\installer\DouyinGuaji-3.3.3-Setup.exe
## 发给别人前检查
- 打包脚本会自动运行 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>`,防止源码、调试产物、个人配置和旧日志混入分发目录。
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
- 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`platform-tools/` 中的 ADB 白名单文件、`android-tools/ADBKeyboard.apk`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
- 正式包会自带 ADB,不要求目标电脑额外安装 Android platform-tools 或配置 PATH。程序在需要中文输入且设备未安装 ADBKeyboard 时,会尝试从随包 `android-tools/ADBKeyboard.apk` 自动安装到手机。新电脑仍需要在手机上开启开发者选项/USB 调试并允许本机 RSA 授权;部分品牌手机首次 USB 识别还需要 Windows 能正确安装对应 USB 驱动。
- 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。
- `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。
- 启用 `-Obfuscate` 后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。
- 默认 Cython 编译后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。使用 `-NoCythonForDevOnly` 生成的明文包禁止分发。
+97 -25
View File
@@ -1,10 +1,14 @@
param(
[string]$Version = "",
[switch]$SkipInstall,
[switch]$Obfuscate,
[switch]$NoCythonForDevOnly,
[switch]$UsePyArmor,
[switch]$NoObfuscateForDevOnly,
[switch]$PackExe,
[switch]$PackExeForce,
[switch]$IncludeLicense,
[switch]$ReuseCache,
[string]$PlatformToolsDir = "",
[string]$UpxDir = ""
)
@@ -27,8 +31,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 +46,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"),
@@ -60,6 +73,9 @@ $CommonArgs = @(
"--hidden-import", "logging.handlers",
"--hidden-import", "cryptography.hazmat.primitives.serialization"
)
if (-not $ReuseCache) {
$CommonArgs = @("--clean") + $CommonArgs
}
$GuiArgs = @(
"--collect-submodules", "gui"
@@ -86,7 +102,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 +116,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 +132,19 @@ foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
Remove-Item -LiteralPath $srcDir -Recurse -Force
}
$RuntimeAssets = @(
"coupon.png",
"fav.png",
"fudai.png",
"fudai_icon_countdown_v20260618.png",
"fudai_icon_pending_v20260618.png",
"fudai_icon_purple_left_v20260618.png",
"fudai_icon_red_left_v20260618.png",
"fudai_task_status_dacheng_shape.png",
"like.png",
"x.png",
"xin.png"
)
$AssetsTarget = Join-Path $DistRoot "assets"
if (Test-Path $AssetsTarget) {
Remove-Item -LiteralPath $AssetsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $AssetsTarget | Out-Null
foreach ($name in $RuntimeAssets) {
$src = Join-Path $Root "assets\$name"
if (-not (Test-Path $src)) {
throw "Missing runtime asset: assets\$name"
}
Copy-Item -LiteralPath $src -Destination (Join-Path $AssetsTarget $name) -Force
$RuntimeAssetFiles = Get-ChildItem -LiteralPath (Join-Path $Root "assets") -File | Where-Object {
$_.Extension -ieq ".png"
}
if (-not $RuntimeAssetFiles) {
throw "Missing runtime assets: assets\*.png"
}
foreach ($asset in $RuntimeAssetFiles) {
Copy-Item -LiteralPath $asset.FullName -Destination (Join-Path $AssetsTarget $asset.Name) -Force
}
$WebuiTarget = Join-Path $DistRoot "webui"
@@ -170,6 +175,73 @@ foreach ($dir in @("logs", "pic", "state")) {
New-Item -ItemType File -Force (Join-Path $runtimeDir ".keep") | Out-Null
}
$PlatformToolCandidates = @()
if ($PlatformToolsDir) {
$PlatformToolCandidates += $PlatformToolsDir
}
foreach ($envName in @("ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT")) {
$envValue = [Environment]::GetEnvironmentVariable($envName)
if (-not $envValue) {
continue
}
if ($envName -eq "ANDROID_PLATFORM_TOOLS") {
$PlatformToolCandidates += $envValue
} else {
$PlatformToolCandidates += (Join-Path $envValue "platform-tools")
}
}
if ($env:LOCALAPPDATA) {
$PlatformToolCandidates += (Join-Path $env:LOCALAPPDATA "platform-tools")
}
$PlatformToolCandidates += (Join-Path $Root "platform-tools")
$ResolvedPlatformTools = ""
foreach ($candidate in $PlatformToolCandidates) {
if (-not $candidate) {
continue
}
$adbCandidate = Join-Path $candidate "adb.exe"
if (Test-Path $adbCandidate) {
$ResolvedPlatformTools = (Resolve-Path $candidate).Path
break
}
}
if (-not $ResolvedPlatformTools) {
throw "Missing Android platform-tools. Provide -PlatformToolsDir or install it under LOCALAPPDATA\platform-tools."
}
$PlatformToolsTarget = Join-Path $DistRoot "platform-tools"
if (Test-Path $PlatformToolsTarget) {
Remove-Item -LiteralPath $PlatformToolsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $PlatformToolsTarget | Out-Null
$PlatformToolFiles = @(
"adb.exe",
"AdbWinApi.dll",
"AdbWinUsbApi.dll",
"NOTICE.txt",
"source.properties"
)
foreach ($name in $PlatformToolFiles) {
$src = Join-Path $ResolvedPlatformTools $name
if ($name -in @("adb.exe", "AdbWinApi.dll", "AdbWinUsbApi.dll") -and -not (Test-Path $src)) {
throw "Missing required platform-tools file: $name"
}
if (Test-Path $src) {
Copy-Item -LiteralPath $src -Destination (Join-Path $PlatformToolsTarget $name) -Force
}
}
$AndroidToolsTarget = Join-Path $DistRoot "android-tools"
if (Test-Path $AndroidToolsTarget) {
Remove-Item -LiteralPath $AndroidToolsTarget -Recurse -Force
}
New-Item -ItemType Directory -Force $AndroidToolsTarget | Out-Null
$AdbKeyboardApk = Join-Path $Root "tools\adb\ADBKeyboard.apk"
if (-not (Test-Path $AdbKeyboardApk)) {
throw "Missing Android helper: tools\adb\ADBKeyboard.apk"
}
Copy-Item -LiteralPath $AdbKeyboardApk -Destination (Join-Path $AndroidToolsTarget "ADBKeyboard.apk") -Force
$licensePath = Join-Path $Root "license.dat"
if ($IncludeLicense -and (Test-Path $licensePath)) {
Copy-Item -LiteralPath $licensePath -Destination (Join-Path $DistRoot "license.dat") -Force
+1 -1
View File
@@ -3,7 +3,7 @@
# 这里的 version 由 tools/dev/bump_version.py 与 version.py 同步维护。
# 注意:为兼容 PEP 440,这里去掉 "V" 前缀,仅保留数字部分(如 V3.3.3 → 3.3.3)。
name = "douyin_guaji"
version = "3.3.3"
version = "3.3.5"
description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具"
readme = "README.md"
requires-python = ">=3.10"
+90
View File
@@ -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():
@@ -30,6 +33,26 @@ def test_load_settings_is_disabled_without_manifest_url(tmp_path, monkeypatch):
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):
from douyin.updater.force_update import UpdateSettings, perform_forced_update
@@ -81,6 +104,73 @@ def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
assert any(arg.startswith("/LOG=") for arg in launched[0])
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
+19
View File
@@ -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
View File
@@ -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()
+101
View File
@@ -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
+3 -1
View File
@@ -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
+38
View File
@@ -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 模块测试。"""
+97 -2
View File
@@ -11,6 +11,7 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
"DouyinGuajiGUI.exe",
"_internal/python310.dll",
"assets/fudai_task_count_v2_one_task.png",
"assets/README.txt",
"README.md",
"douyin/core/douyin_fudai.py",
"artifacts/debug.png",
@@ -18,11 +19,11 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
"logs/unified.log",
"pic/debug_captures/a.png",
"license.dat",
"assets/README.txt",
"webui/debug.html",
"webui/js/README.md",
"DouyinGuajiGUI/_internal/base_library.zip",
"_internal/douyin/core/douyin_fudai.py",
"_internal/douyin/fudai/douyin_fudai_core.cp312-win_amd64.pyd",
"_internal/cv2/__init__.py",
]
@@ -36,14 +37,47 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
assert "license.dat" in blocked
assert "README.md" in blocked
assert "assets/README.txt" in blocked
assert "assets/fudai_task_count_v2_one_task.png" in blocked
assert "assets/fudai_task_count_v2_one_task.png" not in blocked
assert "webui/debug.html" in blocked
assert "webui/js/README.md" in blocked
assert "DouyinGuajiGUI/_internal/base_library.zip" in blocked
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/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",
"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
@@ -54,11 +88,19 @@ def test_distribution_manifest_allows_expected_runtime_shape():
"_internal/base_library.zip",
"_internal/python312.dll",
"assets/fudai.png",
"assets/desktop.png",
"assets/fudai_task_count_v2_one_task.png",
"assets/fudai_task_status_dacheng_shape.png",
"assets/fudai_icon_red_left_v20260618.png",
"webui/index.html",
"webui/css/base.css",
"webui/js/api_client.js",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"platform-tools/NOTICE.txt",
"platform-tools/source.properties",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -68,6 +110,22 @@ def test_distribution_manifest_allows_expected_runtime_shape():
assert find_distribution_issues(entries) == []
def test_distribution_manifest_blocks_unexpected_platform_tools_files():
from tools.distribution_manifest import find_forbidden_distribution_entries
entries = [
"platform-tools/adb.exe",
"platform-tools/fastboot.exe",
"platform-tools/mke2fs.conf",
]
blocked = find_forbidden_distribution_entries(entries)
assert "platform-tools/adb.exe" not in blocked
assert "platform-tools/fastboot.exe" in blocked
assert "platform-tools/mke2fs.conf" in blocked
def test_distribution_manifest_can_allow_license_for_local_test_package():
from tools.distribution_manifest import find_distribution_issues
@@ -79,6 +137,10 @@ def test_distribution_manifest_can_allow_license_for_local_test_package():
"_internal/python312.dll",
"assets/fudai.png",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -100,6 +162,10 @@ def test_distribution_manifest_requires_python_runtime_dll():
"_internal/base_library.zip",
"assets/fudai.png",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
@@ -111,6 +177,31 @@ def test_distribution_manifest_requires_python_runtime_dll():
assert "_internal/python*.dll" in issues
def test_distribution_manifest_requires_bundled_android_runtime():
from tools.distribution_manifest import find_distribution_issues
entries = [
"DouyinGuajiGUI.exe",
"web_gui.exe",
"run_cli.exe",
"_internal/base_library.zip",
"_internal/python312.dll",
"assets/fudai.png",
"webui/index.html",
"config/README.md",
"logs/.keep",
"pic/.keep",
"state/.keep",
]
issues = find_distribution_issues(entries)
assert "platform-tools/adb.exe" in issues
assert "platform-tools/AdbWinApi.dll" in issues
assert "platform-tools/AdbWinUsbApi.dll" in issues
assert "android-tools/ADBKeyboard.apk" in issues
def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
dist = tmp_path / "dist"
for rel in [
@@ -124,6 +215,10 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
"webui/css/base.css",
"webui/js/api_client.js",
"webui/index.html",
"platform-tools/adb.exe",
"platform-tools/AdbWinApi.dll",
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"logs/.keep",
"pic/.keep",
+75 -13
View File
@@ -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,40 @@ 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", 540, 2006) 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_uses_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.2, 0.3]
def test_fast_prejoin_default_delays_wait_for_join_page_and_result(self):
a = _mk_analyser(auto_join_fansclub=True)
handle_reservation_prejoin_fansclub(a, "加入直播粉丝团并关注主播")
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
assert delay_args == [1.2, 1.6]
+26
View File
@@ -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 = "可以参与"
+4
View File
@@ -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)
+93 -8
View File
@@ -37,7 +37,7 @@ def test_v2_profile_keeps_legacy_and_adds_expected_regions(monkeypatch):
assert DETAIL_UI_V2_0["button"] == (70, 2020, 1010, 2165)
assert DETAIL_UI_V2_0_ONE_TASK["content"] == (360, 1460, 1035, 1545)
assert DETAIL_UI_V2_0_ONE_TASK["value"] == (350, 1640, 760, 1735)
assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (730, 1338, 1038, 1418)
assert DETAIL_UI_V2_0_ONE_TASK["countdown_full"] == (700, 1390, 990, 1470)
assert DETAIL_UI_V2_0_ONE_TASK["info_line"] == (430, 1315, 1055, 1435)
assert DETAIL_UI_V2_0_ONE_TASK["task_list"] == (60, 1845, 885, 2005)
assert DETAIL_UI_V2_0_ONE_TASK["task_count"] == (890, 1855, 1040, 1960)
@@ -79,6 +79,9 @@ def test_detail_profile_prefers_config_overrides(monkeypatch):
assert legacy["button"] == (101, 202, 303, 404)
assert v2_two["content"] == (1, 2, 3, 4)
assert v2_two["version"] == "v2_0"
assert v2_one["version"] == "v2_0"
assert legacy["version"] == "legacy"
assert v2_one["info_line"] == (11, 22, 33, 44)
assert lottery["pixel"] == (7, 8, 9, 10)
assert lottery["click"] == (66, 77)
@@ -127,6 +130,66 @@ def test_detail_profile_ignores_stale_v2_two_task_runtime_defaults(monkeypatch):
assert profile["countdown_full"] == coords.DETAIL_UI_V2_0["countdown_full"]
def test_detail_profile_ignores_stale_v2_one_task_narrow_countdown(monkeypatch):
from douyin.fudai.core import coords
monkeypatch.setattr(
coords,
"_read_runtime_region_config",
lambda: {
"fudai_detail_regions": {
"v2_0_one_task": {
"countdown_full": [769, 1384, 1029, 1442],
}
}
},
)
profile = coords.get_fudai_detail_profile("v2_0", task_count=1)
assert profile["countdown_full"] == coords.DETAIL_UI_V2_0_ONE_TASK["countdown_full"]
def test_detail_profile_ignores_previous_default_v2_one_task_countdown(monkeypatch):
from douyin.fudai.core import coords
monkeypatch.setattr(
coords,
"_read_runtime_region_config",
lambda: {
"fudai_detail_regions": {
"v2_0_one_task": {
"countdown_full": [730, 1338, 1038, 1418],
}
}
},
)
profile = coords.get_fudai_detail_profile("v2_0", task_count=1)
assert profile["countdown_full"] == coords.DETAIL_UI_V2_0_ONE_TASK["countdown_full"]
def test_detail_profile_ignores_high_v2_one_task_countdown(monkeypatch):
from douyin.fudai.core import coords
monkeypatch.setattr(
coords,
"_read_runtime_region_config",
lambda: {
"fudai_detail_regions": {
"v2_0_one_task": {
"countdown_full": [700, 1320, 930, 1415],
}
}
},
)
profile = coords.get_fudai_detail_profile("v2_0", task_count=1)
assert profile["countdown_full"] == coords.DETAIL_UI_V2_0_ONE_TASK["countdown_full"]
def test_v2_two_task_profile_covers_batu_4999_sample_regions():
from PIL import Image
from pathlib import Path
@@ -304,7 +367,7 @@ def test_task_list_ocr_critical_path_requires_explicit_opt_in(monkeypatch):
assert _should_schedule_task_list_ocr(analyser, disabled_switches) is False
def test_countdown_full_ocr_is_not_in_detail_critical_path_by_default(monkeypatch):
def test_countdown_full_ocr_is_in_detail_critical_path_by_default(monkeypatch):
from douyin.fudai.douyin_fudai_contain_impl import (
_should_schedule_countdown_full_ocr,
)
@@ -320,10 +383,10 @@ def test_countdown_full_ocr_is_not_in_detail_critical_path_by_default(monkeypatc
{"fudai_detail_ocr_countdown_enabled": True}
)
assert _should_schedule_countdown_full_ocr(SimpleNamespace(), switches) is False
assert _should_schedule_countdown_full_ocr(SimpleNamespace(), switches) is True
def test_countdown_full_ocr_critical_path_requires_explicit_opt_in(monkeypatch):
def test_countdown_full_ocr_critical_path_respects_countdown_switch(monkeypatch):
from douyin.fudai.douyin_fudai_contain_impl import (
_should_schedule_countdown_full_ocr,
)
@@ -342,12 +405,34 @@ def test_countdown_full_ocr_critical_path_requires_explicit_opt_in(monkeypatch):
{"fudai_detail_ocr_countdown_enabled": False}
)
analyser = SimpleNamespace(
fudai_detail_countdown_full_ocr_in_critical_path_enabled=True,
assert _should_schedule_countdown_full_ocr(SimpleNamespace(), switches) is True
assert _should_schedule_countdown_full_ocr(SimpleNamespace(), disabled_switches) is False
def test_countdown_text_fallback_uses_existing_ocr_without_extra_ocr():
from douyin.fudai.douyin_fudai_contain_impl import (
_apply_countdown_text_fallback,
)
assert _should_schedule_countdown_full_ocr(analyser, switches) is True
assert _should_schedule_countdown_full_ocr(analyser, disabled_switches) is False
analyser = SimpleNamespace(fudai_detail_verbose_logs=False)
mm, ss = _apply_countdown_text_fallback(
analyser,
"",
"",
(
("info_line", "免费购129人已参与00 : 00后开奖"),
("countdown_full", ""),
),
)
assert (mm, ss) == ("00", "00")
def test_countdown_full_result_can_override_split_when_scheduled():
from douyin.fudai.douyin_fudai_contain_impl import _parse_mmss_from_full_text
assert _parse_mmss_from_full_text("45秒后开奖") == ("00", "45")
def test_info_line_ocr_is_not_in_detail_critical_path_by_default(monkeypatch):
+9
View File
@@ -147,6 +147,15 @@ class TestShouldSkipFudaiByConfig:
assert isinstance(skip, bool)
assert isinstance(reason, str)
def test_insufficient_time_button_skips(self):
analyser = self._mock()
analyser.button_text_raw = "抽奖剩余时间不足,下次再来参与吧"
detail = ('现金1000元', '00:28', 50, 1, 1000.0,
(time.time()+28, time.time()+28))
skip, reason = should_skip_fudai_by_config(analyser, detail)
assert skip is True
assert "button_unable_to_participate" in reason
# ============================================================
# join_decision.py — basic_join_decision
+33
View File
@@ -65,6 +65,7 @@ class FakeAnalyser:
# FudaiClickExecutor 可能用 operation
class _Op:
def __init__(self):
self.click = MagicMock(return_value=None)
self.click_back = MagicMock(return_value=None)
self.delay = MagicMock(return_value=None)
@@ -104,6 +105,15 @@ class TestFudaiDetector:
assert hasattr(d, "search_regions")
assert isinstance(d.search_regions, list)
def test_search_region_stays_on_small_top_left_icon_height(self):
d = FudaiDetector(FakeAnalyser())
region = d.search_regions[0]
assert region["x1"] == 20
assert region["x2"] == 280
assert region["y_top"] == 348
assert region["y_bottom"] == 455
def test_detect_methods_callable(self):
d = FudaiDetector(FakeAnalyser())
for name in (
@@ -419,6 +429,29 @@ class TestFudaiDetector:
assert d.detect_by_icon_fallback_template(Image.open(sample).convert("RGB")) is None
def test_coupon_guard_uses_click_close_during_reservation_direct_attend():
from douyin.fudai.douyin_fudai_finder_pkg.finder import (
is_coupon_popup_before_fudai_click,
)
analyser = FakeAnalyser()
analyser._current_attending_reservation_fudai = True
pic = Image.new("RGB", (1080, 2400), "white")
with patch(
"douyin.detection.pixel.popups.detect_coupon_popup_background",
return_value=(True, {"method": "mock_coupon"}),
):
detected = is_coupon_popup_before_fudai_click(analyser, pic)
assert detected is True
analyser.operation.click_back.assert_not_called()
analyser.operation.click.assert_called_once_with("test_device", 540, 2006)
assert analyser._log_kv.call_args.kwargs["skipped_reason"] == (
"reservation_direct_attend_coupon_click_close"
)
# ============================================================
# FudaiClickExecutor
# ============================================================
+1 -1
View File
@@ -176,7 +176,7 @@ class TestFudaiDetailOcrGuiConfig:
vars_ = build_config_vars({})
assert vars_["fudai_detail_regions_legacy_content_x1_var"].get() == 389
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1410
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1368
assert vars_["fudai_detail_regions_v2_0_one_task_info_line_x1_var"].get() == 430
assert vars_["pixel_regions_fudai_task_status_x1_var"].get() == 820
assert vars_["pixel_regions_live_room_icon_bbox_x1_var"].get() == 999
+83 -1
View File
@@ -3,7 +3,10 @@ from __future__ import annotations
import time
from unittest.mock import MagicMock, patch
from douyin.fudai.core.fudai_filter_pkg.join_decision import basic_join_decision
from douyin.fudai.core.fudai_filter_pkg.join_decision import (
_looks_like_fansclub_join_button,
basic_join_decision,
)
def _mk_analyser():
@@ -46,10 +49,89 @@ def test_high_value_countdown_gt_records_reservation_and_returns_true():
assert ok is True
mock_record.assert_called_once()
reservation_log_calls = [
call
for call in analyser._log_kv.call_args_list
if len(call.args) >= 2
and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in call.args[1]
]
assert reservation_log_calls
assert all(call.args[0] == "预约" for call in reservation_log_calls)
assert not any(call.args[0] == "参与" for call in reservation_log_calls)
# 记录预约后应立即切换直播间(needswitch=True)
analyser.swipe_up_to_next_live.assert_called_once()
def test_high_value_reservation_prejoins_fansclub_before_recording():
analyser = _mk_analyser()
analyser.auto_join_fansclub = True
analyser.button_text_raw = "加入购物粉丝团并关注主播"
future_ts = time.time() + 300
detail = ("高价值福袋", "05:00", 10, 1, 1999.0, (time.time(), future_ts, 300))
events = []
def _fake_prejoin(_analyser, _button_text):
events.append("prejoin")
return True
def _fake_record(**_kwargs):
events.append("record")
return False
with patch(
"douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config",
return_value=(True, "countdown_gt_118"),
), patch(
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_reservation_prejoin_fansclub",
side_effect=_fake_prejoin,
) as mock_prejoin, patch(
"douyin.reservation.reservation_logic.record.record_high_value_reservation",
side_effect=_fake_record,
) as mock_record:
ok = basic_join_decision(analyser, detail)
assert ok is True
assert events == ["prejoin", "record"]
mock_prejoin.assert_called_once_with(analyser, "加入购物粉丝团并关注主播")
mock_record.assert_called_once()
assert analyser._reservation_prejoined_fansclub is True
analyser.swipe_up_to_next_live.assert_called_once()
def test_fansclub_button_match_accepts_live_and_ocr_variants():
assert _looks_like_fansclub_join_button("加入直播粉丝团并关注主播")
assert _looks_like_fansclub_join_button("加入购物粉丝团并关注主播")
assert _looks_like_fansclub_join_button("加人直播粉丝团并关注主播")
assert _looks_like_fansclub_join_button(
"加入直播粉丝并关注主播",
"需要加入粉丝团",
)
assert not _looks_like_fansclub_join_button("一键发表评论")
def test_high_value_reservation_prejoins_live_fansclub_variant():
analyser = _mk_analyser()
analyser.auto_join_fansclub = True
analyser.button_text_raw = "加入直播粉丝团并关注主播"
future_ts = time.time() + 300
detail = ("高价值福袋", "05:00", 10, 1, 1999.0, (time.time(), future_ts, 300))
with patch(
"douyin.fudai.core.fudai_filter_pkg.join_decision.should_skip_fudai_by_config",
return_value=(True, "countdown_gt_118"),
), patch(
"douyin.fudai.core.fudai_attend_pkg.fansclub_handler.handle_reservation_prejoin_fansclub",
return_value=True,
) as mock_prejoin, patch(
"douyin.reservation.reservation_logic.record.record_high_value_reservation",
return_value=False,
):
ok = basic_join_decision(analyser, detail)
assert ok is True
mock_prejoin.assert_called_once_with(analyser, "加入直播粉丝团并关注主播")
def test_high_value_countdown_within_join_window_attends():
analyser = _mk_analyser()
future_ts = time.time() + 30 # <= join_ahead_seconds
+263
View File
@@ -121,6 +121,64 @@ def test_admin_page_can_create_and_revoke_card(tmp_path):
assert service.activate(card, machine_fingerprint="machine-a").reason == "revoked"
def test_update_manifest_defaults_to_no_update_with_signature(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
resp = client.get("/api/v1/update/manifest")
assert resp.status_code == 200
body = resp.json()
assert body["enabled"] is False
assert body["version"] == "0.0.0"
assert isinstance(body["signature"], str)
def test_admin_can_publish_update_and_download_installer(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
payload = b"installer bytes"
published = client.post(
"/admin/update/publish",
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
data={
"csrf_token": "csrf-token",
"version": "3.3.4",
"notes": "smoke",
"force": "1",
},
files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")},
)
manifest = client.get("/api/v1/update/manifest")
body = manifest.json()
download = client.get("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe")
assert published.status_code == 200
assert "已发布更新 V3.3.4" in published.text
assert manifest.status_code == 200
assert body["enabled"] is True
assert body["version"] == "3.3.4"
assert body["sha256"]
assert body["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.4-Setup.exe")
assert isinstance(body["signature"], str)
assert download.status_code == 200
assert download.content == payload
def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path):
from fastapi.testclient import TestClient
@@ -203,6 +261,74 @@ def test_admin_login_rejects_wrong_token(tmp_path):
assert "管理员 token 不正确" in resp.text
def test_admin_login_is_rate_limited(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS", 2)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
for _ in range(2):
assert client.post("/admin/login", data={"admin_token": "wrong"}).status_code == 403
limited = client.post("/admin/login", data={"admin_token": "wrong"})
assert limited.status_code == 429
assert "登录尝试过于频繁" in limited.text
def test_license_server_secure_defaults_and_forwarded_for_policy(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "RATE_LIMIT_MAX_REQUESTS", 1)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
assert client.get("/docs").status_code == 404
first = client.post(
"/api/v1/activate",
headers={"x-forwarded-for": "198.51.100.1"},
json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"},
)
second = client.post(
"/api/v1/activate",
headers={"x-forwarded-for": "198.51.100.2"},
json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"},
)
assert first.status_code == 404
assert second.status_code == 429
def test_license_server_can_enable_secure_admin_cookies(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setenv("DYGJ_LICENSE_SECURE_COOKIES", "1")
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, admin_token="secret"),
base_url="https://testserver",
)
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
csrf = client.get("/admin")
assert "secure" in login.headers["set-cookie"].lower()
assert "secure" in csrf.headers["set-cookie"].lower()
def test_admin_logout_clears_session(tmp_path):
from fastapi.testclient import TestClient
@@ -247,3 +373,140 @@ def test_api_rate_limits_repeated_failed_activation(tmp_path, monkeypatch):
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
def test_external_redeem_create_requires_bearer_token(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
resp = client.post(
"/api/v1/redeem/external/create",
json={
"platform": "xianyu",
"external_order_id": "ORDER-1",
"customer": "buyer-a",
"days": 30,
"max_devices": 1,
},
)
assert resp.status_code == 403
assert resp.json()["reason"] == "forbidden"
def test_external_redeem_create_returns_claim_url_without_card_key(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
resp = client.post(
"/api/v1/redeem/external/create",
headers={"authorization": "Bearer external-secret"},
json={
"platform": "xianyu",
"external_order_id": "ORDER-1",
"customer": "buyer-a",
"days": 30,
"max_devices": 1,
},
)
body = resp.json()
assert resp.status_code == 200
assert body["ok"] is True
assert body["claim_url"].startswith("https://dy.absfan.cn/redeem#")
assert "card_key" not in body
assert service.stats()["total"] == 0
def test_redeem_claim_exchanges_token_for_card_once(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=30,
max_devices=1,
customer="buyer-a",
platform="xianyu",
external_order_id="ORDER-1",
)
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
first = client.post("/api/v1/redeem/claim", json={"token": token.token})
second = client.post("/api/v1/redeem/claim", json={"token": token.token})
assert first.status_code == 200
assert first.json()["ok"] is True
assert first.json()["card_key"].startswith("DG-")
assert second.status_code == 409
assert second.json()["reason"] == "already_redeemed"
def test_redeem_claim_is_rate_limited(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS", 2)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
for _ in range(2):
assert client.post("/api/v1/redeem/claim", json={"token": "missing"}).status_code == 404
limited = client.post("/api/v1/redeem/claim", json={"token": "missing"})
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
def test_external_redeem_auth_failures_are_rate_limited(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setattr(api, "EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS", 2)
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, external_api_token="external-secret"),
base_url="https://dy.absfan.cn",
)
for _ in range(2):
assert client.post(
"/api/v1/redeem/external/create",
json={"days": 1},
).status_code == 403
limited = client.post(
"/api/v1/redeem/external/create",
json={"days": 1},
)
assert limited.status_code == 429
assert limited.json()["reason"] == "rate_limited"
+86
View File
@@ -100,3 +100,89 @@ def test_license_server_verify_license_doc_requires_card_hash(tmp_path):
assert result.ok is False
assert result.reason == "invalid_signature"
def test_license_server_redeem_token_creates_card_only_when_claimed(tmp_path):
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=14,
max_devices=2,
customer="xianyu-order-1",
platform="xianyu",
external_order_id="ORDER-1",
)
before = service.stats()
claimed = service.claim_redeem_token(token.token)
second = service.claim_redeem_token(token.token)
assert before["total"] == 0
assert claimed.ok is True
assert claimed.card is not None
assert claimed.card.code.startswith("DG-")
assert claimed.card.days == 14
assert claimed.card.max_devices == 2
assert claimed.card.customer == "xianyu-order-1"
assert second.ok is False
assert second.reason == "already_redeemed"
assert service.stats()["total"] == 1
def test_license_server_redeem_token_rejects_expired_token(tmp_path, monkeypatch):
from datetime import timedelta
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
start = core.utcnow()
monkeypatch.setattr(core, "utcnow", lambda: start)
token = service.create_redeem_token(
days=7,
max_devices=1,
customer="expired-order",
platform="xianyu",
external_order_id="ORDER-EXPIRED",
expires_hours=1,
)
monkeypatch.setattr(core, "utcnow", lambda: start + timedelta(hours=2))
result = service.claim_redeem_token(token.token)
assert result.ok is False
assert result.reason == "expired"
assert service.stats()["total"] == 0
def test_license_server_redeem_token_is_single_use_under_concurrency(tmp_path, monkeypatch):
from concurrent.futures import ThreadPoolExecutor
import time
from license_server import core
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
token = service.create_redeem_token(
days=7,
max_devices=1,
customer="race-order",
platform="xianyu",
external_order_id="ORDER-RACE",
)
original_insert_card = service._insert_card
def slow_insert(*args, **kwargs):
time.sleep(0.2)
return original_insert_card(*args, **kwargs)
monkeypatch.setattr(service, "_insert_card", slow_insert)
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda _idx: service.claim_redeem_token(token.token), range(2)))
assert sorted(result.reason for result in results) == ["already_redeemed", "ok"]
assert sum(1 for result in results if result.ok) == 1
assert service.stats()["total"] == 1
+50 -3
View File
@@ -24,6 +24,27 @@ def test_parse_paddle_dict_boxes():
assert boxes[1] == OcrTextBox(text="直播", bbox=(40.0, 2.0, 70.0, 14.0), confidence=0.9)
def test_parse_paddle_rec_polys_boxes():
class ArrayLike:
def __init__(self, value):
self.value = value
def tolist(self):
return self.value
raw = [
{
"rec_texts": ["=购精选商城关注直播推荐"],
"rec_polys": ArrayLike([[[0, 0], [1080, 0], [1080, 80], [0, 80]]]),
"rec_scores": [0.92],
}
]
boxes = parse_ocr_text_boxes(raw)
assert boxes == [
OcrTextBox(text="=购精选商城关注直播推荐", bbox=(0.0, 0.0, 1080.0, 80.0), confidence=0.92)
]
def test_choose_live_tab_ignores_long_text():
selected = choose_live_tab_box(
[
@@ -39,7 +60,7 @@ def test_choose_live_tab_from_joined_tab_row_estimates_substring_center():
selected = choose_live_tab_candidate(
[
OcrTextBox(
text="商城关注直播推荐",
text="=购精选商城关注直播推荐",
bbox=(0.0, 0.0, 1080.0, 80.0),
confidence=0.92,
)
@@ -47,8 +68,8 @@ def test_choose_live_tab_from_joined_tab_row_estimates_substring_center():
)
assert selected is not None
assert selected.box.text == "商城关注直播推荐"
assert 660 <= selected.center_x <= 700
assert selected.box.text == "=购精选商城关注直播推荐"
assert selected.center_x == 810.0
assert selected.center_y == 40.0
@@ -139,6 +160,32 @@ def test_click_live_tab_uses_joined_row_substring(tmp_path):
assert method == "ocr_live_tab"
def test_click_live_tab_uses_text_fallback_when_raw_has_no_bbox(tmp_path):
pic = tmp_path / "live_tab.png"
from PIL import Image
Image.new("RGB", (1080, 80), (255, 255, 255)).save(pic)
analyser = SimpleNamespace()
analyser.device_id = "D"
analyser.resolution_ratio_x = 1080
analyser.resolution_ratio_y = 2400
analyser.cut_pic = MagicMock()
analyser._log_kv = MagicMock()
analyser.operation = SimpleNamespace()
analyser.operation.click = MagicMock()
analyser.operation._find_pic_path = MagicMock(return_value=str(pic))
analyser.operation.analyse_pic_word = MagicMock(return_value="=购精选商城关注直播推荐")
analyser.operation.ocr_type = "paddleocr"
analyser.operation.ocr = SimpleNamespace(predict=MagicMock(return_value=[{"rec_texts": []}]))
x, y, method = click_live_tab_on_recommend_page(analyser)
assert x == 718
assert y == 180
assert method == "ocr_live_tab"
analyser.operation.click.assert_called_once_with("D", x, y)
def test_recommend_page_keeps_second_step_entry_mode():
from douyin.core.fudai_modules import run_once_basic_helpers as ronce
+69 -31
View File
@@ -6,6 +6,12 @@ from pathlib import Path
import pytest
PYARMOR_STUB = (
"from pyarmor_runtime_000000 import __pyarmor__\n"
"__pyarmor__(__name__, __file__, b'PY000000')\n"
)
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")
@@ -41,14 +47,14 @@ def test_create_pyarmor_staging_uses_only_runtime_sources(tmp_path, monkeypatch)
calls.append([str(x) for x in cmd])
assert cwd == root
assert check is True
_write(staging / "douyin" / "__init__.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app_entry.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui_entry.py", "# obfuscated\n")
_write(staging / "operations" / "__init__.py", "# obfuscated\n")
_write(staging / "bin" / "run_cli.py", "# obfuscated\n")
_write(staging / "bin" / "run_cli_entry.py", "# obfuscated\n")
_write(staging / "douyin" / "__init__.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app_entry.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui_entry.py", PYARMOR_STUB)
_write(staging / "operations" / "__init__.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli_entry.py", PYARMOR_STUB)
_write(staging / "pyarmor_runtime_000000" / "__init__.py", "# runtime\n")
return subprocess.CompletedProcess(cmd, 0)
@@ -84,18 +90,36 @@ def test_validate_pyarmor_staging_requires_runtime_package(tmp_path):
validate_pyarmor_staging(staging)
def test_validate_pyarmor_staging_rejects_plain_runtime_source(tmp_path):
from tools.obfuscation_staging import validate_pyarmor_staging
staging = tmp_path / "stage"
_write(staging / "douyin" / "__init__.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app.py", "def leaked():\n return 'plain source'\n")
_write(staging / "gui" / "gui_app_entry.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui_entry.py", PYARMOR_STUB)
_write(staging / "operations" / "__init__.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli_entry.py", PYARMOR_STUB)
_write(staging / "pyarmor_runtime_000000" / "__init__.py")
with pytest.raises(RuntimeError, match="plain runtime source"):
validate_pyarmor_staging(staging)
def test_validate_pyarmor_staging_rejects_sensitive_tools(tmp_path):
from tools.obfuscation_staging import validate_pyarmor_staging
staging = tmp_path / "stage"
_write(staging / "douyin" / "__init__.py")
_write(staging / "gui" / "gui_app.py")
_write(staging / "gui" / "gui_app_entry.py")
_write(staging / "gui" / "web_gui.py")
_write(staging / "gui" / "web_gui_entry.py")
_write(staging / "operations" / "__init__.py")
_write(staging / "bin" / "run_cli.py")
_write(staging / "bin" / "run_cli_entry.py")
_write(staging / "douyin" / "__init__.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app_entry.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui_entry.py", PYARMOR_STUB)
_write(staging / "operations" / "__init__.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli.py", PYARMOR_STUB)
_write(staging / "bin" / "run_cli_entry.py", PYARMOR_STUB)
_write(staging / "pyarmor_runtime_000000" / "__init__.py")
_write(staging / "tools" / "license_dev.py", "PRIVATE_KEY = 'leak'\n")
@@ -112,21 +136,21 @@ def test_create_pyarmor_staging_moves_flat_entry_script_back_to_bin(tmp_path, mo
_make_minimal_project(root)
def fake_runner(cmd, *, cwd, check):
_write(staging / "douyin" / "__init__.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app.py", "# obfuscated\n")
_write(staging / "gui" / "gui_app_entry.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui.py", "# obfuscated\n")
_write(staging / "gui" / "web_gui_entry.py", "# obfuscated\n")
_write(staging / "operations" / "__init__.py", "# obfuscated\n")
_write(staging / "run_cli.py", "# flat obfuscated entry\n")
_write(staging / "run_cli_entry.py", "# flat obfuscated entry wrapper\n")
_write(staging / "douyin" / "__init__.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app.py", PYARMOR_STUB)
_write(staging / "gui" / "gui_app_entry.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui.py", PYARMOR_STUB)
_write(staging / "gui" / "web_gui_entry.py", PYARMOR_STUB)
_write(staging / "operations" / "__init__.py", PYARMOR_STUB)
_write(staging / "run_cli.py", PYARMOR_STUB)
_write(staging / "run_cli_entry.py", PYARMOR_STUB)
_write(staging / "pyarmor_runtime_000000" / "__init__.py", "# runtime\n")
return subprocess.CompletedProcess(cmd, 0)
create_pyarmor_staging(root, staging, runner=fake_runner)
assert (staging / "bin" / "run_cli.py").read_text(encoding="utf-8") == "# flat obfuscated entry\n"
assert (staging / "bin" / "run_cli_entry.py").read_text(encoding="utf-8") == "# flat obfuscated entry wrapper\n"
assert (staging / "bin" / "run_cli.py").read_text(encoding="utf-8") == PYARMOR_STUB
assert (staging / "bin" / "run_cli_entry.py").read_text(encoding="utf-8") == PYARMOR_STUB
assert not (staging / "run_cli.py").exists()
assert not (staging / "run_cli_entry.py").exists()
@@ -186,10 +210,15 @@ def test_collect_runtime_hidden_imports_skips_optional_heavy_modules(tmp_path):
assert "scipy" not in hidden_imports
def test_windows_packaging_script_exposes_obfuscate_switch():
def test_windows_packaging_script_protects_core_modules_by_default():
script = Path("packaging/pyinstaller/build_windows.ps1").read_text(encoding="utf-8")
assert "[switch]$Obfuscate" in script
assert "[switch]$NoCythonForDevOnly" in script
assert "[switch]$UsePyArmor" in script
assert "[switch]$NoObfuscateForDevOnly" in script
assert "if ($UsePyArmor -and -not $NoObfuscateForDevOnly)" in script
assert "elseif (-not $NoCythonForDevOnly -and -not $NoObfuscateForDevOnly)" in script
assert "tools.cython_staging" in script
assert "tools.obfuscation_staging" in script
assert '$env:DISABLE_MODEL_SOURCE_CHECK = "True"' in script
assert '$env:PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK = "1"' in script
@@ -208,7 +237,9 @@ def test_windows_packaging_script_exposes_obfuscate_switch():
assert "python -m PyInstaller @CommonArgs @GuiArgs --name DouyinGuajiGUI" in script
assert "python -m PyInstaller @CommonArgs @GuiArgs --name web_gui" in script
assert "python -m PyInstaller @CommonArgs @CliArgs --name run_cli" in script
assert "Cython core compile failed" in script
assert "PyArmor obfuscation failed" in script
assert "Development plaintext build requested" in script
assert "--paths\", $BuildSourceRoot" in script
common_block = script.split("$GuiArgs = @(", 1)[0]
gui_block = script.split("$GuiArgs = @(", 1)[1].split("$CliArgs = @(", 1)[0]
@@ -228,11 +259,18 @@ def test_windows_packaging_script_exposes_obfuscate_switch():
assert "[switch]$IncludeLicense" in script
assert '"--add-data", "assets;assets"' not in script
assert '"--add-data", "webui;webui"' not in script
assert "$RuntimeAssets = @(" in script
assert 'assets\$name' in script
assert "$RuntimeAssetFiles = Get-ChildItem" in script
assert 'assets\*.png' in script
assert "tools\\adb\\ADBKeyboard.apk" in script
assert "$IncludeLicense -and" in script
assert '$ManifestArgs += "--allow-license"' in script
assert "Get-ChildItem -LiteralPath $srcInternal -Force | Copy-Item" in script
assert "Join-Path $BuildSourceRoot \"gui\\gui_app_entry.py\"" in script
assert "Join-Path $BuildSourceRoot \"gui\\gui_dashboard_app_entry.py\"" in script
assert "Join-Path $BuildSourceRoot \"gui\\web_gui_entry.py\"" in script
assert "Join-Path $BuildSourceRoot \"bin\\run_cli_entry.py\"" in script
assert '[string]$PlatformToolsDir = ""' in script
assert '"ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT"' in script
assert '$PlatformToolFiles = @(' in script
assert '"adb.exe"' in script
assert '"AdbWinApi.dll"' in script
assert '"AdbWinUsbApi.dll"' in script
+140 -1
View File
@@ -19,6 +19,9 @@ from douyin.fudai.douyin_fudai_core_pkg.ocr_tasks import (
OcrTaskRunner,
OcrTaskRunnerFallback,
_BUTTON_KEYWORDS,
_choose_countdown_vote,
_cv_detect_two_zero_digits,
_read_countdown_digits,
_safe_preprocess,
)
@@ -137,9 +140,62 @@ class TestOcrCountdown:
runner.analyser.operation.analyse_pic_digits = MagicMock(
return_value="abc23def"
)
assert runner.ocr_countdown_mm() == "23"
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
return_value="",
):
assert runner.ocr_countdown_mm() == "23"
assert "ocr_countdown_mm" in durations
def test_mm_uses_preprocessed_countdown_image(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["23", "", "", "", "", ""]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._safe_preprocess",
return_value="福袋倒计时_分钟_preprocessed",
) as preprocess, patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
return_value="",
):
assert runner.ocr_countdown_mm() == "23"
preprocess.assert_called_once_with(runner.analyser, "福袋倒计时_分钟")
runner.analyser.operation.analyse_pic_digits.assert_any_call(
"福袋倒计时_分钟_preprocessed", 0
)
runner.analyser.operation.analyse_pic_digits.assert_any_call(
"福袋倒计时_分钟", 0
)
def test_ss_uses_preprocessed_countdown_image(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["45", "", "", "", "", ""]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._safe_preprocess",
return_value="福袋倒计时_秒_preprocessed",
) as preprocess:
assert runner.ocr_countdown_ss() == "45"
preprocess.assert_called_once_with(runner.analyser, "福袋倒计时_秒")
runner.analyser.operation.analyse_pic_digits.assert_any_call(
"福袋倒计时_秒_preprocessed", 0
)
runner.analyser.operation.analyse_pic_digits.assert_any_call(
"福袋倒计时_秒", 0
)
def test_mm_normalizes_ocr_zero_noise(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(return_value="UU")
assert runner.ocr_countdown_mm() == "00"
runner.analyser.operation.analyse_pic_word.assert_not_called()
def test_ss_extracts_digits(self):
runner, durations = _mk_runner()
runner.analyser.operation.analyse_pic_digits = MagicMock(
@@ -161,6 +217,89 @@ class TestOcrCountdown:
)
assert runner.ocr_countdown_mm() is None
def test_countdown_vote_prefers_majority(self):
assert _choose_countdown_vote(["08", "09", "08"]) == "08"
def test_countdown_vote_tie_returns_empty_to_avoid_wrong_join(self):
assert _choose_countdown_vote(["09", "08"]) == ""
def test_read_countdown_digits_uses_modes_and_fallback_pic(self):
analyser = _mk_analyser()
analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["", "99", "08", "8", "08", ""]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
return_value="",
):
result = _read_countdown_digits(
analyser,
"福袋倒计时_分钟_preprocessed",
fallback_picnames=("福袋倒计时_分钟",),
)
assert result == "08"
assert analyser.operation.analyse_pic_digits.call_args_list[0].args == (
"福袋倒计时_分钟_preprocessed",
0,
)
assert analyser.operation.analyse_pic_digits.call_args_list[-1].args == (
"福袋倒计时_分钟",
2,
)
def test_read_countdown_digits_tie_prefers_primary_over_cv_zero(self):
analyser = _mk_analyser()
analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["09", "09", "09", "00", "00", "00"]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
side_effect=["00"],
):
assert _read_countdown_digits(
analyser,
"福袋倒计时_分钟_preprocessed",
fallback_picnames=("福袋倒计时_分钟",),
) == "09"
def test_read_countdown_digits_tie_prefers_consistent_preprocessed(self):
analyser = _mk_analyser()
analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["41", "41", "41", "50", "50", "50"]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
return_value="",
):
assert _read_countdown_digits(
analyser,
"福袋倒计时_秒_preprocessed",
fallback_picnames=("福袋倒计时_秒",),
) == "41"
def test_read_countdown_digits_cv_zero_cannot_override_nonzero_majority(self):
analyser = _mk_analyser()
analyser.operation.analyse_pic_digits = MagicMock(
side_effect=["09", "09", "09", "", "", ""]
)
with patch(
"douyin.fudai.douyin_fudai_core_pkg.ocr_tasks._cv_detect_two_zero_digits",
side_effect=["00"],
):
assert _read_countdown_digits(
analyser,
"福袋倒计时_分钟_preprocessed",
fallback_picnames=("福袋倒计时_分钟",),
) == "09"
def test_cv_detect_two_zero_digits_on_current_minute_crop(self):
assert _cv_detect_two_zero_digits("福袋倒计时_分钟") in ("", "00")
# ============================================================
# ocr_value
+5
View File
@@ -119,6 +119,11 @@ class TestSpecificPaths:
os.path.join(PROJECT_ROOT, "run_cli.exe")
]
def test_bundled_adb_path_uses_project_root(self):
assert path_config.get_bundled_adb_path() == os.path.join(
PROJECT_ROOT, "platform-tools", "adb.exe"
)
# ============================================================
# 路径间不应互相重复
@@ -60,3 +60,27 @@ def test_invalid_countdown_text_is_rejected_by_filter_layer():
skip, reason = should_skip_fudai_by_config(analyser, detail)
assert skip is True
assert reason == "countdown_invalid"
def test_missing_countdown_text_does_not_log_default_sixty_seconds():
analyser = _mk_analyser()
now = time.time()
only_tuple = ("福袋", "", 10, 1, 999.0, (now, now, None))
with patch(
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.read_fudai_detail_once",
return_value=("ok", only_tuple, {}),
), patch(
"douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries.validate_fudai_detail",
return_value=(True, "ok"),
):
read_fudai_detail_with_retries(
analyser=analyser,
fudai_x=0,
read_once_callback=None,
close_detail_callback=None,
ensure_open_callback=None,
)
log_text = "\n".join(str(c) for c in analyser._log_kv.call_args_list)
assert "倒计时=未识别,剩余59秒" not in log_text
+21
View File
@@ -89,6 +89,27 @@ def test_similar_long_titles_are_merged_to_smaller_pos():
assert a._room_pos_to_title_map[3]["merged_positions"] == [3, 4]
def test_recommend_tab_title_is_not_recorded_to_room_map():
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
a = _mk_analyser()
a.room_pos = 15
a.current_room_title = "购精选商城"
a.current_room_title_raw = "购·精选·商城."
a._room_title_identified_positions = {15}
a._room_pos_to_title_map = {13: {"title": "聚亿奢首", "title_raw": "聚亿奢首"}}
with patch.object(mod, "_dump_room_pos_map_to_state", return_value=None):
consumed = mod.record_room_title_and_pos(a)
assert consumed is False
assert 15 not in a._room_pos_to_title_map
assert str(15) not in a._room_pos_to_title_map
assert a._room_pos_to_title_map[13]["title"] == "聚亿奢首"
assert a.current_room_title == ""
assert a.current_room_title_raw == ""
def test_merge_room_info_keeps_explicit_no_fudai_state():
from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod
@@ -33,6 +33,25 @@ def _has_log_reason(analyser, reason: str) -> bool:
return False
def test_reservation_button_fallback_blocks_insufficient_time_text():
from douyin.reservation.douyin_reservation_handler_pkg import direct_attend
analyser = _mk_analyser()
item = {
"button_text": "抽奖剩余时间不足,下次再来参与吧",
"button_status": "可以参与",
}
ok, button_text, button_status = direct_attend._reservation_button_fallback_is_actionable(
analyser,
item,
)
assert ok is False
assert button_text == "抽奖剩余时间不足,下次再来参与吧"
assert button_status == "可以参与"
def test_direct_attend_logs_fixed_success_marker():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
@@ -121,6 +140,40 @@ def test_direct_attend_uses_short_open_budget_for_both_scans():
assert call.kwargs["max_wait_seconds"] == 2.25
def test_direct_attend_extends_first_icon_scan_when_time_budget_allows():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.fudai_icon_max_wait_seconds = 7.0
analyser.reservation_direct_attend_open_max_wait_seconds = 2.5
analyser.reservations[0]["future_ts"] = time.time() + 90.0
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[False, True, False],
) as finder, patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(True, {"mock": True}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
assert finder.call_count == 3
assert finder.call_args_list[0].kwargs["max_wait_seconds"] == 2.5
assert finder.call_args_list[1].kwargs["max_wait_seconds"] == 4.5
assert finder.call_args_list[2].kwargs["max_wait_seconds"] == 2.5
analyser.operation.click.assert_called()
assert not _has_log_reason(analyser, "fudai_icon_not_found")
def test_direct_attend_logs_fixed_failure_marker_when_button_still_exists():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
@@ -309,3 +362,66 @@ def test_direct_attend_uses_reservation_text_fallback_when_button_pixel_misses()
analyser.operation.click.assert_called()
assert _has_log_reason(analyser, "reservation_button_text_fallback_click_sent")
def test_direct_attend_uses_button_ocr_fallback_only_after_pixel_and_cache_miss():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.reservations[0]["button_text"] = "加入购物粉丝团并关注主播"
analyser.reservations[0]["button_status"] = "需要加入粉丝团"
analyser.y_pianyi = 0
analyser.cut_pic = MagicMock(return_value=None)
analyser.operation.analyse_pic_word = MagicMock(return_value="一键发表评论")
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
), patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(False, {"reason": "red_ratio_below_threshold"}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
analyser.cut_pic.assert_called_once()
analyser.operation.analyse_pic_word.assert_called_once()
analyser.operation.click.assert_called()
assert _has_log_reason(analyser, "reservation_button_ocr_fallback_click_sent")
def test_direct_attend_does_not_use_button_ocr_fallback_when_pixel_hits():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.cut_pic = MagicMock(return_value=None)
analyser.operation.analyse_pic_word = MagicMock(return_value="一键发表评论")
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
), patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(True, {"mock": True}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
analyser.cut_pic.assert_not_called()
analyser.operation.analyse_pic_word.assert_not_called()
+43
View File
@@ -160,6 +160,49 @@ class TestSortReservationsInplace:
assert id(items) == original_id
class TestSelectReservationTargetForWindow:
def test_selects_highest_value_when_windows_overlap(self):
from douyin.reservation.reservation_logic.helpers import (
_select_reservation_target_for_window,
)
items = [
{"future_ts": 100.0, "prize_value_yuan": 200.0, "created_ts": 1.0},
{"future_ts": 105.0, "prize_value_yuan": 900.0, "created_ts": 2.0},
{"future_ts": 110.0, "prize_value_yuan": 300.0, "created_ts": 3.0},
]
idx, item = _select_reservation_target_for_window(
items,
now_ts=95.0,
dynamic_ahead_for_item=lambda _item: 10.0,
poll_before=10.0,
)
assert idx == 1
assert item["prize_value_yuan"] == 900.0
def test_keeps_earliest_when_no_window_reached(self):
from douyin.reservation.reservation_logic.helpers import (
_select_reservation_target_for_window,
)
items = [
{"future_ts": 100.0, "prize_value_yuan": 200.0, "created_ts": 1.0},
{"future_ts": 105.0, "prize_value_yuan": 900.0, "created_ts": 2.0},
]
idx, item = _select_reservation_target_for_window(
items,
now_ts=50.0,
dynamic_ahead_for_item=lambda _item: 10.0,
poll_before=10.0,
)
assert idx == 0
assert item["future_ts"] == 100.0
class TestComputeDynamicAhead:
def test_includes_runtime_capture_and_verify_budget(self):
class _A:
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more