Files
douyin_guaji-main/douyin/handlers/douyin_swipe_handler.py
T

564 lines
22 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
import time
import subprocess
from typing import Any
from douyin.logging.action_tracker import track_action
from douyin.handlers import douyin_swipe_ops
class SwipeHandler:
"""滑动处理器:统一管理滑动操作"""
@staticmethod
@track_action("swipe_up_to_next_live")
def swipe_up_to_next_live(analyser: Any) -> None:
"""上滑切换直播间(简单版封装)。
注意:如果处于预约锁定期内(reservation_focus_until_ts > 当前时间),
则不允许上划离开预约直播间,直接返回。
参数:
analyser: 分析器对象
"""
# 检查是否在预约锁定期内
# 但如果当前处于“预约回退/定位直播间”的 seek 过程,则允许强制切换,
# 否则会出现:回退逻辑需要上滑前进,但被锁定期拦截,导致流程看似卡死。
try:
try:
in_seek = bool(
getattr(analyser, "_skip_record_title_during_seek", False)
)
except Exception:
in_seek = False
focus_until = float(
getattr(analyser, "reservation_focus_until_ts", 0.0) or 0.0
)
now_ts = time.time()
if (not in_seek) and focus_until > 0 and now_ts < focus_until:
# 在锁定期内,不允许上划离开预约直播间
remain_seconds = int(focus_until - now_ts)
try:
analyser._log_kv( # type: ignore[attr-defined]
"预约",
"[预约] 锁定期内不允许上划离开预约直播间",
focus_until=int(focus_until),
remain_seconds=remain_seconds,
queue_full_waiting=getattr(
analyser, "queue_full_waiting_at_earliest", False
),
)
except Exception:
pass
return # 直接返回,不执行上划操作
except Exception:
# 如果检查锁定期时出错,继续执行上划(避免因异常导致无法切换)
pass
start_time = time.time()
douyin_swipe_ops.swipe_up_switch_live(analyser)
# 记录直播间位置:上滑 +1
try:
analyser.room_pos += 1
except Exception:
analyser.room_pos = 0
elapsed = time.time() - start_time
analyser._log_kv( # type: ignore[attr-defined]
"操作", "上滑切换直播间", elapsed_seconds=round(elapsed, 2)
)
# 记录滑动次数(用于滑动次数重置功能)
try:
if not hasattr(analyser, "_swipe_times"):
analyser._swipe_times = 0
analyser._swipe_times += 1
except Exception:
pass
# 检查是否需要重置(滑动次数达到阈值)
try:
SwipeHandler.maybe_reset_after_swipes(analyser)
except Exception:
pass
# 设置标志:刚刚切换了直播间,阶段检测后需要等待福袋加载
try:
analyser._just_switched_room = True
except Exception:
pass
# 清除第一次读取标志,确保新直播间的福袋会进行完整的OCR识别
try:
analyser._fudai_detail_first_read = False
analyser._last_fudai_detail_tuple = None
except Exception:
pass
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
try:
skip_record = bool(
getattr(analyser, "_skip_record_title_during_seek", False)
)
if not skip_record:
analyser._record_room_title_and_pos() # type: ignore[attr-defined]
except Exception:
pass
@staticmethod
@track_action("swipe_down_back_from_live")
def swipe_down_back_from_live(analyser: Any) -> None:
"""上划回退到上一个直播间(供预约/无福袋逻辑使用)。
参数:
analyser: 分析器对象
"""
start_time = time.time()
try:
douyin_swipe_ops.swipe_down_back_live(analyser)
except Exception:
# 若子模块未实现,则退化为点击返回键
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
# 记录直播间位置:下滑/回退 -1
try:
analyser.room_pos -= 1
except Exception:
analyser.room_pos = 0
# 记录当前直播间的标题和位置到运行时映射表(用于回退校验)
# 如果是在回退过程中(_seek_reservation_room),跳过记录,因为之前已经记录过了
try:
skip_record = bool(
getattr(analyser, "_skip_record_title_during_seek", False)
)
if not skip_record:
analyser._record_room_title_and_pos() # type: ignore[attr-defined]
except Exception:
pass
@staticmethod # type: ignore[misc]
def maybe_reset_after_swipes(analyser: Any) -> int:
"""达到切换阈值后,在当前直播间页面回退到第一个直播间。
参数:
analyser: 分析器对象
返回:
重置后的滑动次数(通常为0)
"""
try:
needswitch = bool(getattr(analyser, "needswitch", True))
except Exception:
needswitch = True
if not needswitch:
return getattr(analyser, "_swipe_times", 0)
if not bool(getattr(analyser, "reset_after_swipes_enabled", False)):
return getattr(analyser, "_swipe_times", 0)
try:
swipe_times = int(getattr(analyser, "_swipe_times", 0) or 0)
except Exception:
swipe_times = 0
threshold = max(1, int(getattr(analyser, "reset_after_swipes", 0) or 0))
if swipe_times < threshold:
return swipe_times
# 防止回退过程中被重复触发(例如其他流程也触发返回键回退)
try:
if bool(getattr(analyser, "_resetting_after_swipes", False)):
return 0
setattr(analyser, "_resetting_after_swipes", True)
except Exception:
pass
# 根据配置选择回退方式:'swipe'=滑动回退(默认),'back'=按返回键回退
mode = str(
getattr(analyser, "reset_after_swipes_action", "swipe") or "swipe"
).lower()
if mode not in ("swipe", "back"):
mode = "swipe"
# 如果显式启用了达到未找到福袋阈值时按返回键回退(GUI 勾选),优先使用返回键回退
try:
if bool(getattr(analyser, "enable_back_on_misses", False)):
mode = "back"
except Exception:
pass
try:
if mode == "back":
msg = "已切换直播间{}次,达到阈值{}:按一次返回键退出并重新进入直播间".format(
swipe_times, threshold
)
else:
msg = "已切换直播间{}次,达到阈值{}:向上滑动回退到第一个直播间".format(
swipe_times, threshold
)
analyser._log_kv( # type: ignore[attr-defined]
"流程",
msg,
swipe_times=swipe_times,
threshold=threshold,
reset_mode=mode,
)
except Exception:
pass
# 回退次数按当前已切换次数来(更符合"回到本轮第一个直播间"的语义)
back_times = int(swipe_times)
# 防止无限循环:最大回退次数限制为100
if back_times > 100:
back_times = 100
if back_times <= 0:
return 0
if mode == "back":
# 返回键回退:只按一次返回键退出直播间,然后重新进入直播间
try:
setattr(analyser, "_recent_reset_ts", time.time())
setattr(analyser, "_recent_reset_by", "reset_after_swipes_back_once")
except Exception:
pass
try:
analyser.operation.click_back(analyser.device_id)
except Exception:
pass
try:
analyser.operation.delay(getattr(analyser, "BACK_KEY_CLICK_DELAY", 2))
except Exception:
analyser.operation.delay(2)
# 小延迟,避免卡顿导致下一步截图/判断失败
try:
analyser.operation.delay(
getattr(analyser, "RETURN_STEP_DELAY_SECONDS", 0.8)
)
except Exception:
analyser.operation.delay(0.8)
# 尝试确认是否已回到推荐页;若不在推荐页,则兜底走原来的“多次返回到推荐页”逻辑
try:
ok = analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
if ok:
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
if stage != "RECOMMEND_PAGE":
try:
analyser._log_kv( # type: ignore[attr-defined]
"流程",
"返回键回退后未到推荐页,兜底返回推荐页并重进直播",
stage=stage,
seen=seen,
)
except Exception:
pass
SwipeHandler.return_to_recommend_and_reenter_live(analyser)
else:
SwipeHandler._reenter_live_from_recommend(analyser)
else:
SwipeHandler.return_to_recommend_and_reenter_live(analyser)
except Exception:
SwipeHandler.return_to_recommend_and_reenter_live(analyser)
else:
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
for i in range(back_times):
try:
# 标记:本轮处于重置/回退流程中,防止其他路径触发返回键退出
try:
setattr(analyser, "_recent_reset_ts", time.time())
setattr(
analyser, "_recent_reset_by", "reset_after_swipes_swipe"
)
except Exception:
pass
# 向上回退:从上往下滑动(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 内部滑动命令
# 使用配置的滑动持续时间,如果没有配置则使用300ms(比之前的200ms更快)
swipe_duration_ms = int(
getattr(analyser, "swipe_duration_ms", 300) or 300
)
try:
if hasattr(analyser.operation, "_adb"):
adb_cmd = analyser.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 {analyser.device_id} shell input swipe "
f"{start_x} {start_y} {end_x} {end_y} {swipe_duration_ms}"
)
subprocess.run(
cmd,
shell=True,
check=False,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# 注意:这里使用 ADB 直调绕过了 operation.swipe,需要手动标记页面已变化
try:
if hasattr(analyser.operation, "_mark_screen_dirty"):
analyser.operation._mark_screen_dirty(
analyser.device_id
)
except Exception:
pass
except Exception:
# 回退到 operation.swipe
analyser.operation.swipe(
analyser.device_id,
start_x,
start_y,
end_x,
end_y,
swipe_duration_ms,
)
try:
analyser._log_kv( # type: ignore[attr-defined]
"流程", "回退直播间 {}/{}".format(i + 1, back_times)
)
except Exception:
pass
analyser.operation.delay(2)
except Exception:
pass
# 回到第一个后,计数归零
analyser.operation.delay(3)
try:
analyser._swipe_times = 0
analyser.room_pos = 0
# 清除连续未找到福袋计数,避免与其他回退逻辑重复
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
except Exception:
pass
finally:
try:
setattr(analyser, "_resetting_after_swipes", False)
except Exception:
pass
return 0
@staticmethod
def _reenter_live_from_recommend(analyser: Any) -> None:
"""从推荐页重新进入直播间(复用 return_to_recommend_and_reenter_live 的后半段逻辑)。"""
# 等待页面稳定
try:
analyser.operation.delay(getattr(analyser, "PAGE_STABLE_DELAY", 2))
except Exception:
analyser.operation.delay(2)
# 点击关注标签并进入直播间
try:
follow_tab_x = int(709 * analyser.resolution_ratio_x // 1080)
follow_tab_y = int(169 * analyser.resolution_ratio_y // 2400)
analyser.operation.click(analyser.device_id, follow_tab_x, follow_tab_y)
try:
analyser._log_kv( # type: ignore[attr-defined]
"流程", "点击关注标签", x=follow_tab_x, y=follow_tab_y
)
except Exception:
pass
try:
analyser.operation.delay(getattr(analyser, "FOLLOW_TAB_CLICK_DELAY", 2))
except Exception:
analyser.operation.delay(2)
# 小延迟,等待页面卡顿恢复再点击进入
try:
analyser.operation.delay(
getattr(analyser, "RETURN_STEP_DELAY_SECONDS", 0.8)
)
except Exception:
analyser.operation.delay(0.8)
enter_live_x = int(103 * analyser.resolution_ratio_x // 1080)
enter_live_y = int(385 * analyser.resolution_ratio_y // 2400)
analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y)
try:
analyser.operation.delay(getattr(analyser, "ENTER_LIVE_CLICK_DELAY", 1))
except Exception:
analyser.operation.delay(1)
analyser.operation.click(analyser.device_id, enter_live_x, enter_live_y)
# 点击间隔稍微加长,避免卡顿导致第二次点击未生效
try:
analyser.operation.delay(
getattr(analyser, "RETURN_STEP_DELAY_SECONDS", 0.8)
)
except Exception:
analyser.operation.delay(0.8)
try:
analyser._log_kv( # type: ignore[attr-defined]
"流程",
"点击进入直播间位置",
x=enter_live_x,
y=enter_live_y,
次数=2,
)
except Exception:
pass
analyser.operation.delay(getattr(analyser, "ENTER_LIVE_FINAL_DELAY", 3))
try:
analyser._log_kv("流程", "已重新进入直播间") # type: ignore[attr-defined]
except Exception:
pass
try:
analyser._just_switched_room = True
except Exception:
pass
try:
analyser._last_successful_attend_ts = time.time()
analyser._run_start_ts = time.time()
except Exception:
pass
except Exception:
# 保守兜底:失败时尝试按一次返回键
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(getattr(analyser, "BACK_KEY_CLICK_DELAY", 2))
except Exception:
pass
@staticmethod
@track_action("return_to_recommend_and_reenter_live")
def return_to_recommend_and_reenter_live(analyser: Any) -> None:
"""返回推荐页面并重新进入直播间。
通过多次点击返回键返回到推荐页面,然后点击关注标签并进入直播间。
参数:
analyser: 分析器对象
"""
analyser._log_kv("超时", "开始返回推荐页面") # type: ignore[attr-defined]
# 多次点击返回键,直到到达推荐页面
max_back_clicks = analyser.MAX_BACK_CLICKS_TO_RECOMMEND
for i in range(max_back_clicks):
try:
# 截图并诊断当前阶段
ok = analyser.operation.get_screenshot(
analyser.device_id, use_service=False
)
if not ok:
analyser._log_kv( # type: ignore[attr-defined]
"超时", f"获取截图失败 ({i+1}/{max_back_clicks})"
)
# 即使截图失败,也尝试点击返回键
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
continue
# 诊断当前阶段
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
# 如果已经在推荐页面,跳出循环
if stage == "RECOMMEND_PAGE":
analyser._log_kv( # type: ignore[attr-defined]
"超时", f"已到达推荐页面 ({i+1}次返回键)"
)
break
# 点击返回键
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
if i == max_back_clicks - 1:
analyser._log_kv( # type: ignore[attr-defined]
"超时",
f"已点击{max_back_clicks}次返回键,可能未到达推荐页面",
)
except Exception as e:
try:
analyser._log_kv( # type: ignore[attr-defined]
"超时",
f"返回推荐页面时出错 ({i+1}/{max_back_clicks})",
error=str(e),
)
except Exception:
pass
# 继续尝试点击返回键
try:
analyser.operation.click_back(analyser.device_id)
analyser.operation.delay(analyser.BACK_KEY_CLICK_DELAY)
except Exception as e2:
# 记录异常但继续执行
try:
analyser._log_kv( # type: ignore[attr-defined]
"超时",
"点击返回键失败但继续",
error=str(e2),
error_type=type(e2).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
# 等待页面稳定
analyser.operation.delay(analyser.PAGE_STABLE_DELAY)
# 再次截图确认当前阶段
try:
ok = analyser.operation.get_screenshot(analyser.device_id)
if ok:
stage, seen = analyser._diagnose_stage_from_current_screen() # type: ignore[attr-defined]
analyser._log_kv( # type: ignore[attr-defined]
"超时", "确认当前阶段", stage=stage, seen=seen
)
except Exception as e:
# 记录异常但继续执行(阶段诊断失败不影响主流程)
try:
analyser._log_kv( # type: ignore[attr-defined]
"超时",
"确认阶段时出错但继续",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass # 日志系统本身出错时忽略
try:
SwipeHandler._reenter_live_from_recommend(analyser)
except Exception:
pass