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 CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json") def find_adb_executable() -> str: """返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。""" adb = shutil.which("adb") if adb: return adb # 默认安装目录(我们之前下载的 platform-tools) localapp = os.environ.get("LOCALAPPDATA") or "" candidates = [] if localapp: candidates.append(os.path.join(localapp, "platform-tools", "adb.exe")) # 兼容某些人手动放到用户目录的情况 userprofile = os.environ.get("USERPROFILE") or "" if userprofile: candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe")) for p in candidates: if os.path.exists(p): return p return "" def list_adb_devices(adb_exe: str) -> list[str]: try: if not adb_exe: return [] proc = subprocess.run( [adb_exe, "devices", "-l"], capture_output=True, text=True, encoding="utf-8", errors="replace", ) except FileNotFoundError: return [] text = (proc.stdout or "") + "\n" + (proc.stderr or "") pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b" return re.findall(pattern, text) def read_config() -> dict: if not os.path.exists(CONFIG_PATH): return {} with open(CONFIG_PATH, "r", encoding="utf-8") as f: return json.load(f) def write_config(cfg: dict) -> None: with open(CONFIG_PATH, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=4) f.write("\n") @dataclass class RunParams: device_id: str y_pianyi: int needswitch: bool wait_minutes: int skip_if_countdown_gt_seconds: int reset_after_swipes_enabled: bool reset_after_swipes: int min_prize_value_yuan: float min_participants: int max_participants: int auto_join_fansclub: bool fansclub_fail_action: str # Web端新增参数 high_value_room_revisit_enabled: bool high_value_room_revisit_only_current_run: bool reservation_back_verify_enabled: bool reservation_back_swipe_delay: float reservation_preempt_min_value: float fudai_find_max_attempts: int enable_ocr_mode1: bool fudai_template_match_enabled: bool fudai_template_match_threshold: float 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._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 def is_running(self) -> bool: return self._proc is not None and self._proc.poll() is None 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 _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() # --- 福袋:抽取"最近一次"识别到的信息 --- if "福袋内容:" in s: with self._lock: self._fudai_last["content"] = s.split("福袋内容:", 1)[1].strip() self._fudai_last["updated_ts"] = time.time() self._inc("fudai_seen") self._record_event("fudai_seen", self._snapshot_fudai()) 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 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() self._fudai_last["updated_ts"] = time.time() m = re.search(r"奖品价值:\s*([0-9]+(?:\.[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: self._inc("fudai_open_detail") self._record_event("fudai_open_detail", self._snapshot_fudai()) if "点击参与抽奖" in s or ("[参与]" in s and "动作=点击参与" in s): self._inc("fudai_click_attend") self._record_event("fudai_click_attend", self._snapshot_fudai()) # 参与成功/已参与 if ( "已经参与,等待开奖" in s or "已经参与,等待看播时间凑齐开奖" in s or "已参与成功(或看播中)" in s or ("[参与]" in s and ("结果=已参与" in s or "结果=看播中" in s)) ): self._inc("fudai_attend_ok") self._record_event("fudai_attend_ok", self._snapshot_fudai()) if "参与抽奖失败" in s: self._inc("fudai_attend_fail") self._record_event("fudai_attend_fail", self._snapshot_fudai()) # --- 福袋:跳过/过滤原因 --- if "参与人数" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_low") self._record_event("fudai_skip", {"reason": "participants_low", **self._snapshot_fudai()}) if "参与人数" in s and "> 阈值" in s and "不参与" in s: self._inc("fudai_skip_participants_high") self._record_event("fudai_skip", {"reason": "participants_high", **self._snapshot_fudai()}) if "奖品价值" in s and "< 阈值" in s and "不参与" in s: self._inc("fudai_skip_value_low") self._record_event("fudai_skip", {"reason": "value_low", **self._snapshot_fudai()}) if "福袋内容不理想" 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") self._record_event("fudai_skip", {"reason": "countdown_short", **self._snapshot_fudai()}) if "抽奖倒计时时间大于" in s and "暂不参与" in s: self._inc("fudai_skip_countdown_long") self._record_event("fudai_skip", {"reason": "countdown_long", **self._snapshot_fudai()}) 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: 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 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: self._inc("fudai_result_no_win") self._record_event("fudai_result_no_win", self._snapshot_fudai()) if "恭喜中奖了" in s or "检测到中奖结果" in s: self._inc("fudai_result_win") self._record_event("fudai_result_win", self._snapshot_fudai()) self._record_win() if "福袋商品下单成功" in s: self._inc("fudai_order_success") self._record_event("fudai_order_success", self._snapshot_fudai()) # --- 直播间切换(按原因粗分) --- if "上划切换直播间" 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" self._record_event("switch_room", {"reason": meta_reason, **self._snapshot_fudai()}) 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" cmd = [ sys.executable, os.path.join(os.path.dirname(__file__), "run_cli.py"), "--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.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.reservation_preempt_min_value > 0: cmd += ["--reservation-preempt-min-value", str(params.reservation_preempt_min_value)] # 找福袋最大尝试次数 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)]) # 继承当前环境,并确保 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._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", env=env, cwd=os.path.dirname(__file__), ) 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 = [] def _reader(): assert self._proc is not None out = self._proc.stdout if out is None: return for line in out: cleaned_line = line.rstrip("\n") self._on_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 self._on_line(f"[进程结束] exit_code={rc}") self._reader_thread = threading.Thread(target=_reader, daemon=True) self._reader_thread.start() def start_test_yanghao_flow(self, device_id: str, seconds: int) -> None: if self.is_running(): raise RuntimeError("已经在运行") seconds = int(seconds or 0) if seconds <= 0: seconds = 90 cmd = [ sys.executable, os.path.join(os.path.dirname(__file__), "run_cli.py"), "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds), ] if device_id: cmd += ["--device-id", device_id] 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._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", env=env, cwd=os.path.dirname(__file__), ) 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 = [] def _reader(): assert self._proc is not None out = self._proc.stdout if out is None: return for line in out: cleaned_line = line.rstrip("\n") self._on_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 self._on_line(f"[进程结束] exit_code={rc}") self._reader_thread = threading.Thread(target=_reader, daemon=True) self._reader_thread.start() def start_test_comment(self, device_id: str, text: str) -> None: if self.is_running(): raise RuntimeError("已经在运行") text = str(text or "").strip() cmd = [ sys.executable, os.path.join(os.path.dirname(__file__), "run_cli.py"), "--test-comment", ] if text: cmd += ["--test-comment-text", text] if device_id: cmd += ["--device-id", device_id] 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._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH") p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", env=env, cwd=os.path.dirname(__file__), ) 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 = [] def _reader(): assert self._proc is not None out = self._proc.stdout if out is None: return for line in out: cleaned_line = line.rstrip("\n") self._on_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 self._on_line(f"[进程结束] exit_code={rc}") 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._on_line("[错误] 未找到 adb.exe") return False # 如果没有指定设备ID,尝试获取第一个可用设备 if not device_id or device_id.strip() == "": devices = list_adb_devices(adb_exe) if not devices: self._on_line("[错误] 未找到可用设备") return False device_id = devices[0] # 发送返回键 (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, ) if proc.returncode == 0: self._on_line(f"[手动操作] 已发送返回键到设备: {device_id}") return True else: error_msg = proc.stderr or proc.stdout or "未知错误" self._on_line(f"[错误] 发送返回键失败: {error_msg}") return False except subprocess.TimeoutExpired: self._on_line("[错误] 发送返回键超时") return False except Exception as e: self._on_line(f"[错误] 发送返回键异常: {str(e)}") return False def stop(self) -> None: if not self.is_running(): return assert self._proc is not None self._on_line("[停止] 正在终止进程...") self._proc.terminate() try: self._proc.wait(timeout=5) except subprocess.TimeoutExpired: self._on_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._on_line("[停止] 当前无记录中的运行进程") return self._on_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, ) else: # 类 Unix:尝试向进程组发送 SIGKILL import signal os.kill(pid, signal.SIGKILL) except Exception: pass with self._lock: self._proc = None self._pid = None