"""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: s = (line or "").strip() if not s: return with self._lock: self._last_log_ts = time.time() # --- 福袋:抽取"最近一次"识别到的信息 --- # 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容=" content_extracted = False room_title = "" if "福袋内容:" in s: with self._lock: self._fudai_last["content"] = ( s.split("福袋内容:", 1)[1].strip().split()[0] ) # 只取第一个词,避免包含后续字段 self._fudai_last["updated_ts"] = time.time() content_extracted = True else: # 新格式:字段_内容= 或 内容= m = re.search(r"(?:字段_)?内容[=:]\s*([^\s]+)", s) if m: with self._lock: self._fudai_last["content"] = m.group(1).strip() self._fudai_last["updated_ts"] = time.time() content_extracted = True # 提取直播间标题 m = re.search(r"room_title[=:]\s*([^\s,]+)", s) if m: room_title = m.group(1).strip() if content_extracted: fudai_content = self._fudai_last.get("content", "") key = (room_title, fudai_content) if key not in self._recorded_fudai_seen: self._recorded_fudai_seen.add(key) self._inc("fudai_seen") self._record_event("fudai_seen", self._snapshot_fudai()) # 唯一口径:优先按当前直播间位置去重(每个直播间只记一次),回退到 content/prize/countdown 三元组 try: if self._current_room_pos is not None: try: rp = int(self._current_room_pos) except Exception: rp = None if rp is not None and rp not in self._fudai_seen_room_pos: self._fudai_seen_room_pos.add(rp) self._inc("fudai_seen_unique") else: key = self._make_unique_key() if key and key not in self._unique_keys_seen: self._unique_keys_seen.add(key) self._inc("fudai_seen_unique") except Exception: pass # 参与人数:支持多种格式 m = re.search(r"(?:字段_)?参与人数[=:]?\s*(\d+)", s) if not m: m = re.search(r"参与人数:\s*(\d+)", s) if m: with self._lock: self._fudai_last["participants"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() # 福袋份数:支持多种格式 m = re.search(r"(?:字段_)?份数[=:]?\s*(\d+)", s) if not m: m = re.search(r"福袋份数:\s*(\d+)", s) if m: with self._lock: self._fudai_last["copies"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() # 倒计时:支持多种格式 if "倒计时时间:" in s: with self._lock: self._fudai_last["countdown"] = ( s.split("倒计时时间:", 1)[1].strip().split()[0] ) self._fudai_last["updated_ts"] = time.time() else: m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s) if m: with self._lock: self._fudai_last["countdown"] = m.group(1).strip() self._fudai_last["updated_ts"] = time.time() # 奖品价值:支持多种格式 m = re.search( r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s, ) if not m: m = re.search( r"奖品价值:\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)\s*元", s ) if m: try: with self._lock: self._fudai_last["prize_value_yuan"] = float(m.group(1)) self._fudai_last["updated_ts"] = time.time() except Exception: pass # --- 福袋:关键流程计数 --- if "点击打开福袋详情" in s or ("[流程]" in s and "检测到福袋图标并点击" in s): self._inc("fudai_open_detail") self._record_event("fudai_open_detail", self._snapshot_fudai()) try: key = self._make_unique_key() if key and key not in self._unique_keys_open: self._unique_keys_open.add(key) self._inc("fudai_open_detail_unique") except Exception: pass if "点击参与抽奖" in s or ( "[参与]" in s and ("动作=点击参与" in s or "动作=参与" in s) ): self._inc("fudai_click_attend") self._record_event("fudai_click_attend", self._snapshot_fudai()) try: key = self._make_unique_key() if key and key not in self._unique_keys_attend: self._unique_keys_attend.add(key) self._inc("fudai_click_attend_unique") except Exception: pass # 参与成功/已参与:支持更多格式 if ( "已经参与,等待开奖" in s or "已经参与,等待看播时间凑齐开奖" in s or "已参与成功(或看播中)" in s or ( "[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s or "结果=参与成功" in s) ) or ("[参与]" in s and "已参与" in s and "等待开奖" in s) or ("预约回退后直接参与" in s and "参与成功" in s) ): self._inc("fudai_attend_ok") self._record_event("fudai_attend_ok", self._snapshot_fudai()) try: # 优先按直播间去重 if self._current_room_pos is not None: try: rp = int(self._current_room_pos) except Exception: rp = None if rp is not None and rp not in self._fudai_attend_ok_room_pos: self._fudai_attend_ok_room_pos.add(rp) self._inc("fudai_attend_ok_unique") else: key = self._make_unique_key() if key and key not in self._unique_keys_attend: self._unique_keys_attend.add(key) self._inc("fudai_attend_ok_unique") except Exception: pass if "参与抽奖失败" in s or ("[参与]" in s and "结果=失败" in s): self._inc("fudai_attend_fail") self._record_event("fudai_attend_fail", self._snapshot_fudai()) try: # 优先按直播间去重 if self._current_room_pos is not None: try: rp = int(self._current_room_pos) except Exception: rp = None if rp is not None and rp not in self._fudai_attend_fail_room_pos: self._fudai_attend_fail_room_pos.add(rp) self._inc("fudai_attend_fail_unique") else: # 回退到 key 去重(使用相同的 unique_keys_attend 集合) try: key = self._make_unique_key() if key and key not in self._unique_keys_attend: self._unique_keys_attend.add(key) self._inc("fudai_attend_fail_unique") except Exception: pass except Exception: pass # --- 福袋:跳过/过滤原因 --- if "参与人数" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_low") # 提取实际参与人数和阈值 meta = self._snapshot_fudai() m = re.search(r"参与人数[=:]?\s*(\d+)", s) if m: try: meta["participants"] = int(m.group(1)) except Exception: pass m = re.search(r"阈值[=:]?\s*(\d+)", s) if m: try: meta["threshold"] = int(m.group(1)) except Exception: pass self._record_event("fudai_skip", {"reason": "participants_low", **meta}) if "参与人数" in s and "> 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_high") # 提取实际参与人数和阈值 meta = self._snapshot_fudai() m = re.search(r"参与人数[=:]?\s*(\d+)", s) if m: try: meta["participants"] = int(m.group(1)) except Exception: pass m = re.search(r"阈值[=:]?\s*(\d+)", s) if m: try: meta["threshold"] = int(m.group(1)) except Exception: pass self._record_event("fudai_skip", {"reason": "participants_high", **meta}) if "奖品价值" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_value_low") # 提取实际价值和阈值 meta = self._snapshot_fudai() m = re.search( r"(?:奖品)?价值[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s ) if m: try: meta["prize_value_yuan"] = float(m.group(1)) except Exception: pass m = re.search( r"阈值[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s ) if m: try: meta["threshold"] = float(m.group(1)) except Exception: pass self._record_event("fudai_skip", {"reason": "value_low", **meta}) if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" in s): self._inc("fudai_skip_content") self._record_event( "fudai_skip", {"reason": "content", **self._snapshot_fudai()} ) if "抽奖倒计时时间小于" in s and "不参与" in s: self._inc("fudai_skip_countdown_short") # 提取倒计时秒数 meta = self._snapshot_fudai() m = re.search(r"(\d+)\s*秒", s) if m: try: meta["countdown_seconds"] = int(m.group(1)) except Exception: pass self._record_event("fudai_skip", {"reason": "countdown_short", **meta}) if "抽奖倒计时时间大于" in s and "暂不参与" in s: self._inc("fudai_skip_countdown_long") # 提取倒计时秒数 meta = self._snapshot_fudai() m = re.search(r"(\d+)\s*秒", s) if m: try: meta["countdown_seconds"] = int(m.group(1)) except Exception: pass self._record_event("fudai_skip", {"reason": "countdown_long", **meta}) if ( "需要看播时长:默认不参与" in s or "需要开始观看/看播门槛:默认不参与" in s or ("[参与]" in s and "结果=看播门槛" in s) ): self._inc("fudai_skip_watch_required") self._record_event( "fudai_skip", {"reason": "watch_required", **self._snapshot_fudai()} ) if "打开福袋异常" in s or ("[流程]" in s and "打开福袋异常" in s): self._inc("fudai_open_error") self._record_event("fudai_open_error", self._snapshot_fudai()) if "超过10次点击福袋无法打开详情" in s: self._inc("fudai_open_error_too_many") self._record_event("fudai_open_error_too_many", self._snapshot_fudai()) # 倒计时大于阈值但价值达到高价值阈值,记录预约 if ( "[流程]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s ) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s): self._inc("fudai_reserved_high_value") # 提取价值和倒计时信息 meta = self._snapshot_fudai() m = re.search( r"(?:价值|价值元)[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s, ) if m: try: meta["prize_value_yuan"] = float(m.group(1)) except Exception: pass m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s) if m: try: meta["remain_seconds"] = int(m.group(1)) except Exception: pass self._record_event("fudai_reserved_high_value", meta) # --- 错误和异常统计 --- if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s: self._inc("error_total") # 提取错误类型 error_type = "unknown" if "UnboundLocalError" in s: error_type = "UnboundLocalError" self._inc("error_unbound_local") elif "AttributeError" in s: error_type = "AttributeError" self._inc("error_attribute") elif "KeyError" in s: error_type = "KeyError" self._inc("error_key") elif "ValueError" in s: error_type = "ValueError" self._inc("error_value") elif "TypeError" in s: error_type = "TypeError" self._inc("error_type") elif "TimeoutError" in s or "超时" in s: error_type = "TimeoutError" self._inc("error_timeout") elif "ConnectionError" in s or "连接" in s and "失败" in s: error_type = "ConnectionError" self._inc("error_connection") elif "OCR" in s and ("失败" in s or "错误" in s): error_type = "OCR_Error" self._inc("error_ocr") elif "截图" in s and ("失败" in s or "错误" in s): error_type = "Screenshot_Error" self._inc("error_screenshot") elif "识别" in s and ("失败" in s or "错误" in s): error_type = "Detection_Error" self._inc("error_detection") self._record_event("error", {"error_type": error_type}) # --- 阶段诊断错误 --- if "阶段诊断" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_stage_diagnosis") self._record_event("error_stage_diagnosis", {}) # --- 详情读取错误 --- if "读取福袋详情" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_read_detail") self._record_event("error_read_detail", {}) # --- 配置加载错误 --- if "load_config" in s and ("失败" in s or "错误" in s or "异常" in s): self._inc("error_config_load") self._record_event("error_config_load", {}) # --- 状态文件错误 --- if ("预约队列状态文件" in s or "reservations.json" in s) and ( "失败" in s or "错误" in s ): self._inc("error_state_file") self._record_event("error_state_file", {}) # --- 直播间检测错误 --- if "直播间检测" in s and ("失败" in s or "错误" in s): self._inc("error_live_room_detect") self._record_event("error_live_room_detect", {}) # --- 福袋查找错误 --- if "查找福袋" in s and ("失败" in s or "错误" in s or "未找到" in s): self._inc("error_fudai_find") self._record_event("error_fudai_find", {}) # --- 粉丝团门槛 --- if "需要加入粉丝团才能参与" in s or ("[参与]" in s and "结果=需要粉丝团" in s): self._inc("fansclub_required") self._record_event("fansclub_required", self._snapshot_fudai()) if "未启用自动加入粉丝团" in s: self._inc("fansclub_manual_needed") self._record_event("fansclub_manual_needed", self._snapshot_fudai()) if "粉丝团门槛仍未解决" in s or ("[参与]" in s and "粉丝团门槛仍未解决" in s): self._inc("fansclub_unresolved") self._record_event("fansclub_unresolved", self._snapshot_fudai()) # --- 预约队列/回退校验 --- if ( "[预约]" in s and "回退校验通过" in s ) or "回退校验通过:已回到目标直播间" in s: self._inc("reservation_back_verify_ok") self._record_event("reservation_back_verify_ok", {}) if ("[预约]" in s and "回退校验失败" in s) or "回退校验失败" in s: self._inc("reservation_back_verify_fail") self._record_event("reservation_back_verify_fail", {}) if ( "[预约]" in s and "预约队列已满,丢弃最低价值" in s ) or "预约队列已满,丢弃最低价值" in s: self._inc("reservation_drop_low_value") self._record_event("reservation_drop_low_value", {}) if ("[预约]" in s and "清空预约队列" in s) or "清空预约队列" in s: self._inc("reservation_clear") self._record_event("reservation_clear", {}) # --- 预约记录相关 --- if ( "[预约]" in s and "已记录高价值福袋" in s ) or "record_high_value_reservation:已记录高价值福袋" in s: self._inc("reservation_recorded") # 提取预约价值:支持多种格式 value = None m = re.search(r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", s) if not m: m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s) if m: try: value = float(m.group(1)) except Exception: pass # 提取开奖时间 future_ts = None m = re.search(r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)", s) if m: try: future_ts = int(m.group(1)) except Exception: pass # 提取直播间名称 room_title = None m = re.search( r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s ) if m: room_title = m.group(1).strip() meta = self._snapshot_fudai() if value is not None: meta["prize_value_yuan"] = value if future_ts is not None: meta["future_ts"] = future_ts if room_title: meta["room_title"] = room_title self._record_event("reservation_recorded", meta) if ( "[预约]" in s and "进入预约参与窗口" in s ) or "进入预约参与窗口,准备回退到目标直播间" in s: self._inc("reservation_window_entered") self._record_event("reservation_window_entered", {}) if ( ("[预约]" in s and "已回退到目标直播间" in s) or "已回退到目标直播间" in s or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s) ): self._inc("reservation_back_success") # 提取回退信息 meta = {} m = re.search(r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)", s) if m: try: meta["back_times"] = int(m.group(1)) except Exception: pass self._record_event("reservation_back_success", meta) if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s: self._inc("reservation_window_not_reached") self._record_event("reservation_window_not_reached", {}) if ( "[预约]" in s and "已明显错过开奖时间" in s ) or "已明显错过开奖时间,清理过期预约" in s: self._inc("reservation_expired") self._record_event("reservation_expired", {}) if ( "[预约]" in s and "预约队列为空" in s ) or "process_reservation_attend_window:预约队列为空" in s: self._inc("reservation_queue_empty") if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s: self._inc("reservation_locked") self._record_event("reservation_locked", {}) if "[预约]" in s and "已回退到第一个直播间" in s: self._inc("reservation_back_to_first") self._record_event("reservation_back_to_first", {}) if "[预约]" in s and "run_once_basic:检查预约回退触发条件" in s: self._inc("reservation_check_triggered") # 预约队列满时等待 if ( ("[预约]" in s and "队列已满" in s) or "handle_queue_full_wait_at_earliest" in s or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s) ): self._inc("reservation_queue_full_wait") self._record_event("reservation_queue_full_wait", {}) # 回退后直接参与 if ("[预约]" in s and "预约回退后直接参与" in s) or "预约回退后直接参与" in s: self._inc("reservation_back_direct_attend") self._record_event("reservation_back_direct_attend", {}) # 队列满回退后设置参与标志 if "[预约]" in s and "队列满回退后,直接设置参与标志" in s: self._inc("reservation_queue_full_back_attend") self._record_event("reservation_queue_full_back_attend", {}) # 通过相似度匹配识别重复预约 if "[预约]" in s and "通过相似度匹配识别为重复预约" in s: self._inc("reservation_duplicate_detected") self._record_event("reservation_duplicate_detected", {}) # --- 开奖结果 --- if "没有抽中" in s and "关闭弹窗" in s: self._inc("fudai_result_no_win") self._record_event("fudai_result_no_win", self._snapshot_fudai()) if ( "恭喜中奖了" in s or "检测到中奖结果" in s or ("[开奖结果]" in s and "中奖" in s) ): self._inc("fudai_result_win") # 提取中奖信息 meta = self._snapshot_fudai() m = re.search(r"(?:奖品|商品)[=:]?\s*([^\s]+)", s) if m: meta["prize"] = m.group(1).strip() self._record_event("fudai_result_win", meta) self._record_win() if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s): self._inc("fudai_order_success") self._record_event("fudai_order_success", self._snapshot_fudai()) # 等待开奖(只在设置等待开奖标志时计数,避免重复计数) # 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了 if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or ( "[参与]" in s and "设置等待开奖标志" in s ): self._inc("fudai_waiting_lottery") # 提取剩余秒数 meta = self._snapshot_fudai() m = re.search(r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)", s) if m: try: meta["remain_seconds"] = int(m.group(1)) except Exception: pass self._record_event("fudai_waiting_lottery", meta) # --- 直播间切换(按原因粗分) --- if "上划切换直播间" in s or ("[操作]" in s and "上滑切换直播间" in s): self._inc("switch_room") meta_reason = "unknown" if "无福袋" in s: self._inc("switch_room_no_fudai") meta_reason = "no_fudai" elif "参与人数" in s: self._inc("switch_room_participants") meta_reason = "participants" elif "奖品价值" in s: self._inc("switch_room_value") meta_reason = "value" elif "内容不理想" in s: self._inc("switch_room_content") meta_reason = "content" elif "倒计时" in s: self._inc("switch_room_countdown") meta_reason = "countdown" elif "参与抽奖失败" in s: self._inc("switch_room_attend_fail") meta_reason = "attend_fail" elif "记录预约后" in s: self._inc("switch_room_after_reservation") meta_reason = "after_reservation" elif "锁定期内" in s: self._inc("switch_room_locked") meta_reason = "locked" self._record_event( "switch_room", {"reason": meta_reason, **self._snapshot_fudai()} ) # --- 阶段诊断统计 --- if "[阶段诊断]" in s or "阶段诊断" in s: if "阶段诊断完成" in s: self._inc("stage_diagnosis_complete") # 提取阶段和耗时 meta = {} m = re.search(r"阶段[=:]?\s*(\w+)", s) if m: meta["stage"] = m.group(1) m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s) if m: try: meta["elapsed_seconds"] = float(m.group(1)) except Exception: pass m = re.search(r"分数[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s) if m: try: meta["score"] = float(m.group(1)) except Exception: pass self._record_event("stage_diagnosis_complete", meta) elif "阶段诊断失败" in s or "阶段诊断错误" in s: self._inc("stage_diagnosis_failed") self._record_event("stage_diagnosis_failed", {}) # --- OCR识别统计 --- if "[福袋]" in s and "OCR识别" in s: self._inc("ocr_attempt") if "识别成功" in s or "识别完成" in s: self._inc("ocr_success") elif "识别失败" in s or "识别错误" in s: self._inc("ocr_failed") # --- 性能统计 --- m = re.search(r"耗时[=:]?\s*([0-9]+(?:\.[0-9]+)?)\s*秒", s) if m: try: elapsed = float(m.group(1)) # 记录耗时较长的操作 if elapsed > 5.0: self._inc("slow_operation") self._record_event( "slow_operation", {"elapsed_seconds": elapsed, "operation": s[:100]}, ) except Exception: pass # --- 详情识别统计 --- if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s: self._inc("fudai_detail_read_attempt") if ( "识别成功" in s or "识别完成" in s or "read_fudai_detail_once完成(成功)" in s ): self._inc("fudai_detail_read_success") # 提取任务数量 meta = {} m = re.search(r"(?:任务数量|task_count)[=:]?\s*(\d+)", s) if m: try: meta["task_count"] = int(m.group(1)) except Exception: pass self._record_event("fudai_detail_read_success", meta) elif "识别失败" in s or "识别错误" in s: self._inc("fudai_detail_read_failed") self._record_event("fudai_detail_read_failed", {}) # --- 福袋查找统计 --- if "[福袋查找]" in s or "查找福袋" in s: if "检测完成" in s and "命中" in s: self._inc("fudai_find_success") elif "检测完成" in s and "未找到" in s: self._inc("fudai_find_not_found") elif "等待超时" in s: self._inc("fudai_find_timeout") # --- 回退操作统计 --- if ("[预约]" in s and "回退" in s) or "回退到" in s: if "回退完成" in s or "回退成功" in s: self._inc("reservation_back_operation") # 提取回退次数 meta = {} m = re.search(r"(?:回退|back_times)[=:]?\s*(\d+)", s) if m: try: meta["back_times"] = int(m.group(1)) except Exception: pass self._record_event("reservation_back_operation", meta) 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