1740 lines
68 KiB
Python
1740 lines
68 KiB
Python
import json
|
||
import os
|
||
import re
|
||
import secrets
|
||
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
|
||
|
||
# Add project root to Python path
|
||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
if project_root not in sys.path:
|
||
sys.path.insert(0, project_root)
|
||
|
||
from douyin.core import path_config
|
||
|
||
# 从子包 re-export 顶层 helper(保持兼容)
|
||
from gui.web_gui_pkg import (
|
||
_LOGGER,
|
||
_wg_log,
|
||
strip_ansi_escape_codes,
|
||
find_adb_executable,
|
||
list_adb_devices,
|
||
resolve_adb_device,
|
||
read_config,
|
||
write_config,
|
||
get_nested_value,
|
||
_bucket,
|
||
_inc_map,
|
||
_parse_countdown_seconds,
|
||
)
|
||
from gui.web_gui_pkg.request_parsing import read_json, send_json
|
||
from gui.web_gui_pkg.static_handler import serve_static
|
||
|
||
BASE_DIR = path_config.PROJECT_ROOT
|
||
CONFIG_PATH = path_config.get_config_path()
|
||
WEBUI_DIR = path_config.get_webui_dir()
|
||
|
||
import logging as _logging
|
||
|
||
# 模块级 logger:内部错误统一走 logging。
|
||
# 启动横幅和中断消息保留 print(属于交互/CLI 输出,不是日志事件)。
|
||
_LOGGER = _logging.getLogger("gui.web_gui")
|
||
|
||
|
||
|
||
|
||
# CSRF token for POST request protection (local-only server)
|
||
_CSRF_TOKEN = secrets.token_hex(32)
|
||
|
||
|
||
class ProcRunner:
|
||
@staticmethod # type: ignore[misc]
|
||
def _parse_countdown_seconds(text):
|
||
return _parse_countdown_seconds(text)
|
||
|
||
@staticmethod # type: ignore[misc]
|
||
def _bucket(value, edges):
|
||
return _bucket(value, edges)
|
||
|
||
@staticmethod # type: ignore[misc]
|
||
def _inc_map(m, k, n=1):
|
||
return _inc_map(m, k, n)
|
||
|
||
def __init__(self) -> None:
|
||
self._proc: Optional[subprocess.Popen] = None
|
||
self._lock = threading.Lock()
|
||
self._pid_lock = threading.Lock() # 保护 PID 相关操作
|
||
self._log: list[str] = []
|
||
self._log_capacity: int = (
|
||
10000 # 0=不限制(可能占用大量内存),增加到10000避免日志被过早截断
|
||
)
|
||
self._log_file_enabled: bool = True
|
||
self._log_file_path: str = path_config.get_log_file_path()
|
||
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,
|
||
}
|
||
|
||
# 延迟属性:预先声明,避免静态检查报“在 __init__ 外定义属性”
|
||
self._log_permission_warned: bool = False
|
||
self._log_write_error_warned: bool = False
|
||
self._current_trace_id: str = ""
|
||
self._mdc_context: dict[str, str] = {}
|
||
|
||
# 事件流(用于趋势/分布/Top 统计),保留最近 N 条
|
||
self._events: list[dict] = []
|
||
self._events_cap: int = 5000
|
||
|
||
# 中奖记录(用于展示“福袋中奖内容”),保留最近 N 条
|
||
self._wins: list[dict] = []
|
||
self._wins_cap: int = 200
|
||
|
||
# 已记录福袋识别的跟踪(避免同一个直播间同一个福袋重复记录识别次数)
|
||
self._recorded_fudai_seen: set[tuple[str, str]] = (
|
||
set()
|
||
) # (room_title, fudai_content)
|
||
|
||
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(path_config.PROJECT_ROOT, 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 self._log_permission_warned:
|
||
_wg_log(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}", level="WARNING")
|
||
_wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING")
|
||
self._log_permission_warned = True
|
||
except Exception as e:
|
||
# 其他文件写失败不应影响主流程,但记录第一次错误以便调试
|
||
if not self._log_write_error_warned:
|
||
_wg_log(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}", level="WARNING")
|
||
_wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING")
|
||
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 :]
|
||
|
||
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:
|
||
"""委托到 gui/web_gui_pkg/stats_log_parser.update_stats_from_line。"""
|
||
from gui.web_gui_pkg.stats_log_parser import update_stats_from_line
|
||
update_stats_from_line(self, line)
|
||
|
||
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:
|
||
"""获取当前预约队列信息(来自子进程写入的 douyin/core/state/reservations.json)。"""
|
||
if hasattr(path_config, "get_reservations_path"):
|
||
try:
|
||
path = path_config.get_reservations_path()
|
||
except Exception:
|
||
path = os.path.join(
|
||
(
|
||
path_config.PROJECT_ROOT
|
||
if hasattr(path_config, "PROJECT_ROOT")
|
||
else os.getcwd()
|
||
),
|
||
"douyin",
|
||
"core",
|
||
"state",
|
||
"reservations.json",
|
||
)
|
||
else:
|
||
path = os.path.join(
|
||
os.getcwd(), "douyin", "core", "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 = path_config.get_high_value_rooms_path()
|
||
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 send_back_key(self, device_id: str) -> bool:
|
||
try:
|
||
adb = find_adb_executable()
|
||
if not adb:
|
||
self._append_log("[错误] 未找到 adb.exe")
|
||
return False
|
||
if not device_id:
|
||
try:
|
||
device_id = resolve_adb_device(adb)
|
||
except Exception as e:
|
||
self._append_log(f"[错误] 设备选择失败: {e}")
|
||
return False
|
||
proc = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "input", "keyevent", "4"],
|
||
capture_output=True,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
timeout=5,
|
||
check=False,
|
||
)
|
||
if proc.returncode == 0:
|
||
self._append_log(f"[手动操作] 已发送返回键到设备: {device_id}")
|
||
return True
|
||
self._append_log(f"[错误] 发送返回键失败: {(proc.stderr or proc.stdout or '').strip()}")
|
||
return False
|
||
except Exception as e:
|
||
self._append_log(f"[错误] 发送返回键异常: {e}")
|
||
return False
|
||
|
||
def force_stop(self) -> None:
|
||
with self._pid_lock:
|
||
with self._lock:
|
||
pid = self._pid
|
||
p = self._proc
|
||
self._append_log(f"[停止] 强制停止请求 pid={pid or '-'}")
|
||
try:
|
||
if p is not None and p.poll() is None:
|
||
p.kill()
|
||
except Exception:
|
||
pass
|
||
if pid:
|
||
try:
|
||
if os.name == "nt":
|
||
subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True, check=False, timeout=10)
|
||
else:
|
||
subprocess.run(["kill", "-9", str(pid)], capture_output=True, text=True, check=False, timeout=10)
|
||
except Exception as e:
|
||
self._append_log(f"[停止] 系统强制结束失败: {e}")
|
||
with self._lock:
|
||
self._proc = None
|
||
self._pid = None
|
||
self._exit_code = self._exit_code if self._exit_code is not None else -9
|
||
self._append_log("[停止] 强制停止完成")
|
||
|
||
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", {}))
|
||
|
||
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,
|
||
}
|
||
|
||
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
|
||
|
||
run_cli_path = path_config.get_run_cli_path()
|
||
if not os.path.exists(run_cli_path):
|
||
raise FileNotFoundError(
|
||
f"run_cli.py not found.\n"
|
||
f"Expected path: {run_cli_path}\n"
|
||
f"Please ensure run_cli.py is in the project root directory."
|
||
)
|
||
cmd = [
|
||
sys.executable,
|
||
run_cli_path,
|
||
"--test-yanghao-flow",
|
||
"--test-yanghao-flow-seconds",
|
||
str(seconds),
|
||
]
|
||
device_id = resolve_adb_device(find_adb_executable(), 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()
|
||
run_cli_path = path_config.get_run_cli_path()
|
||
if not os.path.exists(run_cli_path):
|
||
raise FileNotFoundError(
|
||
f"run_cli.py not found.\n"
|
||
f"Expected path: {run_cli_path}\n"
|
||
f"Please ensure run_cli.py is in the project root directory."
|
||
)
|
||
cmd = [
|
||
sys.executable,
|
||
run_cli_path,
|
||
"--test-comment",
|
||
]
|
||
if text:
|
||
cmd += ["--test-comment-text", text]
|
||
device_id = resolve_adb_device(find_adb_executable(), 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):
|
||
val = get_nested_value(cfg, key, None) if "." in key else cfg.get(key)
|
||
if val is not None:
|
||
return val
|
||
return default
|
||
|
||
device_id = str(_pick("device_id", "") or "").strip()
|
||
adb = find_adb_executable()
|
||
device_id = resolve_adb_device(adb, device_id)
|
||
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))
|
||
try:
|
||
wait_minutes = int(_pick("wait_minutes", 5))
|
||
except Exception:
|
||
wait_minutes = 5
|
||
if wait_minutes < 0:
|
||
wait_minutes = 0
|
||
|
||
# 启动时自动截图
|
||
if device_id:
|
||
try:
|
||
from douyin.core.underlying_operations import underlying_operations
|
||
|
||
ops = underlying_operations()
|
||
self._append_log(f"[启动] 自动截图: device={device_id}")
|
||
result = ops.get_screenshot(device_id, use_service=False)
|
||
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
|
||
)
|
||
skip_if_countdown_gt_seconds = int(
|
||
_pick("skip_if_countdown_gt_seconds", 900) or 900
|
||
)
|
||
try:
|
||
reset_after_swipes = int(_pick("reset_after_swipes", 10) or 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()
|
||
)
|
||
|
||
run_cli_path = path_config.get_run_cli_path()
|
||
if not os.path.exists(run_cli_path):
|
||
raise FileNotFoundError(
|
||
f"run_cli.py not found.\n"
|
||
f"Expected path: {run_cli_path}\n"
|
||
f"Please ensure run_cli.py is in the project root directory."
|
||
)
|
||
cmd = [
|
||
sys.executable,
|
||
run_cli_path,
|
||
"--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),
|
||
"--skip-if-countdown-gt-seconds",
|
||
str(skip_if_countdown_gt_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")
|
||
reset_action = str(_pick("reset_after_swipes_action", "swipe") or "swipe").strip().lower()
|
||
if reset_action in ("swipe", "back"):
|
||
cmd += ["--reset-after-swipes-action", reset_action]
|
||
try:
|
||
swipe_down_back_count = int(_pick("swipe_down_back_count", 0) or 0)
|
||
except Exception:
|
||
swipe_down_back_count = 0
|
||
swipe_down_back_enabled = bool(_pick("swipe_down_back_enabled", False))
|
||
if swipe_down_back_enabled:
|
||
cmd.append("--swipe-down-back-enabled")
|
||
if swipe_down_back_count > 0:
|
||
cmd += ["--swipe-down-back-count", str(swipe_down_back_count)]
|
||
else:
|
||
cmd.append("--swipe-down-back-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")
|
||
try:
|
||
cmd += ["--high-value-room-revisit-min-interval-seconds", str(int(_pick("high_value_room_revisit_min_interval_seconds", 300) or 300))]
|
||
cmd += ["--high-value-room-revisit-max-per-run", str(int(_pick("high_value_room_revisit_max_per_run", 5) or 5))]
|
||
cmd += ["--high-value-room-revisit-min-prize-value", str(float(_pick("high_value_room_revisit_min_prize_value", 0.0) or 0.0))]
|
||
cmd += ["--high-value-room-revisit-max-age-days", str(int(_pick("high_value_room_revisit_max_age_days", 30) or 30))]
|
||
except Exception:
|
||
pass
|
||
|
||
# 预约回退校验开关(由 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:
|
||
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
|
||
|
||
if bool(_pick("enable_back_on_misses", True)):
|
||
cmd.append("--enable-back-on-misses")
|
||
else:
|
||
cmd.append("--disable-back-on-misses")
|
||
if bool(_pick("yanghao_only", False)):
|
||
cmd.append("--yanghao-only")
|
||
try:
|
||
seconds = int(_pick("yanghao_seconds", _pick("yanghao_recommend_duration_seconds", 60)) or 60)
|
||
if seconds > 0:
|
||
cmd += ["--yanghao-seconds", str(seconds)]
|
||
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=path_config.PROJECT_ROOT,
|
||
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("[网页] 读取线程: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("[网页] 读取线程:子进程stdout已关闭")
|
||
except Exception as e:
|
||
self._append_log(f"[网页] 读取线程异常:{e}")
|
||
|
||
try:
|
||
rc = p.wait(timeout=1)
|
||
except subprocess.TimeoutExpired:
|
||
rc = None
|
||
self._append_log("[网页] 等待进程退出超时,强制终止")
|
||
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:
|
||
send_json(self, obj, status=status)
|
||
|
||
def _read_json(self) -> dict:
|
||
return read_json(self)
|
||
|
||
def _serve_static(self, rel_path: str) -> None:
|
||
serve_static(
|
||
self,
|
||
webui_dir=WEBUI_DIR,
|
||
rel_path=rel_path,
|
||
log_error=lambda msg: _wg_log(msg, level="ERROR"),
|
||
)
|
||
|
||
def do_GET(self):
|
||
u = urlparse(self.path)
|
||
if u.path.startswith("/api/"):
|
||
api_path = u.path.rstrip("/")
|
||
# 提供 CSRF token 给前端
|
||
if u.path == "/api/csrf-token":
|
||
return self._send_json({"token": _CSRF_TOKEN})
|
||
if u.path == "/api/version":
|
||
try:
|
||
from version import APP_VERSION, APP_BUILD_DATE, APP_NAME
|
||
except Exception:
|
||
APP_VERSION, APP_BUILD_DATE, APP_NAME = "?", "?", "douyin_guaji"
|
||
return self._send_json({
|
||
"name": APP_NAME,
|
||
"version": str(APP_VERSION).lstrip("Vv"),
|
||
"build": APP_BUILD_DATE,
|
||
})
|
||
if u.path == "/api/devices":
|
||
adb = find_adb_executable()
|
||
return self._send_json({"adb": adb, "devices": list_adb_devices(adb)})
|
||
if u.path == "/api/wifi/last":
|
||
# 返回 last_wifi_target 记录(也支持 POST)
|
||
try:
|
||
from gui.gui_core_pkg import get_last_wifi_target
|
||
return self._send_json({"ok": True, "last": get_last_wifi_target()})
|
||
except Exception as e:
|
||
return self._send_json({"ok": False, "error": str(e)}, status=500)
|
||
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)
|
||
# 支持后端搜索模式:当提供 q 参数时,按最近若干条在后端过滤并返回(与 /api/actions 行为一致)
|
||
q = (qs.get("q") or [""])[0]
|
||
try:
|
||
tail_n = int((qs.get("lines") or [200])[0])
|
||
except Exception:
|
||
tail_n = 200
|
||
|
||
# 如果提供了搜索关键词,则走后端过滤路径,忽略 since(前端会使用此接口做搜索)
|
||
if q:
|
||
try:
|
||
# 取最近 tail_n 条作为候选,然后按关键词过滤(不区分大小写)
|
||
with RUNNER._lock:
|
||
total = len(RUNNER._log)
|
||
cand = (
|
||
RUNNER._log[-tail_n:] if tail_n > 0 else RUNNER._log[:]
|
||
)
|
||
qlow = q.lower()
|
||
filtered = [l for l in cand if qlow in (l or "").lower()]
|
||
return self._send_json(
|
||
{
|
||
"next": total,
|
||
"lines": filtered,
|
||
"running": RUNNER.is_running(),
|
||
}
|
||
)
|
||
except Exception as e:
|
||
import traceback
|
||
|
||
_wg_log(
|
||
f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}",
|
||
level="ERROR",
|
||
)
|
||
return self._send_json(
|
||
{"next": 0, "lines": [], "running": RUNNER.is_running()}
|
||
)
|
||
|
||
# 默认行为:按 since 增量返回日志(原有逻辑)
|
||
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
|
||
|
||
_wg_log(
|
||
f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}",
|
||
level="ERROR",
|
||
)
|
||
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 path_config.get_log_file_path()
|
||
)
|
||
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_config 中的配置,失败时回退到项目内置路径)
|
||
if hasattr(path_config, "get_actions_log_path"):
|
||
try:
|
||
path = path_config.get_actions_log_path()
|
||
except Exception:
|
||
path = os.path.join(
|
||
(
|
||
path_config.PROJECT_ROOT
|
||
if hasattr(path_config, "PROJECT_ROOT")
|
||
else os.getcwd()
|
||
),
|
||
"logs",
|
||
"actions.log",
|
||
)
|
||
else:
|
||
path = os.path.join(os.getcwd(), "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(str(path_config.PROJECT_ROOT), 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 _verify_csrf_token(self) -> bool:
|
||
"""验证 CSRF token,本地服务器的简单防护"""
|
||
token = self.headers.get("X-CSRF-Token", "")
|
||
return token == _CSRF_TOKEN
|
||
|
||
def do_POST(self):
|
||
u = urlparse(self.path)
|
||
|
||
# CSRF token 验证(对修改操作的 POST 请求)
|
||
if not self._verify_csrf_token():
|
||
return self._send_json({"ok": False, "error": "Invalid CSRF token"}, status=403)
|
||
|
||
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",
|
||
"wait_minutes",
|
||
"y_pianyi",
|
||
"fudai_exit_after_misses",
|
||
"swipe_duration_ms",
|
||
"swipe_up_start_y",
|
||
"swipe_up_end_y",
|
||
"high_value_room_revisit_min_interval_seconds",
|
||
"high_value_room_revisit_max_per_run",
|
||
"high_value_room_revisit_max_age_days",
|
||
"logging.keep_days",
|
||
"logging.compress_after_days",
|
||
}
|
||
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",
|
||
"high_value_fudai_threshold_yuan",
|
||
"fansclub_click_delay",
|
||
"fansclub_auto_join_wait_seconds",
|
||
"fansclub_manual_wait_seconds",
|
||
"fudai_click_wait_seconds",
|
||
"fudai_detail_template_threshold",
|
||
"coupon_template_match_threshold",
|
||
"attend_button_red_ratio_threshold",
|
||
"fansclub_join_red_ratio_threshold",
|
||
"shopping_redpacket_red_ratio_threshold",
|
||
"high_value_fudai_poll_before_seconds",
|
||
"high_value_room_revisit_min_prize_value",
|
||
"reservation_back_verify_wait_seconds",
|
||
"switch_room_wait_after_stage_diag_seconds",
|
||
"logging.max_total_size_gb",
|
||
"logging.monitor_warning_mb",
|
||
"logging.monitor_critical_mb",
|
||
}
|
||
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",
|
||
"fudai_disable_content_recognition",
|
||
"high_value_room_revisit_enabled",
|
||
"high_value_room_revisit_only_current_run",
|
||
"reservation_back_verify_enabled",
|
||
"needswitch",
|
||
"infinite_loop_enabled",
|
||
"enable_back_on_misses",
|
||
"enable_streaming_screenshot",
|
||
"fudai_disable_task_recognition",
|
||
"yanghao_only",
|
||
"debug_captures.async_save",
|
||
"debug_captures.log_on_complete",
|
||
"logging.beautify_output",
|
||
"logging.color_output",
|
||
"logging.show_timestamps",
|
||
"logging.enable_monitor",
|
||
"logging.compress_logs",
|
||
"logging.stage_diag_verbose",
|
||
"logging.performance_tracking.enabled",
|
||
"logging.performance_tracking.track_function_calls",
|
||
}
|
||
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})
|
||
|
||
# Web 端补齐的手动动作与桌面 GUI 常用操作。
|
||
|
||
if u.path == "/api/force-stop":
|
||
RUNNER.force_stop()
|
||
return self._send_json({"ok": True, "message": "已执行强制停止"})
|
||
|
||
if u.path == "/api/back-key":
|
||
body = self._read_json()
|
||
device_id = str(body.get("device_id") or "").strip()
|
||
ok = RUNNER.send_back_key(device_id)
|
||
return self._send_json({"ok": bool(ok), "message": "返回键已发送" if ok else "发送返回键失败"}, status=200 if ok else 500)
|
||
|
||
if u.path == "/api/wifi/enable":
|
||
body = self._read_json()
|
||
adb = find_adb_executable()
|
||
device_id = str(body.get("device_id") or "").strip()
|
||
if not device_id:
|
||
return self._send_json({"ok": False, "error": "missing device_id"}, status=400)
|
||
try:
|
||
from gui.gui_core import enable_wifi_adb
|
||
ok, msg = enable_wifi_adb(adb, device_id)
|
||
except Exception as e:
|
||
ok, msg = False, str(e)
|
||
return self._send_json({"ok": bool(ok), "message": msg}, status=200 if ok else 500)
|
||
|
||
if u.path == "/api/wifi/connect":
|
||
body = self._read_json()
|
||
adb = find_adb_executable()
|
||
ip = str(body.get("ip") or "").strip()
|
||
port = str(body.get("port") or "5555").strip() or "5555"
|
||
if not ip:
|
||
return self._send_json({"ok": False, "error": "missing ip"}, status=400)
|
||
try:
|
||
from gui.gui_core import connect_wifi_adb
|
||
ok, msg = connect_wifi_adb(adb, ip, port)
|
||
except Exception as e:
|
||
ok, msg = False, str(e)
|
||
# 成功后记住,下次启动时自动重连
|
||
if ok:
|
||
try:
|
||
from gui.gui_core_pkg import set_last_wifi_target
|
||
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
|
||
target = ip if ":" in ip else f"{ip}:{port}"
|
||
model = ""
|
||
try:
|
||
model = query_device_model(adb, target)
|
||
except Exception:
|
||
pass
|
||
set_last_wifi_target(target, model)
|
||
except Exception:
|
||
pass
|
||
devices = list_adb_devices(adb) if adb else []
|
||
return self._send_json({"ok": bool(ok), "message": msg, "devices": devices}, status=200 if ok else 500)
|
||
|
||
if u.path == "/api/wifi/disconnect":
|
||
body = self._read_json()
|
||
adb = find_adb_executable()
|
||
ip = str(body.get("ip") or "").strip()
|
||
port = str(body.get("port") or "5555").strip() or "5555"
|
||
if not ip:
|
||
return self._send_json({"ok": False, "error": "missing ip"}, status=400)
|
||
try:
|
||
from gui.gui_core import disconnect_wifi_adb
|
||
ok, msg = disconnect_wifi_adb(adb, ip, port)
|
||
except Exception as e:
|
||
ok, msg = False, str(e)
|
||
# 如果断开的就是上次记住的设备,清掉记录
|
||
if ok:
|
||
try:
|
||
from gui.gui_core_pkg import (
|
||
clear_last_wifi_target,
|
||
get_last_wifi_target,
|
||
)
|
||
last = get_last_wifi_target()
|
||
last_target = str(last.get("target") or "")
|
||
if last_target.startswith(ip):
|
||
clear_last_wifi_target()
|
||
except Exception:
|
||
pass
|
||
devices = list_adb_devices(adb) if adb else []
|
||
return self._send_json({"ok": bool(ok), "message": msg, "devices": devices}, status=200 if ok else 500)
|
||
|
||
if u.path == "/api/wifi/scan":
|
||
"""扫描局域网 ADB 设备。
|
||
|
||
POST body 可选字段:
|
||
- subnet: 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5;
|
||
留空则自动用本机子网
|
||
- ports: 端口规格(int / str / list)。"5555,37000-40000" 等。
|
||
留空 → 仅扫 5555。
|
||
- probe_timeout: 单 IP 探测超时秒(默认 0.3)
|
||
"""
|
||
body = self._read_json()
|
||
adb = find_adb_executable()
|
||
subnet = str(body.get("subnet") or "").strip() or None
|
||
probe_timeout = float(body.get("probe_timeout") or 0.3)
|
||
ports_raw = body.get("ports")
|
||
try:
|
||
from gui.gui_core_pkg import (
|
||
discover_adb_devices,
|
||
get_local_subnet,
|
||
parse_port_spec,
|
||
)
|
||
port_list = parse_port_spec(ports_raw)
|
||
devs = discover_adb_devices(
|
||
adb,
|
||
subnet_spec=subnet,
|
||
ports=port_list,
|
||
probe_timeout=probe_timeout,
|
||
)
|
||
payload = [
|
||
{
|
||
"target": d.target,
|
||
"ip": d.ip,
|
||
"port": d.port,
|
||
"state": d.adb_state,
|
||
"model": d.model,
|
||
"message": d.message,
|
||
}
|
||
for d in devs
|
||
]
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"subnet": subnet or get_local_subnet() or "",
|
||
"ports": port_list,
|
||
"devices": payload,
|
||
}
|
||
)
|
||
except Exception as e:
|
||
return self._send_json(
|
||
{"ok": False, "error": str(e)}, status=500
|
||
)
|
||
|
||
if u.path == "/api/wifi/last":
|
||
"""返回 last_wifi_target 记录(GET 也支持)。"""
|
||
try:
|
||
from gui.gui_core_pkg import get_last_wifi_target
|
||
last = get_last_wifi_target()
|
||
return self._send_json({"ok": True, "last": last})
|
||
except Exception as e:
|
||
return self._send_json(
|
||
{"ok": False, "error": str(e)}, status=500
|
||
)
|
||
|
||
if u.path == "/api/wifi/last/clear":
|
||
"""清除 last_wifi_target 记录。"""
|
||
try:
|
||
from gui.gui_core_pkg import clear_last_wifi_target
|
||
clear_last_wifi_target()
|
||
return self._send_json({"ok": True})
|
||
except Exception as e:
|
||
return self._send_json(
|
||
{"ok": False, "error": str(e)}, status=500
|
||
)
|
||
|
||
if u.path == "/api/wifi/auto-reconnect":
|
||
"""启动自动重连:先 verify 上次的 target,失败则扫描子网 + 智能匹配。
|
||
|
||
返回:
|
||
{
|
||
"ok": true,
|
||
"action": "noop" | "already_online" | "reconnected" | "matched" | "failed",
|
||
"target": "192.168.5.2:5555", # 当前选定的 target,可能为空
|
||
"model": "PEPM00", # 选中的 model,可能为空
|
||
"message": "...",
|
||
"devices": [...] # 扫描候选(仅 action 是 matched/failed 时返回)
|
||
}
|
||
"""
|
||
try:
|
||
from gui.gui_core_pkg import (
|
||
discover_adb_devices,
|
||
get_last_wifi_target,
|
||
pick_best_match,
|
||
set_last_wifi_target,
|
||
)
|
||
from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target
|
||
except Exception as e:
|
||
return self._send_json(
|
||
{"ok": False, "error": f"import failed: {e}"}, status=500
|
||
)
|
||
|
||
adb = find_adb_executable()
|
||
last = get_last_wifi_target() or {}
|
||
target = str(last.get("target") or "")
|
||
model = str(last.get("model") or "")
|
||
|
||
if not target:
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "noop",
|
||
"target": "",
|
||
"model": "",
|
||
"message": "无上次记录",
|
||
}
|
||
)
|
||
|
||
existing = list_adb_devices(adb) if adb else []
|
||
if target in existing:
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "already_online",
|
||
"target": target,
|
||
"model": model,
|
||
"message": f"WiFi 设备已在线: {target}",
|
||
}
|
||
)
|
||
if existing:
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "noop",
|
||
"target": existing[0],
|
||
"model": "",
|
||
"message": (
|
||
f"当前已有设备 {existing[0]},"
|
||
f"上次 WiFi 目标 {target} 不抢占"
|
||
),
|
||
}
|
||
)
|
||
|
||
# 直连
|
||
try:
|
||
state, _ = verify_adb_target(adb, target)
|
||
except Exception as e:
|
||
state = "failed"
|
||
_ = str(e)
|
||
|
||
if state == "connected":
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "reconnected",
|
||
"target": target,
|
||
"model": model,
|
||
"message": f"自动重连成功: {target}",
|
||
}
|
||
)
|
||
if state == "unauthorized":
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "failed",
|
||
"target": target,
|
||
"model": model,
|
||
"message": (
|
||
f"上次设备 {target} 未授权,请在手机上确认 ADB 调试授权"
|
||
),
|
||
}
|
||
)
|
||
|
||
# 不可达 → 扫描 + 智能匹配
|
||
# 如果上次记的端口非 5555,把它加进扫描列表(覆盖 Android 11+ 随机端口的场景)
|
||
try:
|
||
from gui.gui_core_pkg import parse_port_spec
|
||
last_port = 5555
|
||
if ":" in target:
|
||
try:
|
||
last_port = int(target.rsplit(":", 1)[1])
|
||
except ValueError:
|
||
pass
|
||
scan_ports = [5555] if last_port == 5555 else [5555, last_port]
|
||
devs = discover_adb_devices(adb, ports=scan_ports)
|
||
except Exception as e:
|
||
return self._send_json(
|
||
{
|
||
"ok": False,
|
||
"error": f"自动扫描失败: {e}",
|
||
},
|
||
status=500,
|
||
)
|
||
|
||
best = pick_best_match(devs, last)
|
||
payload_devs = [
|
||
{
|
||
"target": d.target,
|
||
"ip": d.ip,
|
||
"port": d.port,
|
||
"state": d.adb_state,
|
||
"model": d.model,
|
||
}
|
||
for d in devs
|
||
]
|
||
|
||
if best is None:
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "failed",
|
||
"target": target,
|
||
"model": model,
|
||
"message": (
|
||
f"上次目标 {target} 不可达,"
|
||
f"扫描发现 {len(devs)} 台候选但无明确匹配"
|
||
if devs
|
||
else (
|
||
f"上次目标 {target} 不可达,扫描也未发现其它设备。"
|
||
f"请检查手机和电脑是否在同一 WiFi"
|
||
)
|
||
),
|
||
"devices": payload_devs,
|
||
}
|
||
)
|
||
|
||
# 命中:更新记忆并返回
|
||
try:
|
||
set_last_wifi_target(best.target, best.model or model)
|
||
except Exception:
|
||
pass
|
||
|
||
if best.target == target:
|
||
msg = f"自动重连成功(扫描确认): {best.target}"
|
||
else:
|
||
msg = (
|
||
f"上次目标 {target} 已变 → 智能匹配到 {best.target}"
|
||
+ (f" ({best.model})" if best.model else "")
|
||
+ "(已更新记忆)"
|
||
)
|
||
return self._send_json(
|
||
{
|
||
"ok": True,
|
||
"action": "matched",
|
||
"target": best.target,
|
||
"model": best.model or "",
|
||
"message": msg,
|
||
"devices": payload_devs,
|
||
}
|
||
)
|
||
|
||
if u.path == "/api/test-yanghao":
|
||
if RUNNER.is_running():
|
||
return self._send_json({"ok": False, "error": "running"}, status=409)
|
||
body = self._read_json()
|
||
cfg = read_config()
|
||
seconds = int(body.get("seconds") or cfg.get("yanghao_recommend_duration_seconds") or 60)
|
||
RUNNER.start_main_run({"device_id": str(body.get("device_id") or ""), "yanghao_only": True, "yanghao_seconds": seconds, "wait_minutes": 0})
|
||
return self._send_json({"ok": True})
|
||
|
||
if u.path == "/api/test-comment":
|
||
return self._send_json({"ok": False, "error": "独立测试评论接口已移除,请用养号参数中的评论概率/文案后启动养号流程"}, status=410)
|
||
|
||
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 douyin.core.underlying_operations import underlying_operations
|
||
|
||
ops = underlying_operations()
|
||
result = ops.get_screenshot(device_id, use_service=False)
|
||
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 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")
|
||
try:
|
||
httpd.serve_forever()
|
||
except KeyboardInterrupt:
|
||
print("[WEBGUI] 收到中断,退出")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
from douyin.core.version import print_version_banner
|
||
|
||
print_version_banner("web_gui")
|
||
except Exception:
|
||
pass
|
||
raise SystemExit(main())
|