diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 15a9c43..0a37379 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 描述中说明回退策略。 diff --git a/config/config.json b/config/config.json index d56aeb5..690fdd8 100644 --- a/config/config.json +++ b/config/config.json @@ -8,7 +8,7 @@ "skip_if_countdown_gt_seconds": 118, "reset_after_swipes_enabled": true, "reset_after_swipes": 25, - "reset_after_swipes_action": "swipe", + "reset_after_swipes_action": "back", "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, @@ -33,7 +33,7 @@ "fudai_icon_retry_delay_seconds": 0.1, "fudai_exit_after_misses": 10, "enable_back_on_misses": false, - "fudai_click_wait_seconds": 1.5, + "fudai_click_wait_seconds": 2.0, "fudai_detail_initial_wait_seconds": 0.8, "fudai_detail_verified_wait_seconds": 0.2, "fudai_detail_retry_delay_seconds": 0.5, diff --git a/docs/AI_PROJECT_SUMMARY.md b/docs/AI_PROJECT_SUMMARY.md index 3ead9f9..ac7cbe3 100644 --- a/docs/AI_PROJECT_SUMMARY.md +++ b/docs/AI_PROJECT_SUMMARY.md @@ -60,6 +60,7 @@ python run_cli.py --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` 的扩充。 diff --git a/docs/完整技术文档.md b/docs/完整技术文档.md index bfc8f26..0eb01a9 100644 --- a/docs/完整技术文档.md +++ b/docs/完整技术文档.md @@ -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` - 福袋详情处理 diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index d654e0c..80e189a 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -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 diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index b547646..c18b2ee 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -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: diff --git a/gui/components/mapping_table.py b/gui/components/mapping_table.py new file mode 100644 index 0000000..4bc9ca4 --- /dev/null +++ b/gui/components/mapping_table.py @@ -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("", _on_inner_configure) + canvas.bind("", _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("", _on_mousewheel) + canvas.bind_all("", _on_mousewheel) + canvas.bind_all("", _on_mousewheel) + except Exception: + pass + + def _unbind_mousewheel(_: object | None = None) -> None: + try: + canvas.unbind_all("") + canvas.unbind_all("") + canvas.unbind_all("") + except Exception: + pass + + try: + canvas.bind("", _bind_mousewheel) + canvas.bind("", _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("", on_click) + card.bind("", on_dbl) + card.bind("", on_enter) + card.bind("", on_leave) + for child in card.winfo_children(): + try: + child.bind("", on_click) + child.bind("", on_dbl) + child.bind("", on_enter) + child.bind("", 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("", _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("", 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 diff --git a/gui/components/mapping_utils.py b/gui/components/mapping_utils.py new file mode 100644 index 0000000..25188ff --- /dev/null +++ b/gui/components/mapping_utils.py @@ -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 diff --git a/gui/gui_app.py b/gui/gui_app.py index 7d8ccee..ad048f4 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -26,6 +26,7 @@ from gui.gui_core import ( write_config, ) from path_config import get_logs_dir +from gui.components.mapping_table import create_mapping_tab # 导入日志颜色配置模块 try: @@ -484,7 +485,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 +2315,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 +2783,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("", _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="映射表") # 日志区