refactor: split large modules and harden live-room fudai flow

This commit is contained in:
Your Name committed 2026-06-01 18:39:44 +08:00
1 parent 1845561405
commit 36e374ef67
86 files changed
+7422 -8404

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
"""ProcRunner 独立操作方法实现(从 gui/web_gui.py 抽离)。"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from typing import Any
from douyin.core import path_config
from .adb_compat import find_adb_executable, resolve_adb_device
def get_reservations(self: Any) -> dict:
"""获取当前预约队列信息。"""
try:
path = path_config.get_reservations_path()
except Exception:
base_dir = (
path_config.PROJECT_ROOT
if hasattr(path_config, "PROJECT_ROOT")
else os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
)
path = os.path.join(base_dir, "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: Any) -> dict:
"""获取永久记录的高价值直播间列表。"""
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: Any, 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 resolve_device_id_for_action(self: Any, requested_device_id: str) -> tuple[str, str]:
"""解析动作类接口使用的设备 ID;返回 (device_id, error_msg)。"""
device_id = str(requested_device_id or "").strip()
adb = find_adb_executable()
if not adb:
return "", "未找到 adb.exe"
if not device_id:
try:
device_id = resolve_adb_device(adb)
except Exception:
return "", "未选择设备,且无法自动解析在线设备"
return device_id, ""
def start_test_yanghao(self: Any, 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.\nExpected path: {run_cli_path}\nPlease 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: Any, 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.\nExpected path: {run_cli_path}\nPlease 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)
+148
View File
@@ -0,0 +1,148 @@
"""ProcRunner 统计聚合逻辑(从 gui/web_gui.py 抽离)。"""
from __future__ import annotations
import time
from typing import Any
def get_stats(self: Any, 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))
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 or 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
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:
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,
}
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,
"wins": wins[-20:],
"trace_id": current_trace_id,
"mdc_context": mdc_context,
}
if include_events:
payload["events"] = events[-200:]
return payload
+9 -6
View File
@@ -50,23 +50,26 @@ def serve_static(
data = f.read()
# 对于静态资源,使用适当的缓存策略
cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600"
handler.send_response(HTTPStatus.OK)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", cache_control)
# 添加 ETag 支持(简单实现:基于文件大小和修改时间)
try:
stat = os.stat(full)
etag = f'"{stat.st_size}-{int(stat.st_mtime)}"'
handler.send_header("ETag", etag)
# 检查 If-None-Match 头,支持 304 Not Modified
if_none_match = handler.headers.get("If-None-Match", "")
if if_none_match == etag:
handler.send_response(HTTPStatus.NOT_MODIFIED)
handler.send_header("ETag", etag)
handler.send_header("Cache-Control", cache_control)
handler.end_headers()
return
except Exception:
pass
etag = None
handler.send_response(HTTPStatus.OK)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", cache_control)
if etag:
handler.send_header("ETag", etag)
handler.end_headers()
handler.wfile.write(data)
except FileNotFoundError: