Files
douyi_guaji_main/douyin/reservation/douyin_reservation_handler.py
T
Your Name c67f22f76f feat: Refactor and reorganize project structure with new modules and files
- Deleted obsolete files including test scripts and configuration files to streamline the project.
- Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components.
- Updated import paths to reflect the new module structure, enhancing code organization and maintainability.
- Added configuration files and documentation to support the new structure and improve user guidance.
2025-12-28 14:16:40 +08:00

591 lines
25 KiB
Python

from __future__ import annotations
"""
预约管理模块
============
职责:高价值福袋预约相关操作
- 查找预约直播间
- 处理预约直接参与
- 根据标题查找位置
- 记录直播间标题和位置
"""
import time
import difflib
from typing import Any, Optional, Dict
from douyin.fudai import douyin_fudai_detail
from douyin.fudai import douyin_fudai_core
from douyin.reservation import douyin_reservation_logic
from douyin.reservation import douyin_reservation_verify
from douyin.handlers import douyin_swipe_handler
class ReservationHandler:
"""预约处理器:统一管理预约操作"""
@staticmethod # type: ignore[misc]
def find_room_pos_by_title(
analyser: Any, target_title: str, target_title_raw: str = ""
) -> Optional[int]:
"""根据直播间标题在运行时映射表中查找对应的位置。
参数:
analyser: 分析器对象
target_title: 目标标题
target_title_raw: 目标原始标题
返回:
如果找到匹配的位置,返回位置值;否则返回 None
"""
try:
if not target_title and not target_title_raw:
return None
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
if not room_pos_map:
return None
# 规范化目标标题
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( # type: ignore[attr-defined]
target_title
)
else:
target_norm = target_title.strip()
except Exception:
target_norm = target_title.strip()
# 遍历映射表查找匹配的标题
best_match_pos: Optional[int] = None
best_match_score = 0.0
for pos, (recorded_title, recorded_title_raw) in room_pos_map.items():
if not recorded_title and not recorded_title_raw:
continue
# 规范化记录的标题
try:
from douyin.other import douyin_high_value_room
if hasattr(douyin_high_value_room, "_normalize_room_title"):
recorded_norm = douyin_high_value_room._normalize_room_title( # type: ignore[attr-defined]
recorded_title
)
else:
recorded_norm = recorded_title.strip()
except Exception:
recorded_norm = recorded_title.strip()
# 计算匹配度
match_score = 0.0
if target_norm and recorded_norm:
# 完全匹配
if target_norm == recorded_norm:
match_score = 1.0
# 子串匹配
elif target_norm in recorded_norm or recorded_norm in target_norm:
match_score = 0.8
# 使用相似度
else:
try:
match_score = difflib.SequenceMatcher(
None, target_norm, recorded_norm
).ratio()
except Exception:
match_score = 0.0
# 如果匹配度足够高,记录最佳匹配
if match_score > best_match_score and match_score >= 0.6:
best_match_score = match_score
best_match_pos = pos
if best_match_pos is not None:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
target_title=target_title[:50] if target_title else "",
found_pos=best_match_pos,
match_score=round(best_match_score, 3),
recorded_title=(
room_pos_map[best_match_pos][0][:50]
if room_pos_map[best_match_pos][0]
else ""
),
)
except Exception:
pass
return best_match_pos
return None
except Exception as e:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:查找时出错",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
return None
@staticmethod # type: ignore[misc]
def record_room_title_and_pos(analyser: Any) -> None:
"""记录当前直播间的标题和位置到运行时映射表。
用于预约回退校验时验证位置信息。
参数:
analyser: 分析器对象
"""
try:
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
# 读取当前直播间标题
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
)
# 更新 analyser 的属性
try:
analyser.current_room_title = room_title
analyser.current_room_title_raw = room_title_raw
except Exception:
pass
# 记录到映射表
if room_pos not in analyser._room_pos_to_title_map:
analyser._room_pos_to_title_map[room_pos] = (
room_title,
room_title_raw,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 记录直播间标题和位置到运行时映射表",
room_pos=room_pos,
room_title=room_title[:50] if room_title else "",
room_title_raw=(
room_title_raw[:50] if room_title_raw else ""
),
map_size=len(analyser._room_pos_to_title_map),
)
except Exception:
pass
else:
# 如果已存在,更新标题(可能标题有变化)
old_title, old_title_raw = analyser._room_pos_to_title_map[room_pos]
if old_title != room_title or old_title_raw != room_title_raw:
analyser._room_pos_to_title_map[room_pos] = (
room_title,
room_title_raw,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 更新直播间标题和位置到运行时映射表",
room_pos=room_pos,
old_room_title=old_title[:50] if old_title else "",
new_room_title=room_title[:50] if room_title else "",
)
except Exception:
pass
except Exception as e:
# 如果读取标题失败,尝试使用缓存的标题
try:
room_title = str(
getattr(analyser, "current_room_title", "") or ""
)
room_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
)
if room_title or room_title_raw:
analyser._room_pos_to_title_map[room_pos] = (
room_title,
room_title_raw,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 使用缓存标题记录直播间位置到运行时映射表",
room_pos=room_pos,
room_title=room_title[:50] if room_title else "",
error=str(e),
)
except Exception:
pass
except Exception:
pass
except Exception:
pass
@staticmethod # type: ignore[misc]
def seek_reservation_room(analyser: Any, item: Dict[str, Any]) -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
说明:
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
参数:
analyser: 分析器对象
item: 预约记录字典
返回:
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
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]
"预约",
"[预约] _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:
# 已在目标位置,但仍需校验
pass
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]
"预约",
"[预约] _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
delay_s = float(
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
)
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
for _ in range(back_times):
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(analyser)
try:
analyser.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
# 清除标志
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]
"预约",
"[预约] _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
delay_s = float(
getattr(analyser, "reservation_back_swipe_delay", 0.6) or 0.6
)
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
for _ in range(forward_times):
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(analyser)
try:
analyser.operation.delay(delay_s)
except Exception:
time.sleep(delay_s)
# 清除标志
try:
analyser._skip_record_title_during_seek = False
except Exception:
pass
# 回退过程中只执行回退操作,不进行校验
# 校验将在 process_reservation_attend_window 中统一进行,使用映射表中的数据
return True
@staticmethod # type: ignore[misc]
def handle_reservation_direct_attend(analyser: Any) -> None:
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。
参数:
analyser: 分析器对象
"""
start_time = time.time()
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后直接参与:使用预约记录中的详情,跳过OCR识别",
)
except Exception:
pass
# 从预约记录中获取详情信息
if not analyser.reservations or len(analyser.reservations) == 0:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后直接参与:预约队列为空,无法获取详情",
)
except Exception:
pass
# 如果预约队列为空,回退到正常流程
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
first_reservation = analyser.reservations[0]
try:
# 从预约记录中获取信息
content = str(first_reservation.get("content", "") or "")
prize_value_yuan = float(
first_reservation.get("prize_value_yuan", 0.0) or 0.0
)
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
time_text = str(first_reservation.get("time_text", "") or "")
participants = int(first_reservation.get("participants", 0) or 0)
copies = int(first_reservation.get("copies", 0) or 0)
# 检查福袋是否已过期
now_ts = time.time()
poll_before = float(
getattr(analyser, "high_value_fudai_poll_before_seconds", 10.0) or 10.0
)
expired_threshold = future_ts + max(0.0, poll_before) # 开奖时间 + 缓冲时间
if future_ts > 0 and now_ts > expired_threshold:
# 福袋已过期,清除标志并退出
try:
from datetime import datetime
future_str = (
datetime.fromtimestamp(future_ts).strftime("%Y-%m-%d %H:%M:%S")
if future_ts > 0
else "无效"
)
expired_seconds = int(now_ts - expired_threshold)
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后直接参与:福袋已过期,清除标志并退出",
future_ts=int(future_ts),
future_str=future_str,
expired_threshold=int(expired_threshold),
expired_seconds=expired_seconds,
now_ts=int(now_ts),
)
except Exception:
pass
# 清除相关标志
analyser._reservation_back_direct_attend = False
analyser._force_attend_after_reservation_back = False
analyser.queue_full_waiting_at_earliest = False
# 从预约队列中移除过期预约
try:
douyin_reservation_logic.cleanup_expired_reservations(
analyser=analyser,
reservations=analyser.reservations,
write_state_callback=lambda: None, # 暂时不写入,避免重复写入
)
except Exception:
pass
return
# 构造倒计时元组
countdown_start = now_ts
countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0)
# 构造 detail tuple(格式与 read_fudai_detail_once 返回的格式一致)
detail = (
content, # 0: 内容
time_text, # 1: 倒计时文本
participants, # 2: 参与人数
copies, # 3: 份数
prize_value_yuan, # 4: 价值
(countdown_start, countdown_end), # 5: 倒计时元组
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后直接参与:从预约记录构造详情",
content=content[:50] if content else "",
prize_value_yuan=prize_value_yuan,
future_ts=int(future_ts) if future_ts > 0 else 0,
time_text=time_text,
participants=participants,
copies=copies,
)
except Exception:
pass
# 保存详情数据,标记为已读取(用于后续可能的第二次打开)
analyser._last_fudai_detail_tuple = detail
analyser._fudai_detail_first_read = True
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
analyser._current_fudai_future_ts = future_ts
# 直接调用参与决策,跳过详情识别
join_result = douyin_fudai_core.basic_join_decision(analyser, detail)
# 如果参与成功,设置开奖等待状态并从预约队列中移除
if join_result and future_ts > 0:
try:
# 设置开奖等待状态
current_time = time.time()
remain_seconds = max(0, future_ts - current_time)
if remain_seconds > 0:
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts - 13.0
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后参与成功,设置开奖等待状态",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
)
# 设置锁定期,防止过早切换直播间
poll_before = float(
getattr(
analyser, "high_value_fudai_poll_before_seconds", 10.0
)
or 10.0
)
analyser.reservation_focus_until_ts = future_ts + max(
0.0, poll_before
)
# 从预约队列中移除已参与的预约
if analyser.reservations and len(analyser.reservations) > 0:
remaining_reservations = []
for res in analyser.reservations:
try:
res_future_ts = float(res.get("future_ts") or 0.0)
if (
res_future_ts > 0
and abs(res_future_ts - future_ts) <= 5.0
):
# 匹配的预约,移除
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后参与成功,从预约队列中移除该预约",
future_ts=int(res_future_ts),
value_yuan=res.get("prize_value_yuan", 0),
content=(
res.get("content", "")[:50]
if res.get("content")
else ""
),
)
else:
# 保留不匹配的预约
remaining_reservations.append(res)
except Exception:
# 如果解析预约项时出错,保留该项(容错处理)
remaining_reservations.append(res)
if len(remaining_reservations) < len(analyser.reservations):
analyser.reservations = remaining_reservations
# 清除预约回退直接参与标志
analyser._reservation_back_direct_attend = False
analyser.reservation_after_action_pending = False
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后参与成功,设置状态时出错",
error=str(e),
error_type=type(e).__name__,
)
elapsed = time.time() - start_time
try:
analyser._log_kv( # type: ignore[attr-defined]
"流程",
"_handle_reservation_direct_attend完成",
elapsed_seconds=round(elapsed, 2),
join_result=join_result,
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 预约回退后直接参与:从预约记录获取详情时出错,回退到正常流程",
error=str(e),
)
except Exception:
pass
# 如果出错,回退到正常流程
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]