Files
douyi_guaji_main/gui/gui_core.py
T
CodexandClaude Opus 4.7 3b8f85b9cb refactor(gui_core): 抽 _update_stats_from_line 解析逻辑到 stats_log_parser (1207 → 541)
Runner._update_stats_from_line 是 666 行的"日志行 → 计数器更新"巨型方法。
按业务事件分类 14 个独立段(福袋字段 / 打开-参与计数器 / 跳过原因 /
错误统计 / 粉丝团 / 预约 / 开奖结果 / 直播间切换 / 阶段诊断 / OCR / 性能 /
详情识别 / 福袋查找 / 回退操作)。

抽到 gui/gui_core_pkg/stats_log_parser.py:
- update_stats_from_line(runner, line) 主入口
- 14 个 _parse_* 子函数按事件分组
- 通过 runner.* 调用保持与原 Runner 方法/状态一致

Runner._update_stats_from_line 从 666 行变成 4 行委托。模块级测试更易于
单独覆盖各分类的解析逻辑。

1408 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:35:04 +08:00

545 lines
20 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.
"""gui_core - gui_app / web_gui / webgui_launcher 共享后端。
历史巨型文件(1594 行)已部分拆出到 ``gui.gui_core_pkg``:
- adb / wifi_adb / config / run_params
本文件保留 Runner 巨型类(1164 行,13 个实例方法 + self 状态),
其他符号通过 from-import 暴露,外部 from gui.gui_core import X 兼容。
"""
from __future__ import annotations
import json
import os
import queue
import re
import shutil
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from typing import Optional
from douyin.core import path_config
# 从子包 re-export 顶层符号(保持兼容)
from gui.gui_core_pkg import (
CONFIG_PATH,
RunParams,
auto_connect_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
enable_wifi_adb,
find_adb_executable,
get_connected_wifi_devices,
get_device_ip,
is_device_wifi_connected,
list_adb_devices,
read_config,
resolve_adb_device,
write_config,
)
class Runner:
def __init__(self, on_line):
self._proc: Optional[subprocess.Popen] = None
self._on_line = on_line
self._reader_thread: Optional[threading.Thread] = None
self._lock = threading.Lock()
self._log: list[str] = []
self._log_capacity: int = 4000
# 统计相关
self._start_ts: Optional[float] = None
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = None
self._counters: dict[str, int] = {}
self._fudai_last: dict[str, object] = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events: list[dict] = []
self._events_cap: int = 5000
self._wins: list[dict] = []
self._wins_cap: int = 200
# 唯一计数去重集合(用于展示“唯一成功次数”口径)
self._unique_keys_seen: set[str] = set()
self._unique_keys_open: set[str] = set()
self._unique_keys_attend: set[str] = set()
# 当前直播间位置(从日志中解析),用于按直播间去重统计
self._current_room_pos: int | None = None
# 按直播间去重集合(优先使用 room_pos;若不可用则回退到 content/prize/countdown key)
self._fudai_seen_room_pos: set[int] = set()
self._fudai_open_room_pos: set[int] = set()
self._fudai_attend_ok_room_pos: set[int] = set()
self._fudai_attend_fail_room_pos: set[int] = set()
# 已记录福袋识别的跟踪(避免同一个直播间同一个福袋重复记录识别次数)
self._recorded_fudai_seen: set[tuple[str, str]] = (
set()
) # (room_title, fudai_content)
def is_running(self) -> bool:
return self._proc is not None and self._proc.poll() is None
def _append_log_line(self, line: str) -> None:
if line is None:
return
with self._lock:
self._log.append(line)
cap = self._log_capacity
if cap > 0 and len(self._log) > cap:
del self._log[: len(self._log) - cap]
def _emit_line(self, line: str) -> None:
self._append_log_line(line)
self._on_line(line)
def _inc(self, key: str, n: int = 1) -> None:
with self._lock:
self._counters[key] = int(self._counters.get(key, 0)) + int(n)
def _record_event(self, typ: str, meta: Optional[dict] = None) -> None:
ev = {
"ts": time.time(),
"type": str(typ),
"meta": meta or {},
}
with self._lock:
self._events.append(ev)
if len(self._events) > self._events_cap:
self._events = self._events[-self._events_cap :]
def _make_unique_key(self) -> str:
"""根据当前 snapshot 生成一个尽可能稳定的唯一键(用于去重)。
使用 content/prize_value/countdown 三元组,如果不可用则返回空字符串。
"""
try:
with self._lock:
content = self._fudai_last.get("content") or ""
prize = str(self._fudai_last.get("prize_value_yuan") or "")
countdown = str(self._fudai_last.get("countdown") or "")
key = f"{content}|{prize}|{countdown}"
return key
except Exception:
return ""
def _record_win(self) -> None:
item = {
"ts": time.time(),
**self._snapshot_fudai(),
}
with self._lock:
self._wins.append(item)
if len(self._wins) > self._wins_cap:
self._wins = self._wins[-self._wins_cap :]
def _snapshot_fudai(self) -> dict:
with self._lock:
return {
"content": self._fudai_last.get("content") or "",
"countdown": self._fudai_last.get("countdown") or "",
"participants": self._fudai_last.get("participants"),
"copies": self._fudai_last.get("copies"),
"prize_value_yuan": self._fudai_last.get("prize_value_yuan"),
}
def _update_stats_from_line(self, line: str) -> None:
"""委托到 gui/gui_core_pkg/stats_log_parser.update_stats_from_line。"""
from gui.gui_core_pkg.stats_log_parser import update_stats_from_line
update_stats_from_line(self, line)
def get_stats(self) -> dict:
with self._lock:
running = self._proc is not None and self._proc.poll() is None
pid = self._pid
start_ts = self._start_ts
last_log_ts = self._last_log_ts
exit_code = self._exit_code
counters = dict(self._counters)
fudai_last = dict(self._fudai_last)
wins = list(self._wins[-20:]) # 只返回最近20条
events = list(self._events[-1000:]) # 返回最近1000条事件用于统计
now = time.time()
uptime = 0
if start_ts and start_ts > 0:
uptime = int(max(0, now - start_ts))
return {
"running": bool(running),
"pid": pid,
"start_ts": start_ts,
"last_log_ts": last_log_ts,
"exit_code": exit_code,
"uptime_seconds": uptime,
"counters": counters,
"fudai_last": fudai_last,
"wins": wins,
"events": events,
}
def start(self, params: RunParams) -> None:
if self.is_running():
raise RuntimeError("已经在运行")
# 如果 wait_minutes=0,表示无限循环模式
wait_minutes_arg = str(params.wait_minutes) if params.wait_minutes > 0 else "0"
run_cli_path = path_config.get_run_cli_path()
if not os.path.exists(run_cli_path):
raise FileNotFoundError(
f"未找到 run_cli.py 文件。\n"
f"预期路径: {run_cli_path}\n"
f"请确保 run_cli.py 位于项目根目录。"
)
cmd = [
sys.executable,
run_cli_path,
"--y-pianyi",
str(params.y_pianyi),
"--wait-minutes",
wait_minutes_arg,
]
if params.device_id:
cmd += ["--device-id", params.device_id]
if params.needswitch:
cmd.append("--needswitch")
cmd += ["--min-prize-value-yuan", str(params.min_prize_value_yuan)]
# 这些参数是新增可调节项:倒计时太短跳过、参与人数范围
cmd += [
"--skip-if-countdown-gt-seconds",
str(int(params.skip_if_countdown_gt_seconds or 900)),
]
if params.reset_after_swipes_enabled:
cmd.append("--reset-after-swipes-enabled")
cmd += ["--reset-after-swipes", str(int(params.reset_after_swipes or 10))]
else:
cmd.append("--reset-after-swipes-disabled")
if int(params.min_participants or 0) > 0:
cmd += ["--min-participants", str(int(params.min_participants))]
if int(params.max_participants or 0) > 0:
cmd += ["--max-participants", str(int(params.max_participants))]
if params.auto_join_fansclub:
cmd.append("--auto-join-fansclub")
if params.fansclub_fail_action:
cmd += ["--fansclub-fail-action", params.fansclub_fail_action]
# 高价值直播间回访
if params.high_value_room_revisit_enabled:
cmd.append("--high-value-room-revisit-enabled")
else:
cmd.append("--high-value-room-revisit-disabled")
if params.high_value_room_revisit_only_current_run:
cmd.append("--high-value-room-revisit-only-current-run")
if params.high_value_room_revisit_min_interval_seconds != 300:
cmd += [
"--high-value-room-revisit-min-interval-seconds",
str(params.high_value_room_revisit_min_interval_seconds),
]
if params.high_value_room_revisit_max_per_run != 5:
cmd += [
"--high-value-room-revisit-max-per-run",
str(params.high_value_room_revisit_max_per_run),
]
if params.high_value_room_revisit_min_prize_value > 0:
cmd += [
"--high-value-room-revisit-min-prize-value",
str(params.high_value_room_revisit_min_prize_value),
]
if params.high_value_room_revisit_max_age_days != 30:
cmd += [
"--high-value-room-revisit-max-age-days",
str(params.high_value_room_revisit_max_age_days),
]
# 预约回退校验
if params.reservation_back_verify_enabled:
cmd.append("--reservation-back-verify-enabled")
else:
cmd.append("--reservation-back-verify-disabled")
if params.reservation_back_swipe_delay > 0:
cmd += [
"--reservation-back-swipe-delay",
str(params.reservation_back_swipe_delay),
]
# 找福袋最大尝试次数
if params.fudai_find_max_attempts > 0:
cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)]
# OCR模式1开关
if params.enable_ocr_mode1:
cmd.append("--enable-ocr-mode1")
else:
cmd.append("--disable-ocr-mode1")
# 福袋模板匹配开关
if params.fudai_template_match_enabled:
cmd.append("--fudai-template-enabled")
else:
cmd.append("--fudai-template-disabled")
# 添加福袋模板匹配阈值参数
cmd.extend(
["--fudai-template-threshold", str(params.fudai_template_match_threshold)]
)
# 启用/禁用 达到连续未找到福袋阈值时按返回键回退
if getattr(params, "enable_back_on_misses", True):
cmd.append("--enable-back-on-misses")
else:
cmd.append("--disable-back-on-misses")
# 确保从 GUI 启动时传递回退方式(若启用返回键回退,则将 reset action 设为 back)
try:
if getattr(params, "enable_back_on_misses", False):
cmd += ["--reset-after-swipes-action", "back"]
except Exception:
pass
# 只养号模式:如果启用则传递到 run_cli.py
try:
if getattr(params, "yanghao_only", False):
cmd.append("--yanghao-only")
# 若指定时长,传给 --yanghao-seconds
if int(getattr(params, "yanghao_seconds", 0) or 0) > 0:
cmd += ["--yanghao-seconds", str(int(params.yanghao_seconds))]
except Exception:
# 忽略,保证兼容旧参数集合
pass
# 继承当前环境,并确保 adb 在 PATH(即使用户没手动刷新 PATH)
env = os.environ.copy()
env.setdefault("PYTHONIOENCODING", "utf-8")
adb_exe = find_adb_executable()
if adb_exe:
adb_dir = os.path.dirname(adb_exe)
env["PATH"] = adb_dir + os.pathsep + env.get("PATH", "")
env["ADB_EXECUTABLE"] = adb_exe
else:
self._emit_line(
"[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH"
)
# Resolve the device before spawning run_cli so background runs never block
# on the interactive select_device() prompt.
try:
resolved_device_id = resolve_adb_device(adb_exe, params.device_id)
try:
i = cmd.index("--device-id")
if i + 1 < len(cmd):
cmd[i + 1] = resolved_device_id
except ValueError:
cmd += ["--device-id", resolved_device_id]
except Exception as e:
self._emit_line(f"[错误] 设备选择失败: {e}")
raise
try:
p = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
env=env,
cwd=path_config.PROJECT_ROOT,
)
except FileNotFoundError as e:
raise RuntimeError(
f"无法启动进程:找不到 Python 解释器或 run_cli.py 文件\n"
f"Python路径: {sys.executable}\n"
f"run_cli.py路径: {run_cli_path}\n"
f"原始错误: {e}"
) from e
except Exception as e:
raise RuntimeError(
f"启动进程失败:{e}\n"
f"命令: {' '.join(cmd)}\n"
f"工作目录: {path_config.PROJECT_ROOT}"
) from e
with self._lock:
self._proc = p
self._pid = p.pid
self._start_ts = time.time()
self._exit_code = None
self._last_log_ts = time.time()
self._counters = {}
self._fudai_last = {
"content": "",
"countdown": "",
"participants": None,
"copies": None,
"prize_value_yuan": None,
"updated_ts": None,
}
self._events = []
self._wins = []
self._log = []
def _reader():
assert self._proc is not None
out = self._proc.stdout
if out is None:
return
try:
# 读取所有输出
has_output = False
for line in out:
has_output = True
cleaned_line = line.rstrip("\n")
self._emit_line(cleaned_line)
try:
self._update_stats_from_line(cleaned_line)
except Exception:
pass
# 等待进程结束
rc = self._proc.wait()
with self._lock:
self._exit_code = rc
# 如果进程立即退出且没有输出,说明可能有问题
if not has_output and rc != 0:
self._emit_line(f"[警告] 进程立即退出,退出码={rc},没有输出")
self._emit_line(
"[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误"
)
else:
self._emit_line(f"[进程结束] exit_code={rc}")
except Exception as e:
# 读取输出时出错
try:
self._emit_line(f"[错误] 读取进程输出失败: {e}")
rc = self._proc.poll()
if rc is not None:
with self._lock:
self._exit_code = rc
self._emit_line(f"[进程结束] exit_code={rc}")
except Exception:
pass
self._reader_thread = threading.Thread(target=_reader, daemon=True)
self._reader_thread.start()
# (已移除) 测试养号启动器
# (已移除) 测试评论启动器
def send_back_key(self, device_id: str) -> bool:
"""手动发送返回键到指定设备。
Args:
device_id: 设备ID,如果为空则仅在单设备在线时自动使用该设备
Returns:
True if successful, False otherwise
"""
try:
adb_exe = find_adb_executable()
if not adb_exe:
self._emit_line("[错误] 未找到 adb.exe")
return False
if not device_id or device_id.strip() == "":
try:
device_id = resolve_adb_device(adb_exe)
except Exception as e:
self._emit_line(f"[错误] 设备选择失败: {e}")
return False
# 发送返回键 (keyevent 4)
cmd = [adb_exe, "-s", device_id, "shell", "input", "keyevent", "4"]
proc = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=5.0,
check=False,
)
if proc.returncode == 0:
self._emit_line(f"[手动操作] 已发送返回键到设备: {device_id}")
return True
else:
error_msg = proc.stderr or proc.stdout or "未知错误"
self._emit_line(f"[错误] 发送返回键失败: {error_msg}")
return False
except subprocess.TimeoutExpired:
self._emit_line("[错误] 发送返回键超时")
return False
except Exception as e:
self._emit_line(f"[错误] 发送返回键异常: {str(e)}")
return False
def stop(self) -> None:
if not self.is_running():
return
assert self._proc is not None
self._emit_line("[停止] 正在终止进程...")
self._proc.terminate()
try:
self._proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self._emit_line("[停止] 进程未退出,强制结束...")
self._proc.kill()
def force_stop(self) -> None:
"""更强硬的停止:直接杀掉已记录的 PID 及其子进程(主要针对 Windows 下残留进程)。"""
with self._lock:
pid = self._pid
proc = self._proc
if not pid and not proc:
self._emit_line("[停止] 当前无记录中的运行进程")
return
self._emit_line(f"[停止] 强制终止进程 (pid={pid}) ...")
# 先尝试通过 Popen 对象 kill
try:
if proc is not None and proc.poll() is None:
proc.kill()
except Exception:
pass
# 再通过系统命令清理可能残留的子进程
if pid:
try:
if os.name == "nt":
# Windows:使用 taskkill 结束进程树
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
else:
# 类 Unix:尝试向进程组发送 SIGKILL
import signal
try:
os.kill(pid, signal.SIGKILL)
except AttributeError:
# 如果SIGKILL不存在,使用SIGTERM
os.kill(pid, signal.SIGTERM)
except Exception:
pass
with self._lock:
self._proc = None
self._pid = None