477 lines
18 KiB
Python
477 lines
18 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import tkinter as tk
|
|
from tkinter import ttk
|
|
|
|
from . import theme
|
|
from .data import DashboardData, fmt_ts, load_dashboard_data
|
|
from .page_context import PageContext
|
|
from .page_helpers import reservation_rows
|
|
from .widgets import flow_grid, log_panel, preview_panel, section, stat_tile, table_panel, text_panel, toolbar
|
|
|
|
_ACTION_EMPTY_RE = re.compile(r"^\d{4}-\d{2}-\d{2} .* - \[ACTION\] (行为|参与|运行)\s*$")
|
|
_ACTION_TIME_PREFIX_RE = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:[,.]\d+)?) - ")
|
|
_BRACKET_TIME_RE = re.compile(r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:[,.]\d+)?)\]\s*")
|
|
_ACTION_KEYWORDS = (
|
|
"[手动操作]",
|
|
"[操作]",
|
|
"[参与]",
|
|
"[中奖]",
|
|
"[运行]",
|
|
"[预约]",
|
|
"[重访]",
|
|
"[养号]",
|
|
"[返回]",
|
|
"[截图]",
|
|
"[ACTION]",
|
|
"上滑切换直播间",
|
|
"下滑回退直播间",
|
|
"发送返回键",
|
|
"点击参与",
|
|
"识别福袋详情完成",
|
|
"程序开始运行",
|
|
"程序运行结束",
|
|
)
|
|
|
|
|
|
def _clean_action_line(line: str) -> str | None:
|
|
text = str(line or "").strip().lstrip("\ufeff")
|
|
if not text or set(text) == {"="}:
|
|
return None
|
|
if _ACTION_EMPTY_RE.match(text):
|
|
return None
|
|
text = _ACTION_TIME_PREFIX_RE.sub("", text, count=1)
|
|
text = _BRACKET_TIME_RE.sub("", text, count=1)
|
|
text = text.replace("[ACTION] ", "").strip()
|
|
if text in {"行为", "参与", "运行"}:
|
|
return None
|
|
return text[:180]
|
|
|
|
|
|
def _is_action_line(line: str) -> bool:
|
|
text = str(line or "")
|
|
return any(keyword in text for keyword in _ACTION_KEYWORDS)
|
|
|
|
|
|
def _runner_action_lines(ctx: PageContext) -> list[str]:
|
|
runner = ctx.runner
|
|
if runner is None:
|
|
return []
|
|
try:
|
|
with runner._lock:
|
|
lines = list(runner._log[-800:])
|
|
except Exception:
|
|
return []
|
|
return [line for line in lines if _is_action_line(line)]
|
|
|
|
|
|
def _compact_action_lines(file_lines: list[str], runner_lines: list[str]) -> list[str]:
|
|
merged: list[str] = []
|
|
seen_recent: list[str] = []
|
|
for raw in [*file_lines, *runner_lines]:
|
|
line = _clean_action_line(raw)
|
|
if not line:
|
|
continue
|
|
if seen_recent and line == seen_recent[-1]:
|
|
continue
|
|
if line in seen_recent[-12:]:
|
|
continue
|
|
merged.append(line)
|
|
seen_recent.append(line)
|
|
if len(seen_recent) > 24:
|
|
seen_recent = seen_recent[-24:]
|
|
return merged[-700:]
|
|
|
|
|
|
def _scroll_controls(parent: tk.Misc, ctx: PageContext, key: str, note: str = "") -> tuple[tk.StringVar, ttk.Combobox]:
|
|
controls = tk.Frame(parent, bg=theme.BG)
|
|
controls.pack(fill="x", pady=(0, 8))
|
|
tk.Label(controls, text="滚动:", bg=theme.BG, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
|
|
existing = ctx.vars.get(key)
|
|
if isinstance(existing, tk.StringVar):
|
|
scroll_var = existing
|
|
else:
|
|
scroll_var = tk.StringVar(value="跟随底部")
|
|
ctx.vars[key] = scroll_var
|
|
scroll_combo = ttk.Combobox(
|
|
controls,
|
|
textvariable=scroll_var,
|
|
values=("跟随底部", "保持位置", "强制顶部"),
|
|
state="readonly",
|
|
width=10,
|
|
)
|
|
scroll_combo.pack(side="left")
|
|
if note:
|
|
tk.Label(
|
|
controls,
|
|
text=note,
|
|
bg=theme.BG,
|
|
fg=theme.SUBTLE,
|
|
font=theme.FONT_SMALL,
|
|
).pack(side="left", padx=(10, 0))
|
|
return scroll_var, scroll_combo
|
|
|
|
|
|
def _scroll_mode(scroll_var: tk.StringVar) -> str:
|
|
value = scroll_var.get()
|
|
if value == "强制顶部":
|
|
return "top"
|
|
if value == "保持位置":
|
|
return "keep"
|
|
return "follow"
|
|
|
|
|
|
def _set_log_text(text: tk.Text, lines: list[str], *, scroll_mode: str = "follow") -> None:
|
|
try:
|
|
before = text.yview()
|
|
top_pos = before[0]
|
|
at_bottom = before[1] >= 0.98
|
|
except Exception:
|
|
top_pos = 0.0
|
|
at_bottom = True
|
|
text.configure(state="normal")
|
|
text.delete("1.0", "end")
|
|
text.insert("1.0", "\n".join(lines[-1000:]) or "暂无数据")
|
|
text.configure(state="disabled")
|
|
if scroll_mode == "top":
|
|
text.yview_moveto(0.0)
|
|
elif scroll_mode == "keep":
|
|
text.yview_moveto(top_pos)
|
|
else:
|
|
text.yview_moveto(1.0)
|
|
|
|
|
|
def _apply_scroll_strategy(text: tk.Text, scroll_var: tk.StringVar) -> None:
|
|
mode = _scroll_mode(scroll_var)
|
|
if mode == "top":
|
|
text.yview_moveto(0.0)
|
|
elif mode == "follow":
|
|
text.yview_moveto(1.0)
|
|
|
|
|
|
def _runner_lines(ctx: PageContext, fallback: list[str]) -> list[str]:
|
|
runner = ctx.runner
|
|
if runner is not None:
|
|
try:
|
|
with runner._lock:
|
|
lines = list(runner._log[-1000:])
|
|
if lines:
|
|
return lines
|
|
except Exception:
|
|
pass
|
|
return fallback
|
|
|
|
|
|
def build_run_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "运行日志", "实时输出 / 独立滚动 / 刷新")
|
|
toolbar(parent, [("刷新", ctx.action("refresh"), "soft"), ("行为日志", ctx.action("show_actions_log"), "soft"), "上一个", "下一个", "清除"])
|
|
scroll_var, scroll_combo = _scroll_controls(parent, ctx, "run_log_scroll_mode")
|
|
box, text = log_panel(parent, "运行日志", _runner_lines(ctx, data.run_log), height=24)
|
|
box.pack(fill="both", expand=True)
|
|
scroll_combo.bind("<<ComboboxSelected>>", lambda _e: _apply_scroll_strategy(text, scroll_var), add="+")
|
|
|
|
def refresh_live() -> None:
|
|
try:
|
|
if not text.winfo_exists():
|
|
return
|
|
except Exception:
|
|
return
|
|
_set_log_text(text, _runner_lines(ctx, data.run_log), scroll_mode=_scroll_mode(scroll_var))
|
|
try:
|
|
text.after(1200, refresh_live)
|
|
except Exception:
|
|
pass
|
|
|
|
refresh_live()
|
|
|
|
|
|
def build_preview(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "截图预览", "选择图片 / 打开pic目录 / 刷新预览")
|
|
toolbar(parent, [("刷新预览", ctx.action("refresh"), "soft"), ("截图+OCR", ctx.action("screenshot_ocr"), "primary"), "打开pic目录"])
|
|
preview_panel(parent, data.current_screenshot_path, "当前截图").pack(fill="both", expand=True)
|
|
|
|
|
|
RESERVATION_COLUMNS = (
|
|
("idx", "#", 40), ("pos", "位置", 70), ("title", "直播间", 220), ("raw_title", "原始标题", 240),
|
|
("content", "内容", 220), ("value", "价值", 80), ("countdown", "倒计时/开奖", 120),
|
|
("participants", "人数", 74), ("copies", "份数", 70), ("task_count", "任务数", 74),
|
|
("status", "状态", 90), ("target_time", "开奖时间", 160), ("created_time", "记录时间", 160),
|
|
)
|
|
|
|
|
|
HOME_RESERVATION_COLUMNS = (
|
|
("idx", "#", 32), ("pos", "位置", 54), ("title", "直播间", 120), ("content", "内容", 160),
|
|
("value", "价值", 58), ("countdown", "倒计时", 76), ("status", "状态", 68), ("target_time", "开奖时间", 132),
|
|
)
|
|
|
|
|
|
def _reservation_rows_for_display(data: DashboardData, *, include_created: bool) -> list[dict]:
|
|
rows = reservation_rows(data)
|
|
for row in rows:
|
|
row["target_time"] = fmt_ts(row["target_time"])
|
|
if include_created:
|
|
row["created_time"] = fmt_ts(row["created_time"])
|
|
return rows
|
|
|
|
|
|
def _reservation_auto_refresh_var(ctx: PageContext) -> tk.BooleanVar:
|
|
var = ctx.vars.get("reservation_auto_refresh")
|
|
if isinstance(var, tk.BooleanVar):
|
|
return var
|
|
var = tk.BooleanVar(value=True)
|
|
ctx.vars["reservation_auto_refresh"] = var
|
|
return var
|
|
|
|
|
|
def _replace_table_rows(tree: ttk.Treeview, columns: tuple[tuple[str, str, int], ...], rows: list[dict]) -> None:
|
|
try:
|
|
yview = tree.yview()
|
|
top_pos = yview[0]
|
|
except Exception:
|
|
top_pos = 0.0
|
|
for item_id in tree.get_children(""):
|
|
tree.delete(item_id)
|
|
if rows:
|
|
for row in rows:
|
|
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
|
|
else:
|
|
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
|
|
try:
|
|
tree.yview_moveto(top_pos)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _schedule_reservation_table_refresh(
|
|
table_box: tk.Misc,
|
|
ctx: PageContext,
|
|
columns: tuple[tuple[str, str, int], ...],
|
|
*,
|
|
include_created: bool,
|
|
interval_ms: int = 5000,
|
|
) -> None:
|
|
enabled_var = _reservation_auto_refresh_var(ctx)
|
|
if getattr(table_box, "_reservation_refresh_scheduled", False):
|
|
return
|
|
setattr(table_box, "_reservation_refresh_scheduled", True)
|
|
|
|
def tick() -> None:
|
|
setattr(table_box, "_reservation_refresh_scheduled", False)
|
|
try:
|
|
if not table_box.winfo_exists():
|
|
return
|
|
except Exception:
|
|
return
|
|
if bool(enabled_var.get()):
|
|
tree = getattr(table_box, "tree", None)
|
|
if tree is not None:
|
|
latest = load_dashboard_data()
|
|
rows = _reservation_rows_for_display(latest, include_created=include_created)
|
|
_replace_table_rows(tree, columns, rows)
|
|
_schedule_reservation_table_refresh(
|
|
table_box,
|
|
ctx,
|
|
columns,
|
|
include_created=include_created,
|
|
interval_ms=interval_ms,
|
|
)
|
|
|
|
try:
|
|
table_box.after(interval_ms, tick)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def reservation_auto_refresh_control(parent: tk.Misc, ctx: PageContext, table_box: tk.Misc, columns, *, include_created: bool) -> tk.Checkbutton:
|
|
auto_refresh_var = _reservation_auto_refresh_var(ctx)
|
|
check = tk.Checkbutton(
|
|
parent,
|
|
text="自动刷新(5s)",
|
|
variable=auto_refresh_var,
|
|
bg=theme.BG,
|
|
fg=theme.TEXT,
|
|
activebackground=theme.BG,
|
|
activeforeground=theme.TEXT,
|
|
selectcolor=theme.SURFACE,
|
|
relief="flat",
|
|
bd=0,
|
|
font=theme.FONT_UI,
|
|
cursor="hand2",
|
|
)
|
|
check.configure(
|
|
command=lambda: _schedule_reservation_table_refresh(
|
|
table_box,
|
|
ctx,
|
|
columns,
|
|
include_created=include_created,
|
|
)
|
|
)
|
|
if bool(auto_refresh_var.get()):
|
|
_schedule_reservation_table_refresh(table_box, ctx, columns, include_created=include_created)
|
|
return check
|
|
|
|
|
|
def build_reservation_queue(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "预约队列", "预约队列总览与等待状态")
|
|
tools = toolbar(parent, [("刷新", ctx.action("refresh"), "soft")])
|
|
rows = _reservation_rows_for_display(data, include_created=True)
|
|
table = table_panel(parent, "预约队列", RESERVATION_COLUMNS, rows, height=18)
|
|
table.pack(fill="both", expand=True)
|
|
reservation_auto_refresh_control(tools, ctx, table, RESERVATION_COLUMNS, include_created=True).pack(side="left", padx=(4, 0))
|
|
|
|
|
|
def build_high_value(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "高价值房间", "持久化高价值记录")
|
|
toolbar(parent, [("刷新", ctx.action("refresh"), "soft")])
|
|
rows = []
|
|
for idx, item in enumerate(data.high_value_rooms[:50], 1):
|
|
rows.append({
|
|
"idx": idx,
|
|
"title": item.get("room_title") or item.get("title") or "-",
|
|
"content": item.get("content") or item.get("prize_content") or "-",
|
|
"value": item.get("prize_value_yuan") or item.get("value") or "-",
|
|
"status": item.get("status") or "已记录",
|
|
})
|
|
table_panel(parent, "高价值房间", (
|
|
("idx", "#", 40), ("title", "直播间", 220), ("content", "内容", 280),
|
|
("value", "价值", 90), ("status", "状态", 100),
|
|
), rows, height=20).pack(fill="both", expand=True)
|
|
|
|
|
|
def build_actions_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "行为日志", "actions.log / 独立滚动 / 刷新")
|
|
toolbar(parent, [("刷新", ctx.action("refresh"), "soft"), ("运行日志", ctx.action("show_run_log"), "soft"), "上一个", "下一个", "清除"])
|
|
scroll_var, scroll_combo = _scroll_controls(parent, ctx, "actions_log_scroll_mode", "合并重复,只看关键操作")
|
|
lines = _compact_action_lines(data.action_log, _runner_action_lines(ctx))
|
|
box, text = log_panel(parent, "行为日志", lines, height=24)
|
|
box.pack(fill="both", expand=True)
|
|
scroll_combo.bind("<<ComboboxSelected>>", lambda _e: _apply_scroll_strategy(text, scroll_var), add="+")
|
|
|
|
def refresh_file() -> None:
|
|
try:
|
|
if not text.winfo_exists():
|
|
return
|
|
except Exception:
|
|
return
|
|
try:
|
|
from .data import load_dashboard_data
|
|
latest = load_dashboard_data().action_log
|
|
except Exception:
|
|
latest = data.action_log
|
|
_set_log_text(text, _compact_action_lines(latest, _runner_action_lines(ctx)), scroll_mode=_scroll_mode(scroll_var))
|
|
try:
|
|
text.after(2000, refresh_file)
|
|
except Exception:
|
|
pass
|
|
|
|
refresh_file()
|
|
|
|
|
|
def build_realtime(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "实时状态", "显示动作流 / 显示截图 / 自动滚动 / 查看大图")
|
|
toolbar(parent, ["显示动作流", "显示截图", "自动滚动", "查看大图"])
|
|
body = tk.Frame(parent, bg=theme.BG)
|
|
body.pack(fill="both", expand=True)
|
|
text_panel(body, "动作流", data.action_log[-120:], height=16).pack(fill="both", expand=True, pady=(0, 12))
|
|
preview_panel(body, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True)
|
|
|
|
|
|
def build_ocr(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "OCR结果", "点击 截图+OCR 后更新")
|
|
toolbar(parent, [("截图+OCR", ctx.action("screenshot_ocr"), "primary"), ("刷新", ctx.action("refresh"), "soft")])
|
|
lines = []
|
|
for p in data.ocr_files[:8]:
|
|
lines.append(f"{p.name} {fmt_ts(p.stat().st_mtime)}")
|
|
text_panel(parent, "OCR结果", lines or ['暂无OCR结果,请先点击"截图+OCR"按钮'], height=24).pack(fill="both", expand=True)
|
|
|
|
|
|
def build_wins(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "中奖记录", "中奖截图列表与预览")
|
|
toolbar(parent, [("刷新列表", ctx.action("refresh"), "soft"), "打开目录", "保存误识别", "加载误识别"])
|
|
body = tk.Frame(parent, bg=theme.BG)
|
|
body.pack(fill="both", expand=True)
|
|
body.grid_columnconfigure(0, weight=4)
|
|
body.grid_columnconfigure(1, weight=5)
|
|
rows = [{"idx": i + 1, "file": p.name, "time": fmt_ts(p.stat().st_mtime)} for i, p in enumerate(data.win_images[:40])]
|
|
table_panel(body, "中奖截图列表", (("idx", "#", 40), ("file", "文件", 260), ("time", "时间", 160)), rows, height=18).grid(row=0, column=0, sticky="nsew", padx=(0, 8))
|
|
preview_panel(body, data.win_images[0] if data.win_images else None, "截图预览").grid(row=0, column=1, sticky="nsew", padx=(8, 0))
|
|
|
|
|
|
def _mapping_auto_refresh_var(ctx: PageContext) -> tk.BooleanVar:
|
|
var = ctx.vars.get("mapping_auto_refresh")
|
|
if isinstance(var, tk.BooleanVar):
|
|
return var
|
|
var = tk.BooleanVar(value=True)
|
|
ctx.vars["mapping_auto_refresh"] = var
|
|
return var
|
|
|
|
|
|
def _schedule_mapping_refresh(widget: tk.Misc, ctx: PageContext, enabled_var: tk.BooleanVar, interval_ms: int = 5000) -> None:
|
|
if getattr(widget, "_mapping_refresh_scheduled", False):
|
|
return
|
|
setattr(widget, "_mapping_refresh_scheduled", True)
|
|
|
|
def tick() -> None:
|
|
setattr(widget, "_mapping_refresh_scheduled", False)
|
|
try:
|
|
if not widget.winfo_exists():
|
|
return
|
|
except Exception:
|
|
return
|
|
if not bool(enabled_var.get()):
|
|
return
|
|
refresh = ctx.action("refresh")
|
|
if refresh:
|
|
refresh()
|
|
|
|
try:
|
|
widget.after(interval_ms, tick)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def build_mapping(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "映射表", "显示原始标题 / 刷新映射表 / 搜索 / 复制条目")
|
|
refresh = ctx.action("refresh")
|
|
auto_refresh_var = _mapping_auto_refresh_var(ctx)
|
|
tools = toolbar(parent, [("刷新映射表", refresh, "soft"), "显示原始标题", "清除", "复制条目"])
|
|
auto_check = tk.Checkbutton(
|
|
tools,
|
|
text="自动刷新(5s)",
|
|
variable=auto_refresh_var,
|
|
bg=theme.BG,
|
|
fg=theme.TEXT,
|
|
activebackground=theme.BG,
|
|
activeforeground=theme.TEXT,
|
|
selectcolor=theme.SURFACE,
|
|
relief="flat",
|
|
bd=0,
|
|
font=theme.FONT_UI,
|
|
cursor="hand2",
|
|
)
|
|
auto_check.pack(side="left", padx=(4, 0))
|
|
mapping_table = table_panel(parent, "运行时映射表", (
|
|
("pos", "位置", 70), ("title", "标题", 230), ("raw_title", "原始标题", 250),
|
|
("reserved", "预约", 64), ("has_fudai", "福袋", 64), ("value", "价值", 90),
|
|
("countdown", "倒计时", 90), ("participants", "人数", 74), ("copies", "份数", 70),
|
|
("button", "按钮", 120), ("task", "任务", 180), ("content", "内容", 220), ("updated", "更新时间", 160),
|
|
), data.mapping_rows, height=22)
|
|
mapping_table.pack(fill="both", expand=True)
|
|
auto_check.configure(command=lambda: _schedule_mapping_refresh(mapping_table, ctx, auto_refresh_var))
|
|
if bool(auto_refresh_var.get()):
|
|
_schedule_mapping_refresh(mapping_table, ctx, auto_refresh_var)
|
|
|
|
|
|
def build_wifi_adb(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
|
section(parent, "WiFi ADB", "扫描 WiFi / USB 授权提示 / 连接状态")
|
|
toolbar(parent, [("扫描WiFi", ctx.action("scan_wifi"), "primary"), ("WiFi ADB", ctx.action("wifi_adb"), "soft"), ("刷新设备", ctx.action("refresh_devices"), "soft")])
|
|
metrics = flow_grid(parent, 4)
|
|
for idx, item in enumerate([
|
|
("USB设备", "待检测", "首次启用", theme.TEAL, theme.TEAL_SOFT),
|
|
("扫描状态", "未扫描", "局域网", theme.BLUE, theme.BLUE_SOFT),
|
|
("默认端口", "5555", "ADB TCP", theme.AMBER, theme.AMBER_SOFT),
|
|
("当前设备", "设备选择器", "顶部下拉", theme.GREEN, theme.GREEN_SOFT),
|
|
]):
|
|
stat_tile(metrics, *item[:3], color=item[3], soft=item[4]).grid(row=0, column=idx, sticky="ew", padx=5)
|