Fix reservation direct attend timing guard

This commit is contained in:
Your Name committed 2026-06-19 21:52:32 +08:00
1 parent 8fac904ba9
commit b533c4e96e
8 files changed
+609 -22

No files matched your search

+2
View File
@@ -178,6 +178,8 @@ def write_reservations_state(
"time_text": str(r.get("time_text") or ""),
"participants": int(r.get("participants") or 0),
"copies": int(r.get("copies") or 0),
"button_text": str(r.get("button_text") or ""),
"button_status": str(r.get("button_status") or ""),
}
)
@@ -17,6 +17,19 @@ from douyin.fudai import douyin_fudai_detail
from douyin.handlers import douyin_swipe_handler
from douyin.reservation import douyin_reservation_logic
_DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES = {
"可参与",
"需要评论",
"需要粉丝团",
"未知可点",
}
_DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
"参与",
"评论",
"发表",
"一键",
)
# 错误处理工具占位(与原文件保持兼容降级)
try:
from douyin.reservation.core.reservation_error_utils import (
@@ -53,6 +66,203 @@ def _log_direct_attend_marker(analyser: Any, status: str, **extra) -> None:
pass
def _clear_direct_attend_flags(analyser: Any, *, clear_focus: bool = False) -> None:
try:
analyser.reservation_after_action_pending = False
analyser._current_attending_reservation_fudai = False
if clear_focus:
analyser.reservation_focus_until_ts = 0.0
except Exception:
pass
def _direct_attend_min_action_seconds(analyser: Any) -> float:
try:
return float(getattr(analyser, "reservation_direct_attend_min_action_seconds", 8.0) or 8.0)
except Exception:
return 8.0
def _direct_attend_failure_limit(analyser: Any) -> int:
try:
return max(1, int(getattr(analyser, "reservation_direct_attend_max_failures", 2) or 2))
except Exception:
return 2
def _reservation_key(item: Dict[str, Any]) -> str:
try:
ft = int(float(item.get("future_ts") or 0.0))
except Exception:
ft = 0
return f"{ft}:{str(item.get('room_title') or '')[:40]}:{str(item.get('content') or '')[:40]}"
def _get_direct_attend_failure_count(analyser: Any, item: Dict[str, Any]) -> int:
key = _reservation_key(item)
state = getattr(analyser, "_reservation_direct_attend_failures", None)
if not isinstance(state, dict):
return 0
try:
return int(state.get(key, 0) or 0)
except Exception:
return 0
def _record_direct_attend_failure(analyser: Any, item: Dict[str, Any], reason: str, **extra) -> int:
key = _reservation_key(item)
state = getattr(analyser, "_reservation_direct_attend_failures", None)
if not isinstance(state, dict):
state = {}
try:
setattr(analyser, "_reservation_direct_attend_failures", state)
except Exception:
pass
try:
count = int(state.get(key, 0) or 0) + 1
state[key] = count
except Exception:
count = 1
try:
analyser._log_kv(
"预约",
"[预约] 预约直参失败计数",
reason=str(reason or ""),
failure_count=count,
failure_limit=_direct_attend_failure_limit(analyser),
reservation_key=key,
**(extra or {}),
)
except Exception:
pass
return count
def _reset_direct_attend_failure_count(analyser: Any, item: Dict[str, Any]) -> None:
state = getattr(analyser, "_reservation_direct_attend_failures", None)
if not isinstance(state, dict):
return
try:
state.pop(_reservation_key(item), None)
except Exception:
pass
def _write_reservations_state_if_possible(analyser: Any, reason: str) -> None:
try:
state_path = getattr(analyser, "_reservations_state_path", "") or path_config.get_reservations_path()
if not state_path:
return
from douyin.reservation.douyin_reservation import write_reservations_state
write_reservations_state(
state_path=state_path,
reservations=list(getattr(analyser, "reservations", []) or []),
room_pos=int(getattr(analyser, "room_pos", 0) or 0),
current_room_title=str(getattr(analyser, "current_room_title", "") or ""),
current_room_title_raw=str(getattr(analyser, "current_room_title_raw", "") or ""),
reason=reason,
analyser=analyser,
)
except Exception:
pass
def _drop_current_reservation(analyser: Any, item: Dict[str, Any], reason: str) -> None:
try:
target_ft = float(item.get("future_ts") or 0.0)
except Exception:
target_ft = 0.0
remaining = []
removed = False
for res in list(getattr(analyser, "reservations", []) or []):
try:
res_ft = float(res.get("future_ts") or 0.0)
same = target_ft > 0 and abs(res_ft - target_ft) <= 5.0
except Exception:
same = False
if same and not removed:
removed = True
continue
remaining.append(res)
try:
analyser.reservations = remaining
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] 预约直参放弃当前预约并从队列移除",
reason=str(reason or ""),
removed=removed,
remain_count=len(remaining),
future_ts=int(target_ft) if target_ft > 0 else 0,
)
except Exception:
pass
_write_reservations_state_if_possible(analyser, reason)
def _save_direct_attend_debug_screenshot(analyser: Any, label: str, **extra) -> None:
try:
from PIL import Image
from douyin.handlers import douyin_screenshot_manager
screenshot_path = path_config.get_screenshot_path()
if not os.path.exists(screenshot_path):
return
img = Image.open(screenshot_path)
try:
img.load()
rgb = img.convert("RGB")
finally:
img.close()
debug_path = douyin_screenshot_manager.save_debug_image(
rgb,
operation_type="reservation_direct_attend",
picname=str(label or "anomaly"),
step="evidence",
extra_info={
"run_id": str(getattr(analyser, "_run_id", "") or ""),
**(extra or {}),
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"预约直参异常截图已保存",
path=debug_path,
label=str(label or ""),
**(extra or {}),
)
except Exception:
pass
except Exception:
pass
def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, Any]) -> tuple[bool, str, str]:
button_text = str(
item.get("button_text")
or item.get("button_text_raw")
or getattr(analyser, "_fudai_button_text", "")
or getattr(analyser, "button_text_raw", "")
or ""
)
button_status = str(
item.get("button_status")
or getattr(analyser, "_fudai_button_status", "")
or getattr(analyser, "button_status", "")
or ""
)
if button_status in _DIRECT_ATTEND_ACTIONABLE_BUTTON_STATUSES:
return True, button_text, button_status
if button_text and any(snippet in button_text for snippet in _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS):
return True, button_text, button_status
return False, button_text, button_status
def handle_reservation_direct_attend(analyser: Any) -> None:
"""预约回退后直接参与:直接查找福袋并点击,使用按钮检测进行决策,跳过OCR识别。
@@ -125,12 +335,13 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
first_reservation.get("prize_value_yuan", 0.0) or 0.0
)
# 检查福袋是否已过期
# 检查福袋是否已过期或已经来不及完成一次直参动作。
now_ts = time.time()
poll_before = float(
getattr(analyser, "high_value_fudai_poll_before_seconds", 10.0) or 10.0
)
expired_threshold = future_ts + max(0.0, poll_before) # 开奖时间 + 缓冲时间
remain_seconds = future_ts - now_ts if future_ts > 0 else 0.0
if future_ts > 0 and now_ts > expired_threshold:
# 福袋已过期,清除标志并退出
@@ -190,6 +401,77 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
return
min_action_seconds = _direct_attend_min_action_seconds(analyser)
if future_ts > 0 and remain_seconds < min_action_seconds:
_log_direct_attend_marker(
analyser,
"fallback",
reason="direct_attend_abort_due_to_insufficient_time",
future_ts=int(future_ts),
remain_seconds=int(max(0, remain_seconds)),
min_action_seconds=round(min_action_seconds, 3),
)
try:
analyser._log_kv(
"预约",
"[预约] 预约回退后直接参与:剩余时间不足,停止本轮直参避免继续拖慢",
reason="direct_attend_abort_due_to_insufficient_time",
future_ts=int(future_ts),
remain_seconds=round(remain_seconds, 3),
min_action_seconds=round(min_action_seconds, 3),
failure_count=_get_direct_attend_failure_count(
analyser, first_reservation
),
)
except Exception:
pass
failure_count = _record_direct_attend_failure(
analyser,
first_reservation,
"direct_attend_abort_due_to_insufficient_time",
remain_seconds=round(remain_seconds, 3),
)
_save_direct_attend_debug_screenshot(
analyser,
"insufficient_time",
reason="direct_attend_abort_due_to_insufficient_time",
future_ts=int(future_ts),
)
if failure_count >= _direct_attend_failure_limit(analyser):
_drop_current_reservation(
analyser,
first_reservation,
"direct_attend_insufficient_time_failure_budget_exhausted",
)
_clear_direct_attend_flags(analyser)
return
failure_count = _get_direct_attend_failure_count(analyser, first_reservation)
failure_limit = _direct_attend_failure_limit(analyser)
if failure_count >= failure_limit:
_log_direct_attend_marker(
analyser,
"failed",
reason="direct_attend_failure_budget_exhausted",
future_ts=int(future_ts),
failure_count=failure_count,
failure_limit=failure_limit,
)
_save_direct_attend_debug_screenshot(
analyser,
"failure_budget_exhausted",
reason="direct_attend_failure_budget_exhausted",
future_ts=int(future_ts),
failure_count=failure_count,
)
_drop_current_reservation(
analyser,
first_reservation,
"direct_attend_failure_budget_exhausted",
)
_clear_direct_attend_flags(analyser, clear_focus=True)
return
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
analyser._current_fudai_future_ts = future_ts
@@ -211,6 +493,20 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
if not opened:
_log_direct_attend_marker(analyser, "fallback", reason="fudai_icon_not_found")
failure_count = _record_direct_attend_failure(
analyser,
first_reservation,
"fudai_icon_not_found",
future_ts=int(future_ts),
remain_seconds=int(max(0, future_ts - time.time())) if future_ts > 0 else 0,
)
_save_direct_attend_debug_screenshot(
analyser,
"verified_return_but_fudai_not_found",
reason="fudai_icon_not_found",
future_ts=int(future_ts),
failure_count=failure_count,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
@@ -219,11 +515,13 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
)
except Exception:
pass
try:
analyser.reservation_after_action_pending = False
analyser._current_attending_reservation_fudai = False
except Exception:
pass
if failure_count >= _direct_attend_failure_limit(analyser):
_drop_current_reservation(
analyser,
first_reservation,
"fudai_icon_not_found_failure_budget_exhausted",
)
_clear_direct_attend_flags(analyser)
return
# 等待页面加载
@@ -285,22 +583,59 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
button_info = {}
if not has_button:
_log_direct_attend_marker(analyser, "fallback", reason="attend_button_not_detected")
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 未检测到参与按钮,退出预约直接参与,等待正常直播间阶段重判",
button_info=button_info,
reason="attend_button_not_detected_after_detail_open",
fallback_ok, fallback_button_text, fallback_button_status = (
_reservation_button_fallback_is_actionable(analyser, first_reservation)
)
if fallback_ok:
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 参与按钮像素未命中,但预约/缓存按钮文本可操作,执行兜底点击",
button_info=button_info,
button_text=fallback_button_text,
button_status=fallback_button_status,
reason="reservation_button_text_fallback_click_sent",
)
except Exception:
pass
button_info = {
**(button_info or {}),
"fallback": "reservation_button_text",
"button_text": fallback_button_text,
"button_status": fallback_button_status,
}
else:
_log_direct_attend_marker(analyser, "fallback", reason="attend_button_not_detected")
failure_count = _record_direct_attend_failure(
analyser,
first_reservation,
"attend_button_not_detected",
future_ts=int(future_ts),
)
except Exception:
pass
try:
analyser.reservation_after_action_pending = False
analyser._current_attending_reservation_fudai = False
except Exception:
pass
return
_save_direct_attend_debug_screenshot(
analyser,
"detail_open_but_attend_button_not_detected",
reason="attend_button_not_detected",
future_ts=int(future_ts),
failure_count=failure_count,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 未检测到参与按钮,退出预约直接参与,等待正常直播间阶段重判",
button_info=button_info,
reason="attend_button_not_detected_after_detail_open",
)
except Exception:
pass
if failure_count >= _direct_attend_failure_limit(analyser):
_drop_current_reservation(
analyser,
first_reservation,
"attend_button_not_detected_failure_budget_exhausted",
)
_clear_direct_attend_flags(analyser)
return
# 步骤3:点击参与按钮
try:
@@ -416,6 +751,7 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
"success",
future_ts=int(future_ts),
)
_reset_direct_attend_failure_count(analyser, first_reservation)
# 记录统计:预约回退成功算作成功参与一次
try:
analyser._log_kv( # type: ignore[attr-defined]
@@ -130,7 +130,39 @@ def compute_dynamic_ahead(
if max_back > 0:
est_back_times = min(est_back_times, max_back)
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))
try:
screenshot_budget = float(
getattr(analyser, "reservation_screenshot_budget_seconds", 8.0) or 8.0
)
except Exception:
screenshot_budget = 8.0
try:
verify_wait = float(
getattr(analyser, "reservation_back_verify_wait_seconds", 5.0) or 5.0
)
except Exception:
verify_wait = 5.0
try:
direct_attend_budget = float(
getattr(analyser, "reservation_direct_attend_min_action_seconds", 8.0)
or 8.0
)
except Exception:
direct_attend_budget = 8.0
try:
safety_budget = float(
getattr(analyser, "reservation_back_safety_budget_seconds", 4.0) or 4.0
)
except Exception:
safety_budget = 4.0
runtime_budget = (
est_back_times * reservation_back_swipe_delay_s_val
+ screenshot_budget
+ verify_wait
+ direct_attend_budget
+ safety_budget
)
dynamic_ahead = int(max(join_ahead, runtime_budget))
except Exception:
dynamic_ahead = int(join_ahead)
return dynamic_ahead, est_back_times
@@ -165,6 +165,12 @@ def record_high_value_reservation(
"time_text": str(time_text or ""),
"participants": int(participants or 0),
"copies": int(copies or 0),
"button_text": str(
getattr(analyser, "_fudai_button_text", "")
or getattr(analyser, "button_text_raw", "")
or ""
),
"button_status": str(getattr(analyser, "_fudai_button_status", "") or ""),
}
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
@@ -24,6 +24,15 @@ def _mk_analyser():
return analyser
def _has_log_reason(analyser, reason: str) -> bool:
for call in analyser._log_kv.call_args_list:
if str(call.kwargs.get("reason", "")) == reason:
return True
if str(call.kwargs.get("原因", "")) == reason:
return True
return False
def test_direct_attend_logs_fixed_success_marker():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
@@ -54,6 +63,33 @@ def test_direct_attend_logs_fixed_success_marker():
assert marker_logs
def test_direct_attend_rescans_fudai_after_join_click_for_verification():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
) as finder, patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(True, {"mock": True}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
assert finder.call_count == 2
analyser.operation.click.assert_called()
def test_direct_attend_logs_fixed_failure_marker_when_button_still_exists():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
@@ -165,3 +201,80 @@ def test_direct_attend_expired_reservation_clears_flags_without_detail_handler()
if len(call.args) >= 2 and str(call.args[1]) == "预约回退 direct_attend 失败"
]
assert marker_logs
def test_direct_attend_aborts_when_remaining_window_too_small():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.reservations = [
{
"future_ts": time.time() + 2.0,
"prize_value_yuan": 5980.0,
"content": "soon",
}
]
analyser._current_attending_reservation_fudai = True
with patch("douyin.core.douyin_flow_control.find_and_open_fudai_detail") as finder:
handle_reservation_direct_attend(analyser)
finder.assert_not_called()
assert analyser.reservation_after_action_pending is False
assert analyser._current_attending_reservation_fudai is False
assert _has_log_reason(analyser, "direct_attend_abort_due_to_insufficient_time")
def test_direct_attend_never_clicks_cached_fudai_x_without_current_scan():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.reservations = [
{
"future_ts": time.time() + 2.0,
"prize_value_yuan": 5980.0,
"content": "soon",
}
]
analyser.last_fudai_x = 162
analyser._current_attending_reservation_fudai = True
with patch("douyin.core.douyin_flow_control.find_and_open_fudai_detail") as finder:
handle_reservation_direct_attend(analyser)
finder.assert_not_called()
analyser.operation.click.assert_not_called()
assert _has_log_reason(analyser, "direct_attend_abort_due_to_insufficient_time")
def test_direct_attend_uses_reservation_text_fallback_when_button_pixel_misses():
from douyin.reservation.douyin_reservation_handler_pkg.direct_attend import (
handle_reservation_direct_attend,
)
analyser = _mk_analyser()
analyser.reservations[0]["button_text"] = "一键发表评论"
analyser.reservations[0]["button_status"] = "需要评论"
with patch(
"douyin.core.douyin_flow_control.find_and_open_fudai_detail",
side_effect=[True, False],
), patch(
"douyin.core.path_config.get_screenshot_path",
return_value="C:/mock/screenshot.png",
), patch(
"PIL.Image.open",
) as mock_open, patch(
"douyin.detection.douyin_pixel.detect_attend_button_red_area",
return_value=(False, {"reason": "red_ratio_below_threshold"}),
):
mock_image = MagicMock()
mock_open.return_value = mock_image
handle_reservation_direct_attend(analyser)
analyser.operation.click.assert_called()
assert _has_log_reason(analyser, "reservation_button_text_fallback_click_sent")
+23
View File
@@ -16,6 +16,9 @@ from douyin.reservation.reservation_logic.helpers import (
_now_ts,
_sort_reservations_inplace,
)
from douyin.reservation.reservation_logic.attend_window_helpers import (
compute_dynamic_ahead,
)
# ============================================================
@@ -155,3 +158,23 @@ class TestSortReservationsInplace:
_sort_reservations_inplace(items)
# 原列表对象未变
assert id(items) == original_id
class TestComputeDynamicAhead:
def test_includes_runtime_capture_and_verify_budget(self):
class _A:
reservation_back_verify_wait_seconds = 5.0
reservation_direct_attend_min_action_seconds = 8.0
reservation_screenshot_budget_seconds = 8.0
high_value_fudai_max_swipe_back = 60
dynamic_ahead, est_back_times = compute_dynamic_ahead(
_A(),
{"pos_seen": 0},
room_pos=2,
reservation_back_swipe_delay_s=0.5,
join_ahead=10.0,
)
assert est_back_times == 2
assert dynamic_ahead >= 25
+28
View File
@@ -8,6 +8,8 @@
from __future__ import annotations
import json
import pytest
@@ -93,6 +95,32 @@ class TestDouyinReservation:
assert callable(write_reservations_state)
def test_write_reservations_state_preserves_button_fields(self, tmp_path):
from douyin.reservation.douyin_reservation import write_reservations_state
state_path = tmp_path / "reservations.json"
write_reservations_state(
state_path=str(state_path),
reservations=[
{
"future_ts": 9999999999.0,
"prize_value_yuan": 899.0,
"content": "X",
"button_text": "一键发表评论",
"button_status": "需要评论",
}
],
room_pos=1,
current_room_title="room",
current_room_title_raw="room",
reason="unit",
)
data = json.loads(state_path.read_text(encoding="utf-8"))
item = data["reservations"][0]
assert item["button_text"] == "一键发表评论"
assert item["button_status"] == "需要评论"
def test_load_high_value_rooms_map_exists(self):
from douyin.reservation.douyin_reservation import load_high_value_rooms_map
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
import time
from types import SimpleNamespace
from unittest.mock import MagicMock
def test_record_high_value_reservation_preserves_button_fields():
from douyin.reservation.reservation_logic.record import record_high_value_reservation
analyser = SimpleNamespace(
_log_kv=MagicMock(return_value=None),
_fudai_button_text="一键发表评论",
_fudai_button_status="需要评论",
)
reservations = []
ok = record_high_value_reservation(
analyser=analyser,
fudai_content_text="儿童电话手表",
prize_value_yuan=899.0,
lastsecond=120,
future_timestamp=time.time() + 600,
x=162,
needswitch=True,
wait_minutes=0,
post_switch_delay_s=0.0,
room_pos=1,
reservations=reservations,
reservation_focus_until_ts_ref=[0.0],
close_detail_callback=lambda: None,
swipe_up_switch_callback=lambda: None,
swipe_down_back_callback=lambda: None,
add_reservation_callback=lambda items, item: items.append(item),
sort_reservations_callback=lambda: None,
write_state_callback=lambda: None,
room_title="学而思",
room_title_raw="学而思",
task_count=2,
time_text="10:00",
participants=0,
copies=1,
)
assert ok is False
assert reservations[0]["button_text"] == "一键发表评论"
assert reservations[0]["button_status"] == "需要评论"