将 high_value_enabled and reservations_list 分支整段(含 4 个回调闭包 + 6 步处理流程) 约 99 行抽到 process_high_value_reservation_check helper,内部组合: - try_handle_queue_full_wait - log_skip_preemption_reason - reset_to_first_room_after_all_reservations_done - log_first_reservation_check - process_reservation_multi_room_mode(多间模式) - cleanup_expired_reservations_single_room(单间模式) 返回值约定: - True:触发了早返回(队列满等待 / 所有预约完成重置),调用方应直接 return - False:未触发早返回,调用方继续 douyin_fudai.py: 1319 → 1228 行 (-91) fudai_detail_helpers.py: 2804 → 2890 行 douyin_fudai.py 跌破 1300 行(4121 → 1228,本会话累计削减 2893 行 = -70%) 验证: - pytest 1013 passed - compile OK Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1229 lines
50 KiB
Python
1229 lines
50 KiB
Python
"""
|
||
本地完整版 douyin_fudai(模块化调度器)
|
||
======================================
|
||
|
||
目标:
|
||
- 不再依赖外部 axf 目录;
|
||
- 保持 `from douyin_fudai import fudai_analyse` 导入方式不变;
|
||
- 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any, List, Tuple, Optional, cast
|
||
import os
|
||
import time
|
||
import subprocess
|
||
import logging
|
||
|
||
# Optional heavy dependencies used in image processing; Pylance may not have them in analysis env
|
||
from PIL import Image # type: ignore[import]
|
||
import numpy as np # type: ignore[import]
|
||
|
||
from douyin.core.underlying_operations import underlying_operations
|
||
|
||
from douyin.stage import douyin_stage
|
||
from douyin.detection import douyin_detection
|
||
from douyin.fudai import douyin_fudai_detail
|
||
from douyin.fudai import douyin_fudai_core
|
||
from douyin.core import douyin_flow_control # pylint: disable=redefined-outer-name
|
||
from douyin.other import douyin_live_room
|
||
from douyin.reservation import (
|
||
douyin_reservation_logic,
|
||
) # pylint: disable=redefined-outer-name
|
||
from douyin.utils import douyin_config
|
||
from douyin.logging import douyin_logging_wrapper
|
||
from douyin.handlers import douyin_screenshot_handler
|
||
from douyin.utils import douyin_helpers
|
||
from douyin.handlers import douyin_popup_handler
|
||
from douyin.handlers import douyin_swipe_handler
|
||
from douyin.reservation import douyin_reservation_handler
|
||
from douyin.stage import douyin_stage_handler
|
||
|
||
|
||
class fudai_analyse:
|
||
"""福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。"""
|
||
|
||
# 类常量:魔法数字提取
|
||
MAX_BACK_CLICKS_TO_RECOMMEND = 10 # 返回推荐页面的最大返回键点击次数
|
||
BACK_KEY_CLICK_DELAY = 1.0 # 返回键点击后的延迟(秒)
|
||
PAGE_STABLE_DELAY = 2.0 # 页面稳定等待时间(秒)
|
||
FOLLOW_TAB_CLICK_DELAY = 2.0 # 点击关注标签后的延迟(秒)
|
||
ENTER_LIVE_CLICK_DELAY = 0.6 # 点击进入直播间的延迟(秒)
|
||
ENTER_LIVE_FINAL_DELAY = 2.0 # 进入直播间后的最终等待时间(秒)
|
||
|
||
def __init__(self) -> None:
|
||
# 设备与分辨率
|
||
self.device_id: str = "" # 设备ID,需要在运行时设置
|
||
self.y_pianyi: int = 0
|
||
self.resolution_ratio_x: int = 1080
|
||
self.resolution_ratio_y: int = 2400
|
||
|
||
# 滑动次数计数器(用于滑动次数重置功能)
|
||
self._swipe_times: int = 0
|
||
|
||
# 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部)
|
||
self.operation = underlying_operations()
|
||
self.config_path = "config/config.json"
|
||
|
||
# 日志相关字段:完全独立的日志系统(不依赖原始代码)
|
||
try:
|
||
from datetime import datetime
|
||
|
||
self._run_id = datetime.now().strftime("%Y%m%d%H%M%S")
|
||
except Exception as e:
|
||
logging.debug("生成 run_id 失败,回退到时间戳: %s", e)
|
||
self._run_id = str(int(time.time()))
|
||
self._log_seq = 0
|
||
self._log_kv_orig = None
|
||
# 日志时间戳使用系统时间(不强制替换年份)
|
||
self._use_real_timestamp = False
|
||
# 使用增强版本(通过日志包装器)
|
||
self._log_kv = lambda *args, **kwargs: douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(
|
||
self, *args, **kwargs
|
||
)
|
||
# 用于跟踪上一个日志标签,以便检测阶段变化并添加分隔符
|
||
self._last_log_tag = None
|
||
# 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告
|
||
self._std_logger = None # type: ignore[assignment]
|
||
|
||
# 初始化统一日志系统和traceId
|
||
# 确保日志系统已配置(在实例化之前)
|
||
try:
|
||
from douyin.logging import douyin_logging
|
||
|
||
# 检查 _logging_configured 标志是否存在
|
||
if not getattr(douyin_logging, "_logging_configured", False):
|
||
douyin_logging.configure_logging()
|
||
except Exception as e:
|
||
logging.warning("日志系统初始化失败: %s", e)
|
||
|
||
try:
|
||
from douyin.logging.unified_logger import MDC, get_unified_logger
|
||
|
||
# 为当前实例设置traceId
|
||
MDC.set_trace_id(f"run_{self._run_id}")
|
||
self._std_logger = get_unified_logger("douyin.fudai")
|
||
except ImportError:
|
||
# 如果unified_logger不可用,使用标准logging
|
||
self._std_logger = logging.getLogger("douyin.fudai")
|
||
# 确保根 logger 有 handlers
|
||
root_logger = logging.getLogger()
|
||
if not root_logger.handlers:
|
||
try:
|
||
from douyin.logging import douyin_logging
|
||
|
||
douyin_logging.configure_logging()
|
||
except Exception:
|
||
pass
|
||
self._forced_reservation_detail = None
|
||
self._forced_reservation_fudai_x = None
|
||
|
||
# 进入直播间后诊断与阶段流转所需的一些状态
|
||
self._last_diag_stage: str = "INIT"
|
||
self._last_diag_seen: str = "-"
|
||
self._last_diag_ts: float = 0.0
|
||
|
||
# 30分钟超时相关:记录最后一次成功参与福袋的时间
|
||
self._last_successful_attend_ts: float = 0.0
|
||
self._no_attend_timeout_minutes: float = (
|
||
30.0 # 30分钟没有参与成功则返回推荐页面(可通过config.json配置)
|
||
)
|
||
self._run_start_ts: float = (
|
||
time.time()
|
||
) # 记录运行开始时间,用于从未成功参与时的超时检查
|
||
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
|
||
self._reservations_state_last_write_ts: float = 0.0
|
||
self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标(用于优化搜索)
|
||
|
||
# 与配置相关的核心字段(默认值由 helper 统一初始化,load_config() 会用 config.json 覆盖)
|
||
from douyin.core.fudai_modules.fudai_init_defaults import init_default_config
|
||
|
||
init_default_config(self)
|
||
|
||
# —— 预约运行时状态(单次运行内有效) ——
|
||
# 高价值福袋预约队列
|
||
self.reservations: list[dict[str, Any]] = []
|
||
# 标记是否是第一次运行 run_once_basic(用于刷新预约队列)
|
||
self._first_run_once_basic: bool = True
|
||
# 当前"直播间位置"计数:上划 +1,下滑 -1(仅在本次连续切换过程中有效)
|
||
self.room_pos: int = 0
|
||
# 回退到预约直播间后,在该时间戳前不允许上划离开
|
||
self.reservation_focus_until_ts: float = 0.0
|
||
# 当前是否还有"完成某个预约后的后续动作"待执行
|
||
self.reservation_after_action_pending: bool = False
|
||
# 达到"无福袋切换阈值"后,是否在处理完预约后回到列表第一个直播间
|
||
self.reset_to_list_after_reservations: bool = False
|
||
# 队列满时是否已回退到最早开奖的预约直播间等待
|
||
self.queue_full_waiting_at_earliest: bool = False
|
||
|
||
# 预约队列状态文件(供 WebGUI / 其他进程查看)
|
||
try:
|
||
from douyin.core import path_config as _pc
|
||
self._reservations_state_path: str = _pc.get_reservations_path()
|
||
except Exception:
|
||
self._reservations_state_path = os.path.join(
|
||
os.path.dirname(__file__), "state", "reservations.json"
|
||
)
|
||
|
||
# 运行时直播间标题和位置映射表(用于回退校验)
|
||
# 格式:{room_pos: {"title": str, "title_raw": str, "has_fudai": bool, "fudai_content": str, "fudai_detail": Any}}
|
||
self._room_pos_to_title_map: dict[int, dict[str, Any]] = {}
|
||
# 每次重新运行时丢弃磁盘上旧的映射表,确保只记录本次运行的结果。
|
||
# 同时尝试删除旧的导出文件(JSON/CSV/MD),以避免 GUI 在未写入新数据前显示过期内容。
|
||
try:
|
||
state_dir = os.path.dirname(self._reservations_state_path)
|
||
state_path = os.path.join(state_dir, "room_pos_map.json")
|
||
csv_path = os.path.join(state_dir, "room_pos_map.csv")
|
||
md_path = os.path.join(state_dir, "room_pos_map.md")
|
||
for p in (state_path, csv_path, md_path):
|
||
try:
|
||
if os.path.exists(p):
|
||
os.remove(p)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 已记录统计的福袋跟踪(避免同一个直播间同一个福袋重复记录统计)
|
||
self._recorded_fudai_stats: set[tuple[str, str]] = (
|
||
set()
|
||
) # (room_title, fudai_content)
|
||
|
||
# 运行时状态标志(避免在外部定义属性的警告)
|
||
self.needswitch: bool | None = (
|
||
None # 是否允许切换直播间,将从配置文件加载,默认 True
|
||
)
|
||
self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果
|
||
self._current_attending_reservation_fudai: bool = (
|
||
False # 当前正在参与的是否为预约福袋
|
||
)
|
||
self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志
|
||
self._just_switched_room: bool = False # 是否刚刚切换了直播间
|
||
|
||
# 高价值房间重访相关状态
|
||
self._last_high_value_revisit_ts: float = (
|
||
time.time()
|
||
) # 最后一次重访时间戳,初始化为当前时间避免启动后立即重访
|
||
self._current_run_revisit_count: int = 0 # 本次运行的重访次数
|
||
self._current_run_high_value_rooms: list[dict[str, Any]] = (
|
||
[]
|
||
) # 本次运行发现的高价值房间
|
||
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = (
|
||
None # 上次读取的福袋详情
|
||
)
|
||
self._current_fudai_future_ts: float = 0.0 # 当前福袋的开奖时间戳
|
||
self._current_fudai_content: str = "" # 当前福袋的内容标识
|
||
self._fudai_detail_first_read: bool = False # 是否第一次读取福袋详情
|
||
self._fudai_detail_consecutive_failures: int = 0 # 连续失败次数
|
||
self._detail_closed_by_attend: bool = False # 详情页是否由参与操作关闭
|
||
self._lottery_result_expected_ts: float = 0.0 # 开奖结果预期时间戳
|
||
self._lottery_wait_start_ts: float = 0.0 # 开始等待开奖的时间戳
|
||
|
||
# 初次加载配置
|
||
self.load_config()
|
||
|
||
# ===== 兼容原始脚本的一些简单封装方法 =====
|
||
def _find_room_pos_by_title(
|
||
self, target_title: str, target_title_raw: str = ""
|
||
) -> int | None:
|
||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||
|
||
返回:
|
||
如果找到匹配的位置,返回位置值;否则返回 None
|
||
"""
|
||
return douyin_reservation_handler.ReservationHandler.find_room_pos_by_title(
|
||
self, target_title, target_title_raw
|
||
)
|
||
|
||
def _record_room_title_and_pos(self) -> None:
|
||
"""记录当前直播间的标题和位置到运行时映射表。
|
||
|
||
用于预约回退校验时验证位置信息。
|
||
"""
|
||
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
|
||
|
||
def click(self, x: int, y: int) -> None:
|
||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||
douyin_helpers.HelperFunctions.click(self, x, y)
|
||
|
||
def swipe(
|
||
self, start_x: int, start_y: int, end_x: int, end_y: int, duration_ms: int = 300
|
||
) -> None:
|
||
"""兼容原版 fudai_analyse.swipe:转发到底层 operation.swipe。
|
||
|
||
参数使用像素坐标,duration_ms 为滑动持续时间(毫秒)。
|
||
"""
|
||
try:
|
||
# 首选底层 operation 的 swipe 实现
|
||
try:
|
||
self.operation.swipe(
|
||
self.device_id, start_x, start_y, end_x, end_y, duration_ms
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退:尝试使用 douyin.handlers.douyin_swipe_ops 的 adb 命令直接发送
|
||
try:
|
||
from douyin.handlers import douyin_swipe_ops
|
||
|
||
ok = douyin_swipe_ops._adb_swipe_direct(
|
||
getattr(self, "device_id", ""),
|
||
start_x,
|
||
start_y,
|
||
end_x,
|
||
end_y,
|
||
duration_ms,
|
||
self.operation,
|
||
)
|
||
if ok:
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 最后兜底:记录滑动失败
|
||
try:
|
||
self._log_kv(
|
||
"滑动",
|
||
"swipe 失败 - 无可用实现",
|
||
start_x=start_x,
|
||
start_y=start_y,
|
||
end_x=end_x,
|
||
end_y=end_y,
|
||
duration_ms=duration_ms,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
try:
|
||
self._log_kv(
|
||
"滑动",
|
||
"swipe 异常",
|
||
start_x=start_x,
|
||
start_y=start_y,
|
||
end_x=end_x,
|
||
end_y=end_y,
|
||
duration_ms=duration_ms,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
def load_config(self) -> None:
|
||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||
douyin_config.ConfigManager.load_config_from_file(self) # type: ignore[attr-defined]
|
||
|
||
# ===== 推荐页养号封装 =====
|
||
def _yanghao_recommend_flow(self, seconds: int) -> None:
|
||
"""封装调用 douyin.other.douyin_yanghao.yanghao_recommend_flow。"""
|
||
try:
|
||
# Respect global enable switch so callers that invoke this
|
||
# method directly cannot bypass the main on/off setting.
|
||
if not bool(getattr(self, "yanghao_enabled", True)):
|
||
try:
|
||
self._log_kv(
|
||
"养号", "_yanghao_recommend_flow skipped - yanghao_enabled=0"
|
||
)
|
||
except Exception:
|
||
logging.info("[养号] _yanghao_recommend_flow skipped - yanghao_enabled=0")
|
||
return
|
||
from douyin.other import douyin_yanghao
|
||
|
||
douyin_yanghao.yanghao_recommend_flow(self, int(seconds or 0))
|
||
except Exception:
|
||
# 兜底:若模块不可用则快速返回
|
||
try:
|
||
self._log_kv(
|
||
"养号", "_yanghao_recommend_flow 未能执行 - 模块缺失或异常"
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
def _yanghao_wait(self, seconds: int) -> None:
|
||
"""封装调用 douyin.other.douyin_yanghao.yanghao_wait(可由主流程在等待阶段调用)。"""
|
||
try:
|
||
from douyin.other import douyin_yanghao
|
||
|
||
douyin_yanghao.yanghao_wait(self, int(seconds or 0))
|
||
except Exception:
|
||
try:
|
||
self._log_kv("养号", "_yanghao_wait 未能执行 - 模块缺失或异常")
|
||
except Exception:
|
||
pass
|
||
|
||
def _yanghao_get_recommend_seconds(self) -> int:
|
||
"""返回配置或默认的推荐页停留时长(秒)。"""
|
||
try:
|
||
from douyin.other import douyin_yanghao
|
||
|
||
return int(douyin_yanghao.yanghao_get_recommend_seconds(self))
|
||
except Exception:
|
||
try:
|
||
return int(
|
||
getattr(self, "yanghao_recommend_duration_seconds", 60) or 60
|
||
)
|
||
except Exception:
|
||
return 60
|
||
|
||
def _maybe_run_yanghao_during_run(self) -> None:
|
||
"""If configured, trigger recommendation-page yanghao at configured intervals.
|
||
|
||
This respects `yanghao_enabled` and will not trigger during lottery-result waiting.
|
||
"""
|
||
try:
|
||
interval = int(getattr(self, "yanghao_recommend_interval_seconds", 0) or 0)
|
||
if interval <= 0:
|
||
return
|
||
|
||
# 不在等待开奖期间触发养号
|
||
if getattr(self, "_waiting_for_lottery_result", False):
|
||
return
|
||
|
||
# 如果正在处理预约或有未完成的预约队列,则跳过触发
|
||
try:
|
||
if getattr(self, "_current_attending_reservation_fudai", False):
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
reservations = getattr(self, "reservations", None)
|
||
if reservations and len(reservations) > 0:
|
||
# 有预约队列,等待预约完成
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
reservation_focus_until = float(
|
||
getattr(self, "reservation_focus_until_ts", 0.0) or 0.0
|
||
)
|
||
if reservation_focus_until > time.time():
|
||
# 当前处于预约焦点期,跳过养号
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
now = time.time()
|
||
last = float(getattr(self, "_last_yanghao_ts", 0.0) or 0.0)
|
||
if now - last < interval:
|
||
return
|
||
|
||
try:
|
||
self._log_kv("养号", "定时触发推荐页养号", interval_seconds=interval)
|
||
except Exception:
|
||
pass
|
||
|
||
self._last_yanghao_ts = now
|
||
seconds = int(getattr(self, "yanghao_recommend_duration_seconds", 60) or 60)
|
||
try:
|
||
self._yanghao_wait(seconds)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# ========== 兼容旧入口:主循环 ==========
|
||
def fudai_choujiang(
|
||
self,
|
||
device_id: str = "",
|
||
y_pianyi: int = 0,
|
||
needswitch: bool = False,
|
||
wait_minutes: int = 15,
|
||
) -> None:
|
||
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
|
||
from douyin.core.fudai_modules.fudai_choujiang_helpers import (
|
||
cleanup_stale_screenshot,
|
||
resolve_device_resolution,
|
||
write_actions_log,
|
||
)
|
||
|
||
cleanup_stale_screenshot(self)
|
||
|
||
# DEBUG: 记录函数入口
|
||
try:
|
||
self._log_kv(
|
||
"DEBUG",
|
||
"entered fudai_choujiang",
|
||
device_id=device_id,
|
||
wait_minutes=wait_minutes,
|
||
)
|
||
except Exception:
|
||
logging.warning(
|
||
f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}"
|
||
)
|
||
self.device_id = device_id or self.device_id
|
||
self.y_pianyi = int(y_pianyi or 0)
|
||
# 保存是否允许切换直播间的配置,供后续所有逻辑统一使用
|
||
try:
|
||
self.needswitch = bool(needswitch)
|
||
except Exception:
|
||
# 兜底:若赋值失败,则保持原有行为(默认允许切换)
|
||
self.needswitch = True
|
||
|
||
resolve_device_resolution(self)
|
||
|
||
write_actions_log("程序开始运行", __file__)
|
||
# 捕获并记录未被捕获的异常以便排查立即退出问题
|
||
try:
|
||
# 原有后续逻辑继续...
|
||
pass
|
||
except Exception as top_exc:
|
||
try:
|
||
self._log_kv(
|
||
"ERROR", "fudai_choujiang top-level exception", error=str(top_exc)
|
||
)
|
||
except Exception:
|
||
import traceback
|
||
|
||
traceback.print_exc()
|
||
raise
|
||
|
||
# 暂时禁用流式截图,使用直接截图模式
|
||
self._log_kv("截图服务", "暂时禁用流式截图,使用直接截图模式")
|
||
|
||
self._log_kv(
|
||
"启动",
|
||
"fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)",
|
||
分辨率=f"{self.resolution_ratio_x}x{self.resolution_ratio_y}",
|
||
needswitch=int(bool(self.needswitch)),
|
||
wait_minutes=int(wait_minutes),
|
||
)
|
||
|
||
# 基础循环:在限定时间内反复执行单轮逻辑
|
||
# 如果 wait_minutes <= 0,则无限循环运行
|
||
if wait_minutes and wait_minutes > 0:
|
||
end_ts = time.time() + int(wait_minutes) * 60
|
||
while time.time() < end_ts:
|
||
try:
|
||
self.run_once_basic()
|
||
except Exception as exc:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv(
|
||
"循环",
|
||
"run_once_basic 异常",
|
||
error=str(exc),
|
||
error_type=type(exc).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 异常后稍作延迟再继续
|
||
try:
|
||
self.operation.delay(2.0)
|
||
except Exception:
|
||
time.sleep(2.0)
|
||
continue
|
||
|
||
# 为避免过于频繁截图,增加少量间隔
|
||
try:
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
time.sleep(1.0)
|
||
|
||
# 记录运行结束(定时模式)
|
||
write_actions_log("程序运行结束(时间到)", __file__)
|
||
|
||
else:
|
||
# 无限循环模式(wait_minutes <= 0)
|
||
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
|
||
while True:
|
||
try:
|
||
self.run_once_basic()
|
||
except KeyboardInterrupt:
|
||
# 允许 Ctrl+C 退出
|
||
self._log_kv("循环", "收到中断信号,退出循环")
|
||
write_actions_log("程序运行结束(中断退出)", __file__)
|
||
raise
|
||
except Exception as exc:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv(
|
||
"循环",
|
||
"run_once_basic 异常",
|
||
error=str(exc),
|
||
error_type=type(exc).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 异常后稍作延迟再继续
|
||
try:
|
||
self.operation.delay(2.0)
|
||
except Exception:
|
||
time.sleep(2.0)
|
||
continue
|
||
|
||
# 为避免过于频繁截图,增加少量间隔
|
||
try:
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
time.sleep(1.0)
|
||
|
||
# ========== 阶段诊断 ==========
|
||
def _diagnose_stage_from_current_screen(
|
||
self, force_screenshot: bool = False, trigger_reason: str = "unknown"
|
||
) -> Tuple[str, str]:
|
||
"""封装到子模块的阶段诊断入口。
|
||
|
||
参数:
|
||
force_screenshot: 是否强制重新截图(默认False,优先使用缓存)
|
||
"""
|
||
return douyin_stage_handler.StageHandler.diagnose_stage_from_current_screen(
|
||
self, force_screenshot=force_screenshot, trigger_reason=trigger_reason
|
||
)
|
||
|
||
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
|
||
def cut_pic(
|
||
self,
|
||
x_top: int = 1,
|
||
y_top: int = 1,
|
||
x_bottom: int = 2,
|
||
y_bottom: int = 2,
|
||
target: str = "",
|
||
cut_pic_name: str = "",
|
||
y_pianyi: int = 0,
|
||
) -> None:
|
||
"""裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。"""
|
||
douyin_screenshot_handler.ScreenshotHandler.cut_pic(
|
||
self, x_top, y_top, x_bottom, y_bottom, target, cut_pic_name, y_pianyi
|
||
)
|
||
|
||
def _read_pixel_stage_state(
|
||
self, return_details: bool = False
|
||
) -> dict | tuple[dict, dict]:
|
||
"""读取像素阶段状态(用于阶段诊断)。
|
||
|
||
参数:
|
||
return_details: 是否返回每个检测步骤的详细信息(包括分数)
|
||
|
||
返回:
|
||
dict: 检测结果(return_details=False时)
|
||
tuple[dict, dict]: (检测结果, 详细信息)(return_details=True时)
|
||
"""
|
||
return douyin_helpers.HelperFunctions.read_pixel_stage_state(
|
||
self, return_details
|
||
)
|
||
|
||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
|
||
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
|
||
|
||
返回 (scaled_x, scaled_y)
|
||
"""
|
||
return douyin_screenshot_handler.ScreenshotHandler.scale_from_base(
|
||
self, base_x, base_y
|
||
)
|
||
|
||
def _save_step_screenshot(self, label: str) -> None:
|
||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
|
||
douyin_screenshot_handler.ScreenshotHandler.save_step_screenshot(self, label)
|
||
|
||
def _capture_roi_screenshot(
|
||
self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None
|
||
) -> str:
|
||
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。"""
|
||
from douyin.core.fudai_modules.fudai_image_helpers import capture_roi_screenshot
|
||
|
||
return capture_roi_screenshot(self, label, sx, sy, size, screenshot_path)
|
||
|
||
def _match_icon_template(
|
||
self, roi_path: str, template_path: str, threshold: float | None = None
|
||
) -> Tuple[bool, float]:
|
||
"""对比 ROI 与模板,返回 (detected: bool, score: float)。"""
|
||
from douyin.core.fudai_modules.fudai_image_helpers import match_icon_template
|
||
|
||
return match_icon_template(self, roi_path, template_path, threshold)
|
||
|
||
def _check_in_live_room_by_icon(
|
||
self,
|
||
) -> Tuple[bool, float]: # pyright: ignore[reportAttributeAccessIssue]
|
||
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
|
||
|
||
返回:
|
||
(detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。
|
||
"""
|
||
return douyin_stage_handler.StageHandler.check_in_live_room_by_icon(self)
|
||
|
||
def check_in_fudai_detail(self) -> bool:
|
||
"""判断当前是否处于福袋详情页:委托给 douyin_detection.check_in_fudai_detail。"""
|
||
try:
|
||
return bool(douyin_detection.check_in_fudai_detail(self))
|
||
except Exception as exc:
|
||
try:
|
||
self._log_kv("检测", "check_in_fudai_detail 异常", error=str(exc))
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
def _enhanced_log_kv(self, *args, **fields):
|
||
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging"""
|
||
douyin_logging_wrapper.LoggingWrapper.enhanced_log_kv(self, *args, **fields)
|
||
|
||
# 供像素/检测模块记录子步骤耗时使用
|
||
def _log_step_time(
|
||
self, step_name: str, start_time: float, extra_info: dict | None = None
|
||
) -> None:
|
||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。"""
|
||
douyin_logging_wrapper.LoggingWrapper.log_step_time(
|
||
self, step_name, start_time, extra_info
|
||
)
|
||
|
||
# ========== 弹窗 / 人机校验 ==========
|
||
def _check_coupon_popup(self) -> bool:
|
||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的"看门狗"中使用)。"""
|
||
return douyin_popup_handler.PopupHandler.check_coupon_popup(self)
|
||
|
||
def _check_shopping_redpacket_popup(self) -> bool:
|
||
"""购物红包中央弹窗。"""
|
||
return douyin_popup_handler.PopupHandler.check_shopping_redpacket_popup(self)
|
||
|
||
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
|
||
def run_once_basic(self) -> None: # type: ignore[complexity]
|
||
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。
|
||
|
||
注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。
|
||
"""
|
||
# use module-level `douyin_reservation_logic` imported at top
|
||
|
||
start_time = time.time()
|
||
self._log_kv("流程", "run_once_basic开始", start_timestamp=start_time)
|
||
# 在主循环开始时检查是否需要定时触发推荐页养号
|
||
try:
|
||
self._maybe_run_yanghao_during_run()
|
||
except Exception:
|
||
pass
|
||
|
||
# 尝试记录当前直播间的标题与位置(如果刚切换则跳过重复记录)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
record_room_title_if_not_just_switched,
|
||
)
|
||
|
||
record_room_title_if_not_just_switched(self)
|
||
|
||
# 直接参与标志已移除,相关旧逻辑已清理,继续按正常流程执行
|
||
# 0. 如果正在等待开奖:不在此期间检查并抢占其他预约,避免放弃当前正在参加的直播间
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_wait_for_lottery_result,
|
||
)
|
||
|
||
if try_wait_for_lottery_result(self, start_time):
|
||
return
|
||
|
||
# 0. 检查30分钟超时:如果30分钟没有成功参与福袋,则返回推荐页面并重新进入直播间
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_no_attend_timeout,
|
||
)
|
||
|
||
if try_no_attend_timeout(self, start_time):
|
||
return
|
||
|
||
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
|
||
try:
|
||
reservation_check_start = time.time()
|
||
self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start)
|
||
|
||
# 初始化预约队列(第一次运行时清空 + 写状态文件)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
initialize_reservations_queue,
|
||
)
|
||
|
||
initialize_reservations_queue(self)
|
||
|
||
high_value_enabled = getattr(self, "high_value_fudai_enabled", False)
|
||
reservations_list = getattr(self, "reservations", None)
|
||
reservations_count = len(reservations_list) if reservations_list else 0
|
||
|
||
# 添加详细的调试日志,确认预约回退逻辑的触发条件
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
log_reservation_check_status,
|
||
)
|
||
|
||
log_reservation_check_status(self, high_value_enabled)
|
||
|
||
if high_value_enabled and reservations_list:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
process_high_value_reservation_check,
|
||
)
|
||
|
||
if process_high_value_reservation_check(self, start_time):
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 检查是否刚刚记录了预约,如果是,强制切换直播间,避免在同一直播间循环
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_just_recorded_reservation_switch,
|
||
)
|
||
|
||
if try_just_recorded_reservation_switch(self, start_time):
|
||
return
|
||
|
||
# 预约检查耗时记录
|
||
reservation_elapsed = time.time() - reservation_check_start
|
||
self._log_kv("预约", f"预约检查完成,耗时: {reservation_elapsed:.3f}s")
|
||
|
||
# 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_skip_stage_diagnosis,
|
||
)
|
||
|
||
if try_skip_stage_diagnosis(self, start_time):
|
||
return
|
||
|
||
# 1. 截图 + 阶段诊断
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
take_screenshot_and_diagnose,
|
||
)
|
||
|
||
result = take_screenshot_and_diagnose(self, start_time)
|
||
if result is None:
|
||
return
|
||
stage, seen = result
|
||
|
||
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_desktop_recovery,
|
||
)
|
||
|
||
if try_desktop_recovery(self):
|
||
return
|
||
|
||
# 2. 诊断后分支(弹窗检测已合并到阶段诊断中)
|
||
|
||
# 2.0. 高价值房间重访检查(在处理其他状态之前)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_high_value_room_revisit,
|
||
)
|
||
|
||
if try_high_value_room_revisit(self, start_time):
|
||
return
|
||
|
||
# 处理弹窗阶段
|
||
if stage == "COUPON_POPUP":
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_coupon_popup,
|
||
)
|
||
|
||
handle_coupon_popup(self, start_time)
|
||
return
|
||
elif stage == "SHOPPING_REDPACKET_POPUP":
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_shopping_redpacket_popup,
|
||
)
|
||
|
||
handle_shopping_redpacket_popup(self, start_time)
|
||
return
|
||
elif stage == "FANSCLUB_JOIN":
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_fansclub_join,
|
||
)
|
||
|
||
handle_fansclub_join(self, start_time)
|
||
return
|
||
elif stage == "FUDai_DETAIL":
|
||
# 已经在详情页:直接按正常详情流程处理(已移除预约回退直接参与标志)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到福袋详情页,按正常详情流程处理",
|
||
stage=stage,
|
||
)
|
||
except Exception:
|
||
pass
|
||
self._handle_in_fudai_detail()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理福袋详情)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
|
||
# 在直播间:按正常直播间流程处理(已移除预约回退直接参与标志)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到直播间,按正常直播间流程处理",
|
||
stage=stage,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_in_live_room_stage,
|
||
)
|
||
|
||
handle_in_live_room_stage(self, start_time)
|
||
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
|
||
# 处理推荐/关注/直播列表页:回到直播间或切换
|
||
if stage == "RECOMMEND_PAGE":
|
||
# 识别到推荐页面:直接点击进入直播页,然后点击进入直播间
|
||
self._log_kv(
|
||
"流程",
|
||
"检测到推荐页面,点击进入直播页并进入直播间",
|
||
stage=stage,
|
||
seen=seen,
|
||
)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_recommend_page,
|
||
)
|
||
|
||
handle_recommend_page(self)
|
||
else:
|
||
# 其他列表页:使用原有逻辑
|
||
douyin_live_room.reflash_zhibo(self)
|
||
elif stage == "FUDai_RESULT":
|
||
# 抽奖结果弹窗:处理开奖结果(使用OCR识别,不使用阶段诊断)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_lottery_result_stage,
|
||
)
|
||
|
||
handle_lottery_result_stage(self, start_time)
|
||
return
|
||
elif stage in ("LIVE_CLOSED",):
|
||
# 直播结束:下滑/切下一个
|
||
self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
|
||
self.swipe_up_to_next_live()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(直播结束)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
else:
|
||
# 未识别出特殊阶段:尽量保持原地,交给上层循环
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"阶段",
|
||
"未匹配到特定阶段",
|
||
stage=stage,
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
|
||
def _check_lottery_result_by_ocr(self) -> Optional[str]:
|
||
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。"""
|
||
return douyin_helpers.HelperFunctions.check_lottery_result_by_ocr(self)
|
||
|
||
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
|
||
"""根据OCR识别结果处理开奖结果。
|
||
|
||
参数:
|
||
result_type: "我知道了" 或 "立即领取奖品"
|
||
"""
|
||
douyin_helpers.HelperFunctions.handle_lottery_result_by_ocr(self, result_type)
|
||
|
||
def _shot_and_diagnose(
|
||
self, tag: str, msg: str, device_id: str, diagnose: bool = True
|
||
) -> None:
|
||
"""截图并执行阶段诊断(兼容旧版调用方式)。
|
||
|
||
Args:
|
||
tag: 日志标签
|
||
msg: 日志消息
|
||
device_id: 设备ID
|
||
diagnose: 是否执行阶段诊断(默认True)
|
||
"""
|
||
douyin_helpers.HelperFunctions.shot_and_diagnose(
|
||
self, tag, msg, device_id, diagnose
|
||
)
|
||
|
||
# ========== 基础动作封装 ==========
|
||
def swipe_up_to_next_live(self) -> None:
|
||
"""上滑切换直播间(简单版封装)。
|
||
|
||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||
则不允许上划离开预约直播间,直接返回。
|
||
"""
|
||
douyin_swipe_handler.SwipeHandler.swipe_up_to_next_live(self)
|
||
|
||
def _return_to_recommend_and_reenter_live(self) -> None:
|
||
"""返回推荐页面并重新进入直播间。
|
||
|
||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||
"""
|
||
douyin_swipe_handler.SwipeHandler.return_to_recommend_and_reenter_live(self)
|
||
|
||
def swipe_down_back_from_live(self) -> None:
|
||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
|
||
douyin_swipe_handler.SwipeHandler.swipe_down_back_from_live(self)
|
||
|
||
def _maybe_reset_after_swipes(self) -> int:
|
||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||
|
||
返回:
|
||
重置后的滑动次数(通常为0)
|
||
"""
|
||
return douyin_swipe_handler.SwipeHandler.maybe_reset_after_swipes(self)
|
||
|
||
def _seek_reservation_room(
|
||
self, item: dict[str, Any], operation_type: str = "预约"
|
||
) -> bool:
|
||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||
|
||
说明:
|
||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||
"""
|
||
return douyin_reservation_handler.ReservationHandler.seek_reservation_room(
|
||
self, item, operation_type=operation_type
|
||
)
|
||
|
||
# ========== 福袋相关 ==========
|
||
def _handle_reservation_direct_attend(self) -> None:
|
||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。"""
|
||
douyin_reservation_handler.ReservationHandler.handle_reservation_direct_attend(
|
||
self
|
||
)
|
||
|
||
# pylint: disable=too-many-nested-blocks
|
||
def _handle_in_fudai_detail(self) -> None:
|
||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||
start_time = time.time()
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
log_handle_in_fudai_detail_entry,
|
||
)
|
||
|
||
log_handle_in_fudai_detail_entry(self)
|
||
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
|
||
|
||
# 检查连续参与失败次数,避免卡死
|
||
consecutive_failures = getattr(self, "_consecutive_attend_failures", 0)
|
||
max_consecutive_failures = 5 # 最多允许5次连续失败
|
||
if consecutive_failures >= max_consecutive_failures:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_consecutive_failures_exceeded,
|
||
)
|
||
|
||
handle_consecutive_failures_exceeded(self, max_consecutive_failures)
|
||
return
|
||
|
||
# 步骤1:检查是否是第二次打开福袋详情
|
||
step1_start = time.time()
|
||
is_second_open = getattr(self, "_fudai_detail_first_read", False)
|
||
# 如果是第二次打开,直接点击参与,不需要验证,使用第一次的倒计时
|
||
is_second_open = getattr(self, "_fudai_detail_first_read", False)
|
||
if is_second_open:
|
||
# 第二次打开:直接点击参与,不进行验证,使用第一次的倒计时
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 获取第一次读取的详情数据
|
||
detail = getattr(self, "_last_fudai_detail_tuple", None)
|
||
if detail is None or not isinstance(detail, tuple) or len(detail) < 6:
|
||
# 如果没有保存的详情数据,需要重新读取(兜底逻辑)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
reread_fudai_detail_fallback,
|
||
)
|
||
|
||
detail = reread_fudai_detail_fallback(self)
|
||
else:
|
||
# 使用第一次保存的详情数据:直接参与(不进行验证)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_second_open_direct_attend,
|
||
)
|
||
|
||
if handle_second_open_direct_attend(self, start_time, step1_start):
|
||
return
|
||
# 异常时继续正常流程
|
||
else:
|
||
# 步骤2:读取福袋详情
|
||
step2_start = time.time()
|
||
# 第一次打开:完整读取详情(包括内容、倒计时、价值)
|
||
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
|
||
self,
|
||
fudai_x=0,
|
||
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
|
||
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
|
||
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
|
||
)
|
||
|
||
# 在第一次打开时立即进行筛选检查,如果不符合要求则直接跳过
|
||
# 注意:这里只检查筛选条件,不执行参与操作
|
||
if detail and isinstance(detail, tuple) and len(detail) >= 6:
|
||
# 先进行数据验证
|
||
is_valid = True
|
||
try:
|
||
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(
|
||
detail, self
|
||
)
|
||
if not is_valid:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_first_open_validation_failed,
|
||
)
|
||
|
||
handle_first_open_validation_failed(
|
||
self, start_time, step2_start, reason
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 步骤3:筛选检查
|
||
step3_start = time.time()
|
||
# 执行筛选检查(不执行参与操作,只检查是否符合筛选条件)
|
||
try:
|
||
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(
|
||
self, detail
|
||
)
|
||
if skip:
|
||
# 检查是否是高价值福袋,如果是则记录预约或立即参与
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
check_high_value_skip_decision,
|
||
)
|
||
|
||
decision = check_high_value_skip_decision(
|
||
self, detail, skip_reason, start_time
|
||
)
|
||
if decision == "recorded":
|
||
return
|
||
elif decision == "attend":
|
||
# 不关闭详情,继续走立即参与逻辑(保存详情数据,标记为已读取)
|
||
skip = False
|
||
|
||
# 如果不是高价值福袋,或者不是倒计时原因,筛选不通过,直接跳过
|
||
if skip:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_filter_skip,
|
||
)
|
||
|
||
handle_filter_skip(self, skip_reason, start_time)
|
||
return
|
||
except Exception as e:
|
||
# 筛选检查异常,记录日志但继续流程
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:筛选检查异常",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 筛选通过,保存详情数据并标记为已读取
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
save_first_open_detail,
|
||
)
|
||
|
||
save_first_open_detail(self, detail)
|
||
else:
|
||
# 详情数据无效,不保存,不标记为已读取
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:第一次打开时详情数据无效,跳过",
|
||
)
|
||
except Exception:
|
||
pass
|
||
return
|
||
|
||
# 检查是否是优惠券弹窗、观看任务或识别错误:根据 _last_fudai_detail_status 分发到对应处理
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
dispatch_last_fudai_detail_status,
|
||
)
|
||
|
||
if dispatch_last_fudai_detail_status(self, start_time):
|
||
return
|
||
|
||
# 如果成功读取,重置失败计数
|
||
try:
|
||
self._fudai_detail_consecutive_failures = 0
|
||
except Exception:
|
||
pass
|
||
|
||
# 额外验证 + 兜底检查(验证失败或无效详情则早返回)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
validate_detail_or_skip,
|
||
)
|
||
|
||
if validate_detail_or_skip(self, detail, start_time):
|
||
return
|
||
|
||
# 记录参与前的状态
|
||
attend_before_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
|
||
|
||
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
extract_future_ts_from_detail,
|
||
)
|
||
|
||
extract_future_ts_from_detail(self, detail)
|
||
|
||
# 重置详情关闭标志
|
||
try:
|
||
self._detail_closed_by_attend = False
|
||
except Exception:
|
||
pass
|
||
|
||
# 步骤3结束计时
|
||
step3_elapsed = (time.time() - step3_start) * 1000
|
||
self._log_kv("详情处理", "步骤3[筛选检查]-完成", 总耗时毫秒=step3_elapsed)
|
||
|
||
# 步骤4:参与决策
|
||
step4_start = time.time()
|
||
# 执行参与决策
|
||
if detail is None:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_detail_none_in_step4,
|
||
)
|
||
|
||
handle_detail_none_in_step4(self, start_time)
|
||
return
|
||
join_result = douyin_fudai_core.basic_join_decision(
|
||
self, detail, (skip, skip_reason)
|
||
)
|
||
|
||
# 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功
|
||
if join_result:
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_attend_success_post_processing,
|
||
)
|
||
|
||
handle_attend_success_post_processing(
|
||
self, detail, start_time, step4_start, attend_before_ts
|
||
)
|
||
|
||
def _handle_live_room_has_or_not_fudai(self) -> None:
|
||
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"."""
|
||
start_time = time.time()
|
||
# 设置当前参与的福袋类型为高价值福袋(非预约)
|
||
self._current_attending_reservation_fudai = False
|
||
|
||
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
try_skip_to_in_fudai_detail_when_verified,
|
||
)
|
||
|
||
if try_skip_to_in_fudai_detail_when_verified(self, start_time):
|
||
return
|
||
|
||
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
should_skip_fudai_search_in_lock_period,
|
||
)
|
||
|
||
if should_skip_fudai_search_in_lock_period(self, start_time):
|
||
return
|
||
|
||
room_pos_ref: List[int] = [0]
|
||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||
if not opened:
|
||
# 无福袋,交给 flow_control 的"无福袋处理"逻辑
|
||
from douyin.core.fudai_modules.fudai_detail_helpers import (
|
||
handle_no_fudai_in_live_room,
|
||
)
|
||
|
||
handle_no_fudai_in_live_room(self, room_pos_ref, start_time)
|
||
return
|
||
|
||
# 成功打开详情:调用同一套详情处理逻辑
|
||
self._handle_in_fudai_detail()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_live_room_has_or_not_fudai完成(成功打开详情)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|