Files
douyin_guaji-main/douyin_reservation_logic.py
T
Your Name 29f7b19916 fix: Clean up code by removing unnecessary blank lines
- Removed excessive blank lines from various markdown and Python files to enhance readability and maintainability.
- Ensured consistent formatting across documentation and code files, improving overall project clarity.
2025-12-25 16:55:44 +08:00

724 lines
24 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.
from __future__ import annotations
"""
高价值福袋预约核心逻辑(模块化版本)
==================================
本模块从原始 `fudai1.py` 的思路抽取并简化了预约相关逻辑,保留了这些要点:
- 以 future_ts(预计开奖时间戳)为主排序键,其次 prize_value_yuan,再次 created_ts;
- 预约队列长度受 high_value_fudai_max_reservations 限制,溢出时裁剪掉优先级最低的记录;
- 进入预约窗口时可以抢占当前流程,回退到目标直播间,再由上层去识别详情并参与;
- 支持轻量的“回退校验”和状态写回(供 GUI / Web 端展示)。
接口签名与之前的 shim 保持兼容,便于在 `douyin_fudai.py` / `douyin_flow_control.py`
中直接调用。
"""
from typing import Any, Dict, List, Callable, Optional
import time
ReservationItem = Dict[str, Any]
def _now_ts() -> float:
return time.time()
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) 相同则视为同一条记录,保留价值更高的那条。
返回:
bool: 如果队列已满且需要回到最早开奖的预约直播间等待,返回 True;否则返回 False。
"""
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)
same_idx: Optional[int] = None
for idx, r in enumerate(reservations):
try:
if (
float(r.get("future_ts") or 0.0) == ft
and str(r.get("content") or "") == content
):
same_idx = idx
break
except Exception:
continue
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:
reservations[same_idx].update(dict(item))
else:
reservations.append(dict(item))
# 排序 + 按上限裁剪
_sort_reservations_inplace(reservations)
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
# 如果队列已满,写入状态文件
if write_state_callback:
try:
write_state_callback()
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",
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:
"""清理已过开奖时间的预约,并视情况写入状态文件。"""
try:
now_ts_drop = _now_ts()
before = len(reservations)
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:
analyser._log_kv(
"预约",
"[预约] cleanup_expired_reservations",
dropped=dropped,
remain=len(reservations),
)
except Exception:
pass
if write_state_callback is not None:
try:
write_state_callback()
except Exception:
pass
except Exception:
# Best-effort cleanup only; never crash主循环
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。
"""
if not reservations:
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:
return False
now_ts = _now_ts()
focus_until = float(
reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0
)
# 如果已经在锁定期内,不需要重复回退
if focus_until > 0 and now_ts < focus_until:
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)
except Exception:
pass
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)
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
# 先轻微下滑一次,确保在直播列表中
try:
swipe_down_back_callback()
time.sleep(max(0.1, float(reservation_back_swipe_delay_s or 0.0)))
except Exception:
pass
# 回退到最早开奖的预约直播间
ok = False
try:
ok = bool(seek_reservation_room_callback(earliest))
except Exception:
ok = False
if ok:
# 设置锁定期:直到最早开奖时间 + 轮询时间
try:
poll_before = float(
getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0
)
except Exception:
poll_before = 10.0
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)
try:
analyser._log_kv(
"预约",
"[预约] 已回退到最早开奖的预约直播间,等待所有预约完成",
earliest_future_ts=int(ft),
focus_until=int(focus_until_new),
)
except Exception:
pass
try:
write_state_callback()
except Exception:
pass
return True
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,表示已经触发了回退/跳转,本轮主循环应尽快结束,
让上层逻辑继续后续处理(例如识别详情并参与)。
"""
if not reservations:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约队列为空,跳过",
)
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
)
# 按统一规则排序(防止外部遗漏 sort)
sort_reservations_callback()
# 取队头(最早需要处理的一条)
target = reservations[0]
try:
ft = float(target.get("future_ts") or 0.0)
except Exception:
ft = 0.0
# 没有合法 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)
try:
write_state_callback()
except Exception:
pass
return False
# 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退
try:
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 120) or 120
)
except Exception:
join_ahead = 120.0
poll_before = float(getattr(analyser, "poll_before_open_seconds", 10.0) or 10.0)
# 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过
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:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 检查",
now_ts=int(now_ts),
focus_until=int(focus_until) if focus_until > 0 else 0,
target_future_ts=int(ft),
dynamic_ahead=dynamic_ahead,
time_window_start=int(ft - dynamic_ahead),
in_lock_period=bool(focus_until > 0 and now_ts < focus_until),
in_time_window=bool(now_ts >= ft - dynamic_ahead),
)
except Exception:
pass
# 优化锁定期检查:
# 1. 如果没有锁定期(focus_until = 0),直接允许检查时间窗口
# 2. 如果锁定期已过期(now_ts >= focus_until),允许检查时间窗口
# 3. 如果锁定期还没结束,但预约时间已经到了,检查是否是同一个预约
# - 如果是同一个预约,允许回退(通常已经在目标直播间了)
# - 如果不是同一个预约,不允许回退(需要等待当前预约完成)
if focus_until > 0 and now_ts < focus_until:
# 锁定期还没结束,检查是否是同一个预约(允许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
# 是同一个预约,即使锁定期还没结束,如果时间窗口到了,也允许回退
# 但这里通常已经在目标直播间了,所以继续检查时间窗口
try:
analyser._log_kv(
"预约",
"[预约] 锁定期未结束但是同一个预约,继续检查时间窗口",
focus_until=int(focus_until),
target_future_ts=int(ft),
)
except Exception:
pass
if now_ts < ft - dynamic_ahead:
# 还没到窗口
try:
analyser._log_kv(
"预约",
"[预约] 时间窗口未到,跳过回退",
now_ts=int(now_ts),
time_window_start=int(ft - dynamic_ahead),
remain_seconds=int((ft - dynamic_ahead) - now_ts),
)
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
# 先轻微下滑一次,确保在直播列表中 / 或触发系统返回
try:
swipe_down_back_callback()
time.sleep(max(0.1, float(reservation_back_swipe_delay_s or 0.0)))
except Exception:
pass
# 调用上层提供的“按预约信息回退到目标直播间”的回调
ok = False
try:
ok = bool(seek_reservation_room_callback(target))
except Exception:
ok = False
if ok:
# 进入锁定期:在开奖附近一段时间内不再切换直播间
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:
validate_back_to_reservation(analyser, reservations, now_ts=_now_ts())
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] 已回退到目标直播间,等待详情识别与参与",
future_ts=int(ft),
focus_until=int(focus_until_new),
lock_period_seconds=int(focus_until_new - _now_ts()),
remain_seconds_to_open=int(ft - _now_ts()),
)
except Exception:
pass
# 不在这里弹出队列,等待真正"参与完毕"后由上层统一处理
try:
write_state_callback()
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
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 = "",
) -> bool:
"""记录一条高价值福袋预约。
当前实现为"只记录,不立刻改变当前直播间"的版本:
- 构造预约 item 并加入 reservations;
- 写入状态文件;
- 返回 False,表示当前轮不需要立即抢占主流程。
"""
try:
# 计算 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:
pass
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 ""),
}
add_reservation_callback(reservations, item)
sort_reservations_callback()
try:
write_state_callback()
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] record_high_value_reservation:已记录高价值福袋",
value=item["prize_value_yuan"],
future_ts=item["future_ts"],
future_str=future_str,
room_title=room_title[:30] if room_title else "",
queue_len=len(reservations),
)
except Exception:
pass
return False
except Exception:
# 任何异常都不影响主流程,只记录日志
try:
analyser._log_kv(
"预约",
"[预约] record_high_value_reservation 异常,忽略本次预约",
error_type="Exception",
)
except Exception:
pass
return False