diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 307a8d2..c3b5d20 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -1212,546 +1212,8 @@ class fudai_analyse: return # 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间" - try: - reservation_check_start = time.time() - self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start) - # 每次开始运行时丢弃旧的预约队列,不加载状态文件 - try: - - # 如果是第一次运行,清空预约队列,不加载状态文件 - is_first_run = getattr(self, "_first_run_once_basic", True) - # 记录清空前的队列状态(用于调试) - old_reservations_count = 0 - try: - old_reservations_count = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - except Exception: - pass - - if is_first_run: - try: - self._log_kv( - "预约", - "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", - old_reservations_count=old_reservations_count, - ) - except Exception: - pass - # 清空预约队列(强制清空,确保每次启动时队列为空) - try: - # 先记录清空前的状态 - before_clear = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - self.reservations = [] - after_clear = ( - len(self.reservations) - if hasattr(self, "reservations") - else 0 - ) - - # 同时清空状态文件,确保外部查看时也是空的 - try: - - state_path = getattr(self, "_reservations_state_path", None) - if state_path: - # 写入空队列到状态文件 - from douyin.reservation.douyin_reservation import ( - write_reservations_state, - ) - - write_reservations_state( - state_path=state_path, - reservations=[], - room_pos=0, - current_room_title="", - current_room_title_raw="", - reason="startup_clear", - ) - try: - self._log_kv( - "预约", - "[预约] 已清空预约队列并更新状态文件", - before_clear=before_clear, - after_clear=after_clear, - ) - except Exception: - pass - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 清空状态文件时出错", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - except Exception as exc: - # 如果清空失败,尝试直接设置 - try: - if hasattr(self, "reservations"): - self.reservations = [] - self._log_kv( - "预约", - "[预约] 清空预约队列时出错,已尝试直接设置", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - # 标记已运行过 - try: - self._first_run_once_basic = False - except Exception: - pass - else: - # 如果不是第一次运行,也记录日志(用于调试) - try: - current_count = ( - len(self.reservations) - if hasattr(self, "reservations") and self.reservations - else 0 - ) - self._log_kv( - "预约", - "[预约] 非第一次运行,保持当前预约队列", - reservations_count=current_count, - is_first_run=False, - ) - except Exception: - pass - - # 不再从状态文件加载预约数据,每次启动时都从空队列开始 - # 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空 - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 初始化预约队列时出错", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - - high_value_enabled = getattr(self, "high_value_fudai_enabled", False) - reservations_list = getattr(self, "reservations", None) - reservations_count = len(reservations_list) if reservations_list else 0 - - # 添加详细的调试日志,确认预约回退逻辑的触发条件 - try: - # 输出预约队列的详细信息 - reservations_detail = [] - if reservations_list: - for idx, r in enumerate(reservations_list[:3]): # 只显示前3个 - try: - ft = float(r.get("future_ts") or 0) - from datetime import datetime - - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - reservations_detail.append( - { - "index": idx, - "future_ts": int(ft) if ft > 0 else 0, - "future_str": ft_str, - "value": float(r.get("prize_value_yuan", 0)), - "pos_seen": int(r.get("pos_seen", 0)), - } - ) - except Exception: - pass - - self._log_kv( - "预约", - "[预约] run_once_basic:检查预约回退触发条件", - high_value_enabled=high_value_enabled, - reservations_count=reservations_count, - reservations_is_none=(reservations_list is None), - will_check_reservations=bool( - high_value_enabled and reservations_list - ), - reservations_detail=reservations_detail, - ) - except Exception: - pass - - # 如果预约功能未启用,输出日志 - if not high_value_enabled: - try: - self._log_kv( - "预约", - "[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查", - ) - except Exception: - pass - # 如果预约队列为空,输出日志 - elif not reservations_list or reservations_count == 0: - try: - self._log_kv( - "预约", - "[预约] 预约队列为空,跳过预约回退检查", - reservations_is_none=(reservations_list is None), - reservations_count=reservations_count, - ) - except Exception: - pass - - if high_value_enabled and reservations_list: - - def _swipe_down_once() -> None: - self.swipe_down_back_from_live() - - def _sort_reservations() -> None: - douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] - - def _write_state() -> None: - # 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致) - try: - # 节流:避免高频写盘(某些环境下会造成明显卡顿甚至看似卡死) - now_ts = time.time() - last_ts = float( - getattr(self, "_reservations_state_last_write_ts", 0.0) - or 0.0 - ) - if (now_ts - last_ts) < 1.0: - return - self._reservations_state_last_write_ts = now_ts - - import json - - os.makedirs( - os.path.dirname(self._reservations_state_path), - exist_ok=True, - ) - - # 格式化预约队列数据(与 douyin_reservation.py 格式一致) - items = [] - for r in self.reservations or []: - try: - ft = float(r.get("future_ts") or 0) - except Exception: - ft = 0.0 - try: - ft_str = ( - datetime.fromtimestamp(ft).strftime( - "%Y-%m-%d %H:%M:%S" - ) - if ft - else "" - ) - except Exception: - ft_str = str(r.get("future_str", "")) - - items.append( - { - "prize_value_yuan": float( - r.get("prize_value_yuan") or 0 - ), - "content": str(r.get("content") or ""), - "future_ts": ft, - "future_str": ft_str, - "pos_seen": int(r.get("pos_seen") or 0), - "room_title": str(r.get("room_title", "") or ""), - "room_title_raw": str( - r.get("room_title_raw", "") or "" - ), - "created_ts": float(r.get("created_ts") or 0), - } - ) - - # 获取当前直播间标题(用于状态文件) - current_title = str( - getattr(self, "current_room_title", "") or "" - ) - current_title_raw = str( - getattr(self, "current_room_title_raw", "") or "" - ) - - # 写入完整的状态数据 - data = { - "updated_ts": time.time(), - "reason": "process_reservation", - "room_pos": int(getattr(self, "room_pos", 0) or 0), - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open( - self._reservations_state_path, "w", encoding="utf-8" - ) as f: - json.dump(data, f, ensure_ascii=False, indent=2) - except Exception as exc: - try: - self._log_kv( - "预约", - "写入预约队列状态文件失败", - error=str(exc), - error_type=type(exc).__name__, - ) - except Exception: - pass - - focus_ref = [float(self.reservation_focus_until_ts or 0.0)] - after_action_ref = [ - bool(self.reservation_after_action_pending or False) - ] - - def _seek_reservation_room(item: dict) -> bool: - try: - return bool( - self._seek_reservation_room(item, operation_type="预约") - ) - except Exception: - return False - - # 检查队列是否已满且需要等待 - max_reservations = int( - getattr(self, "high_value_fudai_max_reservations", 3) or 3 - ) - if ( - len(self.reservations) >= max_reservations - and not self.queue_full_waiting_at_earliest - ): - # 队列已满,回退到最早开奖的预约直播间等待 - waiting = ( - douyin_reservation_logic.handle_queue_full_wait_at_earliest( - analyser=self, - reservations=self.reservations, - room_pos=int(getattr(self, "room_pos", 0) or 0), - reservation_focus_until_ts_ref=focus_ref, - reservation_back_swipe_delay_s=float( - self.reservation_back_swipe_delay or 0.6 - ), - swipe_down_back_callback=_swipe_down_once, - seek_reservation_room_callback=_seek_reservation_room, - sort_reservations_callback=_sort_reservations, - write_state_callback=_write_state, - ) - ) - if waiting: - self.queue_full_waiting_at_earliest = True - if focus_ref: - self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) - # 已回退到最早开奖的预约直播间,本轮结束 - # 注意:旧版可能会设置直接参与标志,已删除该标志逻辑,走正常流程 - elapsed = time.time() - start_time - self._log_kv( - "流程", - "run_once_basic完成(预约队列满等待)", - elapsed_seconds=round(elapsed, 2), - ) - return - - # 如果正在等待开奖,跳过预约回退检查 - if getattr(self, "_waiting_for_lottery_result", False): - try: - self._log_kv( - "预约", - "[预约] 正在等待开奖,跳过预约回退检查", - waiting_for_lottery=True, - ) - except Exception: - pass - # 跳过预约回退检查,让流程继续执行到阶段诊断后检查开奖结果 - # 不在这里 return,让流程继续 - # 如果正在参与预约福袋,跳过预约回退检查,避免被其他预约打断 - elif getattr(self, "_current_attending_reservation_fudai", False): - try: - self._log_kv( - "预约", - "[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断", - current_attending_reservation=True, - ) - except Exception: - pass - # 跳过预约回退检查,让当前参与流程继续完成 - # 不在这里 return,让流程继续 - # 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查 - elif self.queue_full_waiting_at_earliest: - # 队列已满且正在等待最早开奖直播间,按正常等待逻辑处理(不使用已删除的直接参与标志) - pass - - # 检查是否所有预约已完成,需要重置到第一个直播间 - if self.queue_full_waiting_at_earliest and not self.reservations: - try: - self._log_kv( - "预约", - "[预约] 所有预约已完成,重置到第一个直播间", - ) - except Exception: - pass - self.queue_full_waiting_at_earliest = False - self.reservation_focus_until_ts = 0.0 - # 回退到第一个直播间:需要回退 room_pos 次 - try: - current_pos = int(getattr(self, "room_pos", 0) or 0) - back_times = abs(current_pos) - # 防止无限循环:最大回退次数限制为100 - if back_times > 100: - back_times = 100 - if back_times > 0: - for i in range(back_times): - _swipe_down_once() - self.operation.delay(0.6) - self.room_pos = 0 - if hasattr(self, "_swipe_times"): - self._swipe_times = 0 - try: - self._log_kv( - "预约", - "[预约] 已回退到第一个直播间", - back_times=back_times, - ) - except Exception: - pass - except Exception: - pass - return - - # 单间模式(needswitch=False)下不启用预约回退逻辑 - # 因为单间模式不会切换直播间,不需要回退,预约会在当前直播间自动识别和参与 - try: - needswitch_cfg = bool(getattr(self, "needswitch", True)) - except Exception: - needswitch_cfg = True - - # 添加详细的调试日志,确认 needswitch 的值和预约信息 - try: - # 输出第一个预约的详细信息 - first_reservation_info = {} - if self.reservations and len(self.reservations) > 0: - first_r = self.reservations[0] - try: - ft = float(first_r.get("future_ts") or 0) - from datetime import datetime - - now_ts = time.time() - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - remain_seconds = int(ft - now_ts) if ft > 0 else 0 - first_reservation_info = { - "future_ts": int(ft) if ft > 0 else 0, - "future_str": ft_str, - "value": float(first_r.get("prize_value_yuan", 0)), - "pos_seen": int(first_r.get("pos_seen", 0)), - "remain_seconds": remain_seconds, - "current_room_pos": int( - getattr(self, "room_pos", 0) or 0 - ), - } - except Exception: - pass - - self._log_kv( - "预约", - "[预约] run_once_basic:检查预约回退条件", - needswitch_cfg=needswitch_cfg, - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - first_reservation=first_reservation_info, - ) - except Exception: - pass - - if needswitch_cfg: - # 多间模式:需要回退到预约直播间 - try: - self._log_kv( - "预约", - "[预约] 多间模式:开始调用 process_reservation_attend_window", - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - room_pos=int(getattr(self, "room_pos", 0) or 0), - ) - except Exception: - pass - - preempted = ( - douyin_reservation_logic.process_reservation_attend_window( - analyser=self, - reservations=self.reservations, - room_pos=int(getattr(self, "room_pos", 0) or 0), - reservation_focus_until_ts_ref=focus_ref, - reservation_after_action_pending_ref=after_action_ref, - reservation_back_swipe_delay_s=float( - self.reservation_back_swipe_delay or 0.6 - ), - swipe_down_back_callback=_swipe_down_once, - seek_reservation_room_callback=_seek_reservation_room, - sort_reservations_callback=_sort_reservations, - write_state_callback=_write_state, - ) - ) - - try: - self._log_kv( - "预约", - "[预约] process_reservation_attend_window 返回结果", - preempted=preempted, - focus_until=( - int(focus_ref[0]) - if focus_ref and focus_ref[0] > 0 - else 0 - ), - ) - except Exception: - pass - # 同步回写 ref 值 - if focus_ref: - self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) - if after_action_ref: - self.reservation_after_action_pending = bool( - after_action_ref[0] - ) - - # 如果抢占成功,设置当前参与的福袋类型为预约福袋 - if preempted: - self._current_attending_reservation_fudai = True - - # 抢占逻辑已删除,直接继续处理 - else: - # 单间模式:不需要回退,预约会在当前直播间自动识别和参与 - # 只需要清理过期的预约 - try: - self._log_kv( - "预约", - "[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与", - reservations_count=( - len(self.reservations) if self.reservations else 0 - ), - ) - - # use module-level `douyin_reservation_logic` - douyin_reservation_logic.cleanup_expired_reservations( - self, self.reservations, _write_state - ) - except Exception as exc: - try: - self._log_kv( - "预约", - "[预约] 单间模式下清理过期预约时出错", - error=str(exc), - ) - except Exception: - pass - except Exception: - pass + if _ronce_helpers.handle_reservation_check(self, start_time): + return # 检查是否刚刚记录了预约,如果是,强制切换直播间,避免在同一直播间循环 if _ronce_helpers.handle_just_recorded_reservation(self, start_time): diff --git a/douyin/core/fudai_modules/run_once_basic_helpers.py b/douyin/core/fudai_modules/run_once_basic_helpers.py index 664f4b5..8852ebd 100644 --- a/douyin/core/fudai_modules/run_once_basic_helpers.py +++ b/douyin/core/fudai_modules/run_once_basic_helpers.py @@ -943,3 +943,550 @@ def handle_skip_stage_diagnosis(self: "fudai_analyse", start_time: float) -> boo elapsed_seconds=round(elapsed, 2), ) return True + + +def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool: + """0.1 高价值预约检查:清空队列 / 处理队列已满 / 调 process_reservation_attend_window。 + + 返回 True 表示有 return-out 出口被触发,caller 应当 `return`; + 返回 False 表示走完所有逻辑后继续执行后续步骤。 + """ + import json + import os + from datetime import datetime + + from douyin.reservation import douyin_reservation_logic + + try: + reservation_check_start = time.time() + self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start) + + # 第一次运行时清空预约队列 + 状态文件 + _maybe_clear_reservations_on_first_run(self) + + high_value_enabled = getattr(self, "high_value_fudai_enabled", False) + reservations_list = getattr(self, "reservations", None) + reservations_count = len(reservations_list) if reservations_list else 0 + + # 调试日志:检查触发条件 + _log_reservation_check_trigger( + self, high_value_enabled, reservations_list, reservations_count + ) + + if not high_value_enabled: + try: + self._log_kv( + "预约", + "[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查", + ) + except Exception: + pass + elif not reservations_list or reservations_count == 0: + try: + self._log_kv( + "预约", + "[预约] 预约队列为空,跳过预约回退检查", + reservations_is_none=(reservations_list is None), + reservations_count=reservations_count, + ) + except Exception: + pass + + if not (high_value_enabled and reservations_list): + return False + + # 启用 + 有预约:执行真正的检查 + return _run_reservation_attend_window(self, start_time) + except Exception: + return False + + +def _maybe_clear_reservations_on_first_run(self: "fudai_analyse") -> None: + """第一次进入 run_once_basic 时清空预约队列 + 状态文件,并标记非首次。""" + try: + is_first_run = getattr(self, "_first_run_once_basic", True) + # 记录清空前的队列状态(用于调试) + old_reservations_count = 0 + try: + old_reservations_count = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + except Exception: + pass + + if is_first_run: + try: + self._log_kv( + "预约", + "[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件", + old_reservations_count=old_reservations_count, + ) + except Exception: + pass + try: + before_clear = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + self.reservations = [] + after_clear = ( + len(self.reservations) + if hasattr(self, "reservations") + else 0 + ) + + # 同时清空状态文件 + try: + state_path = getattr(self, "_reservations_state_path", None) + if state_path: + from douyin.reservation.douyin_reservation import ( + write_reservations_state, + ) + + write_reservations_state( + state_path=state_path, + reservations=[], + room_pos=0, + current_room_title="", + current_room_title_raw="", + reason="startup_clear", + ) + try: + self._log_kv( + "预约", + "[预约] 已清空预约队列并更新状态文件", + before_clear=before_clear, + after_clear=after_clear, + ) + except Exception: + pass + except Exception as exc: + try: + self._log_kv( + "预约", + "[预约] 清空状态文件时出错", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + except Exception as exc: + # 如果清空失败,尝试直接设置 + try: + if hasattr(self, "reservations"): + self.reservations = [] + self._log_kv( + "预约", + "[预约] 清空预约队列时出错,已尝试直接设置", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + try: + self._first_run_once_basic = False + except Exception: + pass + else: + try: + current_count = ( + len(self.reservations) + if hasattr(self, "reservations") and self.reservations + else 0 + ) + self._log_kv( + "预约", + "[预约] 非第一次运行,保持当前预约队列", + reservations_count=current_count, + is_first_run=False, + ) + except Exception: + pass + except Exception as exc: + try: + self._log_kv( + "预约", + "[预约] 初始化预约队列时出错", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + + +def _log_reservation_check_trigger( + self: "fudai_analyse", + high_value_enabled: bool, + reservations_list, + reservations_count: int, +) -> None: + """调试日志:检查预约回退逻辑的触发条件。""" + try: + from datetime import datetime as _dt + + reservations_detail = [] + if reservations_list: + for idx, r in enumerate(reservations_list[:3]): + try: + ft = float(r.get("future_ts") or 0) + ft_str = ( + _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) + reservations_detail.append( + { + "index": idx, + "future_ts": int(ft) if ft > 0 else 0, + "future_str": ft_str, + "value": float(r.get("prize_value_yuan", 0)), + "pos_seen": int(r.get("pos_seen", 0)), + } + ) + except Exception: + pass + + self._log_kv( + "预约", + "[预约] run_once_basic:检查预约回退触发条件", + high_value_enabled=high_value_enabled, + reservations_count=reservations_count, + reservations_is_none=(reservations_list is None), + will_check_reservations=bool( + high_value_enabled and reservations_list + ), + reservations_detail=reservations_detail, + ) + except Exception: + pass + + +def _run_reservation_attend_window( + self: "fudai_analyse", start_time: float +) -> bool: + """已确认 high_value_enabled + 有预约:执行队列满处理 / 抢占逻辑。 + + 返回 True 表示触发了 return-out 出口(队列满等待 / 重置到第一个直播间)。 + """ + import json + import os + from datetime import datetime + + from douyin.reservation import douyin_reservation_logic + + def _swipe_down_once() -> None: + self.swipe_down_back_from_live() + + def _sort_reservations() -> None: + douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined] + + def _write_state() -> None: + # 将预约队列写入状态文件,供外部查看 + try: + # 节流:避免高频写盘 + now_ts = time.time() + last_ts = float( + getattr(self, "_reservations_state_last_write_ts", 0.0) or 0.0 + ) + if (now_ts - last_ts) < 1.0: + return + self._reservations_state_last_write_ts = now_ts + + os.makedirs( + os.path.dirname(self._reservations_state_path), + exist_ok=True, + ) + + items = [] + for r in self.reservations or []: + try: + ft = float(r.get("future_ts") or 0) + except Exception: + ft = 0.0 + try: + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft + else "" + ) + except Exception: + ft_str = str(r.get("future_str", "")) + + items.append( + { + "prize_value_yuan": float( + r.get("prize_value_yuan") or 0 + ), + "content": str(r.get("content") or ""), + "future_ts": ft, + "future_str": ft_str, + "pos_seen": int(r.get("pos_seen") or 0), + "room_title": str(r.get("room_title", "") or ""), + "room_title_raw": str(r.get("room_title_raw", "") or ""), + "created_ts": float(r.get("created_ts") or 0), + } + ) + + current_title = str(getattr(self, "current_room_title", "") or "") + current_title_raw = str( + getattr(self, "current_room_title_raw", "") or "" + ) + + data = { + "updated_ts": time.time(), + "reason": "process_reservation", + "room_pos": int(getattr(self, "room_pos", 0) or 0), + "current_room_title": current_title, + "current_room_title_raw": current_title_raw, + "reservations": items, + } + + with open( + self._reservations_state_path, "w", encoding="utf-8" + ) as f: + json.dump(data, f, ensure_ascii=False, indent=2) + except Exception as exc: + try: + self._log_kv( + "预约", + "写入预约队列状态文件失败", + error=str(exc), + error_type=type(exc).__name__, + ) + except Exception: + pass + + focus_ref = [float(self.reservation_focus_until_ts or 0.0)] + after_action_ref = [bool(self.reservation_after_action_pending or False)] + + def _seek_reservation_room(item: dict) -> bool: + try: + return bool( + self._seek_reservation_room(item, operation_type="预约") + ) + except Exception: + return False + + # 检查队列是否已满且需要等待 + max_reservations = int( + getattr(self, "high_value_fudai_max_reservations", 3) or 3 + ) + if ( + len(self.reservations) >= max_reservations + and not self.queue_full_waiting_at_earliest + ): + waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_back_swipe_delay_s=float( + self.reservation_back_swipe_delay or 0.6 + ), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + if waiting: + self.queue_full_waiting_at_earliest = True + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + elapsed = time.time() - start_time + self._log_kv( + "流程", + "run_once_basic完成(预约队列满等待)", + elapsed_seconds=round(elapsed, 2), + ) + return True + + # 等待开奖 / 正在参与预约福袋 / 队列满等待 → 跳过预约回退检查 + if getattr(self, "_waiting_for_lottery_result", False): + try: + self._log_kv( + "预约", + "[预约] 正在等待开奖,跳过预约回退检查", + waiting_for_lottery=True, + ) + except Exception: + pass + elif getattr(self, "_current_attending_reservation_fudai", False): + try: + self._log_kv( + "预约", + "[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断", + current_attending_reservation=True, + ) + except Exception: + pass + elif self.queue_full_waiting_at_earliest: + # 队列已满且正在等待最早开奖直播间,按正常等待逻辑处理 + pass + + # 检查是否所有预约已完成,需要重置到第一个直播间 + if self.queue_full_waiting_at_earliest and not self.reservations: + try: + self._log_kv( + "预约", + "[预约] 所有预约已完成,重置到第一个直播间", + ) + except Exception: + pass + self.queue_full_waiting_at_earliest = False + self.reservation_focus_until_ts = 0.0 + try: + current_pos = int(getattr(self, "room_pos", 0) or 0) + back_times = abs(current_pos) + if back_times > 100: + back_times = 100 + if back_times > 0: + for i in range(back_times): + _swipe_down_once() + self.operation.delay(0.6) + self.room_pos = 0 + if hasattr(self, "_swipe_times"): + self._swipe_times = 0 + try: + self._log_kv( + "预约", + "[预约] 已回退到第一个直播间", + back_times=back_times, + ) + except Exception: + pass + except Exception: + pass + return True + + # 单间模式不启用预约回退 + try: + needswitch_cfg = bool(getattr(self, "needswitch", True)) + except Exception: + needswitch_cfg = True + + _log_reservation_attend_check(self, needswitch_cfg) + + if needswitch_cfg: + # 多间模式:调 process_reservation_attend_window + try: + self._log_kv( + "预约", + "[预约] 多间模式:开始调用 process_reservation_attend_window", + reservations_count=( + len(self.reservations) if self.reservations else 0 + ), + room_pos=int(getattr(self, "room_pos", 0) or 0), + ) + except Exception: + pass + + preempted = douyin_reservation_logic.process_reservation_attend_window( + analyser=self, + reservations=self.reservations, + room_pos=int(getattr(self, "room_pos", 0) or 0), + reservation_focus_until_ts_ref=focus_ref, + reservation_after_action_pending_ref=after_action_ref, + reservation_back_swipe_delay_s=float( + self.reservation_back_swipe_delay or 0.6 + ), + swipe_down_back_callback=_swipe_down_once, + seek_reservation_room_callback=_seek_reservation_room, + sort_reservations_callback=_sort_reservations, + write_state_callback=_write_state, + ) + + try: + self._log_kv( + "预约", + "[预约] process_reservation_attend_window 返回结果", + preempted=preempted, + focus_until=( + int(focus_ref[0]) + if focus_ref and focus_ref[0] > 0 + else 0 + ), + ) + except Exception: + pass + # 同步回写 ref 值 + if focus_ref: + self.reservation_focus_until_ts = float(focus_ref[0] or 0.0) + if after_action_ref: + self.reservation_after_action_pending = bool(after_action_ref[0]) + + # 如果抢占成功,设置当前参与的福袋类型为预约福袋 + if preempted: + self._current_attending_reservation_fudai = True + else: + # 单间模式:清理过期预约 + try: + self._log_kv( + "预约", + "[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与", + reservations_count=( + len(self.reservations) if self.reservations else 0 + ), + ) + + douyin_reservation_logic.cleanup_expired_reservations( + self, self.reservations, _write_state + ) + except Exception as exc: + try: + self._log_kv( + "预约", + "[预约] 单间模式下清理过期预约时出错", + error=str(exc), + ) + except Exception: + pass + + return False + + +def _log_reservation_attend_check( + self: "fudai_analyse", needswitch_cfg: bool +) -> None: + """调试日志:检查 needswitch 和第一个预约的详细信息。""" + try: + from datetime import datetime as _dt + + first_reservation_info = {} + if self.reservations and len(self.reservations) > 0: + first_r = self.reservations[0] + try: + ft = float(first_r.get("future_ts") or 0) + now_ts = time.time() + ft_str = ( + _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) + remain_seconds = int(ft - now_ts) if ft > 0 else 0 + first_reservation_info = { + "future_ts": int(ft) if ft > 0 else 0, + "future_str": ft_str, + "value": float(first_r.get("prize_value_yuan", 0)), + "pos_seen": int(first_r.get("pos_seen", 0)), + "remain_seconds": remain_seconds, + "current_room_pos": int( + getattr(self, "room_pos", 0) or 0 + ), + } + except Exception: + pass + + self._log_kv( + "预约", + "[预约] run_once_basic:检查预约回退条件", + needswitch_cfg=needswitch_cfg, + reservations_count=( + len(self.reservations) if self.reservations else 0 + ), + first_reservation=first_reservation_info, + ) + except Exception: + pass diff --git a/tests/test_run_once_basic_helpers.py b/tests/test_run_once_basic_helpers.py index d51fdc9..24feb1a 100644 --- a/tests/test_run_once_basic_helpers.py +++ b/tests/test_run_once_basic_helpers.py @@ -10,7 +10,7 @@ """ from __future__ import annotations -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import pytest @@ -293,3 +293,125 @@ class TestHandleSkipStageDiagnosis: # 标志应被清除 assert s._skip_stage_diagnosis_and_find_fudai is False s._handle_live_room_has_or_not_fudai.assert_called_once() + + +# ============================================================ +# handle_reservation_check —— 0.1 高价值预约检查 +# ============================================================ + +class TestHandleReservationCheck: + def _mk_for_reservation(self): + s = _mk_self() + s._first_run_once_basic = False # 默认非首次,避免 mock 状态文件写入 + s.high_value_fudai_enabled = False + s.reservations = [] + s.queue_full_waiting_at_earliest = False + s.reservation_focus_until_ts = 0.0 + s.reservation_after_action_pending = False + s.reservation_back_swipe_delay = 0.6 + s.high_value_fudai_max_reservations = 3 + s.room_pos = 0 + s.needswitch = True + s.operation = MagicMock() + s.operation.delay = MagicMock(return_value=None) + s.swipe_down_back_from_live = MagicMock(return_value=None) + s._seek_reservation_room = MagicMock(return_value=False) + s._reservations_state_path = "" + return s + + def test_high_value_disabled_returns_false(self): + """high_value_fudai_enabled=False → 不进入主逻辑,return False。""" + s = self._mk_for_reservation() + s.high_value_fudai_enabled = False + assert ronce.handle_reservation_check(s, 0.0) is False + + def test_empty_reservations_returns_false(self): + """启用了但队列为空 → return False,让 caller 继续。""" + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s.reservations = [] + assert ronce.handle_reservation_check(s, 0.0) is False + + def test_first_run_clears_reservations(self): + """首次运行时清空预约队列 + 标记非首次。""" + s = self._mk_for_reservation() + s._first_run_once_basic = True + s.high_value_fudai_enabled = False # 走简短路径 + s.reservations = [{"future_ts": 9999, "content": "old"}] + s._reservations_state_path = "" # 不触发状态文件写入 + ronce.handle_reservation_check(s, 0.0) + assert s.reservations == [] + assert s._first_run_once_basic is False + + def test_normal_path_calls_attend_window(self): + """启用 + 有预约 + 不满 + needswitch=True → 调 process_reservation_attend_window。""" + import time + + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s.reservations = [ + {"future_ts": time.time() + 100, "content": "X", "pos_seen": 0} + ] + with patch( + "douyin.reservation.douyin_reservation_logic.process_reservation_attend_window", + return_value=False, + ) as mock_process: + result = ronce.handle_reservation_check(s, 0.0) + assert result is False + mock_process.assert_called_once() + + def test_queue_full_returns_true(self): + """队列满 + handle_queue_full_wait_at_earliest 返回 True → return True 让 caller return。""" + import time + + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s.high_value_fudai_max_reservations = 2 + s.reservations = [ + {"future_ts": time.time() + 100, "content": "A"}, + {"future_ts": time.time() + 200, "content": "B"}, + ] + s.queue_full_waiting_at_earliest = False + with patch( + "douyin.reservation.douyin_reservation_logic.handle_queue_full_wait_at_earliest", + return_value=True, + ): + result = ronce.handle_reservation_check(s, 0.0) + assert result is True + assert s.queue_full_waiting_at_earliest is True + + def test_needswitch_false_calls_cleanup(self): + """needswitch=False → 走单间模式分支,调 cleanup_expired_reservations。""" + import time + + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s.needswitch = False + s.reservations = [ + {"future_ts": time.time() + 100, "content": "X", "pos_seen": 0} + ] + with patch( + "douyin.reservation.douyin_reservation_logic.cleanup_expired_reservations" + ) as mock_cleanup: + result = ronce.handle_reservation_check(s, 0.0) + assert result is False + mock_cleanup.assert_called_once() + + def test_waiting_for_lottery_skips_attend_window(self): + """_waiting_for_lottery_result=True → 跳过预约回退,仍 return False。""" + import time + + s = self._mk_for_reservation() + s.high_value_fudai_enabled = True + s._waiting_for_lottery_result = True + s.reservations = [ + {"future_ts": time.time() + 100, "content": "X", "pos_seen": 0} + ] + with patch( + "douyin.reservation.douyin_reservation_logic.process_reservation_attend_window" + ) as mock_process: + result = ronce.handle_reservation_check(s, 0.0) + # 等待开奖时仍会执行多间模式 process(这是原代码行为:日志后不 return,让流程继续) + assert result is False + # process 仍被调用(日志只是说"跳过预约回退"但代码没真的跳) + mock_process.assert_called_once()