import json import os import re import shutil import subprocess import sys import threading import time from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse BASE_DIR = os.path.dirname(__file__) CONFIG_PATH = os.path.join(BASE_DIR, "config.json") WEBUI_DIR = os.path.join(BASE_DIR, "webui") def find_adb_executable() -> str: adb = shutil.which("adb") if adb: return adb 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") class ProcRunner: def __init__(self) -> None: self._proc: subprocess.Popen | None = None self._lock = threading.Lock() self._log: list[str] = [] self._log_capacity: int = 2000 # 0=不限制(可能占用大量内存) self._log_file_enabled: bool = True self._log_file_path: str = os.path.join(BASE_DIR, "logs", "unified.log") self._start_ts: float | None = None self._last_log_ts: float | None = None self._exit_code: int | None = None self._pid: int | None = None # 运行统计(基于 stdout 日志解析) self._counters: dict[str, int] = {} self._fudai_last: dict[str, object] = { "content": "", "countdown": "", "participants": None, "copies": None, "prize_value_yuan": None, "updated_ts": None, } # 事件流(用于趋势/分布/Top 统计),保留最近 N 条 self._events: list[dict] = [] self._events_cap: int = 5000 # 中奖记录(用于展示“福袋中奖内容”),保留最近 N 条 self._wins: list[dict] = [] self._wins_cap: int = 200 def _reload_log_settings(self) -> None: """从 config.json 读取日志设置:统一文件路径 + Web GUI 内存缓存上限。""" try: cfg = read_config() except Exception: cfg = {} try: self._log_file_enabled = bool(cfg.get("log_unified_enabled", True)) except Exception: self._log_file_enabled = True path = str(cfg.get("log_unified_path") or "logs/unified.log") if not os.path.isabs(path): path = os.path.join(BASE_DIR, path) self._log_file_path = path try: cap = int(cfg.get("webgui_log_capacity", 2000)) except Exception: cap = 2000 self._log_capacity = cap def _append_to_unified_file(self, line: str) -> None: if not self._log_file_enabled: return try: os.makedirs(os.path.dirname(self._log_file_path), exist_ok=True) except Exception: pass try: # 使用 utf-8-sig:文件首次创建时会写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码 with open(self._log_file_path, "a", encoding="utf-8-sig", errors="replace") as f: f.write(line + "\n") except Exception: # 文件写失败不应影响主流程 pass def _inc(self, key: str, n: int = 1) -> None: self._counters[key] = int(self._counters.get(key, 0)) + int(n) def _record_event(self, typ: str, meta: dict | None = None) -> None: ev = { "ts": time.time(), "type": str(typ), "meta": meta or {}, } 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(), } self._wins.append(item) if len(self._wins) > self._wins_cap: self._wins = self._wins[-self._wins_cap:] @staticmethod def _parse_countdown_seconds(text: str) -> int | None: t = str(text or "").strip() if not t: return None # 优先解析 hh:mm:ss / mm:ss if ":" in t: parts = [p for p in t.split(":") if p != ""] try: nums = [int(p) for p in parts] except Exception: nums = [] if len(nums) == 2: mm, ss = nums return max(0, mm * 60 + ss) if len(nums) == 3: hh, mm, ss = nums return max(0, hh * 3600 + mm * 60 + ss) # 解析中文:xx小时xx分xx秒 total = 0 m = re.search(r"(\d+)\s*小时", t) if m: total += int(m.group(1)) * 3600 m = re.search(r"(\d+)\s*分", t) if m: total += int(m.group(1)) * 60 m = re.search(r"(\d+)\s*秒", t) if m: total += int(m.group(1)) if total > 0: return total # 兜底:纯数字当秒 if re.fullmatch(r"\d+", t): try: return int(t) except Exception: return None return None @staticmethod def _bucket(value: float, edges: list[float]) -> str: # edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+ if not edges: return "all" for i in range(len(edges) - 1): a = edges[i] b = edges[i + 1] if value >= a and value < b: return f"{a:g}-{b:g}" return f"{edges[-1]:g}+" @staticmethod def _inc_map(m: dict, k: str, n: int = 1) -> None: m[k] = int(m.get(k, 0)) + int(n) def _snapshot_fudai(self) -> dict: 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 # --- 福袋:抽取“最近一次”识别到的信息 --- if "福袋内容:" in s: 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: self._fudai_last["participants"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() m = re.search(r"福袋份数:\s*(\d+)", s) if m: self._fudai_last["copies"] = int(m.group(1)) self._fudai_last["updated_ts"] = time.time() if "倒计时时间:" in s: 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: 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()}) # --- 性能:进入直播间到识别福袋耗时 --- m = re.search(r"进入直播间到识别福袋耗时:\s*([0-9]+(?:\.[0-9]+)?)\s*秒(?:\s*进入原因=(.*))?", s) if m: try: secs = float(m.group(1)) except Exception: secs = None reason = str(m.group(2) or "") # 记录为事件,便于后续做分布/趋势分析 self._record_event("enter_to_fudai_seen", {"secs": secs, "enter_reason": reason, **self._snapshot_fudai()}) # 同时做一个计数器 try: self._inc("enter_to_fudai_seen") except Exception: pass def is_running(self) -> bool: with self._lock: return self._proc is not None and self._proc.poll() is None def get_reservations(self) -> dict: """获取当前预约队列信息(来自子进程写入的 state/reservations.json)。""" path = os.path.join(BASE_DIR, "state", "reservations.json") try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, dict): return data except Exception: return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "state_read_or_parse_failed"} return {"reservations": [], "room_pos": 0, "updated_ts": 0.0, "reason": "no_state_file"} def get_high_value_rooms(self) -> dict: """获取永久记录的高价值直播间列表(来自 state/high_value_rooms.json)。""" path = os.path.join(BASE_DIR, "state", "high_value_rooms.json") try: if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: data = json.load(f) if isinstance(data, dict): return data if isinstance(data, list): return {"updated_ts": 0.0, "reason": "legacy_list", "total": len(data), "rooms": data} except Exception: return {"updated_ts": 0.0, "reason": "state_read_or_parse_failed", "total": 0, "rooms": []} return {"updated_ts": 0.0, "reason": "no_state_file", "total": 0, "rooms": []} def stop(self) -> None: with self._lock: p = self._proc if p is None or p.poll() is not None: return self._append_log("[网页] 停止:终止进程") try: p.terminate() p.wait(timeout=5) except Exception: try: p.kill() except Exception: pass def _append_log(self, line: str) -> None: # 先写入统一文件:不受内存容量影响 self._append_to_unified_file(line) with self._lock: self._log.append(line) self._last_log_ts = time.time() # 在持锁状态内更新统计,避免并发读写 counters try: self._update_stats_from_line(line) except Exception: pass cap = int(self._log_capacity or 0) if cap > 0 and len(self._log) > cap: self._log = self._log[-cap:] def get_stats(self, include_events: bool = False) -> 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 log_len = len(self._log) counters = dict(self._counters) fudai_last = dict(self._fudai_last) events = list(self._events) wins = list(self._wins) now = time.time() uptime = 0 if start_ts and start_ts > 0: uptime = int(max(0, now - start_ts)) # ===== 统计聚合(趋势/分布/Top) ===== now = time.time() window_seconds = 2 * 3600 bin_seconds = 5 * 60 bins = int(window_seconds // bin_seconds) ts0 = int(now - window_seconds) def _bin_idx(ts: float) -> int: i = int((ts - ts0) // bin_seconds) if i < 0: return -1 if i >= bins: return -1 return i series = { "fudai_open_detail": [0] * bins, "fudai_attend_ok": [0] * bins, "fudai_attend_fail": [0] * bins, "fudai_result_win": [0] * bins, "fudai_result_no_win": [0] * bins, "fudai_skip": [0] * bins, "switch_room": [0] * bins, } skip_reason = {} switch_reason = {} value_buckets = {} participants_buckets = {} countdown_buckets = {} content_top = {} # 桶边界 value_edges = [0, 10, 50, 100, 200, 500] participants_edges = [0, 100, 500, 1000, 5000, 10000] countdown_edges = [0, 30, 60, 5 * 60, 15 * 60, 60 * 60] for ev in events: ts = float(ev.get("ts") or 0) typ = str(ev.get("type") or "") meta = ev.get("meta") if isinstance(ev.get("meta"), dict) else {} bi = _bin_idx(ts) if bi >= 0: if typ in series: series[typ][bi] += 1 if typ == "fudai_skip": series["fudai_skip"][bi] += 1 if typ == "switch_room": series["switch_room"][bi] += 1 # 分布/Top if typ == "fudai_skip": r = str(meta.get("reason") or "unknown") self._inc_map(skip_reason, r, 1) if typ == "switch_room": r = str(meta.get("reason") or "unknown") self._inc_map(switch_reason, r, 1) content = str(meta.get("content") or "").strip() if content: # 只取前 60 字符作为展示 key,避免超长撑爆 key = (content[:60] + "…") if len(content) > 60 else content self._inc_map(content_top, key, 1) v = meta.get("prize_value_yuan") if isinstance(v, (int, float)): b = self._bucket(float(v), value_edges) self._inc_map(value_buckets, b, 1) p = meta.get("participants") if isinstance(p, int): b = self._bucket(float(p), participants_edges) self._inc_map(participants_buckets, b, 1) cd = meta.get("countdown") if isinstance(cd, str) and cd.strip(): sec = self._parse_countdown_seconds(cd) if isinstance(sec, int): b = self._bucket(float(sec), countdown_edges) self._inc_map(countdown_buckets, b, 1) def _top_k(m: dict, k: int = 10) -> list[dict]: items = [{"key": kk, "count": int(vv)} for kk, vv in m.items()] items.sort(key=lambda x: x["count"], reverse=True) return items[:k] timeline = { "start_ts": ts0, "bin_seconds": bin_seconds, "bins": bins, "series": series, } agg = { "skip_reason": skip_reason, "switch_reason": switch_reason, "value_buckets": value_buckets, "participants_buckets": participants_buckets, "countdown_buckets": countdown_buckets, "content_top": _top_k(content_top, 12), "timeline": timeline, } payload = { "running": bool(running), "pid": pid, "start_ts": start_ts, "last_log_ts": last_log_ts, "exit_code": exit_code, "uptime_seconds": uptime, "log_len": log_len, "log_capacity": int(self._log_capacity or 0), "log_file": self._log_file_path if self._log_file_enabled else "", "counters": counters, "fudai_last": fudai_last, "agg": agg, # 仅返回最近 20 条,避免过大 "wins": wins[-20:], } if include_events: # 仅返回最近 200 条,防止数据过大 tail = events[-200:] payload["events"] = tail return payload def get_logs_since(self, idx: int) -> tuple[int, list[str]]: with self._lock: if idx < 0: idx = 0 if idx > len(self._log): idx = len(self._log) lines = self._log[idx:] return len(self._log), lines def start_test_yanghao(self, device_id: str, seconds: int) -> None: if self.is_running(): raise RuntimeError("already running") seconds = int(seconds or 0) if seconds <= 0: seconds = 60 cmd = [ sys.executable, os.path.join(BASE_DIR, "run_cli.py"), "--test-yanghao-flow", "--test-yanghao-flow-seconds", str(seconds), ] if device_id: cmd += ["--device-id", device_id] self._start_process(cmd) def start_test_comment(self, device_id: str, text: str) -> None: if self.is_running(): raise RuntimeError("already running") text = str(text or "").strip() cmd = [ sys.executable, os.path.join(BASE_DIR, "run_cli.py"), "--test-comment", ] if text: cmd += ["--test-comment-text", text] if device_id: cmd += ["--device-id", device_id] self._start_process(cmd) def start_main_run(self, params: dict) -> None: if self.is_running(): raise RuntimeError("already running") cfg = {} try: cfg = read_config() or {} except Exception: cfg = {} def _pick(key: str, default): if isinstance(params, dict) and key in params and params.get(key) is not None: return params.get(key) if isinstance(cfg, dict) and key in cfg and cfg.get(key) is not None: return cfg.get(key) return default device_id = str(_pick("device_id", "") or "").strip() y_pianyi = int(_pick("y_pianyi", 0) or 0) needswitch = bool(_pick("needswitch", False)) reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False)) wait_minutes = int(_pick("wait_minutes", 5) or 5) # 这些运行参数与 run_cli.py --help 对齐 min_prize_value_yuan = float(_pick("min_prize_value_yuan", 0) or 0) min_participants = int(_pick("min_participants", 0) or 0) max_participants = int(_pick("max_participants", 0) or 0) skip_if_countdown_lt_seconds = int(_pick("skip_if_countdown_lt_seconds", 15) or 15) try: reset_after_swipes = int(_pick("reset_after_swipes", 10)) except Exception: reset_after_swipes = 10 if reset_after_swipes < 1: reset_after_swipes = 1 auto_join_fansclub = bool(_pick("auto_join_fansclub", False)) fansclub_fail_action = str(_pick("fansclub_fail_action", "") or "").strip().lower() cmd = [ sys.executable, os.path.join(BASE_DIR, "run_cli.py"), "--y-pianyi", str(y_pianyi), "--wait-minutes", str(wait_minutes), "--min-prize-value-yuan", str(min_prize_value_yuan), "--skip-if-countdown-lt-seconds", str(skip_if_countdown_lt_seconds), ] if device_id: cmd += ["--device-id", device_id] if needswitch: cmd.append("--needswitch") if reset_after_swipes_enabled: cmd.append("--reset-after-swipes-enabled") cmd += ["--reset-after-swipes", str(reset_after_swipes)] else: cmd.append("--reset-after-swipes-disabled") if min_participants > 0: cmd += ["--min-participants", str(min_participants)] if max_participants > 0: cmd += ["--max-participants", str(max_participants)] if auto_join_fansclub: cmd.append("--auto-join-fansclub") if fansclub_fail_action: cmd += ["--fansclub-fail-action", fansclub_fail_action] # 高价值直播间回访运行时开关(由 GUI 在启动时覆盖) high_value_room_revisit_enabled = bool(_pick("high_value_room_revisit_enabled", True)) high_value_room_revisit_only_current_run = bool(_pick("high_value_room_revisit_only_current_run", False)) if high_value_room_revisit_enabled: cmd.append("--high-value-room-revisit-enabled") else: cmd.append("--high-value-room-revisit-disabled") if high_value_room_revisit_only_current_run: cmd.append("--high-value-room-revisit-only-current-run") # 预约回退校验开关(由 Run 面板控制) reservation_back_verify_enabled = bool(_pick("reservation_back_verify_enabled", True)) if reservation_back_verify_enabled: cmd.append("--reservation-back-verify-enabled") else: cmd.append("--reservation-back-verify-disabled") # 回退回滑快速延迟(可由 Run 面板设置):仅在未启用回退校验时生效 try: rbd = float(_pick("reservation_back_swipe_delay", 0) or 0) except Exception: rbd = 0.0 if rbd > 0: cmd += ["--reservation-back-swipe-delay", str(rbd)] # 预约抢占最小价值(GUI 启动时可覆盖) try: rpmin = float(_pick("reservation_preempt_min_value", 0) or 0) except Exception: rpmin = 0.0 if rpmin > 0: cmd += ["--reservation-preempt-min-value", str(rpmin)] # 找福袋最大尝试次数(GUI 启动时可覆盖) try: fudai_find_max_attempts = int(_pick("fudai_find_max_attempts", 0) or 0) except Exception: fudai_find_max_attempts = 0 if fudai_find_max_attempts > 0: cmd += ["--fudai-find-max-attempts", str(fudai_find_max_attempts)] self._start_process(cmd) def _start_process(self, cmd: list[str]) -> None: # 每次启动前刷新一次日志设置 self._reload_log_settings() env = os.environ.copy() env.setdefault("PYTHONIOENCODING", "utf-8") env.setdefault("PYTHONUNBUFFERED", "1") # 尽量减少第三方库的英文噪声日志(不影响主逻辑) env.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True") env.setdefault("PYTHONWARNINGS", "ignore") # 若启用统一日志文件:由 Web GUI 负责落盘,子进程不再 Tee 到文件,避免重复写入 if self._log_file_enabled: env["NO_TEE_STDOUT"] = "1" 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 p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", env=env, cwd=BASE_DIR, ) 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._append_log(f"[网页] 启动:{' '.join(cmd)}") def _reader() -> None: out = p.stdout if out is None: return for line in out: self._append_log(line.rstrip("\n")) rc = p.wait() self._append_log(f"[网页] 进程退出:退出码={rc}") with self._lock: self._exit_code = rc threading.Thread(target=_reader, daemon=True).start() RUNNER = ProcRunner() class Handler(BaseHTTPRequestHandler): def _send_json(self, obj, status: int = 200) -> None: data = json.dumps(obj, ensure_ascii=False).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def _read_json(self) -> dict: n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n > 0 else b"{}" try: return json.loads(raw.decode("utf-8")) except Exception: return {} def _serve_static(self, rel_path: str) -> None: rel_path = rel_path.lstrip("/") if not rel_path: rel_path = "index.html" safe = os.path.normpath(rel_path).replace("\\", "/") if safe.startswith("../") or safe.startswith("..\\"): self.send_error(HTTPStatus.FORBIDDEN) return full = os.path.join(WEBUI_DIR, safe) if not os.path.isfile(full): self.send_error(HTTPStatus.NOT_FOUND) return ext = os.path.splitext(full)[1].lower() ctype = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "application/javascript; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml; charset=utf-8", }.get(ext, "application/octet-stream") with open(full, "rb") as f: data = f.read() self.send_response(HTTPStatus.OK) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) def do_GET(self): u = urlparse(self.path) if u.path.startswith("/api/"): api_path = u.path.rstrip("/") if u.path == "/api/devices": adb = find_adb_executable() return self._send_json({"adb": adb, "devices": list_adb_devices(adb)}) if u.path == "/api/config": cfg = read_config() return self._send_json(cfg) if u.path == "/api/stats": qs = parse_qs(u.query) detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in ("1", "true", "yes") return self._send_json(RUNNER.get_stats(include_events=detail)) if api_path in ("/api/reservations", "/api/reservation"): # 返回当前预约队列信息 return self._send_json(RUNNER.get_reservations()) if api_path in ( "/api/high-value-rooms", "/api/high_value_rooms", "/api/high_value_room", "/api/high-value-room", ): return self._send_json(RUNNER.get_high_value_rooms()) if u.path == "/api/logs": qs = parse_qs(u.query) since = 0 try: since = int((qs.get("since") or [0])[0]) except Exception: since = 0 next_idx, lines = RUNNER.get_logs_since(since) return self._send_json({"next": next_idx, "lines": lines, "running": RUNNER.is_running()}) self.send_error(HTTPStatus.NOT_FOUND) return if u.path.startswith("/pic/"): # 只允许读取 pic 目录下的文件(便于前端预览 latest.png) rel = u.path.lstrip("/") safe = os.path.normpath(rel).replace("\\", "/") if not safe.startswith("pic/"): self.send_error(HTTPStatus.FORBIDDEN) return full = os.path.join(BASE_DIR, safe) if not os.path.isfile(full): self.send_error(HTTPStatus.NOT_FOUND) return ext = os.path.splitext(full)[1].lower() ctype = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}.get(ext, "application/octet-stream") with open(full, "rb") as f: data = f.read() self.send_response(HTTPStatus.OK) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) return self._serve_static(u.path) def do_POST(self): u = urlparse(self.path) if u.path == "/api/config": body = self._read_json() cfg = read_config() update = body.get("config") if isinstance(body.get("config"), dict) else body int_keys = { "min_participants", "max_participants", "skip_if_countdown_lt_seconds", "reset_after_swipes", "yanghao_like_icon_x", "yanghao_like_icon_y", "yanghao_fav_icon_x", "yanghao_fav_icon_y", "yanghao_like_roi_offset_x", "yanghao_like_roi_offset_y", "yanghao_fav_roi_offset_x", "yanghao_fav_roi_offset_y", "yanghao_icon_roi_size", "yanghao_comment_btn_x", "yanghao_comment_btn_y", "yanghao_comment_input_x", "yanghao_comment_input_y", "yanghao_comment_send_x", "yanghao_comment_send_y", "yanghao_comment_close_x", "yanghao_comment_close_y", "yanghao_after_dwell_swipe_distance_px", "yanghao_recommend_duration_seconds", "yanghao_recommend_interval_seconds", } float_keys = { "min_prize_value_yuan", "yanghao_like_prob", "yanghao_fav_prob", "yanghao_comment_prob", "yanghao_icon_match_threshold", } bool_keys = { "auto_join_fansclub", "reset_after_swipes_enabled", "yanghao_enable_actions", "yanghao_enabled", "yanghao_step_screenshot", } list_str_keys = { "contains_want", "contains_not_want", "yanghao_comment_texts", "yanghao_like_keywords", "yanghao_fav_keywords", } deny_keys = { "yanghao_use_recommend_flow", "yanghao_text_recommend", "yanghao_text_live", "yanghao_text_enter_live", "yanghao_fallback_close_x", "yanghao_fallback_close_y", "yanghao_fallback_recommend_x", "yanghao_fallback_recommend_y", "yanghao_fallback_live_x", "yanghao_fallback_live_y", "yanghao_fallback_enter_live_x", "yanghao_fallback_enter_live_y", } for k, v in (update or {}).items(): if k in deny_keys: continue if k in int_keys: try: cfg[k] = int(v) except Exception: continue elif k in float_keys: try: cfg[k] = float(v) except Exception: continue elif k in bool_keys: cfg[k] = bool(v) elif k in list_str_keys: if isinstance(v, list): cfg[k] = [str(x) for x in v if str(x).strip()] else: cfg[k] = [str(x).strip() for x in str(v).splitlines() if str(x).strip()] else: cfg[k] = v write_config(cfg) return self._send_json({"ok": True}) if u.path == "/api/start-run": if RUNNER.is_running(): return self._send_json({"ok": False, "error": "running"}, status=409) body = self._read_json() try: RUNNER.start_main_run(body or {}) except Exception as e: return self._send_json({"ok": False, "error": str(e)}, status=500) return self._send_json({"ok": True}) if u.path == "/api/test-yanghao": if RUNNER.is_running(): return self._send_json({"ok": False, "error": "running"}, status=409) body = self._read_json() device_id = str(body.get("device_id") or "").strip() seconds = int(body.get("seconds") or 60) try: RUNNER.start_test_yanghao(device_id, seconds) except Exception as e: return self._send_json({"ok": False, "error": str(e)}, status=500) return self._send_json({"ok": True}) if u.path == "/api/test-comment": if RUNNER.is_running(): return self._send_json({"ok": False, "error": "running"}, status=409) body = self._read_json() device_id = str(body.get("device_id") or "").strip() text = str(body.get("text") or "").strip() try: RUNNER.start_test_comment(device_id, text) except Exception as e: return self._send_json({"ok": False, "error": str(e)}, status=500) return self._send_json({"ok": True}) if u.path == "/api/stop": RUNNER.stop() return self._send_json({"ok": True}) self.send_error(HTTPStatus.NOT_FOUND) def log_message(self, fmt, *args): return def main() -> int: host = "127.0.0.1" # 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000 env_port = os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "8000" try: port = int(env_port) except Exception: port = 8000 if port < 1 or port > 65535: port = 8000 print(f"[WEBGUI] 启动端口={port}(可设置环境变量 PORT 覆盖)") try: httpd = ThreadingHTTPServer((host, port), Handler) except OSError as e: print(f"[WEBGUI] 端口 {port} 启动失败:{e}") print("[WEBGUI] 处理建议:1) 关闭占用该端口的进程 2) 改为其他端口,例如前置设置 PORT=8001") raise print(f"Web GUI: http://{host}:{port}") print("- 可在页面里设置养号时长/间隔并保存到 config.json") print("- 可一键运行‘测试养号流程’,日志会在页面里滚动显示") try: httpd.serve_forever() except KeyboardInterrupt: print("[WEBGUI] 收到中断,退出") return 0 if __name__ == "__main__": try: from version import print_version_banner print_version_banner("web_gui") except Exception: pass raise SystemExit(main())