Files
douyi_guaji_main/douyin/reservation/douyin_reservation_handler.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

795 lines
32 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.
from __future__ import annotations
"""
预约管理模块
============
职责:高价值福袋预约相关操作
- 查找预约直播间
- 处理预约直接参与
- 根据标题查找位置
- 记录直播间标题和位置
"""
import time
import difflib
from typing import Any, Optional, Dict
from douyin.fudai import douyin_fudai_detail
from douyin.reservation import douyin_reservation_logic
from douyin.handlers import douyin_swipe_handler
# 导入预约错误处理工具
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):
pass
def format_reservation_context(*args, **kwargs):
return {}
_RESERVATION_ERROR_UTILS_AVAILABLE = False
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:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
target_title=target_title[:50] if target_title else "",
target_title_raw=target_title_raw[:50] if target_title_raw else "",
),
level="WARNING",
stage="根据标题查找位置",
)
else:
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:
mapping_enabled = bool(getattr(analyser, "record_room_title_mapping_enabled", True))
if not mapping_enabled:
return
except Exception:
pass
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
# 记录读取标题失败的错误
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(
room_pos=room_pos,
),
level="WARNING",
stage="读取直播间标题",
)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(),
level="WARNING",
stage="记录直播间标题和位置",
)
else:
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
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
try:
analyser._skip_record_title_during_seek = True
except Exception:
pass
# 执行连续滑动,不在每次滑动后添加延迟(ADB滑动命令本身会等待完成)
for i in range(back_times):
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]
"预约",
"[预约] _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):
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 中统一进行,使用映射表中的数据
return True
@staticmethod # type: ignore[misc]
def handle_reservation_direct_attend(analyser: Any) -> None:
"""预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。
新流程:
1. 直接查找福袋图标并点击
2. 点击后调用阶段检测中的按钮检测进行决策
3. 完成决策后,再点击福袋图标验证参与状态
4. 参与成功后进入开奖倒计时
参数:
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:
# 从预约记录中获取信息
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
prize_value_yuan = float(
first_reservation.get("prize_value_yuan", 0.0) or 0.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._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
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
analyser._current_fudai_future_ts = future_ts
# 步骤1:直接查找福袋图标并点击
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 步骤1:直接查找福袋图标并点击",
)
except Exception:
pass
import douyin.core.douyin_flow_control as douyin_flow_control
room_pos_ref = [int(getattr(analyser, "room_pos", 0) or 0)]
opened = douyin_flow_control.find_and_open_fudai_detail(
analyser, room_pos_ref
)
if not opened:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 未找到福袋图标,回退到正常流程",
)
except Exception:
pass
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
# 等待页面加载
try:
analyser.operation.delay(0.5) # 等待详情页加载(减少延迟)
except Exception:
time.sleep(0.5)
# 步骤2:调用阶段检测中的按钮检测进行决策
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 步骤2:调用按钮检测进行决策",
)
except Exception:
pass
# 获取截图
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
except Exception:
pass
# 检测参与按钮
from PIL import Image
import path_config
try:
screenshot_path = path_config.get_screenshot_path()
pic_rgb = Image.open(screenshot_path) # type: ignore[attr-defined]
except Exception:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 无法读取截图,回退到正常流程",
)
except Exception:
pass
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
from douyin.detection import douyin_pixel
button_result = douyin_pixel.detect_attend_button_red_area(
pic_rgb, return_info=True, analyser=analyser
)
if isinstance(button_result, tuple):
has_button, button_info = button_result
else:
has_button = button_result
button_info = {}
if not has_button:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 未检测到参与按钮,回退到正常流程",
button_info=button_info,
)
except Exception:
pass
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
# 步骤3:点击参与按钮
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 步骤3:点击参与按钮",
button_info=button_info,
)
except Exception:
pass
# 点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
attend_x = int(543 * rx / 1080)
attend_y = int(2070 * ry / 2400)
analyser.operation.click(analyser.device_id, attend_x, attend_y)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 已点击参与按钮",
click_x=attend_x,
click_y=attend_y,
)
except Exception:
pass
# 等待点击后的响应
try:
analyser.operation.delay(0.8) # 等待参与响应(减少延迟)
except Exception:
time.sleep(0.8)
# 步骤4:点击福袋图标验证参与状态
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 步骤4:点击福袋图标验证参与状态",
)
except Exception:
pass
# 再次查找并点击福袋图标
room_pos_ref2 = [int(getattr(analyser, "room_pos", 0) or 0)]
opened2 = douyin_flow_control.find_and_open_fudai_detail(
analyser, room_pos_ref2
)
if not opened2:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 验证时未找到福袋图标,可能已参与成功",
)
except Exception:
pass
else:
# 等待详情页加载
try:
analyser.operation.delay(0.5) # 减少延迟
except Exception:
time.sleep(0.5)
# 再次检测按钮状态,验证是否参与成功
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
screenshot_path2 = path_config.get_screenshot_path()
pic_rgb2 = Image.open(screenshot_path2) # type: ignore[attr-defined]
button_result2 = douyin_pixel.detect_attend_button_red_area(
pic_rgb2, return_info=True, analyser=analyser
)
if isinstance(button_result2, tuple):
has_button2, button_info2 = button_result2
else:
has_button2 = button_result2
button_info2 = {}
if has_button2:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 验证时仍检测到参与按钮,可能参与失败",
button_info=button_info2,
)
except Exception:
pass
# 如果还有按钮,回退到正常流程
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
return
except Exception:
pass
# 步骤5:参与成功,设置开奖等待状态并从预约队列中移除
join_result = True # 假设参与成功
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_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]