Files
douyin_guaji-main/douyin/core/douyin_flow_control.py
T

577 lines
19 KiB
Python

"""
Flow control main helpers (本地模块化实现,基础版)
================================================
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
"""
from __future__ import annotations
from typing import Any, Callable, List, Optional, Tuple
import time
import os
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
import path_config
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
func_start_time: float | None = None,
):
if func_start_time is None:
func_start_time = time.time()
return find_and_open_fudai_detail(
analyser=analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)
def find_and_open_fudai_detail(
analyser: Any,
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
if func_start_time is None:
func_start_time = time.time()
# 如果正在等待开奖,不应该再次打开福袋详情
try:
if getattr(analyser, "_waiting_for_lottery_result", False):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:正在等待开奖,跳过打开福袋详情",
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(等待开奖中)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
pass
device_id = getattr(analyser, "device_id", "")
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=True)
if not x:
x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False)
if x:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标",
x=int(x or 0),
elapsed_seconds=round(time.time() - start_time, 2),
)
except Exception:
pass
break
elapsed = time.time() - start_time
remaining = max_wait_seconds - elapsed
if remaining <= 0:
break
wait_time = min(retry_delay_seconds, remaining)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:未检测到福袋图标,等待后重试",
elapsed_seconds=round(elapsed, 2),
remaining_seconds=round(remaining, 2),
wait_seconds=round(wait_time, 2),
)
except Exception:
pass
try:
analyser.operation.delay(wait_time)
except Exception:
time.sleep(wait_time)
if not x:
try:
total_elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:等待超时,未检测到福袋图标",
x=int(x or 0),
max_wait_seconds=max_wait_seconds,
total_elapsed_seconds=round(total_elapsed, 2),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(未找到福袋)",
elapsed_seconds=round(elapsed, 2),
)
# 未找到福袋:增加连续未找到计数(由 analyser 维护),以便触发退出直播间动作
try:
cur = int(getattr(analyser, "_consecutive_no_fudai_count", 0) or 0)
cur += 1
setattr(analyser, "_consecutive_no_fudai_count", cur)
threshold = (
int(getattr(analyser, "fudai_exit_after_misses", 0) or 0) or None
)
if threshold is None or threshold <= 0:
# 如果未配置阈值,则尝试读取配置属性(兼容性)
try:
import json
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
threshold = int(
cfg.get("fudai_exit_after_misses", 30) or 30
)
except Exception:
threshold = 30
# 如果计数达到阈值,执行返回键退出直播间并重置计数
if threshold and cur >= threshold:
try:
analyser._log_kv(
"流程",
"连续未找到福袋达到阈值:按返回键退出直播间",
consecutive_no_fudai=cur,
threshold=threshold,
)
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
try:
# 兜底:使用通用 click 返回坐标
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
back_x = int(50 * rx / 1080)
back_y = int(50 * ry / 2400)
analyser.operation.click(analyser.device_id, back_x, back_y)
except Exception:
pass
# 重置计数,避免重复触发
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
base_y = 403 # 与检测时使用的同一水平线附近
click_x = int(x * rx / 1080)
click_y = int(base_y * ry / 2400)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:检测到福袋图标并点击",
fudai_x=int(x),
click_x=click_x,
click_y=click_y,
)
except Exception:
pass
# 同步保存一个福袋图标的完整调试截图(确保无论检测路径如何都能保存)
try:
from PIL import Image
import importlib
douyin_screenshot_manager = importlib.import_module(
"douyin.handlers.douyin_screenshot_manager"
)
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
try:
box_r = 30
coord_box = (
max(0, click_x - box_r),
max(0, click_y - box_r),
click_x + box_r,
click_y + box_r,
)
except Exception:
coord_box = None
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=coord_box,
extra_info={
"source": "flow_on_detect",
"click_x": click_x,
"click_y": click_y,
"detected_x_scaled": click_x,
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"流程检测到福袋图标后保存完整截图",
path=debug_path,
)
except Exception:
pass
except Exception:
pass
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
wait_seconds = float(getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
)
except Exception:
pass
try:
analyser.operation.delay(wait_seconds)
except Exception:
time.sleep(wait_seconds)
from douyin.stage import douyin_stage
analyser.operation.get_screenshot(device_id, use_service=False)
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
)
except Exception:
pass
return False
try:
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage, reason = (
"IN_LIVE_ROOM",
"阶段诊断返回 None,默认判定为在直播间",
)
else:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
)
except Exception:
pass
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 成功打开福袋详情:重置连续未找到计数
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
return True
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
)
except Exception:
pass
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
try:
back_click_x = int(520 * rx / 1080)
back_click_y = int(505 * ry / 2400)
except Exception:
back_click_x, back_click_y = 520, 505
try:
analyser.operation.click(device_id, back_click_x, back_click_y)
except Exception:
try:
analyser.click(back_click_x, back_click_y)
except Exception:
pass
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
try:
analyser.last_fudai_x = 0
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测异常",
error=str(e),
)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
return False
except Exception:
try:
analyser.click(x, base_y)
wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 1.0) or 1.0
)
analyser.operation.delay(wait_seconds)
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底成功)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
return False
return False
def filter_fudai_detail(
analyser: Any,
detail: tuple,
x: int,
needswitch: bool,
post_switch_delay_s: float,
close_detail_callback,
swipe_up_switch_callback,
add_reservation_callback,
) -> bool:
"""福袋详情过滤逻辑:根据 config.json 对福袋进行基础筛选。"""
start_time = time.time()
skip, reason = should_skip_fudai_by_config(analyser, detail)
try:
content = (
str(detail[0] or "")
if isinstance(detail, tuple) and len(detail) >= 1
else ""
)
analyser._log_kv(
"流程",
"filter_fudai_detail",
x=x,
needswitch=needswitch,
skip=int(bool(skip)),
reason=reason,
content_preview=content[:60] if content else "",
)
except Exception:
pass
if not skip:
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选通过)",
elapsed_seconds=round(elapsed, 2),
)
return False
try:
close_detail_callback(analyser)
except Exception:
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
try:
time.sleep(post_switch_delay_s or 1.2)
except Exception:
pass
elapsed = time.time() - start_time
analyser._log_kv(
"流程",
"filter_fudai_detail完成(筛选不通过)",
elapsed_seconds=round(elapsed, 2),
reason=reason,
)
return True
def handle_no_fudai_situation(
analyser: Any,
x: int,
swipe_times: int,
wait_times_ref: List[int],
needswitch: bool,
reservation_focus_until_ts: float,
reservations: list,
room_pos: int,
post_switch_delay_s: float,
swipe_up_switch_callback: Optional[Callable[[], None]],
swipe_down_back_callback: Callable[[], None],
sort_reservations_callback: Callable[[], None],
clear_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
back_to_list_callback: Callable[[], None],
into_list_callback: Callable[[], None],
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
seek_reservation_room_callback: Optional[Callable[[dict[str, Any]], bool]] = None,
reservation_after_action_pending_ref: Optional[List[bool]] = None,
reservation_back_swipe_delay_s: Optional[float] = None,
) -> bool:
"""处理未找到福袋的逻辑(预约回退 / 切换直播间)。"""
handled_reservation = False
seek_callback = seek_reservation_room_callback or (lambda item: False)
reservation_after_action_pending_ref = (
reservation_after_action_pending_ref
if reservation_after_action_pending_ref
else [False]
)
reservation_back_swipe_delay_s = (
reservation_back_swipe_delay_s
if reservation_back_swipe_delay_s is not None
else float(getattr(analyser, "reservation_back_swipe_delay_s", 0.5) or 0.5)
)
try:
from douyin.reservation import douyin_reservation_logic
handled_reservation = (
douyin_reservation_logic.process_reservation_attend_window(
analyser,
reservations,
room_pos,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
reservation_back_swipe_delay_s,
swipe_down_back_callback,
seek_callback,
sort_reservations_callback,
write_state_callback,
)
)
except Exception:
handled_reservation = False
if handled_reservation:
return True
if wait_times_ref:
wait_times_ref[0] += 1
if needswitch and swipe_up_switch_callback:
try:
swipe_up_switch_callback()
except Exception:
pass
delay_seconds = float(post_switch_delay_s or 1.0)
try:
analyser.operation.delay(delay_seconds)
except Exception:
time.sleep(delay_seconds)
if swipe_times_ref:
swipe_times_ref[0] += 1
return False