Files
douyin_guaji-main/douyin/reservation/douyin_reservation_handler.py
T

1161 lines
48 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
import json
import csv
import os
import path_config
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, room_info in room_pos_map.items():
if isinstance(room_info, dict):
recorded_title = room_info.get("title", "")
recorded_title_raw = room_info.get("title_raw", "")
else:
# 兼容旧格式
recorded_title, recorded_title_raw = room_info
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:
room_info = room_pos_map[best_match_pos]
if isinstance(room_info, dict):
recorded_title = room_info.get("title", "")
else:
recorded_title = room_info[0] if room_info else ""
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
log_type="OP",
target_title=target_title[:50] if target_title else "",
found_pos=best_match_pos,
match_score=round(best_match_score, 3),
recorded_title=recorded_title[:50] if recorded_title 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)
)
revisit_enabled = bool(
getattr(analyser, "high_value_room_revisit_enabled", False)
)
back_verify_enabled = bool(
getattr(analyser, "reservation_back_verify_enabled", True)
)
# 添加调试日志
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 检查映射表记录条件",
mapping_enabled=mapping_enabled,
revisit_enabled=revisit_enabled,
back_verify_enabled=back_verify_enabled,
condition_result=not mapping_enabled
or (not revisit_enabled and not back_verify_enabled),
)
if not mapping_enabled or (not revisit_enabled and not back_verify_enabled):
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 跳过映射表记录",
reason="config_disabled",
)
return
except Exception:
pass
try:
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
# 在记录映射表前清理旧截图文件,避免复用过期的截图
# 但在并行处理时不清理,因为主线程还在使用截图文件
is_parallel_recording = getattr(
analyser, "_screenshot_ready_for_ocr", False
)
if not is_parallel_recording:
try:
import path_config
import os
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
os.remove(pic_path)
analyser._log_kv(
"预约",
"[预约] 清理旧截图文件,避免复用过期截图",
room_pos=room_pos,
path=pic_path,
log_type="SCREENSHOT",
)
except Exception as e:
analyser._log_kv(
"预约",
f"[预约] 清理旧截图文件失败 - {str(e)}",
room_pos=room_pos,
level="WARNING",
error=str(e),
)
# 检查是否已经为当前直播间识别过标题,避免重复截图和OCR
identified_positions = getattr(
analyser, "_room_title_identified_positions", set()
)
if not isinstance(identified_positions, set):
identified_positions = set()
if room_pos in identified_positions:
# 已经识别过,直接使用缓存的标题
try:
analyser._log_kv(
"预约",
"[预约] 复用已缓存的直播间标题",
room_pos=room_pos,
title=getattr(analyser, "current_room_title", ""),
log_type="DEBUG",
)
except Exception:
pass
return
# 读取当前直播间标题 - 移除:由并行OCR统一处理,避免重复识别
# 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
# # 标记该位置已识别过标题
# identified_positions.add(room_pos)
# analyser._room_title_identified_positions = identified_positions
# 记录到映射表(包含福袋信息)- 仅记录位置,不包含标题(标题由并行OCR提供)
try:
# 检查是否有福袋
has_fudai = bool(getattr(analyser, "_current_fudai_content", ""))
fudai_content = str(getattr(analyser, "_current_fudai_content", ""))
fudai_detail = getattr(analyser, "_last_fudai_detail_tuple", None)
# 添加调试日志
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 准备记录映射表",
room_pos=room_pos,
room_title=getattr(
analyser, "current_room_title", ""
), # 当前缓存的标题
has_fudai=has_fudai,
fudai_content=fudai_content[:30] if fudai_content else "",
current_map_size=len(
getattr(analyser, "_room_pos_to_title_map", {})
),
)
room_info = {
"title": "", # 标题由并行OCR提供,后续填充
"title_raw": "", # 标题由并行OCR提供,后续填充
"has_fudai": has_fudai,
"fudai_content": fudai_content,
"fudai_detail": fudai_detail,
"timestamp": time.time(),
}
# 检查是否应该记录(位置不存在)
should_record = room_pos not in getattr(
analyser, "_room_pos_to_title_map", {}
)
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 检查记录条件",
room_pos=room_pos,
room_pos_in_map=not should_record,
should_record=should_record,
has_fudai=has_fudai,
fudai_content=fudai_content[:30] if fudai_content else "",
)
# 检查映射表中是否已有相同标题的直播间(可能表示滑动切换失败)
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
duplicate_title_positions = []
current_title = getattr(analyser, "current_room_title", "").strip()
if current_title:
for pos, info in room_pos_map.items():
existing_title = info.get("title", "").strip()
if (
existing_title
and existing_title == current_title
and pos != room_pos
):
duplicate_title_positions.append(pos)
if duplicate_title_positions:
# 删除重复位置的记录
deleted_count = 0
for dup_pos in duplicate_title_positions:
if dup_pos in room_pos_map:
del room_pos_map[dup_pos]
deleted_count += 1
analyser._log_kv( # type: ignore[attr-defined]
"警告",
"[警告] 检测到重复直播间标题,已删除重复记录",
current_room_pos=room_pos,
deleted_positions=duplicate_title_positions,
deleted_count=deleted_count,
room_title=current_title,
reason="duplicate_title_deduplicated",
level="WARNING",
)
# 在当前记录中标记去重信息
room_info["deduplicated_from"] = duplicate_title_positions
room_info["deduplication_timestamp"] = time.time()
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 重复标题去重完成,继续记录当前位置",
room_pos=room_pos,
room_title=current_title,
deduplicated_positions=duplicate_title_positions,
)
if should_record:
# 映射表中没有记录,需要直接识别截图记录直播间标题
try:
from douyin.fudai import douyin_fudai_detail
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 的属性
analyser.current_room_title = room_title
analyser.current_room_title_raw = room_title_raw
# 标记该位置已识别过标题
identified_positions.add(room_pos)
analyser._room_title_identified_positions = identified_positions
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 识别并记录直播间标题到映射表",
log_type="OP",
room_pos=room_pos,
room_title=room_title,
room_title_raw=room_title_raw,
)
# 更新房间信息
room_info["title"] = room_title
room_info["title_raw"] = room_title_raw
except Exception as e:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 识别直播间标题失败",
error=str(e),
room_pos=room_pos,
level="WARNING",
)
analyser._room_pos_to_title_map[room_pos] = room_info
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 记录直播间信息到运行时映射表",
log_type="OP",
room_pos=room_pos,
room_title=room_info["title"],
has_fudai=has_fudai,
fudai_content=fudai_content[:30] if fudai_content else "",
)
except Exception:
pass
# 序列化运行时映射表到文件,供 GUI 刷新使用
try:
_dump_room_pos_map_to_state(analyser)
except Exception:
pass
else:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 跳过记录:位置已存在",
room_pos=room_pos,
has_fudai=has_fudai,
fudai_content=fudai_content[:30] if fudai_content else "",
current_map_size=len(
getattr(analyser, "_room_pos_to_title_map", {})
),
)
except Exception as e:
# 如果记录映射表失败,记录错误但不影响主流程
try:
analyser._log_kv(
"预约",
"[预约] 记录映射表失败",
error=str(e),
room_pos=room_pos,
level="WARNING",
)
except Exception:
pass
except Exception as e:
# 如果整个记录过程失败,记录错误但不影响主流程
try:
analyser._log_kv(
"预约",
"[预约] 记录直播间标题和位置失败",
error=str(e),
room_pos=room_pos,
level="WARNING",
)
except Exception:
pass
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
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:
# 已在目标位置,但仍需校验
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]
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):
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):
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
try:
analyser._log_kv( # type: ignore[attr-defined]
"诊断",
"handle_reservation_direct_attend:当前关键 flags",
reservation_after_action_pending=bool(
getattr(analyser, "reservation_after_action_pending", False)
),
reservation_focus_until_ts=float(
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
),
waiting_for_lottery=bool(
getattr(analyser, "_waiting_for_lottery_result", False)
),
room_pos=int(getattr(analyser, "room_pos", 0) or 0),
)
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.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
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:
analyser._log_kv( # type: ignore[attr-defined]
"统计",
"metric",
metric="fudai_attend",
metric_type="success",
run_id=getattr(analyser, "_run_id", ""),
source="reservation_backtrack",
future_ts=int(future_ts),
)
except Exception:
pass
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
analyser._lottery_wait_start_ts = current_time
analyser._current_attending_reservation_fudai = (
True # 标记当前正在参与预约福袋
)
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]
def _dump_room_pos_map_to_state(analyser: Any) -> None:
"""将 analyser._room_pos_to_title_map 序列化到 douyin/core/state/room_pos_map.json。
结构为 {"<pos>": [title, title_raw], ...},Unicode保持原样。
"""
try:
room_pos_map = getattr(analyser, "_room_pos_to_title_map", {})
# 即使没有映射,也希望写入本次运行的元信息
state_dir = os.path.join(path_config.PROJECT_ROOT, "douyin", "core", "state")
os.makedirs(state_dir, exist_ok=True)
final_path = os.path.join(state_dir, "room_pos_map.json")
tmp_path = final_path + ".tmp"
# 过滤掉空条目,只保留本次运行有值的映射
filtered = {}
for k, v in room_pos_map.items():
try:
if isinstance(v, dict):
title = (v.get("title", "") or "").strip()
title_raw = (v.get("title_raw", "") or "").strip()
else:
# 兼容旧格式
title = (v[0] or "").strip() if len(v) > 0 else ""
title_raw = (v[1] or "").strip() if len(v) > 1 else ""
except Exception:
title = ""
title_raw = ""
if not title and not title_raw:
continue
filtered[str(k)] = [title, title_raw]
# 准备写入数据:保留原有 top-level 映射结构,同时添加一个保留的元信息字段
data = dict(filtered)
try:
data["_meta"] = {
"source": final_path,
"generated_ts": int(time.time()),
"run_id": getattr(analyser, "_run_id", ""),
}
except Exception:
data["_meta"] = {"generated_ts": int(time.time())}
# 使用漂亮的缩进写入 JSON(先写 tmp 再替换)
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
try:
os.replace(tmp_path, final_path)
except Exception:
# os.replace 在某些环境可能不可用,回退到重命名
os.rename(tmp_path, final_path)
# 同步导出 CSV 和 Markdown 表格(仅包含映射条目,不包含 _meta)
try:
csv_path = os.path.join(state_dir, "room_pos_map.csv")
csv_tmp = csv_path + ".tmp"
md_path = os.path.join(state_dir, "room_pos_map.md")
md_tmp = md_path + ".tmp"
# 写 CSV
with open(csv_tmp, "w", encoding="utf-8", newline="") as cf:
writer = csv.writer(cf)
writer.writerow(
["pos", "title", "title_raw", "has_fudai", "fudai_content"]
)
for k in sorted(
filtered.keys(), key=lambda x: int(x) if x.isdigit() else x
):
v = room_pos_map.get(int(k) if k.isdigit() else k, {})
if isinstance(v, dict):
title = v.get("title", "")
title_raw = v.get("title_raw", "")
has_fudai = v.get("has_fudai", False)
fudai_content = v.get("fudai_content", "")
else:
# 兼容旧格式
title = v[0] if len(v) > 0 else ""
title_raw = v[1] if len(v) > 1 else ""
has_fudai = False
fudai_content = ""
writer.writerow(
[k, title, title_raw, has_fudai, fudai_content[:100]]
)
try:
os.replace(csv_tmp, csv_path)
except Exception:
os.rename(csv_tmp, csv_path)
# 写 Markdown(顶部注释 source)
with open(md_tmp, "w", encoding="utf-8") as mf:
mf.write(f"<!-- source: {final_path} -->\n\n")
mf.write("| 位置 | 标题 | 原始标题 | 有福袋 | 福袋内容 |\n")
mf.write("|-:|:-|:-|:-:|:-|\n")
for k in sorted(
filtered.keys(), key=lambda x: int(x) if x.isdigit() else x
):
v = room_pos_map.get(int(k) if k.isdigit() else k, {})
if isinstance(v, dict):
title = v.get("title", "").replace("|", "\\|")
title_raw = v.get("title_raw", "").replace("|", "\\|")
has_fudai = "✓" if v.get("has_fudai", False) else ""
fudai_content = (
v.get("fudai_content", "")[:50] + "..."
if len(v.get("fudai_content", "")) > 50
else v.get("fudai_content", "")
).replace("|", "\\|")
else:
# 兼容旧格式
title = (v[0] if len(v) > 0 else "").replace("|", "\\|")
title_raw = (v[1] if len(v) > 1 else "").replace("|", "\\|")
has_fudai = ""
fudai_content = ""
mf.write(
f"| {k} | {title} | {title_raw} | {has_fudai} | {fudai_content} |\n"
)
try:
os.replace(md_tmp, md_path)
except Exception:
os.rename(md_tmp, md_path)
except Exception:
# 导出 CSV/MD 失败不影响 JSON 写入
try:
analyser._log_kv("预约", "[预约] 导出 CSV/MD 失败")
except Exception:
pass
except Exception:
try:
analyser._log_kv("预约", "[预约] 序列化映射表到文件失败")
except Exception:
pass