Files
douyin_guaji-main/douyin/core/douyin_flow_control.py
T
2025-12-31 11:55:01 +08:00

632 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
"""
Flow control main helpers (本地模块化实现,基础版)
================================================
当前只实现与你"基础抢福袋、不启用预约"相关的核心流程:
- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转)
- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情
- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换
- filter_fudai_detail:根据 config.json 对福袋进行基础筛选
"""
from typing import Any, List, 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
from douyin.reservation import douyin_reservation_logic
import path_config
from PIL import Image
def handle_stage_after_diagnosis(
analyser: Any,
stage: str,
seen: str,
loop_count: int,
) -> bool:
"""记录阶段诊断结果,当前不改变主流程走向。"""
try:
analyser._log_kv(
"流程",
"handle_stage_after_diagnosis",
stage=stage,
seen=seen,
loop_count=loop_count,
)
except Exception:
pass
return False
def find_and_open_fudai_detail(
analyser: Any,
room_pos_ref: List[int],
) -> bool:
"""在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。"""
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=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))
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 path_config
from douyin.handlers import 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")
# 使用与检测处相同的命名(pixel_detect + fudai_icon + detected)
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=None,
extra_info={"source": "flow_on_detect", "click_x": click_x, "click_y": click_y},
)
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)
# 智能等待:先等待最小时间,然后循环检测详情页是否已打开
# 这样可以减少不必要的等待时间
min_wait_seconds = 0.5 # 最小等待时间(确保点击生效)
max_wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0
)
check_interval = 0.2 # 每次检测间隔(秒)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:开始智能等待",
min_wait_seconds=min_wait_seconds,
max_wait_seconds=max_wait_seconds,
check_interval=check_interval,
)
except Exception:
pass
# 先等待最小时间
analyser.operation.delay(min_wait_seconds)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:最小等待时间已过,开始循环检测",
elapsed_seconds=min_wait_seconds,
)
except Exception:
pass
# 智能等待:循环检测详情页是否已打开
from douyin.stage import douyin_stage
wait_start = time.time()
detail_opened = False
check_count = 0
while (time.time() - wait_start) < (max_wait_seconds - min_wait_seconds):
check_count += 1
elapsed_in_loop = time.time() - wait_start
try:
analyser.operation.get_screenshot(device_id)
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
# 快速检测是否已在详情页(只检测关键特征,不执行完整阶段诊断)
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is not None:
stage, reason = result
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待检测中",
check_count=check_count,
elapsed_in_loop=round(elapsed_in_loop, 2),
total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2),
current_stage=stage,
reason=reason[:50] if reason else "",
)
except Exception:
pass
if stage == "FUDai_DETAIL":
detail_opened = True
elapsed_wait = time.time() - wait_start
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待检测到详情页已打开",
check_count=check_count,
wait_seconds=round(elapsed_wait + min_wait_seconds, 2),
elapsed_in_loop=round(elapsed_wait, 2),
)
except Exception:
pass
break
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待检测中(阶段诊断返回None)",
check_count=check_count,
elapsed_in_loop=round(elapsed_in_loop, 2),
total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2),
)
except Exception:
pass
else:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待检测中(截图文件不存在)",
check_count=check_count,
elapsed_in_loop=round(elapsed_in_loop, 2),
total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2),
pic_path=pic_path,
)
except Exception:
pass
except Exception as e:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待检测中(检测异常)",
check_count=check_count,
elapsed_in_loop=round(elapsed_in_loop, 2),
total_elapsed=round(elapsed_in_loop + min_wait_seconds, 2),
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
# 等待一小段时间后再次检测
try:
analyser.operation.delay(check_interval)
except Exception:
time.sleep(check_interval)
# 记录智能等待结束状态
total_elapsed = time.time() - wait_start + min_wait_seconds
if not detail_opened:
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:智能等待超时,未检测到详情页",
check_count=check_count,
total_elapsed=round(total_elapsed, 2),
max_wait_seconds=max_wait_seconds,
)
except Exception:
pass
# 如果智能等待已检测到详情页,直接返回成功,无需再次检测
if detail_opened:
# 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv("流程", "find_and_open_fudai_detail完成(成功打开详情)", elapsed_seconds=round(elapsed, 2))
return True
# 如果智能等待未检测到详情页,执行完整的验证流程
# 确保有最新截图
analyser.operation.get_screenshot(device_id)
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
# 清除第一次读取标志,确保新打开的福袋会进行完整的OCR识别
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
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
# 使用固定坐标 (520, 505) 进行点击,而不是系统返回键
# 根据当前分辨率进行等比例换算(基准分辨率 1080x2400)
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:
# 兜底:直接用 analyser.click
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:
# 阶段检测失败,返回False
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)
# 点击后等待福袋详情页加载(可配置)
fudai_click_wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0
)
analyser.operation.delay(fudai_click_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
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,
swipe_down_back_callback,
sort_reservations_callback,
clear_reservations_callback,
write_state_callback,
back_to_list_callback,
into_list_callback,
reservation_focus_until_ts_ref: List[float],
reset_to_list_after_reservations_ref: List[bool],
swipe_times_ref: List[int],
) -> bool:
"""当前直播间没有福袋时的基础处理。
本地版实现:
- 先让预约模块有机会“抢占”流程(例如到点需要回退到预约直播间);
- 若未触发预约回退,则执行简单的等待 + 上滑切换。
"""
try:
analyser._log_kv(
"流程",
"handle_no_fudai_situation",
x=x,
swipe_times=swipe_times,
room_pos=room_pos,
reservations=len(reservations),
)
except Exception:
pass
# --- 优先让“预约回退窗口”有机会执行 ---
try:
if getattr(analyser, "high_value_fudai_enabled", False) and reservations:
# 构造回调:下滑回退一个直播间
def _swipe_down_once() -> None:
try:
if swipe_down_back_callback:
swipe_down_back_callback()
except Exception:
pass
def _sort_reservations() -> None:
try:
# 使用统一核心逻辑排序
douyin_reservation_logic._sort_reservations_inplace(reservations) # type: ignore[attr-defined]
except Exception:
pass
def _write_state() -> None:
try:
if write_state_callback:
write_state_callback()
except Exception:
pass
# 调用预约窗口处理:若返回 True,表示已触发回退,本轮不再上滑
def _seek_reservation_room(item: dict) -> bool:
"""委托给 analyser._seek_reservation_room,避免简化为恒 True。"""
try:
fn = getattr(analyser, "_seek_reservation_room", None)
if not fn:
return False
return bool(fn(item))
except Exception:
return False
preempted = douyin_reservation_logic.process_reservation_attend_window(
analyser=analyser,
reservations=reservations,
room_pos=room_pos,
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
reservation_after_action_pending_ref=[False],
reservation_back_swipe_delay_s=float(
getattr(analyser, "reservation_back_swipe_delay", 0.6) 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 preempted:
return True
except Exception:
# 预约处理异常不影响基础切换逻辑
pass
# 简单策略:轻微等待 + 上滑切换
try:
analyser.operation.delay(1.0)
except Exception:
time.sleep(1.0)
if needswitch and swipe_up_switch_callback:
swipe_up_switch_callback()
try:
analyser.operation.delay(post_switch_delay_s or 1.2)
except Exception:
time.sleep(post_switch_delay_s or 1.2)
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
return False