拆分 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>
This commit is contained in:
1 parent
787c4e8eec
commit
74209035f7
9 files changed
+2949
-2698
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -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",
|
||||
]
|
||||
@@ -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]
|
||||
@@ -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
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user