"""reservation_logic.attend_window - 进入预约窗口的处理(最大头)。 process_reservation_attend_window:当临近某条预约的开奖时间时, 抢占当前流程,回退到目标直播间,再触发详情识别与参与逻辑。 包含回退路径选择、回退校验、超时保护、失败重试等。 """ from __future__ import annotations import time from typing import Any, Callable, Dict, List, Optional from ._common import ( ReservationItem, format_reservation_context, log_reservation_error, safe_write_state, ) from .helpers import ( _calculate_string_similarity, _extract_content_core, _normalize_room_title_for_matching, _now_ts, _sort_reservations_inplace, ) from .attend_window_helpers import ( compute_dynamic_ahead, log_attend_window_check_details, ) def process_reservation_attend_window( analyser: Any, reservations: List[ReservationItem], room_pos: int, reservation_focus_until_ts_ref: List[float], reservation_after_action_pending_ref: List[bool], reservation_back_swipe_delay_s: float, swipe_down_back_callback: Callable[[], None], seek_reservation_room_callback: Callable[[ReservationItem], bool], sort_reservations_callback: Callable[[], None], write_state_callback: Callable[[], None], ) -> bool: """在主循环中调用:处理"是否需要回退到某个预约直播间并参与"。 返回: bool: 若为 True,表示已经触发了回退/跳转,本轮主循环应尽快结束, 让上层逻辑继续后续处理(例如识别详情并参与)。 """ start_time = time.time() # 总超时兜底:避免预约分支在某些机型/状态下长时间阻塞导致主循环“看似卡死”。 try: total_timeout_s = float( getattr(analyser, "reservation_back_total_timeout_seconds", 20.0) or 20.0 ) except Exception: total_timeout_s = 20.0 # 添加函数入口日志 try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window 函数入口", reservations_count=len(reservations) if reservations else 0, room_pos=room_pos, ) except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, format_reservation_context(reservations=reservations), level="WARNING", stage="记录函数入口日志", ) else: pass # 检查是否正在等待开奖且当前参与的是预约福袋,如果是则不抢占 try: waiting_for_lottery = bool( getattr(analyser, "_waiting_for_lottery_result", False) ) current_attending_reservation = bool( getattr(analyser, "_current_attending_reservation_fudai", False) ) if waiting_for_lottery and current_attending_reservation: try: analyser._log_kv( "预约", "[预约] 正在等待预约福袋开奖,不抢占其他预约", waiting_for_lottery=waiting_for_lottery, current_attending_reservation=current_attending_reservation, ) except Exception: pass return False except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, format_reservation_context(reservations=reservations), level="WARNING", stage="检查是否正在等待预约福袋开奖", ) else: pass if not reservations: try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:预约队列为空,跳过", ) except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, {}, level="WARNING", stage="记录队列为空日志", ) else: pass return False now_ts = _now_ts() focus_until = float( reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0 ) # 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数) try: poll_before = float( getattr(analyser, "high_value_fudai_poll_before_seconds", 10.0) or 10.0 ) except Exception: poll_before = 10.0 poll_before = max(0.0, poll_before) # 按统一规则排序(防止外部遗漏 sort) # 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。 try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:开始队列排序", reservations_count=len(reservations) if reservations else 0, ) except Exception: pass # 超时检查 try: if (time.time() - start_time) > total_timeout_s: try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:超时退出(排序前)", total_timeout_seconds=round(total_timeout_s, 3), ) except Exception: pass return False except Exception: pass try: _sort_reservations_inplace(reservations) except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, format_reservation_context(reservations=reservations), level="WARNING", stage="队列排序", ) else: try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:队列排序异常(忽略)", error=str(e), error_type=type(e).__name__, ) except Exception: pass try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:队列排序完成", earliest_future_ts=( int(float((reservations[0].get("future_ts") or 0.0))) if reservations else 0 ), ) except Exception: pass # 锁定期内:优先处理“锁定的预约”,避免被队头其它预约打断。 # 同时,如果锁定期对应的预约已不在队列(例如刚参与成功并移除),视为“锁定失效”,清除锁定期。 if focus_until > 0 and now_ts < focus_until: locked_idx = None try: for i, item in enumerate(reservations): try: item_ft = float(item.get("future_ts") or 0.0) except Exception: continue if item_ft <= 0: continue expected_focus_until = item_ft + max(0.0, poll_before) if abs(focus_until - expected_focus_until) <= 5.0: locked_idx = i break except Exception: locked_idx = None if locked_idx is None: try: analyser._log_kv( "预约", "[预约] 检测到锁定期已失效(锁定预约不在队列),清除锁定期", focus_until=int(focus_until), lock_period_remain_seconds=int(focus_until - now_ts), reservations_count=len(reservations), ) except Exception: pass try: if reservation_focus_until_ts_ref: reservation_focus_until_ts_ref[0] = 0.0 else: reservation_focus_until_ts_ref.append(0.0) except Exception: pass focus_until = 0.0 elif locked_idx != 0: try: locked_item = reservations.pop(locked_idx) reservations.insert(0, locked_item) analyser._log_kv( "预约", "[预约] 锁定期内固定处理锁定预约(忽略队头其他预约)", focus_until=int(focus_until), locked_future_ts=int(float(locked_item.get("future_ts") or 0.0)), moved_from_index=int(locked_idx), ) except Exception: pass # 超时检查 try: if (time.time() - start_time) > total_timeout_s: try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:超时退出(排序后)", total_timeout_seconds=round(total_timeout_s, 3), ) except Exception: pass return False except Exception: pass # 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标) target = reservations[0] try: ft = float(target.get("future_ts") or 0.0) except Exception: ft = 0.0 # 检查是否已经参与过该预约(通过 _participated_fudai_future_ts) try: participated_fudai_ts = getattr( analyser, "_participated_fudai_future_ts", set() ) if not isinstance(participated_fudai_ts, set): participated_fudai_ts = set() # 检查是否已经参与过(允许5秒误差) already_participated = False for participated_ts in participated_fudai_ts: if abs(ft - participated_ts) <= 5.0: already_participated = True break if already_participated: # 已经参与过,从预约队列中移除 try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:检测到已参与过该预约,从队列中移除", target_future_ts=int(ft) if ft > 0 else 0, ) except Exception: pass reservations.pop(0) if _RESERVATION_ERROR_UTILS_AVAILABLE: safe_write_state( write_state_callback, analyser, format_reservation_context( item=target, reservations=reservations, reason="已参与过", ), ) else: try: write_state_callback() except Exception: pass return False except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, format_reservation_context( item=target, reservations=reservations, ), level="WARNING", stage="检查是否已参与", ) else: pass # 添加目标预约的详细信息日志 try: from datetime import datetime ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" ) analyser._log_kv( "预约", "[预约] process_reservation_attend_window 获取目标预约", target_future_ts=int(ft) if ft > 0 else 0, target_future_str=ft_str, target_value=float(target.get("prize_value_yuan", 0)), target_pos_seen=int(target.get("pos_seen", 0)), target_content=str(target.get("content", ""))[:50], ) except Exception: pass # 没有合法 future_ts,则直接丢弃 if ft <= 0: try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:预约 future_ts 无效,丢弃", future_ts=ft, target=target, ) except Exception: pass reservations.pop(0) if _RESERVATION_ERROR_UTILS_AVAILABLE: safe_write_state( write_state_callback, analyser, format_reservation_context( item=target, reservations=reservations, reason="future_ts 无效", ), ) else: try: write_state_callback() except Exception: pass return False # 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退 join_ahead = float( getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 ) dynamic_ahead, est_back_times = compute_dynamic_ahead( analyser, target, room_pos, reservation_back_swipe_delay_s ) # 添加详细的调试日志:记录锁定期状态和时间窗口检查结果 log_attend_window_check_details( analyser, now_ts=now_ts, focus_until=focus_until, ft=ft, dynamic_ahead=dynamic_ahead, join_ahead=join_ahead, poll_before=poll_before, est_back_times=est_back_times, ) # 优化锁定期检查: # 1. 如果没有锁定期(focus_until = 0),直接允许检查时间窗口 # 2. 如果锁定期已过期(now_ts >= focus_until),允许检查时间窗口 # 3. 如果锁定期还没结束,但预约时间已经到了,检查是否是同一个预约 # - 如果是同一个预约,允许回退(通常已经在目标直播间了) # - 如果不是同一个预约,不允许回退(需要等待当前预约完成) # 4. 特殊情况:如果是队列满后立即参与模式(通过标志判断),允许检查时间窗口 # 先检查是否是队列满立即参与模式 is_queue_full_immediate_attend_check = False try: queue_full_waiting_check = bool( getattr(analyser, "queue_full_waiting_at_earliest", False) or False ) if queue_full_waiting_check: is_queue_full_immediate_attend_check = True except Exception: pass if ( focus_until > 0 and now_ts < focus_until and abs(focus_until - now_ts) > 1.0 and not is_queue_full_immediate_attend_check ): # 锁定期还没结束,检查是否是同一个预约(允许5秒误差) expected_focus_until = ft + max(0.0, poll_before) if abs(focus_until - expected_focus_until) > 5.0: # 不是同一个预约,锁定期还没结束,不允许回退 try: analyser._log_kv( "预约", "[预约] 锁定期未结束且不是当前预约,跳过回退", focus_until=int(focus_until), expected_focus_until=int(expected_focus_until), target_future_ts=int(ft), lock_period_remain_seconds=int(focus_until - now_ts), ) except Exception: pass return False # 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退 # 但这里通常已经在目标直播间了,需要检查是否已经在目标位置 # 获取当前实际的 room_pos(可能已经被更新) try: current_room_pos_check = int( getattr(analyser, "room_pos", room_pos) or room_pos ) except Exception: current_room_pos_check = int(room_pos) # 计算位置差 try: target_pos_check = int(target.get("pos_seen") or 0) except Exception: target_pos_check = 0 pos_diff_check = current_room_pos_check - target_pos_check # 如果已经在目标位置(pos_diff == 0),说明已经在目标直播间,不需要再次回退 # 但是需要检查时间窗口是否到达,如果到达了,应该返回 True 表示需要参与 # 或者如果是队列满立即参与模式,直接返回 True if pos_diff_check == 0: # 检查是否是队列满立即参与模式 is_queue_full_immediate_attend_pos = False try: queue_full_waiting_pos = bool( getattr(analyser, "queue_full_waiting_at_earliest", False) or False ) if queue_full_waiting_pos: is_queue_full_immediate_attend_pos = True except Exception: pass # 检查时间窗口是否到达,或者是队列满立即参与模式 if is_queue_full_immediate_attend_pos or ( now_ts >= ft - dynamic_ahead and now_ts <= ft + max(0.0, poll_before) ): # 时间窗口已到达或队列满立即参与模式,虽然已在目标位置,但需要参与,返回 True try: analyser._log_kv( "预约", "[预约] 锁定期未结束但是同一个预约,且已在目标位置,时间窗口已到达或队列满立即参与模式,需要参与", focus_until=int(focus_until), target_future_ts=int(ft), current_room_pos=current_room_pos_check, target_pos=target_pos_check, now_ts=int(now_ts), time_window_start=int(ft - dynamic_ahead), time_window_end=int(ft + max(0.0, poll_before)), is_queue_full_immediate_attend=is_queue_full_immediate_attend_pos, ) except Exception: pass # 更新锁定期和待处理标志(如果不是队列满立即参与模式,才设置锁定期) if not is_queue_full_immediate_attend_pos: focus_until_new = ft + max(0.0, poll_before) if reservation_focus_until_ts_ref: reservation_focus_until_ts_ref[0] = focus_until_new else: reservation_focus_until_ts_ref.append(focus_until_new) if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = True else: reservation_after_action_pending_ref.append(True) try: write_state_callback() except Exception: pass return True else: # 时间窗口未到达,跳过 # 注意:如果已经在目标位置但时间窗口未到,不应该设置 reservation_after_action_pending # 因为这会导致反复等待,应该清除这个标志,让主循环正常处理 try: analyser._log_kv( "预约", "[预约] 锁定期未结束但是同一个预约,且已在目标位置,但时间窗口未到达,跳过回退并清除待处理标志", focus_until=int(focus_until), target_future_ts=int(ft), current_room_pos=current_room_pos_check, target_pos=target_pos_check, now_ts=int(now_ts), time_window_start=int(ft - dynamic_ahead), time_window_end=int(ft + max(0.0, poll_before)), ) except Exception: pass # 清除待处理标志,避免反复等待 if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = False return False # 如果不在目标位置,继续检查时间窗口 try: analyser._log_kv( "预约", "[预约] 锁定期未结束但是同一个预约,继续检查时间窗口", focus_until=int(focus_until), target_future_ts=int(ft), current_room_pos=current_room_pos_check, target_pos=target_pos_check, pos_diff=pos_diff_check, ) except Exception: pass # 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期) is_queue_full_immediate_attend = False try: # 检查队列满等待标志 queue_full_waiting = bool( getattr(analyser, "queue_full_waiting_at_earliest", False) or False ) if queue_full_waiting: is_queue_full_immediate_attend = True try: analyser._log_kv( "预约", "[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与", queue_full_waiting=queue_full_waiting, target_future_ts=int(ft), ) except Exception: pass except Exception: pass if not is_queue_full_immediate_attend and now_ts < ft - dynamic_ahead: # 还没到窗口(非队列满立即参与模式) try: from datetime import datetime time_window_start_ts = ft - dynamic_ahead time_window_start_str = ( datetime.fromtimestamp(time_window_start_ts).strftime( "%Y-%m-%d %H:%M:%S" ) if time_window_start_ts > 0 else "无效" ) analyser._log_kv( "预约", "[预约] 时间窗口未到,跳过回退", now_ts=int(now_ts), now_str=datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S"), time_window_start=int(time_window_start_ts), time_window_start_str=time_window_start_str, remain_seconds=int((ft - dynamic_ahead) - now_ts), target_future_ts=int(ft), dynamic_ahead=dynamic_ahead, ) except Exception: pass return False if now_ts > ft + max(0.0, poll_before): # 已明显错过开奖时间,交给统一清理逻辑 try: analyser._log_kv( "预约", "[预约] 已明显错过开奖时间,清理过期预约", future_ts=int(ft), now_ts=int(now_ts), poll_before=poll_before, missed_seconds=int(now_ts - (ft + max(0.0, poll_before))), ) except Exception: pass cleanup_expired_reservations(analyser, reservations, write_state_callback) return False # 进入预约参与窗口:执行回退动作 try: analyser._log_kv( "预约", "[预约] 进入预约参与窗口,准备回退到目标直播间", future_ts=int(ft), now_ts=int(now_ts), room_pos=int(room_pos), queue_len=len(reservations), dynamic_ahead=int(dynamic_ahead), est_back_times=int(est_back_times), remain_seconds_to_open=int(ft - now_ts), time_window_start=int(ft - dynamic_ahead), time_window_end=int(ft + max(0.0, poll_before)), ) except Exception: pass # 获取当前实际的 room_pos(可能已经被更新) try: current_room_pos = int(getattr(analyser, "room_pos", room_pos) or room_pos) except Exception: current_room_pos = int(room_pos) # 计算位置差 try: target_pos = int(target.get("pos_seen") or 0) except Exception: target_pos = 0 pos_diff = current_room_pos - target_pos # 调用上层提供的"按预约信息回退到目标直播间"的回调 try: analyser._log_kv( "预约", "[预约] 准备执行回退到预约直播间", target_pos_seen=target_pos, current_room_pos=current_room_pos, pos_diff=pos_diff, ) except Exception: pass # 直接调用回退回调,不需要预先下滑 # 原因: # 1. 回退前已经进行了阶段诊断,处理了弹窗和福袋详情页等异常状态 # 2. 如果已经在直播间,不需要下滑 # 3. 预先下滑会导致 room_pos 减1,影响后续的回退计算,导致少回退一个直播间 ok = False try: ok = bool(seek_reservation_room_callback(target)) except Exception as e: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, e, format_reservation_context( item=target, reservations=reservations, current_room_pos=current_room_pos, target_pos=target_pos, pos_diff=pos_diff, ), level="ERROR", stage="执行回退操作", ) else: try: analyser._log_kv( "预约", "[预约] 执行回退时发生异常", error=str(e), error_type=type(e).__name__, ) except Exception: pass ok = False if ok: # 获取目标直播间名字和福袋详情(用于日志和校验) target_room_title = str(target.get("room_title") or "").strip() target_room_title_raw = str(target.get("room_title_raw") or "").strip() target_content = str(target.get("content") or "").strip() target_value = float(target.get("prize_value_yuan") or 0.0) try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:回退操作成功,准备进行回退校验", target_pos=int(target.get("pos_seen", 0)), target_room_title=target_room_title[:50] if target_room_title else "", target_room_title_raw=( target_room_title_raw[:50] if target_room_title_raw else "" ), target_content=target_content[:50] if target_content else "", target_value_yuan=target_value, current_room_pos=int(room_pos), reservation_back_verify_enabled=bool( getattr(analyser, "reservation_back_verify_enabled", True) ), level="DEBUG", ) except Exception: pass # 回退成功后,进行回退校验(如果启用了回退校验) verify_ok = True verify_detail = None try: verify_enabled = bool( getattr(analyser, "reservation_back_verify_enabled", True) ) try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:检查回退校验开关", reservation_back_verify_enabled=verify_enabled, level="DEBUG", ) except Exception: pass if verify_enabled: # 回退操作后等待直播间加载完成,然后再进行校验 # 使用配置项控制等待时间,默认3秒(确保直播间标题等信息加载完成) try: verify_wait_seconds = float( 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秒 if verify_wait_seconds > 10.0: verify_wait_seconds = 10.0 # 最大10秒,避免等待过久 except Exception: verify_wait_seconds = 3.0 try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:回退后等待直播间加载完成(开始等待)", verify_wait_seconds=verify_wait_seconds, level="INFO", ) except Exception: pass # 记录等待开始时间,并在等待结束后写入实际等待时长,便于验证配置是否生效 wait_start_ts = time.time() try: 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: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:开始调用回退校验函数", target_pos=int(target.get("pos_seen", 0)), target_room_title=( target_room_title[:50] if target_room_title else "" ), level="DEBUG", ) except Exception: pass import douyin.reservation.douyin_reservation_verify as douyin_reservation_verify verify_ok, verify_detail = ( douyin_reservation_verify.validate_back_to_reservation( analyser=analyser, item=target, quick=False, max_checks=3, ) ) try: analyser._log_kv( "预约", "[预约] process_reservation_attend_window:回退校验函数返回", verify_ok=verify_ok, verify_detail_exists=verify_detail is not None, level="DEBUG", ) except Exception: pass if not verify_ok: if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, Exception("回退校验失败:回退操作成功但校验未通过"), format_reservation_context( item=target, reservations=reservations, verify_detail=verify_detail, target_pos=int(target.get("pos_seen", 0)), target_room_title=( target_room_title[:50] if target_room_title else "" ), ), level="WARNING", stage="回退校验", ) else: try: analyser._log_kv( "预约", "[预约] 回退校验失败:回退操作成功但校验未通过(不再自动回退重试,避免循环卡死)", target_pos=int(target.get("pos_seen", 0)), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass # 回退校验失败:根据映射表尝试再次回退到对应直播间,且不进入锁定期 try: try: analyser._log_kv( "预约", "[预约] 回退校验失败:尝试根据映射表回退到对应直播间并跳过设置锁定期", target_pos=int(target.get("pos_seen", 0)), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass # 校验失败意味着位置信息可能不准确,尝试用映射表识别“当前/目标”位置差 updated_target = dict(target) try: room_pos_before_map = int( getattr(analyser, "room_pos", 0) or 0 ) except Exception: room_pos_before_map = 0 mapped_target_pos = None mapped_current_pos = None try: from douyin.reservation.douyin_reservation_handler import ( ReservationHandler, ) mapped_target_pos = ( ReservationHandler.find_room_pos_by_title( analyser, target_room_title, target_room_title_raw, ) ) if ( mapped_target_pos is not None and mapped_target_pos > 0 ): updated_target["pos_seen"] = int( mapped_target_pos ) try: analyser._log_kv( "预约", "[预约] 重新查找目标直播间位置成功", old_pos=int(target.get("pos_seen", 0)), new_pos=int(mapped_target_pos), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass else: try: analyser._log_kv( "预约", "[预约] 重新查找目标直播间位置失败,使用原有位置", target_pos=int( target.get("pos_seen", 0) ), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass # 识别当前直播间标题(优先缓存,必要时重新识别) current_room_title = str( getattr(analyser, "current_room_title", "") or "" ).strip() current_room_title_raw = str( getattr(analyser, "current_room_title_raw", "") or "" ).strip() if ( not current_room_title and not current_room_title_raw ): try: from douyin.fudai import douyin_fudai_detail y_pianyi_val = int( getattr(analyser, "y_pianyi", 0) or 0 ) ( current_room_title, current_room_title_raw, ) = douyin_fudai_detail.read_live_room_title_core( analyser, y_pianyi_val ) try: analyser.current_room_title = ( current_room_title ) analyser.current_room_title_raw = ( current_room_title_raw ) except Exception: pass except Exception: current_room_title = "" current_room_title_raw = "" if current_room_title or current_room_title_raw: mapped_current_pos = ( ReservationHandler.find_room_pos_by_title( analyser, current_room_title, current_room_title_raw, ) ) if ( mapped_current_pos is not None and mapped_current_pos > 0 ): try: old_room_pos = int( getattr(analyser, "room_pos", 0) or 0 ) except Exception: old_room_pos = 0 try: analyser.room_pos = int( mapped_current_pos ) except Exception: pass try: analyser._log_kv( "预约", "[预约] 通过映射表识别当前直播间位置", old_pos=int(old_room_pos), new_pos=int(mapped_current_pos), current_room_title=( current_room_title[:50] if current_room_title else "" ), ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "[预约] 重新查找目标/当前直播间位置时出错", error=str(e), target_pos=int(target.get("pos_seen", 0)), ) except Exception: pass # 尝试使用回退回调根据映射表差值重新回退 ok2 = False should_retry_seek = True mapped_pos_diff = None if ( mapped_current_pos is not None and mapped_target_pos is not None ): try: mapped_pos_diff = int(mapped_target_pos) - int( mapped_current_pos ) except Exception: mapped_pos_diff = None try: analyser._log_kv( "预约", "[预约] 映射表差值回退准备", mapped_current_pos=int(mapped_current_pos), mapped_target_pos=int(mapped_target_pos), mapped_pos_diff=( int(mapped_pos_diff) if mapped_pos_diff is not None else None ), ) except Exception: pass if mapped_pos_diff == 0: # 若映射表显示已在目标位置但校验失败,尝试根据回退前位置进行一次纠偏回退 if ( mapped_target_pos is not None and room_pos_before_map != mapped_target_pos ): try: if room_pos_before_map > int( mapped_target_pos ): updated_target[ "_seek_direction_hint" ] = "down" elif room_pos_before_map < int( mapped_target_pos ): updated_target[ "_seek_direction_hint" ] = "up" except Exception: pass try: analyser._log_kv( "预约", "[预约] 映射表显示已在目标位置但校验失败,启用纠偏回退", mapped_current_pos=int( mapped_current_pos ), mapped_target_pos=int( mapped_target_pos ), room_pos_before_map=int( room_pos_before_map ), direction_hint=updated_target.get( "_seek_direction_hint", "" ), ) except Exception: pass else: should_retry_seek = False try: analyser._log_kv( "预约", "[预约] 映射表显示已在目标位置,但校验失败,跳过二次回退", mapped_current_pos=int( mapped_current_pos ), mapped_target_pos=int( mapped_target_pos ), ) except Exception: pass if should_retry_seek: try: if seek_reservation_room_callback: ok2 = bool( seek_reservation_room_callback( updated_target ) ) except Exception: ok2 = False if ok2: # 第二次回退成功,设置锁定期并标记待处理 focus_until_new = ft + max(0.0, poll_before) if reservation_focus_until_ts_ref: reservation_focus_until_ts_ref[0] = ( focus_until_new ) else: reservation_focus_until_ts_ref.append( focus_until_new ) if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = True else: reservation_after_action_pending_ref.append( True ) try: analyser._log_kv( "预约", "[预约] 第二次回退成功:已根据映射表回退到目标直播间", target_pos=int( updated_target.get("pos_seen", 0) ), target_room_title=( target_room_title[:50] if target_room_title else "" ), focus_until=int(focus_until_new), ) except Exception: pass try: write_state_callback() except Exception: pass # 返回 True 表示回退成功 return True else: # 第二次回退也失败,清理锁定相关标志 try: if reservation_focus_until_ts_ref: reservation_focus_until_ts_ref[0] = 0.0 except Exception: pass try: if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = ( False ) except Exception: pass try: analyser._log_kv( "预约", "[预约] 第二次回退失败:无法根据映射表定位到目标直播间", target_pos=int( updated_target.get("pos_seen", 0) ), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass try: write_state_callback() except Exception: pass except Exception: pass # 不设置锁定期,回退校验失败视作本次未成功回退,返回 False 以便上层继续处理 return False else: try: analyser._log_kv( "预约", f"[预约] 回退校验通过:已成功回退到目标直播间并验证福袋详情 - 目标位置:{int(target.get('pos_seen', 0))}, 直播间:'{target_room_title[:30] if target_room_title else ''}'", target_pos=int(target.get("pos_seen", 0)), target_room_title=( target_room_title[:50] if target_room_title else "" ), ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "[预约] 回退校验执行时发生异常,继续执行", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 校验异常不影响主流程,继续执行 else: try: analyser._log_kv( "预约", "[预约] 回退校验已禁用,跳过校验", ) except Exception: pass except Exception as e: try: analyser._log_kv( "预约", "[预约] 检查回退校验开关时发生异常,继续执行", error=str(e), error_type=type(e).__name__, ) except Exception: pass # 如果回退或校验失败,直接返回 False if not ok: try: analyser._log_kv( "预约", "[预约] 回退或校验失败,保留队列以便后续重试或清理", future_ts=int(ft), now_ts=int(now_ts), remain_seconds_to_open=int(ft - now_ts), target_pos=int(target.get("pos_seen", 0)), current_room_pos=int(room_pos), ) except Exception: pass try: write_state_callback() except Exception: pass return False # 进入锁定期:在开奖附近一段时间内不再切换直播间 focus_until_new = ft + max(0.0, poll_before) if reservation_focus_until_ts_ref: reservation_focus_until_ts_ref[0] = focus_until_new else: reservation_focus_until_ts_ref.append(focus_until_new) if reservation_after_action_pending_ref: reservation_after_action_pending_ref[0] = True else: reservation_after_action_pending_ref.append(True) try: from datetime import datetime ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" ) # 运行日志 analyser._log_kv( "预约", f"[预约] 已回退到目标直播间,等待详情识别与参与 - 直播间:'{target_room_title[:30] if target_room_title else ''}', 开奖时间:{ft_str}, 价值:{target_value}元", future_ts=int(ft), future_str=ft_str, focus_until=int(focus_until_new), lock_period_seconds=int(focus_until_new - _now_ts()), remain_seconds_to_open=int(ft - _now_ts()), target_room_title=target_room_title, target_room_title_raw=target_room_title_raw, target_content=target_content, target_value_yuan=target_value, ) # 行为日志 analyser._log_kv( "行为", "回退到预约直播间成功", action="回退到预约直播间", result="成功", detail={ "目标直播间": ( target_room_title if target_room_title else target_room_title_raw ), "目标直播间原始": target_room_title_raw, "福袋内容": target_content, "福袋价值": target_value, "预计开奖时间": ft_str, "预计开奖时间戳": int(ft), "剩余秒数": int(ft - _now_ts()) if ft > _now_ts() else 0, }, ) except Exception: pass # 不在这里弹出队列,等待真正"参与完毕"后由上层统一处理 try: write_state_callback() except Exception: pass # 添加函数完成日志 try: from datetime import datetime elapsed = time.time() - start_time analyser._log_kv( "预约", "[预约] process_reservation_attend_window 返回结果", result="已触发回退", future_ts=int(ft), now_ts=int(now_ts), remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, elapsed_seconds=round(elapsed, 3), ) except Exception: pass return True # 回退失败:记录日志,等待后续重试或清理 try: analyser._log_kv( "预约", "[预约] 回退到预约直播间失败,保留队列以便后续重试或清理", future_ts=int(ft), now_ts=int(now_ts), remain_seconds_to_open=int(ft - now_ts), target_pos=int(target.get("pos_seen", 0)), current_room_pos=int(room_pos), ) except Exception: pass try: write_state_callback() except Exception: pass # 添加函数完成日志 try: from datetime import datetime elapsed = time.time() - start_time analyser._log_kv( "预约", "[预约] process_reservation_attend_window 返回结果", result="未触发回退", future_ts=int(ft) if ft > 0 else 0, now_ts=int(now_ts), remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, elapsed_seconds=round(elapsed, 3), ) except Exception: pass return False