- Removed excessive blank lines from various markdown and Python files to improve readability and maintainability. - Ensured consistent formatting across documentation and code files, contributing to overall project clarity. - Enhanced logging mechanisms for better consistency and debugging support.
5309 lines
243 KiB
Python
5309 lines
243 KiB
Python
from __future__ import annotations
|
||
|
||
"""
|
||
本地完整版 douyin_fudai(模块化调度器)
|
||
======================================
|
||
|
||
目标:
|
||
- 不再依赖外部 axf 目录;
|
||
- 保持 `from douyin_fudai import fudai_analyse` 导入方式不变;
|
||
- 将核心逻辑拆分到各子模块,仅在此做"组装 + 调度"。
|
||
"""
|
||
|
||
from typing import Any, List, Tuple, Optional
|
||
import os
|
||
import time
|
||
import sys
|
||
import logging
|
||
|
||
from Underlying_Operations import underlying_operations
|
||
|
||
import douyin_stage
|
||
import douyin_detection
|
||
import douyin_fudai_detail
|
||
import douyin_fudai_core
|
||
import douyin_flow_control
|
||
import douyin_live_room
|
||
import douyin_lottery
|
||
import douyin_popups
|
||
import douyin_robot
|
||
import douyin_swipe_ops
|
||
import douyin_text_utils
|
||
import douyin_utils
|
||
import douyin_yanghao
|
||
import douyin_pixel
|
||
import douyin_reservation_logic
|
||
import douyin_reservation_verify
|
||
import douyin_high_value_room
|
||
|
||
|
||
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.json"
|
||
|
||
# 日志相关字段:完全独立的日志系统(不依赖原始代码)
|
||
try:
|
||
from datetime import datetime
|
||
|
||
self._run_id = datetime.now().strftime("%Y%m%d%H%M%S")
|
||
except Exception:
|
||
self._run_id = str(int(time.time()))
|
||
self._log_seq = 0
|
||
self._log_kv_orig = None
|
||
# 使用增强版本
|
||
self._log_kv = self._enhanced_log_kv
|
||
# 用于跟踪上一个日志标签,以便检测阶段变化并添加分隔符
|
||
self._last_log_tag = None
|
||
# 预定义可在运行中动态创建的属性,避免 access-before-definition / attribute-defined-outside-init 警告
|
||
self._std_logger = None # type: ignore[assignment]
|
||
|
||
# 初始化统一日志系统和traceId
|
||
# 确保日志系统已配置(在实例化之前)
|
||
try:
|
||
import douyin_logging
|
||
|
||
# 检查 _logging_configured 标志是否存在
|
||
if not getattr(douyin_logging, "_logging_configured", False):
|
||
douyin_logging.configure_logging()
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
from 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:
|
||
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()
|
||
) # 记录运行开始时间,用于从未成功参与时的超时检查
|
||
self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标(用于优化搜索)
|
||
|
||
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
|
||
self.contains_not_want: list[str] = []
|
||
self.contains_want: list[str] = []
|
||
self.min_prize_value_yuan: float = 0.0
|
||
self.min_participants: int = 0
|
||
self.max_participants: int = 0
|
||
self.skip_if_countdown_gt_seconds: int = 900
|
||
self.skip_if_countdown_lt_seconds: int = 0 # 倒计时小于该秒数则不参与
|
||
self.no_fudai_watchdog_enabled: bool = False
|
||
# 福袋图标检测节流相关默认值
|
||
# 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整
|
||
# 注意:已改为使用时间限制(fudai_icon_max_wait_seconds),不再使用尝试次数限制
|
||
self.fudai_icon_retry_delay_seconds: float = 0.6
|
||
self.fudai_icon_max_wait_seconds: float = 5.0
|
||
# 点击福袋图标后等待详情页加载的时间(秒)
|
||
self.fudai_click_wait_seconds: float = 2.0
|
||
# 切换直播间后等待阶段诊断的时间(秒)
|
||
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
|
||
# fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用
|
||
self.fudai_find_max_attempts: int = 10
|
||
|
||
# 优化查找器相关配置
|
||
self.fudai_finder_optimized_enabled: bool = True # 默认启用优化查找器
|
||
self.fudai_click_verify_enabled: bool = True # 点击后验证是否成功打开详情页
|
||
self.fudai_find_max_retries: int = 3 # 最大重试次数
|
||
self.screenshot_diagnose_min_interval_seconds: float = 8.0
|
||
# 开奖页面检测红色占比阈值(0.0~1.0)
|
||
self.lucky_draw_red_ratio_threshold: float = 0.9
|
||
# 优惠券模板匹配阈值(0.0~1.0,默认0.75)
|
||
self.coupon_template_match_threshold: float = 0.75
|
||
# 参与按钮红色占比阈值(0.0~1.0,默认0.25)
|
||
self.attend_button_red_ratio_threshold: float = 0.25
|
||
# 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)
|
||
self.fansclub_join_red_ratio_threshold: float = 0.25
|
||
|
||
# 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8)
|
||
self.live_room_match_threshold: float = 0.8
|
||
# 福袋模板匹配开关(默认关闭)
|
||
self.fudai_template_match_enabled: bool = False
|
||
# 福袋模板匹配阈值(0.0~1.0,默认0.7)
|
||
self.fudai_template_match_threshold: float = 0.7
|
||
|
||
# —— 高价值福袋 / 预约相关配置(从原 fudai1 精简迁移) ——
|
||
# 是否启用“高价值福袋预约参与”
|
||
self.high_value_fudai_enabled: bool = False
|
||
# 高价值阈值(元)
|
||
self.high_value_fudai_threshold_yuan: float = 500.0
|
||
# 提前参与秒数:开奖前 N 秒回到该直播间并参与
|
||
self.high_value_fudai_join_ahead_seconds: int = 120
|
||
# 从当前位置最多回滑多少次以回到预约直播间
|
||
self.high_value_fudai_max_swipe_back: int = 35
|
||
# 同时记录的最大预约数量
|
||
self.high_value_fudai_max_reservations: int = 3
|
||
# 完成某个预约福袋后的动作:stay=停留当前直播间;continue=继续执行抢福袋
|
||
self.high_value_fudai_after_action: str = "continue"
|
||
self.high_value_fudai_after_stay_seconds: int = 120
|
||
|
||
# 高价值直播间"回访"相关(当前仅保留配置,不在本地版强制启用复杂逻辑)
|
||
self.high_value_room_revisit_enabled: bool = False
|
||
self.high_value_room_revisit_only_current_run: bool = False
|
||
|
||
# 粉丝团相关配置
|
||
self.auto_join_fansclub: bool = False # 是否自动加入粉丝团
|
||
self.fansclub_fail_action: str = (
|
||
"stay" # 粉丝团失败策略:stay=停留,switch=切换
|
||
)
|
||
|
||
# 预约回退相关
|
||
self.reservation_back_verify_enabled: bool = True # 默认启用回退校验
|
||
# 未做回退校验时的快速回滑延迟(秒)
|
||
self.reservation_back_swipe_delay: float = 0.6
|
||
# 预约抢占最小价值:低于该价值的预约不会抢占当前任务(元)
|
||
self.reservation_preempt_min_value_yuan: float = 0.0
|
||
# 在预计开奖前多少秒开始积极轮询结果
|
||
self.poll_before_open_seconds: int = 10
|
||
|
||
# 滑动次数重置相关
|
||
self.reset_after_swipes_enabled: bool = False # 由 Web/CLI 显式开关
|
||
self.reset_after_swipes: int = 10 # 达到阈值次数后回退,需启用开关后生效
|
||
|
||
# 意外返回桌面自救相关
|
||
self.desktop_icon_x: int = 153 # 桌面图标 X 坐标(默认值)
|
||
self.desktop_icon_y: int = 260 # 桌面图标 Y 坐标(默认值)
|
||
self.yanghao_fallback_live_x: int = 540 # 养号备用直播按钮 X 坐标
|
||
self.yanghao_fallback_live_y: int = 2000 # 养号备用直播按钮 Y 坐标
|
||
self.yanghao_fallback_enter_live_x: int = 540 # 养号备用进入直播间 X 坐标
|
||
self.yanghao_fallback_enter_live_y: int = 1200 # 养号备用进入直播间 Y 坐标
|
||
|
||
# —— 预约运行时状态(单次运行内有效) ——
|
||
# 高价值福袋预约队列
|
||
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 / 其他进程查看)
|
||
self._reservations_state_path: str = os.path.join(
|
||
os.path.dirname(__file__), "state", "reservations.json"
|
||
)
|
||
|
||
# 运行时直播间标题和位置映射表(用于回退校验)
|
||
# 格式:{room_pos: (room_title, room_title_raw)}
|
||
self._room_pos_to_title_map: dict[int, tuple[str, str]] = {}
|
||
|
||
# 初次加载配置
|
||
self.load_config()
|
||
|
||
# ===== 兼容原始脚本的一些简单封装方法 =====
|
||
def _find_room_pos_by_title(self, target_title: str, target_title_raw: str = "") -> int | None:
|
||
"""根据直播间标题在运行时映射表中查找对应的位置。
|
||
|
||
返回:
|
||
如果找到匹配的位置,返回位置值;否则返回 None
|
||
"""
|
||
try:
|
||
if not target_title and not target_title_raw:
|
||
return None
|
||
|
||
room_pos_map = getattr(self, "_room_pos_to_title_map", {})
|
||
if not room_pos_map:
|
||
return None
|
||
|
||
# 规范化目标标题
|
||
try:
|
||
import douyin_high_value_room
|
||
if hasattr(douyin_high_value_room, '_normalize_room_title'):
|
||
target_norm = douyin_high_value_room._normalize_room_title(target_title) # type: ignore[attr-defined]
|
||
else:
|
||
target_norm = target_title.strip()
|
||
except Exception:
|
||
target_norm = target_title.strip()
|
||
|
||
# 遍历映射表查找匹配的标题
|
||
best_match_pos = None
|
||
best_match_score = 0.0
|
||
|
||
for pos, (recorded_title, recorded_title_raw) in room_pos_map.items():
|
||
if not recorded_title and not recorded_title_raw:
|
||
continue
|
||
|
||
# 规范化记录的标题
|
||
try:
|
||
import douyin_high_value_room
|
||
if hasattr(douyin_high_value_room, '_normalize_room_title'):
|
||
recorded_norm = douyin_high_value_room._normalize_room_title(recorded_title) # type: ignore[attr-defined]
|
||
else:
|
||
recorded_norm = recorded_title.strip()
|
||
except Exception:
|
||
recorded_norm = recorded_title.strip()
|
||
|
||
# 计算匹配度
|
||
match_score = 0.0
|
||
if target_norm and recorded_norm:
|
||
# 完全匹配
|
||
if target_norm == recorded_norm:
|
||
match_score = 1.0
|
||
# 子串匹配
|
||
elif target_norm in recorded_norm or recorded_norm in target_norm:
|
||
match_score = 0.8
|
||
# 使用相似度
|
||
else:
|
||
try:
|
||
import difflib
|
||
match_score = difflib.SequenceMatcher(None, target_norm, recorded_norm).ratio()
|
||
except Exception:
|
||
match_score = 0.0
|
||
|
||
# 如果匹配度足够高,记录最佳匹配
|
||
if match_score > best_match_score and match_score >= 0.6:
|
||
best_match_score = match_score
|
||
best_match_pos = pos
|
||
|
||
if best_match_pos is not None:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _find_room_pos_by_title:在映射表中找到匹配位置",
|
||
target_title=target_title[:50] if target_title else "",
|
||
found_pos=best_match_pos,
|
||
match_score=round(best_match_score, 3),
|
||
recorded_title=room_pos_map[best_match_pos][0][:50] if room_pos_map[best_match_pos][0] else "",
|
||
)
|
||
except Exception:
|
||
pass
|
||
return best_match_pos
|
||
|
||
return None
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _find_room_pos_by_title:查找时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
return None
|
||
|
||
def _record_room_title_and_pos(self) -> None:
|
||
"""记录当前直播间的标题和位置到运行时映射表。
|
||
|
||
用于预约回退校验时验证位置信息。
|
||
"""
|
||
try:
|
||
room_pos = int(getattr(self, "room_pos", 0) or 0)
|
||
|
||
# 读取当前直播间标题
|
||
try:
|
||
import douyin_fudai_detail as dfd_module
|
||
y_pianyi_val = int(getattr(self, "y_pianyi", 0) or 0)
|
||
room_title, room_title_raw = dfd_module.read_live_room_title_core(
|
||
self, y_pianyi_val
|
||
)
|
||
|
||
# 更新 analyser 的属性
|
||
try:
|
||
self.current_room_title = room_title
|
||
self.current_room_title_raw = room_title_raw
|
||
except Exception:
|
||
pass
|
||
|
||
# 记录到映射表
|
||
if room_pos not in self._room_pos_to_title_map:
|
||
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 记录直播间标题和位置到运行时映射表",
|
||
room_pos=room_pos,
|
||
room_title=room_title[:50] if room_title else "",
|
||
room_title_raw=room_title_raw[:50] if room_title_raw else "",
|
||
map_size=len(self._room_pos_to_title_map),
|
||
)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 如果已存在,更新标题(可能标题有变化)
|
||
old_title, old_title_raw = self._room_pos_to_title_map[room_pos]
|
||
if old_title != room_title or old_title_raw != room_title_raw:
|
||
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 更新直播间标题和位置到运行时映射表",
|
||
room_pos=room_pos,
|
||
old_room_title=old_title[:50] if old_title else "",
|
||
new_room_title=room_title[:50] if room_title else "",
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
# 如果读取标题失败,尝试使用缓存的标题
|
||
try:
|
||
room_title = str(getattr(self, "current_room_title", "") or "")
|
||
room_title_raw = str(getattr(self, "current_room_title_raw", "") or "")
|
||
if room_title or room_title_raw:
|
||
self._room_pos_to_title_map[room_pos] = (room_title, room_title_raw)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 使用缓存标题记录直播间位置到运行时映射表",
|
||
room_pos=room_pos,
|
||
room_title=room_title[:50] if room_title else "",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
def click(self, x: int, y: int) -> None:
|
||
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
|
||
start_time = time.time()
|
||
try:
|
||
self.operation.click(self.device_id, int(x), int(y))
|
||
elapsed = time.time() - start_time
|
||
if elapsed > 0.1: # 只记录耗时较长的点击操作
|
||
self._log_kv(
|
||
"操作",
|
||
"点击操作",
|
||
x=int(x),
|
||
y=int(y),
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
def load_config(self) -> None:
|
||
"""从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。"""
|
||
import json
|
||
import os
|
||
|
||
path = getattr(self, "config_path", "config.json")
|
||
try:
|
||
if not os.path.exists(path):
|
||
return
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
config = json.load(f)
|
||
except Exception:
|
||
return
|
||
|
||
try:
|
||
self.contains_not_want = list(config.get("contains_not_want", []) or [])
|
||
except Exception:
|
||
self.contains_not_want = []
|
||
try:
|
||
self.contains_want = list(config.get("contains_want", []) or [])
|
||
except Exception:
|
||
self.contains_want = []
|
||
|
||
def _float(name: str, default: float) -> float:
|
||
try:
|
||
return float(config.get(name, default) or default)
|
||
except Exception:
|
||
return default
|
||
|
||
def _int(name: str, default: int) -> int:
|
||
try:
|
||
return int(config.get(name, default) or default)
|
||
except Exception:
|
||
return default
|
||
|
||
self.min_prize_value_yuan = _float(
|
||
"min_prize_value_yuan", self.min_prize_value_yuan
|
||
)
|
||
self.min_participants = _int("min_participants", self.min_participants)
|
||
self.max_participants = _int("max_participants", self.max_participants)
|
||
self.skip_if_countdown_gt_seconds = _int(
|
||
"skip_if_countdown_gt_seconds", self.skip_if_countdown_gt_seconds
|
||
)
|
||
self.skip_if_countdown_lt_seconds = _int(
|
||
"skip_if_countdown_lt_seconds", self.skip_if_countdown_lt_seconds
|
||
)
|
||
|
||
try:
|
||
self.no_fudai_watchdog_enabled = bool(
|
||
config.get("no_fudai_watchdog_enabled", self.no_fudai_watchdog_enabled)
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
self.fudai_icon_retry_delay_seconds = _float(
|
||
"fudai_icon_retry_delay_seconds",
|
||
self.fudai_icon_retry_delay_seconds,
|
||
)
|
||
self.fudai_icon_max_wait_seconds = _float(
|
||
"fudai_icon_max_wait_seconds",
|
||
self.fudai_icon_max_wait_seconds,
|
||
)
|
||
self.fudai_click_wait_seconds = _float(
|
||
"fudai_click_wait_seconds",
|
||
self.fudai_click_wait_seconds,
|
||
)
|
||
self.switch_room_wait_after_stage_diag_seconds = _float(
|
||
"switch_room_wait_after_stage_diag_seconds",
|
||
self.switch_room_wait_after_stage_diag_seconds,
|
||
)
|
||
self.fudai_find_max_attempts = _int(
|
||
"fudai_find_max_attempts",
|
||
self.fudai_find_max_attempts,
|
||
)
|
||
self.screenshot_diagnose_min_interval_seconds = _float(
|
||
"screenshot_diagnose_min_interval_seconds",
|
||
self.screenshot_diagnose_min_interval_seconds,
|
||
)
|
||
self.lucky_draw_red_ratio_threshold = _float(
|
||
"lucky_draw_red_ratio_threshold",
|
||
self.lucky_draw_red_ratio_threshold,
|
||
)
|
||
if self.lucky_draw_red_ratio_threshold < 0.0:
|
||
self.lucky_draw_red_ratio_threshold = 0.0
|
||
if self.lucky_draw_red_ratio_threshold > 1.0:
|
||
self.lucky_draw_red_ratio_threshold = 1.0
|
||
self.coupon_template_match_threshold = _float(
|
||
"coupon_template_match_threshold",
|
||
self.coupon_template_match_threshold,
|
||
)
|
||
if self.coupon_template_match_threshold < 0.0:
|
||
self.coupon_template_match_threshold = 0.0
|
||
if self.coupon_template_match_threshold > 1.0:
|
||
self.coupon_template_match_threshold = 1.0
|
||
self.attend_button_red_ratio_threshold = _float(
|
||
"attend_button_red_ratio_threshold",
|
||
self.attend_button_red_ratio_threshold,
|
||
)
|
||
if self.attend_button_red_ratio_threshold < 0.0:
|
||
self.attend_button_red_ratio_threshold = 0.0
|
||
if self.attend_button_red_ratio_threshold > 1.0:
|
||
self.attend_button_red_ratio_threshold = 1.0
|
||
self.fansclub_join_red_ratio_threshold = _float(
|
||
"fansclub_join_red_ratio_threshold",
|
||
self.fansclub_join_red_ratio_threshold,
|
||
)
|
||
if self.fansclub_join_red_ratio_threshold < 0.0:
|
||
self.fansclub_join_red_ratio_threshold = 0.0
|
||
if self.fansclub_join_red_ratio_threshold > 1.0:
|
||
self.fansclub_join_red_ratio_threshold = 1.0
|
||
if self.lucky_draw_red_ratio_threshold > 1.0:
|
||
self.lucky_draw_red_ratio_threshold = 1.0
|
||
self.live_room_match_threshold = _float(
|
||
"live_room_match_threshold",
|
||
self.live_room_match_threshold,
|
||
)
|
||
# 确保阈值在合理范围内
|
||
if self.live_room_match_threshold < 0.0:
|
||
self.live_room_match_threshold = 0.0
|
||
if self.live_room_match_threshold > 1.0:
|
||
self.live_room_match_threshold = 1.0
|
||
|
||
try:
|
||
self.fudai_template_match_enabled = bool(
|
||
config.get(
|
||
"fudai_template_match_enabled", self.fudai_template_match_enabled
|
||
)
|
||
)
|
||
except Exception:
|
||
pass
|
||
self.fudai_template_match_threshold = _float(
|
||
"fudai_template_match_threshold",
|
||
self.fudai_template_match_threshold,
|
||
)
|
||
# 确保阈值在合理范围内
|
||
if self.fudai_template_match_threshold < 0.0:
|
||
self.fudai_template_match_threshold = 0.0
|
||
if self.fudai_template_match_threshold > 1.0:
|
||
self.fudai_template_match_threshold = 1.0
|
||
|
||
# 福袋详情页模板匹配阈值(独立配置)
|
||
self.fudai_detail_template_threshold = _float(
|
||
"fudai_detail_template_threshold",
|
||
0.7, # 默认值
|
||
)
|
||
# 确保阈值在合理范围内
|
||
if self.fudai_detail_template_threshold < 0.0:
|
||
self.fudai_detail_template_threshold = 0.0
|
||
if self.fudai_detail_template_threshold > 1.0:
|
||
self.fudai_detail_template_threshold = 1.0
|
||
|
||
# 粉丝团相关配置
|
||
try:
|
||
self.auto_join_fansclub = bool(
|
||
config.get("auto_join_fansclub", self.auto_join_fansclub)
|
||
)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
self.fansclub_fail_action = str(
|
||
config.get("fansclub_fail_action", self.fansclub_fail_action) or "stay"
|
||
).lower()
|
||
except Exception:
|
||
pass
|
||
|
||
# —— 高价值福袋 / 预约配置加载 ——
|
||
try:
|
||
self.high_value_fudai_enabled = bool(
|
||
config.get("high_value_fudai_enabled", self.high_value_fudai_enabled)
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
self.high_value_fudai_threshold_yuan = _float(
|
||
"high_value_fudai_threshold_yuan",
|
||
self.high_value_fudai_threshold_yuan,
|
||
)
|
||
self.high_value_fudai_join_ahead_seconds = _int(
|
||
"high_value_fudai_join_ahead_seconds",
|
||
self.high_value_fudai_join_ahead_seconds,
|
||
)
|
||
self.high_value_fudai_max_swipe_back = _int(
|
||
"high_value_fudai_max_swipe_back",
|
||
self.high_value_fudai_max_swipe_back,
|
||
)
|
||
self.high_value_fudai_max_reservations = _int(
|
||
"high_value_fudai_max_reservations",
|
||
self.high_value_fudai_max_reservations,
|
||
)
|
||
# 合理范围约束
|
||
if self.high_value_fudai_max_reservations < 1:
|
||
self.high_value_fudai_max_reservations = 1
|
||
if self.high_value_fudai_max_reservations > 50:
|
||
self.high_value_fudai_max_reservations = 50
|
||
|
||
try:
|
||
self.high_value_fudai_after_action = (
|
||
str(
|
||
config.get(
|
||
"high_value_fudai_after_action",
|
||
self.high_value_fudai_after_action,
|
||
)
|
||
or self.high_value_fudai_after_action
|
||
)
|
||
.strip()
|
||
.lower()
|
||
)
|
||
except Exception:
|
||
pass
|
||
if self.high_value_fudai_after_action not in ("stay", "continue"):
|
||
self.high_value_fudai_after_action = "continue"
|
||
|
||
self.high_value_fudai_after_stay_seconds = _int(
|
||
"high_value_fudai_after_stay_seconds",
|
||
self.high_value_fudai_after_stay_seconds,
|
||
)
|
||
if self.high_value_fudai_after_stay_seconds < 0:
|
||
self.high_value_fudai_after_stay_seconds = 0
|
||
if self.high_value_fudai_after_stay_seconds > 3600:
|
||
self.high_value_fudai_after_stay_seconds = 3600
|
||
|
||
# 高价值直播间回访相关(当前本地版暂不强制使用,仅保留配置)
|
||
try:
|
||
self.high_value_room_revisit_enabled = bool(
|
||
config.get(
|
||
"high_value_room_revisit_enabled",
|
||
self.high_value_room_revisit_enabled,
|
||
)
|
||
)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
self.high_value_room_revisit_only_current_run = bool(
|
||
config.get(
|
||
"high_value_room_revisit_only_current_run",
|
||
self.high_value_room_revisit_only_current_run,
|
||
)
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 是否允许切换直播间配置(needswitch)
|
||
# 注意:如果 self.needswitch 已经通过命令行参数设置,则优先使用命令行参数
|
||
# 只有在 self.needswitch 未设置或为默认值时,才从 config.json 读取
|
||
try:
|
||
# 检查是否已经通过命令行参数设置了 needswitch
|
||
if not hasattr(self, "needswitch") or self.needswitch is None:
|
||
# 如果未设置,从 config.json 读取
|
||
config_needswitch = bool(config.get("needswitch", True))
|
||
self.needswitch = config_needswitch
|
||
try:
|
||
self._log_kv(
|
||
"配置",
|
||
"[配置] load_config:从 config.json 读取 needswitch",
|
||
needswitch=config_needswitch,
|
||
)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 如果已经设置(通过命令行参数),保持命令行参数的值不变(不覆盖)
|
||
try:
|
||
self._log_kv(
|
||
"配置",
|
||
"[配置] load_config:保持命令行参数 needswitch(不覆盖)",
|
||
needswitch=self.needswitch,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
# 如果读取失败,使用默认值 True(允许切换)
|
||
if not hasattr(self, "needswitch"):
|
||
self.needswitch = True
|
||
try:
|
||
self._log_kv(
|
||
"配置",
|
||
"[配置] load_config:needswitch 读取失败,使用默认值 True",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 滑动次数重置配置
|
||
try:
|
||
self.reset_after_swipes_enabled = bool(
|
||
config.get("reset_after_swipes_enabled", False)
|
||
)
|
||
except Exception:
|
||
self.reset_after_swipes_enabled = False
|
||
try:
|
||
raw_reset_swipes = config.get("reset_after_swipes", 10)
|
||
self.reset_after_swipes = int(
|
||
10 if raw_reset_swipes is None else raw_reset_swipes
|
||
)
|
||
except Exception:
|
||
self.reset_after_swipes = 10
|
||
if self.reset_after_swipes < 1:
|
||
self.reset_after_swipes = 1
|
||
|
||
# 意外返回桌面自救配置
|
||
try:
|
||
self.desktop_icon_x = int(config.get("desktop_icon_x", self.desktop_icon_x))
|
||
self.desktop_icon_y = int(config.get("desktop_icon_y", self.desktop_icon_y))
|
||
self.yanghao_fallback_live_x = int(
|
||
config.get("yanghao_fallback_live_x", self.yanghao_fallback_live_x)
|
||
)
|
||
self.yanghao_fallback_live_y = int(
|
||
config.get("yanghao_fallback_live_y", self.yanghao_fallback_live_y)
|
||
)
|
||
self.yanghao_fallback_enter_live_x = int(
|
||
config.get(
|
||
"yanghao_fallback_enter_live_x", self.yanghao_fallback_enter_live_x
|
||
)
|
||
)
|
||
self.yanghao_fallback_enter_live_y = int(
|
||
config.get(
|
||
"yanghao_fallback_enter_live_y", self.yanghao_fallback_enter_live_y
|
||
)
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 预约回退与抢占策略
|
||
try:
|
||
self.reservation_back_verify_enabled = bool(
|
||
config.get(
|
||
"reservation_back_verify_enabled",
|
||
self.reservation_back_verify_enabled,
|
||
)
|
||
)
|
||
except Exception:
|
||
self.reservation_back_verify_enabled = True # 默认启用
|
||
|
||
self.reservation_back_swipe_delay = _float(
|
||
"reservation_back_swipe_delay",
|
||
self.reservation_back_swipe_delay,
|
||
)
|
||
if self.reservation_back_swipe_delay < 0.0:
|
||
self.reservation_back_swipe_delay = 0.0
|
||
|
||
self.reservation_preempt_min_value_yuan = _float(
|
||
"reservation_preempt_min_value",
|
||
self.reservation_preempt_min_value_yuan,
|
||
)
|
||
if self.reservation_preempt_min_value_yuan < 0.0:
|
||
self.reservation_preempt_min_value_yuan = 0.0
|
||
|
||
self.poll_before_open_seconds = _int(
|
||
"poll_before_open_seconds",
|
||
self.poll_before_open_seconds,
|
||
)
|
||
if self.poll_before_open_seconds < 0:
|
||
self.poll_before_open_seconds = 0
|
||
|
||
# 30分钟超时保护配置
|
||
self._no_attend_timeout_minutes = _float(
|
||
"no_attend_timeout_minutes",
|
||
self._no_attend_timeout_minutes,
|
||
)
|
||
# 合理范围约束:0表示禁用,最大24小时(1440分钟)
|
||
if self._no_attend_timeout_minutes < 0:
|
||
self._no_attend_timeout_minutes = 0
|
||
if self._no_attend_timeout_minutes > 1440:
|
||
self._no_attend_timeout_minutes = 1440
|
||
|
||
# ========== 兼容旧入口:主循环 ==========
|
||
def fudai_choujiang(
|
||
self,
|
||
device_id: str = "",
|
||
y_pianyi: int = 0,
|
||
needswitch: bool = False,
|
||
wait_minutes: int = 15,
|
||
) -> None:
|
||
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
|
||
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
|
||
try:
|
||
rx, ry = self.operation.get_device_resolution(self.device_id)
|
||
self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int(
|
||
ry or 2400
|
||
)
|
||
except Exception:
|
||
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
|
||
|
||
# 记录运行开始
|
||
from datetime import datetime
|
||
|
||
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
try:
|
||
import os
|
||
|
||
actions_log_path = os.path.join(
|
||
os.path.dirname(__file__), "logs", "actions.log"
|
||
)
|
||
log_dir = os.path.dirname(actions_log_path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
with open(
|
||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||
) as f:
|
||
f.write("=" * 80 + "\n")
|
||
f.write(f"{start_time} - [GUI] - [运行] 程序开始运行\n")
|
||
f.flush()
|
||
except Exception:
|
||
pass
|
||
|
||
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 e:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv(
|
||
"循环",
|
||
"run_once_basic 异常",
|
||
error=str(e),
|
||
error_type=type(e).__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)
|
||
|
||
# 记录运行结束(定时模式)
|
||
try:
|
||
from datetime import datetime
|
||
|
||
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
import os
|
||
|
||
actions_log_path = os.path.join(
|
||
os.path.dirname(__file__), "logs", "actions.log"
|
||
)
|
||
log_dir = os.path.dirname(actions_log_path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
with open(
|
||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||
) as f:
|
||
f.write("=" * 80 + "\n")
|
||
f.write(f"{end_time} - [GUI] - [运行] 程序运行结束(时间到)\n")
|
||
f.flush()
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 无限循环模式(wait_minutes <= 0)
|
||
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
|
||
while True:
|
||
try:
|
||
self.run_once_basic()
|
||
except KeyboardInterrupt:
|
||
# 允许 Ctrl+C 退出
|
||
self._log_kv("循环", "收到中断信号,退出循环")
|
||
# 记录运行结束
|
||
try:
|
||
from datetime import datetime
|
||
|
||
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
import os
|
||
|
||
actions_log_path = os.path.join(
|
||
os.path.dirname(__file__), "logs", "actions.log"
|
||
)
|
||
log_dir = os.path.dirname(actions_log_path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
with open(
|
||
actions_log_path,
|
||
"a",
|
||
encoding="utf-8-sig",
|
||
errors="replace",
|
||
) as f:
|
||
f.write("=" * 80 + "\n")
|
||
f.write(
|
||
f"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n"
|
||
)
|
||
f.flush()
|
||
except Exception:
|
||
pass
|
||
raise
|
||
except Exception as e:
|
||
# 捕获异常,记录日志,但继续循环
|
||
try:
|
||
self._log_kv(
|
||
"循环",
|
||
"run_once_basic 异常",
|
||
error=str(e),
|
||
error_type=type(e).__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) -> Tuple[str, str]:
|
||
"""封装到子模块的阶段诊断入口。"""
|
||
result = douyin_stage.diagnose_stage_from_current_screen(self)
|
||
if result is None:
|
||
return ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
|
||
return result
|
||
|
||
# ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ==========
|
||
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 基准)。"""
|
||
try:
|
||
x1 = x_top * self.resolution_ratio_x // 1080
|
||
y1 = y_top * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||
x2 = x_bottom * self.resolution_ratio_x // 1080
|
||
y2 = y_bottom * self.resolution_ratio_y // 2400 + int(y_pianyi or 0)
|
||
self.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"截图",
|
||
"cut_pic 失败",
|
||
error=str(e),
|
||
x_top=x_top,
|
||
y_top=y_top,
|
||
x_bottom=x_bottom,
|
||
y_bottom=y_bottom,
|
||
y_pianyi=y_pianyi,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
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时)
|
||
"""
|
||
import os
|
||
|
||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||
# 获取分辨率比例和y偏移参数
|
||
resolution_ratio_x = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||
resolution_ratio_y = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||
y_pianyi = int(getattr(self, "y_pianyi", 0) or 0)
|
||
lucky_threshold = float(
|
||
getattr(self, "lucky_draw_red_ratio_threshold", 0.9) or 0.9
|
||
)
|
||
# 获取模板匹配阈值(优先使用福袋详情页专用阈值)
|
||
fudai_template_threshold = float(
|
||
getattr(self, "fudai_detail_template_threshold", None)
|
||
or getattr(self, "fudai_template_match_threshold", 0.7)
|
||
or 0.7
|
||
)
|
||
if fudai_template_threshold < 0.0:
|
||
fudai_template_threshold = 0.0
|
||
if fudai_template_threshold > 1.0:
|
||
fudai_template_threshold = 1.0
|
||
return douyin_pixel.read_pixel_stage_state_from_screenshot(
|
||
pic_path,
|
||
resolution_ratio_x,
|
||
resolution_ratio_y,
|
||
y_pianyi,
|
||
lucky_threshold,
|
||
fudai_template_threshold,
|
||
return_details=return_details,
|
||
analyser=self,
|
||
)
|
||
|
||
def _scale_from_base(self, base_x: int, base_y: int) -> tuple[int, int]:
|
||
"""将以 1080x2400 为基准的坐标缩放到当前设备分辨率并应用 y 偏移。
|
||
|
||
返回 (scaled_x, scaled_y)
|
||
"""
|
||
try:
|
||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||
y_off = int(getattr(self, "y_pianyi", 0) or 0)
|
||
sx = int(base_x * rx // 1080)
|
||
sy = int(base_y * ry // 2400) + y_off
|
||
return sx, sy
|
||
except Exception:
|
||
try:
|
||
return int(base_x), int(base_y)
|
||
except Exception:
|
||
return 0, 0
|
||
|
||
def _save_step_screenshot(self, label: str) -> None:
|
||
"""保存当前截图到 `pic/steps/` 目录,文件名包含 run_id 与序号,供调试与回放使用。"""
|
||
try:
|
||
import os
|
||
import shutil
|
||
|
||
base_dir = os.path.dirname(__file__)
|
||
pic_dir = os.path.join(base_dir, "pic")
|
||
# 确保有最新截图
|
||
try:
|
||
self.operation.get_screenshot(self.device_id)
|
||
except Exception:
|
||
pass
|
||
src = os.path.join(pic_dir, "screenshot.png")
|
||
if not os.path.exists(src):
|
||
return
|
||
steps_dir = os.path.join(pic_dir, "steps")
|
||
os.makedirs(steps_dir, exist_ok=True)
|
||
fname = f"{getattr(self,'_run_id','run')}_{getattr(self,'_log_seq',0):04d}_{label}.png"
|
||
dst = os.path.join(steps_dir, fname)
|
||
try:
|
||
shutil.copy(src, dst)
|
||
except Exception:
|
||
# 最后降级为重命名保存
|
||
try:
|
||
shutil.copy(src, dst)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
def _check_in_live_room_by_icon(
|
||
self,
|
||
) -> Tuple[bool, float]: # pyright: ignore[reportAttributeAccessIssue]
|
||
"""通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。
|
||
|
||
返回:
|
||
(detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。
|
||
"""
|
||
# pyright: ignore[reportAttributeAccessIssue]
|
||
# 为了兼容没有 cv2/numpy 的环境,这里做降级处理
|
||
try:
|
||
import cv2 # type: ignore[import-untyped, attr-defined]
|
||
import numpy as np # type: ignore
|
||
import os
|
||
|
||
# 抑制OpenCV的文件读取警告(多种方法组合)
|
||
# 方法1:设置环境变量
|
||
os.environ["OPENCV_LOG_LEVEL"] = "ERROR"
|
||
# 方法2:使用cv2.setLogLevel(OpenCV 4.x+)
|
||
try:
|
||
cv2.setLogLevel(0) # type: ignore[attr-defined] # 0 = SILENT
|
||
except (AttributeError, Exception):
|
||
# 如果setLogLevel不存在(旧版本OpenCV),尝试其他方法
|
||
try:
|
||
# OpenCV 3.x 使用 cv2.utils.logging.setLogLevel
|
||
if hasattr(cv2, "utils") and hasattr(cv2.utils, "logging"):
|
||
cv2.utils.logging.setLogLevel( # type: ignore[attr-defined]
|
||
cv2.utils.logging.LOG_LEVEL_SILENT # type: ignore[attr-defined]
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 方法3:通过logging抑制Python层的警告
|
||
try:
|
||
import logging
|
||
|
||
logging.getLogger("cv2").setLevel(logging.ERROR)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断",
|
||
"_check_in_live_room_by_icon 缺少opencv/numpy,跳过图形识别",
|
||
)
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
base_dir = os.path.dirname(__file__)
|
||
pic_dir = os.path.join(base_dir, "pic")
|
||
assets_dir = os.path.join(base_dir, "assets")
|
||
screenshot_path = os.path.join(pic_dir, "screenshot.png")
|
||
|
||
# 确保有最新截图
|
||
try:
|
||
self.operation.get_screenshot(self.device_id)
|
||
except Exception:
|
||
# 若截图失败则尝试继续使用旧图
|
||
pass
|
||
|
||
if not os.path.exists(screenshot_path):
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断",
|
||
"_check_in_live_room_by_icon 截图不存在",
|
||
path=screenshot_path,
|
||
)
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
try:
|
||
img = cv2.imread( # type: ignore[attr-defined]
|
||
screenshot_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||
)
|
||
if img is None:
|
||
raise RuntimeError("cv2.imread 返回 None")
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断", "_check_in_live_room_by_icon 读取截图失败", error=str(e)
|
||
)
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
# 获取可配置的匹配阈值(用于模板匹配,像素检测使用不同的阈值)
|
||
# 注意:live_room_match_threshold 主要用于像素检测,模板匹配可以使用稍低的阈值
|
||
threshold = float(getattr(self, "live_room_match_threshold", 0.8) or 0.8)
|
||
# 模板匹配可以使用稍低的阈值(像素检测优先,模板匹配作为补充)
|
||
template_threshold = threshold * 0.9 # 模板匹配阈值设为像素检测阈值的90%
|
||
# 确保阈值在合理范围内
|
||
if threshold < 0.0:
|
||
threshold = 0.0
|
||
if threshold > 1.0:
|
||
threshold = 1.0
|
||
if template_threshold < 0.0:
|
||
template_threshold = 0.0
|
||
if template_threshold > 1.0:
|
||
template_threshold = 1.0
|
||
|
||
# 第一步:裁剪右上角图标区域,保存到 pic/ocr/ 目录
|
||
ih, iw = img.shape[:2]
|
||
roi_x1 = max(0, int(iw * 0.60)) # 60%宽度开始
|
||
roi_y1 = 0
|
||
roi_x2 = iw # 100%宽度
|
||
roi_y2 = min(ih, int(ih * 0.40)) # 40%高度
|
||
roi = img[roi_y1:roi_y2, roi_x1:roi_x2] # type: ignore[index]
|
||
|
||
if roi.size == 0:
|
||
try:
|
||
self._log_kv("阶段诊断", "_check_in_live_room_by_icon ROI区域为空")
|
||
except Exception:
|
||
pass
|
||
return False, 0.0
|
||
|
||
# 保存裁剪的ROI区域到 pic/ocr/ 目录
|
||
ocr_dir = os.path.join(pic_dir, "ocr")
|
||
os.makedirs(ocr_dir, exist_ok=True)
|
||
x_roi_path = os.path.join(ocr_dir, "xx.png")
|
||
xin_roi_path = os.path.join(ocr_dir, "xxin.png")
|
||
|
||
try:
|
||
# 保存ROI区域(两个文件保存相同的内容,因为x和xin图标在同一区域)
|
||
cv2.imwrite(x_roi_path, roi) # type: ignore[attr-defined]
|
||
cv2.imwrite(xin_roi_path, roi) # type: ignore[attr-defined]
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断", "_check_in_live_room_by_icon 保存ROI失败", error=str(e)
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 第二步:使用 assets/ 目录下的模板去匹配 pic/ocr/ 目录下的裁剪图片
|
||
# assets/x.png 和 assets/xin.png 是模板
|
||
# pic/ocr/xx.png 和 pic/ocr/xxin.png 是要匹配的图片
|
||
template_roi_pairs = [
|
||
(os.path.join(assets_dir, "x.png"), x_roi_path, "x"),
|
||
(os.path.join(assets_dir, "xin.png"), xin_roi_path, "xin"),
|
||
]
|
||
|
||
best_score = 0.0
|
||
best_name = ""
|
||
detected = False
|
||
|
||
for template_path, roi_path, icon_name in template_roi_pairs:
|
||
try:
|
||
# 检查模板文件是否存在
|
||
if not os.path.exists(template_path) or not os.path.isfile(
|
||
template_path
|
||
):
|
||
continue
|
||
try:
|
||
if os.path.getsize(template_path) == 0:
|
||
continue
|
||
except (OSError, IOError):
|
||
continue
|
||
|
||
# 检查ROI文件是否存在(应该刚保存的)
|
||
if not os.path.exists(roi_path) or not os.path.isfile(roi_path):
|
||
continue
|
||
|
||
# 读取模板和ROI图片
|
||
try:
|
||
tpl = cv2.imread( # type: ignore[attr-defined]
|
||
template_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||
)
|
||
roi_img = cv2.imread( # type: ignore[attr-defined]
|
||
roi_path, cv2.IMREAD_GRAYSCALE # type: ignore[attr-defined]
|
||
)
|
||
except Exception:
|
||
continue
|
||
|
||
if tpl is None or roi_img is None:
|
||
continue
|
||
|
||
th, tw = tpl.shape[:2]
|
||
rh, rw = roi_img.shape[:2]
|
||
|
||
# 模板必须小于或等于ROI
|
||
if th > rh or tw > rw:
|
||
# 如果模板比ROI大,缩小模板
|
||
scale = min(rh / max(th, 1), rw / max(tw, 1))
|
||
if scale <= 0:
|
||
continue
|
||
tpl = cv2.resize( # type: ignore[attr-defined]
|
||
tpl, (max(1, int(tw * scale)), max(1, int(th * scale)))
|
||
)
|
||
th, tw = tpl.shape[:2]
|
||
|
||
# 在ROI中匹配模板
|
||
res = cv2.matchTemplate( # type: ignore[attr-defined]
|
||
roi_img, tpl, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
|
||
)
|
||
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc( # type: ignore[attr-defined]
|
||
res
|
||
)
|
||
|
||
# 记录最佳匹配分数和模板名称
|
||
if max_val > best_score:
|
||
best_score = float(max_val or 0.0)
|
||
best_name = f"assets/{icon_name}.png -> ocr/{'xx' if icon_name == 'x' else 'xxin'}.png"
|
||
|
||
# 如果匹配分数达到阈值,标记为检测成功
|
||
# 使用 template_threshold(模板匹配阈值),而不是 threshold(像素检测阈值)
|
||
if max_val >= template_threshold:
|
||
detected = True
|
||
except Exception:
|
||
continue
|
||
|
||
if not detected and best_score == 0.0:
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断", "_check_in_live_room_by_icon 无可用模板或ROI文件"
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
self._log_kv(
|
||
"阶段诊断",
|
||
"_check_in_live_room_by_icon 结果",
|
||
detected=int(bool(detected)),
|
||
score=round(best_score, 3),
|
||
template=best_name or "-",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
return bool(detected), float(best_score or 0.0)
|
||
|
||
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 e:
|
||
try:
|
||
self._log_kv("检测", "check_in_fudai_detail 异常", error=str(e))
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
def _enhanced_log_kv(self, *args, **fields):
|
||
"""增强的日志记录方法:始终输出到 stdout(供 GUI 捕获),同时可选输出到标准 logging"""
|
||
# 解析参数:优先使用位置参数,避免与关键字参数冲突
|
||
if len(args) >= 1:
|
||
tag = args[0]
|
||
# 如果位置参数提供了 tag,从 fields 中移除 tag 避免冲突
|
||
fields.pop("tag", None)
|
||
else:
|
||
tag = fields.get("tag", "日志")
|
||
|
||
if len(args) >= 2:
|
||
msg = args[1]
|
||
# 如果位置参数提供了 msg,从 fields 中移除 msg 避免冲突
|
||
fields.pop("msg", None)
|
||
else:
|
||
msg = fields.get("msg", "")
|
||
|
||
# 获取日志级别
|
||
log_level = fields.get("level", "INFO").upper()
|
||
if log_level not in ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"):
|
||
log_level = "INFO"
|
||
|
||
# 递增日志序号
|
||
try:
|
||
self._log_seq += 1
|
||
except Exception:
|
||
self._log_seq = 1
|
||
|
||
# 获取时间戳
|
||
try:
|
||
from datetime import datetime
|
||
|
||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
except Exception:
|
||
# 如果无法导入 datetime(极少见),回退为 time.strftime,避免引用未定义的名字
|
||
try:
|
||
import time
|
||
|
||
timestamp = time.strftime("%H:%M:%S")
|
||
except Exception:
|
||
timestamp = ""
|
||
|
||
# 获取调用者信息(模块名:函数名:行号)
|
||
caller_info = ""
|
||
try:
|
||
import inspect
|
||
|
||
# 获取调用栈:跳过 _enhanced_log_kv 本身,找到真正的调用者
|
||
frame = inspect.currentframe()
|
||
if frame:
|
||
# frame.f_back 是调用 _enhanced_log_kv 的帧(可能是 _log_kv 或其他)
|
||
# 需要再往上找一层,找到实际调用 _log_kv 的代码
|
||
caller_frame = frame.f_back
|
||
if caller_frame:
|
||
# 检查是否是 _log_kv 的调用(属性赋值的情况)
|
||
if (
|
||
caller_frame.f_code.co_name == "_log_kv"
|
||
or "log_kv" in caller_frame.f_code.co_name
|
||
):
|
||
caller_frame = caller_frame.f_back
|
||
# 如果找到了调用者,提取信息
|
||
if caller_frame:
|
||
filename = caller_frame.f_code.co_filename
|
||
funcname = caller_frame.f_code.co_name
|
||
lineno = caller_frame.f_lineno
|
||
# 只取文件名,不包含路径
|
||
import os
|
||
|
||
filename = os.path.basename(filename)
|
||
# 如果文件名是 <string> 或类似,说明是测试代码,跳过
|
||
if filename and filename not in ("<string>", "<stdin>"):
|
||
caller_info = f"{filename}:{funcname}:{lineno}"
|
||
except Exception:
|
||
pass
|
||
|
||
# 字段映射(中文 key)
|
||
key_map = {
|
||
"rid": "运行",
|
||
"seq": "序号",
|
||
"msg": "说明",
|
||
"stage": "阶段",
|
||
"seen": "识别",
|
||
"ok": "成功",
|
||
"text": "文本",
|
||
"action": "动作",
|
||
"result": "结果",
|
||
"mode": "模式",
|
||
"reason": "原因",
|
||
"wait_seconds": "等待秒",
|
||
"value_yuan": "价值元",
|
||
"future": "开奖时间",
|
||
"pos_seen": "发现位置",
|
||
"qsize": "队列数量",
|
||
"room_pos": "当前位置",
|
||
"content": "内容",
|
||
"countdown": "倒计时",
|
||
"participants": "参与人数",
|
||
"copies": "份数",
|
||
"seconds": "耗时秒",
|
||
"error": "错误",
|
||
"error_type": "错误类型",
|
||
"fudai_x": "福袋X坐标",
|
||
"attempt": "尝试次数",
|
||
"room_title": "直播间名",
|
||
"back_times": "需回退次数",
|
||
}
|
||
|
||
# 构建日志行(增强格式:时间 级别 标签 [调用者] 消息 字段...)
|
||
log_parts = []
|
||
if timestamp:
|
||
log_parts.append(f"[{timestamp}]")
|
||
log_parts.append(f"[{log_level}]")
|
||
log_parts.append(f"[{tag}]")
|
||
|
||
# 添加调用者信息(如果获取成功)
|
||
if caller_info:
|
||
log_parts.append(f"[{caller_info}]")
|
||
|
||
if msg:
|
||
m = str(msg).replace("\r", " ").replace("\n", " ").strip()
|
||
if len(m) > 200:
|
||
m = m[:200] + "..."
|
||
log_parts.append(m)
|
||
|
||
# 添加字段信息
|
||
for k, v in fields.items():
|
||
if k in ("tag", "msg", "level", "exc_info", "_show_caller", "_caller"):
|
||
continue
|
||
if v is None:
|
||
continue
|
||
key_cn = key_map.get(str(k), f"字段_{k}")
|
||
# 格式化值
|
||
if isinstance(v, float):
|
||
if abs(v) < 1:
|
||
v_str = f"{v:.3f}"
|
||
elif abs(v) < 100:
|
||
v_str = f"{v:.2f}"
|
||
else:
|
||
v_str = f"{int(v)}"
|
||
elif isinstance(v, (int, bool)):
|
||
v_str = str(v)
|
||
else:
|
||
s = str(v).replace("\r", " ").replace("\n", " ").strip()
|
||
if len(s) > 100:
|
||
s = s[:100] + "..."
|
||
v_str = s
|
||
log_parts.append(f"{key_cn}={v_str}")
|
||
|
||
# 构建完整日志行
|
||
log_line = " ".join(log_parts)
|
||
|
||
# 判断是否需要添加分隔符(便于查看日志)
|
||
need_separator = False
|
||
separator_reason = ""
|
||
|
||
# 1. 错误发生时(优先级最高)
|
||
if log_level in ("ERROR", "WARNING", "CRITICAL"):
|
||
need_separator = True
|
||
separator_reason = "错误/警告"
|
||
|
||
# 2. 运行开始时
|
||
elif tag and any(keyword in str(tag) for keyword in ["运行", "启动", "开始", "初始化"]):
|
||
need_separator = True
|
||
separator_reason = "运行开始"
|
||
|
||
# 3. 阶段变化时(tag变化且包含阶段相关关键词)
|
||
elif tag and self._last_log_tag != tag:
|
||
if any(keyword in str(tag) for keyword in ["阶段", "循环", "参与", "检测", "寻找", "进入", "退出"]):
|
||
need_separator = True
|
||
separator_reason = "阶段变化"
|
||
|
||
# 4. 重要操作(通过tag判断)
|
||
elif tag and self._last_log_tag != tag:
|
||
if any(keyword in str(tag) for keyword in ["参与", "中奖", "完成", "失败", "超时"]):
|
||
need_separator = True
|
||
separator_reason = "重要操作"
|
||
|
||
# 输出分隔符(如果需要)
|
||
if need_separator:
|
||
try:
|
||
# 使用等号作为分隔符,更清晰易读
|
||
separator = "=" * 80
|
||
# 在分隔符中间显示原因,更美观
|
||
reason_text = f" {separator_reason} "
|
||
separator_line = f"{separator}\n{reason_text.center(80, '=')}\n{separator}"
|
||
print(separator_line, flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 更新上一个日志标签
|
||
self._last_log_tag = tag
|
||
|
||
# 始终输出到 stdout(供 GUI 捕获)- 这是最重要的!
|
||
try:
|
||
print(log_line, flush=True) # flush=True 确保立即输出,不缓冲
|
||
except Exception:
|
||
pass
|
||
|
||
# 写入行为日志(actions.log)- 使用运行日志格式,但只保留关键信息
|
||
# 记录所有操作到行为日志
|
||
try:
|
||
# 判断是否需要记录(记录所有操作,但可以过滤一些噪音日志)
|
||
should_log = True
|
||
|
||
# 过滤一些不需要记录的日志(避免噪音)
|
||
if tag:
|
||
# 跳过一些调试或详细日志
|
||
skip_tags = ["[调试图像]", "[步骤耗时]"]
|
||
for skip_tag in skip_tags:
|
||
if tag.startswith(skip_tag):
|
||
should_log = False
|
||
break
|
||
|
||
if should_log:
|
||
# 获取时间戳
|
||
if not timestamp:
|
||
from datetime import datetime
|
||
|
||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
|
||
|
||
# 提取关键信息:做了什么、耗时、分数
|
||
# 如果msg为空,从tag中提取操作描述
|
||
if msg:
|
||
action_desc = str(msg)
|
||
# 移除函数名:匹配 "函数名:" 或 "函数名 " 格式
|
||
import re
|
||
|
||
# 移除函数名(匹配函数名后跟冒号、空格的情况)
|
||
# 匹配模式:函数名(可能包含下划线)后跟冒号或空格
|
||
# 例如:read_fudai_detail_once: 或 read_fudai_detail_with_retries 或 _handle_in_fudai_detail:
|
||
# 先移除带冒号的函数名
|
||
action_desc = re.sub(
|
||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s*[::]\s*", "", action_desc
|
||
)
|
||
# 再移除带空格的函数名(但后面不是字母/下划线开头的单词)
|
||
# 例如:read_fudai_detail_with_retries 最终结果 -> 最终结果
|
||
action_desc = re.sub(
|
||
r"^[a-zA-Z_][a-zA-Z0-9_]*\s+(?=[^a-zA-Z_])", "", action_desc
|
||
)
|
||
# 如果移除后为空,保留原描述
|
||
if not action_desc.strip():
|
||
action_desc = str(msg)
|
||
# 简化描述:移除字段前缀,只保留关键信息
|
||
if "字段_" in action_desc:
|
||
# 提取阶段信息(如果有)
|
||
if "字段_阶段=" in action_desc:
|
||
stage_match = re.search(r"字段_阶段=(\w+)", action_desc)
|
||
if stage_match:
|
||
action_desc = f"阶段={stage_match.group(1)}"
|
||
else:
|
||
# 简化其他字段描述,只保留消息部分
|
||
action_desc = action_desc.split("字段_")[0].strip()
|
||
else:
|
||
# 从tag中提取操作类型(移除标签的方括号)
|
||
if tag:
|
||
tag_clean = tag.strip("[]").strip()
|
||
if tag_clean:
|
||
action_desc = tag_clean
|
||
else:
|
||
action_desc = "操作"
|
||
else:
|
||
action_desc = "操作"
|
||
|
||
# 提取耗时(从字段中查找,优先使用毫秒字段)
|
||
elapsed_str = ""
|
||
if "elapsed_ms" in fields:
|
||
elapsed_seconds = float(fields.get("elapsed_ms", 0)) / 1000.0
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "total_elapsed_ms" in fields:
|
||
elapsed_seconds = float(fields.get("total_elapsed_ms", 0)) / 1000.0
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "总耗时毫秒" in fields:
|
||
elapsed_seconds = float(fields.get("总耗时毫秒", 0)) / 1000.0
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "seconds" in fields:
|
||
elapsed_seconds = float(fields.get("seconds", 0))
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
elif "elapsed_seconds" in fields:
|
||
elapsed_seconds = float(fields.get("elapsed_seconds", 0))
|
||
elapsed_str = f"耗时:{elapsed_seconds:.2f}s"
|
||
|
||
# 提取分数(如果有)
|
||
score_str = ""
|
||
if "score" in fields and fields.get("score") is not None:
|
||
try:
|
||
score_val = float(fields.get("score", 0))
|
||
score_str = f"分数:{score_val:.3f}"
|
||
except (ValueError, TypeError):
|
||
pass
|
||
elif "max_val" in fields and fields.get("max_val") is not None:
|
||
try:
|
||
score_val = float(fields.get("max_val", 0))
|
||
score_str = f"分数:{score_val:.3f}"
|
||
except (ValueError, TypeError):
|
||
pass
|
||
elif "分数" in fields:
|
||
score_field = fields.get("分数")
|
||
# 允许显示0.0分数,只要不是None
|
||
if score_field is not None:
|
||
try:
|
||
score_val = float(score_field)
|
||
score_str = f"分数:{score_val:.3f}"
|
||
except (ValueError, TypeError):
|
||
pass
|
||
|
||
# 构建精简的行为日志行,使用运行日志格式:时间 - [GUI] - [标签] 做了什么 耗时:XXs 分数:XX
|
||
action_parts = [timestamp, "-", "[GUI]", "-"]
|
||
if tag:
|
||
action_parts.append(tag)
|
||
else:
|
||
action_parts.append("[日志]")
|
||
action_parts.append(action_desc)
|
||
|
||
if elapsed_str:
|
||
action_parts.append(elapsed_str)
|
||
|
||
if score_str:
|
||
action_parts.append(score_str)
|
||
|
||
action_log_line = " ".join(action_parts)
|
||
|
||
# 写入 actions.log 文件
|
||
import os
|
||
|
||
actions_log_path = os.path.join(
|
||
os.path.dirname(__file__), "logs", "actions.log"
|
||
)
|
||
log_dir = os.path.dirname(actions_log_path)
|
||
if log_dir:
|
||
os.makedirs(log_dir, exist_ok=True)
|
||
|
||
# 检测标签变化,用====分隔不同步骤
|
||
# 使用实例变量记录上一个标签
|
||
if not hasattr(self, "_last_action_tag"):
|
||
self._last_action_tag = None
|
||
|
||
# 如果标签变化,添加分隔符
|
||
current_tag = tag or "[日志]"
|
||
if (
|
||
self._last_action_tag is not None
|
||
and self._last_action_tag != current_tag
|
||
):
|
||
# 标签变化,添加分隔符(增加到80个等号)
|
||
with open(
|
||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||
) as f:
|
||
f.write("=" * 80 + "\n")
|
||
f.flush()
|
||
|
||
# 更新上一个标签
|
||
self._last_action_tag = current_tag
|
||
|
||
# 写入日志行
|
||
with open(
|
||
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
|
||
) as f:
|
||
f.write(action_log_line + "\n")
|
||
f.flush()
|
||
except Exception:
|
||
pass
|
||
|
||
# 同时输出到标准 logging(如果已配置,可选)
|
||
try:
|
||
# 确保日志系统已配置
|
||
import logging
|
||
|
||
root_logger = logging.getLogger()
|
||
if not root_logger.handlers:
|
||
# 如果根 logger 没有 handlers,尝试配置日志系统
|
||
try:
|
||
import douyin_logging
|
||
|
||
douyin_logging.configure_logging()
|
||
except Exception:
|
||
pass
|
||
|
||
if not hasattr(self, "_std_logger") or self._std_logger is None:
|
||
try:
|
||
from unified_logger import get_unified_logger
|
||
|
||
self._std_logger = get_unified_logger("douyin.fudai")
|
||
except ImportError:
|
||
try:
|
||
import douyin_logger
|
||
|
||
self._std_logger = douyin_logger.get_logger("douyin")
|
||
except Exception:
|
||
# 如果都失败了,使用根 logger
|
||
self._std_logger = logging.getLogger("douyin.fudai")
|
||
|
||
# 使用根 logger 确保日志能写入文件(子 logger 会传播到根 logger)
|
||
root_logger = logging.getLogger()
|
||
if root_logger.handlers:
|
||
# 如果根 logger 有 handlers,使用根 logger 写入(确保能写入文件)
|
||
# 构建标准 logging 消息(包含调用者信息)
|
||
std_msg_parts = [f"[{tag}]"]
|
||
if caller_info:
|
||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||
if msg:
|
||
# 对消息进行敏感信息脱敏
|
||
try:
|
||
from unified_logger import SensitiveDataMasker
|
||
|
||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||
std_msg_parts.append(masked_msg)
|
||
except ImportError:
|
||
std_msg_parts.append(str(msg))
|
||
|
||
# 对字段进行敏感信息脱敏
|
||
masked_fields = {}
|
||
try:
|
||
from unified_logger import SensitiveDataMasker
|
||
|
||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||
except ImportError:
|
||
masked_fields = fields
|
||
|
||
for k, v in masked_fields.items():
|
||
if k in (
|
||
"tag",
|
||
"msg",
|
||
"level",
|
||
"exc_info",
|
||
"_show_caller",
|
||
"_caller",
|
||
):
|
||
continue
|
||
if v is not None:
|
||
std_msg_parts.append(f"{k}={v}")
|
||
|
||
log_message = " ".join(std_msg_parts)
|
||
|
||
# 检查是否有异常信息
|
||
exc_info = fields.get("exc_info")
|
||
if exc_info is None:
|
||
if sys.exc_info()[0] is not None:
|
||
exc_info = sys.exc_info()
|
||
|
||
# 记录到根 logger(确保能写入文件)
|
||
level = getattr(logging, log_level, logging.INFO)
|
||
if exc_info:
|
||
root_logger.log(
|
||
level,
|
||
log_message,
|
||
exc_info=exc_info,
|
||
extra={"caller": caller_info},
|
||
)
|
||
else:
|
||
root_logger.log(level, log_message, extra={"caller": caller_info})
|
||
elif hasattr(self, "_std_logger") and self._std_logger:
|
||
# 如果根 logger 没有 handlers,尝试使用 _std_logger(但通常不会到这里)
|
||
# 构建标准 logging 消息(包含调用者信息)
|
||
std_msg_parts = [f"[{tag}]"]
|
||
if caller_info:
|
||
std_msg_parts.append(f"[调用:{caller_info}]")
|
||
if msg:
|
||
# 对消息进行敏感信息脱敏
|
||
try:
|
||
from unified_logger import SensitiveDataMasker
|
||
|
||
masked_msg = SensitiveDataMasker.mask_all(str(msg))
|
||
std_msg_parts.append(masked_msg)
|
||
except ImportError:
|
||
std_msg_parts.append(str(msg))
|
||
|
||
# 对字段进行敏感信息脱敏
|
||
masked_fields = {}
|
||
try:
|
||
from unified_logger import SensitiveDataMasker
|
||
|
||
masked_fields = SensitiveDataMasker.mask_dict(fields)
|
||
except ImportError:
|
||
masked_fields = fields
|
||
|
||
for k, v in masked_fields.items():
|
||
if k in (
|
||
"tag",
|
||
"msg",
|
||
"level",
|
||
"exc_info",
|
||
"_show_caller",
|
||
"_caller",
|
||
):
|
||
continue
|
||
if v is not None:
|
||
std_msg_parts.append(f"{k}={v}")
|
||
|
||
log_message = " ".join(std_msg_parts)
|
||
|
||
# 检查是否有异常信息
|
||
exc_info = fields.get("exc_info")
|
||
if exc_info is None:
|
||
if sys.exc_info()[0] is not None:
|
||
exc_info = sys.exc_info()
|
||
|
||
# 记录到标准 logger(使用 extra 参数传递调用者信息,让 formatter 使用)
|
||
level = getattr(logging, log_level, logging.INFO)
|
||
if exc_info:
|
||
self._std_logger.log(
|
||
level,
|
||
log_message,
|
||
exc_info=exc_info,
|
||
extra={"caller": caller_info},
|
||
)
|
||
else:
|
||
self._std_logger.log(
|
||
level, log_message, extra={"caller": caller_info}
|
||
)
|
||
except Exception as e:
|
||
# 如果标准 logging 写入失败,尝试使用根 logger 写入(作为备用)
|
||
try:
|
||
import logging
|
||
|
||
root_logger = logging.getLogger()
|
||
level = getattr(logging, log_level, logging.INFO)
|
||
# 构建简单的日志消息
|
||
simple_msg = f"[{tag}] {msg}" if msg else f"[{tag}]"
|
||
# 直接使用根 logger,它会自动处理子 logger 的传播
|
||
root_logger.log(level, simple_msg)
|
||
except Exception:
|
||
# 如果所有日志写入都失败,至少确保 stdout 输出(已在上面完成)
|
||
pass
|
||
|
||
# 如果有异常堆栈,也输出到 stdout
|
||
exc_info = fields.get("exc_info")
|
||
if exc_info is None:
|
||
if sys.exc_info()[0] is not None:
|
||
exc_info = sys.exc_info()
|
||
|
||
if exc_info:
|
||
try:
|
||
import traceback
|
||
|
||
# exc_info 应该是 (type, value, traceback) 元组
|
||
if isinstance(exc_info, tuple) and len(exc_info) == 3:
|
||
exc_type, exc_value, exc_traceback = exc_info
|
||
# 确保 exc_value 是 BaseException 实例
|
||
if isinstance(exc_value, BaseException):
|
||
tb_str = traceback.format_exception(
|
||
exc_type, exc_value, exc_traceback
|
||
)
|
||
else:
|
||
# 如果不是异常实例,创建一个包装异常
|
||
try:
|
||
# 尝试使用原始值
|
||
tb_str = traceback.format_exception(
|
||
exc_type,
|
||
(
|
||
BaseException(str(exc_value))
|
||
if exc_value
|
||
else BaseException("Unknown error")
|
||
),
|
||
exc_traceback,
|
||
)
|
||
except Exception:
|
||
# 如果还是失败,只输出异常信息
|
||
print(
|
||
f" 异常类型: {exc_type}, 异常值: {exc_value}",
|
||
flush=True,
|
||
)
|
||
tb_str = []
|
||
for line in tb_str:
|
||
print(f" {line.rstrip()}", flush=True)
|
||
else:
|
||
# 如果不是标准格式,尝试直接格式化
|
||
try:
|
||
tb_str = traceback.format_exception(*exc_info)
|
||
for line in tb_str:
|
||
print(f" {line.rstrip()}", flush=True)
|
||
except Exception:
|
||
# 如果格式化失败,只输出异常信息
|
||
print(f" 异常信息: {exc_info}", flush=True)
|
||
except Exception:
|
||
pass
|
||
|
||
# 供像素/检测模块记录子步骤耗时使用
|
||
def _log_step_time(
|
||
self, step_name: str, start_time: float, extra_info: dict | None = None
|
||
) -> None:
|
||
"""记录某个子步骤的耗时(供检测模块调用,减少日志噪音)。"""
|
||
try:
|
||
elapsed = time.time() - float(start_time or 0.0)
|
||
except Exception:
|
||
elapsed = 0.0
|
||
fields: dict[str, Any] = {"seconds": elapsed}
|
||
if extra_info:
|
||
for k, v in extra_info.items():
|
||
fields[str(k)] = v
|
||
try:
|
||
self._log_kv("步骤耗时", step_name, **fields)
|
||
except Exception:
|
||
pass
|
||
|
||
# ========== 弹窗 / 人机校验 ==========
|
||
def _check_coupon_popup(self) -> bool:
|
||
"""购物券 / 新客专享券 等底部营销弹窗(仅在详情链路外的“看门狗”中使用)。"""
|
||
return douyin_popups.check_coupon_popup(self)
|
||
|
||
def _check_shopping_redpacket_popup(self) -> bool:
|
||
"""购物红包中央弹窗。"""
|
||
return douyin_popups.check_shopping_redpacket_popup(self)
|
||
|
||
# ========== 主循环骨架(基础抢福袋 + 简化预约抢占) ==========
|
||
def run_once_basic(self) -> None:
|
||
"""单轮基础抢福袋流程(包含简化版高价值福袋预约回退)。"""
|
||
import douyin_reservation_logic # 确保在函数作用域内可用
|
||
start_time = time.time()
|
||
# 0. 如果正在等待开奖,检查高价值预约是否需要抢占,否则只检测开奖结果
|
||
if getattr(self, "_waiting_for_lottery_result", False):
|
||
try:
|
||
# 检查是否有高价值预约需要处理(除非遇到高价值预约,否则应该等待福袋开奖)
|
||
should_preempt = False
|
||
try:
|
||
if getattr(self, "high_value_fudai_enabled", False) and getattr(
|
||
self, "reservations", None
|
||
):
|
||
reservations = self.reservations
|
||
if reservations and len(reservations) > 0:
|
||
# 检查是否有预约需要立即处理
|
||
import douyin_reservation_logic
|
||
|
||
reservation_focus_until_ts_ref = [0.0]
|
||
reservation_after_action_pending_ref = [False]
|
||
room_pos_ref = [getattr(self, "room_pos", 0) or 0]
|
||
|
||
# 检查是否有预约需要抢占
|
||
preempted = douyin_reservation_logic.process_reservation_attend_window(
|
||
self,
|
||
reservations,
|
||
room_pos_ref[0],
|
||
reservation_focus_until_ts_ref,
|
||
reservation_after_action_pending_ref,
|
||
float(
|
||
getattr(self, "reservation_back_swipe_delay_s", 0.5)
|
||
or 0.5
|
||
),
|
||
lambda: self.swipe_down_back_from_live(),
|
||
lambda item: self._seek_reservation_room(item),
|
||
lambda: (
|
||
douyin_reservation_logic._sort_reservations_inplace(
|
||
self.reservations
|
||
)
|
||
if self.reservations
|
||
else None
|
||
),
|
||
lambda: None, # write_state_callback
|
||
)
|
||
|
||
if preempted:
|
||
# 有高价值预约需要处理,清除等待开奖标志,中断等待
|
||
self._waiting_for_lottery_result = False
|
||
should_preempt = True
|
||
self._log_kv(
|
||
"参与",
|
||
"等待开奖期间检测到高价值预约需要处理,中断等待",
|
||
)
|
||
except Exception as e:
|
||
self._log_kv("参与", "检查高价值预约时出错", error=str(e))
|
||
|
||
if should_preempt:
|
||
# 被高价值预约抢占,继续执行后续逻辑处理预约
|
||
pass
|
||
else:
|
||
# 没有预约抢占,继续等待开奖
|
||
# 直接用预计开奖时间减去当前时间计算剩余秒数,加上6秒延迟修正
|
||
future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0
|
||
current_ts = time.time()
|
||
remain_seconds = max(0, future_ts - current_ts + 6.0) # 加上6秒延迟,修正倒计时误差
|
||
|
||
# 开奖时间 + 1秒缓冲后开始检测开奖结果(提前4秒:从+5秒改为+1秒)
|
||
check_start_ts = future_ts + 1.0
|
||
# 超时时间:如果超过开奖时间10秒还没检测到结果,清除等待标志(福袋开奖后10秒会自动关闭)
|
||
timeout_ts = future_ts + 10.0
|
||
|
||
if current_ts >= timeout_ts:
|
||
# 超过超时时间,清除等待标志,避免卡死
|
||
self._waiting_for_lottery_result = False
|
||
timeout_seconds = int(current_ts - future_ts)
|
||
self._log_kv(
|
||
"参与",
|
||
f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作",
|
||
超时秒数=timeout_seconds,
|
||
)
|
||
# 继续执行后续逻辑,不返回
|
||
elif current_ts >= check_start_ts:
|
||
# 已经超过开奖时间+缓冲时间,直接点击"我知道了"按钮(多次点击,确保关闭弹窗)
|
||
# 计算已过开奖时间的秒数
|
||
passed_seconds = int(current_ts - future_ts)
|
||
self._log_kv(
|
||
"参与",
|
||
f"等待开奖结果中,OCR未识别到结果(已过开奖时间{passed_seconds}秒),开始直接点击",
|
||
已过开奖时间秒数=passed_seconds,
|
||
)
|
||
# 按钮位置基于1080x2400:532, 1322
|
||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||
btn_x = int(532 * rx // 1080)
|
||
btn_y = int(1322 * ry // 2400)
|
||
|
||
# 直接点击"我知道了"按钮,最多点击10次,每次间隔1秒
|
||
clicked_count = 0
|
||
max_clicks = 10
|
||
for i in range(max_clicks):
|
||
try:
|
||
self.operation.get_screenshot(self.device_id)
|
||
# 检查是否还在开奖结果弹窗(通过阶段诊断)
|
||
import douyin_stage
|
||
stage_result = douyin_stage.diagnose_stage_from_current_screen(self)
|
||
if stage_result is None:
|
||
current_stage = "UNKNOWN"
|
||
else:
|
||
current_stage, _ = stage_result
|
||
|
||
# 如果不在开奖结果弹窗,说明已经关闭,停止点击
|
||
if current_stage != "FUDai_RESULT":
|
||
self._log_kv(
|
||
"参与",
|
||
"等待开奖期间:直接点击后弹窗已关闭",
|
||
clicked_count=i + 1,
|
||
stage=current_stage,
|
||
)
|
||
break
|
||
|
||
# 点击"我知道了"按钮
|
||
self.operation.click(self.device_id, btn_x, btn_y)
|
||
clicked_count += 1
|
||
self._log_kv(
|
||
"参与",
|
||
"等待开奖期间:直接点击我知道了按钮",
|
||
click_count=clicked_count,
|
||
x=btn_x,
|
||
y=btn_y,
|
||
)
|
||
self.operation.delay(1.0)
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"参与",
|
||
"等待开奖期间:直接点击时出错",
|
||
error=str(e),
|
||
click_count=clicked_count,
|
||
)
|
||
break
|
||
|
||
# 如果直接点击失败,回退到OCR识别方式
|
||
if clicked_count == 0:
|
||
self._log_kv("参与", "等待开奖期间:直接点击失败,回退到OCR识别")
|
||
self.operation.get_screenshot(self.device_id)
|
||
result = self._check_lottery_result_by_ocr()
|
||
if result:
|
||
self._waiting_for_lottery_result = False
|
||
self._log_kv("参与", "等待期间检测到开奖结果,开始处理")
|
||
self._handle_lottery_result_by_ocr(result)
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(等待开奖期间处理结果)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
|
||
# 清除等待标志,切换直播间
|
||
self._waiting_for_lottery_result = False
|
||
self._log_kv(
|
||
"参与",
|
||
"等待开奖期间:已直接点击我知道了按钮",
|
||
clicked_count=clicked_count,
|
||
)
|
||
|
||
# 切换下一个直播间
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
|
||
if needswitch:
|
||
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),
|
||
)
|
||
return
|
||
else:
|
||
# 还未到开奖时间,短暂等待后继续检测
|
||
wait_s = min(2.0, remain_seconds)
|
||
remain_seconds_int = int(remain_seconds)
|
||
# 在日志消息中显示倒计时
|
||
self._log_kv(
|
||
"参与",
|
||
f"等待开奖中,剩余{remain_seconds_int}秒",
|
||
剩余秒数=remain_seconds_int,
|
||
)
|
||
self.operation.delay(wait_s)
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
f"run_once_basic完成(等待开奖中,剩余{remain_seconds_int}秒)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return # 返回,不执行其他操作
|
||
except Exception as e:
|
||
self._log_kv("参与", "等待开奖检测时出错", error=str(e))
|
||
# 出错时清除等待标志,避免卡死
|
||
self._waiting_for_lottery_result = False
|
||
|
||
# 0. 检查30分钟超时:如果30分钟没有成功参与福袋,则返回推荐页面并重新进入直播间
|
||
try:
|
||
last_attend_ts = float(
|
||
getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
|
||
)
|
||
timeout_minutes = float(
|
||
getattr(self, "_no_attend_timeout_minutes", 30.0) or 30.0
|
||
)
|
||
current_ts = time.time()
|
||
run_start_ts = float(
|
||
getattr(self, "_run_start_ts", current_ts) or current_ts
|
||
)
|
||
|
||
# 如果从未成功参与过,且运行时间超过30分钟,则触发超时
|
||
# 如果成功参与过,检查距离最后一次成功参与是否超过30分钟
|
||
if last_attend_ts > 0:
|
||
elapsed_minutes = (current_ts - last_attend_ts) / 60.0
|
||
if elapsed_minutes >= timeout_minutes:
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
f"30分钟未参与成功福袋,返回推荐页面重新进入直播间",
|
||
last_attend_minutes_ago=round(elapsed_minutes, 1),
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 返回推荐页面并重新进入直播间
|
||
self._return_to_recommend_and_reenter_live()
|
||
# 重置最后成功参与时间,避免立即再次触发
|
||
try:
|
||
self._last_successful_attend_ts = current_ts
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(30分钟超时处理)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
else:
|
||
# 从未成功参与过,检查运行时间
|
||
elapsed_minutes = (current_ts - run_start_ts) / 60.0
|
||
if elapsed_minutes >= timeout_minutes:
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
f"运行{round(elapsed_minutes, 1)}分钟仍未参与成功福袋,返回推荐页面重新进入直播间",
|
||
run_minutes=round(elapsed_minutes, 1),
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 返回推荐页面并重新进入直播间
|
||
self._return_to_recommend_and_reenter_live()
|
||
# 重置运行开始时间(在成功重新进入直播间后重置,避免立即再次触发)
|
||
# 注意:重置逻辑已移至 _return_to_recommend_and_reenter_live() 方法中
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(30分钟超时处理)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv("超时", "检查30分钟超时时出错", error=str(e))
|
||
except Exception:
|
||
pass
|
||
|
||
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
|
||
try:
|
||
# 每次开始运行时丢弃旧的预约队列,不加载状态文件
|
||
try:
|
||
import json
|
||
|
||
# 如果是第一次运行,清空预约队列,不加载状态文件
|
||
is_first_run = getattr(self, "_first_run_once_basic", True)
|
||
# 记录清空前的队列状态(用于调试)
|
||
old_reservations_count = 0
|
||
try:
|
||
old_reservations_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
|
||
except Exception:
|
||
pass
|
||
|
||
if is_first_run:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件",
|
||
old_reservations_count=old_reservations_count,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 清空预约队列(强制清空,确保每次启动时队列为空)
|
||
try:
|
||
# 先记录清空前的状态
|
||
before_clear = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
|
||
self.reservations = []
|
||
after_clear = len(self.reservations) if hasattr(self, "reservations") else 0
|
||
|
||
# 同时清空状态文件,确保外部查看时也是空的
|
||
try:
|
||
import os
|
||
state_path = getattr(self, "_reservations_state_path", None)
|
||
if state_path:
|
||
# 写入空队列到状态文件
|
||
from douyin_reservation import write_reservations_state
|
||
write_reservations_state(
|
||
state_path=state_path,
|
||
reservations=[],
|
||
room_pos=0,
|
||
current_room_title="",
|
||
current_room_title_raw="",
|
||
reason="startup_clear",
|
||
)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 已清空预约队列并更新状态文件",
|
||
before_clear=before_clear,
|
||
after_clear=after_clear,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 清空状态文件时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
# 如果清空失败,尝试直接设置
|
||
try:
|
||
if hasattr(self, "reservations"):
|
||
self.reservations = []
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 清空预约队列时出错,已尝试直接设置",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 标记已运行过
|
||
try:
|
||
self._first_run_once_basic = False
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 如果不是第一次运行,也记录日志(用于调试)
|
||
try:
|
||
current_count = len(self.reservations) if hasattr(self, "reservations") and self.reservations else 0
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 非第一次运行,保持当前预约队列",
|
||
reservations_count=current_count,
|
||
is_first_run=False,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 不再从状态文件加载预约数据,每次启动时都从空队列开始
|
||
# 已移除从状态文件加载预约数据的逻辑,每次启动时预约队列为空
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 初始化预约队列时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
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
|
||
|
||
# 添加详细的调试日志,确认预约回退逻辑的触发条件
|
||
try:
|
||
# 输出预约队列的详细信息
|
||
reservations_detail = []
|
||
if reservations_list:
|
||
for idx, r in enumerate(reservations_list[:3]): # 只显示前3个
|
||
try:
|
||
ft = float(r.get("future_ts") or 0)
|
||
from datetime import datetime
|
||
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
|
||
reservations_detail.append({
|
||
"index": idx,
|
||
"future_ts": int(ft) if ft > 0 else 0,
|
||
"future_str": ft_str,
|
||
"value": float(r.get("prize_value_yuan", 0)),
|
||
"pos_seen": int(r.get("pos_seen", 0)),
|
||
})
|
||
except Exception:
|
||
pass
|
||
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] run_once_basic:检查预约回退触发条件",
|
||
high_value_enabled=high_value_enabled,
|
||
reservations_count=reservations_count,
|
||
reservations_is_none=(reservations_list is None),
|
||
will_check_reservations=bool(high_value_enabled and reservations_list),
|
||
reservations_detail=reservations_detail,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果预约功能未启用,输出日志
|
||
if not high_value_enabled:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 如果预约队列为空,输出日志
|
||
elif not reservations_list or reservations_count == 0:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约队列为空,跳过预约回退检查",
|
||
reservations_is_none=(reservations_list is None),
|
||
reservations_count=reservations_count,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
if high_value_enabled and reservations_list:
|
||
|
||
def _swipe_down_once() -> None:
|
||
self.swipe_down_back_from_live()
|
||
|
||
def _sort_reservations() -> None:
|
||
douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined]
|
||
|
||
def _write_state() -> None:
|
||
# 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致)
|
||
try:
|
||
import json
|
||
import os
|
||
from datetime import datetime
|
||
|
||
os.makedirs(
|
||
os.path.dirname(self._reservations_state_path),
|
||
exist_ok=True,
|
||
)
|
||
|
||
# 格式化预约队列数据(与 douyin_reservation.py 格式一致)
|
||
items = []
|
||
for r in self.reservations or []:
|
||
try:
|
||
ft = float(r.get("future_ts") or 0)
|
||
except Exception:
|
||
ft = 0.0
|
||
try:
|
||
ft_str = (
|
||
datetime.fromtimestamp(ft).strftime(
|
||
"%Y-%m-%d %H:%M:%S"
|
||
)
|
||
if ft
|
||
else ""
|
||
)
|
||
except Exception:
|
||
ft_str = str(r.get("future_str", ""))
|
||
|
||
items.append(
|
||
{
|
||
"prize_value_yuan": float(
|
||
r.get("prize_value_yuan") or 0
|
||
),
|
||
"content": str(r.get("content") or ""),
|
||
"future_ts": ft,
|
||
"future_str": ft_str,
|
||
"pos_seen": int(r.get("pos_seen") or 0),
|
||
"room_title": str(r.get("room_title", "") or ""),
|
||
"room_title_raw": str(
|
||
r.get("room_title_raw", "") or ""
|
||
),
|
||
"created_ts": float(r.get("created_ts") or 0),
|
||
}
|
||
)
|
||
|
||
# 获取当前直播间标题(用于状态文件)
|
||
current_title = str(
|
||
getattr(self, "current_room_title", "") or ""
|
||
)
|
||
current_title_raw = str(
|
||
getattr(self, "current_room_title_raw", "") or ""
|
||
)
|
||
|
||
# 写入完整的状态数据
|
||
data = {
|
||
"updated_ts": time.time(),
|
||
"reason": "process_reservation",
|
||
"room_pos": int(getattr(self, "room_pos", 0) or 0),
|
||
"current_room_title": current_title,
|
||
"current_room_title_raw": current_title_raw,
|
||
"reservations": items,
|
||
}
|
||
|
||
with open(
|
||
self._reservations_state_path, "w", encoding="utf-8"
|
||
) as f:
|
||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"写入预约队列状态文件失败",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
focus_ref = [float(self.reservation_focus_until_ts or 0.0)]
|
||
after_action_ref = [
|
||
bool(self.reservation_after_action_pending or False)
|
||
]
|
||
|
||
def _seek_reservation_room(item: dict) -> bool:
|
||
try:
|
||
return bool(self._seek_reservation_room(item))
|
||
except Exception:
|
||
return False
|
||
|
||
# 检查队列是否已满且需要等待
|
||
max_reservations = int(
|
||
getattr(self, "high_value_fudai_max_reservations", 3) or 3
|
||
)
|
||
if (
|
||
len(self.reservations) >= max_reservations
|
||
and not self.queue_full_waiting_at_earliest
|
||
):
|
||
# 队列已满,回退到最早开奖的预约直播间等待
|
||
waiting = (
|
||
douyin_reservation_logic.handle_queue_full_wait_at_earliest(
|
||
analyser=self,
|
||
reservations=self.reservations,
|
||
room_pos=int(getattr(self, "room_pos", 0) or 0),
|
||
reservation_focus_until_ts_ref=focus_ref,
|
||
reservation_back_swipe_delay_s=float(
|
||
self.reservation_back_swipe_delay or 0.6
|
||
),
|
||
swipe_down_back_callback=_swipe_down_once,
|
||
seek_reservation_room_callback=_seek_reservation_room,
|
||
sort_reservations_callback=_sort_reservations,
|
||
write_state_callback=_write_state,
|
||
)
|
||
)
|
||
if waiting:
|
||
self.queue_full_waiting_at_earliest = True
|
||
if focus_ref:
|
||
self.reservation_focus_until_ts = float(focus_ref[0] or 0.0)
|
||
# 已回退到最早开奖的预约直播间,本轮结束
|
||
# 注意:_reservation_back_direct_attend 标志已在 handle_queue_full_wait_at_earliest 中设置
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(预约队列满等待)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
|
||
# 如果正在等待开奖,跳过预约回退检查
|
||
if getattr(self, "_waiting_for_lottery_result", False):
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 正在等待开奖,跳过预约回退检查",
|
||
waiting_for_lottery=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 跳过预约回退检查,让流程继续执行到阶段诊断后检查开奖结果
|
||
# 不在这里 return,让流程继续
|
||
# 如果已经在队列满等待状态,且设置了直接参与标志,立即执行参与,不再循环检查
|
||
elif self.queue_full_waiting_at_earliest:
|
||
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
|
||
if reservation_direct_attend:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 队列满等待状态,已设置直接参与标志,立即执行参与(不再循环检查)",
|
||
reservation_direct_attend=reservation_direct_attend,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 立即执行参与,不再循环检查预约回退
|
||
# 先进行阶段诊断,然后根据阶段执行参与
|
||
try:
|
||
self.operation.get_screenshot(self.device_id)
|
||
except Exception:
|
||
pass
|
||
import douyin_stage
|
||
result = douyin_stage.diagnose_stage_from_current_screen(self)
|
||
if result is None:
|
||
stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
|
||
else:
|
||
stage, reason = result
|
||
|
||
if stage == "FUDai_DETAIL":
|
||
# 在福袋详情页,直接参与
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到福袋详情页,立即执行直接参与",
|
||
stage=stage,
|
||
)
|
||
except Exception:
|
||
pass
|
||
self._reservation_back_direct_attend = False # 清除标志
|
||
self._force_attend_after_reservation_back = True # 设置强制参与标志
|
||
self._handle_reservation_direct_attend()
|
||
elif stage == "IN_LIVE_ROOM":
|
||
# 在直播间,查找福袋并打开详情页
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到直播间,查找福袋并打开详情页后执行直接参与",
|
||
stage=stage,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 查找福袋并打开详情页
|
||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||
original_max_wait = getattr(self, "fudai_icon_max_wait_seconds", None)
|
||
try:
|
||
wait_seconds_for_find = float(
|
||
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0
|
||
)
|
||
self.fudai_icon_max_wait_seconds = wait_seconds_for_find
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)",
|
||
room_pos=room_pos_ref[0],
|
||
max_wait_seconds=wait_seconds_for_find,
|
||
)
|
||
except Exception:
|
||
pass
|
||
found = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||
# 恢复原始配置
|
||
try:
|
||
if original_max_wait is not None:
|
||
self.fudai_icon_max_wait_seconds = original_max_wait
|
||
elif hasattr(self, "fudai_icon_max_wait_seconds"):
|
||
delattr(self, "fudai_icon_max_wait_seconds")
|
||
except Exception:
|
||
pass
|
||
if found:
|
||
# 成功打开详情页,直接参与
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 成功打开详情页,立即执行直接参与",
|
||
)
|
||
except Exception:
|
||
pass
|
||
self._reservation_back_direct_attend = False # 清除标志
|
||
self._force_attend_after_reservation_back = True # 设置强制参与标志
|
||
self._handle_reservation_direct_attend()
|
||
else:
|
||
# 查找福袋失败,保留标志,下一轮继续尝试
|
||
try:
|
||
self._reservation_back_direct_attend = True # 恢复标志
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
|
||
flag_restored=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 其他阶段,保留标志,下一轮继续尝试
|
||
try:
|
||
self._reservation_back_direct_attend = True # 恢复标志
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到其他阶段,保留直接参与标志,下一轮继续尝试",
|
||
stage=stage,
|
||
flag_restored=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(预约回退直接参与)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
|
||
# 检查是否所有预约已完成,需要重置到第一个直播间
|
||
if self.queue_full_waiting_at_earliest and not self.reservations:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 所有预约已完成,重置到第一个直播间",
|
||
)
|
||
except Exception:
|
||
pass
|
||
self.queue_full_waiting_at_earliest = False
|
||
self.reservation_focus_until_ts = 0.0
|
||
# 回退到第一个直播间:需要回退 room_pos 次
|
||
try:
|
||
current_pos = int(getattr(self, "room_pos", 0) or 0)
|
||
back_times = abs(current_pos)
|
||
# 防止无限循环:最大回退次数限制为100
|
||
if back_times > 100:
|
||
back_times = 100
|
||
if back_times > 0:
|
||
for i in range(back_times):
|
||
_swipe_down_once()
|
||
self.operation.delay(0.6)
|
||
self.room_pos = 0
|
||
if hasattr(self, "_swipe_times"):
|
||
self._swipe_times = 0
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 已回退到第一个直播间",
|
||
back_times=back_times,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
return
|
||
|
||
# 单间模式(needswitch=False)下不启用预约回退逻辑
|
||
# 因为单间模式不会切换直播间,不需要回退,预约会在当前直播间自动识别和参与
|
||
try:
|
||
needswitch_cfg = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch_cfg = True
|
||
|
||
# 添加详细的调试日志,确认 needswitch 的值和预约信息
|
||
try:
|
||
# 输出第一个预约的详细信息
|
||
first_reservation_info = {}
|
||
if self.reservations and len(self.reservations) > 0:
|
||
first_r = self.reservations[0]
|
||
try:
|
||
ft = float(first_r.get("future_ts") or 0)
|
||
from datetime import datetime
|
||
import time as time_module
|
||
now_ts = time_module.time()
|
||
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
|
||
remain_seconds = int(ft - now_ts) if ft > 0 else 0
|
||
first_reservation_info = {
|
||
"future_ts": int(ft) if ft > 0 else 0,
|
||
"future_str": ft_str,
|
||
"value": float(first_r.get("prize_value_yuan", 0)),
|
||
"pos_seen": int(first_r.get("pos_seen", 0)),
|
||
"remain_seconds": remain_seconds,
|
||
"current_room_pos": int(getattr(self, "room_pos", 0) or 0),
|
||
}
|
||
except Exception:
|
||
pass
|
||
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] run_once_basic:检查预约回退条件",
|
||
needswitch_cfg=needswitch_cfg,
|
||
reservations_count=(
|
||
len(self.reservations) if self.reservations else 0
|
||
),
|
||
first_reservation=first_reservation_info,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
if needswitch_cfg:
|
||
# 多间模式:需要回退到预约直播间
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 多间模式:开始调用 process_reservation_attend_window",
|
||
reservations_count=len(self.reservations) if self.reservations else 0,
|
||
room_pos=int(getattr(self, "room_pos", 0) or 0),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
preempted = (
|
||
douyin_reservation_logic.process_reservation_attend_window(
|
||
analyser=self,
|
||
reservations=self.reservations,
|
||
room_pos=int(getattr(self, "room_pos", 0) or 0),
|
||
reservation_focus_until_ts_ref=focus_ref,
|
||
reservation_after_action_pending_ref=after_action_ref,
|
||
reservation_back_swipe_delay_s=float(
|
||
self.reservation_back_swipe_delay or 0.6
|
||
),
|
||
swipe_down_back_callback=_swipe_down_once,
|
||
seek_reservation_room_callback=_seek_reservation_room,
|
||
sort_reservations_callback=_sort_reservations,
|
||
write_state_callback=_write_state,
|
||
)
|
||
)
|
||
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] process_reservation_attend_window 返回结果",
|
||
preempted=preempted,
|
||
focus_until=int(focus_ref[0]) if focus_ref and focus_ref[0] > 0 else 0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 同步回写 ref 值
|
||
if focus_ref:
|
||
self.reservation_focus_until_ts = float(focus_ref[0] or 0.0)
|
||
if after_action_ref:
|
||
self.reservation_after_action_pending = bool(
|
||
after_action_ref[0]
|
||
)
|
||
|
||
if preempted:
|
||
# 已触发预约回退,设置标志:下一轮直接参与,跳过详情识别
|
||
try:
|
||
self._reservation_back_direct_attend = True
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退成功,设置直接参与标志(跳过详情识别)",
|
||
flag_set=True,
|
||
next_round_will_check="下一轮将检查此标志并直接参与",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(预约回退)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
else:
|
||
# 单间模式:不需要回退,预约会在当前直播间自动识别和参与
|
||
# 只需要清理过期的预约
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与",
|
||
reservations_count=len(self.reservations) if self.reservations else 0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
import douyin_reservation_logic
|
||
|
||
douyin_reservation_logic.cleanup_expired_reservations(
|
||
self, self.reservations, _write_state
|
||
)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 单间模式下清理过期预约时出错",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后)
|
||
skip_stage_diagnosis = getattr(
|
||
self, "_skip_stage_diagnosis_and_find_fudai", False
|
||
)
|
||
if skip_stage_diagnosis:
|
||
try:
|
||
self._skip_stage_diagnosis_and_find_fudai = False # 清除标志
|
||
self._log_kv("流程", "点击参与抽奖后,跳过阶段检测,直接查找福袋")
|
||
except Exception:
|
||
pass
|
||
# 直接查找福袋,跳过阶段检测
|
||
self._handle_live_room_has_or_not_fudai()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(跳过阶段检测)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
|
||
# 1. 截图 + 阶段诊断
|
||
screenshot_start = time.time()
|
||
ok = self.operation.get_screenshot(self.device_id)
|
||
screenshot_elapsed = time.time() - screenshot_start
|
||
if not ok:
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"截图",
|
||
"获取截图失败",
|
||
ok=0,
|
||
elapsed_seconds=round(elapsed, 2),
|
||
screenshot_elapsed_seconds=round(screenshot_elapsed, 2),
|
||
)
|
||
return
|
||
|
||
stage, seen = self._diagnose_stage_from_current_screen()
|
||
self._last_diag_stage = stage
|
||
self._last_diag_seen = seen
|
||
self._last_diag_ts = time.time()
|
||
# 简洁输出阶段诊断结果(不额外添加分隔符,避免日志噪音)
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"截图",
|
||
"截图+阶段诊断",
|
||
stage=stage,
|
||
seen=seen,
|
||
elapsed_seconds=round(elapsed, 2),
|
||
screenshot_elapsed_seconds=round(screenshot_elapsed, 2),
|
||
)
|
||
|
||
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
|
||
try:
|
||
top_pkg = ""
|
||
try:
|
||
top_pkg = self.operation.get_top_package(self.device_id) or ""
|
||
self._log_kv("自救", "桌面检测:获取前台包名", top_pkg=top_pkg)
|
||
except Exception as e:
|
||
top_pkg = ""
|
||
self._log_kv("自救", "桌面检测:获取前台包名失败", error=str(e))
|
||
|
||
# 如果获取到包名且不是抖音相关包,说明可能在桌面或其他应用
|
||
is_douyin_pkg = (
|
||
top_pkg
|
||
and (
|
||
"aweme" in top_pkg
|
||
or "douyin" in top_pkg
|
||
or "com.ss.android.ugc" in top_pkg
|
||
)
|
||
)
|
||
|
||
if top_pkg and not is_douyin_pkg:
|
||
self._log_kv(
|
||
"自救",
|
||
"桌面检测:检测到不在抖音前台",
|
||
top_pkg=top_pkg,
|
||
is_douyin=False,
|
||
)
|
||
try:
|
||
self._log_kv(
|
||
"自救",
|
||
"发现前台包不在抖音,尝试恢复进入直播间",
|
||
top_pkg=top_pkg,
|
||
)
|
||
# 直接点击桌面图标的预设坐标
|
||
try:
|
||
self.click(int(self.desktop_icon_x), int(self.desktop_icon_y))
|
||
except Exception:
|
||
# 退化为默认硬编码位置
|
||
self.click(153, 260)
|
||
self.operation.delay(2)
|
||
|
||
# 点击直播与进入直播间的备用坐标
|
||
try:
|
||
lx = int(self.yanghao_fallback_live_x)
|
||
ly = int(self.yanghao_fallback_live_y)
|
||
self._log_kv("自救", "点击直播按钮", x=lx, y=ly)
|
||
self.click(lx, ly)
|
||
self.operation.delay(1.5)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
ex = int(self.yanghao_fallback_enter_live_x)
|
||
ey = int(self.yanghao_fallback_enter_live_y)
|
||
self._log_kv("自救", "点击进入直播间", x=ex, y=ey, 次数=2)
|
||
self.click(ex, ey)
|
||
self.operation.delay(0.6)
|
||
self.click(ex, ey)
|
||
self.operation.delay(2.0)
|
||
except Exception:
|
||
pass
|
||
# 自救完成后,不在这里结束本轮流程,而是立即重新执行一次主流程:
|
||
# 重新截图 + 阶段诊断 + 查找福袋,使流程与正常进入直播间路径保持一致
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic:自救完成,立即重新执行一次主流程",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 为避免递归过深,仅在当前检测到不在抖音前台的场景下递归一次;
|
||
# 自救完成后前台包名应为抖音,下一次 run_once_basic 将不会再次进入自救分支。
|
||
try:
|
||
self.operation.delay(0.5)
|
||
except Exception:
|
||
time.sleep(0.5)
|
||
self.run_once_basic()
|
||
return
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv("自救", "恢复失败", error=str(e), error_type=type(e).__name__)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
# 桌面检测本身出错,记录日志
|
||
try:
|
||
self._log_kv("自救", "桌面检测异常", error=str(e), error_type=type(e).__name__)
|
||
except Exception:
|
||
pass
|
||
|
||
# 2. 诊断后分支(弹窗检测已合并到阶段诊断中)
|
||
# 处理弹窗阶段
|
||
if stage == "COUPON_POPUP":
|
||
# 优惠券弹窗:按返回键关闭
|
||
self._log_kv("弹窗处理", "检测到优惠券弹窗,按返回键关闭")
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(0.5)
|
||
self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗")
|
||
except Exception as e:
|
||
self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e))
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理优惠券弹窗)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif stage == "SHOPPING_REDPACKET_POPUP":
|
||
# 购物红包弹窗:点击关闭按钮
|
||
self._log_kv("弹窗处理", "检测到购物红包弹窗,点击关闭按钮")
|
||
try:
|
||
close_x = int(530 * self.resolution_ratio_x // 1080)
|
||
close_y = int(1647 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, close_x, close_y)
|
||
self.operation.delay(0.5)
|
||
self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y)
|
||
except Exception as e:
|
||
self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e))
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理购物红包弹窗)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif stage == "FANSCLUB_JOIN":
|
||
# 粉丝团加入阶段:先点击参与按钮,再点击两次预设位置,最后关闭详情页
|
||
self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理")
|
||
try:
|
||
# 第一步:先点击参与按钮(基于截图优化坐标:OCR区域(306,2030)-(780,2110),区域中心(543, 2070))
|
||
attend_x = int(543 * self.resolution_ratio_x // 1080)
|
||
attend_y = int(2070 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, attend_x, attend_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"先点击参与按钮",
|
||
x=attend_x,
|
||
y=attend_y,
|
||
base_x=543,
|
||
base_y=2070,
|
||
region="(306,2030)-(780,2110)",
|
||
)
|
||
self.operation.delay(0.5) # 等待参与按钮响应
|
||
|
||
# 第二步:点击两次预设位置(527, 567)
|
||
preset_x = int(527 * self.resolution_ratio_x // 1080)
|
||
preset_y = int(567 * self.resolution_ratio_y // 2400)
|
||
|
||
# 第一次点击预设位置
|
||
self.operation.click(self.device_id, preset_x, preset_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"第一次点击预设位置",
|
||
x=preset_x,
|
||
y=preset_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(0.5) # 短暂等待后立即第二次点击
|
||
|
||
# 第二次点击预设位置
|
||
self.operation.click(self.device_id, preset_x, preset_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"第二次点击预设位置",
|
||
x=preset_x,
|
||
y=preset_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(1.0) # 等待点击完成
|
||
|
||
# 第三步:关闭详情页(点击详情页旁边位置)
|
||
close_x = int(500 * self.resolution_ratio_x // 1080)
|
||
close_y = int(470 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, close_x, close_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"关闭详情页",
|
||
x=close_x,
|
||
y=close_y,
|
||
base_x=500,
|
||
base_y=470,
|
||
)
|
||
self.operation.delay(1.0) # 等待关闭完成
|
||
except Exception as e:
|
||
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(e))
|
||
|
||
# 如果启用了自动加入,等待页面加载后再次点击(如果需要)
|
||
if getattr(self, "auto_join_fansclub", False):
|
||
self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载")
|
||
self.operation.delay(1.0)
|
||
# 再次诊断阶段,看是否还在粉丝团加入页
|
||
try:
|
||
stage_after, seen_after = (
|
||
self._diagnose_stage_from_current_screen()
|
||
)
|
||
if stage_after == "FANSCLUB_JOIN":
|
||
# 仍在粉丝团加入页,再次点击(连续点击两次)
|
||
# 使用预设位置坐标(527, 567)
|
||
preset_x = int(527 * self.resolution_ratio_x // 1080)
|
||
preset_y = int(567 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, preset_x, preset_y)
|
||
self._log_kv(
|
||
"粉丝团处理", "仍在粉丝团加入页,再次第一次点击",
|
||
x=preset_x,
|
||
y=preset_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(0.5)
|
||
self.operation.click(self.device_id, preset_x, preset_y)
|
||
self._log_kv(
|
||
"粉丝团处理", "仍在粉丝团加入页,再次第二次点击",
|
||
x=preset_x,
|
||
y=preset_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(2.0)
|
||
|
||
# 加入粉丝团成功后,点击 (527, 567) 返回直播间
|
||
try:
|
||
return_x = int(527 * self.resolution_ratio_x // 1080)
|
||
return_y = int(567 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, return_x, return_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"加入粉丝团成功后,点击返回直播间",
|
||
x=return_x,
|
||
y=return_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(1.0) # 等待返回完成
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"粉丝团处理", "点击返回直播间失败", error=str(e)
|
||
)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"未启用自动加入粉丝团,等待手动确认",
|
||
wait_seconds=15,
|
||
)
|
||
self.operation.delay(15.0)
|
||
|
||
# 未启用自动加入时,也需要在等待后点击返回
|
||
# 加入粉丝团成功后,点击 (527, 567) 返回直播间
|
||
try:
|
||
return_x = int(527 * self.resolution_ratio_x // 1080)
|
||
return_y = int(567 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, return_x, return_y)
|
||
self._log_kv(
|
||
"粉丝团处理",
|
||
"加入粉丝团成功后,点击返回直播间",
|
||
x=return_x,
|
||
y=return_y,
|
||
base_x=527,
|
||
base_y=567,
|
||
)
|
||
self.operation.delay(1.0) # 等待返回完成
|
||
except Exception as e:
|
||
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(e))
|
||
|
||
# 延迟后返回,让主循环继续处理
|
||
self.operation.delay(0.5)
|
||
|
||
# 如果失败,根据配置决定是否切换直播间
|
||
fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay")
|
||
if fansclub_fail_action == "switch":
|
||
self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间")
|
||
try:
|
||
self.swipe_up_to_next_live()
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理粉丝团)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif stage == "FUDai_DETAIL":
|
||
# 已经在详情页:检查是否是预约回退后的直接参与
|
||
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到福袋详情页,检查预约回退直接参与标志",
|
||
stage=stage,
|
||
reservation_direct_attend=reservation_direct_attend,
|
||
)
|
||
except Exception:
|
||
pass
|
||
if reservation_direct_attend:
|
||
# 预约回退后直接参与:使用正常流程,但设置强制参与标志
|
||
try:
|
||
self._reservation_back_direct_attend = False # 清除标志
|
||
# 设置强制参与标志,让 basic_join_decision 跳过倒计时检查
|
||
self._force_attend_after_reservation_back = True
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:使用正常流程,设置强制参与标志",
|
||
flag_cleared=True,
|
||
force_attend=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 使用正常流程处理
|
||
self._handle_reservation_direct_attend()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(预约回退直接参与)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
else:
|
||
# 正常流程:读详情并决定是否参与
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退直接参与标志为False,执行正常流程",
|
||
reservation_direct_attend=reservation_direct_attend,
|
||
)
|
||
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"):
|
||
# 在直播间:检查是否是预约回退后的直接参与
|
||
reservation_direct_attend = getattr(self, "_reservation_back_direct_attend", False)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 检测到直播间,检查预约回退直接参与标志",
|
||
stage=stage,
|
||
reservation_direct_attend=reservation_direct_attend,
|
||
)
|
||
except Exception:
|
||
pass
|
||
if reservation_direct_attend:
|
||
# 预约回退后直接参与:查找福袋并打开详情页,然后直接参与
|
||
try:
|
||
self._reservation_back_direct_attend = False # 清除标志
|
||
# 设置强制参与标志,让 basic_join_decision 跳过倒计时检查
|
||
self._force_attend_after_reservation_back = True
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:查找福袋并打开详情页,设置强制参与标志",
|
||
flag_cleared=True,
|
||
force_attend=True,
|
||
stage=stage,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 回退后等待页面加载和查找福袋都使用 switch_room_wait_after_stage_diag_seconds 参数
|
||
try:
|
||
wait_seconds = float(
|
||
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0
|
||
)
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后等待页面加载(使用 switch_room_wait_after_stage_diag_seconds)",
|
||
wait_seconds=wait_seconds,
|
||
)
|
||
self.operation.delay(wait_seconds)
|
||
except Exception:
|
||
try:
|
||
time.sleep(7.0)
|
||
except Exception:
|
||
pass
|
||
|
||
# 查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds 作为最大等待时间)
|
||
import douyin_flow_control
|
||
room_pos_ref = [int(getattr(self, "room_pos", 0) or 0)]
|
||
# 临时设置 fudai_icon_max_wait_seconds 为 switch_room_wait_after_stage_diag_seconds
|
||
original_max_wait = None
|
||
try:
|
||
original_max_wait = getattr(self, "fudai_icon_max_wait_seconds", None)
|
||
wait_seconds_for_find = float(
|
||
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0
|
||
)
|
||
self.fudai_icon_max_wait_seconds = wait_seconds_for_find
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 开始查找福袋并打开详情页(使用 switch_room_wait_after_stage_diag_seconds)",
|
||
room_pos=room_pos_ref[0],
|
||
max_wait_seconds=wait_seconds_for_find,
|
||
)
|
||
except Exception:
|
||
pass
|
||
found = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||
# 恢复原始配置
|
||
try:
|
||
if original_max_wait is not None:
|
||
self.fudai_icon_max_wait_seconds = original_max_wait
|
||
elif hasattr(self, "fudai_icon_max_wait_seconds"):
|
||
delattr(self, "fudai_icon_max_wait_seconds")
|
||
except Exception:
|
||
pass
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 查找福袋结果",
|
||
found=found,
|
||
room_pos=room_pos_ref[0],
|
||
)
|
||
except Exception:
|
||
pass
|
||
if found:
|
||
# 成功打开详情页,直接参与
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 成功打开详情页,开始直接参与",
|
||
)
|
||
except Exception:
|
||
pass
|
||
self._handle_reservation_direct_attend()
|
||
else:
|
||
# 查找福袋失败,保留标志,下一轮继续尝试
|
||
try:
|
||
self._reservation_back_direct_attend = True # 恢复标志
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后查找福袋失败,保留直接参与标志,下一轮继续尝试",
|
||
flag_restored=True,
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(预约回退直接参与)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
|
||
# 在直播间:如果刚刚切换了直播间,等待福袋加载
|
||
just_switched = getattr(self, "_just_switched_room", False)
|
||
if just_switched:
|
||
try:
|
||
self._just_switched_room = False # 清除标志
|
||
wait_seconds = float(
|
||
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0)
|
||
or 7.0
|
||
)
|
||
if wait_seconds > 0:
|
||
self._log_kv(
|
||
"流程",
|
||
"切换直播间后,阶段检测完成,等待福袋加载",
|
||
wait_seconds=wait_seconds,
|
||
)
|
||
self.operation.delay(wait_seconds)
|
||
except Exception as e:
|
||
try:
|
||
self._just_switched_room = False # 确保清除标志
|
||
self._log_kv("流程", "等待福袋加载时出错", error=str(e))
|
||
except Exception:
|
||
pass
|
||
|
||
# 在直播间:寻找福袋图标并尝试点开
|
||
self._handle_live_room_has_or_not_fudai()
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理直播间)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
|
||
# 处理推荐/关注/直播列表页:回到直播间或切换
|
||
if stage == "RECOMMEND_PAGE":
|
||
# 识别到推荐页面:直接点击进入直播页,然后点击进入直播间
|
||
self._log_kv(
|
||
"流程",
|
||
"检测到推荐页面,点击进入直播页并进入直播间",
|
||
stage=stage,
|
||
seen=seen,
|
||
)
|
||
try:
|
||
# 直接点击 (718, 169) 进入直播页 - 基于1080x2400分辨率
|
||
live_tab_x = int(718 * self.resolution_ratio_x // 1080)
|
||
live_tab_y = int(169 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, live_tab_x, live_tab_y)
|
||
self._log_kv("流程", "点击进入直播页", x=live_tab_x, y=live_tab_y)
|
||
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
|
||
|
||
# 点击进入直播间的位置 (103, 382),连点两次
|
||
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
|
||
enter_live_y = int(382 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self.operation.delay(self.ENTER_LIVE_CLICK_DELAY)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self._log_kv(
|
||
"流程",
|
||
"点击进入直播间位置",
|
||
x=enter_live_x,
|
||
y=enter_live_y,
|
||
次数=2,
|
||
)
|
||
self.operation.delay(self.ENTER_LIVE_FINAL_DELAY)
|
||
except Exception as e:
|
||
self._log_kv("流程", "处理推荐页面时出错", error=str(e))
|
||
# 如果出错,尝试回退
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(1.0)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 其他列表页:使用原有逻辑
|
||
douyin_live_room.reflash_zhibo(self)
|
||
elif stage == "FUDai_RESULT":
|
||
# 抽奖结果弹窗:处理开奖结果(使用OCR识别,不使用阶段诊断)
|
||
# 清除等待开奖标志
|
||
self._waiting_for_lottery_result = False
|
||
|
||
self._log_kv("开奖结果", "检测到抽奖结果弹窗,使用OCR识别处理")
|
||
# 直接OCR识别并处理
|
||
result = self._check_lottery_result_by_ocr()
|
||
if result:
|
||
self._handle_lottery_result_by_ocr(result)
|
||
else:
|
||
# OCR识别失败,使用返回键关闭
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(0.5)
|
||
self.swipe_up_to_next_live()
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"run_once_basic完成(处理开奖结果)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
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识别开奖结果按钮区域,返回识别到的文本类型。
|
||
|
||
返回:
|
||
"我知道了" - 识别到"我知道了"按钮
|
||
"立即领取奖品" - 识别到"立即领取奖品"按钮
|
||
None - 未识别到相关文本
|
||
"""
|
||
try:
|
||
# OCR区域:(175, 1267) 到 (890, 1377)
|
||
# 裁剪区域用于OCR识别(通过cut_pic会自动保存到debug_captures)
|
||
self.cut_pic(175, 1267, 890, 1377, "", "开奖结果按钮", 0)
|
||
|
||
# OCR识别
|
||
ocr_text = str(self.operation.analyse_pic_word("开奖结果按钮", 0) or "")
|
||
|
||
self._log_kv("开奖结果", "OCR识别结果", text=ocr_text)
|
||
|
||
# 检查识别到的文本
|
||
if "我知道了" in ocr_text:
|
||
return "我知道了"
|
||
elif (
|
||
"立即领取奖品" in ocr_text
|
||
or "领取奖品" in ocr_text
|
||
or "立即领取" in ocr_text
|
||
):
|
||
return "立即领取奖品"
|
||
else:
|
||
# 尝试模式1识别
|
||
ocr_text_1 = str(
|
||
self.operation.analyse_pic_word("开奖结果按钮", 1) or ""
|
||
)
|
||
if "我知道了" in ocr_text_1:
|
||
return "我知道了"
|
||
elif (
|
||
"立即领取奖品" in ocr_text_1
|
||
or "领取奖品" in ocr_text_1
|
||
or "立即领取" in ocr_text_1
|
||
):
|
||
return "立即领取奖品"
|
||
|
||
return None
|
||
except Exception as e:
|
||
self._log_kv("开奖结果", "OCR识别异常", error=str(e))
|
||
return None
|
||
|
||
def _handle_lottery_result_by_ocr(self, result_type: str) -> None:
|
||
"""根据OCR识别结果处理开奖结果。
|
||
|
||
参数:
|
||
result_type: "我知道了" 或 "立即领取奖品"
|
||
"""
|
||
start_time = time.time()
|
||
try:
|
||
if result_type == "我知道了":
|
||
# 识别到"我知道了",点击按钮,切换下一个直播间
|
||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||
# 按钮位置在OCR区域中心附近 (175+890)/2=532, (1267+1377)/2=1322
|
||
btn_x = int(532 * rx // 1080)
|
||
btn_y = int(1322 * ry // 2400)
|
||
|
||
self.operation.click(self.device_id, btn_x, btn_y)
|
||
self._log_kv("开奖结果", "点击我知道了按钮", x=btn_x, y=btn_y)
|
||
self.operation.delay(0.5)
|
||
|
||
# 切换下一个直播间
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
|
||
if needswitch:
|
||
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋")
|
||
self.swipe_up_to_next_live()
|
||
else:
|
||
self._log_kv(
|
||
"开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间"
|
||
)
|
||
|
||
elif result_type == "立即领取奖品":
|
||
# 识别到"立即领取奖品",保存全屏截图到单独文件夹,点击返回键,切换下一个直播间
|
||
try:
|
||
import os
|
||
import shutil
|
||
from datetime import datetime
|
||
|
||
# 确保有最新截图
|
||
self.operation.get_screenshot(self.device_id)
|
||
|
||
base_dir = os.path.dirname(__file__)
|
||
pic_dir = os.path.join(base_dir, "pic")
|
||
src = os.path.join(pic_dir, "screenshot.png")
|
||
|
||
if os.path.exists(src):
|
||
# 创建单独的文件夹保存"立即领取奖品"的截图
|
||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||
os.makedirs(prize_dir, exist_ok=True)
|
||
|
||
# 保存截图,文件名包含时间戳
|
||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
dst = os.path.join(prize_dir, f"prize_{timestamp}.png")
|
||
shutil.copy(src, dst)
|
||
|
||
self._log_kv("开奖结果", "已保存立即领取奖品截图", path=dst)
|
||
except Exception as e:
|
||
self._log_kv("开奖结果", "保存截图失败", error=str(e))
|
||
|
||
# 点击返回键
|
||
self.operation.click_back(self.device_id)
|
||
self._log_kv("开奖结果", "点击返回键关闭开奖结果")
|
||
self.operation.delay(0.5)
|
||
|
||
# 切换下一个直播间
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
|
||
if needswitch:
|
||
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋")
|
||
self.swipe_up_to_next_live()
|
||
else:
|
||
self._log_kv(
|
||
"开奖结果", "处理完开奖结果,未启用切换,继续在当前直播间"
|
||
)
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"开奖结果", "处理开奖结果失败", error=str(e), result_type=result_type
|
||
)
|
||
# 失败时尝试按返回键并切换
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(0.5)
|
||
self.swipe_up_to_next_live()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_lottery_result_by_ocr完成",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
result_type=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)
|
||
"""
|
||
try:
|
||
# 截图
|
||
ok = self.operation.get_screenshot(device_id)
|
||
if not ok:
|
||
self._log_kv(tag, f"{msg} - 获取截图失败", ok=0)
|
||
return
|
||
|
||
# 如果启用诊断,执行阶段诊断
|
||
if diagnose:
|
||
stage, seen = self._diagnose_stage_from_current_screen()
|
||
self._last_diag_stage = stage
|
||
self._last_diag_seen = seen
|
||
self._last_diag_ts = time.time()
|
||
# 使用位置参数调用,避免与关键字参数冲突
|
||
self._log_kv(tag, msg, **{"stage": stage, "seen": seen})
|
||
else:
|
||
self._log_kv(tag, msg)
|
||
except Exception as e:
|
||
# 避免异常影响主流程
|
||
try:
|
||
self._log_kv(tag, f"{msg} - 异常: {type(e).__name__}")
|
||
except Exception:
|
||
pass
|
||
|
||
# ========== 基础动作封装 ==========
|
||
def swipe_up_to_next_live(self) -> None:
|
||
"""上滑切换直播间(简单版封装)。
|
||
|
||
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
|
||
则不允许上划离开预约直播间,直接返回。
|
||
"""
|
||
# 检查是否在预约锁定期内
|
||
try:
|
||
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
|
||
now_ts = time.time()
|
||
if focus_until > 0 and now_ts < focus_until:
|
||
# 在锁定期内,不允许上划离开预约直播间
|
||
remain_seconds = int(focus_until - now_ts)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 锁定期内不允许上划离开预约直播间",
|
||
focus_until=int(focus_until),
|
||
remain_seconds=remain_seconds,
|
||
queue_full_waiting=getattr(self, "queue_full_waiting_at_earliest", False),
|
||
)
|
||
except Exception:
|
||
pass
|
||
return # 直接返回,不执行上划操作
|
||
except Exception:
|
||
# 如果检查锁定期时出错,继续执行上划(避免因异常导致无法切换)
|
||
pass
|
||
|
||
start_time = time.time()
|
||
douyin_swipe_ops.swipe_up_switch_live(self)
|
||
# 记录直播间位置:上滑 +1
|
||
try:
|
||
self.room_pos += 1
|
||
except Exception:
|
||
self.room_pos = 0
|
||
elapsed = time.time() - start_time
|
||
self._log_kv("操作", "上滑切换直播间", elapsed_seconds=round(elapsed, 2))
|
||
|
||
# 记录滑动次数(用于滑动次数重置功能)
|
||
try:
|
||
if not hasattr(self, "_swipe_times"):
|
||
self._swipe_times = 0
|
||
self._swipe_times += 1
|
||
except Exception:
|
||
pass
|
||
|
||
# 检查是否需要重置(滑动次数达到阈值)
|
||
try:
|
||
self._maybe_reset_after_swipes()
|
||
except Exception:
|
||
pass
|
||
|
||
# 设置标志:刚刚切换了直播间,阶段检测后需要等待福袋加载
|
||
try:
|
||
self._just_switched_room = True
|
||
except Exception:
|
||
pass
|
||
|
||
# 清除第一次读取标志,确保新直播间的福袋会进行完整的OCR识别
|
||
try:
|
||
self._fudai_detail_first_read = False
|
||
self._last_fudai_detail_tuple = None
|
||
except Exception:
|
||
pass
|
||
|
||
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
|
||
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
|
||
try:
|
||
skip_record = bool(getattr(self, "_skip_record_title_during_seek", False))
|
||
if not skip_record:
|
||
self._record_room_title_and_pos()
|
||
except Exception:
|
||
pass
|
||
|
||
def _return_to_recommend_and_reenter_live(self) -> None:
|
||
"""返回推荐页面并重新进入直播间。
|
||
|
||
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
|
||
"""
|
||
self._log_kv("超时", "开始返回推荐页面")
|
||
|
||
# 多次点击返回键,直到到达推荐页面
|
||
max_back_clicks = self.MAX_BACK_CLICKS_TO_RECOMMEND
|
||
for i in range(max_back_clicks):
|
||
try:
|
||
# 截图并诊断当前阶段
|
||
ok = self.operation.get_screenshot(self.device_id)
|
||
if not ok:
|
||
self._log_kv("超时", f"获取截图失败 ({i+1}/{max_back_clicks})")
|
||
# 即使截图失败,也尝试点击返回键
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
|
||
continue
|
||
|
||
# 诊断当前阶段
|
||
stage, seen = self._diagnose_stage_from_current_screen()
|
||
|
||
# 如果已经在推荐页面,跳出循环
|
||
if stage == "RECOMMEND_PAGE":
|
||
self._log_kv("超时", f"已到达推荐页面 ({i+1}次返回键)")
|
||
break
|
||
|
||
# 点击返回键
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
|
||
|
||
if i == max_back_clicks - 1:
|
||
self._log_kv(
|
||
"超时", f"已点击{max_back_clicks}次返回键,可能未到达推荐页面"
|
||
)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
f"返回推荐页面时出错 ({i+1}/{max_back_clicks})",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 继续尝试点击返回键
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
|
||
except Exception as e:
|
||
# 记录异常但继续执行
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
"点击返回键失败但继续",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass # 日志系统本身出错时忽略
|
||
|
||
# 等待页面稳定
|
||
self.operation.delay(self.PAGE_STABLE_DELAY)
|
||
|
||
# 再次截图确认当前阶段
|
||
try:
|
||
ok = self.operation.get_screenshot(self.device_id)
|
||
if ok:
|
||
stage, seen = self._diagnose_stage_from_current_screen()
|
||
self._log_kv("超时", "确认当前阶段", stage=stage, seen=seen)
|
||
except Exception as e:
|
||
# 记录异常但继续执行(阶段诊断失败不影响主流程)
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
"确认阶段时出错但继续",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass # 日志系统本身出错时忽略
|
||
|
||
# 点击关注标签并进入直播间(复用现有逻辑)
|
||
try:
|
||
# 点击关注标签 (709, 169) - 基于1080x2400分辨率
|
||
follow_tab_x = int(709 * self.resolution_ratio_x // 1080)
|
||
follow_tab_y = int(169 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, follow_tab_x, follow_tab_y)
|
||
self._log_kv("超时", "点击关注标签", x=follow_tab_x, y=follow_tab_y)
|
||
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
|
||
|
||
# 点击进入直播间的位置 (103, 385),连点两次
|
||
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
|
||
enter_live_y = int(385 * self.resolution_ratio_y // 2400)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self.operation.delay(self.ENTER_LIVE_CLICK_DELAY)
|
||
self.operation.click(self.device_id, enter_live_x, enter_live_y)
|
||
self._log_kv(
|
||
"超时",
|
||
"点击进入直播间位置",
|
||
x=enter_live_x,
|
||
y=enter_live_y,
|
||
次数=2,
|
||
)
|
||
self.operation.delay(self.ENTER_LIVE_FINAL_DELAY)
|
||
|
||
self._log_kv("超时", "已重新进入直播间")
|
||
|
||
# 重置超时相关时间戳(在成功重新进入直播间后重置,避免立即再次触发)
|
||
try:
|
||
self._last_successful_attend_ts = time.time()
|
||
self._run_start_ts = time.time()
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
"重置时间戳时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass # 日志系统本身出错时忽略
|
||
except Exception as e:
|
||
# 记录异常但继续执行
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
"重新进入直播间时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
except Exception:
|
||
pass # 日志系统本身出错时忽略
|
||
# 如果出错,尝试回退
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(self.BACK_KEY_CLICK_DELAY)
|
||
except Exception as e2:
|
||
try:
|
||
self._log_kv(
|
||
"超时",
|
||
"回退操作失败",
|
||
error=str(e2),
|
||
error_type=type(e2).__name__,
|
||
)
|
||
except Exception:
|
||
pass # 日志系统本身出错时忽略
|
||
|
||
def swipe_down_back_from_live(self) -> None:
|
||
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。"""
|
||
start_time = time.time()
|
||
try:
|
||
douyin_swipe_ops.swipe_down_back_live(self)
|
||
except Exception:
|
||
# 若子模块未实现,则退化为点击返回键
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
except Exception:
|
||
pass
|
||
# 记录直播间位置:下滑/回退 -1
|
||
try:
|
||
self.room_pos -= 1
|
||
except Exception:
|
||
self.room_pos = 0
|
||
|
||
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
|
||
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
|
||
try:
|
||
skip_record = bool(getattr(self, "_skip_record_title_during_seek", False))
|
||
if not skip_record:
|
||
self._record_room_title_and_pos()
|
||
except Exception:
|
||
pass
|
||
|
||
def _maybe_reset_after_swipes(self) -> int:
|
||
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
|
||
|
||
返回:
|
||
重置后的滑动次数(通常为0)
|
||
"""
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
if not needswitch:
|
||
return getattr(self, "_swipe_times", 0)
|
||
|
||
if not bool(getattr(self, "reset_after_swipes_enabled", False)):
|
||
return getattr(self, "_swipe_times", 0)
|
||
|
||
try:
|
||
swipe_times = int(getattr(self, "_swipe_times", 0) or 0)
|
||
except Exception:
|
||
swipe_times = 0
|
||
|
||
threshold = max(1, int(self.reset_after_swipes or 0))
|
||
if swipe_times < threshold:
|
||
return swipe_times
|
||
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"已切换直播间{}次,达到阈值{}:向上回退到第一个直播间".format(
|
||
swipe_times, threshold
|
||
),
|
||
swipe_times=swipe_times,
|
||
threshold=threshold,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退次数按当前已切换次数来(更符合"回到本轮第一个直播间"的语义)
|
||
back_times = int(swipe_times)
|
||
# 防止无限循环:最大回退次数限制为100
|
||
if back_times > 100:
|
||
back_times = 100
|
||
if back_times <= 0:
|
||
return 0
|
||
|
||
# 向上回退:从上往下滑动(与上划切换相反方向)
|
||
try:
|
||
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
|
||
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
|
||
except Exception:
|
||
rx, ry = 1080, 2400
|
||
|
||
for i in range(back_times):
|
||
try:
|
||
# 向上回退:从上往下滑动(start_y < end_y)
|
||
start_x = 760 * rx // 1080
|
||
start_y = 800 * ry // 2400 # 上方起始位置
|
||
end_x = 760 * rx // 1080
|
||
end_y = 1600 * ry // 2400 # 下方结束位置
|
||
# 直接使用 ADB 内部滑动命令
|
||
try:
|
||
import subprocess
|
||
if hasattr(self.operation, '_adb'):
|
||
adb_cmd = self.operation._adb()
|
||
else:
|
||
import os
|
||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
|
||
adb_cmd = f'"{adb_cmd}"'
|
||
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 200"
|
||
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||
except Exception:
|
||
# 回退到 operation.swipe
|
||
self.operation.swipe(self.device_id, start_x, start_y, end_x, end_y, 200)
|
||
try:
|
||
self._log_kv("流程", "回退直播间 {}/{}".format(i + 1, back_times))
|
||
except Exception:
|
||
pass
|
||
self.operation.delay(2)
|
||
except Exception:
|
||
pass
|
||
|
||
# 回到第一个后,计数归零
|
||
self.operation.delay(3)
|
||
try:
|
||
self._swipe_times = 0
|
||
self.room_pos = 0
|
||
except Exception:
|
||
pass
|
||
return 0
|
||
|
||
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
|
||
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
|
||
|
||
说明:
|
||
- 使用 high_value_fudai_max_swipe_back 约束最大回退次数;
|
||
- 如果启用了回退校验,会进行详细校验(直播间名、福袋详情匹配)。
|
||
"""
|
||
try:
|
||
target_pos = int(item.get("pos_seen") or 0)
|
||
except Exception:
|
||
target_pos = 0
|
||
try:
|
||
cur_pos = int(getattr(self, "room_pos", 0) or 0)
|
||
except Exception:
|
||
cur_pos = 0
|
||
|
||
# 计算需要切换的次数和方向
|
||
# room_pos 越大表示越靠下,越小表示越靠上
|
||
# 如果 target_pos < cur_pos,说明目标在上方,需要向上回退(使用 swipe_down_back_from_live,room_pos 减少)
|
||
# 如果 target_pos > cur_pos,说明目标在下方,需要向下切换(使用 swipe_up_to_next_live,room_pos 增加)
|
||
# 注意:pos_diff = target_pos - cur_pos
|
||
# - 如果 pos_diff < 0,说明 target_pos < cur_pos,目标在上方,需要向上回退(减少 room_pos)
|
||
# - 如果 pos_diff > 0,说明 target_pos > cur_pos,目标在下方,需要向下切换(增加 room_pos)
|
||
# 注意:如果预先下滑了一次(在 process_reservation_attend_window 中),cur_pos 已经减1了
|
||
# 但这是为了确保在直播列表中,不影响回退次数的计算,因为回退次数是基于实际的位置差计算的
|
||
pos_diff = target_pos - cur_pos
|
||
|
||
try:
|
||
max_back = int(getattr(self, "high_value_fudai_max_swipe_back", 60) or 60)
|
||
except Exception:
|
||
max_back = 60
|
||
# 防止无限循环:最大回退次数限制为100
|
||
if max_back > 100:
|
||
max_back = 100
|
||
if max_back < 0:
|
||
max_back = 0
|
||
|
||
# 获取目标直播间名字
|
||
target_room_title = str(item.get("room_title") or "").strip()
|
||
target_room_title_raw = str(item.get("room_title_raw") or "").strip()
|
||
|
||
# 输出目标直播间的位置和标题信息
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room:开始回退到目标直播间",
|
||
target_room_title=target_room_title,
|
||
target_room_title_raw=target_room_title_raw,
|
||
target_pos=target_pos,
|
||
current_room_pos=cur_pos,
|
||
target_room_info=f"位置={target_pos}, 标题={target_room_title or target_room_title_raw}",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 计算切换方向和次数",
|
||
current_room_pos=cur_pos,
|
||
target_pos=target_pos,
|
||
pos_diff=pos_diff,
|
||
direction="向上回退" if pos_diff < 0 else "向下切换" if pos_diff > 0 else "已在目标位置",
|
||
target_room_title=target_room_title,
|
||
target_room_title_raw=target_room_title_raw,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
if pos_diff == 0:
|
||
# 已在目标位置,但仍需校验
|
||
pass
|
||
elif pos_diff < 0:
|
||
# 目标在上方(target_pos < cur_pos),需要向上回退(减少 room_pos)
|
||
# 使用 swipe_down_back_from_live(),它会执行 room_pos -= 1
|
||
# 注意:如果预先下滑了一次(在 process_reservation_attend_window 中),cur_pos 已经减1了
|
||
# 这会导致 pos_diff 的计算少1,所以需要补偿:back_times = abs(pos_diff) + 1
|
||
# 但实际上,预先下滑是为了确保在直播列表中,不应该影响回退次数
|
||
# 所以如果预先下滑了,pos_diff 已经包含了这个影响,直接使用 abs(pos_diff) 即可
|
||
# 但为了确保回退到正确位置,如果 pos_diff < 0,需要回退 abs(pos_diff) 次
|
||
back_times = min(abs(pos_diff), max_back) if max_back > 0 else abs(pos_diff)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 向上回退(目标在上方)",
|
||
back_times=back_times,
|
||
current_room_pos=cur_pos,
|
||
target_pos=target_pos,
|
||
pos_diff=pos_diff,
|
||
target_room_title=target_room_title,
|
||
target_room_title_raw=target_room_title_raw,
|
||
)
|
||
except Exception:
|
||
pass
|
||
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
|
||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||
try:
|
||
self._skip_record_title_during_seek = True
|
||
except Exception:
|
||
pass
|
||
for _ in range(back_times):
|
||
self.swipe_down_back_from_live()
|
||
try:
|
||
self.operation.delay(delay_s)
|
||
except Exception:
|
||
time.sleep(delay_s)
|
||
# 清除标志
|
||
try:
|
||
self._skip_record_title_during_seek = False
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 目标在下方(target_pos > cur_pos),需要向下切换(增加 room_pos)
|
||
# 使用 swipe_up_to_next_live(),它会执行 room_pos += 1
|
||
forward_times = min(pos_diff, max_back) if max_back > 0 else pos_diff
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 向下切换(目标在下方)",
|
||
forward_times=forward_times,
|
||
current_room_pos=cur_pos,
|
||
target_pos=target_pos,
|
||
pos_diff=pos_diff,
|
||
target_room_title=target_room_title,
|
||
target_room_title_raw=target_room_title_raw,
|
||
)
|
||
except Exception:
|
||
pass
|
||
delay_s = float(getattr(self, "reservation_back_swipe_delay", 0.6) or 0.6)
|
||
# 回退时设置标志,跳过记录标题(因为之前已经记录过了)
|
||
try:
|
||
self._skip_record_title_during_seek = True
|
||
except Exception:
|
||
pass
|
||
for _ in range(forward_times):
|
||
self.swipe_up_to_next_live()
|
||
try:
|
||
self.operation.delay(delay_s)
|
||
except Exception:
|
||
time.sleep(delay_s)
|
||
# 清除标志
|
||
try:
|
||
self._skip_record_title_during_seek = False
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退完成后记录日志
|
||
try:
|
||
current_room_pos_after = int(getattr(self, "room_pos", cur_pos) or cur_pos)
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 回退完成",
|
||
target_room_title=target_room_title,
|
||
target_room_title_raw=target_room_title_raw,
|
||
target_pos=target_pos,
|
||
current_room_pos=current_room_pos_after,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退完成后,从映射表中读取目标位置的标题进行验证
|
||
# 不需要再次记录标题,因为:
|
||
# 1. 在寻找福袋的过程中已经记录过直播间标题了
|
||
# 2. 回退时只需要滑动到目标位置,不需要再次记录
|
||
# 3. 直接使用映射表中已有的数据验证即可
|
||
try:
|
||
room_pos_map = getattr(self, "_room_pos_to_title_map", {})
|
||
if target_pos in room_pos_map:
|
||
recorded_title, recorded_title_raw = room_pos_map[target_pos]
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 回退完成,从映射表验证标题",
|
||
target_pos=target_pos,
|
||
target_room_title=target_room_title[:50] if target_room_title else "",
|
||
recorded_room_title=recorded_title[:50] if recorded_title else "",
|
||
title_match=(target_room_title in recorded_title) or (recorded_title in target_room_title) if (target_room_title and recorded_title) else False,
|
||
)
|
||
except Exception:
|
||
pass
|
||
else:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] _seek_reservation_room 回退完成,但映射表中未找到目标位置",
|
||
target_pos=target_pos,
|
||
map_size=len(room_pos_map),
|
||
available_positions=list(room_pos_map.keys())[:10] if room_pos_map else [],
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 回退过程中只执行回退操作,不进行校验
|
||
# 校验将在 process_reservation_attend_window 中统一进行,使用映射表中的数据
|
||
return True
|
||
|
||
# ========== 福袋相关 ==========
|
||
def _handle_reservation_direct_attend(self) -> None:
|
||
"""预约回退后直接参与:直接使用预约记录中的详情,跳过OCR识别。"""
|
||
start_time = time.time()
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:使用预约记录中的详情,跳过OCR识别",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 从预约记录中获取详情信息
|
||
if not self.reservations or len(self.reservations) == 0:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:预约队列为空,无法获取详情",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 如果预约队列为空,回退到正常流程
|
||
self._handle_in_fudai_detail()
|
||
return
|
||
|
||
first_reservation = self.reservations[0]
|
||
try:
|
||
# 从预约记录中获取信息
|
||
content = str(first_reservation.get("content", "") or "")
|
||
prize_value_yuan = float(first_reservation.get("prize_value_yuan", 0.0) or 0.0)
|
||
future_ts = float(first_reservation.get("future_ts", 0.0) or 0.0)
|
||
time_text = str(first_reservation.get("time_text", "") or "")
|
||
participants = int(first_reservation.get("participants", 0) or 0)
|
||
copies = int(first_reservation.get("copies", 0) or 0)
|
||
|
||
# 构造倒计时元组
|
||
now_ts = time.time()
|
||
countdown_start = now_ts
|
||
countdown_end = future_ts if future_ts > 0 else (now_ts + 60.0)
|
||
|
||
# 构造 detail tuple(格式与 read_fudai_detail_once 返回的格式一致)
|
||
detail = (
|
||
content, # 0: 内容
|
||
time_text, # 1: 倒计时文本
|
||
participants, # 2: 参与人数
|
||
copies, # 3: 份数
|
||
prize_value_yuan, # 4: 价值
|
||
(countdown_start, countdown_end), # 5: 倒计时元组
|
||
)
|
||
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:从预约记录构造详情",
|
||
content=content[:50] if content else "",
|
||
prize_value_yuan=prize_value_yuan,
|
||
future_ts=int(future_ts) if future_ts > 0 else 0,
|
||
time_text=time_text,
|
||
participants=participants,
|
||
copies=copies,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 保存详情数据,标记为已读取(用于后续可能的第二次打开)
|
||
self._last_fudai_detail_tuple = detail
|
||
self._fudai_detail_first_read = True
|
||
|
||
# 设置当前福袋的 future_ts(用于参与成功后从预约队列中移除)
|
||
self._current_fudai_future_ts = future_ts
|
||
|
||
# 直接调用参与决策,跳过详情识别
|
||
join_result = douyin_fudai_core.basic_join_decision(self, detail)
|
||
|
||
# 如果参与成功,设置开奖等待状态并从预约队列中移除
|
||
if join_result and future_ts > 0:
|
||
try:
|
||
# 设置开奖等待状态
|
||
current_time = time.time()
|
||
remain_seconds = max(0, future_ts - current_time)
|
||
if remain_seconds > 0:
|
||
self._waiting_for_lottery_result = True
|
||
self._lottery_result_expected_ts = future_ts - 13.0
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后参与成功,设置开奖等待状态",
|
||
remain_seconds=int(remain_seconds),
|
||
future_ts=int(future_ts),
|
||
lottery_result_expected_ts=int(self._lottery_result_expected_ts),
|
||
)
|
||
|
||
# 设置锁定期,防止过早切换直播间
|
||
poll_before = float(getattr(self, "high_value_fudai_poll_before_seconds", 10.0) or 10.0)
|
||
self.reservation_focus_until_ts = future_ts + max(0.0, poll_before)
|
||
|
||
# 从预约队列中移除已参与的预约
|
||
if self.reservations and len(self.reservations) > 0:
|
||
remaining_reservations = []
|
||
for res in self.reservations:
|
||
try:
|
||
res_future_ts = float(res.get("future_ts") or 0.0)
|
||
if res_future_ts > 0 and abs(res_future_ts - future_ts) <= 5.0:
|
||
# 匹配的预约,移除
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后参与成功,从预约队列中移除该预约",
|
||
future_ts=int(res_future_ts),
|
||
value_yuan=res.get("prize_value_yuan", 0),
|
||
content=(res.get("content", "")[:50] if res.get("content") else ""),
|
||
)
|
||
else:
|
||
# 保留不匹配的预约
|
||
remaining_reservations.append(res)
|
||
except Exception:
|
||
# 如果解析预约项时出错,保留该项(容错处理)
|
||
remaining_reservations.append(res)
|
||
|
||
if len(remaining_reservations) < len(self.reservations):
|
||
self.reservations = remaining_reservations
|
||
# 写入预约状态
|
||
try:
|
||
import douyin_reservation_logic
|
||
if hasattr(douyin_reservation_logic, "_write_reservation_state"):
|
||
# 如果有写入函数,调用它
|
||
pass
|
||
else:
|
||
# 否则使用内联写入逻辑
|
||
import os
|
||
import json
|
||
from datetime import datetime
|
||
|
||
state_path = getattr(self, "_reservations_state_path", None)
|
||
if not state_path:
|
||
state_path = os.path.join(
|
||
os.path.dirname(__file__),
|
||
"state",
|
||
"reservations.json",
|
||
)
|
||
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
||
|
||
items = []
|
||
for r in remaining_reservations or []:
|
||
try:
|
||
ft = float(r.get("future_ts") or 0)
|
||
except Exception:
|
||
ft = 0.0
|
||
try:
|
||
ft_str = (
|
||
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
|
||
if ft
|
||
else ""
|
||
)
|
||
except Exception:
|
||
ft_str = str(r.get("future_str", ""))
|
||
|
||
items.append({
|
||
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
|
||
"content": str(r.get("content") or ""),
|
||
"future_ts": ft,
|
||
"future_str": ft_str,
|
||
"pos_seen": int(r.get("pos_seen") or 0),
|
||
"room_title": str(r.get("room_title") or ""),
|
||
"room_title_raw": str(r.get("room_title_raw") or ""),
|
||
"created_ts": float(r.get("created_ts") or 0),
|
||
"task_count": int(r.get("task_count") or 2),
|
||
"time_text": str(r.get("time_text") or ""),
|
||
"participants": int(r.get("participants") or 0),
|
||
"copies": int(r.get("copies") or 0),
|
||
})
|
||
|
||
current_title = str(getattr(self, "current_room_title", "") or "")
|
||
current_title_raw = str(getattr(self, "current_room_title_raw", "") or "")
|
||
|
||
data = {
|
||
"updated_ts": time.time(),
|
||
"reason": "remove_reservation_after_attend",
|
||
"room_pos": 0,
|
||
"current_room_title": current_title,
|
||
"current_room_title_raw": current_title_raw,
|
||
"reservations": items,
|
||
}
|
||
|
||
with open(state_path, "w", encoding="utf-8") as f:
|
||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 已写入预约队列状态文件(移除预约后)",
|
||
path=state_path,
|
||
queue_len=len(remaining_reservations),
|
||
)
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 写入预约状态失败",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
|
||
# 清除预约回退直接参与标志
|
||
self._reservation_back_direct_attend = False
|
||
self.reservation_after_action_pending = False
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后参与成功,设置状态时出错",
|
||
error=str(e),
|
||
error_type=type(e).__name__,
|
||
)
|
||
|
||
elapsed = time.time() - start_time
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_reservation_direct_attend完成",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
join_result=join_result,
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 预约回退后直接参与:从预约记录获取详情时出错,回退到正常流程",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 如果出错,回退到正常流程
|
||
self._handle_in_fudai_detail()
|
||
|
||
def _handle_in_fudai_detail(self) -> None:
|
||
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
|
||
start_time = time.time()
|
||
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
|
||
|
||
# 检查是否是第二次打开福袋详情(已经读取过详情)
|
||
# 如果是第二次打开,直接点击参与,不需要验证,使用第一次的倒计时
|
||
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:
|
||
# 如果没有保存的详情数据,需要重新读取(兜底逻辑)
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取",
|
||
)
|
||
except Exception:
|
||
pass
|
||
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:
|
||
self._last_fudai_detail_tuple = detail
|
||
else:
|
||
# 使用第一次保存的详情数据,设置当前福袋的倒计时信息
|
||
try:
|
||
if isinstance(detail, tuple) and len(detail) >= 6:
|
||
countdown_tuple = detail[5] # type: ignore[index]
|
||
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
|
||
future_ts = float(countdown_tuple[1] or 0.0)
|
||
if future_ts > 0:
|
||
# 设置当前福袋的 future_ts,供 attend_choujiang 使用
|
||
self._current_fudai_future_ts = future_ts
|
||
self._log_kv(
|
||
"参与",
|
||
"第二次打开:使用第一次的倒计时信息",
|
||
future_ts=int(future_ts),
|
||
remain_seconds=int(future_ts - time.time()),
|
||
)
|
||
except Exception as e:
|
||
self._log_kv(
|
||
"参与",
|
||
"第二次打开:设置倒计时信息时出错",
|
||
error=str(e),
|
||
)
|
||
|
||
# 直接调用参与函数,不进行验证
|
||
try:
|
||
attend_result = douyin_fudai_core.attend_choujiang(self)
|
||
|
||
if attend_result:
|
||
self._log_kv(
|
||
"参与",
|
||
"第二次打开:直接点击参与成功",
|
||
result="参与成功",
|
||
)
|
||
else:
|
||
self._log_kv(
|
||
"参与",
|
||
"第二次打开:直接点击参与失败",
|
||
result="参与失败",
|
||
)
|
||
|
||
# 清除第一次读取标志,下次打开新福袋时重新识别
|
||
try:
|
||
self._fudai_detail_first_read = False
|
||
self._last_fudai_detail_tuple = None
|
||
except Exception:
|
||
pass
|
||
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(第二次打开直接参与)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
attend_result=attend_result,
|
||
)
|
||
return
|
||
except Exception as e:
|
||
self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e))
|
||
# 异常时继续正常流程
|
||
else:
|
||
# 第一次打开:完整读取详情(包括内容、倒计时、价值)
|
||
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:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:第一次打开时数据验证失败,跳过",
|
||
validation_reason=reason,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 关闭详情页并返回
|
||
try:
|
||
douyin_fudai_detail.close_fudai_detail(self)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(数据验证失败)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 执行筛选检查(不执行参与操作,只检查是否符合筛选条件)
|
||
try:
|
||
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(
|
||
self, detail
|
||
)
|
||
if skip:
|
||
# 检查是否是高价值福袋,如果是则记录预约或立即参与
|
||
try:
|
||
# 提取价值信息
|
||
prize_value_yuan = 0.0
|
||
countdown_tuple = None
|
||
if isinstance(detail, tuple) and len(detail) >= 6:
|
||
prize_value_yuan = float(detail[4] or 0.0)
|
||
countdown_tuple = detail[5]
|
||
|
||
# 检查是否启用高价值预约
|
||
high_value_enabled = bool(
|
||
getattr(self, "high_value_fudai_enabled", False)
|
||
)
|
||
high_value_threshold = float(
|
||
getattr(self, "high_value_fudai_threshold_yuan", 500.0)
|
||
or 500.0
|
||
)
|
||
|
||
# 检查价值是否达到高价值阈值
|
||
is_high_value = (
|
||
high_value_enabled
|
||
and prize_value_yuan > 0
|
||
and prize_value_yuan >= high_value_threshold
|
||
and isinstance(countdown_tuple, (tuple, list))
|
||
and len(countdown_tuple) >= 2
|
||
and float(countdown_tuple[1] or 0.0) > 0.0
|
||
)
|
||
|
||
# 如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值
|
||
# 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约
|
||
if is_high_value and skip_reason.startswith(
|
||
"countdown_gt_"
|
||
):
|
||
# 计算剩余秒数
|
||
remain_seconds = None
|
||
if (
|
||
isinstance(countdown_tuple, (tuple, list))
|
||
and len(countdown_tuple) >= 2
|
||
):
|
||
try:
|
||
now = time.time()
|
||
cd_start = float(countdown_tuple[0] or 0.0)
|
||
cd_end = float(countdown_tuple[1] or 0.0)
|
||
if cd_start > 0 and cd_end > cd_start:
|
||
remain_seconds = float(cd_end - now)
|
||
except Exception:
|
||
pass
|
||
|
||
# 获取"预约参与阈值"配置
|
||
join_ahead_seconds = int(
|
||
getattr(
|
||
self, "high_value_fudai_join_ahead_seconds", 120
|
||
)
|
||
or 120
|
||
)
|
||
|
||
# 如果剩余秒数在"预约参与阈值"内,立即参与而不是预约
|
||
if (
|
||
remain_seconds is not None
|
||
and remain_seconds <= join_ahead_seconds
|
||
):
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与",
|
||
reason=skip_reason,
|
||
value_yuan=prize_value_yuan,
|
||
threshold=high_value_threshold,
|
||
remain_seconds=int(remain_seconds),
|
||
join_ahead_threshold=join_ahead_seconds,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 不关闭详情,继续走立即参与逻辑(保存详情数据,标记为已读取)
|
||
skip = False
|
||
else:
|
||
# 剩余秒数大于"预约参与阈值",记录预约
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约",
|
||
reason=skip_reason,
|
||
value_yuan=prize_value_yuan,
|
||
threshold=high_value_threshold,
|
||
remain_seconds=(
|
||
int(remain_seconds)
|
||
if remain_seconds is not None
|
||
else None
|
||
),
|
||
join_ahead_threshold=join_ahead_seconds,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 调用 basic_join_decision 来记录预约
|
||
# 注意:basic_join_decision 内部已经关闭详情并切换直播间,不需要再次关闭
|
||
try:
|
||
douyin_fudai_core.basic_join_decision(
|
||
self, detail
|
||
)
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:记录预约时出错",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(记录预约)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception as e:
|
||
# 高价值检查异常,记录日志但继续流程
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:高价值检查异常",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果不是高价值福袋,或者不是倒计时原因,筛选不通过,直接跳过
|
||
if skip:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过",
|
||
skip_reason=skip_reason,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 关闭详情页
|
||
try:
|
||
douyin_fudai_detail.close_fudai_detail(self)
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果允许切换直播间,筛选不通过直接切换直播间
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
if needswitch:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:筛选不通过后切换直播间",
|
||
skip_reason=skip_reason,
|
||
)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
# 优先使用封装好的上滑切房方法
|
||
if hasattr(self, "swipe_up_to_next_live"):
|
||
self.swipe_up_to_next_live()
|
||
else:
|
||
# 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标)
|
||
try:
|
||
rx = int(
|
||
getattr(
|
||
self, "resolution_ratio_x", 1080
|
||
)
|
||
or 1080
|
||
)
|
||
ry = int(
|
||
getattr(
|
||
self, "resolution_ratio_y", 2400
|
||
)
|
||
or 2400
|
||
)
|
||
except Exception:
|
||
rx, ry = 1080, 2400
|
||
start_x = 540 * rx // 1080
|
||
start_y = 1700 * ry // 2400
|
||
end_x = 540 * rx // 1080
|
||
end_y = 700 * ry // 2400
|
||
# 直接使用 ADB 内部滑动命令
|
||
try:
|
||
import subprocess
|
||
if hasattr(self.operation, '_adb'):
|
||
adb_cmd = self.operation._adb()
|
||
else:
|
||
import os
|
||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
|
||
adb_cmd = f'"{adb_cmd}"'
|
||
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
|
||
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||
except Exception:
|
||
# 回退到 operation.swipe
|
||
self.operation.swipe(
|
||
self.device_id,
|
||
start_x,
|
||
start_y,
|
||
end_x,
|
||
end_y,
|
||
300,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(筛选不通过)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception as e:
|
||
# 筛选检查异常,记录日志但继续流程
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:筛选检查异常",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 筛选通过,保存详情数据并标记为已读取
|
||
try:
|
||
self._last_fudai_detail_tuple = detail
|
||
self._fudai_detail_first_read = True
|
||
except Exception:
|
||
pass
|
||
else:
|
||
# 详情数据无效,不保存,不标记为已读取
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:第一次打开时详情数据无效,跳过",
|
||
)
|
||
except Exception:
|
||
pass
|
||
return
|
||
|
||
# 检查是否是优惠券弹窗、观看任务或识别错误:如果检测到,应该直接跳过,不继续处理
|
||
try:
|
||
last_status = getattr(self, "_last_fudai_detail_status", "")
|
||
if last_status == "coupon_popup":
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:检测到优惠券弹窗,已关闭,跳过后续处理",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(优惠券弹窗)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif last_status == "watch_task":
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:检测到'观看X分钟'任务,已在OCR阶段跳过,无需后续处理",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(观看任务)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif last_status == "validation_failed":
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理",
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(验证失败)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
elif last_status == "error":
|
||
# 检查是否是任务数量为0的错误
|
||
try:
|
||
last_extra = getattr(self, "_last_fudai_detail_extra", {})
|
||
if (
|
||
isinstance(last_extra, dict)
|
||
and last_extra.get("reason") == "task_count_zero"
|
||
):
|
||
# 记录连续失败次数
|
||
consecutive_failures = (
|
||
getattr(self, "_fudai_detail_consecutive_failures", 0) or 0
|
||
)
|
||
consecutive_failures += 1
|
||
try:
|
||
self._fudai_detail_consecutive_failures = (
|
||
consecutive_failures
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果连续失败3次,强制关闭详情页并切换直播间,避免卡死
|
||
if consecutive_failures >= 3:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死",
|
||
consecutive_failures=consecutive_failures,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 强制关闭详情页
|
||
try:
|
||
douyin_fudai_detail.close_fudai_detail(self)
|
||
self.operation.delay(0.5)
|
||
except Exception:
|
||
pass
|
||
# 切换直播间
|
||
try:
|
||
needswitch = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch = True
|
||
if needswitch:
|
||
try:
|
||
if hasattr(self, "swipe_up_to_next_live"):
|
||
self.swipe_up_to_next_live()
|
||
else:
|
||
rx = int(
|
||
getattr(self, "resolution_ratio_x", 1080)
|
||
or 1080
|
||
)
|
||
ry = int(
|
||
getattr(self, "resolution_ratio_y", 2400)
|
||
or 2400
|
||
)
|
||
start_x = 540 * rx // 1080
|
||
start_y = 1700 * ry // 2400
|
||
end_x = 540 * rx // 1080
|
||
end_y = 700 * ry // 2400
|
||
# 直接使用 ADB 内部滑动命令
|
||
try:
|
||
import subprocess
|
||
if hasattr(self.operation, '_adb'):
|
||
adb_cmd = self.operation._adb()
|
||
else:
|
||
import os
|
||
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
|
||
if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'):
|
||
adb_cmd = f'"{adb_cmd}"'
|
||
cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300"
|
||
subprocess.run(cmd, shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||
except Exception:
|
||
# 回退到 operation.swipe
|
||
self.operation.swipe(
|
||
self.device_id,
|
||
start_x,
|
||
start_y,
|
||
end_x,
|
||
end_y,
|
||
300,
|
||
)
|
||
self.operation.delay(0.5)
|
||
except Exception:
|
||
pass
|
||
# 重置失败计数
|
||
try:
|
||
self._fudai_detail_consecutive_failures = 0
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(连续失败)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
else:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
|
||
consecutive_failures=consecutive_failures,
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(任务数量为0)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 如果成功读取,重置失败计数
|
||
try:
|
||
self._fudai_detail_consecutive_failures = 0
|
||
except Exception:
|
||
pass
|
||
|
||
# 额外验证:使用验证函数检查数据合理性
|
||
try:
|
||
# 使用已导入的模块,避免重复导入导致作用域问题
|
||
if detail is None:
|
||
try:
|
||
self._log_kv("福袋详情", "详情数据为 None,跳过验证")
|
||
except Exception:
|
||
pass
|
||
else:
|
||
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(
|
||
detail, self
|
||
)
|
||
if not is_valid:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错",
|
||
validation_reason=reason,
|
||
)
|
||
except Exception:
|
||
pass
|
||
douyin_fudai_detail.close_fudai_detail(self)
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(验证失败)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
|
||
try:
|
||
if isinstance(detail, tuple) and len(detail) >= 5:
|
||
content = str(detail[0] or "")
|
||
prize_value_yuan = float(detail[4] or 0.0)
|
||
if not content and prize_value_yuan == 0.0:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
|
||
content=content,
|
||
prize_value_yuan=prize_value_yuan,
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(无效详情)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 记录参与前的状态
|
||
attend_before_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
|
||
|
||
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
|
||
try:
|
||
if isinstance(detail, tuple) and len(detail) >= 6:
|
||
countdown_tuple = detail[5]
|
||
if (
|
||
isinstance(countdown_tuple, (tuple, list))
|
||
and len(countdown_tuple) >= 2
|
||
):
|
||
future_ts = float(countdown_tuple[1] or 0.0)
|
||
if future_ts > 0:
|
||
self._current_fudai_future_ts = future_ts
|
||
except Exception:
|
||
pass
|
||
|
||
# 重置详情关闭标志
|
||
try:
|
||
self._detail_closed_by_attend = False
|
||
except Exception:
|
||
pass
|
||
|
||
# 执行参与决策
|
||
if detail is None:
|
||
try:
|
||
self._log_kv("参与", "详情数据为 None,无法执行参与决策")
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_in_fudai_detail完成(详情为None)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
join_result = douyin_fudai_core.basic_join_decision(self, detail)
|
||
|
||
# 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功
|
||
attend_after_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
|
||
if join_result and attend_after_ts > attend_before_ts:
|
||
# 参与成功,设置等待开奖标志,停止其他行为
|
||
try:
|
||
# 从 detail 中提取倒计时信息
|
||
countdown_tuple = None
|
||
remain_seconds = 0
|
||
future_timestamp = 0.0
|
||
if isinstance(detail, tuple) and len(detail) >= 6:
|
||
countdown_tuple = detail[5]
|
||
if isinstance(countdown_tuple, tuple) and len(countdown_tuple) >= 2:
|
||
# countdown_tuple[0] 是 countdown_start(开始时间戳)
|
||
# countdown_tuple[1] 是 countdown_end(结束时间戳/开奖时间戳)
|
||
future_timestamp = float(countdown_tuple[1] or 0.0)
|
||
# 计算剩余秒数:结束时间戳 - 当前时间
|
||
current_time = time.time()
|
||
if future_timestamp > current_time:
|
||
remain_seconds = int(future_timestamp - current_time)
|
||
|
||
if remain_seconds > 0:
|
||
# 设置等待开奖标志和预期开奖时间
|
||
# 直接保存开奖时间戳,等待时直接用 future_timestamp - time.time() 计算剩余秒数
|
||
# 提前13秒,修正倒计时误差
|
||
self._waiting_for_lottery_result = True
|
||
self._lottery_result_expected_ts = (
|
||
future_timestamp - 13.0
|
||
) # 提前13秒,修正倒计时误差
|
||
|
||
self._log_kv(
|
||
"参与",
|
||
"参与成功,设置等待开奖标志,停止其他行为",
|
||
remain_seconds=remain_seconds,
|
||
future_ts=int(future_timestamp),
|
||
)
|
||
|
||
# 检查是否是预约福袋,如果是,清除锁定期并从预约队列中移除已完成的预约
|
||
try:
|
||
if getattr(self, "reservation_after_action_pending", False):
|
||
# 这是预约福袋,参与成功后需要清除锁定期和移除预约
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 参与成功,清除锁定期并移除预约",
|
||
future_ts=int(future_timestamp),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 清除锁定期
|
||
self.reservation_focus_until_ts = 0.0
|
||
self.reservation_after_action_pending = False
|
||
|
||
# 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差)
|
||
if hasattr(self, "reservations") and self.reservations:
|
||
import douyin_reservation_logic
|
||
|
||
reservations_to_remove = []
|
||
for idx, r in enumerate(self.reservations):
|
||
try:
|
||
r_ft = float(r.get("future_ts") or 0.0)
|
||
if (
|
||
r_ft > 0
|
||
and abs(r_ft - future_timestamp) < 5.0
|
||
):
|
||
reservations_to_remove.append(idx)
|
||
except Exception:
|
||
continue
|
||
|
||
# 从后往前删除,避免索引变化
|
||
for idx in reversed(reservations_to_remove):
|
||
try:
|
||
removed = self.reservations.pop(idx)
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 已从队列中移除已完成的预约",
|
||
future_ts=int(
|
||
removed.get("future_ts", 0)
|
||
),
|
||
content=str(removed.get("content", ""))[
|
||
:50
|
||
],
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
# 重新排序预约队列
|
||
if self.reservations:
|
||
try:
|
||
douyin_reservation_logic._sort_reservations_inplace(
|
||
self.reservations
|
||
)
|
||
except Exception:
|
||
pass
|
||
except Exception as e:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 清除锁定期和移除预约时出错",
|
||
error=str(e),
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 关闭详情页,返回直播间等待开奖
|
||
# 检查 attend_choujiang 是否已经关闭了详情,如果已关闭就不应该再点击返回键
|
||
detail_already_closed = getattr(
|
||
self, "_detail_closed_by_attend", False
|
||
)
|
||
if not detail_already_closed:
|
||
try:
|
||
self.operation.click_back(self.device_id)
|
||
self.operation.delay(1.0)
|
||
self._log_kv("参与", "已关闭详情页,返回直播间等待开奖")
|
||
except Exception:
|
||
pass
|
||
else:
|
||
try:
|
||
self._log_kv(
|
||
"参与",
|
||
"详情页已由 attend_choujiang 关闭,跳过返回键点击",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
# 清除第一次读取标志,下次打开新福袋时重新识别
|
||
try:
|
||
self._fudai_detail_first_read = False
|
||
self._last_fudai_detail_tuple = None
|
||
except Exception:
|
||
pass
|
||
|
||
# 清除第一次读取标志,下次打开新福袋时重新识别
|
||
try:
|
||
self._fudai_detail_first_read = False
|
||
self._last_fudai_detail_tuple = None
|
||
except Exception:
|
||
pass
|
||
|
||
# 返回,让主循环只检测开奖结果,不执行其他操作
|
||
return
|
||
else:
|
||
self._log_kv("参与", "参与成功但无法获取倒计时,跳过等待")
|
||
except Exception as e:
|
||
self._log_kv("参与", "设置等待开奖标志时出错", error=str(e))
|
||
|
||
def _handle_live_room_has_or_not_fudai(self) -> None:
|
||
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"."""
|
||
start_time = time.time()
|
||
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
|
||
# 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋
|
||
try:
|
||
already_verified = bool(
|
||
getattr(self, "_fudai_detail_verified", False) or False
|
||
)
|
||
if already_verified:
|
||
try:
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋",
|
||
)
|
||
except Exception:
|
||
pass
|
||
# 直接调用详情处理逻辑,不查找福袋
|
||
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),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
|
||
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
|
||
try:
|
||
import time as time_module
|
||
now_ts = time_module.time()
|
||
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
|
||
queue_full_waiting = bool(getattr(self, "queue_full_waiting_at_earliest", False) or False)
|
||
|
||
if focus_until > 0 and now_ts < focus_until and queue_full_waiting:
|
||
# 在锁定期内,且队列满等待中,检查时间窗口
|
||
if self.reservations and len(self.reservations) > 0:
|
||
earliest = self.reservations[0]
|
||
try:
|
||
ft = float(earliest.get("future_ts") or 0.0)
|
||
if ft > 0:
|
||
join_ahead = float(
|
||
getattr(self, "high_value_fudai_join_ahead_seconds", 120) or 120
|
||
)
|
||
poll_before = float(getattr(self, "poll_before_open_seconds", 10.0) or 10.0)
|
||
time_window_start_ts = ft - join_ahead
|
||
time_window_end_ts = ft + max(0.0, poll_before)
|
||
|
||
# 如果时间窗口未到,避免重复打开福袋详情
|
||
if now_ts < time_window_start_ts:
|
||
try:
|
||
self._log_kv(
|
||
"预约",
|
||
"[预约] 锁定期内时间窗口未到,避免重复打开福袋详情",
|
||
focus_until=int(focus_until),
|
||
now_ts=int(now_ts),
|
||
time_window_start=int(time_window_start_ts),
|
||
remain_seconds=int(time_window_start_ts - now_ts),
|
||
)
|
||
except Exception:
|
||
pass
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
return
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
room_pos_ref: List[int] = [0]
|
||
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
|
||
if not opened:
|
||
# 无福袋,交给 flow_control 的“无福袋处理”逻辑
|
||
# 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房)
|
||
try:
|
||
needswitch_cfg = bool(getattr(self, "needswitch", True))
|
||
except Exception:
|
||
needswitch_cfg = True
|
||
|
||
wait_times_ref = [0]
|
||
swipe_times_ref = [0]
|
||
reservation_focus_until_ts_ref = [0.0]
|
||
reset_to_list_after_reservations_ref = [False]
|
||
douyin_flow_control.handle_no_fudai_situation(
|
||
self,
|
||
x=0,
|
||
swipe_times=0,
|
||
wait_times_ref=wait_times_ref,
|
||
needswitch=needswitch_cfg,
|
||
reservation_focus_until_ts=0.0,
|
||
reservations=[],
|
||
room_pos=room_pos_ref[0],
|
||
post_switch_delay_s=1.5,
|
||
swipe_up_switch_callback=self.swipe_up_to_next_live,
|
||
swipe_down_back_callback=lambda: None,
|
||
sort_reservations_callback=lambda: None,
|
||
clear_reservations_callback=lambda: None,
|
||
write_state_callback=lambda: None,
|
||
back_to_list_callback=lambda: None,
|
||
into_list_callback=lambda: None,
|
||
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
|
||
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
|
||
swipe_times_ref=swipe_times_ref,
|
||
)
|
||
elapsed = time.time() - start_time
|
||
self._log_kv(
|
||
"流程",
|
||
"_handle_live_room_has_or_not_fudai完成(无福袋)",
|
||
elapsed_seconds=round(elapsed, 2),
|
||
)
|
||
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),
|
||
)
|