From 74209035f7c68f425f9c0ddbdb1ff722b8d8d3af Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 21 May 2026 17:03:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8B=86=E5=88=86=20douyin=5Freservation=5Flog?= =?UTF-8?q?ic=20(2702=20=E2=86=92=207=20=E4=B8=AA=E5=AD=90=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=20+=2053=20=E8=A1=8C=20shim)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把 douyin/reservation/douyin_reservation_logic.py 按职责拆成 douyin/reservation/reservation_logic/ 子包: - _common (57) 共享错误处理工具占位 + ReservationItem 类型 - helpers (130) 内部工具:标题归一化 / 相似度 / 排序 / 时间戳 - add (447) add_reservation_core_logic 主入口(添加新预约) - cleanup_validate (136) validate_back_to_reservation / cleanup_expired_reservations - queue_full (305) handle_queue_full_wait_at_earliest 队列满时等待策略 - attend_window (1437) process_reservation_attend_window 进入预约窗口(最大头) - record (328) record_high_value_reservation 高价值预约登记入口 原文件改为 53 行 re-export shim,17 个公共符号全部保留。 - process_reservation_attend_window 7 处外部引用 - handle_queue_full_wait_at_earliest 5 处外部引用 - _now_ts 5 处 / cleanup_expired_reservations 4 处 / _sort_reservations_inplace 4 处 - 其他 5 处以下 全部不需修改。 回归: - 8 个新文件 + shim compileall 通过 - pytest 353 passed / 1 skipped - 旧 import 路径与新子包路径返回同一函数对象 - _now_ts / _normalize_room_title / _calculate_string_similarity 等纯函数 调用结果与拆分前一致 Co-Authored-By: Claude Opus 4.7 --- .../reservation/douyin_reservation_logic.py | 2747 +---------------- .../reservation/reservation_logic/__init__.py | 60 + .../reservation/reservation_logic/_common.py | 57 + douyin/reservation/reservation_logic/add.py | 447 +++ .../reservation_logic/attend_window.py | 1437 +++++++++ .../reservation_logic/cleanup_validate.py | 136 + .../reservation/reservation_logic/helpers.py | 130 + .../reservation_logic/queue_full.py | 305 ++ .../reservation/reservation_logic/record.py | 328 ++ 9 files changed, 2949 insertions(+), 2698 deletions(-) create mode 100644 douyin/reservation/reservation_logic/__init__.py create mode 100644 douyin/reservation/reservation_logic/_common.py create mode 100644 douyin/reservation/reservation_logic/add.py create mode 100644 douyin/reservation/reservation_logic/attend_window.py create mode 100644 douyin/reservation/reservation_logic/cleanup_validate.py create mode 100644 douyin/reservation/reservation_logic/helpers.py create mode 100644 douyin/reservation/reservation_logic/queue_full.py create mode 100644 douyin/reservation/reservation_logic/record.py diff --git a/douyin/reservation/douyin_reservation_logic.py b/douyin/reservation/douyin_reservation_logic.py index c18b2ee..932d415 100644 --- a/douyin/reservation/douyin_reservation_logic.py +++ b/douyin/reservation/douyin_reservation_logic.py @@ -1,2702 +1,53 @@ -from __future__ import annotations +"""douyin_reservation_logic - 兼容入口(保留外部 import 路径)。 -""" -高价值福袋预约核心逻辑(模块化版本) -================================== +实际实现位于子包 ``douyin.reservation.reservation_logic``。 +本文件仅 re-export 公共符号;详见各子模块文档: -本模块从原始 `fudai1.py` 的思路抽取并简化了预约相关逻辑,保留了这些要点: -- 以 future_ts(预计开奖时间戳)为主排序键,其次 prize_value_yuan,再次 created_ts; -- 预约队列长度受 high_value_fudai_max_reservations 限制,溢出时裁剪掉优先级最低的记录; -- 进入预约窗口时可以抢占当前流程,回退到目标直播间,再由上层去识别详情并参与; -- 支持轻量的“回退校验”和状态写回(供 GUI / Web 端展示)。 - -接口签名与之前的 shim 保持兼容,便于在 `douyin_fudai.py` / `douyin_flow_control.py` -中直接调用。 +- ``reservation_logic._common`` 共享错误处理工具 + ReservationItem 类型 +- ``reservation_logic.helpers`` 内部工具:标题归一化 / 相似度 / 排序 +- ``reservation_logic.add`` add_reservation_core_logic 主入口 +- ``reservation_logic.cleanup_validate`` validate_back_to_reservation / cleanup_expired_reservations +- ``reservation_logic.queue_full`` handle_queue_full_wait_at_earliest +- ``reservation_logic.attend_window`` process_reservation_attend_window(最大头) +- ``reservation_logic.record`` record_high_value_reservation """ -from typing import Any, Dict, List, Callable, Optional -import time -import re - -# 导入预约错误处理工具(在类型检查时导入真实签名以满足静态分析) -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from douyin.reservation.core.reservation_error_utils import ( # pragma: no cover - log_reservation_error, - safe_write_state, - format_reservation_context, - validate_reservation_item, - ) - - _RESERVATION_ERROR_UTILS_AVAILABLE = True -else: - try: - from douyin.reservation.core.reservation_error_utils import ( # type: ignore[import] - log_reservation_error, - safe_write_state, - format_reservation_context, - validate_reservation_item, - ) - - _RESERVATION_ERROR_UTILS_AVAILABLE = True - except Exception: - # 运行时回退到通用占位实现(使用宽松签名以兼容各种调用) - def log_reservation_error(*args, **kwargs) -> None: - return None - - def safe_write_state(*args, **kwargs) -> bool: - return True - - def format_reservation_context(*args, **kwargs) -> Dict[str, Any]: - return {} - - def validate_reservation_item(*args, **kwargs) -> bool: - return True - - _RESERVATION_ERROR_UTILS_AVAILABLE = False - -# 为兼容类型检查,将实际导入或占位函数转换为 Any(避免赋值/导入时的类型不匹配报错) -from typing import Any as _Any, cast - -log_reservation_error = cast(_Any, log_reservation_error) -safe_write_state = cast(_Any, safe_write_state) -format_reservation_context = cast(_Any, format_reservation_context) -validate_reservation_item = cast(_Any, validate_reservation_item) - -ReservationItem = Dict[str, Any] - - -def _now_ts() -> float: - return time.time() - - -def _normalize_room_title_for_matching(title: str) -> str: - """规范化直播间标题用于匹配比较。 - - 去除数字、特殊字符等,只保留核心名称部分。 - 例如:"王媛媛" 和 "王媛媛2" 会被规范化为相同的字符串。 - """ - if not title: - return "" - # 去除空格和换行 - s = str(title).replace("\r", " ").replace("\n", " ").strip() - s = re.sub(r"\s+", "", s) - # 去除常见无关词 - for w in ( - "点赞", - "赞", - "关注", - "粉丝", - "直播中", - "正在直播", - "进入直播间", - "推荐", - "在线", - "人在线", - ): - s = s.replace(w, "") - # 去除数字和特殊字符,只保留中文、英文、数字(但去除末尾的数字) - # 先去除末尾的数字(如 "王媛媛2" -> "王媛媛") - s = re.sub(r"\d+$", "", s) - # 去除所有特殊字符,只保留中文、英文 - s = re.sub(r"[^A-Za-z\u4e00-\u9fff]", "", s) - return s - - -def _calculate_string_similarity(s1: str, s2: str) -> float: - """计算两个字符串的相似度(简单的字符重叠比例)。 - - 返回 0.0 到 1.0 之间的值,1.0 表示完全相同。 - """ - if not s1 or not s2: - return 0.0 - if s1 == s2: - return 1.0 - - # 计算字符集合的交集和并集 - set1 = set(s1) - set2 = set(s2) - intersection = len(set1 & set2) - union = len(set1 | set2) - - if union == 0: - return 0.0 - - # Jaccard相似度 - jaccard = intersection / union - - # 如果长度相近,额外加分 - len_ratio = ( - min(len(s1), len(s2)) / max(len(s1), len(s2)) - if max(len(s1), len(s2)) > 0 - else 0.0 - ) - - # 综合相似度(Jaccard占70%,长度比例占30%) - similarity = jaccard * 0.7 + len_ratio * 0.3 - - return similarity - - -def _extract_content_core(content: str) -> str: - """提取福袋内容的核心部分(去除倒计时等变化部分)。 - - 例如:"10后开奖03(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" - 提取为:"琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" - """ - if not content: - return "" - # 去除开头的倒计时部分(如 "10后开奖03"、"06后开奖09" 等) - # 匹配模式:数字+后开奖+数字 - s = re.sub(r"^\d+后开奖\d+", "", content) - # 去除开头的括号和数字 - s = re.sub(r"^[\((]\d+", "", s) - # 去除开头的数字 - s = re.sub(r"^\d+", "", s) - # 去除前后空格 - s = s.strip() - return s - - -def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None: - """按 future_ts 升序,其次 prize_value_yuan 降序,其次 created_ts 升序排序。""" - - def _key(it: ReservationItem): - ft = float(it.get("future_ts") or 0.0) - val = float(it.get("prize_value_yuan") or 0.0) - created = float(it.get("created_ts") or 0.0) - # future_ts 越小越优先;价值越大越优先(因此取 -val);创建时间越早越优先 - return (ft, -val, created) - - reservations.sort(key=_key) - - -def add_reservation_core_logic( - reservations: List[ReservationItem], - item: ReservationItem, - max_reservations: Optional[int] = None, - analyser: Any = None, - write_state_callback: Optional[Callable[[], None]] = None, -) -> bool: - """向预约队列追加/更新一条记录,并根据上限裁剪。 - - 去重策略: - - key = (future_ts, content) 相同则视为同一条记录,保留价值更高的那条。 - - 如果直播间名字相同(规范化后),且 (future_ts, content) 相同,也视为同一条记录。 - - 返回: - bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。 - """ - start_time = time.time() - step_start_time = start_time - - ft = float(item.get("future_ts") or 0.0) - content = str(item.get("content") or "") - prize_value = float(item.get("prize_value_yuan") or 0.0) - room_title = str(item.get("room_title") or "") - room_title_normalized = _normalize_room_title_for_matching(room_title) - - # 步骤1: 参数处理和规范化 - try: - analyser._log_kv( - "预约", - "[预约] 步骤1: 参数处理和规范化", - log_type="OP", - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - step_start_time = time.time() - - # 添加函数入口日志 - try: - from datetime import datetime - - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - analyser._log_kv( - "预约", - "[预约] add_reservation_core_logic 函数入口", - log_type="OP", - future_ts=int(ft) if ft > 0 else 0, - future_str=ft_str, - prize_value_yuan=prize_value, - room_title=room_title[:50] if room_title else "", - content=content[:50] if content else "", - queue_len_before=len(reservations), - max_reservations=max_reservations, - ) - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context(item=item, reservations=reservations), - level="WARNING", - stage="记录函数入口日志", - ) - else: - try: - analyser._log_kv( - "预约", "[预约] 记录函数入口日志失败", log_type="ERR", error=str(e) - ) - except Exception: - pass - - # 步骤2: 查找是否已存在相同预约 - try: - analyser._log_kv( - "预约", - "[预约] 步骤2: 开始查找是否已存在相同预约", - log_type="OP", - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - step_start_time = time.time() - - same_idx: Optional[int] = None - for idx, r in enumerate(reservations): - try: - r_ft = float(r.get("future_ts") or 0.0) - r_content = str(r.get("content") or "") - r_prize_value = float(r.get("prize_value_yuan") or 0.0) - r_room_title = str(r.get("room_title") or "") - r_room_title_normalized = _normalize_room_title_for_matching(r_room_title) - - # 判断是否为同一个预约: - # 1. (future_ts, content) 相同,且直播间名字相同(规范化后) - # 2. 或者 (future_ts, content) 相同(兼容旧数据,没有直播间名字的情况) - # 3. 或者通过相似度匹配:直播间名称相似 + 开奖时间相近 + 奖品价值相同 + 内容核心部分相似 - is_same_future_and_content = r_ft == ft and r_content == content - is_same_room_title = ( - room_title_normalized - and r_room_title_normalized - and room_title_normalized == r_room_title_normalized - ) - - # 相似度匹配(处理OCR误差) - is_similar_room_title = False - is_similar_time = False - is_same_prize_value = False - is_similar_content = False - - if room_title_normalized and r_room_title_normalized: - # 计算直播间名称相似度 - room_title_similarity = _calculate_string_similarity( - room_title_normalized, r_room_title_normalized - ) - # 如果一个是另一个的子串,或者相似度 >= 0.6,视为相似 - is_similar_room_title = ( - room_title_normalized in r_room_title_normalized - or r_room_title_normalized in room_title_normalized - or room_title_similarity >= 0.6 - ) - - # 开奖时间相近(相差60秒内,放宽容忍度以处理OCR误差和实际时间差) - time_diff = abs(r_ft - ft) - is_similar_time = time_diff <= 60.0 - - # 奖品价值相同(允许0.01的误差) - prize_diff = abs(r_prize_value - prize_value) - is_same_prize_value = prize_diff < 0.01 - - # 内容核心部分相似 - content_core = _extract_content_core(content) - r_content_core = _extract_content_core(r_content) - if content_core and r_content_core: - content_similarity = _calculate_string_similarity( - content_core, r_content_core - ) - is_similar_content = content_similarity >= 0.7 - - # 判断是否为同一个预约 - if is_same_future_and_content: - # 如果 (future_ts, content) 相同 - if is_same_room_title: - # 直播间名字也相同(规范化后),确定是同一个预约 - same_idx = idx - break - elif not room_title_normalized and not r_room_title_normalized: - # 都没有直播间名字,视为同一个预约(兼容旧数据) - same_idx = idx - break - # 如果只有一个有直播间名字,也视为同一个预约(兼容旧数据) - elif (room_title_normalized and not r_room_title_normalized) or ( - not room_title_normalized and r_room_title_normalized - ): - same_idx = idx - break - # 如果直播间名称相同(规范化后)且价值相同,即使时间差稍大也视为重复 - elif is_same_room_title and is_same_prize_value and time_diff <= 300.0: - # 直播间名称相同且价值相同,时间差在5分钟内,视为重复 - same_idx = idx - try: - if analyser: - analyser._log_kv( - "预约", - "[预约] 通过直播间名称和价值匹配识别为重复预约", - log_type="OP", - room_title_normalized=room_title_normalized, - time_diff=round(time_diff, 2), - prize_value_yuan=prize_value, - ) - except Exception: - pass - break - elif ( - is_similar_room_title - and is_similar_time - and is_same_prize_value - and ( - is_similar_content - or ( - # 如果内容核心均为空(OCR 未识别到内容),则允许仅凭直播间名称相似、时间接近和价值相同判定为重复 - not content_core - and not r_content_core - ) - ) - ): - # 通过相似度匹配判断为同一个预约(处理OCR误差) - same_idx = idx - try: - if analyser: - analyser._log_kv( - "预约", - "[预约] 通过相似度匹配识别为重复预约", - log_type="OP", - room_title_normalized=room_title_normalized, - r_room_title_normalized=r_room_title_normalized, - time_diff=round(time_diff, 2), - prize_diff=round(prize_diff, 2), - content_core=content_core[:50], - r_content_core=r_content_core[:50], - ) - except Exception: - pass - break - except Exception: - continue - - # 步骤3: 相似度匹配完成 - try: - analyser._log_kv( - "预约", - "[预约] 步骤3: 相似度匹配完成", - log_type="OP", - same_idx=same_idx, - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - step_start_time = time.time() - - if same_idx is not None: - # 若新记录价值更高,则更新 - try: - old_val = float(reservations[same_idx].get("prize_value_yuan") or 0.0) - except Exception: - old_val = 0.0 - if prize_value > old_val: - try: - analyser._log_kv( - "预约", - "[预约] 检测到重复预约,更新为更高价值", - same_idx=same_idx, - old_value_yuan=old_val, - new_value_yuan=prize_value, - future_ts=int(ft) if ft > 0 else 0, - ) - except Exception: - pass - reservations[same_idx].update(dict(item)) - else: - try: - analyser._log_kv( - "预约", - "[预约] 检测到重复预约,但新价值不高于旧值,保留旧记录", - same_idx=same_idx, - old_value_yuan=old_val, - new_value_yuan=prize_value, - future_ts=int(ft) if ft > 0 else 0, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "预约", - "[预约] 添加新预约到队列", - future_ts=int(ft) if ft > 0 else 0, - prize_value_yuan=prize_value, - queue_len_before=len(reservations), - ) - except Exception: - pass - reservations.append(dict(item)) - - # 步骤4: 添加/更新预约完成 - try: - analyser._log_kv( - "预约", - "[预约] 步骤4: 添加/更新预约完成", - log_type="OP", - same_idx=same_idx, - queue_len_after=len(reservations), - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - step_start_time = time.time() - - # 排序 + 按上限裁剪 - _sort_reservations_inplace(reservations) - - # 步骤5: 排序完成 - try: - analyser._log_kv( - "预约", - "[预约] 步骤5: 排序完成", - log_type="OP", - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - step_start_time = time.time() - - queue_full = False - if ( - max_reservations is not None - and max_reservations > 0 - and len(reservations) > max_reservations - ): - # 记录被丢弃的记录信息 - dropped_items = reservations[max_reservations:] - for dropped in dropped_items: - try: - dropped_value = float(dropped.get("prize_value_yuan") or 0.0) - dropped_future_ts = float(dropped.get("future_ts") or 0.0) - dropped_content = str(dropped.get("content") or "")[:50] - try: - from datetime import datetime - - dropped_future_str = datetime.fromtimestamp( - dropped_future_ts - ).strftime("%Y-%m-%d %H:%M:%S") - except Exception: - dropped_future_str = str(dropped_future_ts) - - if analyser: - try: - analyser._log_kv( - "预约", - "预约队列已满,丢弃最低优先级记录", - cap=max_reservations, - dropped_value_yuan=dropped_value, - dropped_future_ts=int(dropped_future_ts), - dropped_future_str=dropped_future_str, - dropped_content=dropped_content, - queue_len_before=len(reservations), - ) - except Exception: - pass - except Exception: - pass - - # 按当前排序规则,队尾是"优先级最低"的记录 - del reservations[max_reservations:] - queue_full = True - - try: - analyser._log_kv( - "预约", - "[预约] 预约队列已满,已裁剪到上限", - max_reservations=max_reservations, - queue_len_after=len(reservations), - dropped_count=len(dropped_items), - ) - except Exception: - pass - - # 如果队列已满,写入状态文件 - if write_state_callback: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - safe_write_state( - write_state_callback, - analyser, - format_reservation_context( - item=item, - reservations=reservations, - queue_full=True, - dropped_count=len(dropped_items) if dropped_items else 0, - ), - ) - else: - try: - write_state_callback() - except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] 写入状态文件失败(队列已满)", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 步骤6: 队列裁剪和状态写入完成 - try: - analyser._log_kv( - "预约", - "[预约] 步骤6: 队列裁剪和状态写入完成", - log_type="OP", - queue_full=queue_full, - queue_len_final=len(reservations), - elapsed_seconds=round(time.time() - step_start_time, 3), - ) - except Exception: - pass - - # 添加函数完成日志 - try: - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] add_reservation_core_logic 完成", - log_type="OP", - queue_len_after=len(reservations), - queue_full=queue_full, - elapsed_seconds=round(elapsed, 3), - ) - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context(item=item, reservations=reservations), - level="WARNING", - stage="记录函数完成日志", - ) - else: - try: - analyser._log_kv( - "预约", "[预约] 记录函数完成日志失败", log_type="ERR", error=str(e) - ) - except Exception: - pass - - return queue_full - - -def validate_back_to_reservation( - analyser: Any, - reservations: List[ReservationItem], - now_ts: float | None = None, -) -> None: - """回退校验:当前实现为轻量版本,仅记录日志,保留扩展点。""" - if now_ts is None: - now_ts = _now_ts() - try: - analyser._log_kv( - "预约", - "[预约] validate_back_to_reservation", - log_type="OP", - count=len(reservations), - now_ts=int(now_ts), - ) - except Exception: - pass - - -def cleanup_expired_reservations( - analyser: Any, - reservations: List[ReservationItem], - write_state_callback: Optional[Callable[[], None]] = None, -) -> None: - """清理已过开奖时间的预约,并视情况写入状态文件。""" - start_time = time.time() - try: - now_ts_drop = _now_ts() - before = len(reservations) - - # 记录被清理的预约详情 - dropped_items_detail = [] - for r in reservations: - try: - r_ft = float(r.get("future_ts") or 0.0) - if r_ft <= now_ts_drop: - dropped_items_detail.append( - { - "future_ts": int(r_ft), - "prize_value_yuan": float(r.get("prize_value_yuan", 0)), - "content": str(r.get("content", ""))[:50], - "room_title": str(r.get("room_title", ""))[:30], - } - ) - except Exception: - pass - - reservations[:] = [ - r for r in reservations if float(r.get("future_ts") or 0.0) > now_ts_drop - ] - dropped = max(0, before - len(reservations)) - - if dropped: - try: - from datetime import datetime - - now_str = datetime.fromtimestamp(now_ts_drop).strftime( - "%Y-%m-%d %H:%M:%S" - ) - analyser._log_kv( - "预约", - "[预约] cleanup_expired_reservations:清理过期预约", - dropped_count=dropped, - remain_count=len(reservations), - now_ts=int(now_ts_drop), - now_str=now_str, - dropped_items=dropped_items_detail[:5], # 只记录前5个,避免日志过长 - ) - except Exception: - pass - - if write_state_callback is not None: - try: - write_state_callback() - except Exception: - pass - else: - try: - analyser._log_kv( - "预约", - "[预约] cleanup_expired_reservations:无需清理", - queue_len=len(reservations), - now_ts=int(now_ts_drop), - ) - except Exception: - pass - except Exception as e: - # Best-effort cleanup only; never crash主循环 - try: - analyser._log_kv( - "预约", - "[预约] cleanup_expired_reservations 异常", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - try: - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] cleanup_expired_reservations 完成", - elapsed_seconds=round(elapsed, 3), - ) - except Exception: - pass - - -def handle_queue_full_wait_at_earliest( - analyser: Any, - reservations: List[ReservationItem], - room_pos: int, - reservation_focus_until_ts_ref: List[float], - 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;否则返回 False。 - """ - start_time = time.time() - - try: - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest 函数入口", - queue_len=len(reservations) if reservations else 0, - room_pos=room_pos, - ) - except Exception: - pass - - if not reservations: - try: - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest:预约队列为空,跳过", - ) - except Exception: - pass - return False - - # 排序确保取到最早开奖的 - sort_reservations_callback() - - # 取最早开奖的预约 - earliest = reservations[0] - try: - ft = float(earliest.get("future_ts") or 0.0) - except Exception: - ft = 0.0 - - if ft <= 0: - try: - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest:最早预约 future_ts 无效,跳过", - future_ts=ft, - ) - except Exception: - 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,禁止为负数) - poll_before: float = 0.0 - - # 如果已经在锁定期内,不需要重复回退 - if focus_until > 0 and now_ts < focus_until: - try: - from datetime import datetime - - focus_until_str = datetime.fromtimestamp(focus_until).strftime( - "%Y-%m-%d %H:%M:%S" - ) - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest:已在锁定期内,跳过回退", - focus_until=int(focus_until), - focus_until_str=focus_until_str, - lock_period_remain_seconds=int(focus_until - now_ts), - ) - except Exception: - pass - return False - - try: - analyser._log_kv( - "预约", - "[预约] 队列已满,回退到最早开奖的预约直播间等待", - earliest_future_ts=int(ft), - queue_len=len(reservations), - room_pos=int(room_pos), - ) - except Exception: - pass - - # 先进行阶段诊断,处理弹窗等,避免卡死在某个页面 - try: - # 确保有最新截图 - try: - analyser.operation.get_screenshot(analyser.device_id, use_service=False) - except Exception: - pass - - from douyin.stage import douyin_stage - - result = douyin_stage.diagnose_stage_from_current_screen(analyser) - if result is None: - stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") - else: - stage, reason = result - - # 如果检测到需要处理的弹窗或异常状态,先处理 - if stage in ( - "LUCKY_DRAW_RESULT", - "COUPON_POPUP", - "SHOPPING_REDPACKET_POPUP", - "FANS_CLUB_JOIN", - ): - try: - analyser._log_kv( - "预约", - "[预约] 回退前检测到弹窗,先处理", - stage=stage, - reason=reason, - ) - except Exception: - pass - - # 处理弹窗:点击返回或关闭按钮 - try: - analyser.operation.click_back(analyser.device_id) - time.sleep(0.5) - # 重新截图并再次诊断,确保已处理 - try: - analyser.operation.get_screenshot( - analyser.device_id, use_service=False - ) - except Exception: - pass - result = douyin_stage.diagnose_stage_from_current_screen(analyser) - if result is None: - stage, reason = ( - "IN_LIVE_ROOM", - "阶段诊断返回 None,默认判定为在直播间", - ) - else: - stage, reason = result - except Exception: - pass - elif stage == "FUDai_DETAIL": - # 如果在福袋详情页,先关闭详情页 - try: - analyser._log_kv( - "预约", - "[预约] 回退前检测到在福袋详情页,先关闭", - stage=stage, - ) - except Exception: - pass - try: - analyser.operation.click_back(analyser.device_id) - time.sleep(0.5) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] 回退前阶段诊断失败,继续执行回退", - error=str(e), - error_type=type(e).__name__, - ) - 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(earliest.get("pos_seen") or 0) - except Exception: - target_pos = 0 - _pos_diff = current_room_pos - target_pos # 位置差(用于调试,当前未使用) - - # 直接调用回退回调,不需要预先下滑 - # 原因: - # 1. 回退前已经进行了阶段诊断,处理了弹窗和福袋详情页等异常状态 - # 2. 如果已经在直播间,不需要下滑 - # 3. 预先下滑会导致 room_pos 减1,影响后续的回退计算,导致少回退一个直播间 - - # 回退到最早开奖的预约直播间 - ok = False - try: - ok = bool(seek_reservation_room_callback(earliest)) - except Exception: - ok = False - - if ok: - # 回退后等待页面加载 - try: - analyser.operation.delay(1.5) # 等待页面加载 - except Exception: - time.sleep(1.5) - - # 队列满后回退到最早直播间,继续执行后续流程 - try: - analyser._log_kv( - "预约", - "[预约] 队列满回退后,继续执行后续流程", - earliest_future_ts=int(ft), - now_ts=int(now_ts), - remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, - ) - except Exception: - pass - - # 队列满后立即参与,不设置锁定期(设置为0),使用标志控制 - # 这样不会影响切换直播间的逻辑,同时后续的 process_reservation_attend_window 不会因为锁定期而跳过 - focus_until_new = 0.0 # 设置为0,表示不设置锁定期,使用标志控制 - 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) - - try: - from datetime import datetime - - ft_str = ( - datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") - if ft > 0 - else "无效" - ) - analyser._log_kv( - "预约", - "[预约] 已回退到最早开奖的预约直播间,立即参与(不等待开奖窗口)", - earliest_future_ts=int(ft), - earliest_future_str=ft_str, - now_ts=int(now_ts), - focus_until=int(focus_until_new), - remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, - immediate_attend=True, - ) - except Exception: - pass - - try: - write_state_callback() - except Exception: - pass - - try: - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest 完成(已回退)", - elapsed_seconds=round(elapsed, 3), - ) - except Exception: - pass - - return True - - try: - elapsed = time.time() - start_time - analyser._log_kv( - "预约", - "[预约] handle_queue_full_wait_at_earliest 完成(回退失败)", - elapsed_seconds=round(elapsed, 3), - ) - except Exception: - pass - - return False - - -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: - # 获取目标直播间名字和福袋详情(用于日志和校验) - 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 - - -def record_high_value_reservation( - analyser: Any, - fudai_content_text: str, - prize_value_yuan: float, - lastsecond: int, - future_timestamp: float, - x: int, - needswitch: bool, - wait_minutes: int, - post_switch_delay_s: float, - room_pos: int, - reservations: List[ReservationItem], - reservation_focus_until_ts_ref: List[float], - close_detail_callback: Callable[[], None], - swipe_up_switch_callback: Callable[[], None], - swipe_down_back_callback: Callable[[], None], - add_reservation_callback: Callable[[List[ReservationItem], ReservationItem], None], - sort_reservations_callback: Callable[[], None], - write_state_callback: Callable[[], None], - room_title: str = "", - room_title_raw: str = "", - task_count: int = 2, - time_text: str = "", - participants: int = 0, - copies: int = 0, -) -> bool: - """记录一条高价值福袋预约。 - - 当前实现为"只记录,不立刻改变当前直播间"的版本: - - 构造预约 item 并加入 reservations; - - 写入状态文件; - - 返回 False,表示当前轮不需要立即抢占主流程。 - """ - try: - # 验证输入参数 - try: - if not isinstance(fudai_content_text, str): - fudai_content_text = str(fudai_content_text or "") - if not isinstance(prize_value_yuan, (int, float)): - prize_value_yuan = float(prize_value_yuan or 0.0) - if not isinstance(future_timestamp, (int, float)) or future_timestamp <= 0: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:future_timestamp 无效", - future_timestamp=future_timestamp, - error_type="InvalidParameter", - ) - except Exception: - pass - return False - if not isinstance(room_pos, int): - room_pos = int(room_pos or 0) - except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:参数验证失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - return False - - # 计算 future_str(预计开奖时间的字符串格式) - future_str = "" - try: - if future_timestamp and future_timestamp > 0: - from datetime import datetime - - future_str = datetime.fromtimestamp(float(future_timestamp)).strftime( - "%Y-%m-%d %H:%M:%S" - ) - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context( - future_timestamp=future_timestamp, - prize_value_yuan=prize_value_yuan, - ), - level="WARNING", - stage="计算 future_str", - ) - else: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:计算 future_str 失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 验证 reservations 列表 - if not isinstance(reservations, list): - if _RESERVATION_ERROR_UTILS_AVAILABLE: - try: - raise TypeError( - f"reservations 不是列表类型,而是 {type(reservations).__name__}" - ) - except TypeError as e: - log_reservation_error( - analyser, - e, - format_reservation_context( - reservations_type=type(reservations).__name__, - prize_value_yuan=prize_value_yuan, - future_timestamp=future_timestamp, - ), - level="ERROR", - stage="验证 reservations 列表", - ) - else: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:reservations 不是列表", - reservations_type=type(reservations).__name__, - error_type="InvalidParameter", - ) - except Exception: - pass - return False - - # 构造预约项 - try: - item: ReservationItem = { - "future_ts": float(future_timestamp or 0.0), - "future_str": future_str, - "prize_value_yuan": float(prize_value_yuan or 0.0), - "content": str(fudai_content_text or ""), - "pos_seen": int(room_pos), - "created_ts": _now_ts(), - "room_title": str(room_title or ""), - "room_title_raw": str(room_title_raw or ""), - "task_count": int(task_count or 2), - "time_text": str(time_text or ""), - "participants": int(participants or 0), - "copies": int(copies or 0), - } - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context( - prize_value_yuan=prize_value_yuan, - future_timestamp=future_timestamp, - room_pos=room_pos, - room_title=room_title, - room_title_raw=room_title_raw, - ), - level="ERROR", - stage="构造预约项", - ) - else: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:构造预约项失败", - error=str(e), - error_type=type(e).__name__, - prize_value_yuan=prize_value_yuan, - future_timestamp=future_timestamp, - room_pos=room_pos, - ) - except Exception: - pass - return False - - # 调用回调函数添加预约 - try: - add_reservation_callback(reservations, item) - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context( - item=item, - reservations=reservations, - queue_len_before=len(reservations), - ), - level="ERROR", - stage="调用 add_reservation_callback", - ) - else: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:add_reservation_callback 失败", - error=str(e), - error_type=type(e).__name__, - queue_len_before=len(reservations), - ) - except Exception: - pass - return False - - # 排序预约队列 - try: - sort_reservations_callback() - except Exception as e: - if _RESERVATION_ERROR_UTILS_AVAILABLE: - log_reservation_error( - analyser, - e, - format_reservation_context( - item=item, - reservations=reservations, - ), - level="WARNING", - stage="调用 sort_reservations_callback", - ) - else: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:sort_reservations_callback 失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 写入状态文件 - if _RESERVATION_ERROR_UTILS_AVAILABLE: - safe_write_state( - write_state_callback, - analyser, - format_reservation_context( - item=item, - reservations=reservations, - ), - ) - else: - try: - write_state_callback() - except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:write_state_callback 失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 记录成功日志 - try: - from datetime import datetime - - created_str = datetime.fromtimestamp(item["created_ts"]).strftime( - "%Y-%m-%d %H:%M:%S" - ) - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:已记录高价值福袋", - value_yuan=item["prize_value_yuan"], - future_ts=int(item["future_ts"]), - future_str=future_str, - created_ts=int(item["created_ts"]), - created_str=created_str, - room_title=room_title[:50] if room_title else "", - room_title_raw=room_title_raw[:50] if room_title_raw else "", - content=fudai_content_text[:50] if fudai_content_text else "", - pos_seen=room_pos, - task_count=task_count, - participants=participants, - copies=copies, - queue_len=len(reservations), - ) - except Exception as e: - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation:记录成功日志失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - return False - except Exception as e: - # 任何异常都不影响主流程,只记录日志 - try: - analyser._log_kv( - "预约", - "[预约] record_high_value_reservation 异常,忽略本次预约", - error=str(e), - error_type=type(e).__name__, - prize_value_yuan=prize_value_yuan, - future_timestamp=future_timestamp, - room_pos=room_pos, - room_title=room_title[:50] if room_title else "", - ) - except Exception: - pass - return False +from douyin.reservation.reservation_logic import ( + ReservationItem, + _RESERVATION_ERROR_UTILS_AVAILABLE, + _calculate_string_similarity, + _extract_content_core, + _normalize_room_title_for_matching, + _now_ts, + _sort_reservations_inplace, + add_reservation_core_logic, + cleanup_expired_reservations, + format_reservation_context, + handle_queue_full_wait_at_earliest, + log_reservation_error, + process_reservation_attend_window, + record_high_value_reservation, + safe_write_state, + validate_back_to_reservation, + validate_reservation_item, +) + +__all__ = [ + "ReservationItem", + "_RESERVATION_ERROR_UTILS_AVAILABLE", + "log_reservation_error", + "safe_write_state", + "format_reservation_context", + "validate_reservation_item", + "_now_ts", + "_normalize_room_title_for_matching", + "_calculate_string_similarity", + "_extract_content_core", + "_sort_reservations_inplace", + "add_reservation_core_logic", + "validate_back_to_reservation", + "cleanup_expired_reservations", + "handle_queue_full_wait_at_earliest", + "process_reservation_attend_window", + "record_high_value_reservation", +] diff --git a/douyin/reservation/reservation_logic/__init__.py b/douyin/reservation/reservation_logic/__init__.py new file mode 100644 index 0000000..b73a800 --- /dev/null +++ b/douyin/reservation/reservation_logic/__init__.py @@ -0,0 +1,60 @@ +"""reservation_logic - 高价值福袋预约核心逻辑子包。 + +原 douyin/reservation/douyin_reservation_logic.py 拆成 6 个子模块: + +- _common 共享:错误处理工具占位 + ReservationItem 类型 +- helpers 内部工具:标题归一化 / 相似度 / 排序 / 时间戳 +- add add_reservation_core_logic 添加新预约 +- cleanup_validate validate_back_to_reservation / cleanup_expired_reservations +- queue_full handle_queue_full_wait_at_earliest 队列满时等待策略 +- attend_window process_reservation_attend_window 进入预约窗口的处理(最大头) +- record record_high_value_reservation 高价值预约登记入口 + +外部 import 路径不变: +``from douyin.reservation.douyin_reservation_logic import process_reservation_attend_window`` +仍可用(原文件改成 re-export shim)。 +""" + +from ._common import ( + ReservationItem, + _RESERVATION_ERROR_UTILS_AVAILABLE, + format_reservation_context, + log_reservation_error, + safe_write_state, + validate_reservation_item, +) +from .helpers import ( + _calculate_string_similarity, + _extract_content_core, + _normalize_room_title_for_matching, + _now_ts, + _sort_reservations_inplace, +) +from .add import add_reservation_core_logic +from .cleanup_validate import ( + cleanup_expired_reservations, + validate_back_to_reservation, +) +from .queue_full import handle_queue_full_wait_at_earliest +from .attend_window import process_reservation_attend_window +from .record import record_high_value_reservation + +__all__ = [ + "ReservationItem", + "_RESERVATION_ERROR_UTILS_AVAILABLE", + "log_reservation_error", + "safe_write_state", + "format_reservation_context", + "validate_reservation_item", + "_now_ts", + "_normalize_room_title_for_matching", + "_calculate_string_similarity", + "_extract_content_core", + "_sort_reservations_inplace", + "add_reservation_core_logic", + "validate_back_to_reservation", + "cleanup_expired_reservations", + "handle_queue_full_wait_at_earliest", + "process_reservation_attend_window", + "record_high_value_reservation", +] diff --git a/douyin/reservation/reservation_logic/_common.py b/douyin/reservation/reservation_logic/_common.py new file mode 100644 index 0000000..117a9ca --- /dev/null +++ b/douyin/reservation/reservation_logic/_common.py @@ -0,0 +1,57 @@ +"""reservation_logic._common - 共享类型与错误处理工具。 + +被 add / cleanup_validate / queue_full / attend_window / record 各子模块共用。 +- log_reservation_error / safe_write_state / format_reservation_context / + validate_reservation_item:从 douyin.reservation.core.reservation_error_utils 导入; + 导入失败时降级为占位实现(参数宽松,调用 OK 但什么都不做)。 +- ReservationItem:单条预约的字典类型别名。 +- _RESERVATION_ERROR_UTILS_AVAILABLE:标记真实工具是否成功导入。 +""" +from __future__ import annotations + +from typing import Any, Dict, TYPE_CHECKING + +if TYPE_CHECKING: + from douyin.reservation.core.reservation_error_utils import ( # pragma: no cover + log_reservation_error, + safe_write_state, + format_reservation_context, + validate_reservation_item, + ) + + _RESERVATION_ERROR_UTILS_AVAILABLE = True +else: + try: + from douyin.reservation.core.reservation_error_utils import ( # type: ignore[import] + log_reservation_error, + safe_write_state, + format_reservation_context, + validate_reservation_item, + ) + + _RESERVATION_ERROR_UTILS_AVAILABLE = True + except Exception: + # 运行时回退到通用占位实现(使用宽松签名以兼容各种调用) + def log_reservation_error(*args, **kwargs) -> None: + return None + + def safe_write_state(*args, **kwargs) -> bool: + return True + + def format_reservation_context(*args, **kwargs) -> Dict[str, Any]: + return {} + + def validate_reservation_item(*args, **kwargs) -> bool: + return True + + _RESERVATION_ERROR_UTILS_AVAILABLE = False + +# 为兼容类型检查,将实际导入或占位函数转换为 Any(避免赋值/导入时的类型不匹配报错) +from typing import Any as _Any, cast + +log_reservation_error = cast(_Any, log_reservation_error) +safe_write_state = cast(_Any, safe_write_state) +format_reservation_context = cast(_Any, format_reservation_context) +validate_reservation_item = cast(_Any, validate_reservation_item) + +ReservationItem = Dict[str, Any] diff --git a/douyin/reservation/reservation_logic/add.py b/douyin/reservation/reservation_logic/add.py new file mode 100644 index 0000000..66c3008 --- /dev/null +++ b/douyin/reservation/reservation_logic/add.py @@ -0,0 +1,447 @@ +"""reservation_logic.add - add_reservation_core_logic 主入口。 + +往预约队列添加一条新预约: +- 去重 / 触发优先级排序 / 队列上限裁剪 / 状态写回 / 错误日志 +""" +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, + validate_reservation_item, +) +from .helpers import ( + _calculate_string_similarity, + _extract_content_core, + _normalize_room_title_for_matching, + _now_ts, + _sort_reservations_inplace, +) + + +def add_reservation_core_logic( + reservations: List[ReservationItem], + item: ReservationItem, + max_reservations: Optional[int] = None, + analyser: Any = None, + write_state_callback: Optional[Callable[[], None]] = None, +) -> bool: + """向预约队列追加/更新一条记录,并根据上限裁剪。 + + 去重策略: + - key = (future_ts, content) 相同则视为同一条记录,保留价值更高的那条。 + - 如果直播间名字相同(规范化后),且 (future_ts, content) 相同,也视为同一条记录。 + + 返回: + bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。 + """ + start_time = time.time() + step_start_time = start_time + + ft = float(item.get("future_ts") or 0.0) + content = str(item.get("content") or "") + prize_value = float(item.get("prize_value_yuan") or 0.0) + room_title = str(item.get("room_title") or "") + room_title_normalized = _normalize_room_title_for_matching(room_title) + + # 步骤1: 参数处理和规范化 + try: + analyser._log_kv( + "预约", + "[预约] 步骤1: 参数处理和规范化", + log_type="OP", + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + step_start_time = time.time() + + # 添加函数入口日志 + try: + from datetime import datetime + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) + analyser._log_kv( + "预约", + "[预约] add_reservation_core_logic 函数入口", + log_type="OP", + future_ts=int(ft) if ft > 0 else 0, + future_str=ft_str, + prize_value_yuan=prize_value, + room_title=room_title[:50] if room_title else "", + content=content[:50] if content else "", + queue_len_before=len(reservations), + max_reservations=max_reservations, + ) + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(item=item, reservations=reservations), + level="WARNING", + stage="记录函数入口日志", + ) + else: + try: + analyser._log_kv( + "预约", "[预约] 记录函数入口日志失败", log_type="ERR", error=str(e) + ) + except Exception: + pass + + # 步骤2: 查找是否已存在相同预约 + try: + analyser._log_kv( + "预约", + "[预约] 步骤2: 开始查找是否已存在相同预约", + log_type="OP", + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + step_start_time = time.time() + + same_idx: Optional[int] = None + for idx, r in enumerate(reservations): + try: + r_ft = float(r.get("future_ts") or 0.0) + r_content = str(r.get("content") or "") + r_prize_value = float(r.get("prize_value_yuan") or 0.0) + r_room_title = str(r.get("room_title") or "") + r_room_title_normalized = _normalize_room_title_for_matching(r_room_title) + + # 判断是否为同一个预约: + # 1. (future_ts, content) 相同,且直播间名字相同(规范化后) + # 2. 或者 (future_ts, content) 相同(兼容旧数据,没有直播间名字的情况) + # 3. 或者通过相似度匹配:直播间名称相似 + 开奖时间相近 + 奖品价值相同 + 内容核心部分相似 + is_same_future_and_content = r_ft == ft and r_content == content + is_same_room_title = ( + room_title_normalized + and r_room_title_normalized + and room_title_normalized == r_room_title_normalized + ) + + # 相似度匹配(处理OCR误差) + is_similar_room_title = False + is_similar_time = False + is_same_prize_value = False + is_similar_content = False + + if room_title_normalized and r_room_title_normalized: + # 计算直播间名称相似度 + room_title_similarity = _calculate_string_similarity( + room_title_normalized, r_room_title_normalized + ) + # 如果一个是另一个的子串,或者相似度 >= 0.6,视为相似 + is_similar_room_title = ( + room_title_normalized in r_room_title_normalized + or r_room_title_normalized in room_title_normalized + or room_title_similarity >= 0.6 + ) + + # 开奖时间相近(相差60秒内,放宽容忍度以处理OCR误差和实际时间差) + time_diff = abs(r_ft - ft) + is_similar_time = time_diff <= 60.0 + + # 奖品价值相同(允许0.01的误差) + prize_diff = abs(r_prize_value - prize_value) + is_same_prize_value = prize_diff < 0.01 + + # 内容核心部分相似 + content_core = _extract_content_core(content) + r_content_core = _extract_content_core(r_content) + if content_core and r_content_core: + content_similarity = _calculate_string_similarity( + content_core, r_content_core + ) + is_similar_content = content_similarity >= 0.7 + + # 判断是否为同一个预约 + if is_same_future_and_content: + # 如果 (future_ts, content) 相同 + if is_same_room_title: + # 直播间名字也相同(规范化后),确定是同一个预约 + same_idx = idx + break + elif not room_title_normalized and not r_room_title_normalized: + # 都没有直播间名字,视为同一个预约(兼容旧数据) + same_idx = idx + break + # 如果只有一个有直播间名字,也视为同一个预约(兼容旧数据) + elif (room_title_normalized and not r_room_title_normalized) or ( + not room_title_normalized and r_room_title_normalized + ): + same_idx = idx + break + # 如果直播间名称相同(规范化后)且价值相同,即使时间差稍大也视为重复 + elif is_same_room_title and is_same_prize_value and time_diff <= 300.0: + # 直播间名称相同且价值相同,时间差在5分钟内,视为重复 + same_idx = idx + try: + if analyser: + analyser._log_kv( + "预约", + "[预约] 通过直播间名称和价值匹配识别为重复预约", + log_type="OP", + room_title_normalized=room_title_normalized, + time_diff=round(time_diff, 2), + prize_value_yuan=prize_value, + ) + except Exception: + pass + break + elif ( + is_similar_room_title + and is_similar_time + and is_same_prize_value + and ( + is_similar_content + or ( + # 如果内容核心均为空(OCR 未识别到内容),则允许仅凭直播间名称相似、时间接近和价值相同判定为重复 + not content_core + and not r_content_core + ) + ) + ): + # 通过相似度匹配判断为同一个预约(处理OCR误差) + same_idx = idx + try: + if analyser: + analyser._log_kv( + "预约", + "[预约] 通过相似度匹配识别为重复预约", + log_type="OP", + room_title_normalized=room_title_normalized, + r_room_title_normalized=r_room_title_normalized, + time_diff=round(time_diff, 2), + prize_diff=round(prize_diff, 2), + content_core=content_core[:50], + r_content_core=r_content_core[:50], + ) + except Exception: + pass + break + except Exception: + continue + + # 步骤3: 相似度匹配完成 + try: + analyser._log_kv( + "预约", + "[预约] 步骤3: 相似度匹配完成", + log_type="OP", + same_idx=same_idx, + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + step_start_time = time.time() + + if same_idx is not None: + # 若新记录价值更高,则更新 + try: + old_val = float(reservations[same_idx].get("prize_value_yuan") or 0.0) + except Exception: + old_val = 0.0 + if prize_value > old_val: + try: + analyser._log_kv( + "预约", + "[预约] 检测到重复预约,更新为更高价值", + same_idx=same_idx, + old_value_yuan=old_val, + new_value_yuan=prize_value, + future_ts=int(ft) if ft > 0 else 0, + ) + except Exception: + pass + reservations[same_idx].update(dict(item)) + else: + try: + analyser._log_kv( + "预约", + "[预约] 检测到重复预约,但新价值不高于旧值,保留旧记录", + same_idx=same_idx, + old_value_yuan=old_val, + new_value_yuan=prize_value, + future_ts=int(ft) if ft > 0 else 0, + ) + except Exception: + pass + else: + try: + analyser._log_kv( + "预约", + "[预约] 添加新预约到队列", + future_ts=int(ft) if ft > 0 else 0, + prize_value_yuan=prize_value, + queue_len_before=len(reservations), + ) + except Exception: + pass + reservations.append(dict(item)) + + # 步骤4: 添加/更新预约完成 + try: + analyser._log_kv( + "预约", + "[预约] 步骤4: 添加/更新预约完成", + log_type="OP", + same_idx=same_idx, + queue_len_after=len(reservations), + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + step_start_time = time.time() + + # 排序 + 按上限裁剪 + _sort_reservations_inplace(reservations) + + # 步骤5: 排序完成 + try: + analyser._log_kv( + "预约", + "[预约] 步骤5: 排序完成", + log_type="OP", + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + step_start_time = time.time() + + queue_full = False + if ( + max_reservations is not None + and max_reservations > 0 + and len(reservations) > max_reservations + ): + # 记录被丢弃的记录信息 + dropped_items = reservations[max_reservations:] + for dropped in dropped_items: + try: + dropped_value = float(dropped.get("prize_value_yuan") or 0.0) + dropped_future_ts = float(dropped.get("future_ts") or 0.0) + dropped_content = str(dropped.get("content") or "")[:50] + try: + from datetime import datetime + + dropped_future_str = datetime.fromtimestamp( + dropped_future_ts + ).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + dropped_future_str = str(dropped_future_ts) + + if analyser: + try: + analyser._log_kv( + "预约", + "预约队列已满,丢弃最低优先级记录", + cap=max_reservations, + dropped_value_yuan=dropped_value, + dropped_future_ts=int(dropped_future_ts), + dropped_future_str=dropped_future_str, + dropped_content=dropped_content, + queue_len_before=len(reservations), + ) + except Exception: + pass + except Exception: + pass + + # 按当前排序规则,队尾是"优先级最低"的记录 + del reservations[max_reservations:] + queue_full = True + + try: + analyser._log_kv( + "预约", + "[预约] 预约队列已满,已裁剪到上限", + max_reservations=max_reservations, + queue_len_after=len(reservations), + dropped_count=len(dropped_items), + ) + except Exception: + pass + + # 如果队列已满,写入状态文件 + if write_state_callback: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=item, + reservations=reservations, + queue_full=True, + dropped_count=len(dropped_items) if dropped_items else 0, + ), + ) + else: + try: + write_state_callback() + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] 写入状态文件失败(队列已满)", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + # 步骤6: 队列裁剪和状态写入完成 + try: + analyser._log_kv( + "预约", + "[预约] 步骤6: 队列裁剪和状态写入完成", + log_type="OP", + queue_full=queue_full, + queue_len_final=len(reservations), + elapsed_seconds=round(time.time() - step_start_time, 3), + ) + except Exception: + pass + + # 添加函数完成日志 + try: + elapsed = time.time() - start_time + analyser._log_kv( + "预约", + "[预约] add_reservation_core_logic 完成", + log_type="OP", + queue_len_after=len(reservations), + queue_full=queue_full, + elapsed_seconds=round(elapsed, 3), + ) + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context(item=item, reservations=reservations), + level="WARNING", + stage="记录函数完成日志", + ) + else: + try: + analyser._log_kv( + "预约", "[预约] 记录函数完成日志失败", log_type="ERR", error=str(e) + ) + except Exception: + pass + + return queue_full + + diff --git a/douyin/reservation/reservation_logic/attend_window.py b/douyin/reservation/reservation_logic/attend_window.py new file mode 100644 index 0000000..4f17897 --- /dev/null +++ b/douyin/reservation/reservation_logic/attend_window.py @@ -0,0 +1,1437 @@ +"""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: + # 获取目标直播间名字和福袋详情(用于日志和校验) + 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 + + diff --git a/douyin/reservation/reservation_logic/cleanup_validate.py b/douyin/reservation/reservation_logic/cleanup_validate.py new file mode 100644 index 0000000..ca5978d --- /dev/null +++ b/douyin/reservation/reservation_logic/cleanup_validate.py @@ -0,0 +1,136 @@ +"""reservation_logic.cleanup_validate - 校验与过期清理。 + +- validate_back_to_reservation 回退后校验是否进入了正确的直播间 +- cleanup_expired_reservations 清理已过开奖时间的预约 +""" +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, + _normalize_room_title_for_matching, + _now_ts, + _sort_reservations_inplace, +) + + +def validate_back_to_reservation( + analyser: Any, + reservations: List[ReservationItem], + now_ts: float | None = None, +) -> None: + """回退校验:当前实现为轻量版本,仅记录日志,保留扩展点。""" + if now_ts is None: + now_ts = _now_ts() + try: + analyser._log_kv( + "预约", + "[预约] validate_back_to_reservation", + log_type="OP", + count=len(reservations), + now_ts=int(now_ts), + ) + except Exception: + pass + + + + +def cleanup_expired_reservations( + analyser: Any, + reservations: List[ReservationItem], + write_state_callback: Optional[Callable[[], None]] = None, +) -> None: + """清理已过开奖时间的预约,并视情况写入状态文件。""" + start_time = time.time() + try: + now_ts_drop = _now_ts() + before = len(reservations) + + # 记录被清理的预约详情 + dropped_items_detail = [] + for r in reservations: + try: + r_ft = float(r.get("future_ts") or 0.0) + if r_ft <= now_ts_drop: + dropped_items_detail.append( + { + "future_ts": int(r_ft), + "prize_value_yuan": float(r.get("prize_value_yuan", 0)), + "content": str(r.get("content", ""))[:50], + "room_title": str(r.get("room_title", ""))[:30], + } + ) + except Exception: + pass + + reservations[:] = [ + r for r in reservations if float(r.get("future_ts") or 0.0) > now_ts_drop + ] + dropped = max(0, before - len(reservations)) + + if dropped: + try: + from datetime import datetime + + now_str = datetime.fromtimestamp(now_ts_drop).strftime( + "%Y-%m-%d %H:%M:%S" + ) + analyser._log_kv( + "预约", + "[预约] cleanup_expired_reservations:清理过期预约", + dropped_count=dropped, + remain_count=len(reservations), + now_ts=int(now_ts_drop), + now_str=now_str, + dropped_items=dropped_items_detail[:5], # 只记录前5个,避免日志过长 + ) + except Exception: + pass + + if write_state_callback is not None: + try: + write_state_callback() + except Exception: + pass + else: + try: + analyser._log_kv( + "预约", + "[预约] cleanup_expired_reservations:无需清理", + queue_len=len(reservations), + now_ts=int(now_ts_drop), + ) + except Exception: + pass + except Exception as e: + # Best-effort cleanup only; never crash主循环 + try: + analyser._log_kv( + "预约", + "[预约] cleanup_expired_reservations 异常", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + try: + elapsed = time.time() - start_time + analyser._log_kv( + "预约", + "[预约] cleanup_expired_reservations 完成", + elapsed_seconds=round(elapsed, 3), + ) + except Exception: + pass + + diff --git a/douyin/reservation/reservation_logic/helpers.py b/douyin/reservation/reservation_logic/helpers.py new file mode 100644 index 0000000..943525b --- /dev/null +++ b/douyin/reservation/reservation_logic/helpers.py @@ -0,0 +1,130 @@ +"""reservation_logic.helpers - 内部工具函数。 + +- _now_ts 当前时间戳(time.time 别名) +- _normalize_room_title_for_matching 规范化直播间标题用于匹配 +- _calculate_string_similarity 两个字符串的相似度(用于回退校验) +- _extract_content_core 抽取福袋内容主干 +- _sort_reservations_inplace 队列排序:future_ts → prize → created_ts +""" +from __future__ import annotations + +import re +import time +from typing import List + +from ._common import ReservationItem + + +def _now_ts() -> float: + return time.time() + + + + +def _normalize_room_title_for_matching(title: str) -> str: + """规范化直播间标题用于匹配比较。 + + 去除数字、特殊字符等,只保留核心名称部分。 + 例如:"王媛媛" 和 "王媛媛2" 会被规范化为相同的字符串。 + """ + if not title: + return "" + # 去除空格和换行 + s = str(title).replace("\r", " ").replace("\n", " ").strip() + s = re.sub(r"\s+", "", s) + # 去除常见无关词 + for w in ( + "点赞", + "赞", + "关注", + "粉丝", + "直播中", + "正在直播", + "进入直播间", + "推荐", + "在线", + "人在线", + ): + s = s.replace(w, "") + # 去除数字和特殊字符,只保留中文、英文、数字(但去除末尾的数字) + # 先去除末尾的数字(如 "王媛媛2" -> "王媛媛") + s = re.sub(r"\d+$", "", s) + # 去除所有特殊字符,只保留中文、英文 + s = re.sub(r"[^A-Za-z\u4e00-\u9fff]", "", s) + return s + + + + +def _calculate_string_similarity(s1: str, s2: str) -> float: + """计算两个字符串的相似度(简单的字符重叠比例)。 + + 返回 0.0 到 1.0 之间的值,1.0 表示完全相同。 + """ + if not s1 or not s2: + return 0.0 + if s1 == s2: + return 1.0 + + # 计算字符集合的交集和并集 + set1 = set(s1) + set2 = set(s2) + intersection = len(set1 & set2) + union = len(set1 | set2) + + if union == 0: + return 0.0 + + # Jaccard相似度 + jaccard = intersection / union + + # 如果长度相近,额外加分 + len_ratio = ( + min(len(s1), len(s2)) / max(len(s1), len(s2)) + if max(len(s1), len(s2)) > 0 + else 0.0 + ) + + # 综合相似度(Jaccard占70%,长度比例占30%) + similarity = jaccard * 0.7 + len_ratio * 0.3 + + return similarity + + + + +def _extract_content_core(content: str) -> str: + """提取福袋内容的核心部分(去除倒计时等变化部分)。 + + 例如:"10后开奖03(琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" + 提取为:"琦儿专属1HONOR/荣耀平板X9Pro11.5英寸/官方" + """ + if not content: + return "" + # 去除开头的倒计时部分(如 "10后开奖03"、"06后开奖09" 等) + # 匹配模式:数字+后开奖+数字 + s = re.sub(r"^\d+后开奖\d+", "", content) + # 去除开头的括号和数字 + s = re.sub(r"^[\((]\d+", "", s) + # 去除开头的数字 + s = re.sub(r"^\d+", "", s) + # 去除前后空格 + s = s.strip() + return s + + + + +def _sort_reservations_inplace(reservations: List[ReservationItem]) -> None: + """按 future_ts 升序,其次 prize_value_yuan 降序,其次 created_ts 升序排序。""" + + def _key(it: ReservationItem): + ft = float(it.get("future_ts") or 0.0) + val = float(it.get("prize_value_yuan") or 0.0) + created = float(it.get("created_ts") or 0.0) + # future_ts 越小越优先;价值越大越优先(因此取 -val);创建时间越早越优先 + return (ft, -val, created) + + reservations.sort(key=_key) + + diff --git a/douyin/reservation/reservation_logic/queue_full.py b/douyin/reservation/reservation_logic/queue_full.py new file mode 100644 index 0000000..86b59ee --- /dev/null +++ b/douyin/reservation/reservation_logic/queue_full.py @@ -0,0 +1,305 @@ +"""reservation_logic.queue_full - 队列满时的等待策略。 + +handle_queue_full_wait_at_earliest:当预约队列达到上限时, +回退到最早开奖的预约直播间等待,确保不丢失最高优先级的预约。 +""" +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, + _normalize_room_title_for_matching, + _now_ts, + _sort_reservations_inplace, +) + + +def handle_queue_full_wait_at_earliest( + analyser: Any, + reservations: List[ReservationItem], + room_pos: int, + reservation_focus_until_ts_ref: List[float], + 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;否则返回 False。 + """ + start_time = time.time() + + try: + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest 函数入口", + queue_len=len(reservations) if reservations else 0, + room_pos=room_pos, + ) + except Exception: + pass + + if not reservations: + try: + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest:预约队列为空,跳过", + ) + except Exception: + pass + return False + + # 排序确保取到最早开奖的 + sort_reservations_callback() + + # 取最早开奖的预约 + earliest = reservations[0] + try: + ft = float(earliest.get("future_ts") or 0.0) + except Exception: + ft = 0.0 + + if ft <= 0: + try: + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest:最早预约 future_ts 无效,跳过", + future_ts=ft, + ) + except Exception: + 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,禁止为负数) + poll_before: float = 0.0 + + # 如果已经在锁定期内,不需要重复回退 + if focus_until > 0 and now_ts < focus_until: + try: + from datetime import datetime + + focus_until_str = datetime.fromtimestamp(focus_until).strftime( + "%Y-%m-%d %H:%M:%S" + ) + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest:已在锁定期内,跳过回退", + focus_until=int(focus_until), + focus_until_str=focus_until_str, + lock_period_remain_seconds=int(focus_until - now_ts), + ) + except Exception: + pass + return False + + try: + analyser._log_kv( + "预约", + "[预约] 队列已满,回退到最早开奖的预约直播间等待", + earliest_future_ts=int(ft), + queue_len=len(reservations), + room_pos=int(room_pos), + ) + except Exception: + pass + + # 先进行阶段诊断,处理弹窗等,避免卡死在某个页面 + try: + # 确保有最新截图 + try: + analyser.operation.get_screenshot(analyser.device_id, use_service=False) + except Exception: + pass + + from douyin.stage import douyin_stage + + result = douyin_stage.diagnose_stage_from_current_screen(analyser) + if result is None: + stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间") + else: + stage, reason = result + + # 如果检测到需要处理的弹窗或异常状态,先处理 + if stage in ( + "LUCKY_DRAW_RESULT", + "COUPON_POPUP", + "SHOPPING_REDPACKET_POPUP", + "FANS_CLUB_JOIN", + ): + try: + analyser._log_kv( + "预约", + "[预约] 回退前检测到弹窗,先处理", + stage=stage, + reason=reason, + ) + except Exception: + pass + + # 处理弹窗:点击返回或关闭按钮 + try: + analyser.operation.click_back(analyser.device_id) + time.sleep(0.5) + # 重新截图并再次诊断,确保已处理 + try: + analyser.operation.get_screenshot( + analyser.device_id, use_service=False + ) + except Exception: + pass + result = douyin_stage.diagnose_stage_from_current_screen(analyser) + if result is None: + stage, reason = ( + "IN_LIVE_ROOM", + "阶段诊断返回 None,默认判定为在直播间", + ) + else: + stage, reason = result + except Exception: + pass + elif stage == "FUDai_DETAIL": + # 如果在福袋详情页,先关闭详情页 + try: + analyser._log_kv( + "预约", + "[预约] 回退前检测到在福袋详情页,先关闭", + stage=stage, + ) + except Exception: + pass + try: + analyser.operation.click_back(analyser.device_id) + time.sleep(0.5) + except Exception: + pass + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] 回退前阶段诊断失败,继续执行回退", + error=str(e), + error_type=type(e).__name__, + ) + 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(earliest.get("pos_seen") or 0) + except Exception: + target_pos = 0 + _pos_diff = current_room_pos - target_pos # 位置差(用于调试,当前未使用) + + # 直接调用回退回调,不需要预先下滑 + # 原因: + # 1. 回退前已经进行了阶段诊断,处理了弹窗和福袋详情页等异常状态 + # 2. 如果已经在直播间,不需要下滑 + # 3. 预先下滑会导致 room_pos 减1,影响后续的回退计算,导致少回退一个直播间 + + # 回退到最早开奖的预约直播间 + ok = False + try: + ok = bool(seek_reservation_room_callback(earliest)) + except Exception: + ok = False + + if ok: + # 回退后等待页面加载 + try: + analyser.operation.delay(1.5) # 等待页面加载 + except Exception: + time.sleep(1.5) + + # 队列满后回退到最早直播间,继续执行后续流程 + try: + analyser._log_kv( + "预约", + "[预约] 队列满回退后,继续执行后续流程", + earliest_future_ts=int(ft), + now_ts=int(now_ts), + remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, + ) + except Exception: + pass + + # 队列满后立即参与,不设置锁定期(设置为0),使用标志控制 + # 这样不会影响切换直播间的逻辑,同时后续的 process_reservation_attend_window 不会因为锁定期而跳过 + focus_until_new = 0.0 # 设置为0,表示不设置锁定期,使用标志控制 + 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) + + try: + from datetime import datetime + + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft > 0 + else "无效" + ) + analyser._log_kv( + "预约", + "[预约] 已回退到最早开奖的预约直播间,立即参与(不等待开奖窗口)", + earliest_future_ts=int(ft), + earliest_future_str=ft_str, + now_ts=int(now_ts), + focus_until=int(focus_until_new), + remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0, + immediate_attend=True, + ) + except Exception: + pass + + try: + write_state_callback() + except Exception: + pass + + try: + elapsed = time.time() - start_time + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest 完成(已回退)", + elapsed_seconds=round(elapsed, 3), + ) + except Exception: + pass + + return True + + try: + elapsed = time.time() - start_time + analyser._log_kv( + "预约", + "[预约] handle_queue_full_wait_at_earliest 完成(回退失败)", + elapsed_seconds=round(elapsed, 3), + ) + except Exception: + pass + + return False + + diff --git a/douyin/reservation/reservation_logic/record.py b/douyin/reservation/reservation_logic/record.py new file mode 100644 index 0000000..0d01031 --- /dev/null +++ b/douyin/reservation/reservation_logic/record.py @@ -0,0 +1,328 @@ +"""reservation_logic.record - record_high_value_reservation 主入口。 + +把识别到的高价值福袋登记到预约队列。包装 add_reservation_core_logic, +处理直播间标题归一化、超过阈值判断、状态文件写回等。 +""" +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 .add import add_reservation_core_logic +from .helpers import ( + _normalize_room_title_for_matching, + _now_ts, +) + + +def record_high_value_reservation( + analyser: Any, + fudai_content_text: str, + prize_value_yuan: float, + lastsecond: int, + future_timestamp: float, + x: int, + needswitch: bool, + wait_minutes: int, + post_switch_delay_s: float, + room_pos: int, + reservations: List[ReservationItem], + reservation_focus_until_ts_ref: List[float], + close_detail_callback: Callable[[], None], + swipe_up_switch_callback: Callable[[], None], + swipe_down_back_callback: Callable[[], None], + add_reservation_callback: Callable[[List[ReservationItem], ReservationItem], None], + sort_reservations_callback: Callable[[], None], + write_state_callback: Callable[[], None], + room_title: str = "", + room_title_raw: str = "", + task_count: int = 2, + time_text: str = "", + participants: int = 0, + copies: int = 0, +) -> bool: + """记录一条高价值福袋预约。 + + 当前实现为"只记录,不立刻改变当前直播间"的版本: + - 构造预约 item 并加入 reservations; + - 写入状态文件; + - 返回 False,表示当前轮不需要立即抢占主流程。 + """ + try: + # 验证输入参数 + try: + if not isinstance(fudai_content_text, str): + fudai_content_text = str(fudai_content_text or "") + if not isinstance(prize_value_yuan, (int, float)): + prize_value_yuan = float(prize_value_yuan or 0.0) + if not isinstance(future_timestamp, (int, float)) or future_timestamp <= 0: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:future_timestamp 无效", + future_timestamp=future_timestamp, + error_type="InvalidParameter", + ) + except Exception: + pass + return False + if not isinstance(room_pos, int): + room_pos = int(room_pos or 0) + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:参数验证失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + return False + + # 计算 future_str(预计开奖时间的字符串格式) + future_str = "" + try: + if future_timestamp and future_timestamp > 0: + from datetime import datetime + + future_str = datetime.fromtimestamp(float(future_timestamp)).strftime( + "%Y-%m-%d %H:%M:%S" + ) + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + future_timestamp=future_timestamp, + prize_value_yuan=prize_value_yuan, + ), + level="WARNING", + stage="计算 future_str", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:计算 future_str 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + # 验证 reservations 列表 + if not isinstance(reservations, list): + if _RESERVATION_ERROR_UTILS_AVAILABLE: + try: + raise TypeError( + f"reservations 不是列表类型,而是 {type(reservations).__name__}" + ) + except TypeError as e: + log_reservation_error( + analyser, + e, + format_reservation_context( + reservations_type=type(reservations).__name__, + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + ), + level="ERROR", + stage="验证 reservations 列表", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:reservations 不是列表", + reservations_type=type(reservations).__name__, + error_type="InvalidParameter", + ) + except Exception: + pass + return False + + # 构造预约项 + try: + item: ReservationItem = { + "future_ts": float(future_timestamp or 0.0), + "future_str": future_str, + "prize_value_yuan": float(prize_value_yuan or 0.0), + "content": str(fudai_content_text or ""), + "pos_seen": int(room_pos), + "created_ts": _now_ts(), + "room_title": str(room_title or ""), + "room_title_raw": str(room_title_raw or ""), + "task_count": int(task_count or 2), + "time_text": str(time_text or ""), + "participants": int(participants or 0), + "copies": int(copies or 0), + } + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + room_pos=room_pos, + room_title=room_title, + room_title_raw=room_title_raw, + ), + level="ERROR", + stage="构造预约项", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:构造预约项失败", + error=str(e), + error_type=type(e).__name__, + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + room_pos=room_pos, + ) + except Exception: + pass + return False + + # 调用回调函数添加预约 + try: + add_reservation_callback(reservations, item) + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + reservations=reservations, + queue_len_before=len(reservations), + ), + level="ERROR", + stage="调用 add_reservation_callback", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:add_reservation_callback 失败", + error=str(e), + error_type=type(e).__name__, + queue_len_before=len(reservations), + ) + except Exception: + pass + return False + + # 排序预约队列 + try: + sort_reservations_callback() + except Exception as e: + if _RESERVATION_ERROR_UTILS_AVAILABLE: + log_reservation_error( + analyser, + e, + format_reservation_context( + item=item, + reservations=reservations, + ), + level="WARNING", + stage="调用 sort_reservations_callback", + ) + else: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:sort_reservations_callback 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + # 写入状态文件 + if _RESERVATION_ERROR_UTILS_AVAILABLE: + safe_write_state( + write_state_callback, + analyser, + format_reservation_context( + item=item, + reservations=reservations, + ), + ) + else: + try: + write_state_callback() + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:write_state_callback 失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + # 记录成功日志 + try: + from datetime import datetime + + created_str = datetime.fromtimestamp(item["created_ts"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:已记录高价值福袋", + value_yuan=item["prize_value_yuan"], + future_ts=int(item["future_ts"]), + future_str=future_str, + created_ts=int(item["created_ts"]), + created_str=created_str, + room_title=room_title[:50] if room_title else "", + room_title_raw=room_title_raw[:50] if room_title_raw else "", + content=fudai_content_text[:50] if fudai_content_text else "", + pos_seen=room_pos, + task_count=task_count, + participants=participants, + copies=copies, + queue_len=len(reservations), + ) + except Exception as e: + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation:记录成功日志失败", + error=str(e), + error_type=type(e).__name__, + ) + except Exception: + pass + + return False + except Exception as e: + # 任何异常都不影响主流程,只记录日志 + try: + analyser._log_kv( + "预约", + "[预约] record_high_value_reservation 异常,忽略本次预约", + error=str(e), + error_type=type(e).__name__, + prize_value_yuan=prize_value_yuan, + future_timestamp=future_timestamp, + room_pos=room_pos, + room_title=room_title[:50] if room_title else "", + ) + except Exception: + pass + return False