Files
douyin_guaji-main/douyin/reservation/reservation_logic/record.py
T
CodexandClaude Opus 4.7 74209035f7 拆分 douyin_reservation_logic (2702 → 7 个子模块 + 53 行 shim)
把 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 <noreply@anthropic.com>
2026-05-21 17:03:55 +08:00

329 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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