diff --git a/douyin/reservation/douyin_reservation_handler_pkg/record_title.py b/douyin/reservation/douyin_reservation_handler_pkg/record_title.py index 1ac2fe8..1bb6deb 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/record_title.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/record_title.py @@ -88,6 +88,72 @@ def _merge_room_info(base: dict[str, Any], extra: dict[str, Any]) -> dict[str, A return base +def _titles_match(left: str, right: str) -> bool: + left_norm = _normalize_room_title_for_matching(left) + right_norm = _normalize_room_title_for_matching(right) + if not left_norm or not right_norm: + return False + return left_norm == right_norm or left_norm in right_norm or right_norm in left_norm + + +def _should_protect_pending_reservation_target( + analyser: Any, + room_pos: int, + existing_info: dict[str, Any], + current_title: str, + current_title_raw: str, +) -> tuple[bool, dict[str, Any]]: + """避免回退失败后把待开奖预约目标位写成当前错误直播间。""" + try: + if not bool(getattr(analyser, "_reservation_seek_uncertain", False)): + return False, {} + failed_pos = int(getattr(analyser, "_reservation_seek_failed_target_pos", -1)) + if failed_pos != int(room_pos): + return False, {} + except Exception: + return False, {} + + reservations = getattr(analyser, "reservations", []) or [] + if not isinstance(reservations, list): + reservations = [] + + existing_title = str(existing_info.get("title", "") or "").strip() + existing_title_raw = str(existing_info.get("title_raw", "") or "").strip() + current_title_any = (current_title or current_title_raw or "").strip() + + for item in reservations: + if not isinstance(item, dict): + continue + try: + pos_seen = int(item.get("pos_seen") or -1) + except Exception: + pos_seen = -1 + if pos_seen != int(room_pos): + continue + reservation_title = str(item.get("room_title", "") or "").strip() + reservation_title_raw = str(item.get("room_title_raw", "") or "").strip() + reservation_title_any = (reservation_title or reservation_title_raw or "").strip() + if not reservation_title_any: + continue + existing_matches = ( + _titles_match(existing_title, reservation_title_any) + or _titles_match(existing_title_raw, reservation_title_any) + or not (existing_title or existing_title_raw) + ) + current_matches = _titles_match(current_title_any, reservation_title_any) + if existing_matches and not current_matches: + return True, { + "reservation_title": reservation_title, + "reservation_title_raw": reservation_title_raw, + "existing_title": existing_title, + "existing_title_raw": existing_title_raw, + "current_title": current_title, + "current_title_raw": current_title_raw, + "reason": "protect_pending_reservation_target_after_seek_mismatch", + } + return False, {} + + def record_room_title_and_pos(analyser: Any) -> bool: """记录当前直播间的标题和位置到运行时映射表。 @@ -288,6 +354,36 @@ def record_room_title_and_pos(analyser: Any) -> bool: room_info["title"] = room_title room_info["title_raw"] = room_title_raw + protect_target, protect_detail = _should_protect_pending_reservation_target( + analyser, + room_pos, + existing_info, + room_title, + room_title_raw, + ) + if protect_target: + try: + analyser._log_kv( # type: ignore[attr-defined] + "预约", + "[预约] 跳过映射表覆盖:当前位置是待回退预约目标但当前标题不匹配", + room_pos=room_pos, + existing_title=protect_detail.get("existing_title", "")[:50], + reservation_title=protect_detail.get("reservation_title", "")[:50], + current_title=protect_detail.get("current_title", "")[:50], + reason=protect_detail.get("reason", ""), + level="WARNING", + ) + except Exception: + pass + _emit_flow_flag( + analyser, + "room_map_record", + "skip_protected_pending_reservation_target", + room_pos=room_pos, + reason=protect_detail.get("reason", ""), + ) + return False + current_title_for_norm = room_title or room_title_raw current_title_norm = _normalize_room_title_for_matching(current_title_for_norm) duplicate_title_positions: list[int] = [] diff --git a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py index 7fb2af2..a9ca7a2 100644 --- a/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py +++ b/douyin/reservation/douyin_reservation_handler_pkg/seek_room.py @@ -65,6 +65,15 @@ def seek_reservation_room( # 计算需要切换的次数和方向 pos_diff = target_pos - cur_pos moved = False # 标记是否实际执行了滑动操作 + try: + if "_seek_start_room_pos" not in item: + item["_seek_start_room_pos"] = int(cur_pos) + if pos_diff < 0: + item["_seek_direction_hint"] = "down" + elif pos_diff > 0: + item["_seek_direction_hint"] = "up" + except Exception: + pass try: max_back = int( @@ -222,6 +231,7 @@ def seek_reservation_room( douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live( analyser ) + moved = True try: analyser.operation.delay(0.1) except Exception: @@ -232,6 +242,7 @@ def seek_reservation_room( analyser._skip_record_title_during_seek = False except Exception: pass + return True return False except Exception: # 若验证流程异常,返回 False 以避免误判 diff --git a/douyin/reservation/reservation_logic/attend_window_verify.py b/douyin/reservation/reservation_logic/attend_window_verify.py index fc90585..2bbd43e 100644 --- a/douyin/reservation/reservation_logic/attend_window_verify.py +++ b/douyin/reservation/reservation_logic/attend_window_verify.py @@ -253,6 +253,12 @@ def _handle_verify_failure( verify_detail: Any, ) -> bool: """校验失败 → 用映射表重定位 + 二次回退。返回 True/False 给 caller。""" + _mark_seek_uncertain( + analyser, + target, + target_room_title, + target_room_title_raw, + ) if _RESERVATION_ERROR_UTILS_AVAILABLE: log_reservation_error( analyser, @@ -375,6 +381,51 @@ def _handle_verify_failure( return False +def _mark_seek_uncertain( + analyser: Any, + target: ReservationItem, + target_room_title: str, + target_room_title_raw: str, +) -> None: + """回退校验失败后,标记当前 room_pos 只是一种预期值,不可直接写映射表。""" + try: + target_pos = int(target.get("pos_seen") or 0) + except Exception: + target_pos = 0 + try: + current_title = str(getattr(analyser, "current_room_title", "") or "").strip() + current_title_raw = str( + getattr(analyser, "current_room_title_raw", "") or "" + ).strip() + except Exception: + current_title = "" + current_title_raw = "" + try: + analyser._reservation_seek_uncertain = True + analyser._reservation_seek_failed_target_pos = int(target_pos) + analyser._reservation_seek_expected_title = str(target_room_title or "").strip() + analyser._reservation_seek_expected_title_raw = str( + target_room_title_raw or "" + ).strip() + analyser._reservation_seek_current_title = current_title + analyser._reservation_seek_current_title_raw = current_title_raw + analyser._reservation_seek_failed_ts = time.time() + except Exception: + pass + try: + analyser._log_kv( + "预约", + "[预约] 回退校验失败:标记当前位置不可信,保护预约目标映射", + target_pos=int(target_pos), + expected_title=str(target_room_title or "")[:50], + current_title=current_title[:50] if current_title else "", + reason="reservation_seek_verify_failed", + level="WARNING", + ) + except Exception: + pass + + def _remap_target_via_room_titles( analyser: Any, target: ReservationItem, @@ -564,6 +615,30 @@ def _retry_seek_with_mapped_diff( except Exception: pass + if mapped_current_pos is None and mapped_target_pos is not None: + try: + seek_start_pos = int(updated_target.get("_seek_start_room_pos") or 0) + except Exception: + seek_start_pos = 0 + if seek_start_pos and seek_start_pos != int(mapped_target_pos): + try: + if seek_start_pos > int(mapped_target_pos): + updated_target["_seek_direction_hint"] = "down" + elif seek_start_pos < int(mapped_target_pos): + updated_target["_seek_direction_hint"] = "up" + except Exception: + pass + try: + analyser._log_kv( + "预约", + "[预约] 当前房间未能映射,使用回退前起点启用纠偏回退", + mapped_target_pos=int(mapped_target_pos), + seek_start_room_pos=int(seek_start_pos), + direction_hint=updated_target.get("_seek_direction_hint", ""), + ) + except Exception: + pass + if should_retry_seek: try: if seek_reservation_room_callback: diff --git a/tests/test_attend_window_verify_realign.py b/tests/test_attend_window_verify_realign.py new file mode 100644 index 0000000..a199a8b --- /dev/null +++ b/tests/test_attend_window_verify_realign.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from unittest.mock import MagicMock + + +def _mk_analyser(): + class _A: + pass + + a = _A() + a._log_kv = MagicMock(return_value=None) + a.room_pos = 2 + a.current_room_title = "料音城ATK官抖音旗舰" + a.current_room_title_raw = "料音城ATK官抖音旗舰" + a._room_pos_to_title_map = { + 2: {"title": "麦小登18", "title_raw": "麦小登-18."} + } + return a + + +def test_retry_sets_direction_hint_from_seek_start_when_current_room_unknown(): + from douyin.reservation.reservation_logic import attend_window_verify as mod + + analyser = _mk_analyser() + target = { + "pos_seen": 2, + "room_title": "麦小登18", + "room_title_raw": "麦小登-18.", + "_seek_start_room_pos": 7, + "_seek_direction_hint": "down", + } + calls = [] + + def seek_callback(item): + calls.append(dict(item)) + return True + + ok = mod._retry_seek_with_mapped_diff( + analyser=analyser, + updated_target=target, + mapped_target_pos=2, + mapped_current_pos=None, + room_pos_before_map=2, + seek_reservation_room_callback=seek_callback, + ) + + assert ok is True + assert calls + assert calls[0]["_seek_direction_hint"] == "down" + assert calls[0]["_seek_start_room_pos"] == 7 + + +def test_verify_failure_marks_room_pos_uncertain_before_retry(): + from douyin.reservation.reservation_logic import attend_window_verify as mod + + analyser = _mk_analyser() + target = { + "pos_seen": 2, + "room_title": "麦小登18", + "room_title_raw": "麦小登-18.", + "_seek_start_room_pos": 7, + "_seek_direction_hint": "down", + } + + ok = mod._handle_verify_failure( + analyser=analyser, + target=target, + reservations=[target], + target_room_title="麦小登18", + target_room_title_raw="麦小登-18.", + ft=9999999999.0, + poll_before=10.0, + reservation_focus_until_ts_ref=[0.0], + reservation_after_action_pending_ref=[False], + seek_reservation_room_callback=lambda item: False, + write_state_callback=lambda: None, + verify_detail=None, + ) + + assert ok is False + assert analyser._reservation_seek_uncertain is True + assert analyser._reservation_seek_failed_target_pos == 2 + assert analyser._reservation_seek_expected_title == "麦小登18" + assert analyser._reservation_seek_current_title == "料音城ATK官抖音旗舰" diff --git a/tests/test_record_title_mapping.py b/tests/test_record_title_mapping.py index 4fbeb0c..1266f9e 100644 --- a/tests/test_record_title_mapping.py +++ b/tests/test_record_title_mapping.py @@ -110,3 +110,45 @@ def test_same_room_streak_triggers_reset_and_consumes_swipe(): # 回顶逻辑不应清空映射表 assert isinstance(a._room_pos_to_title_map, dict) assert len(a._room_pos_to_title_map) >= 1 + + +def test_pending_reservation_target_not_overwritten_after_failed_seek(): + from douyin.reservation.douyin_reservation_handler_pkg import record_title as mod + + a = _mk_analyser() + a.room_pos = 2 + a.current_room_title = "料音城ATK官抖音旗舰" + a.current_room_title_raw = "料音城ATK官抖音旗舰" + a._room_title_identified_positions = {2} + a._reservation_seek_uncertain = True + a._reservation_seek_failed_target_pos = 2 + a.reservations = [ + { + "future_ts": 9999999999.0, + "pos_seen": 2, + "room_title": "麦小登18", + "room_title_raw": "麦小登-18.", + "content": "新款小型电动车", + } + ] + a._current_fudai_content = "错误房间福袋" + a._last_fudai_detail_tuple = ("wrong",) + a._room_pos_to_title_map = { + 2: { + "title": "麦小登18", + "title_raw": "麦小登-18.", + "has_fudai": True, + "fudai_content": "新款小型电动车", + "fudai_detail": ("target",), + "timestamp": 1.0, + } + } + + with patch.object(mod, "_dump_room_pos_map_to_state", return_value=None): + consumed = mod.record_room_title_and_pos(a) + + assert consumed is False + assert a._room_pos_to_title_map[2]["title"] == "麦小登18" + assert a._room_pos_to_title_map[2]["fudai_content"] == "新款小型电动车" + messages = [call.args[1] for call in a._log_kv.call_args_list if len(call.args) > 1] + assert any("跳过映射表覆盖" in msg for msg in messages) diff --git a/tests/test_seek_room_realign.py b/tests/test_seek_room_realign.py new file mode 100644 index 0000000..e7fe3e1 --- /dev/null +++ b/tests/test_seek_room_realign.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from unittest.mock import MagicMock, patch + + +def test_same_pos_title_mismatch_direction_hint_performs_realign_and_returns_true(): + from douyin.reservation.douyin_reservation_handler_pkg import seek_room as mod + + class _Op: + def delay(self, _seconds): + return None + + class _A: + pass + + analyser = _A() + analyser.room_pos = 2 + analyser.current_room_title = "料音城ATK官抖音旗舰" + analyser.current_room_title_raw = "料音城ATK官抖音旗舰" + analyser.operation = _Op() + analyser._log_kv = MagicMock(return_value=None) + item = { + "pos_seen": 2, + "room_title": "麦小登18", + "room_title_raw": "麦小登-18.", + "_seek_start_room_pos": 7, + "_seek_direction_hint": "down", + } + + with patch.object( + mod.douyin_swipe_handler.SwipeHandler, + "swipe_down_back_from_live", + return_value=None, + ) as mock_down: + ok = mod.seek_reservation_room(analyser, item) + + assert ok is True + mock_down.assert_called_once_with(analyser) + assert item["_seek_start_room_pos"] == 7 + assert item["_seek_mismatch_realign_done"] is True