Files
douyi_guaji_main/gui/web_gui.py
T

953 lines
36 KiB
Python

import json
import os
import re
import secrets
import shutil
import subprocess
import sys
import threading
import time
import atexit
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)
if __name__ == "__main__":
from douyin.updater.bootstrap import run_startup_update_check_early
run_startup_update_check_early(app_name="web_gui")
from douyin.core import path_config
from douyin.license.license_manager import require_online_license_or_exit, start_online_license_monitor
# 从子包 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
from gui.web_gui_pkg.net_config import get_web_gui_host, get_web_gui_port
from gui.web_gui_pkg.routes import handle_get, handle_post
from gui.web_gui_pkg import proc_runner_ops as _proc_ops
from gui.web_gui_pkg import proc_runner_stats as _proc_stats
from gui.process_pause import resume_process_tree, suspend_process_tree
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
self._paused: bool = False
self._owned_run_cli_pids: set[int] = set()
# 运行统计(基于 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 is_paused(self) -> bool:
with self._lock:
return bool(self._paused and self._proc is not None and self._proc.poll() is None)
def _list_project_run_cli_processes(self) -> list[tuple[int, str]]:
"""列出当前仓库下运行的 run_cli.py 进程(含 pid 与命令行)。"""
entries: list[tuple[int, str]] = []
root_norm = str(path_config.PROJECT_ROOT).replace("/", "\\").lower()
try:
if os.name == "nt":
ps_cmd = (
"Get-CimInstance Win32_Process "
"| Where-Object { $_.Name -eq 'python.exe' -and $_.CommandLine -like '*run_cli.py*' } "
"| Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"
)
proc = subprocess.run(
["powershell", "-NoProfile", "-Command", ps_cmd],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=6,
check=False,
)
raw = (proc.stdout or "").strip()
if not raw:
return entries
try:
data = json.loads(raw)
except Exception:
data = None
if isinstance(data, dict):
data = [data]
if isinstance(data, list):
for item in data:
try:
pid = int(item.get("ProcessId") or 0)
cmdline = str(item.get("CommandLine") or "")
except Exception:
continue
if pid <= 0 or not cmdline:
continue
if root_norm in cmdline.replace("/", "\\").lower():
entries.append((pid, cmdline))
else:
proc = subprocess.run(
["ps", "-eo", "pid=,args="],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=4,
check=False,
)
for line in (proc.stdout or "").splitlines():
s = str(line or "").strip()
if not s:
continue
parts = s.split(None, 1)
if len(parts) < 2:
continue
try:
pid = int(parts[0])
except Exception:
continue
cmdline = parts[1]
low = cmdline.lower()
if "run_cli.py" in low and root_norm in cmdline.replace("/", "\\").lower():
entries.append((pid, cmdline))
except Exception:
return []
return entries
def _cleanup_orphan_run_cli_processes(self, device_id: str = "") -> int:
"""清理当前仓库遗留的 run_cli.py 进程,避免同机并发导致重复动作。"""
try:
with self._lock:
tracked_pid = int(self._pid or 0)
owned_pids = {int(x) for x in (self._owned_run_cli_pids or set())}
except Exception:
tracked_pid = 0
owned_pids = set()
current_pid = int(os.getpid() or 0)
device_tag = str(device_id or "").strip()
if not device_tag:
return 0
killed = 0
for pid, cmdline in self._list_project_run_cli_processes():
if pid <= 0:
continue
if pid in (tracked_pid, current_pid):
continue
if pid not in owned_pids:
continue
if device_tag:
dev1 = f"--device-id {device_tag}"
dev2 = f'--device-id "{device_tag}"'
if dev1 not in cmdline and dev2 not in cmdline:
continue
try:
self._append_log(f"[启动清理] 发现遗留 run_cli 进程 pid={pid},准备终止")
except Exception:
pass
try:
if os.name == "nt":
subprocess.run(
["taskkill", "/PID", str(pid), "/T", "/F"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=8,
check=False,
)
else:
subprocess.run(
["kill", "-9", str(pid)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=5,
check=False,
)
killed += 1
try:
self._append_log(f"[启动清理] 已终止遗留 run_cli 进程 pid={pid}")
except Exception:
pass
except Exception as e:
try:
self._append_log(f"[启动清理] 终止遗留 run_cli 进程失败 pid={pid} error={e}")
except Exception:
pass
return killed
def get_reservations(self) -> dict:
return _proc_ops.get_reservations(self)
def get_high_value_rooms(self) -> dict:
return _proc_ops.get_high_value_rooms(self)
def send_back_key(self, device_id: str) -> bool:
return _proc_ops.send_back_key(self, device_id)
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 '-'}")
if self.is_paused() and pid:
try:
resume_process_tree(int(pid))
except Exception:
pass
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._paused = False
if pid:
self._owned_run_cli_pids.discard(int(pid))
self._exit_code = self._exit_code if self._exit_code is not None else -9
try:
extra_killed = self._cleanup_orphan_run_cli_processes("")
if extra_killed > 0:
self._append_log(f"[停止] 额外清理遗留 run_cli 进程 {extra_killed} 个")
except Exception:
pass
self._append_log("[停止] 强制停止完成")
def stop(self) -> None:
with self._lock:
p = self._proc
if p is None or p.poll() is not None:
return
if self.is_paused():
self.resume()
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
self._paused = False
if getattr(p, "pid", None):
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
self._append_log("[网页] 停止:已尝试终止并清理进程引用")
def pause(self) -> bool:
with self._lock:
p = self._proc
pid = self._pid or (p.pid if p is not None else None)
already_paused = self._paused
if p is None or p.poll() is not None or not pid:
self._append_log("[网页] 暂停:当前没有正在运行的进程")
with self._lock:
self._paused = False
return False
if already_paused:
self._append_log("[网页] 暂停:当前已经是暂停状态")
return True
try:
suspend_process_tree(int(pid))
with self._lock:
self._paused = True
self._append_log("[网页] 暂停:已暂停运行进程")
return True
except Exception as e:
self._append_log(f"[网页] 暂停失败:{e}")
return False
def resume(self) -> bool:
with self._lock:
p = self._proc
pid = self._pid or (p.pid if p is not None else None)
already_paused = self._paused
if p is None or p.poll() is not None or not pid:
self._append_log("[网页] 继续:当前没有可恢复的运行进程")
with self._lock:
self._paused = False
return False
if not already_paused:
self._append_log("[网页] 继续:当前不在暂停状态")
return True
try:
resume_process_tree(int(pid))
with self._lock:
self._paused = False
self._append_log("[网页] 继续:已恢复运行进程")
return True
except Exception as e:
self._append_log(f"[网页] 继续失败:{e}")
return False
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:
return _proc_stats.get_stats(self, include_events)
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:
return _proc_ops.start_test_yanghao(self, device_id, seconds)
def start_test_comment(self, device_id: str, text: str) -> None:
return _proc_ops.start_test_comment(self, device_id, text)
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)
try:
cleaned = self._cleanup_orphan_run_cli_processes(device_id)
if cleaned > 0:
self._append_log(
f"[启动清理] 已清理同设备遗留 run_cli 进程 {cleaned} 个,避免重复切房"
)
except Exception:
pass
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_cmd = path_config.get_run_cli_command()
run_cli_path = run_cli_cmd[-1] if run_cli_cmd else path_config.get_run_cli_path()
if not os.path.exists(run_cli_path):
raise FileNotFoundError(
f"run_cli launcher not found.\n"
f"Expected path: {run_cli_path}\n"
f"Please ensure run_cli.py is in the source tree or run_cli.exe is in the install directory."
)
cmd = [
*run_cli_cmd,
"--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
reenter_mode = str(
_pick("reenter_live_entry_mode", "follow_list") or "follow_list"
).strip().lower()
reenter_mode_source = "default"
try:
if (
isinstance(params, dict)
and params.get("reenter_live_entry_mode") is not None
):
reenter_mode_source = "params"
elif isinstance(cfg, dict) and cfg.get("reenter_live_entry_mode") is not None:
reenter_mode_source = "config"
except Exception:
reenter_mode_source = "default"
if reenter_mode in ("follow_list", "screen_center"):
cmd += ["--reenter-live-entry-mode", reenter_mode]
self._start_process(cmd)
try:
# 放在 _start_process 之后,避免被启动时日志清空逻辑抹掉
self._append_log(
"[WEB_DEBUG] 启动参数解析:reenter_live_entry_mode="
f"{reenter_mode} source={reenter_mode_source}"
)
self._append_log(
"[WEB_DEBUG] 启动命令检查:cmd_has_reenter_flag="
f"{'--reenter-live-entry-mode' in cmd}"
)
except Exception:
pass
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._paused = False
self._owned_run_cli_pids.add(int(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
self._paused = False
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
try:
self._proc = None
self._pid = None
self._paused = False
self._owned_run_cli_pids.discard(int(p.pid))
except Exception:
pass
threading.Thread(target=_reader, daemon=True).start()
RUNNER = ProcRunner()
atexit.register(lambda: RUNNER.force_stop())
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)
return handle_get(self, u, RUNNER, _CSRF_TOKEN)
def do_POST(self):
u = urlparse(self.path)
return handle_post(self, u, RUNNER, _CSRF_TOKEN)
def main() -> int:
require_online_license_or_exit()
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
host = get_web_gui_host()
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
port = get_web_gui_port()
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] 收到中断,退出")
try:
RUNNER.force_stop()
except Exception:
pass
finally:
try:
httpd.server_close()
except Exception:
pass
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())