Files
douyi_guaji_main/gui/web_gui.py
T
CodexandClaude Opus 4.7 52b811d0cb feat(scan): WiFi-ADB 扫描支持自定义/多端口(覆盖 Android 11+ 随机端口)
之前只扫 5555。Android 11+ "无线调试" 用 37000-44999 随机端口,
固定的 adb tcpip 也可改端口。新接口让扫描适配任意端口规格。

新增 parse_port_spec:解析端口规格字符串
  - 5555            单端口
  - "5555,5556"     逗号分隔
  - "37000-37010"   范围(最大 1024 个)
  - 混合格式与序列输入
  - 非法/越界 → 退化为默认 5555
  - 单个范围 > 1024 端口直接忽略,避免误扫整个端口段

scan_open_ports 重构:
  - 接受 ports 参数(list[int]),传 ports 时优先于旧 port=int
  - 返回 list[(ip, port)] 而不是 list[ip],按 (IP 数值序, port 升序) 稳定排序

discover_adb_devices 支持 ports 参数,按 (ip, port) 逐个 verify_adb_target

接入 GUI 与 webui:
  - gui_app.py 扫描对话框新增"端口"输入框 + 提示
  - gui_app.py 启动重连:上次端口非 5555 时把它一并扫描
  - web_gui.py /api/wifi/scan 接受 ports;/api/wifi/auto-reconnect 同上次端口逻辑

新增 13 个 parse_port_spec 单测 + 4 个 scan_open_ports 多端口测试 +
2 个 discover_adb_devices 多端口集成测试。
真机验证:6 端口 (5555 + 37000-37005) × 254 IP,~8.5s 扫完,
正确发现 192.168.5.2:5555 (PEPM00)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:02:48 +08:00

2430 lines
98 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 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,
)
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:
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 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信息(可用于统计)
self._mdc_context[key] = value
# --- 福袋:抽取"最近一次"识别到的信息 ---
# 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容="
content_extracted = False
room_title = ""
if "福袋内容:" in s:
self._fudai_last["content"] = (
s.split("福袋内容:", 1)[1].strip().split()[0]
) # 只取第一个词,避免包含后续字段
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
else:
# 新格式:字段_内容= 或 内容=
m = re.search(r"(?:字段_)?内容[=:]\s*([^\s]+)", s)
if m:
self._fudai_last["content"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
content_extracted = True
# 提取直播间标题
m = re.search(r"room_title[=:]\s*([^\s,]+)", s)
if m:
room_title = m.group(1).strip()
if content_extracted:
fudai_content = self._fudai_last.get("content", "")
key = (room_title, fudai_content)
if key not in self._recorded_fudai_seen:
self._recorded_fudai_seen.add(key)
self._inc("fudai_seen")
self._record_event("fudai_seen", self._snapshot_fudai())
# 参与人数:支持多种格式
m = re.search(r"(?:字段_)?参与人数[=:]?\s*(\d+)", s)
if not m:
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 not m:
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().split()[0]
)
self._fudai_last["updated_ts"] = time.time()
else:
m = re.search(r"(?:字段_)?倒计时[=:]?\s*([^\s]+)", s)
if m:
self._fudai_last["countdown"] = m.group(1).strip()
self._fudai_last["updated_ts"] = time.time()
# 奖品价值:支持多种格式
m = re.search(
r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)",
s,
)
if not m:
m = re.search(
r"奖品价值:\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][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 or ("[流程]" in s and "检测到福袋图标并点击" 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 or "动作=参与" 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 or "结果=参与成功" in s)
)
or ("[参与]" in s and "已参与" in s and "等待开奖" in s)
or ("预约回退后直接参与" in s and "参与成功" in s)
):
self._inc("fudai_attend_ok")
self._record_event("fudai_attend_ok", self._snapshot_fudai())
if "参与抽奖失败" in s or ("[参与]" in s and "结果=失败" 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")
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "participants_low", **meta})
if "参与人数" in s and "> 阈值" in s and "不参与" in s:
self._inc("fudai_skip_participants_high")
# 提取实际参与人数和阈值
meta = self._snapshot_fudai()
m = re.search(r"参与人数[=:]?\s*(\d+)", s)
if m:
try:
meta["participants"] = int(m.group(1))
except Exception:
pass
m = re.search(r"阈值[=:]?\s*(\d+)", s)
if m:
try:
meta["threshold"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "participants_high", **meta})
if "奖品价值" in s and "< 阈值" in s and "不参与" in s:
self._inc("fudai_skip_value_low")
# 提取实际价值和阈值
meta = self._snapshot_fudai()
m = re.search(
r"(?:奖品)?价值[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s
)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(
r"阈值[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s
)
if m:
try:
meta["threshold"] = float(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "value_low", **meta})
if "福袋内容不理想" in s or ("[筛选]" in s and "内容" in s and "黑名单" 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")
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "countdown_short", **meta})
if "抽奖倒计时时间大于" in s and "暂不参与" in s:
self._inc("fudai_skip_countdown_long")
# 提取倒计时秒数
meta = self._snapshot_fudai()
m = re.search(r"(\d+)\s*秒", s)
if m:
try:
meta["countdown_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_skip", {"reason": "countdown_long", **meta})
# 看播门槛:默认不参与(新结构化日志)
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 or ("[流程]" in s and "打开福袋异常" 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 and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s
) or ("[参与]" in s and "倒计时大于阈值,但价值达到高价值阈值,记录预约" in s):
self._inc("fudai_reserved_high_value")
# 提取价值和倒计时信息
meta = self._snapshot_fudai()
m = re.search(r"(?:价值|价值元)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
if m:
try:
meta["prize_value_yuan"] = float(m.group(1))
except Exception:
pass
m = re.search(r"(?:剩余|倒计时)[=:]?\s*(\d+)\s*秒", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_reserved_high_value", meta)
# --- 错误和异常统计(与 gui_core.py 保持一致) ---
if "[错误]" in s or "[异常]" in s or "错误=" in s or "异常=" in s:
self._inc("error_total")
error_type = "unknown"
if "UnboundLocalError" in s:
error_type = "UnboundLocalError"
self._inc("error_unbound_local")
elif "AttributeError" in s:
error_type = "AttributeError"
self._inc("error_attribute")
elif "KeyError" in s:
error_type = "KeyError"
self._inc("error_key")
elif "ValueError" in s:
error_type = "ValueError"
self._inc("error_value")
elif "TypeError" in s:
error_type = "TypeError"
self._inc("error_type")
elif "TimeoutError" in s or "超时" in s:
error_type = "TimeoutError"
self._inc("error_timeout")
elif "ConnectionError" in s or ("连接" in s and "失败" in s):
error_type = "ConnectionError"
self._inc("error_connection")
elif "OCR" in s and ("失败" in s or "错误" in s):
error_type = "OCR_Error"
self._inc("error_ocr")
elif "截图" in s and ("失败" in s or "错误" in s):
error_type = "Screenshot_Error"
self._inc("error_screenshot")
elif "识别" in s and ("失败" in s or "错误" in s):
error_type = "Detection_Error"
self._inc("error_detection")
self._record_event("error", {"error_type": error_type})
if "阶段诊断" in s and ("失败" in s or "错误" in s or "异常" in s):
self._inc("error_stage_diagnosis")
self._record_event("error_stage_diagnosis", {})
if "读取福袋详情" in s and ("失败" in s or "错误" in s or "异常" in s):
self._inc("error_read_detail")
self._record_event("error_read_detail", {})
if "load_config" in s and ("失败" in s or "错误" in s or "异常" in s):
self._inc("error_config_load")
self._record_event("error_config_load", {})
if ("预约队列状态文件" in s or "reservations.json" in s) and (
"失败" in s or "错误" in s
):
self._inc("error_state_file")
self._record_event("error_state_file", {})
if "直播间检测" in s and ("失败" in s or "错误" in s):
self._inc("error_live_room_detect")
self._record_event("error_live_room_detect", {})
if "查找福袋" in s and ("失败" in s or "错误" in s or "未找到" in s):
self._inc("error_fudai_find")
self._record_event("error_fudai_find", {})
# --- 粉丝团门槛 ---
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", {})
# --- 预约记录相关(与 gui_core.py 保持一致) ---
if (
"[预约]" in s and "已记录高价值福袋" in s
) or "record_high_value_reservation:已记录高价值福袋" in s:
self._inc("reservation_recorded")
# 提取预约价值:支持多种格式
value = None
m = re.search(r"(?:字段_)?(?:价值|价值元|value)[=:]?\s*(\d+(?:\.\d+)?)", s)
if not m:
m = re.search(r"value[=:]?\s*(\d+(?:\.\d+)?)", s)
if m:
try:
value = float(m.group(1))
except Exception:
pass
# 提取开奖时间
future_ts = None
m = re.search(r"(?:字段_)?(?:开奖时间|future|future_ts)[=:]?\s*(\d+)", s)
if m:
try:
future_ts = int(m.group(1))
except Exception:
pass
# 提取直播间名称
room_title = None
m = re.search(
r"(?:字段_)?(?:直播间|直播间名|room_title)[=:]?\s*([^\s]+)", s
)
if m:
room_title = m.group(1).strip()
meta = self._snapshot_fudai()
if value is not None:
meta["prize_value_yuan"] = value
if future_ts is not None:
meta["future_ts"] = future_ts
if room_title:
meta["room_title"] = room_title
self._record_event("reservation_recorded", meta)
if (
"[预约]" in s and "进入预约参与窗口" in s
) or "进入预约参与窗口,准备回退到目标直播间" in s:
self._inc("reservation_window_entered")
self._record_event("reservation_window_entered", {})
if (
("[预约]" in s and "已回退到目标直播间" in s)
or "已回退到目标直播间" in s
or ("[预约]" in s and "已回退到最早开奖的预约直播间" in s)
):
self._inc("reservation_back_success")
# 提取回退信息
meta = {}
m = re.search(r"(?:字段_)?(?:需回退次数|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_success", meta)
if ("[预约]" in s and "时间窗口未到" in s) or "时间窗口未到,跳过回退" in s:
self._inc("reservation_window_not_reached")
self._record_event("reservation_window_not_reached", {})
if (
"[预约]" in s and "已明显错过开奖时间" in s
) or "已明显错过开奖时间,清理过期预约" in s:
self._inc("reservation_expired")
self._record_event("reservation_expired", {})
if (
"[预约]" in s and "预约队列为空" in s
) or "process_reservation_attend_window:预约队列为空" in s:
self._inc("reservation_queue_empty")
if ("[预约]" in s and "锁定期未结束" in s) or "锁定期未结束" in s:
self._inc("reservation_locked")
self._record_event("reservation_locked", {})
if "[预约]" in s and "已回退到第一个直播间" in s:
self._inc("reservation_back_to_first")
self._record_event("reservation_back_to_first", {})
if "[预约]" in s and "run_once_basic:检查预约回退触发条件" in s:
self._inc("reservation_check_triggered")
if (
("[预约]" in s and "队列已满" in s)
or "handle_queue_full_wait_at_earliest" in s
or ("[预约]" in s and "队列已满,回退到最早开奖的预约直播间" in s)
):
self._inc("reservation_queue_full_wait")
self._record_event("reservation_queue_full_wait", {})
# 回退后直接参与
if ("[预约]" in s and "预约回退后直接参与" in s) or "预约回退后直接参与" in s:
self._inc("reservation_back_direct_attend")
self._record_event("reservation_back_direct_attend", {})
# 队列满回退后设置参与标志
if "[预约]" in s and "队列满回退后,直接设置参与标志" in s:
self._inc("reservation_queue_full_back_attend")
self._record_event("reservation_queue_full_back_attend", {})
# 通过相似度匹配识别重复预约
if "[预约]" in s and "通过相似度匹配识别为重复预约" in s:
self._inc("reservation_duplicate_detected")
self._record_event("reservation_duplicate_detected", {})
# --- 开奖结果 ---
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
or ("[开奖结果]" in s and "中奖" in s)
):
self._inc("fudai_result_win")
# 提取中奖信息
meta = self._snapshot_fudai()
m = re.search(r"(?:奖品|商品)[=:]?\s*([^\s]+)", s)
if m:
meta["prize"] = m.group(1).strip()
self._record_event("fudai_result_win", meta)
self._record_win()
if "福袋商品下单成功" in s or ("[开奖结果]" in s and "下单成功" in s):
self._inc("fudai_order_success")
self._record_event("fudai_order_success", self._snapshot_fudai())
# 等待开奖(只在设置等待开奖标志时计数,避免重复计数)
# 注意:不要匹配"已经参与,等待开奖",因为那已经在参与成功时计数了
if ("[参与]" in s and "参与成功,设置等待开奖标志" in s) or (
"[参与]" in s and "设置等待开奖标志" in s
):
self._inc("fudai_waiting_lottery")
# 提取剩余秒数
meta = self._snapshot_fudai()
m = re.search(r"(?:剩余|倒计时|remain_seconds)[=:]?\s*(\d+)", s)
if m:
try:
meta["remain_seconds"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_waiting_lottery", meta)
# --- 直播间切换(按原因粗分) ---
if "上划切换直播间" in s or ("[操作]" in s and "上滑切换直播间" 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"
elif "记录预约后" in s:
self._inc("switch_room_after_reservation")
meta_reason = "after_reservation"
elif "锁定期内" in s:
self._inc("switch_room_locked")
meta_reason = "locked"
self._record_event(
"switch_room", {"reason": meta_reason, **self._snapshot_fudai()}
)
# --- 阶段诊断统计 ---
if "[阶段诊断]" in s or "阶段诊断" in s:
if "阶段诊断完成" in s:
self._inc("stage_diagnosis_complete")
# 提取阶段和耗时
meta = {}
m = re.search(r"阶段[=:]?\s*(\w+)", s)
if m:
meta["stage"] = m.group(1)
m = re.search(
r"耗时[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)\s*秒", s
)
if m:
try:
meta["elapsed_seconds"] = float(m.group(1))
except Exception:
pass
m = re.search(
r"分数[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)", s
)
if m:
try:
meta["score"] = float(m.group(1))
except Exception:
pass
self._record_event("stage_diagnosis_complete", meta)
elif "阶段诊断失败" in s or "阶段诊断错误" in s:
self._inc("stage_diagnosis_failed")
self._record_event("stage_diagnosis_failed", {})
# --- OCR识别统计 ---
if "[福袋]" in s and "OCR识别" in s:
self._inc("ocr_attempt")
if "识别成功" in s or "识别完成" in s:
self._inc("ocr_success")
elif "识别失败" in s or "识别错误" in s:
self._inc("ocr_failed")
# --- 性能统计 ---
m = re.search(
r"耗时[=:]?\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][0-9]+)?)\s*秒", s
)
if m:
try:
elapsed = float(m.group(1))
# 记录耗时较长的操作
if elapsed > 5.0:
self._inc("slow_operation")
self._record_event(
"slow_operation",
{"elapsed_seconds": elapsed, "operation": s[:100]},
)
except Exception:
pass
# --- 详情识别统计 ---
if ("[福袋详情]" in s and "识别" in s) or "识别福袋详情" in s:
self._inc("fudai_detail_read_attempt")
if (
"识别成功" in s
or "识别完成" in s
or "read_fudai_detail_once完成(成功)" in s
):
self._inc("fudai_detail_read_success")
# 提取任务数量
meta = {}
m = re.search(r"(?:任务数量|task_count)[=:]?\s*(\d+)", s)
if m:
try:
meta["task_count"] = int(m.group(1))
except Exception:
pass
self._record_event("fudai_detail_read_success", meta)
elif "识别失败" in s or "识别错误" in s:
self._inc("fudai_detail_read_failed")
self._record_event("fudai_detail_read_failed", {})
# --- 福袋查找统计 ---
if "[福袋查找]" in s or "查找福袋" in s:
if "检测完成" in s and "命中" in s:
self._inc("fudai_find_success")
elif "检测完成" in s and "未找到" in s:
self._inc("fudai_find_not_found")
elif "等待超时" in s:
self._inc("fudai_find_timeout")
# --- 回退操作统计 ---
if ("[预约]" in s and "回退" in s) or "回退到" in s:
if "回退完成" in s or "回退成功" in s:
self._inc("reservation_back_operation")
# 提取回退次数
meta = {}
m = re.search(r"(?:回退|back_times)[=:]?\s*(\d+)", s)
if m:
try:
meta["back_times"] = int(m.group(1))
except Exception:
pass
self._record_event("reservation_back_operation", meta)
# --- 性能:进入直播间到识别福袋耗时 ---
m = re.search(
r"进入直播间到识别福袋耗时:\s*([0-9]+(?:[.\u00B7\uFF0E\uFF61·.。][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:
"""获取当前预约队列信息(来自子进程写入的 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:
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:
_wg_log(f"[WEB_GUI] Error serving static file {rel_path}: {e}", level="ERROR")
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("/")
# 提供 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())