优化:调整代码格式,增强可读性

This commit is contained in:
Your Name committed 2026-01-23 15:29:09 +08:00
1 parent 3b4293365d
commit 4903e50ff2
15 files changed
+1968 -539

No files matched your search

+42 -1
View File
@@ -1,35 +1,76 @@
# Copilot 指令(douyin_guaji-main)
## 来自 `docs/完整技术文档.md` 的补充(要点)
- 版本:V4.5(2026-01-18)。本文件为实现细节与验证命令的权威来源,agent 在执行重大改动前请核对文档中的“验证要点”。
- 配置优先级:代码默认 < `config/config.json` < 环境变量 < CLI 参数(`run_cli.py` 覆盖最高优先)。
- 截图写入:tmp -> 原子替换(`_safe_replace_file`),注意 Windows 文件锁;外部镜像由 `DISABLE_SCREENSHOT_MIRROR` 控制。
- OCR:优先 EasyOCR,回退 PaddleOCR;支持延迟初始化(`SKIP_OCR_INIT=1`),首次调用按需初始化。
- 日志与时间戳:使用 `douyin/logging/douyin_logging.py` 与 `unified_logger`(毫秒精度),业务日志请用 `analyser._log_kv(...)`。
- 验证脚本:文档提供多个 `python -m py_compile` 与 `inspect` 验证示例,建议把常用验证命令做成 `tools/verify_*.ps1` 便于 CI/本地复现。
## 快速运行 & 关键点概览
- CLI 入口:`run_cli.py`;主调度器:`douyin/core/douyin_fudai.py`(核心类 `fudai_analyse`,主流程见 `run_once_basic()`)。
- 设备/ADB/OCR 层:`Underlying_Operations.py`(优先 EasyOCR,失败回退 PaddleOCR;测试时用 `SKIP_OCR_INIT=1` 跳过 OCR 初始化)。
- 配置与路径:以 `config/config.json` 为准,统一使用 `path_config.py` 提供的路径函数(不要硬编码 `assets/`、`pic/`、`logs/`)。
下面使用简短清单帮助 agent 立即定位常用操作与约定(快速、可执行、可验证)。
## 先从这里入手(入口/主链路)
- CLI 入口:`run_cli.py`;主调度器:`douyin/core/douyin_fudai.py` 的 `fudai_analyse`(`fudai_choujiang()` -> 循环 `run_once_basic()`)。
- 设备/ADB/OCR 兼容层:`Underlying_Operations.py`(OCR:优先 EasyOCR,失败回退 PaddleOCR;可用 `SKIP_OCR_INIT=1` 跳过初始化)。
- 路径与配置:以 `config/config.json` 为准,统一用 `path_config.py` 取路径(不要硬编码 `assets/`、`pic/`、`logs/`)。
- 路径与配置:以 `config/config.json` 为准,统一用 `path_config.py` 取路径(不要硬编码./;; `assets/`、`pic/`、`logs/`)。
## 架构要点(理解模块边界)
- 核心包:`douyin/`;主要分层:`core/`(流程/状态) + `stage/`(阶段诊断) + `handlers/`(截图/弹窗/滑动等操作) + `fudai/`(福袋查找/详情/流程) + `reservation/`(高价值预约/回退校验) + `detection/`(像素/模板检测)。
- 分辨率适配以 1080x2400 为基准:坐标/ROI 一般需要走“缩放/偏移”路径(见 `fudai_analyse` 的分辨率字段与相关 helper)。
- 开发以模块化为主:新功能/修复优先落在 `douyin/*`(业务流程)与 `operations/*`(底层封装);`Underlying_Operations.py` 多为兼容与兜底,避免把新逻辑持续堆进去。
## 配置加载与覆盖优先级(以 config.json 为核心)
- 真实配置文件:`config/config.json`(`path_config.get_config_path()`);GUI/WebGUI 会读写它。
- `douyin/utils/douyin_config.py:ConfigManager.load_config_from_file()` 会把配置写回 analyser;命令行传入的 `needswitch` 会被保留(命令行优先)。
- `run_cli.py` 会在创建 `fudai_analyse()` 后,用 CLI 参数覆盖部分字段(如 `min_prize_value_yuan`、`skip_if_countdown_*`、OCR/模板开关等)。
## 日志与调试图像(排障首选路径)
- 日志初始化:`douyin/logging/douyin_logging.py:configure_logging()`;统一日志能力在 `unified_logger.py`(traceId/MDC/脱敏)。
- 业务日志优先用 `analyser._log_kv(...)`(实现见 `douyin/logging/douyin_logging_wrapper.py`):始终 stdout 可被 GUI 捕获,并带阶段分隔。
- 截图/调试图像:`douyin/handlers/douyin_screenshot_manager.py`(可异步保存;行为日志写入 `logs/actions.log`,路径用 `path_config.get_actions_log_path()`)。
- 排障开关以 `config/config.json` 为准:优先通过 `debug_captures.*` 控制调试图像(enabled/keep_days/max_files/async_save/log_on_complete),环境变量只作为性能/临时诊断手段。
## 状态文件(别改路径/格式)
- 预约队列落盘:`douyin/core/state/reservations.json`(见 `fudai_analyse._reservations_state_path`)。
- 高价值直播间等状态:`state/high_value_rooms.json`(路径见 `path_config.get_high_value_rooms_path()`)。
## 兼容/遗留机制(默认不用,但别误删)
- `run_cli.py` 仍保留 shim + `EXTERNAL_DOUYIN_FUDAI_DIR` 的兼容加载逻辑;本仓库已内置“本地完整版”实现,日常开发以本仓库代码为主。
- `Underlying_Operations.py` 可能会把 `pic/screenshot.png` 镜像到外部目录;如做性能排查可设 `DISABLE_SCREENSHOT_MIRROR=1`。
## 开发约束(本仓库高频踩坑)
- 代码修改规范(硬性):严格 4 空格缩进(禁用 Tab);`try` 必须配 `except/finally`,`if` 必须配对 `else/elif`,`for/while`/`def/class` 块必须完整且缩进正确。
- 修改流程:先理清缩进层级再改;改完做一次语法自检,避免孤立的 `except/else/elif`、括号/引号不配对、冒号后缺缩进块(详见 `docs/完整技术文档.md`)。
- 当前仓库没有可运行的 `pytest` 测试集;常用验证方式是跑 `python run_cli.py ...` 或 GUI/WebGUI,并结合 `logs/` + `pic/` 调试输出定位问题。
## 模块化要点(新代码必读)
- 把业务逻辑放到 `douyin/` 的合适子包,不要把业务代码塞入 `Underlying_Operations.py` 或顶层脚本。举例:
- `douyin/core/`:调度与全局运行状态(全局 orchestrator)
- `douyin/handlers/`:设备交互、截图、弹窗与滑动
- `douyin/fudai/`:福袋查找与参与的业务实现
- `douyin/reservation/`:预约队列与回退校验实现
- `douyin/detection/`:像素/模板/阈值检测算法实现
- 设计原则:单一职责、清晰 API、低耦合。每个新模块应只负责一类功能并导出明确函数/类(例如 `douyin/fudai/my_finder.py` 导出 `find_fudai(analyser, device_id)`)。
- 依赖注入优先:模块应通过参数接收 `operation` 或 `analyser` 实例,避免在模块内直接引用全局单例,便于测试和替换实现。
- 避免在模块导入阶段执行重型副作用(例如初始化 OCR、长时间文件 I/O、启动设备连接)。对重型依赖使用延迟导入或在显式的 init()/start() 中加载。
- 配置与路径使用 `path_config.py` 和 `config/config.json`,不要硬编码路径或阈值;新增配置需在 `config/config.json` 加入默认值并在模块中读取。
- 日志使用 `analyser._log_kv(...)` 或 `unified_logger`,避免无注释的 print。出错时记录上下文(traceId / run id)。
- 在涉及点击/滑动/截图等行为时,应通过 `underlying_operations` 提供的接口调用,不要在高层模块直接调 adb 命令(底层模块可实现 adb 直接调用,但需注明)。
- 新增检测/模板/handler 请放到相应目录并在模块顶部导出 API,补充 `docs/` 中的简短说明并在 `tools/` 提供一个轻量的验证脚本用于手动验证。
- 虽然仓库中没有统一 pytest 测试集,但新增模块应附带小规模验证:可在 `tools/` 下添加 demo 脚本,或通过 `run_cli.py` 的参数提供可触发的测试路径。
- 代码风格与质量:4 空格缩进、类型注解优先、合理的异常处理(不要留下孤立的 except/else/elif)、并在 PR 描述中说明回退策略。
+10 -3
View File
@@ -1531,15 +1531,19 @@ class underlying_operations:
# 否则继续重试
continue
def analyse_pic_word(self, picname, change_color=0, pic_path=None):
def analyse_pic_word(
self, picname, change_color=0, pic_path=None, return_confidence=False
):
"""对指定图片运行 OCR 并返回拼接后的文本结果。
参数:
picname: 用于分类和调试的图片名(如"福袋内容")
change_color: 颜色处理模式,0=保留彩色,1/2=二值化等
pic_path: 可选的图片路径,未提供时通过 `_find_pic_path` 查找
return_confidence: 是否返回置信度信息(默认False,保持向后兼容)
返回:
识别到的文本(字符串),识别失败返回空字符串
如果return_confidence=False: 识别到的文本(字符串),识别失败返回空字符串
如果return_confidence=True: (text, confidence_info) 元组,其中confidence_info是置信度信息字典
"""
if not pic_path:
try:
@@ -1905,7 +1909,10 @@ class underlying_operations:
except Exception:
pass
return text
if return_confidence:
return text, ocr_confidence_info
else:
return text
def analyse_pic_digits(self, picname, change_color=1, pic_path=None):
"""轻量数字OCR识别函数,专门用于识别数字(0-9)。
+4 -3
View File
@@ -29,7 +29,7 @@
"yanghao_fallback_enter_live_x": 540,
"yanghao_fallback_enter_live_y": 1200,
"fudai_find_max_attempts": 99999,
"fudai_icon_max_wait_seconds": 6.0,
"fudai_icon_max_wait_seconds": 6.5,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 10,
"enable_back_on_misses": false,
@@ -139,7 +139,7 @@
"fudai_template_match_enabled": false,
"fudai_template_match_threshold": 0.7,
"lucky_draw_red_ratio_threshold": 0.8,
"shopping_redpacket_red_ratio_threshold": 0.5,
"shopping_redpacket_red_ratio_threshold": 0.2,
"y_pianyi": 0,
"skip_if_countdown_lt_seconds": 5,
"no_attend_timeout_minutes": 30.0,
@@ -206,6 +206,7 @@
"coupon_template_match_threshold": 0.35,
"attend_button_red_ratio_threshold": 0.25,
"fansclub_join_red_ratio_threshold": 0.25,
"shopping_redpacket_ocr_confidence_threshold": 0.35,
"reservation_test_mode": false,
"swipe_duration_ms": 250,
"gui": {
@@ -224,4 +225,4 @@
"high_value_room_revisit_max_age_days": 1,
"swipe_up_start_y": 1200,
"swipe_up_end_y": 600
}
}
+1
View File
@@ -60,6 +60,7 @@ python run_cli.py --device-id <DEVICE_ID> --wait-minutes 0
2. 检查 `pic/` 下的 `screenshot.png` 与裁剪图 (`pic/cut_*`),验证 `福袋价值` 裁剪区域是否为新坐标 (639,1466)-(769,1586)(已在代码中更新)。
## 变更与可检索点
- 2026-01-18: 修复预约更新后的循环问题,添加强制切换标志和关闭详情(`douyin/fudai/douyin_fudai_core.py` 和 `douyin/core/douyin_fudai.py`)。
- 已修改:`douyin/fudai/douyin_fudai_core.py` 中 `value_box` 裁剪坐标改为 `(639, 1466, 769, 1586)`。
- 文档新增:本 AI 摘要(此文件)与 `docs/完整技术文档.md` 的扩充。
+85
View File
@@ -0,0 +1,85 @@
# WiFi ADB 功能使用指南
## 功能概述
WiFi ADB 功能允许您通过WiFi网络连接Android设备进行调试,而不需要USB线缆。这对于远程调试或多设备管理非常有用。
## 为什么需要USB连接?
**重要说明:** Android系统的安全机制要求首次启用WiFi ADB时必须通过USB连接。这是Google为了安全考虑而设计的限制。
### 工作原理:
1. **USB阶段**:通过USB连接发送 `adb tcpip 5555` 命令启用WiFi ADB模式
2. **重启阶段**:设备重启并进入WiFi ADB模式
3. **WiFi阶段**:此后可以通过WiFi连接使用,无需USB线缆
### 好处:
- 设置完成后,设备会出现在"WiFi设备"列表中
- 可以同时管理多台设备
- 无需物理连接,方便远程操作
- 设备重启后自动保持WiFi ADB模式
## 使用方法
### 快速自动连接(推荐)
1. 确保您的Android设备已通过USB连接到电脑
2. 在抖音挂机GUI中点击"WiFi ADB"按钮
3. 在弹出的对话框中选择已连接的设备
4. 点击"自动连接"按钮
5. 系统将自动:
- 启用设备的WiFi ADB模式
- 等待设备重启
- 获取设备IP地址
- 建立WiFi连接
6. 连接成功后,设备将出现在设备列表中
### 手动连接
如果自动连接失败,可以使用手动方式:
1. 选择已连接的USB设备
2. 点击"启用WiFi ADB"按钮(设备将重启)
3. 等待设备重启完成后,输入IP地址
- 如果不知道IP地址,可以再次点击"启用WiFi ADB",系统会尝试自动获取
4. 点击"连接"按钮建立WiFi连接
5. 连接成功后,设备将出现在设备列表中
### 断开连接
1. 在WiFi ADB对话框中输入要断开连接的设备IP地址
2. 点击"断开"按钮
3. 设备将从ADB设备列表中移除
## 注意事项
- 设备和电脑必须在同一个WiFi网络中
- 确保设备已开启开发者选项和USB调试
- 自动连接时设备会重启,请等待重启完成(通常需要1-2分钟)
- 如果自动连接失败,请检查防火墙设置和网络连接
## 故障排除
### 自动连接失败
- 确认设备已正确连接到WiFi网络
- 检查设备电池电量和网络连接稳定性
- 尝试重启设备后重新连接
- 如果多次失败,使用手动连接方式
### 连接失败
- 确认IP地址正确且设备在线
- 检查端口5555是否被占用
- 确认设备和电脑在同一网络
- 尝试重启ADB服务:`adb kill-server && adb start-server`
### 无法获取IP地址
- 确保设备已连接到WiFi网络
- 检查设备网络设置
- 尝试手动输入IP地址
- 确认设备未开启飞行模式
### 设备重启后无法连接
- 等待设备完全启动完成
- 确认WiFi ADB模式仍处于启用状态
- 检查设备网络连接是否正常
- 尝试重新启用WiFi ADB模式
+96 -3
View File
@@ -1,12 +1,13 @@
# 抖音福袋挂机 — 完整技术文档(重构)
版本: V4.4
版本: V4.5
最后更新: 2026-01-18
目标读者: 开发者、维护者、运维与 AI 助手
说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。
-- 变更记录
- 2026-01-18: V4.5 — 修复预约更新后的循环问题,添加强制切换标志防止在同一直播间反复检测。
- 2026-01-18: V4.4 — 修复并行OCR重试导致日志/重试噪音,参与失败自动切换直播间;购物红包像素+OCR复查(非直播间也OCR复查);并行OCR完成后写盘映射表以提升回退校验一致性;预约回退纠偏(方向提示)与二次回退改进;GUI映射表自适应列与新增购物红包阈值配置(GUI暴露)。
- 2026-01-16: V4.3 — 修复GUI回退配置逻辑分离问题,完善预约二次回退机制。
- 2026-01-16: V4.2 — 优化任务数量传递逻辑,统一日志时间戳格式,添加警告日志追踪。
@@ -26,6 +27,7 @@
- 映射表并行OCR写盘:并行 OCR 完成后会将运行时 `analyser._room_pos_to_title_map` 写入状态(调用 `_dump_room_pos_map_to_state`),保证预约回退时使用最新映射(见 `douyin/fudai/douyin_fudai_core.py` 和 `douyin/reservation/douyin_reservation_handler.py`)。
- 预约回退纠偏与二次回退修复:当映射表显示已在目标位置但校验失败时,记录方向提示 `_seek_direction_hint` 并在 `seek_reservation_room` 中执行一次纠偏滑动(上/下),避免二次回退未触发滑动导致定位失败。
- GUI 映射表改进:`gui/gui_app.py` 中映射表现在可垂直扩展(`pack(fill=BOTH, expand=True)`)、自动根据内容自适应列宽,并在刷新后触发列自适应。
- 新增 UI 交互:为避免列过窄导致文字被挤在一起,GUI 新增“显示原始标题”复选框(默认隐藏 `title_raw` 列)可释放列宽;同时支持双击行弹出详情窗口查看完整文本(适用于被截断的 `任务列表` / `福袋内容` 等字段)。
- 取消 SwipeHandler 中的早返回:修复 `douyin/handlers/douyin_swipe_handler.py` 中对 `has_fudai` 的早返回逻辑,确保在有福袋信息时仍然允许上滑切换直播间(避免写盘后被误拦截)。
**验证要点(运行时观察)**:
@@ -79,6 +81,42 @@ PY
如果需要,我可以把这些验证步骤做成独立脚本并加入 `tools/` 供 CI / 本地复现调用。
### 2026-01-18: V4.5 — 预约更新循环修复 ✅
- 修复预约更新后的循环问题:当福袋已被预约过时,`douyin/fudai/douyin_fudai_core.py` 的 `basic_join_decision` 函数会更新预约信息,但之前未设置强制切换标志,导致程序在同一直播间反复检测和参与,形成循环。
- 强制切换标志机制:更新预约后设置 `analyser._just_recorded_reservation = True`,并返回 `False` 触发切换;`douyin/core/douyin_fudai.py` 的 `run_once_basic` 检查该标志并强制调用 `swipe_up_to_next_live`。
- 关闭详情页:更新预约后添加关闭详情页逻辑,避免停留在详情页。
**验证要点(运行时观察)**:
- 日志:更新预约后应有 `"切换直播间"` 记录,无反复 `[福袋查找]` 循环;有 `"已关闭详情(更新预约后)"` 日志。
- 行为:预约更新后立即切换到下一个直播间,避免卡在同一房间。
**快速验证命令(仓库根目录,PowerShell)**:
```powershell
# 语法检查
python -m py_compile douyin/fudai/douyin_fudai_core.py
python -m py_compile douyin/core/douyin_fudai.py
# 检查标志设置
python - <<'PY'
import inspect
import douyin.fudai.douyin_fudai_core as core
source = inspect.getsource(core.basic_join_decision)
print('_just_recorded_reservation set in update branch:', 'analyser._just_recorded_reservation = True' in source and 'return False' in source)
PY
# 检查标志检查
python - <<'PY'
import inspect
import douyin.core.douyin_fudai as main
source = inspect.getsource(main.run_once_basic)
print('flag check and swipe:', '_just_recorded_reservation' in source and 'swipe_up_to_next_live' in source)
PY
```
如果需要,我可以把这些验证步骤做成独立脚本并加入 `tools/` 供 CI / 本地复现调用。
- 概要:修复GUI中滑动重置回退方式与返回键回退的配置逻辑分离问题;完善预约系统中回退校验失败后的二次回退机制,确保能根据映射表重新定位目标直播间;优化滑动重置回退过程中的延迟,从2秒减少到0.1秒以加快回退速度;修复映射表中福袋信息记录缺失问题,确保福袋内容和详情能正确记录到映射表中;新增映射表重复直播间标题检测和去重功能,自动删除重复记录并标记去重信息。
- GUI回退配置逻辑分离:
@@ -462,6 +500,21 @@ text = op.analyse_pic_word(img)
- `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。
- `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。
- `douyin/fudai/douyin_fudai_core.py`:福袋核心逻辑。
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py` 第214行,`fudai_detail_modules/fudai_detail_reader.py` 第15行和第315行。
- `basic_join_decision`:基础版参与决策,根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。调用位置:`douyin/core/douyin_fudai.py` 第3127行和第3721行。
- `attend_choujiang`:点击参与抽奖。调用位置:`douyin/core/douyin_fudai.py` 第2892行,`douyin/core/fudai_modules/fudai_main_logic.py` 第223行,以及文件内多处。
- `check_lucky_draw_result`:判定福袋抽奖的结果(简化)。统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr),不再对弹窗文字或其它区域进行OCR识别。返回:1='我知道了', 2='立即领取奖品', False=未识别。调用位置:文件内第3913行。
- `check_have_reward_notice_confirm`:判断是否有领奖的二次确认提醒。调用位置:文件内第3937行。
- `get_reward`:中奖后领奖然后返回。调用位置:无外部调用。
- `douyin/utils/douyin_utils.py`:通用工具函数。
- `normalize_countdown_text`:对福袋倒计时类 OCR 文本做标准化,抽离自 douyin_fudai.py,方便复用与单元测试。调用位置:`douyin/utils/douyin_text_utils.py` 第12行和第56行。
- `extract_prize_value_yuan`:从 OCR 文本中抽取奖品价值金额(元),抽离自 douyin_fudai.py。调用位置:`douyin/fudai/core/fudai_detail_reader.py` 第16行和第1174行,`douyin/fudai/douyin_fudai_core.py` 第11行和第1965行,`douyin/utils/douyin_text_utils.py` 第12行和第65行。
- `douyin/stage/douyin_stage.py`:阶段诊断逻辑。
- `diagnose_stage_from_current_screen`:完整抽離自 `douyin_fudai.fudai_analyse._diagnose_stage_from_current_screen`。日志輸出已從 print 改為 _log_kv,方便結構化查看。当前模式:优先使用像素检测,OCR检测已暂时关闭用于测试像素检测精准度。注意:此函数复杂度较高,包含多个检测步骤和条件分支,这是设计上的权衡。调用位置:`douyin/core/douyin_flow_control.py` 第393行,`douyin/reservation/douyin_reservation_logic.py` 第812行和第846行,`douyin/stage/douyin_stage_handler.py` 第44行。
**最近修改要点(2026-01-18)**:
- `douyin/fudai/core/fudai_attend.py`:修复并行OCR重试导致的无限重试日志,增加重试计数 `click_times` 及短延时。
- `douyin/core/douyin_fudai.py`:在 `_handle_in_fudai_detail` 中增加连续参与失败阈值逻辑,超过阈值可关闭详情并切换直播间(若 `needswitch` 为 True)。
@@ -478,6 +531,46 @@ text = op.analyse_pic_word(img)
在文档中引用这些文件并包含小示例会帮助维护者快速定位实现点。
### GUI — 映射表组件(`gui/components/mapping_table.py`)
概述:该组件在 GUI 中以标签页形式展示运行时的房间-位置映射(来源 `douyin/core/state/room_pos_map.json`),供人工核验与调试。
- 入口函数:`create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Frame`
- 调用位置:`gui/gui_app.py` 在创建 Notebook 页时直接 import 并挂载(参见 `create_mapping_tab(...)` 的使用)。
- 数据源:优先读取项目根下或 `douyin/core/state/room_pos_map.json`;若不存在会尝试 `douyin/state/room_pos_map.json` 与若干备份路径;同时读取 `reservations.json` 以标记已预约项。
- 显示与交互要点:
- 使用 Canvas + 内嵌 `inner_frame` 的卡片式布局渲染每条记录;每个字段独占一行(标题/原始标题/更新时间/已预约/有福袋/价值/参与人数/份数/倒计时/按钮/任务列表/福袋内容),满足“每一个内容换一行”的需求。
- 为了更合理使用横向空间,组件根据 canvas 宽度自动计算列数(默认最多 3 列),并把卡片以 grid 网格方式分列显示;每列计算独立的 wraplength 以保证文字在列内换行。
- 控件:自动刷新开关(默认 5s)、手动刷新按钮、显示原始标题开关、搜索框 + 回车触发、清除按钮、复制选中条目按钮与状态提示。
- 鼠标交互:卡片支持单击选中(高亮)、双击弹出详情窗口、键入搜索过滤;Canvas 区域绑定鼠标滚轮(enter/leave 动态绑定),支持 Windows/macOS/Linux 的滚轮和 X11 Button-4/5。
- 样式与可配置点:
- 字体:基础为等宽字体(Consolas),当前实现较紧凑的尺寸(base 10 / title 12 / meta 9 / body 10),可在组件内部调整。
- 颜色/间距:卡片背景、hover 背景与选中背景有明确区分;卡片间距与分隔线已调整为更紧凑的视觉。
- 实现细节(注意点):
- 组件会在刷新前保存当前的 canvas.yview(),刷新完后尝试恢复到之前位置,避免刷新回到顶部的问题。
- 旧实现中曾使用 Text 区索引定位(`mapping_text`),当前实现已移除该依赖,事件均基于卡片索引与 `last_selected_entry` 管理。若你在调试中看到与 `mapping_text` 相关的 trace,请清理缓存/重启 GUI。
- 为避免过窄列导致被挤在一起,组件提供“显示原始标题”开关,开启后会增加行数但释放列宽以避免截断。
- 调试 / 验证步骤:
1. 在项目根运行 GUI:
```powershell
python gui\gui_app.py
```
2. 打开“运行时映射表”页,验证:每字段是否独占一行、卡片列数是否随窗口宽度变化、滚动条与滚轮是否正常、双击详情与复制按钮是否工作。
3. 若需要查看源文件:`douyin/core/state/room_pos_map.json`(包含 timestamp 字段,可用于同步更新时间)。
- 已知限制与后续优化:
- 当前列数上限为 3(实现中可调),在极宽窗口下可以适当增加列数或使用自适应列宽策略;
- 卡片圆角/阴影等更高级视觉需要额外绘制或使用第三方皮肤(如 ttkbootstrap),可作为后续优化项;
- UI 国际化与主题适配(浅色/深色)尚未全面支持,建议在统一主题体系下再做统一调整。
***
## 运行流程概览(精简)
1. `run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
@@ -3972,7 +4065,7 @@ if process_reservation_attend_window(
- **设计模式**: Mixin组合模式
- **主要方法**:
- `fudai_choujiang()`: 主循环入口
- `run_once_basic()`: 单次循环执行
- `run_once_basic()`: 单次循环执行,包含所有核心逻辑;检查 `_just_recorded_reservation` 标志并强制切换直播间
- `load_config()`: 加载配置
#### 11.1.2 `douyin_flow_control.py` - 流程控制
@@ -4030,7 +4123,7 @@ if process_reservation_attend_window(
- **职责**: 福袋核心业务逻辑
- **主要函数**:
- `get_fudai_contain()`: 获取福袋信息(并行OCR)
- `basic_join_decision()`: 判断是否参与
- `basic_join_decision()`: 判断是否参与;支持预约更新后的强制切换(设置 `_just_recorded_reservation` 标志并返回 `False` 触发切换,避免循环)
#### 11.4.2 `douyin_fudai_detail.py` - 福袋详情处理
+18
View File
@@ -5859,6 +5859,24 @@ def basic_join_decision(
analyser._just_recorded_reservation = True
except Exception:
pass
# 更新预约后关闭详情页,避免影响后续预约回退
try:
analyser.click(500, 470)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser._log_kv(
"参与",
"basic_join_decision:已关闭详情(更新预约后)",
action="close_detail_after_reservation_update",
)
except Exception:
pass
# 更新预约后返回False,触发切换直播间
return False
+22 -7
View File
@@ -1760,8 +1760,8 @@ def process_reservation_attend_window(
# 使用配置项控制等待时间,默认3秒(确保直播间标题等信息加载完成)
try:
verify_wait_seconds = float(
getattr(analyser, "reservation_back_verify_wait_seconds", 3.0)
or 3.0
getattr(analyser, "reservation_back_verify_wait_seconds", 5.0)
or 5.0
)
if verify_wait_seconds < 0.1:
verify_wait_seconds = 0.1 # 最小0.1秒
@@ -1773,17 +1773,32 @@ def process_reservation_attend_window(
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退后等待直播间加载完成",
"[预约] process_reservation_attend_window:回退后等待直播间加载完成(开始等待)",
verify_wait_seconds=verify_wait_seconds,
level="DEBUG",
level="INFO",
)
except Exception:
pass
# 记录等待开始时间,并在等待结束后写入实际等待时长,便于验证配置是否生效
wait_start_ts = time.time()
try:
analyser.operation.delay(verify_wait_seconds)
except Exception:
time.sleep(verify_wait_seconds)
try:
analyser.operation.delay(verify_wait_seconds)
except Exception:
time.sleep(verify_wait_seconds)
finally:
waited = time.time() - wait_start_ts
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:回退等待完成",
expected_wait_seconds=verify_wait_seconds,
waited_seconds=round(waited, 3),
level="INFO",
)
except Exception:
pass
try:
try:
+50 -7
View File
@@ -379,15 +379,30 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
name_rp0 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp0, 0) or ""
ocr_result = analyser.operation.analyse_pic_word(
name_rp0, 0, return_confidence=True
)
if isinstance(ocr_result, tuple):
redpacket_text, ocr_confidence_info = ocr_result
else:
redpacket_text = str(ocr_result or "")
ocr_confidence_info = None
ocr_elapsed = (time.time() - ocr_start) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式0",
耗时毫秒=ocr_elapsed,
文本长度=len(redpacket_text),
文本预览=redpacket_text[:50] if redpacket_text else "",
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
redpacket_keywords = ("购物红包", "邀你抢", "抢红包")
@@ -402,10 +417,14 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
name_rp1 = preprocess_for_ocr(
analyser, "診斷購物紅包-非直播间复查"
)
redpacket_text = str(
analyser.operation.analyse_pic_word(name_rp1, 1)
or ""
ocr_result_1 = analyser.operation.analyse_pic_word(
name_rp1, 1, return_confidence=True
)
if isinstance(ocr_result_1, tuple):
redpacket_text, ocr_confidence_info = ocr_result_1
else:
redpacket_text = str(ocr_result_1 or "")
ocr_confidence_info = None
ocr_elapsed_1 = (time.time() - ocr_start_1) * 1000
_log(
"步骤2.5[购物红包OCR复查]-OCR模式1",
@@ -414,12 +433,36 @@ def diagnose_stage_from_current_screen(analyser, trigger_reason="unknown"): # t
文本预览=(
redpacket_text[:50] if redpacket_text else ""
),
平均置信度=(
ocr_confidence_info.get("avg_confidence")
if ocr_confidence_info
else None
),
最大置信度=(
ocr_confidence_info.get("max_confidence")
if ocr_confidence_info
else None
),
)
if redpacket_text and any(
# 检查关键词匹配或置信度阈值
has_keyword_match = redpacket_text and any(
kw in redpacket_text for kw in redpacket_keywords
):
)
has_high_confidence = (
ocr_confidence_info
and ocr_confidence_info.get("max_confidence", 0)
>= analyser.shopping_redpacket_ocr_confidence_threshold
)
if has_keyword_match or has_high_confidence:
redpacket_verified = True
_log(
"步骤2.5[购物红包OCR复查]-命中",
关键词匹配=has_keyword_match,
高置信度匹配=has_high_confidence,
阈值=analyser.shopping_redpacket_ocr_confidence_threshold,
)
except Exception as e:
redpacket_elapsed = (time.time() - step_redpacket_ocr_start) * 1000
_log(
+12
View File
@@ -170,6 +170,18 @@ class ConfigManager:
analyser, "shopping_redpacket_red_ratio_threshold", 0.15
)
if "shopping_redpacket_ocr_confidence_threshold" in config:
threshold = float(
config["shopping_redpacket_ocr_confidence_threshold"] or 0.35
)
analyser.shopping_redpacket_ocr_confidence_threshold = max(
0.0, min(1.0, threshold)
)
else:
analyser.shopping_redpacket_ocr_confidence_threshold = getattr(
analyser, "shopping_redpacket_ocr_confidence_threshold", 0.35
)
# 粉丝团等待/点击延迟配置
if "fansclub_click_delay" in config:
analyser.fansclub_click_delay = float(config["fansclub_click_delay"] or 0.6)
+660
View File
@@ -0,0 +1,660 @@
import json
import os
import time
import tkinter as tk
from tkinter import ttk
from typing import Any, List
from datetime import datetime
try:
from . import mapping_utils
except Exception:
try:
import gui.components.mapping_utils as mapping_utils
except Exception:
mapping_utils = None
try:
from ttkbootstrap.scrolled import ScrolledText as TBSrolledText
ScrolledText = TBSrolledText
except Exception:
try:
from tkinter.scrolledtext import ScrolledText
except Exception:
ScrolledText = None
def create_mapping_tab(root: tk.Tk, notebook: ttk.Notebook, cfg: dict) -> ttk.Frame:
"""创建并返回映射表 Tab(文本样式,类似预约队列)"""
mapping_tab = ttk.Frame(notebook)
map_box = ttk.LabelFrame(mapping_tab, text="运行时映射表(文本样式)")
map_box.pack(fill=tk.BOTH, expand=True, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=tk.X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=tk.LEFT)
refresh_btn = ttk.Button(map_ctrl, text="刷新映射表", width=12)
refresh_btn.pack(side=tk.LEFT, padx=(8, 6))
mapping_source_var = tk.StringVar(value="未加载")
ttk.Label(map_ctrl, textvariable=mapping_source_var).pack(side=tk.LEFT, padx=(8, 0))
show_title_raw_var = tk.BooleanVar(value=False)
show_title_raw_chk = ttk.Checkbutton(
map_ctrl, text="显示原始标题", variable=show_title_raw_var
)
show_title_raw_chk.pack(side=tk.LEFT, padx=(8, 6))
mapping_text_box = ttk.Frame(map_box)
mapping_text_box.pack(fill=tk.BOTH, expand=True, padx=10, pady=(6, 10))
# 使用 Canvas + Frame 的卡片式布局以获得更高档的样式和更好的可读性
canvas = tk.Canvas(mapping_text_box, borderwidth=0, highlightthickness=0)
vscroll = ttk.Scrollbar(mapping_text_box, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vscroll.set)
vscroll.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
inner_frame = ttk.Frame(canvas)
window_id = canvas.create_window((0, 0), window=inner_frame, anchor="nw")
def _on_inner_configure(event: object | None = None) -> None:
try:
canvas.configure(scrollregion=canvas.bbox("all"))
except Exception:
pass
def _on_canvas_configure(event: object | None = None) -> None:
try:
canvas.itemconfigure(window_id, width=event.width)
except Exception:
pass
inner_frame.bind("<Configure>", _on_inner_configure)
canvas.bind("<Configure>", _on_canvas_configure)
# 鼠标滚轮支持(进入时绑定,离开时解绑),兼容 Windows/macOS/Linux
def _on_mousewheel(event: object | None = None) -> None:
try:
# Windows / Mac / X11 事件差异处理
if hasattr(event, "delta") and event.delta:
# Windows 和 macOS 返回 delta(macOS 可能需要不同符号)
# 在 Windows 上,event.delta 为 120 的倍数/方向
delta = int(-1 * (event.delta / 120))
if delta == 0:
# fallback for small deltas
delta = -1 if event.delta < 0 else 1
canvas.yview_scroll(delta, "units")
else:
# X11 可能使用 Button-4/Button-5
if getattr(event, "num", None) == 4:
canvas.yview_scroll(-1, "units")
elif getattr(event, "num", None) == 5:
canvas.yview_scroll(1, "units")
except Exception:
pass
def _bind_mousewheel(_: object | None = None) -> None:
try:
# 绑定到 canvas 的所有滚轮事件,以保证在 card 上也能滚动
canvas.bind_all("<MouseWheel>", _on_mousewheel)
canvas.bind_all("<Button-4>", _on_mousewheel)
canvas.bind_all("<Button-5>", _on_mousewheel)
except Exception:
pass
def _unbind_mousewheel(_: object | None = None) -> None:
try:
canvas.unbind_all("<MouseWheel>")
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
except Exception:
pass
try:
canvas.bind("<Enter>", _bind_mousewheel)
canvas.bind("<Leave>", _unbind_mousewheel)
except Exception:
pass
# 字体与样式(调小以适配用户需求)
try:
import tkinter.font as tkfont
base_font = tkfont.Font(family="Consolas", size=10)
title_font = tkfont.Font(family="Consolas", size=12, weight="bold")
meta_font = tkfont.Font(family="Consolas", size=9, slant="italic")
body_font = tkfont.Font(family="Consolas", size=10)
except Exception:
base_font = title_font = meta_font = body_font = None
# 记录每个卡片的 widget 以便选中与复制
mapping_entries_widgets: List[tk.Widget] = []
# 视觉样式变量
normal_bg = "#ffffff"
hover_bg = "#f6fbff"
selected_bg = "#eaf2ff"
# 状态/搜索/复制 控件
mapping_status_var = tk.StringVar(value="")
ttk.Label(map_ctrl, textvariable=mapping_status_var, foreground="#666666").pack(
side=tk.LEFT, padx=(8, 6)
)
search_var = tk.StringVar(value="")
search_entry = ttk.Entry(map_ctrl, textvariable=search_var, width=26)
search_entry.pack(side=tk.LEFT, padx=(8, 6))
ttk.Button(
map_ctrl,
text="清除",
width=6,
command=lambda: (search_var.set(""), _load_mapping_to_view()),
).pack(side=tk.LEFT, padx=(0, 6))
copy_btn = ttk.Button(map_ctrl, text="复制条目", width=10)
copy_btn.pack(side=tk.LEFT, padx=(4, 6))
# 记录最后一次单击选中的条目索引
last_selected_entry = {"idx": None}
# 存储文本块以便双击查看详情
mapping_entries_text: List[str] = []
mapping_entries_start_lines: List[int] = []
def _load_mapping_to_view():
nonlocal mapping_entries_text, mapping_entries_start_lines
# entries_pool 存放解析得到的所有条目文本;mapping_entries_text 用于显示(会在渲染时按过滤更新)
entries_pool: List[str] = []
mapping_entries_text = []
mapping_entries_start_lines = []
all_lines: List[str] = []
# 读取预约队列与映射表(使用 mapping_utils 模块以实现模块化)
try:
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
except Exception:
base_dir = os.getcwd()
# 尝试通过工具模块加载 reservations 信息
reservations_data = {}
try:
if mapping_utils:
reservations_data = mapping_utils.load_reservations(base_dir)
except Exception:
reservations_data = {}
possible_paths = [
os.path.join(base_dir, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
found = False
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
raw = f.read()
try:
parsed = json.loads(raw)
except Exception:
parsed = None
mapping_source_var.set(p)
if not parsed:
all_lines = ["(非JSON,查看原始文件)", raw]
entries_pool = []
else:
try:
if mapping_utils:
entries_pool = mapping_utils.parse_entries(
parsed, show_title_raw_var.get(), reservations_data
)
else:
# fallback to simple parsing: convert dict/list to strings
if isinstance(parsed, dict):
entries_pool = [
"\n".join([f"[{k}] {v}"])
for k, v in parsed.items()
]
else:
entries_pool = [str(parsed)]
# build all_lines for raw view
all_lines = []
for entry in entries_pool:
all_lines.extend(entry.split("\n"))
all_lines.append("")
except Exception:
entries_pool = []
all_lines = []
found = True
break
except Exception:
pass
# 保存当前可见位置(避免刷新后回到顶部)
try:
prev_top = None
try:
v = canvas.yview()
if isinstance(v, (tuple, list)) and len(v) >= 1:
prev_top = float(v[0])
except Exception:
prev_top = None
except Exception:
prev_top = None
# 清空旧卡片
try:
for w in inner_frame.winfo_children():
try:
w.destroy()
except Exception:
pass
mapping_entries_widgets.clear()
except Exception:
pass
# 渲染卡片式条目(每个字段单独一行)
mapping_entries_start_lines = []
mapping_entries_text = []
if found and entries_pool:
filter_key = (search_var.get() or "").strip().lower()
try:
canvas.update_idletasks()
wraplen = max(220, canvas.winfo_width() - 60)
except Exception:
wraplen = 800
# 计算列数以合理分配右边空白区域
try:
canvas.update_idletasks()
canvas_w = canvas.winfo_width() or 800
except Exception:
canvas_w = 800
min_card_w = 300
h_gap = 12
try:
columns = max(1, int((canvas_w + h_gap) / (min_card_w + h_gap)))
except Exception:
columns = 1
# 限制最大列数以避免过窄(可根据实际需求调整)
columns = min(columns, 3)
# 配置列权重
try:
for ci in range(columns):
inner_frame.grid_columnconfigure(ci, weight=1, uniform="col")
except Exception:
pass
placed = 0
for idx, entry in enumerate(entries_pool):
if filter_key and filter_key not in entry.lower():
continue
# 存储用于复制/详情的纯文本
mapping_entries_text.append(entry)
lines = entry.split("\n")
# 卡片容器(更紧凑的间距与更清晰的边界)
try:
card = tk.Frame(
inner_frame,
bg=normal_bg,
bd=0,
highlightthickness=1,
highlightbackground="#e6e6e6",
relief="flat",
)
except Exception:
card = tk.Frame(inner_frame, bg=normal_bg)
# 计算网格位置
row = placed // columns
col = placed % columns
try:
card.grid(row=row, column=col, sticky="nwe", padx=6, pady=4)
except Exception:
try:
card.pack(fill="x", padx=6, pady=4, anchor="n")
except Exception:
pass
# 计算每列可用宽度用于 wraplength
try:
col_total_gap = columns * 12
col_width = max(220, int((canvas_w - col_total_gap) / columns))
card_wraplen = max(160, col_width - 40)
except Exception:
card_wraplen = wraplen
# 标题行(紧凑)
try:
lbl_title = tk.Label(
card,
text=lines[0],
font=title_font,
bg=normal_bg,
fg="#0b3d91",
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
except Exception:
lbl_title = tk.Label(card, text=lines[0], bg=normal_bg)
lbl_title.pack(fill="x", padx=10, pady=(6, 1))
# 其余行逐行显示(meta/body 区分),行间距更小
for li, ln in enumerate(lines[1:], start=1):
try:
if show_title_raw_var.get():
if li in (1, 2, 3):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
if li in (1, 2):
lbl = tk.Label(
card,
text=ln,
font=meta_font,
fg="#555555",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
else:
lbl = tk.Label(
card,
text=ln,
font=body_font,
fg="#222222",
bg=normal_bg,
anchor="w",
justify="left",
wraplength=card_wraplen,
)
lbl.pack(fill="x", padx=10, pady=(0, 1))
except Exception:
try:
tk.Label(card, text=ln, bg=normal_bg).pack(
fill="x", padx=10, pady=(0, 1)
)
except Exception:
pass
# 分隔线
try:
ttk.Separator(card, orient="horizontal").pack(
fill="x", padx=8, pady=(6, 4)
)
except Exception:
pass
mapping_entries_widgets.append(card)
# 绑定点击/双击以及 hover 事件
def _make_bind_handlers(ci: int, cframe: tk.Widget):
def _on_click(e: object | None = None) -> None:
try:
# 取消其他选中并高亮当前
for i, w in enumerate(mapping_entries_widgets):
bg = normal_bg if i != ci else selected_bg
try:
try:
w.configure(**{"bg": bg})
except Exception:
w.configure(**{"background": bg})
except Exception:
pass
for ch in w.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
last_selected_entry["idx"] = ci
except Exception:
pass
def _on_dbl(e: object | None = None) -> None:
try:
content = mapping_entries_text[ci]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
def _on_enter(e: object | None = None) -> None:
try:
# 悬停时改变背景(若已选中则保持选中色)
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else hover_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
def _on_leave(e: object | None = None) -> None:
try:
bg = (
selected_bg
if last_selected_entry.get("idx") == ci
else normal_bg
)
try:
try:
cframe.configure(**{"bg": bg})
except Exception:
cframe.configure(**{"background": bg})
except Exception:
pass
for ch in cframe.winfo_children():
try:
try:
ch.configure(**{"bg": bg})
except Exception:
ch.configure(**{"background": bg})
except Exception:
pass
except Exception:
pass
return _on_click, _on_dbl, _on_enter, _on_leave
on_click, on_dbl, on_enter, on_leave = _make_bind_handlers(
len(mapping_entries_widgets) - 1, card
)
try:
card.bind("<Button-1>", on_click)
card.bind("<Double-1>", on_dbl)
card.bind("<Enter>", on_enter)
card.bind("<Leave>", on_leave)
for child in card.winfo_children():
try:
child.bind("<Button-1>", on_click)
child.bind("<Double-1>", on_dbl)
child.bind("<Enter>", on_enter)
child.bind("<Leave>", on_leave)
except Exception:
pass
except Exception:
pass
placed += 1
else:
mapping_source_var.set("未找到 room_pos_map.json")
try:
tk.Label(
inner_frame, text="未找到映射表文件或无数据", fg="#666666"
).pack(padx=8, pady=8)
except Exception:
pass
# 恢复之前的滚动位置(若可用)
try:
canvas.update_idletasks()
except Exception:
pass
try:
if prev_top is not None:
canvas.yview_moveto(prev_top)
except Exception:
pass
# 刷新后清除选中索引
try:
last_selected_entry["idx"] = None
except Exception:
pass
# 绑定刷新按钮与自动刷新
refresh_btn.config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询
root.after(5000, _maybe_auto_refresh)
# 点击/双击的回退处理:如果用户在卡片外双击或点击,使用最后一次选中项展示详情
def _open_selected_entry_detail(event: object | None = None) -> None:
try:
idx = last_selected_entry.get("idx")
if idx is None:
if mapping_entries_text:
idx = 0
else:
return
try:
content = mapping_entries_text[idx]
except Exception:
content = ""
if not content:
return
win = tk.Toplevel(root)
win.title("条目详情")
try:
if ScrolledText:
st = ScrolledText(win, width=100, height=20)
st.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
st.insert("1.0", content)
st.configure(state="disabled")
else:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
lbl = ttk.Label(win, text=content, justify="left")
lbl.pack(fill=tk.BOTH, expand=True, padx=6, pady=6)
except Exception:
pass
try:
# 在 canvas 上双击会打开当前选中条目的详情(作为卡片双击的补偿)
canvas.bind("<Double-1>", _open_selected_entry_detail)
except Exception:
pass
# 复制选中条目到剪贴板
def _copy_selected_entry() -> None:
try:
idx = last_selected_entry.get("idx")
if idx is None or idx < 0 or idx >= len(mapping_entries_text):
if mapping_entries_text:
content = mapping_entries_text[0]
else:
content = ""
else:
content = mapping_entries_text[idx]
if content:
try:
root.clipboard_clear()
root.clipboard_append(content)
mapping_status_var.set("已复制到剪贴板")
root.after(1800, lambda: mapping_status_var.set(""))
except Exception:
pass
except Exception:
pass
try:
copy_btn.config(command=_copy_selected_entry)
except Exception:
pass
try:
search_entry.bind("<Return>", lambda e: _load_mapping_to_view())
except Exception:
pass
try:
show_title_raw_chk.config(command=_load_mapping_to_view)
_load_mapping_to_view()
except Exception:
pass
return mapping_tab
+216
View File
@@ -0,0 +1,216 @@
import json
import os
from datetime import datetime
from typing import Any, Dict, List, Tuple
def load_reservations(base_dir: str | None = None) -> Dict[int, Any]:
"""加载 reservations.json 并返回以 pos_seen 为键的映射字典。"""
if not base_dir:
try:
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..")
)
except Exception:
base_dir = os.getcwd()
reservations_data: Dict[int, Any] = {}
reservations_paths = [
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "reservations.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "reservations.json"),
]
for res_path in reservations_paths:
try:
if os.path.exists(res_path):
with open(res_path, "r", encoding="utf-8") as f:
raw = f.read()
parsed = json.loads(raw)
if isinstance(parsed, dict) and "queue" in parsed:
for item in parsed["queue"]:
pos = item.get("pos_seen", 0)
try:
if pos:
reservations_data[int(pos)] = item
except Exception:
# pos 可能不可转为 int,跳过
pass
break
except Exception:
# ignore malformed reservation files
pass
return reservations_data
def _format_timestamp(ts: Any) -> str:
try:
return datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
try:
return str(ts)
except Exception:
return "-"
def parse_entries(
parsed: Any,
show_title_raw: bool = False,
reservations_data: Dict[int, Any] | None = None,
) -> List[str]:
"""从解析后的 JSON 数据中生成 entries_pool(每项为多行文本)。
返回值:entries_pool(List[str]),每个字符串为一个条目的多行表示。
"""
if reservations_data is None:
reservations_data = {}
entries_pool: List[str] = []
if not parsed:
return entries_pool
# 如果是字典,按 key 排序(尽可能把纯数字当作数字排序)
if isinstance(parsed, dict):
try:
if "_meta" in parsed:
parsed = dict(parsed)
parsed.pop("_meta", None)
except Exception:
pass
try:
keys = sorted(
parsed.keys(), key=lambda x: int(x) if str(x).isdigit() else x
)
except Exception:
keys = list(parsed.keys())
for k in keys:
try:
v = parsed.get(k, {})
# prepare defaults
title = title_raw = "-"
has_fudai = ""
fudai_content = "-"
task_list = button_text = countdown_text = fudai_value = (
participants
) = copies = "-"
if isinstance(v, dict):
title = (v.get("title", "") or "").strip() or "-"
title_raw = (v.get("title_raw", "") or "").strip() or "-"
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (v.get("fudai_content", "") or "").strip() or "-"
fudai_detail = v.get("fudai_detail")
if isinstance(fudai_detail, dict):
task_list = (
str(fudai_detail.get("task_list") or "").strip() or "-"
)
button_text = (
str(fudai_detail.get("button_text") or "").strip() or "-"
)
fudai_time = (
str(fudai_detail.get("time_text") or "").strip() or "-"
)
fudai_value = (
f"{float(fudai_detail.get('prize_value_yuan') or 0):.2f}"
if fudai_detail.get("prize_value_yuan")
else "-"
)
participants = (
str(fudai_detail.get("participants") or 0)
if fudai_detail.get("participants")
else "-"
)
copies = (
str(fudai_detail.get("copies") or 0)
if fudai_detail.get("copies")
else "-"
)
mm = str(fudai_detail.get("countdown_mm") or "").strip()
ss = str(fudai_detail.get("countdown_ss") or "").strip()
if fudai_time and fudai_time != "-":
countdown_text = fudai_time
elif mm or ss:
if mm.isdigit() and len(mm) == 1:
mm = f"0{mm}"
if ss.isdigit() and len(ss) == 1:
ss = f"0{ss}"
if mm and ss:
countdown_text = f"{mm}:{ss}"
else:
countdown_text = mm or ss
elif (
fudai_detail
and isinstance(fudai_detail, (tuple, list))
and len(fudai_detail) >= 5
):
fudai_time = fudai_detail[1] or "-"
fudai_value = (
f"{fudai_detail[4] or 0:.2f}" if fudai_detail[4] else "-"
)
participants = (
str(fudai_detail[2] or 0) if fudai_detail[2] else "-"
)
copies = str(fudai_detail[3] or 0) if fudai_detail[3] else "-"
countdown_text = fudai_time or "-"
else:
fudai_time = "-"
try:
is_reserved = "✓" if int(k) in reservations_data else ""
except Exception:
is_reserved = ""
else:
# v is likely a list/tuple
try:
title = (v[0] or "").strip() or "-"
except Exception:
title = "-"
try:
title_raw = (v[1] or "").strip() or "-"
except Exception:
title_raw = "-"
is_reserved = ""
except Exception:
title = title_raw = "-"
has_fudai = ""
fudai_content = task_list = countdown_text = fudai_value = (
participants
) = copies = button_text = is_reserved = "-"
# timestamp
try:
ts = v.get("timestamp") if isinstance(v, dict) else None
if not ts and isinstance(v, dict):
fd = v.get("fudai_detail")
if isinstance(fd, dict):
ts = fd.get("timestamp")
updated_text = _format_timestamp(ts) if ts else "-"
except Exception:
updated_text = "-"
entry_lines: List[str] = []
entry_lines.append(f"[位置 {k}] {title}")
if show_title_raw:
entry_lines.append(f"原始标题: {title_raw}")
entry_lines.append(f"更新时间: {updated_text}")
entry_lines.append(f"已预约: {is_reserved}")
entry_lines.append(f"有福袋: {has_fudai}")
entry_lines.append(f"价值(元): {fudai_value}")
entry_lines.append(f"参与人数: {participants}")
entry_lines.append(f"份数: {copies}")
entry_lines.append(f"倒计时: {countdown_text}")
entry_lines.append(f"按钮: {button_text}")
entry_lines.append(f"任务列表: {task_list}")
entry_lines.append(f"福袋内容: {fudai_content}")
entries_pool.append("\n".join(entry_lines))
elif isinstance(parsed, (list, tuple)):
for i, v in enumerate(parsed):
entries_pool.append(str(v))
return entries_pool
+336 -515
View File
@@ -22,10 +22,18 @@ from gui.gui_core import (
Runner,
find_adb_executable,
list_adb_devices,
enable_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
get_device_ip,
auto_connect_wifi_adb,
is_device_wifi_connected,
get_connected_wifi_devices,
read_config,
write_config,
)
from path_config import get_logs_dir
from gui.components.mapping_table import create_mapping_tab
# 导入日志颜色配置模块
try:
@@ -147,6 +155,8 @@ def main():
# 常量兜底:部分主题常量未提供时使用字符串
BOTTOM = "bottom"
# W 常量在部分导入路径中可能不存在,兜底为 'w'(grid sticky 使用)
W = "w"
root.title("抖音福袋挂机 - 可视化控制台")
root.geometry("1400x900") # 增大窗口尺寸,提供更多空间
@@ -362,6 +372,328 @@ def main():
refresh_devices_btn = ttk.Button(top, text="刷新设备", command=refresh_devices)
refresh_devices_btn.pack(side=LEFT, padx=(0, 20))
# WiFi ADB 功能
def open_wifi_adb_dialog():
"""打开WiFi ADB设置对话框"""
dialog = tk.Toplevel(root)
dialog.title("WiFi ADB 设置")
dialog.geometry("500x450")
# 允许用户调整对话框大小,避免窗口内容被裁剪
dialog.resizable(True, True)
dialog.minsize(420, 320)
# 获取设备列表并分类
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]
# 创建设备选择区域
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)
# USB设备选择
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
row=0, column=0, sticky=W, pady=(0, 5)
)
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
usb_combo = ttk.Combobox(
device_frame,
textvariable=usb_device_var,
values=usb_devices,
width=25,
state="readonly" if not usb_devices else "normal",
)
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
# 显示USB设备状态
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
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))
# WiFi设备选择
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
wifi_combo = ttk.Combobox(
device_frame,
textvariable=wifi_device_var,
values=wifi_devices,
width=25,
state="readonly" if not wifi_devices else "normal",
)
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
# 显示WiFi设备状态
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
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))
# IP地址输入区域
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
# 使 IP/端口 输入框随窗口宽度伸缩
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)
)
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")
ttk.Label(ip_frame, text="端口(默认5555):").grid(
row=0, column=1, sticky=W, pady=(0, 5)
)
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")
# 按钮区域
button_frame = ttk.Frame(dialog)
button_frame.pack(fill=X, padx=10, pady=10)
def enable_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
success, msg = enable_wifi_adb(adb_exe, device_id)
on_line(f"[WiFi ADB] {msg}")
if success:
# 尝试获取IP地址
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
on_line(f"[WiFi ADB] 设备IP地址: {ip_msg}")
def connect_wifi():
ip = ip_var.get().strip()
port = port_var.get().strip()
if not ip:
on_line("[WiFi ADB] 请输入IP地址")
return
success, msg = connect_wifi_adb(adb_exe, ip, port)
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog()
def disconnect_wifi():
device_id = wifi_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择WiFi设备")
return
# 从设备ID中提取IP地址
ip_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", device_id)
if not ip_match:
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
return
ip = ip_match.group(1)
success, msg = disconnect_wifi_adb(adb_exe, ip, "5555")
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 重新打开对话框以更新设备列表
dialog.destroy()
open_wifi_adb_dialog()
def auto_connect_wifi():
device_id = usb_device_var.get()
if not device_id:
on_line("[WiFi ADB] 请先选择USB设备")
return
# 显示进度
on_line("[WiFi ADB] 开始自动连接...")
# 创建进度对话框
progress_dialog = tk.Toplevel(dialog)
progress_dialog.title("自动连接中...")
progress_dialog.geometry("300x120")
progress_dialog.resizable(False, False)
ttk.Label(progress_dialog, text="正在自动连接WiFi ADB,请稍候...").pack(
pady=10
)
ttk.Label(progress_dialog, text="设备将会重启,请等待重启完成").pack(
pady=(0, 10)
)
progress_bar = ttk.Progressbar(progress_dialog, mode="indeterminate")
progress_bar.pack(fill=X, padx=20, pady=(0, 20))
progress_bar.start()
def do_auto_connect():
try:
success, msg = auto_connect_wifi_adb(adb_exe, device_id)
progress_dialog.destroy()
on_line(f"[WiFi ADB] {msg}")
if success:
# 刷新设备列表
refresh_devices()
# 尝试获取并显示IP
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if ip_success:
ip_var.set(ip_msg)
# 重新打开对话框以显示新的WiFi设备
dialog.destroy()
open_wifi_adb_dialog()
except Exception as e:
progress_dialog.destroy()
on_line(f"[WiFi ADB] 自动连接异常: {str(e)}")
# 在后台线程中执行自动连接
threading.Thread(target=do_auto_connect, daemon=True).start()
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
is_maximized = False
original_geometry = None
def toggle_maximize():
nonlocal is_maximized, original_geometry
try:
if not is_maximized:
original_geometry = dialog.geometry()
dialog.update_idletasks()
w = int(dialog.winfo_screenwidth() * 0.8)
h = int(dialog.winfo_screenheight() * 0.8)
dialog.geometry(f"{w}x{h}")
is_maximized = True
else:
if original_geometry:
dialog.geometry(original_geometry)
is_maximized = False
except Exception as e:
on_line(f"[WiFi ADB] 切换窗口大小失败: {e}")
def refresh_device_lists():
"""刷新设备列表"""
nonlocal usb_devices, wifi_devices
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]
# 更新USB设备下拉框
usb_combo["values"] = usb_devices
usb_combo["state"] = "readonly" if not usb_devices else "normal"
if usb_devices:
usb_device_var.set(usb_devices[0])
else:
usb_device_var.set("")
# 更新WiFi设备下拉框
wifi_combo["values"] = wifi_devices
wifi_combo["state"] = "readonly" if not wifi_devices else "normal"
if wifi_devices:
wifi_device_var.set(wifi_devices[0])
else:
wifi_device_var.set("")
# 更新状态标签
usb_status_text = (
f"检测到 {len(usb_devices)} 个USB设备"
if usb_devices
else "未检测到USB设备,请确保设备已连接并授权"
)
usb_status_label.config(
text=usb_status_text, foreground="red" if not usb_devices else "green"
)
wifi_status_text = (
f"已连接 {len(wifi_devices)} 个WiFi设备"
if wifi_devices
else "无WiFi设备连接"
)
wifi_status_label.config(
text=wifi_status_text, foreground="blue" if wifi_devices else "gray"
)
on_line("[WiFi ADB] 设备列表已刷新")
# USB设备操作按钮
usb_button_frame = ttk.Frame(button_frame)
usb_button_frame.pack(fill=X, pady=(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))
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)
)
# WiFi设备操作按钮
wifi_button_frame = ttk.Frame(button_frame)
wifi_button_frame.pack(fill=X, pady=(10, 0))
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))
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
side=LEFT
)
# 说明文本
info_text = """重要说明:
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
使用方法:
1. 连接Android设备到电脑(USB)
2. 点击"刷新设备"确保设备被检测到
3. 选择USB设备,点击"自动连接"或手动操作
4. 等待设备重启后即可通过WiFi使用"""
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")
wifi_adb_btn = ttk.Button(top, text="WiFi ADB", command=open_wifi_adb_dialog)
wifi_adb_btn.pack(side=LEFT, padx=(0, 20))
# 配置区(提前读取配置,供后续使用)
cfg = read_config()
@@ -484,7 +816,7 @@ def main():
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
)
reservation_back_verify_wait_seconds_var = tk.DoubleVar(
value=float(cfg.get("reservation_back_verify_wait_seconds", 3.0) or 3.0)
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
)
fudai_find_max_attempts_var = tk.IntVar(
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
@@ -2314,7 +2646,7 @@ def main():
reservation_back_swipe_delay_var.get() or 0
)
cfg2["reservation_back_verify_wait_seconds"] = float(
reservation_back_verify_wait_seconds_var.get() or 3.0
reservation_back_verify_wait_seconds_var.get() or 5.0
)
cfg2["fudai_find_max_attempts"] = int(fudai_find_max_attempts_var.get() or 0)
cfg2["fudai_icon_retry_delay_seconds"] = float(
@@ -2782,519 +3114,8 @@ def main():
notebook.add(realtime_tab, text="实时状态")
notebook.add(ocr_results_tab, text="OCR结果")
notebook.add(win_record_tab, text="中奖记录")
# 将运行时映射表加入右侧 Notebook
mapping_tab = ttk.Frame(notebook)
map_box = ttk.LabelFrame(mapping_tab, text="运行时映射表(包含福袋详情)")
map_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
map_ctrl = ttk.Frame(map_box)
map_ctrl.pack(fill=X, padx=10, pady=(8, 6))
map_auto_refresh_var = tk.BooleanVar(value=True)
ttk.Checkbutton(
map_ctrl, text="自动刷新(5s)", variable=map_auto_refresh_var
).pack(side=LEFT)
ttk.Button(map_ctrl, text="刷新映射表", width=12).pack(side=LEFT, padx=(8, 6))
# 映射内容显示区(表格形式)
mapping_source_var = tk.StringVar(value="未加载")
ttk.Label(map_ctrl, textvariable=mapping_source_var).pack(side=LEFT, padx=(8, 0))
# mapping_tree_box 应该放在 map_box(LabelFrame)内部,
# 否则与控件区的布局会错位,导致列显示挤在一起和滚动行为异常。
mapping_tree_box = ttk.Frame(map_box)
mapping_tree_box.pack(fill=BOTH, expand=True, padx=10, pady=(6, 10))
mapping_tree = ttk.Treeview(
mapping_tree_box,
columns=(
"pos",
"title",
"title_raw",
"has_fudai",
"fudai_content",
"task_list",
"countdown",
"fudai_value",
"participants",
"copies",
"button_text",
"is_reserved",
),
show="headings",
height=12,
)
# 为表头指定对齐,便于阅读;长列允许 stretch 以便在窗口拉伸时扩展
mapping_tree.heading("pos", text="位置", anchor="center")
mapping_tree.heading("title", text="标题", anchor="w")
mapping_tree.heading("title_raw", text="原始标题", anchor="w")
mapping_tree.heading("has_fudai", text="有福袋", anchor="center")
mapping_tree.heading("fudai_content", text="福袋内容", anchor="w")
mapping_tree.heading("task_list", text="任务列表", anchor="w")
mapping_tree.heading("countdown", text="倒计时", anchor="center")
mapping_tree.heading("fudai_value", text="价值(元)", anchor="e")
mapping_tree.heading("participants", text="参与人数", anchor="e")
mapping_tree.heading("copies", text="份数", anchor="e")
mapping_tree.heading("button_text", text="按钮文本", anchor="w")
mapping_tree.heading("is_reserved", text="已预约", anchor="center")
# 优化列宽与伸缩行为:让标题/内容类列随窗口拉伸,数值列保持固定宽度
mapping_tree.column("pos", width=50, anchor="e", stretch=False)
mapping_tree.column("title", width=220, anchor="w", stretch=True)
mapping_tree.column("title_raw", width=220, anchor="w", stretch=True)
mapping_tree.column("has_fudai", width=60, anchor="center", stretch=False)
mapping_tree.column("fudai_content", width=300, anchor="w", stretch=True)
mapping_tree.column("task_list", width=240, anchor="w", stretch=True)
mapping_tree.column("countdown", width=90, anchor="center", stretch=False)
mapping_tree.column("fudai_value", width=90, anchor="e", stretch=False)
mapping_tree.column("participants", width=90, anchor="e", stretch=False)
mapping_tree.column("copies", width=70, anchor="e", stretch=False)
mapping_tree.column("button_text", width=180, anchor="w", stretch=True)
mapping_tree.column("is_reserved", width=70, anchor="center", stretch=False)
mapping_tree.tag_configure("odd", background="#fafafa")
mapping_tree.tag_configure("even", background="#ffffff")
# 自动调整列宽以适应内容(基于文本像素宽度测量)
try:
import tkinter.font as tkfont
def _adjust_mapping_tree_columns(
tree: ttk.Treeview, padding: int = 12, max_width: int = 1200
) -> None:
try:
font = tkfont.Font()
except Exception:
try:
# 回退:创建默认字体
font = tkfont.Font()
except Exception:
font = None
# 最小列宽(与之前的默认宽度保持一致,避免太窄)
min_widths = {
"pos": 50,
"title": 120,
"title_raw": 120,
"has_fudai": 60,
"fudai_content": 180,
"task_list": 160,
"countdown": 90,
"fudai_value": 90,
"participants": 90,
"copies": 70,
"button_text": 140,
"is_reserved": 70,
}
cols = tree["columns"]
for col in cols:
try:
# 获取表头文本
header = tree.heading(col).get("text", str(col))
except Exception:
try:
header = tree.heading(col, "text")
except Exception:
header = str(col)
try:
max_w = font.measure(str(header)) if font else len(str(header)) * 8
except Exception:
max_w = len(str(header)) * 8
# 遍历所有行,找到最大内容宽度
for iid in tree.get_children():
try:
cell = str(tree.set(iid, col) or "")
except Exception:
cell = ""
try:
w = font.measure(cell) if font else len(cell) * 8
except Exception:
w = len(cell) * 8
if w > max_w:
max_w = w
target = int(max(min_widths.get(col, 40), max_w + padding))
if target > max_width:
target = max_width
try:
tree.column(col, width=target)
except Exception:
pass
except Exception:
# tkinter.font 不可用时跳过自动调整
def _adjust_mapping_tree_columns(
tree: ttk.Treeview, padding: int = 12, max_width: int = 1200
) -> None:
return
map_scroll_y = ttk.Scrollbar(
mapping_tree_box, orient="vertical", command=mapping_tree.yview
)
map_scroll_x = ttk.Scrollbar(
mapping_tree_box, orient="horizontal", command=mapping_tree.xview
)
mapping_tree.configure(
yscrollcommand=map_scroll_y.set, xscrollcommand=map_scroll_x.set
)
# 使用 grid 布局使横向/纵向滚动条与 Treeview 精确对齐
mapping_tree_box.grid_rowconfigure(0, weight=1)
mapping_tree_box.grid_columnconfigure(0, weight=1)
mapping_tree.grid(row=0, column=0, sticky="nsew")
map_scroll_y.grid(row=0, column=1, sticky="ns")
map_scroll_x.grid(row=1, column=0, sticky="ew")
# 绑定窗口变化:自动调整列宽以适配内容(节流,避免频繁计算)
mapping_tree_autofit_job = {"id": None}
def _schedule_mapping_tree_autofit(_event: object | None = None) -> None:
try:
job_id = mapping_tree_autofit_job.get("id")
if job_id:
root.after_cancel(job_id)
except Exception:
pass
def _do_adjust() -> None:
try:
_adjust_mapping_tree_columns(mapping_tree)
except Exception:
pass
try:
mapping_tree_autofit_job["id"] = root.after(120, _do_adjust)
except Exception:
_do_adjust()
try:
mapping_tree_box.bind("<Configure>", _schedule_mapping_tree_autofit)
except Exception:
pass
# 加载映射表到表格(尝试多个可能的路径)
def _load_mapping_to_view():
# 清空表格
try:
mapping_tree.delete(*mapping_tree.get_children())
except Exception:
pass
# 加载预约状态(用于检查是否已预约)
reservations_data = {}
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
reservations_paths = [
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "reservations.json"),
os.path.join(
os.getcwd(), "douyin", "core", "state", "reservations.json"
),
]
for res_path in reservations_paths:
try:
if os.path.exists(res_path):
with open(res_path, "r", encoding="utf-8") as f:
res_raw = f.read()
res_parsed = json.loads(res_raw)
if isinstance(res_parsed, dict) and "queue" in res_parsed:
# 提取预约队列中的位置信息
for item in res_parsed["queue"]:
pos = item.get("pos_seen", 0)
if pos:
reservations_data[pos] = item
break
except Exception:
pass
except Exception:
pass
# 优先使用基于项目目录的固定路径,避免不同工作目录导致无法找到状态文件
try:
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
except Exception:
base_dir = os.getcwd()
possible_paths = [
os.path.join(base_dir, "douyin", "core", "state", "room_pos_map.json"),
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
os.path.join(base_dir, "douyin", "state", "room_pos_map.json"),
os.path.join(os.getcwd(), "douyin", "core", "state", "room_pos_map.json"),
]
found = False
row_index = 0
for p in possible_paths:
try:
if os.path.exists(p):
with open(p, "r", encoding="utf-8") as f:
raw = f.read()
try:
parsed = json.loads(raw)
except Exception:
parsed = None
mapping_source_var.set(p)
if not parsed:
# 非JSON或解析错误:在表格中显示原始文本的一行提示
mapping_tree.insert(
"",
"end",
values=(
"-",
"(非JSON,查看原始文件)",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
),
tags=("even",),
)
else:
# 移除元信息
if isinstance(parsed, dict) and "_meta" in parsed:
parsed.pop("_meta", None)
# 按数字顺序插入
try:
keys = sorted(
parsed.keys(),
key=lambda x: int(x) if str(x).isdigit() else x,
)
except Exception:
keys = list(parsed.keys())
for k in keys:
try:
v = parsed.get(k, {})
if isinstance(v, dict):
# 新格式:字典
title = (v.get("title", "") or "").strip() or "-"
title_raw = (
v.get("title_raw", "") or ""
).strip() or "-"
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (
v.get("fudai_content", "") or ""
).strip() or "-"
# 提取福袋详细信息
fudai_detail = v.get("fudai_detail")
task_list = "-"
button_text = "-"
countdown_text = "-"
if isinstance(fudai_detail, dict):
task_list = (
str(
fudai_detail.get("task_list") or ""
).strip()
or "-"
)
button_text = (
str(
fudai_detail.get("button_text") or ""
).strip()
or "-"
)
fudai_time = (
str(
fudai_detail.get("time_text") or ""
).strip()
or "-"
)
fudai_value = (
f"{float(fudai_detail.get('prize_value_yuan') or 0):.2f}"
if fudai_detail.get("prize_value_yuan")
else "-"
)
participants = (
str(fudai_detail.get("participants") or 0)
if fudai_detail.get("participants")
else "-"
)
copies = (
str(fudai_detail.get("copies") or 0)
if fudai_detail.get("copies")
else "-"
)
mm = str(
fudai_detail.get("countdown_mm") or ""
).strip()
ss = str(
fudai_detail.get("countdown_ss") or ""
).strip()
if fudai_time and fudai_time != "-":
countdown_text = fudai_time
elif mm or ss:
if mm.isdigit() and len(mm) == 1:
mm = f"0{mm}"
if ss.isdigit() and len(ss) == 1:
ss = f"0{ss}"
if mm and ss:
countdown_text = f"{mm}:{ss}"
else:
countdown_text = mm or ss
elif (
fudai_detail
and isinstance(fudai_detail, (tuple, list))
and len(fudai_detail) >= 5
):
# fudai_detail结构: (content, time_text, participants, copies, prize_value_yuan, countdown_tuple)
fudai_time = fudai_detail[1] or "-" # time_text
fudai_value = (
f"{fudai_detail[4] or 0:.2f}"
if fudai_detail[4]
else "-"
) # prize_value_yuan
participants = (
str(fudai_detail[2] or 0)
if fudai_detail[2]
else "-"
) # participants
copies = (
str(fudai_detail[3] or 0)
if fudai_detail[3]
else "-"
) # copies
countdown_text = fudai_time or "-"
else:
fudai_time = "-"
fudai_value = "-"
participants = "-"
copies = "-"
countdown_text = "-"
# 检查是否已预约
is_reserved = (
"✓" if int(k) in reservations_data else ""
)
else:
# 兼容旧格式:元组
title = (v[0] or "").strip() or "-"
title_raw = (v[1] or "").strip() or "-"
has_fudai = ""
fudai_content = "-"
fudai_time = "-"
countdown_text = "-"
fudai_value = "-"
participants = "-"
copies = "-"
task_list = "-"
button_text = "-"
is_reserved = (
"✓" if int(k) in reservations_data else ""
)
except Exception:
(
title,
title_raw,
has_fudai,
fudai_content,
task_list,
countdown_text,
fudai_value,
participants,
copies,
button_text,
is_reserved,
) = (
"-",
"-",
"",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
"-",
)
row_tag = "even" if row_index % 2 == 0 else "odd"
mapping_tree.insert(
"",
"end",
values=(
k,
title,
title_raw,
has_fudai,
fudai_content,
task_list,
countdown_text,
fudai_value,
participants,
copies,
button_text,
is_reserved,
),
tags=(row_tag,),
)
row_index += 1
found = True
break
except Exception:
# 忽略单个路径读取错误,尝试下一个候选
pass
# 如果已找到并填充了映射表,尝试自动调整列宽以适配内容
if found:
try:
_schedule_mapping_tree_autofit()
except Exception:
try:
_adjust_mapping_tree_columns(mapping_tree)
except Exception:
pass
if not found:
mapping_source_var.set("未找到 room_pos_map.json")
mapping_tree.insert(
"",
"end",
values=(
"-",
"未找到映射表文件",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
),
tags=("even",),
)
# 绑定刷新按钮与自动刷新
btns = map_ctrl.winfo_children()
if btns and isinstance(btns[-1], ttk.Button):
btns[-1].config(command=_load_mapping_to_view)
def _maybe_auto_refresh():
if map_auto_refresh_var.get():
try:
_load_mapping_to_view()
except Exception:
pass
root.after(5000, _maybe_auto_refresh)
# 启动自动刷新轮询(无害,如果开关关闭不会频繁IO)
root.after(5000, _maybe_auto_refresh)
# 使用模块化组件创建映射表并加入 Notebook
mapping_tab = create_mapping_tab(root, notebook, cfg)
notebook.add(mapping_tab, text="映射表")
# 日志区
+299
View File
@@ -59,6 +59,273 @@ def list_adb_devices(adb_exe: str) -> list[str]:
return re.findall(pattern, text)
def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool:
"""检查设备是否已经在WiFi ADB模式下连接
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID(IP:端口格式)
Returns:
bool: 是否为WiFi连接
"""
if not device_id or not adb_exe:
return False
# 检查device_id是否为IP:端口格式
if ":" in device_id and device_id.split(":")[0].count(".") == 3:
return True
return False
def get_connected_wifi_devices(adb_exe: str) -> list[str]:
"""获取已连接的WiFi ADB设备列表
Args:
adb_exe: ADB可执行文件路径
Returns:
list: WiFi连接的设备ID列表
"""
devices = list_adb_devices(adb_exe)
wifi_devices = []
for device in devices:
if is_device_wifi_connected(adb_exe, device):
wifi_devices.append(device)
return wifi_devices
def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]:
"""启用设备的WiFi ADB调试模式
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 启用TCP/IP模式
proc = subprocess.run(
[adb_exe, "-s", device_id, "tcpip", "5555"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
if proc.returncode == 0:
return True, "WiFi ADB已启用,请等待设备重启完成"
else:
error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "")
return False, f"启用WiFi ADB失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "启用WiFi ADB超时"
except Exception as e:
return False, f"启用WiFi ADB异常: {str(e)}"
def connect_wifi_adb(
adb_exe: str, ip_address: str, port: str = "5555"
) -> tuple[bool, str]:
"""连接到WiFi ADB设备
Args:
adb_exe: ADB可执行文件路径
ip_address: 设备IP地址
port: 端口号,默认5555
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not ip_address:
return False, "ADB路径或IP地址为空"
target = f"{ip_address}:{port}"
# 连接到设备
proc = subprocess.run(
[adb_exe, "connect", target],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
if proc.returncode == 0 and "connected" in output.lower():
return True, f"成功连接到 {target}"
else:
return False, f"连接失败: {output}"
except subprocess.TimeoutExpired:
return False, "连接WiFi ADB超时"
except Exception as e:
return False, f"连接WiFi ADB异常: {str(e)}"
def disconnect_wifi_adb(
adb_exe: str, ip_address: str, port: str = "5555"
) -> tuple[bool, str]:
"""断开WiFi ADB连接
Args:
adb_exe: ADB可执行文件路径
ip_address: 设备IP地址
port: 端口号,默认5555
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not ip_address:
return False, "ADB路径或IP地址为空"
target = f"{ip_address}:{port}"
# 断开连接
proc = subprocess.run(
[adb_exe, "disconnect", target],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
if proc.returncode == 0:
return True, f"成功断开连接 {target}"
else:
return False, f"断开连接失败: {output}"
except subprocess.TimeoutExpired:
return False, "断开WiFi ADB超时"
except Exception as e:
return False, f"断开WiFi ADB异常: {str(e)}"
def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
"""获取设备的IP地址
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
Returns:
tuple: (成功否, IP地址或错误消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 获取网络接口信息
proc = subprocess.run(
[adb_exe, "-s", device_id, "shell", "ip", "route"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=10,
)
if proc.returncode == 0:
# 解析输出获取IP地址
lines = proc.stdout.strip().split("\n")
for line in lines:
if "src" in line:
parts = line.split()
for part in parts:
if part.count(".") == 3: # IP地址格式
return True, part
return False, "无法从设备获取IP地址"
else:
error_msg = (proc.stdout or "") + "\n" + (proc.stderr or "")
return False, f"获取IP地址失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "获取设备IP超时"
except Exception as e:
return False, f"获取设备IP异常: {str(e)}"
def auto_connect_wifi_adb(
adb_exe: str, device_id: str, max_attempts: int = 3
) -> tuple[bool, str]:
"""自动启用WiFi ADB并连接设备
Args:
adb_exe: ADB可执行文件路径
device_id: 设备ID
max_attempts: 最大尝试次数
Returns:
tuple: (成功否, 消息)
"""
try:
if not adb_exe or not device_id:
return False, "ADB路径或设备ID为空"
# 步骤1: 启用WiFi ADB
enable_success, enable_msg = enable_wifi_adb(adb_exe, device_id)
if not enable_success:
return False, f"启用WiFi ADB失败: {enable_msg}"
# 等待设备重启
import time
time.sleep(3) # 等待3秒让设备开始重启
# 步骤2: 尝试多次获取IP并连接
for attempt in range(max_attempts):
# 等待设备重启完成
wait_time = 5 + attempt * 2 # 逐渐增加等待时间
time.sleep(wait_time)
# 获取IP地址
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
if not ip_success:
if attempt == max_attempts - 1:
return False, f"获取IP地址失败: {ip_msg}"
continue
ip_address = ip_msg
# 提取纯 IPv4 地址(有些设备返回类似 10.0.0.0/8 的网络)
m = re.search(r"(\d+\.\d+\.\d+\.\d+)", ip_address)
if m:
ip_address = m.group(1)
# 尝试连接
connect_success, connect_msg = connect_wifi_adb(adb_exe, ip_address)
if connect_success:
return True, f"自动连接成功! IP: {ip_address}"
if attempt == max_attempts - 1:
return False, f"连接失败: {connect_msg}"
return False, "自动连接超时,请稍后重试"
except Exception as e:
return False, f"自动连接异常: {str(e)}"
def read_config() -> dict:
if not os.path.exists(CONFIG_PATH):
return {}
@@ -1074,6 +1341,38 @@ class Runner:
"[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH"
)
# 如果用户指定了 device_id,但当前 adb 列表中没有该设备,则尝试回退到任意可用设备
try:
if getattr(params, "device_id", None):
try:
available = list_adb_devices(adb_exe)
except Exception as _:
available = []
if params.device_id not in available:
if available:
fallback = available[0]
self._emit_line(
f"[警告] 配置的 device_id '{params.device_id}' 当前不可见,自动改用 '{fallback}'"
)
# 将 cmd 中的 --device-id 参数替换为 fallback
try:
i = cmd.index("--device-id")
if i + 1 < len(cmd):
cmd[i + 1] = fallback
except ValueError:
# 没有找到 --device-id 则追加
cmd += ["--device-id", fallback]
else:
# 没有任何设备在线,提示并中止启动
self._emit_line(
f"[错误] 配置的 device_id '{params.device_id}' 不在线,且未检测到其它 adb 设备。请连接设备或指定正确的 device-id。"
)
raise RuntimeError("没有可用的 adb 设备")
except Exception as e:
# 仅记录告警,不阻塞后续的调试信息(启动进程时仍可能失败)
self._emit_line(f"[警告] 检查可用 adb 设备时发生异常: {e}")
try:
p = subprocess.Popen(
cmd,
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""
工具脚本:自动将通过 USB 连接的设备切换到 WiFi ADB 并建立连接。
用法示例:
python tools/auto_connect_wifi_adb.py --all
python tools/auto_connect_wifi_adb.py --device MB75DEFQZHZTGMLJ
该脚本依赖仓库中的 `gui.gui_core` 中的 ADB 辅助函数(如 `auto_connect_wifi_adb`)。
"""
import argparse
import sys
import os
from typing import List
# 当从 tools 目录直接运行脚本时,Python 的 sys.path[0] 会是 tools/,需要把项目根目录加入路径
this_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(this_dir, ".."))
if project_root not in sys.path:
sys.path.insert(0, project_root)
try:
from gui.gui_core import (
find_adb_executable,
list_adb_devices,
get_connected_wifi_devices,
auto_connect_wifi_adb,
)
except Exception as e:
print(f"无法导入 gui.gui_core: {e}", file=sys.stderr)
sys.exit(2)
def choose_targets(adb_exe: str, device_arg: str | None, all_flag: bool) -> List[str]:
devices = list_adb_devices(adb_exe)
wifi = get_connected_wifi_devices(adb_exe)
usb_devices = [d for d in devices if d not in wifi]
if device_arg:
if device_arg not in devices:
raise ValueError(f"指定的设备 {device_arg} 未在 adb 设备列表中: {devices}")
return [device_arg]
if all_flag:
return usb_devices
# 默认行为:如果只有一个 USB 设备则选择它;否则提示用户
if len(usb_devices) == 1:
return [usb_devices[0]]
if len(usb_devices) == 0:
return []
raise ValueError(
"检测到多个 USB 设备,请使用 --device 指定或者加上 --all 来对所有设备同时尝试"
)
def main():
parser = argparse.ArgumentParser(description="自动启用并连接 WiFi ADB 的工具脚本")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--device", help="指定要自动连接的设备ID(adb serial)")
group.add_argument(
"-a", "--all", action="store_true", help="对所有检测到的 USB 设备尝试自动连接"
)
parser.add_argument(
"--max-attempts",
type=int,
default=3,
help="每台设备尝试获取 IP 和连接的最大次数(默认3)",
)
args = parser.parse_args()
adb_exe = find_adb_executable()
if not adb_exe:
print(
"未找到 adb 可执行文件,请安装 platform-tools 或确保 adb 在 PATH 中",
file=sys.stderr,
)
sys.exit(2)
try:
targets = choose_targets(adb_exe, args.device, args.all)
except ValueError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
if not targets:
print("未检测到可用于自动连接的 USB 设备(或指定的设备不在列表中)")
sys.exit(0)
print(f"即将对 {len(targets)} 台设备尝试自动连接: {targets}")
overall_ok = True
for dev in targets:
print("\n-------------------------------")
print(f"开始自动连接设备: {dev}")
ok, msg = auto_connect_wifi_adb(adb_exe, dev, max_attempts=args.max_attempts)
print(msg)
if not ok:
overall_ok = False
print(f"设备 {dev} 自动连接失败", file=sys.stderr)
else:
print(f"设备 {dev} 已成功通过 WiFi 连接")
if overall_ok:
print("\n所有设备自动连接尝试已完成,全部成功(或至少有一台成功)")
sys.exit(0)
else:
print(
"\n部分设备自动连接失败,请查看上面的错误信息或使用 --device 指定单台设备重试"
)
sys.exit(1)
if __name__ == "__main__":
main()