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

463 lines
16 KiB
Python

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 import check_have_fudai_with_ready_screenshot
from douyin_fudai_core import should_skip_fudai_by_config
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
# 优先走底层 operation.click,失败再尝试 analyser.click
try:
analyser.operation.click(device_id, click_x, click_y)
# 点击后等待福袋详情页加载(可配置)
fudai_click_wait_seconds = float(
getattr(analyser, "fudai_click_wait_seconds", 2.0) or 2.0
)
analyser.operation.delay(fudai_click_wait_seconds)
# 点击后验证:检测是否成功打开福袋详情页(必须执行,不能静默失败)
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:
import douyin_stage
result = douyin_stage.diagnose_stage_from_current_screen(analyser)
if result is None:
stage, reason = ("IN_LIVE_ROOM", "阶段诊断返回 None,默认判定为在直播间")
else:
stage, reason = result
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