Files
douyi_guaji_main/web_gui.py
T
Your Name fe0098c591 feat: Enhance 福袋 template matching functionality
- Introduced a new configuration option to enable or disable 福袋 template matching, improving user control over the feature.
- Updated command-line arguments to support enabling and disabling the 福袋 template matching feature.
- Enhanced the GUI to include options for configuring 福袋 template matching settings.
- Improved error handling and logging in various modules to support the new functionality.
- Updated documentation to reflect changes in 福袋 template matching features and configuration options.
2025-12-22 04:05:22 +08:00

1494 lines
58 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.
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 typing import Optional
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")
# ANSI转义序列清理正则表达式
_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
def strip_ansi_escape_codes(text: str) -> str:
"""移除字符串中的ANSI转义序列(颜色代码等)。"""
if not isinstance(text, str):
return str(text)
return _ANSI_ESCAPE_RE.sub("", text)
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: Optional[subprocess.Popen] = None
self._lock = threading.Lock()
self._log: list[str] = []
self._log_capacity: int = (
10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
)
self._log_file_enabled: bool = True
self._log_file_path: str = os.path.join(BASE_DIR, "logs", "unified.log")
self._start_ts: Optional[float] = None
self._last_log_ts: Optional[float] = None
self._exit_code: Optional[int] = None
self._pid: Optional[int] = 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", 10000))
except Exception:
cap = 10000
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 as e:
# 目录创建失败,可能是权限问题,但继续尝试写入(可能目录已存在)
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")
f.flush() # 确保立即写入磁盘,避免缓冲区延迟导致日志丢失
except PermissionError as e:
# 权限错误,只输出一次警告避免刷屏
if not hasattr(self, "_log_permission_warned"):
print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_permission_warned = True
except Exception as e:
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
if not hasattr(self, "_log_write_error_warned"):
print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}")
print(f"[WEB_GUI] 错误详情: {e}")
self._log_write_error_warned = True
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: Optional[dict] = 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 # type: ignore[misc]
def _parse_countdown_seconds(text: str) -> Optional[int]:
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 # type: ignore[misc]
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 # type: ignore[misc]
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
# --- 统一日志格式解析:提取traceId和MDC信息 ---
# 格式:时间戳(毫秒) - [级别] - [线程名] - [模块名:函数名:行号] - [traceId:xxx] - 消息 | MDC: 上下文信息
trace_id_match = re.search(r'\[traceId:([^\]]+)\]', s)
if trace_id_match:
trace_id = trace_id_match.group(1)
# 存储当前traceId(用于统计和显示)
if not hasattr(self, '_current_trace_id'):
self._current_trace_id = trace_id
elif trace_id != 'N/A':
self._current_trace_id = trace_id
# 提取MDC信息
mdc_match = re.search(r'MDC:\s*([^|]+)', s)
if mdc_match:
mdc_str = mdc_match.group(1).strip()
# 解析MDC键值对
mdc_pairs = re.findall(r'(\w+)=([^,\s]+)', mdc_str)
for key, value in mdc_pairs:
# 存储MDC信息(可用于统计)
if not hasattr(self, '_mdc_context'):
self._mdc_context = {}
self._mdc_context[key] = value
# --- 福袋:抽取"最近一次"识别到的信息 ---
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
# 清理进程引用,避免后续 stop/状态查询混淆
with self._lock:
try:
self._proc = None
self._pid = None
except Exception:
pass
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
def _append_log(self, line: str) -> None:
# 清理ANSI转义序列,避免在Web界面显示异常字符
line = strip_ansi_escape_codes(line)
# 先写入统一文件:不受内存容量影响
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 meta is not None:
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), [float(x) for x in value_edges])
self._inc_map(value_buckets, b, 1)
p = meta.get("participants")
if isinstance(p, int):
b = self._bucket(float(p), [float(e) for e in 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), [float(e) for e in 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,
}
# 获取当前traceId和MDC上下文
current_trace_id = getattr(self, '_current_trace_id', None)
mdc_context = dict(getattr(self, '_mdc_context', {}))
# 获取当前traceId和MDC上下文
current_trace_id = getattr(self, '_current_trace_id', None)
mdc_context = dict(getattr(self, '_mdc_context', {}))
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:],
# 统一日志系统信息
"trace_id": current_trace_id,
"mdc_context": mdc_context,
"trace_id": current_trace_id,
"mdc_context": mdc_context,
}
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
log_len = len(self._log)
# 如果索引越界或等于日志长度(说明日志可能被截断了),返回所有日志
# 让前端能够检测到并重置索引
if idx >= log_len:
idx = 0
lines = self._log[idx:]
return log_len, 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)
# 启动时自动截图
if device_id:
try:
from Underlying_Operations import underlying_operations
ops = underlying_operations()
self._append_log(f"[启动] 自动截图: device={device_id}")
result = ops.get_screenshot(device_id)
if result:
self._append_log("[启动] 截图成功,已保存到 pic/screenshot.png")
else:
self._append_log("[启动] 截图失败")
except Exception as e:
self._append_log(f"[启动] 截图异常: {e}")
# 这些运行参数与 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)]
# OCR模式1开关(命令行优先)
enable_ocr_mode1 = bool(_pick("enable_ocr_mode1", False))
if enable_ocr_mode1:
cmd.append("--enable-ocr-mode1")
else:
cmd.append("--disable-ocr-mode1")
# 福袋模板匹配开关(命令行优先)
fudai_template_match_enabled = bool(_pick("fudai_template_match_enabled", False))
if fudai_template_match_enabled:
cmd.append("--fudai-template-enabled")
else:
cmd.append("--fudai-template-disabled")
# 福袋模板匹配阈值(命令行优先)
try:
fudai_template_match_threshold = float(_pick("fudai_template_match_threshold", 0.7) or 0.7)
if 0.0 <= fudai_template_match_threshold <= 1.0:
cmd += ["--fudai-template-threshold", str(fudai_template_match_threshold)]
except Exception:
pass
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,
bufsize=1, # 行缓冲模式,确保实时输出
)
# 立即记录进程信息并初始化状态
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._log = []
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)}")
self._append_log(f"[网页] 子进程 PID={p.pid} 已创建,准备启动读取线程")
def _reader() -> None:
self._append_log(f"[网页] 读取线程启动,监视 PID={p.pid}")
out = p.stdout
if out is None:
self._append_log(f"[网页] 读取线程:stdout 为 None,无法读取子进程输出")
try:
rc = p.wait()
except Exception:
rc = None
self._append_log(f"[网页] 进程退出(无输出):退出码={rc}")
with self._lock:
self._exit_code = rc
return
try:
# 使用迭代器读取,Python会自动处理缓冲
# 配合PYTHONUNBUFFERED=1和line_buffering=True,应该能实时获取输出
# iter(out.readline, '') 会在readline返回空字符串(EOF)时自动停止
for line in iter(out.readline, ""):
try:
cleaned_line = line.rstrip("\n\r")
if cleaned_line: # 忽略空行
self._append_log(cleaned_line)
except Exception:
# 避免单条日志处理异常中断读取循环
pass
except BrokenPipeError:
# 进程已关闭stdout
self._append_log(f"[网页] 读取线程:子进程stdout已关闭")
except Exception as e:
self._append_log(f"[网页] 读取线程异常:{e}")
try:
rc = p.wait(timeout=1)
except subprocess.TimeoutExpired:
rc = None
self._append_log(f"[网页] 等待进程退出超时,强制终止")
try:
p.kill()
rc = p.wait(timeout=5)
except Exception:
pass
except Exception:
rc = None
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("..\\") or ".." in safe:
self.send_error(HTTPStatus.FORBIDDEN)
return
full = os.path.join(WEBUI_DIR, safe)
# 额外安全检查:确保文件在 WEBUI_DIR 目录内
try:
full_real = os.path.realpath(full)
webui_real = os.path.realpath(WEBUI_DIR)
if not full_real.startswith(webui_real + os.sep) and full_real != webui_real:
self.send_error(HTTPStatus.FORBIDDEN)
return
except Exception:
self.send_error(HTTPStatus.FORBIDDEN)
return
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")
try:
with open(full, "rb") as f:
data = f.read()
# 对于静态资源,使用适当的缓存策略
cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600"
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", cache_control)
# 添加 ETag 支持(简单实现:基于文件大小和修改时间)
try:
stat = os.stat(full)
etag = f'"{stat.st_size}-{int(stat.st_mtime)}"'
self.send_header("ETag", etag)
# 检查 If-None-Match 头,支持 304 Not Modified
if_none_match = self.headers.get("If-None-Match", "")
if if_none_match == etag:
self.send_response(HTTPStatus.NOT_MODIFIED)
self.end_headers()
return
except Exception:
pass
self.end_headers()
self.wfile.write(data)
except FileNotFoundError:
self.send_error(HTTPStatus.NOT_FOUND)
except Exception as e:
print(f"[WEB_GUI] Error serving static file {rel_path}: {e}")
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
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 (ValueError, TypeError, IndexError):
since = 0
try:
next_idx, lines = RUNNER.get_logs_since(since)
return self._send_json(
{
"next": next_idx,
"lines": lines,
"running": RUNNER.is_running(),
}
)
except Exception as e:
# 记录错误但不中断请求,返回空日志
import traceback
print(
f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}"
)
return self._send_json(
{"next": 0, "lines": [], "running": RUNNER.is_running()}
)
if u.path == "/api/logfile-tail":
# 返回统一日志文件的尾部若干行,便于在内存日志不同步时调试
qs = parse_qs(u.query)
try:
n = int((qs.get("lines") or [100])[0])
except Exception:
n = 100
path = (
RUNNER._log_file_path
if hasattr(RUNNER, "_log_file_path")
else os.path.join(BASE_DIR, "logs", "unified.log")
)
out_lines = []
try:
if os.path.exists(path):
# 读取尾部若干行(简单实现:读全文件或最后 64KB)
size = os.path.getsize(path)
read_bytes = min(size, 65536)
with open(path, "rb") as f:
if read_bytes < size:
f.seek(-read_bytes, os.SEEK_END)
data = f.read().decode("utf-8", errors="replace")
parts = data.splitlines()
out_lines = parts[-n:]
except Exception:
out_lines = ["<failed to read logfile>"]
return self._send_json({"ok": True, "path": path, "lines": out_lines})
if u.path == "/api/actions":
# 返回精简行为日志(logs/actions.log)的尾部若干行,便于在 Web GUI 中单独查看点击/识别耗时
qs = parse_qs(u.query)
try:
n = int((qs.get("lines") or [200])[0])
except Exception:
n = 200
path = os.path.join(BASE_DIR, "logs", "actions.log")
out_lines: list[str] = []
try:
if os.path.exists(path):
size = os.path.getsize(path)
read_bytes = min(size, 65536)
with open(path, "rb") as f:
if read_bytes < size:
f.seek(-read_bytes, os.SEEK_END)
data = f.read().decode("utf-8", errors="replace")
parts = data.splitlines()
out_lines = parts[-n:]
except Exception:
out_lines = ["<failed to read actions.log>"]
return self._send_json({"ok": True, "path": path, "lines": out_lines})
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",
"skip_if_countdown_gt_seconds",
"reset_after_swipes",
"fudai_find_max_attempts",
"fudai_quiet_start_hour",
"fudai_quiet_end_hour",
"high_value_fudai_join_ahead_seconds",
"high_value_fudai_max_swipe_back",
"high_value_fudai_max_reservations",
"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",
"fudai_template_match_threshold",
"lucky_draw_red_ratio_threshold",
"live_room_match_threshold",
"stage_diag_max_time",
"stage_diag_max_step_time",
"fudai_icon_retry_delay_seconds",
"fudai_icon_max_wait_seconds",
"reservation_back_swipe_delay",
"reservation_preempt_min_value",
"high_value_fudai_threshold_yuan",
}
bool_keys = {
"auto_join_fansclub",
"reset_after_swipes_enabled",
"yanghao_enable_actions",
"yanghao_enabled",
"yanghao_step_screenshot",
"enable_ocr_mode1",
"fudai_template_match_enabled",
"fudai_quiet_hours_enabled",
"high_value_fudai_enabled",
"high_value_room_revisit_enabled",
"high_value_room_revisit_only_current_run",
"reservation_back_verify_enabled",
}
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",
}
def set_nested_value(obj, key, value):
"""设置嵌套配置值,支持如 'debug_captures.auto_cleanup' 这样的键"""
if "." in key:
parts = key.split(".")
current = obj
for part in parts[:-1]:
if part not in current or not isinstance(current[part], dict):
current[part] = {}
current = current[part]
current[parts[-1]] = value
else:
obj[key] = value
for k, v in (update or {}).items():
if k in deny_keys:
continue
if k in int_keys:
try:
set_nested_value(cfg, k, int(v))
except Exception:
continue
elif k in float_keys:
try:
set_nested_value(cfg, k, float(v))
except Exception:
continue
elif k in bool_keys:
set_nested_value(cfg, k, bool(v))
elif k in list_str_keys:
if isinstance(v, list):
set_nested_value(cfg, k, [str(x) for x in v if str(x).strip()])
else:
set_nested_value(cfg, k, [
str(x).strip()
for x in str(v).splitlines()
if str(x).strip()
])
else:
set_nested_value(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})
if u.path == "/api/screenshot":
# 手动截图接口
body = self._read_json()
device_id = str(body.get("device_id") or "").strip()
try:
from Underlying_Operations import underlying_operations
ops = underlying_operations()
result = ops.get_screenshot(device_id)
if result:
return self._send_json({"ok": True, "message": "截图成功"})
else:
return self._send_json(
{"ok": False, "error": "截图失败"}, status=500
)
except Exception as e:
return self._send_json({"ok": False, "error": str(e)}, status=500)
self.send_error(HTTPStatus.NOT_FOUND)
def log_message(self, format, *args): # type: ignore[override]
# 覆盖基类方法以抑制日志输出
# 参数名从 fmt 改为 format 以匹配基类签名
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())