- Removed obsolete command-line test parameters from `run_cli.py` to streamline functionality. - Introduced a new `ocr_preprocess.py` module for unified OCR image preprocessing, enhancing recognition stability. - Updated various components to utilize the new preprocessing function, improving code organization and readability. - Adjusted configuration values in `config.json` for better performance and consistency. - Added comprehensive technical documentation for the Douyin project, detailing code modification standards and operational guidelines. - Cleaned up excessive blank lines across multiple files to enhance overall readability.
1007 lines
42 KiB
Python
1007 lines
42 KiB
Python
import json
|
||
import os
|
||
import queue
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
from dataclasses import dataclass
|
||
from typing import Optional
|
||
|
||
import path_config
|
||
|
||
CONFIG_PATH = path_config.get_config_path()
|
||
|
||
|
||
def find_adb_executable() -> str:
|
||
"""返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。"""
|
||
adb = shutil.which("adb")
|
||
if adb:
|
||
return adb
|
||
|
||
# 默认安装目录(我们之前下载的 platform-tools)
|
||
localapp = os.environ.get("LOCALAPPDATA") or ""
|
||
candidates = []
|
||
if localapp:
|
||
candidates.append(os.path.join(localapp, "platform-tools", "adb.exe"))
|
||
|
||
# 兼容某些人手动放到用户目录的情况
|
||
userprofile = os.environ.get("USERPROFILE") or ""
|
||
if userprofile:
|
||
candidates.append(os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe"))
|
||
|
||
for p in candidates:
|
||
if os.path.exists(p):
|
||
return p
|
||
return ""
|
||
|
||
|
||
def list_adb_devices(adb_exe: str) -> list[str]:
|
||
try:
|
||
if not adb_exe:
|
||
return []
|
||
proc = subprocess.run(
|
||
[adb_exe, "devices", "-l"],
|
||
capture_output=True,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
)
|
||
except FileNotFoundError:
|
||
return []
|
||
text = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||
pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b"
|
||
return re.findall(pattern, text)
|
||
|
||
|
||
def read_config() -> dict:
|
||
if not os.path.exists(CONFIG_PATH):
|
||
return {}
|
||
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
||
return json.load(f)
|
||
|
||
|
||
def write_config(cfg: dict) -> None:
|
||
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
|
||
json.dump(cfg, f, ensure_ascii=False, indent=4)
|
||
f.write("\n")
|
||
|
||
|
||
@dataclass
|
||
class RunParams:
|
||
device_id: str
|
||
y_pianyi: int
|
||
needswitch: bool
|
||
wait_minutes: int
|
||
skip_if_countdown_gt_seconds: int
|
||
reset_after_swipes_enabled: bool
|
||
reset_after_swipes: int
|
||
min_prize_value_yuan: float
|
||
min_participants: int
|
||
max_participants: int
|
||
auto_join_fansclub: bool
|
||
fansclub_fail_action: str
|
||
# Web端新增参数
|
||
high_value_room_revisit_enabled: bool
|
||
high_value_room_revisit_only_current_run: bool
|
||
reservation_back_verify_enabled: bool
|
||
reservation_back_swipe_delay: float
|
||
reservation_preempt_min_value: float
|
||
fudai_find_max_attempts: int
|
||
enable_ocr_mode1: bool
|
||
fudai_template_match_enabled: bool
|
||
fudai_template_match_threshold: float
|
||
|
||
|
||
class Runner:
|
||
def __init__(self, on_line):
|
||
self._proc: Optional[subprocess.Popen] = None
|
||
self._on_line = on_line
|
||
self._reader_thread: Optional[threading.Thread] = None
|
||
self._lock = threading.Lock()
|
||
|
||
# 统计相关
|
||
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._counters: dict[str, int] = {}
|
||
self._fudai_last: dict[str, object] = {
|
||
"content": "",
|
||
"countdown": "",
|
||
"participants": None,
|
||
"copies": None,
|
||
"prize_value_yuan": None,
|
||
"updated_ts": None,
|
||
}
|
||
self._events: list[dict] = []
|
||
self._events_cap: int = 5000
|
||
self._wins: list[dict] = []
|
||
self._wins_cap: int = 200
|
||
|
||
def is_running(self) -> bool:
|
||
return self._proc is not None and self._proc.poll() is None
|
||
|
||
def _inc(self, key: str, n: int = 1) -> None:
|
||
with self._lock:
|
||
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 {},
|
||
}
|
||
with self._lock:
|
||
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(),
|
||
}
|
||
with self._lock:
|
||
self._wins.append(item)
|
||
if len(self._wins) > self._wins_cap:
|
||
self._wins = self._wins[-self._wins_cap:]
|
||
|
||
def _snapshot_fudai(self) -> dict:
|
||
with self._lock:
|
||
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
|
||
|
||
with self._lock:
|
||
self._last_log_ts = time.time()
|
||
|
||
# --- 福袋:抽取"最近一次"识别到的信息 ---
|
||
# 支持多种格式:旧格式"福袋内容:"和新格式"字段_内容="或"内容="
|
||
content_extracted = False
|
||
if "福袋内容:" in s:
|
||
with self._lock:
|
||
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:
|
||
with self._lock:
|
||
self._fudai_last["content"] = m.group(1).strip()
|
||
self._fudai_last["updated_ts"] = time.time()
|
||
content_extracted = True
|
||
|
||
if content_extracted:
|
||
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:
|
||
with self._lock:
|
||
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:
|
||
with self._lock:
|
||
self._fudai_last["copies"] = int(m.group(1))
|
||
self._fudai_last["updated_ts"] = time.time()
|
||
|
||
# 倒计时:支持多种格式
|
||
if "倒计时时间:" in s:
|
||
with self._lock:
|
||
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:
|
||
with self._lock:
|
||
self._fudai_last["countdown"] = m.group(1).strip()
|
||
self._fudai_last["updated_ts"] = time.time()
|
||
|
||
# 奖品价值:支持多种格式
|
||
m = re.search(r"(?:字段_)?(?:价值|价值元|奖品价值)[=:]?\s*([0-9]+(?:\.[0-9]+)?)", s)
|
||
if not m:
|
||
m = re.search(r"奖品价值:\s*([0-9]+(?:\.[0-9]+)?)\s*元", s)
|
||
if m:
|
||
try:
|
||
with self._lock:
|
||
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]+(?:\.[0-9]+)?)", s)
|
||
if m:
|
||
try:
|
||
meta["prize_value_yuan"] = float(m.group(1))
|
||
except Exception:
|
||
pass
|
||
m = re.search(r"阈值[=:]?\s*([0-9]+(?:\.[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)
|
||
|
||
# --- 错误和异常统计 ---
|
||
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", {})
|
||
|
||
# --- 预约记录相关 ---
|
||
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]+(?:\.[0-9]+)?)\s*秒", s)
|
||
if m:
|
||
try:
|
||
meta["elapsed_seconds"] = float(m.group(1))
|
||
except Exception:
|
||
pass
|
||
m = re.search(r"分数[=:]?\s*([0-9]+(?:\.[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]+(?:\.[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)
|
||
|
||
def get_stats(self) -> 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
|
||
counters = dict(self._counters)
|
||
fudai_last = dict(self._fudai_last)
|
||
wins = list(self._wins[-20:]) # 只返回最近20条
|
||
events = list(self._events[-1000:]) # 返回最近1000条事件用于统计
|
||
|
||
now = time.time()
|
||
uptime = 0
|
||
if start_ts and start_ts > 0:
|
||
uptime = int(max(0, now - start_ts))
|
||
|
||
return {
|
||
"running": bool(running),
|
||
"pid": pid,
|
||
"start_ts": start_ts,
|
||
"last_log_ts": last_log_ts,
|
||
"exit_code": exit_code,
|
||
"uptime_seconds": uptime,
|
||
"counters": counters,
|
||
"fudai_last": fudai_last,
|
||
"wins": wins,
|
||
"events": events,
|
||
}
|
||
|
||
def start(self, params: RunParams) -> None:
|
||
if self.is_running():
|
||
raise RuntimeError("已经在运行")
|
||
|
||
# 如果 wait_minutes=0,表示无限循环模式
|
||
wait_minutes_arg = str(params.wait_minutes) if params.wait_minutes > 0 else "0"
|
||
run_cli_path = path_config.get_run_cli_path()
|
||
if not os.path.exists(run_cli_path):
|
||
raise FileNotFoundError(
|
||
f"未找到 run_cli.py 文件。\n"
|
||
f"预期路径: {run_cli_path}\n"
|
||
f"请确保 run_cli.py 位于项目根目录。"
|
||
)
|
||
cmd = [
|
||
sys.executable,
|
||
run_cli_path,
|
||
"--y-pianyi",
|
||
str(params.y_pianyi),
|
||
"--wait-minutes",
|
||
wait_minutes_arg,
|
||
]
|
||
if params.device_id:
|
||
cmd += ["--device-id", params.device_id]
|
||
if params.needswitch:
|
||
cmd.append("--needswitch")
|
||
|
||
cmd += ["--min-prize-value-yuan", str(params.min_prize_value_yuan)]
|
||
|
||
# 这些参数是新增可调节项:倒计时太短跳过、参与人数范围
|
||
cmd += ["--skip-if-countdown-gt-seconds", str(int(params.skip_if_countdown_gt_seconds or 900))]
|
||
if params.reset_after_swipes_enabled:
|
||
cmd.append("--reset-after-swipes-enabled")
|
||
cmd += ["--reset-after-swipes", str(int(params.reset_after_swipes or 10))]
|
||
else:
|
||
cmd.append("--reset-after-swipes-disabled")
|
||
if int(params.min_participants or 0) > 0:
|
||
cmd += ["--min-participants", str(int(params.min_participants))]
|
||
if int(params.max_participants or 0) > 0:
|
||
cmd += ["--max-participants", str(int(params.max_participants))]
|
||
|
||
if params.auto_join_fansclub:
|
||
cmd.append("--auto-join-fansclub")
|
||
if params.fansclub_fail_action:
|
||
cmd += ["--fansclub-fail-action", params.fansclub_fail_action]
|
||
|
||
# 高价值直播间回访
|
||
if params.high_value_room_revisit_enabled:
|
||
cmd.append("--high-value-room-revisit-enabled")
|
||
else:
|
||
cmd.append("--high-value-room-revisit-disabled")
|
||
if params.high_value_room_revisit_only_current_run:
|
||
cmd.append("--high-value-room-revisit-only-current-run")
|
||
|
||
# 预约回退校验
|
||
if params.reservation_back_verify_enabled:
|
||
cmd.append("--reservation-back-verify-enabled")
|
||
else:
|
||
cmd.append("--reservation-back-verify-disabled")
|
||
if params.reservation_back_swipe_delay > 0:
|
||
cmd += ["--reservation-back-swipe-delay", str(params.reservation_back_swipe_delay)]
|
||
|
||
# 预约抢占最小价值
|
||
if params.reservation_preempt_min_value > 0:
|
||
cmd += ["--reservation-preempt-min-value", str(params.reservation_preempt_min_value)]
|
||
|
||
# 找福袋最大尝试次数
|
||
if params.fudai_find_max_attempts > 0:
|
||
cmd += ["--fudai-find-max-attempts", str(params.fudai_find_max_attempts)]
|
||
|
||
# OCR模式1开关
|
||
if params.enable_ocr_mode1:
|
||
cmd.append("--enable-ocr-mode1")
|
||
else:
|
||
cmd.append("--disable-ocr-mode1")
|
||
|
||
# 福袋模板匹配开关
|
||
if params.fudai_template_match_enabled:
|
||
cmd.append("--fudai-template-enabled")
|
||
else:
|
||
cmd.append("--fudai-template-disabled")
|
||
|
||
# 添加福袋模板匹配阈值参数
|
||
cmd.extend(["--fudai-template-threshold", str(params.fudai_template_match_threshold)])
|
||
|
||
# 继承当前环境,并确保 adb 在 PATH(即使用户没手动刷新 PATH)
|
||
env = os.environ.copy()
|
||
env.setdefault("PYTHONIOENCODING", "utf-8")
|
||
|
||
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
|
||
else:
|
||
self._on_line("[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH")
|
||
|
||
try:
|
||
p = subprocess.Popen(
|
||
cmd,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.STDOUT,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
env=env,
|
||
cwd=path_config.PROJECT_ROOT,
|
||
)
|
||
except FileNotFoundError as e:
|
||
raise RuntimeError(
|
||
f"无法启动进程:找不到 Python 解释器或 run_cli.py 文件\n"
|
||
f"Python路径: {sys.executable}\n"
|
||
f"run_cli.py路径: {run_cli_path}\n"
|
||
f"原始错误: {e}"
|
||
)
|
||
except Exception as e:
|
||
raise RuntimeError(
|
||
f"启动进程失败:{e}\n"
|
||
f"命令: {' '.join(cmd)}\n"
|
||
f"工作目录: {path_config.PROJECT_ROOT}"
|
||
)
|
||
|
||
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._counters = {}
|
||
self._fudai_last = {
|
||
"content": "",
|
||
"countdown": "",
|
||
"participants": None,
|
||
"copies": None,
|
||
"prize_value_yuan": None,
|
||
"updated_ts": None,
|
||
}
|
||
self._events = []
|
||
self._wins = []
|
||
|
||
def _reader():
|
||
assert self._proc is not None
|
||
out = self._proc.stdout
|
||
if out is None:
|
||
return
|
||
try:
|
||
# 读取所有输出
|
||
has_output = False
|
||
for line in out:
|
||
has_output = True
|
||
cleaned_line = line.rstrip("\n")
|
||
self._on_line(cleaned_line)
|
||
try:
|
||
self._update_stats_from_line(cleaned_line)
|
||
except Exception:
|
||
pass
|
||
|
||
# 等待进程结束
|
||
rc = self._proc.wait()
|
||
with self._lock:
|
||
self._exit_code = rc
|
||
|
||
# 如果进程立即退出且没有输出,说明可能有问题
|
||
if not has_output and rc != 0:
|
||
self._on_line(f"[警告] 进程立即退出,退出码={rc},没有输出")
|
||
self._on_line("[提示] 可能的原因:run_cli.py启动失败、导入错误或配置错误")
|
||
else:
|
||
self._on_line(f"[进程结束] exit_code={rc}")
|
||
except Exception as e:
|
||
# 读取输出时出错
|
||
try:
|
||
self._on_line(f"[错误] 读取进程输出失败: {e}")
|
||
rc = self._proc.poll()
|
||
if rc is not None:
|
||
with self._lock:
|
||
self._exit_code = rc
|
||
self._on_line(f"[进程结束] exit_code={rc}")
|
||
except Exception:
|
||
pass
|
||
|
||
self._reader_thread = threading.Thread(target=_reader, daemon=True)
|
||
self._reader_thread.start()
|
||
|
||
# (已移除) 测试养号启动器
|
||
|
||
# (已移除) 测试评论启动器
|
||
|
||
def send_back_key(self, device_id: str) -> bool:
|
||
"""手动发送返回键到指定设备。
|
||
|
||
Args:
|
||
device_id: 设备ID,如果为空则使用第一个可用设备
|
||
|
||
Returns:
|
||
True if successful, False otherwise
|
||
"""
|
||
try:
|
||
adb_exe = find_adb_executable()
|
||
if not adb_exe:
|
||
self._on_line("[错误] 未找到 adb.exe")
|
||
return False
|
||
|
||
# 如果没有指定设备ID,尝试获取第一个可用设备
|
||
if not device_id or device_id.strip() == "":
|
||
devices = list_adb_devices(adb_exe)
|
||
if not devices:
|
||
self._on_line("[错误] 未找到可用设备")
|
||
return False
|
||
device_id = devices[0]
|
||
|
||
# 发送返回键 (keyevent 4)
|
||
cmd = [adb_exe, "-s", device_id, "shell", "input", "keyevent", "4"]
|
||
proc = subprocess.run(
|
||
cmd,
|
||
capture_output=True,
|
||
text=True,
|
||
encoding="utf-8",
|
||
errors="replace",
|
||
timeout=5.0,
|
||
)
|
||
|
||
if proc.returncode == 0:
|
||
self._on_line(f"[手动操作] 已发送返回键到设备: {device_id}")
|
||
return True
|
||
else:
|
||
error_msg = proc.stderr or proc.stdout or "未知错误"
|
||
self._on_line(f"[错误] 发送返回键失败: {error_msg}")
|
||
return False
|
||
except subprocess.TimeoutExpired:
|
||
self._on_line("[错误] 发送返回键超时")
|
||
return False
|
||
except Exception as e:
|
||
self._on_line(f"[错误] 发送返回键异常: {str(e)}")
|
||
return False
|
||
|
||
def stop(self) -> None:
|
||
if not self.is_running():
|
||
return
|
||
assert self._proc is not None
|
||
self._on_line("[停止] 正在终止进程...")
|
||
self._proc.terminate()
|
||
try:
|
||
self._proc.wait(timeout=5)
|
||
except subprocess.TimeoutExpired:
|
||
self._on_line("[停止] 进程未退出,强制结束...")
|
||
self._proc.kill()
|
||
|
||
def force_stop(self) -> None:
|
||
"""更强硬的停止:直接杀掉已记录的 PID 及其子进程(主要针对 Windows 下残留进程)。"""
|
||
with self._lock:
|
||
pid = self._pid
|
||
proc = self._proc
|
||
if not pid and not proc:
|
||
self._on_line("[停止] 当前无记录中的运行进程")
|
||
return
|
||
|
||
self._on_line(f"[停止] 强制终止进程 (pid={pid}) ...")
|
||
|
||
# 先尝试通过 Popen 对象 kill
|
||
try:
|
||
if proc is not None and proc.poll() is None:
|
||
proc.kill()
|
||
except Exception:
|
||
pass
|
||
|
||
# 再通过系统命令清理可能残留的子进程
|
||
if pid:
|
||
try:
|
||
if os.name == "nt":
|
||
# Windows:使用 taskkill 结束进程树
|
||
subprocess.run(
|
||
["taskkill", "/PID", str(pid), "/T", "/F"],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
else:
|
||
# 类 Unix:尝试向进程组发送 SIGKILL
|
||
import signal
|
||
|
||
try:
|
||
os.kill(pid, signal.SIGKILL)
|
||
except AttributeError:
|
||
# 如果SIGKILL不存在,使用SIGTERM
|
||
os.kill(pid, signal.SIGTERM)
|
||
except Exception:
|
||
pass
|
||
|
||
with self._lock:
|
||
self._proc = None
|
||
self._pid = None
|
||
|
||
|
||
|