"""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, ) 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 # 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退 try: join_ahead = float( getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 ) except Exception: join_ahead = 100.0 # poll_before 已在函数前部统一计算 # 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过 dynamic_ahead = int(join_ahead) est_back_times = 0 try: target_pos = int(target.get("pos_seen") or 0) est_back_times = max(0, int(room_pos) - target_pos) try: max_back = int( getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60 ) except Exception: max_back = 60 if max_back > 0: est_back_times = min(est_back_times, max_back) # 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲) reservation_back_swipe_delay_s_val = float( reservation_back_swipe_delay_s or 0.6 ) dynamic_ahead = int( max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18) ) except Exception: dynamic_ahead = int(join_ahead) # 添加详细的调试日志:记录锁定期状态和时间窗口检查结果 try: from datetime import datetime now_str = datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S") 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 "无效" ) time_window_end_ts = ft + max(0.0, poll_before) time_window_end_str = ( datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S") if time_window_end_ts > 0 else "无效" ) ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效" ) analyser._log_kv( "预约", "[预约] process_reservation_attend_window 详细检查", now_ts=int(now_ts), now_str=now_str, focus_until=int(focus_until) if focus_until > 0 else 0, target_future_ts=int(ft), target_future_str=ft_str, dynamic_ahead=dynamic_ahead, join_ahead=join_ahead, poll_before=poll_before, est_back_times=est_back_times, time_window_start=int(time_window_start_ts), time_window_start_str=time_window_start_str, time_window_end=int(time_window_end_ts), time_window_end_str=time_window_end_str, remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, remain_seconds_to_window=( int(time_window_start_ts - now_ts) if time_window_start_ts > now_ts else 0 ), in_lock_period=bool(focus_until > 0 and now_ts < focus_until), in_time_window=bool(now_ts >= time_window_start_ts), passed_time_window=bool(now_ts > time_window_end_ts), ) except Exception: pass # 优化锁定期检查: # 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: from douyin.reservation.reservation_logic.attend_window_verify import ( handle_back_verify, ) _verify_result = handle_back_verify( analyser=analyser, target=target, reservations=reservations, room_pos=room_pos, ft=ft, poll_before=poll_before, reservation_focus_until_ts_ref=reservation_focus_until_ts_ref, reservation_after_action_pending_ref=reservation_after_action_pending_ref, seek_reservation_room_callback=seek_reservation_room_callback, write_state_callback=write_state_callback, ) if _verify_result is not None: return _verify_result # 如果回退或校验失败,直接返回 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