Files
douyin_guaji-main/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py
T
CodexandClaude Opus 4.7 85bd488f66 拆分 douyin_reservation_handler (1314 → 6 个子模块 + 29 行 shim)
把 douyin/reservation/douyin_reservation_handler.py 按职责拆成
douyin/reservation/douyin_reservation_handler_pkg/ 子包:

- find_room (169)       find_room_pos_by_title 按标题查找直播间位置
- record_title (333)    record_room_title_and_pos 记录直播间标题与位置
- seek_room (319)       seek_reservation_room 回退到目标预约直播间
- direct_attend (441)   handle_reservation_direct_attend 预约直接参与
- dump_state (180)      _dump_room_pos_map_to_state 序列化映射到 state 文件
- handler (43)          ReservationHandler 类(薄壳,每个 staticmethod 1 行 forwarding)

策略亮点:原 ReservationHandler 4 个方法都是 @staticmethod 且第一个参数为
analyser,搬出来成 module-level 函数后,类方法变成 1 行 forwarding。
公共 API 100% 保留:ReservationHandler.method(analyser, ...) 完全不需要改。

外部 import 路径不变:
``from douyin.reservation.douyin_reservation_handler import ReservationHandler``
仍可用(原文件改成 29 行 re-export shim)。
- ReservationHandler 5 处外部引用
- find_room_pos_by_title 2 处外部引用
- handle_reservation_direct_attend / _dump_room_pos_map_to_state 各 1 处
全部不需修改。

回归:
- 7 个新文件 + shim compileall 通过
- pytest 353 passed / 1 skipped
- ReservationHandler.find_room_pos_by_title / module-level 函数 / 顶层
  _dump_room_pos_map_to_state 都能正常调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 18:21:40 +08:00

320 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""douyin_reservation_handler_pkg.seek_room - 回退到目标预约直播间。
seek_reservation_room:从当前位置上/下滑动若干次回退到目标直播间,
带超时与失败兜底。
"""
from __future__ import annotations
import csv
import difflib
import json
import os
import time
from typing import Any, Dict, Optional
from douyin.core import path_config
from douyin.fudai import douyin_fudai_detail
from douyin.handlers import douyin_swipe_handler
from douyin.reservation import douyin_reservation_logic
# 错误处理工具占位(与原文件保持兼容降级)
try:
from douyin.reservation.core.reservation_error_utils import (
log_reservation_error,
format_reservation_context,
)
_RESERVATION_ERROR_UTILS_AVAILABLE = True
except ImportError:
def log_reservation_error(*args, **kwargs):
return None
def format_reservation_context(*args, **kwargs):
return {}
_RESERVATION_ERROR_UTILS_AVAILABLE = False
def seek_reservation_room(
analyser: Any, item: Dict[str, Any], operation_type: str = "预约"
) -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
说明:
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
参数:
analyser: 分析器对象
item: 预约记录字典
operation_type: 操作类型,用于日志标识("预约" 或 "高价值房间")
返回:
bool: 是否成功回退到目标直播间
"""
try:
target_pos = int(item.get("pos_seen") or 0)
except Exception:
target_pos = 0
try:
cur_pos = int(getattr(analyser, "room_pos", 0) or 0)
except Exception:
cur_pos = 0
# 计算需要切换的次数和方向
pos_diff = target_pos - cur_pos
moved = False # 标记是否实际执行了滑动操作
try:
max_back = int(
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
)
except Exception:
max_back = 60
# 防止无限循环:最大回退次数限制为100
if max_back > 100:
max_back = 100
if max_back < 0:
max_back = 0
# 获取目标直播间名字
target_room_title = str(item.get("room_title") or "").strip()
target_room_title_raw = str(item.get("room_title_raw") or "").strip()
# 输出目标直播间的位置和标题信息
try:
analyser._log_kv( # type: ignore[attr-defined]
operation_type,
f"[{operation_type}] _seek_reservation_room:开始回退到目标直播间",
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
target_pos=target_pos,
current_room_pos=cur_pos,
target_room_info=(
f"位置={target_pos}, "
f"标题={target_room_title or target_room_title_raw}"
),
)
except Exception:
pass
if pos_diff == 0:
# 已在目标位置:为了避免在校验失败后被误判为“回退成功”,
# 需要额外确认当前直播间标题与目标标题是否匹配;若无法匹配则返回 False。
try:
# 优先使用缓存的标题
cur_title = str(
getattr(analyser, "current_room_title", "") or ""
).strip()
cur_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
).strip()
# 如果缓存为空且有目标标题,尝试重新 OCR 识别当前直播间标题以确认
if not cur_title and (target_room_title or target_room_title_raw):
try:
y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0)
room_title, room_title_raw = (
douyin_fudai_detail.read_live_room_title_core(
analyser, y_pianyi_val
)
)
cur_title = (room_title or "").strip()
cur_title_raw = (room_title_raw or "").strip()
except Exception:
pass
# 规范化并比较标题(尽量使用已有的规范化方法)
try:
from douyin.other import douyin_high_value_room
if hasattr(douyin_high_value_room, "_normalize_room_title"):
target_norm = douyin_high_value_room._normalize_room_title(
target_room_title
)
cur_norm = douyin_high_value_room._normalize_room_title(
cur_title
)
else:
target_norm = (target_room_title or "").strip()
cur_norm = (cur_title or "").strip()
except Exception:
target_norm = (target_room_title or "").strip()
cur_norm = (cur_title or "").strip()
# 如果标题匹配或包含关系视为成功,否则视为失败
if (
target_norm
and cur_norm
and (
target_norm == cur_norm
or target_norm in cur_norm
or cur_norm in target_norm
)
):
try:
analyser._log_kv(
operation_type,
f"[{operation_type}] _seek_reservation_room:已在目标位置且标题匹配,视为回退成功",
target_pos=target_pos,
current_title=cur_title,
)
except Exception:
pass
return True
else:
try:
analyser._log_kv(
operation_type,
f"[{operation_type}] _seek_reservation_room:已在目标位置但标题不匹配,视为回退失败",
target_pos=target_pos,
expected_title=target_room_title,
current_title=cur_title,
)
except Exception:
pass
# 若有方向提示,则执行一次纠偏切换,避免二次回退未触发滑动
try:
direction_hint = str(
item.get("_seek_direction_hint", "")
).lower()
except Exception:
direction_hint = ""
try:
already_done = bool(
item.get("_seek_mismatch_realign_done", False)
)
except Exception:
already_done = False
if direction_hint in ("up", "down") and not already_done:
try:
item["_seek_mismatch_realign_done"] = True
except Exception:
pass
try:
analyser._log_kv(
operation_type,
f"[{operation_type}] _seek_reservation_room:标题不匹配,执行一次纠偏切换",
direction=direction_hint,
target_pos=target_pos,
)
except Exception:
pass
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
try:
if direction_hint == "down":
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(
analyser
)
else:
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(
analyser
)
try:
analyser.operation.delay(0.1)
except Exception:
time.sleep(0.1)
except Exception:
pass
try:
analyser._skip_record_title_during_seek = False
except Exception:
pass
return False
except Exception:
# 若验证流程异常,返回 False 以避免误判
try:
analyser._log_kv(
operation_type,
f"[{operation_type}] _seek_reservation_room:位置相同但验证异常,视为回退失败",
target_pos=target_pos,
)
except Exception:
pass
return False
elif pos_diff < 0:
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
try:
analyser._log_kv( # type: ignore[attr-defined]
operation_type,
f"[{operation_type}] _seek_reservation_room 向上回退(目标在上方)",
back_times=back_times,
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
)
except Exception:
pass
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
# 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成)
for i in range(back_times):
moved = True
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(analyser)
# 只在最后一次滑动后添加短暂延迟,确保页面稳定
if i == back_times - 1 and back_times > 0:
try:
analyser.operation.delay(0.1) # 最后一次滑动后短暂等待
except Exception:
time.sleep(0.1)
# 清除标志
try:
analyser._skip_record_title_during_seek = False
except Exception:
pass
else:
# 目标在下方(target_pos > cur_pos),需要向下切换(增加 room_pos)
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
try:
analyser._log_kv( # type: ignore[attr-defined]
operation_type,
f"[{operation_type}] _seek_reservation_room 向下切换(目标在下方)",
forward_times=forward_times,
current_room_pos=cur_pos,
target_pos=target_pos,
pos_diff=pos_diff,
target_room_title=target_room_title,
target_room_title_raw=target_room_title_raw,
)
except Exception:
pass
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
# 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成)
for i in range(forward_times):
moved = True
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(analyser)
# 只在最后一次滑动后添加短暂延迟,确保页面稳定
if i == forward_times - 1 and forward_times > 0:
try:
analyser.operation.delay(0.1) # 最后一次滑动后短暂等待
except Exception:
time.sleep(0.1)
# 清除标志
try:
analyser._skip_record_title_during_seek = False
except Exception:
pass
# 回退过程中只执行回退操作,不进行校验;校验将在 process_reservation_attend_window 中统一进行。
# 只有在实际执行了滑动(moved=True)时返回 True,避免在未移动时被误判为“回退成功”。
if moved:
# 回退成功后,更新映射表文件以覆盖原本的
try:
_dump_room_pos_map_to_state(analyser)
except Exception:
pass
return bool(moved)