Files
douyin_guaji-main/douyin/core/douyin_flow_control.py
T
Your Name 0b5f150691 Refactor and clean up code across multiple scripts
- Removed trailing whitespace and ensured files end with a single newline in cleanup_unused_files.py.
- Added fix_trailing_whitespace.py to batch remove trailing whitespace from Python files.
- Updated install_dependencies.py to improve dependency installation prompts.
- Cleaned up pick_coords.py by removing unnecessary whitespace and improving code readability.
- Enhanced region_selector.py by disabling specific pylint checks for better compatibility with third-party libraries.
- Improved WPS流程图生成工具.py by cleaning up whitespace and enhancing readability.
- Updated __init__.py in typings to remove unnecessary lines.
- Modified app.js to adjust default configuration values and clean up unused code.
2026-01-02 23:57:03 +08:00

514 lines
17 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),
)
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
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