Files
douyin_guaji-main/webui/app.js
T
Your Name 533943620c feat: Optimize OCR performance and enhance debugging features
- Implemented parallel execution for OCR tasks, significantly improving recognition speed for content, countdown, and value detection.
- Updated configuration settings to support automatic cleanup of debug captures, including retention days and maximum file limits.
- Enhanced GUI to include new options for debugging parameters, allowing users to configure debug capture settings directly.
- Improved documentation to reflect changes in OCR functionality and debugging features, ensuring clarity for users.
- Refined error handling and logging across various modules to facilitate better monitoring and troubleshooting.
2025-12-22 03:27:37 +08:00

1193 lines
41 KiB
JavaScript
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.
let logIdx = 0;
let pollTimer = null;
let statsTimer = null;
let shotTimer = null;
let lastLogUpdateTime = 0; // 最后成功获取日志的时间
let logErrorCount = 0; // 连续错误计数
let emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住)
const DEFAULTS = {
// 筛选
min_prize_value_yuan: 0,
min_participants: 0,
max_participants: 0,
skip_if_countdown_lt_seconds: 15,
reset_after_swipes_enabled: false,
reset_after_swipes: 10,
auto_join_fansclub: false,
fansclub_fail_action: "stay",
// 养号
yanghao_enabled: true,
yanghao_enable_actions: true,
yanghao_step_screenshot: false,
yanghao_recommend_duration_seconds: 60,
yanghao_recommend_interval_seconds: 0,
yanghao_like_prob: 0.15,
yanghao_fav_prob: 0.05,
yanghao_comment_prob: 0,
yanghao_icon_roi_size: 180,
yanghao_icon_match_threshold: 0.72,
yanghao_like_template_path: "assets/like.png",
yanghao_fav_template_path: "assets/fav.png",
yanghao_after_dwell_swipe_direction: "up",
yanghao_after_dwell_swipe_distance_px: 900,
// 高价值福袋预约
high_value_fudai_enabled: false,
high_value_fudai_threshold_yuan: 1000,
high_value_fudai_join_ahead_seconds: 120,
high_value_fudai_max_swipe_back: 60,
high_value_fudai_max_reservations: 5,
high_value_fudai_after_action: "continue",
high_value_room_revisit_enabled: true,
high_value_room_revisit_only_current_run: false,
reservation_back_verify_enabled: true,
// 找福袋图标相关
fudai_find_max_attempts: 5,
fudai_icon_retry_delay_seconds: 0.6,
fudai_icon_max_wait_seconds: 5.0,
live_room_match_threshold: 0.8,
reservation_preempt_min_value: 0,
reservation_back_swipe_delay: 0.6,
// 定时禁抢福袋(默认 2-7 点)
fudai_quiet_hours_enabled: true,
fudai_quiet_start_hour: 2,
fudai_quiet_end_hour: 7,
// 调试相关
"debug_captures.auto_cleanup": true,
"debug_captures.keep_days": 7,
"debug_captures.max_files": 2000,
enable_ocr_mode1: false,
fudai_template_match_enabled: false,
fudai_template_match_threshold: 0.7,
lucky_draw_red_ratio_threshold: 0.8,
live_room_match_threshold: 0.7,
stage_diag_max_time: 15.0,
stage_diag_max_step_time: 4.0,
};
function $(id) { return document.getElementById(id); }
function initTabs() {
const tabButtons = Array.from(document.querySelectorAll(".tabBtn[data-target]"));
const panels = Array.from(document.querySelectorAll(".panel[data-panel]"));
if (tabButtons.length === 0 || panels.length === 0) return;
const setActive = (target) => {
for (const btn of tabButtons) {
const isActive = btn.dataset.target === target;
btn.classList.toggle("active", isActive);
btn.setAttribute("aria-selected", isActive ? "true" : "false");
}
for (const panel of panels) {
const isActive = panel.dataset.panel === target;
panel.toggleAttribute("hidden", !isActive);
panel.classList.toggle("active", isActive);
}
};
for (const btn of tabButtons) {
btn.addEventListener("click", () => setActive(btn.dataset.target));
}
const defaultTarget = tabButtons.find(b => b.classList.contains("active"))?.dataset.target || tabButtons[0].dataset.target;
setActive(defaultTarget);
}
function appendLog(lines) {
const log = $("log");
if (!lines || lines.length === 0) return;
// 检查是否在底部附近(用户可能在看最新日志)
const wasNearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 100;
// 性能优化:批量追加文本,减少重排次数
const newText = lines.join("\n") + "\n";
log.textContent += newText;
// 性能优化:限制日志长度,避免内存溢出(保留最近 50000 字符)
const maxLength = 50000;
if (log.textContent.length > maxLength) {
log.textContent = log.textContent.slice(-maxLength);
}
// 只有在底部附近时才自动滚动,避免打断用户查看历史日志
if (wasNearBottom) {
log.scrollTop = log.scrollHeight;
}
}
function fmtTime(ts) {
if (!ts) return "-";
try {
return new Date(ts * 1000).toLocaleString();
} catch {
return "-";
}
}
function fmtDuration(seconds) {
const s = Math.max(0, parseInt(seconds || 0, 10));
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
if (h > 0) return `${h}小时${m}分${sec}秒`;
if (m > 0) return `${m}分${sec}秒`;
return `${sec}秒`;
}
function pollShot() {
const img = $("liveShot");
if (!img) return;
// 性能优化:避免重复加载相同的图片(如果正在加载中)
if (img.dataset.loading === "true") return;
const url = `/pic/screenshot.png?t=${Date.now()}`;
img.dataset.loading = "true";
img.src = url;
const status = $("liveShotStatus");
if (status) status.textContent = `刷新中:${new Date().toLocaleTimeString()}`;
}
function startShotPolling() {
if (shotTimer) clearInterval(shotTimer);
const img = $("liveShot");
const status = $("liveShotStatus");
if (img) {
img.addEventListener("load", () => {
img.dataset.loading = "false";
if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`;
});
img.addEventListener("error", () => {
img.dataset.loading = "false";
if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)";
});
}
// 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力
shotTimer = setInterval(pollShot, 1500);
}
function setTextIfExists(id, text) {
const el = $(id);
if (!el) return;
el.textContent = String(text ?? "-");
}
function clearEl(el) {
while (el && el.firstChild) el.removeChild(el.firstChild);
}
function renderBars(containerId, dataMap, labelMap) {
const root = $(containerId);
if (!root) return;
clearEl(root);
const m = (dataMap && typeof dataMap === "object") ? dataMap : {};
const items = Object.keys(m).map(k => ({ key: k, count: Number(m[k]) || 0 }))
.filter(x => x.count > 0);
items.sort((a, b) => b.count - a.count);
if (items.length === 0) {
const d = document.createElement("div");
d.className = "hint";
d.textContent = "暂无数据";
root.appendChild(d);
return;
}
const max = Math.max(...items.map(x => x.count));
for (const it of items) {
const row = document.createElement("div");
row.className = "barRow";
const label = document.createElement("div");
label.className = "barLabel";
label.textContent = (labelMap && labelMap[it.key]) ? labelMap[it.key] : it.key;
const track = document.createElement("div");
track.className = "barTrack";
const fill = document.createElement("div");
fill.className = "barFill";
fill.style.width = `${max > 0 ? (it.count / max * 100) : 0}%`;
track.appendChild(fill);
const val = document.createElement("div");
val.className = "barValue";
val.textContent = String(it.count);
row.appendChild(label);
row.appendChild(track);
row.appendChild(val);
root.appendChild(row);
}
}
function renderTopContent(containerId, items) {
const root = $(containerId);
if (!root) return;
clearEl(root);
const list = Array.isArray(items) ? items : [];
const head = document.createElement("div");
head.className = "tableRow tableHead";
head.innerHTML = `<div>#</div><div>内容</div><div>次数</div>`;
root.appendChild(head);
if (list.length === 0) {
const row = document.createElement("div");
row.className = "tableRow";
row.innerHTML = `<div class="mono">-</div><div class="hint">暂无数据</div><div class="mono">-</div>`;
root.appendChild(row);
return;
}
list.forEach((it, idx) => {
const row = document.createElement("div");
row.className = "tableRow";
const key = String(it.key ?? "");
const cnt = Number(it.count) || 0;
row.innerHTML = `<div class="mono">#${idx + 1}</div><div>${escapeHtml(key)}</div><div class="mono">${cnt}</div>`;
root.appendChild(row);
});
}
function escapeHtml(s) {
return String(s ?? "")
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");
}
function renderWinsTable(containerId, wins) {
const root = $(containerId);
if (!root) return;
clearEl(root);
const list = Array.isArray(wins) ? wins : [];
const head = document.createElement("div");
head.className = "tableRow tableHead";
head.innerHTML = `<div>时间</div><div>内容</div><div>价值</div>`;
root.appendChild(head);
if (list.length === 0) {
const row = document.createElement("div");
row.className = "tableRow";
row.innerHTML = `<div class="mono">-</div><div class="hint">暂无中奖记录</div><div class="mono">-</div>`;
root.appendChild(row);
return;
}
// 后端按时间顺序存储,这里倒序展示(最新在上)
for (let i = list.length - 1; i >= 0; i--) {
const it = list[i] || {};
const ts = Number(it.ts) || 0;
const content = String(it.content || "-");
const value = (it.prize_value_yuan === null || typeof it.prize_value_yuan === "undefined") ? "-" : String(it.prize_value_yuan);
const row = document.createElement("div");
row.className = "tableRow";
row.innerHTML = `<div class="mono">${escapeHtml(fmtTime(ts))}</div><div>${escapeHtml(content)}</div><div class="mono">${escapeHtml(value)}</div>`;
root.appendChild(row);
}
}
function renderTimeline(containerId, timeline) {
const root = $(containerId);
if (!root) return;
clearEl(root);
const t = (timeline && typeof timeline === "object") ? timeline : null;
const series = t && t.series && typeof t.series === "object" ? t.series : null;
const bins = Number(t && t.bins) || 0;
if (!series || bins <= 0) {
const d = document.createElement("div");
d.className = "hint";
d.textContent = "暂无数据";
root.appendChild(d);
return;
}
const keys = [
"fudai_open_detail",
"fudai_attend_ok",
"fudai_attend_fail",
"fudai_result_win",
"fudai_result_no_win",
"fudai_skip",
"switch_room",
];
let maxY = 0;
for (const k of keys) {
const arr = Array.isArray(series[k]) ? series[k] : [];
for (const v of arr) maxY = Math.max(maxY, Number(v) || 0);
}
if (maxY <= 0) {
const d = document.createElement("div");
d.className = "hint";
d.textContent = "暂无数据";
root.appendChild(d);
return;
}
const W = 900;
const H = 220;
const padL = 36;
const padR = 14;
const padT = 10;
const padB = 26;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
svg.setAttribute("width", "100%");
svg.setAttribute("height", String(H));
svg.style.display = "block";
const axis = document.createElementNS("http://www.w3.org/2000/svg", "path");
axis.setAttribute("d", `M ${padL} ${H - padB} L ${W - padR} ${H - padB}`);
axis.setAttribute("stroke", "var(--border)");
axis.setAttribute("fill", "none");
svg.appendChild(axis);
const mkText = (x, y, txt, anchor = "start") => {
const el = document.createElementNS("http://www.w3.org/2000/svg", "text");
el.setAttribute("x", String(x));
el.setAttribute("y", String(y));
el.setAttribute("fill", "var(--muted)");
el.setAttribute("font-size", "11");
el.setAttribute("text-anchor", anchor);
el.textContent = txt;
return el;
};
const startTs = Number(t.start_ts) || 0;
const binSec = Number(t.bin_seconds) || 0;
const xAt = (i) => {
if (bins <= 1) return padL;
return padL + (W - padL - padR) * (i / (bins - 1));
};
const yAt = (v) => {
const vv = Number(v) || 0;
const h = (H - padT - padB);
return (H - padB) - (vv / maxY) * h;
};
// y 轴 max 标记
svg.appendChild(mkText(padL, padT + 10, String(maxY), "start"));
// x 轴 3 个时间刻度
const fmtShort = (ts) => {
if (!ts) return "-";
try { return new Date(ts * 1000).toLocaleTimeString(); } catch { return "-"; }
};
svg.appendChild(mkText(padL, H - 8, fmtShort(startTs), "start"));
svg.appendChild(mkText((padL + (W - padR)) / 2, H - 8, fmtShort(startTs + Math.floor(bins / 2) * binSec), "middle"));
svg.appendChild(mkText(W - padR, H - 8, fmtShort(startTs + (bins - 1) * binSec), "end"));
const strokes = {
fudai_open_detail: { stroke: "var(--primary)", dash: "" },
fudai_attend_ok: { stroke: "var(--primary)", dash: "6 4" },
fudai_attend_fail: { stroke: "var(--danger)", dash: "" },
fudai_result_win: { stroke: "var(--danger)", dash: "6 4" },
fudai_result_no_win: { stroke: "var(--muted)", dash: "" },
fudai_skip: { stroke: "var(--muted)", dash: "6 4" },
switch_room: { stroke: "var(--text)", dash: "2 4" },
};
for (const k of keys) {
const arr = Array.isArray(series[k]) ? series[k] : [];
if (arr.length === 0) continue;
let d = "";
for (let i = 0; i < Math.min(bins, arr.length); i++) {
const x = xAt(i);
const y = yAt(arr[i]);
d += (i === 0) ? `M ${x.toFixed(2)} ${y.toFixed(2)}` : ` L ${x.toFixed(2)} ${y.toFixed(2)}`;
}
const p = document.createElementNS("http://www.w3.org/2000/svg", "path");
p.setAttribute("d", d);
p.setAttribute("fill", "none");
p.setAttribute("stroke", strokes[k]?.stroke || "var(--primary)");
p.setAttribute("stroke-width", "2");
if (strokes[k]?.dash) p.setAttribute("stroke-dasharray", strokes[k].dash);
p.setAttribute("stroke-linecap", "round");
p.setAttribute("stroke-linejoin", "round");
svg.appendChild(p);
}
root.appendChild(svg);
const legend = document.createElement("div");
legend.className = "hint";
legend.textContent = "图例:实线/虚线区分同色不同事件";
root.appendChild(legend);
}
async function apiGet(path) {
const res = await fetch(path, { cache: "no-store" });
if (!res.ok) throw new Error(await res.text());
return await res.json();
}
async function apiPost(path, body) {
const res = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body || {}),
});
const data = await res.json();
if (!res.ok) {
const errorMsg = data.error || data.message || res.statusText;
const error = new Error(errorMsg);
error.status = res.status;
error.data = data;
throw error;
}
return data;
}
async function refreshDevices() {
const data = await apiGet("/api/devices");
const sel = $("device");
sel.innerHTML = "";
const devices = data.devices || [];
const optAuto = document.createElement("option");
optAuto.value = "";
optAuto.textContent = "(auto)";
sel.appendChild(optAuto);
for (const d of devices) {
const opt = document.createElement("option");
opt.value = d;
opt.textContent = d;
sel.appendChild(opt);
}
$("adbStatus").textContent = data.adb ? `adb: ${data.adb}` : "未找到 adb.exe(请安装 platform-tools)";
}
function getConfigBoundElements() {
return Array.from(document.querySelectorAll("[data-key]"));
}
function coerceValue(type, raw, isCheckbox) {
if (type === "bool") return !!raw;
if (type === "int") {
const n = parseInt(String(raw ?? "0"), 10);
return Number.isFinite(n) ? n : 0;
}
if (type === "float") {
const n = parseFloat(String(raw ?? "0"));
return Number.isFinite(n) ? n : 0;
}
if (type === "list_lines") {
if (Array.isArray(raw)) return raw.map(x => String(x).trim()).filter(Boolean);
return String(raw ?? "").split("\n").map(x => x.trim()).filter(Boolean);
}
if (isCheckbox) return !!raw;
return String(raw ?? "");
}
function getNestedValue(obj, key) {
if (!obj || !key) return undefined;
// 支持嵌套键,如 "debug_captures.auto_cleanup"
if (key.includes(".")) {
const parts = key.split(".");
let current = obj;
for (const part of parts) {
if (current && typeof current === "object" && part in current) {
current = current[part];
} else {
return undefined;
}
}
return current;
}
return obj[key];
}
function setNestedValue(obj, key, value) {
if (!obj || !key) return;
// 支持嵌套键,如 "debug_captures.auto_cleanup"
if (key.includes(".")) {
const parts = key.split(".");
let current = obj;
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
if (!(part in current) || typeof current[part] !== "object" || current[part] === null) {
current[part] = {};
}
current = current[part];
}
current[parts[parts.length - 1]] = value;
} else {
obj[key] = value;
}
}
function applyConfigToUI(cfg) {
for (const el of getConfigBoundElements()) {
const key = el.dataset.key;
const type = el.dataset.type || "str";
const val = cfg ? getNestedValue(cfg, key) : undefined;
// undefined/null 都视为"未配置":保留页面默认值
const hasVal = !(typeof val === "undefined" || val === null);
const useVal = hasVal ? val : (Object.prototype.hasOwnProperty.call(DEFAULTS, key) ? DEFAULTS[key] : undefined);
if (typeof useVal === "undefined") continue;
if (el.type === "checkbox") {
el.checked = !!useVal;
continue;
}
if (type === "list_lines") {
el.value = (Array.isArray(useVal) ? useVal : []).join("\n");
continue;
}
el.value = String(useVal);
}
}
function collectConfigFromUI() {
const out = {};
for (const el of getConfigBoundElements()) {
const key = el.dataset.key;
const type = el.dataset.type || "str";
if (!key) continue;
const value = el.type === "checkbox"
? coerceValue(type, el.checked, true)
: coerceValue(type, el.value, false);
// 支持嵌套键,如 "debug_captures.auto_cleanup"
setNestedValue(out, key, value);
}
return out;
}
async function loadConfig() {
const cfg = await apiGet("/api/config");
applyConfigToUI(cfg);
appendLog(["[WEB] 配置已加载"]);
}
async function saveConfig() {
const cfgUpdate = collectConfigFromUI();
await apiPost("/api/config", cfgUpdate);
appendLog(["[WEB] 配置已保存到 config.json"]);
}
async function startRun() {
try {
const deviceId = $("device").value || "";
const yPianyi = parseInt($("y_pianyi").value || "0", 10);
const waitMinutes = parseInt($("wait_minutes").value || "5", 10);
const needswitch = $("needswitch").checked;
const cfgPart = collectConfigFromUI();
appendLog([`[WEB] 正在启动...`]);
const result = await apiPost("/api/start-run", {
device_id: deviceId,
y_pianyi: yPianyi,
wait_minutes: waitMinutes,
needswitch,
reset_after_swipes_enabled: cfgPart.reset_after_swipes_enabled,
min_prize_value_yuan: cfgPart.min_prize_value_yuan,
min_participants: cfgPart.min_participants,
max_participants: cfgPart.max_participants,
skip_if_countdown_lt_seconds: cfgPart.skip_if_countdown_lt_seconds,
reset_after_swipes: cfgPart.reset_after_swipes,
auto_join_fansclub: cfgPart.auto_join_fansclub,
fansclub_fail_action: cfgPart.fansclub_fail_action,
high_value_room_revisit_enabled: cfgPart.high_value_room_revisit_enabled,
high_value_room_revisit_only_current_run: cfgPart.high_value_room_revisit_only_current_run,
reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled,
reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay,
fudai_find_max_attempts: cfgPart.fudai_find_max_attempts,
reservation_preempt_min_value: cfgPart.reservation_preempt_min_value,
});
// 检查返回结果
if (result && result.ok === false) {
const errorMsg = result.error || "未知错误";
appendLog([`[WEB] 启动失败: ${errorMsg}`]);
if (errorMsg === "running") {
appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]);
}
return;
}
appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]);
// 启动时自动截图
if (deviceId) {
try {
appendLog(["[截图] 启动时自动截图..."]);
const screenshotResult = await apiPost("/api/screenshot", { device_id: deviceId });
if (screenshotResult.ok) {
appendLog(["[截图] 启动截图成功,已保存到 pic/screenshot.png"]);
// 刷新截图显示
pollShot();
} else {
appendLog([`[截图] 启动截图失败: ${screenshotResult.error || "未知错误"}`]);
}
} catch (e) {
appendLog([`[截图] 启动截图失败: ${e?.message || e}`]);
}
}
// 重置本地日志索引并清空显示区域,然后立即拉取最新日志
try {
logIdx = 0;
emptyResponseCount = 0; // 重置空响应计数
// 清空日志显示区域,准备显示新进程的日志
const logEl = $("log");
if (logEl) {
logEl.textContent = "";
}
await pollLogs();
} catch (e) {
console.error("[WEB] pollLogs error after start:", e);
}
} catch (e) {
console.error("[WEB] startRun error:", e);
const errorMsg = e.message || String(e);
appendLog([`[WEB] 启动失败: ${errorMsg}`]);
// 如果是"running"错误,显示友好提示
if (errorMsg === "running" || (e.status === 409)) {
appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]);
}
}
}
async function testYanghao() {
const deviceId = $("device").value || "";
const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10);
await apiPost("/api/test-yanghao", { device_id: deviceId, seconds });
appendLog([`[WEB] 已启动测试养号:device=${deviceId || '(auto)'} seconds=${seconds}`]);
}
async function testComment() {
const deviceId = $("device").value || "";
const text = "";
await apiPost("/api/test-comment", { device_id: deviceId, text });
appendLog([`[WEB] 已启动测试评论:device=${deviceId || '(auto)'}${text ? ' text=自定义' : ''}`]);
}
async function stopRun() {
await apiPost("/api/stop", {});
appendLog(["[WEB] 已发送停止"]);
// 重置并拉取日志,确保能看到后端的停止确认输出
try {
logIdx = 0;
emptyResponseCount = 0; // 重置空响应计数
await pollLogs();
} catch (e) {
// ignore
}
}
async function pollLogs() {
try {
const data = await apiGet(`/api/logs?since=${logIdx}`);
// 检查返回数据是否有效
if (!data || typeof data !== 'object') {
console.error('[WEB_DBG] pollLogs: invalid response data', data);
logErrorCount++;
return;
}
// 重置错误计数(API调用成功)
logErrorCount = 0;
// 记录API调用成功的时间(即使没有新日志,也说明连接正常)
const apiCallTime = Date.now();
// 获取返回的索引
const nextIdx = typeof data.next === 'number' ? data.next : 0;
// 如果返回的索引小于当前索引,说明日志被截断了,需要重置
// 或者如果返回了所有日志(lines数量很大),也可能是重置了索引
if (nextIdx < logIdx && logIdx > 0) {
console.warn('[WEB_DBG] pollLogs: 检测到日志截断,重置索引', { oldIdx: logIdx, newIdx: nextIdx });
logIdx = 0;
emptyResponseCount = 0; // 重置空响应计数
// 清空日志显示区域,准备重新显示
const log = document.getElementById('log');
if (log) {
log.textContent = '';
}
// 重新请求一次以获取所有日志
const retryData = await apiGet(`/api/logs?since=0`);
if (retryData && typeof retryData === 'object' && Array.isArray(retryData.lines)) {
logIdx = typeof retryData.next === 'number' ? retryData.next : 0;
if (retryData.lines.length > 0) {
appendLog(retryData.lines);
}
}
return;
}
// 更新日志索引
logIdx = nextIdx;
// API调用成功,更新最后更新时间(不管是否有新日志)
lastLogUpdateTime = apiCallTime;
// 追加日志
if (Array.isArray(data.lines) && data.lines.length > 0) {
appendLog(data.lines);
emptyResponseCount = 0; // 重置空响应计数
} else {
// 没有新日志是正常的(比如脚本没有运行),不需要重置索引
// 只有在检测到索引不同步时才重置(已在前面处理)
emptyResponseCount++;
// 移除自动重置逻辑,避免在没有新日志时频繁清空日志显示
}
// 容错:确保索引不为负数
if (logIdx < 0) {
console.warn('[WEB_DBG] pollLogs: logIdx为负数,重置为0');
logIdx = 0;
emptyResponseCount = 0;
}
} catch (e) {
logErrorCount++;
console.error('[WEB_DBG] pollLogs error:', e);
// 如果连续10次出错,重置索引
if (logErrorCount >= 10) {
console.warn('[WEB_DBG] pollLogs: 连续10次错误,重置索引');
logIdx = 0;
logErrorCount = 0;
emptyResponseCount = 0; // 重置空响应计数
}
// 错误时不追加日志到界面,避免刷屏,只在控制台输出
// 如果是网络错误或超时,不重置索引;如果是其他错误,考虑重置
if (e.message && !e.message.includes('NetworkError') && !e.message.includes('Failed to fetch') && !e.message.includes('timeout')) {
console.error('[WEB_DBG] pollLogs failed:', e.message);
// 非网络错误,可能是数据格式错误,重置索引尝试恢复
if (e.message.includes('JSON') || e.message.includes('parse')) {
console.warn('[WEB_DBG] pollLogs: 数据解析错误,重置索引');
logIdx = 0;
emptyResponseCount = 0; // 重置空响应计数
}
}
}
}
async function pollReservations() {
try {
const data = await apiGet(`/api/reservations?t=${Date.now()}`);
const container = $("reservationsContent");
if (!container) return;
// 保留上次滚动位置
const prevList = container.querySelector('.reservationsList');
const prevScroll = prevList ? prevList.scrollTop : 0;
clearEl(container);
const reservations = data.reservations || [];
const room_pos = data.room_pos || 0;
const updated_ts = data.updated_ts || 0;
const current_room_title = data.current_room_title || "";
const current_room_title_raw = data.current_room_title_raw || "";
const reason = data.reason || "";
// 显示基本信息
const info = document.createElement("div");
info.className = "reservationsInfo";
info.innerHTML = `
<div><strong>当前位置:</strong>${room_pos}</div>
<div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>
<div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>
<div><strong>预约数量:</strong>${reservations.length}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
if (reservations.length === 0) {
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = "暂无预约信息";
container.appendChild(hint);
return;
}
// 显示预约列表
const list = document.createElement("div");
list.className = "reservationsList";
reservations.forEach((item, idx) => {
const card = document.createElement("div");
card.className = "reservationItem";
const now = Date.now() / 1000;
const future_ts = item.future_ts || 0;
const remain = Math.max(0, Math.floor(future_ts - now));
const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : "已到开奖时间";
card.innerHTML = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">${item.prize_value_yuan || 0}元</span>
</div>
<div class="reservationBody">
<div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>
<div><strong>开奖时间:</strong>${item.future_str || '-'}</div>
<div><strong>剩余时间:</strong>${remainStr}</div>
<div><strong>发现位置:</strong>${item.pos_seen || 0}</div>
<div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>
<div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>
</div>
`;
list.appendChild(card);
});
container.appendChild(list);
// 恢复滚动位置(若有)
try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }
} catch (e) {
console.error("poll reservations failed:", e);
const container = $("reservationsContent");
if (!container) return;
clearEl(container);
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = `预约信息获取失败:${e?.message || e}`;
container.appendChild(hint);
}
}
async function pollHighValueRooms() {
try {
const data = await apiGet(`/api/high-value-rooms?t=${Date.now()}`);
const container = $("highValueRoomsContent");
if (!container) return;
// 保留上次滚动位置
const prevList = container.querySelector('.reservationsList');
const prevScroll = prevList ? prevList.scrollTop : 0;
clearEl(container);
const rooms = Array.isArray(data.rooms) ? data.rooms : [];
const updated_ts = Number(data.updated_ts) || 0;
const reason = String(data.reason || "");
const total = Number(data.total) || rooms.length;
const info = document.createElement("div");
info.className = "reservationsInfo";
info.innerHTML = `
<div><strong>记录数量:</strong>${total}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
if (rooms.length === 0) {
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = "暂无记录";
container.appendChild(hint);
return;
}
const list = document.createElement("div");
list.className = "reservationsList";
rooms.forEach((item, idx) => {
const card = document.createElement("div");
card.className = "reservationItem";
const roomTitle = String(item.room_title || "-");
const roomRaw = String(item.room_title_raw_last || "-");
const posSeen = (typeof item.pos_seen === "number") ? item.pos_seen : ((item.pos_seen === null || typeof item.pos_seen === "undefined") ? "-" : String(item.pos_seen));
const firstSeen = Number(item.first_seen_ts) || 0;
const lastSeen = Number(item.last_seen_ts) || 0;
const seenCount = Number(item.seen_count) || 0;
const maxVal = (item.max_prize_value_yuan === null || typeof item.max_prize_value_yuan === "undefined") ? "-" : String(item.max_prize_value_yuan);
const lastVal = (item.last_prize_value_yuan === null || typeof item.last_prize_value_yuan === "undefined") ? "-" : String(item.last_prize_value_yuan);
card.innerHTML = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">max ${escapeHtml(maxVal)}元</span>
</div>
<div class="reservationBody">
<div><strong>直播间(清洗后):</strong>${escapeHtml(roomTitle)}</div>
<div><strong>直播间原文:</strong>${escapeHtml(roomRaw)}</div>
<div><strong>最近位置:</strong>${escapeHtml(posSeen)}</div>
<div><strong>首次记录:</strong>${escapeHtml(fmtTime(firstSeen))}</div>
<div><strong>最近记录:</strong>${escapeHtml(fmtTime(lastSeen))}</div>
<div><strong>记录次数:</strong>${escapeHtml(seenCount)}</div>
<div><strong>最近价值:</strong>${escapeHtml(lastVal)}元</div>
</div>
`;
// 让每条记录的 header 可点击以折叠/展开本条详情
list.appendChild(card);
try {
const header = card.querySelector('.reservationHeader');
const body = card.querySelector('.reservationBody');
if (header && body) {
header.style.cursor = 'pointer';
header.addEventListener('click', () => {
if (body.style.display === 'none') {
body.style.display = '';
} else {
body.style.display = 'none';
}
});
}
} catch (e) {
// ignore
}
});
container.appendChild(list);
// 恢复滚动位置(若有)
try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }
// 全局折叠/展开按钮绑定:折叠/展开整个列表(隐藏序号/条目),而不是仅隐藏每条的详情
try {
const btnExpand = $('hv_expand_all');
const btnCollapse = $('hv_collapse_all');
if (btnExpand) btnExpand.addEventListener('click', () => {
const listEl = container.querySelector('.reservationsList');
if (listEl) listEl.style.display = '';
});
if (btnCollapse) btnCollapse.addEventListener('click', () => {
const listEl = container.querySelector('.reservationsList');
if (listEl) listEl.style.display = 'none';
});
} catch (e) {
// ignore
}
} catch (e) {
console.error("poll high value rooms failed:", e);
const container = $("highValueRoomsContent");
if (!container) return;
clearEl(container);
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = `直播间记录获取失败:${e?.message || e}`;
container.appendChild(hint);
}
}
async function pollStats() {
try {
const s = await apiGet(`/api/stats?t=${Date.now()}`);
const running = s.running ? "运行中" : "未运行";
setTextIfExists("statRunning", running);
setTextIfExists("statPid", s.pid ?? "-");
setTextIfExists("statUptime", fmtDuration(s.uptime_seconds));
setTextIfExists("statLogLen", s.log_len ?? "-");
if ($("statLogCap")) {
const cap = s.log_capacity ?? 2000;
const len = s.log_len ?? 0;
$("statLogCap").textContent = `缓存上限:${cap}(已用 ${len}/${cap})`;
}
setTextIfExists("statLastLog", fmtTime(s.last_log_ts));
setTextIfExists("statExitCode", (s.exit_code === null || typeof s.exit_code === "undefined") ? "-" : s.exit_code);
// 显示traceId和MDC信息
const traceId = s.trace_id || "-";
setTextIfExists("statTraceId", traceId);
const mdcContext = s.mdc_context || {};
if ($("statTraceIdHint")) {
const mdcKeys = Object.keys(mdcContext);
if (mdcKeys.length > 0) {
const mdcStr = mdcKeys.map(k => `${k}=${mdcContext[k]}`).join(", ");
$("statTraceIdHint").textContent = `MDC: ${mdcStr}`;
} else {
$("statTraceIdHint").textContent = "";
}
}
const c = s.counters || {};
const getC = (k) => Number.isFinite(Number(c[k])) ? Number(c[k]) : 0;
setTextIfExists("statFudaiSeen", getC("fudai_seen"));
setTextIfExists("statFudaiOpen", getC("fudai_open_detail"));
setTextIfExists("statFudaiAttendOk", getC("fudai_attend_ok"));
setTextIfExists("statFudaiAttendFail", getC("fudai_attend_fail"));
setTextIfExists("statFudaiNoWin", getC("fudai_result_no_win"));
setTextIfExists("statFudaiWin", getC("fudai_result_win"));
setTextIfExists("statSkipValueLow", getC("fudai_skip_value_low"));
const pLow = getC("fudai_skip_participants_low");
const pHigh = getC("fudai_skip_participants_high");
setTextIfExists("statSkipParticipants", pLow + pHigh);
if ($("statSkipParticipantsHint")) {
$("statSkipParticipantsHint").textContent = `低:${pLow} / 高:${pHigh}`;
}
setTextIfExists("statSkipContent", getC("fudai_skip_content"));
const cdShort = getC("fudai_skip_countdown_short");
const cdLong = getC("fudai_skip_countdown_long");
setTextIfExists("statSkipCountdown", cdShort + cdLong);
if ($("statSkipCountdownHint")) {
$("statSkipCountdownHint").textContent = `短:${cdShort} / 长:${cdLong}`;
}
const fcReq = getC("fansclub_required");
const fcManual = getC("fansclub_manual_needed");
const fcUn = getC("fansclub_unresolved");
setTextIfExists("statFansclub", fcReq);
if ($("statFansclubHint")) {
$("statFansclubHint").textContent = `需手动:${fcManual} / 未解决:${fcUn}`;
}
const sw = getC("switch_room");
setTextIfExists("statSwitchRoom", sw);
if ($("statSwitchRoomHint")) {
const parts = [
`无福袋:${getC("switch_room_no_fudai")}`,
`人数:${getC("switch_room_participants")}`,
`价值:${getC("switch_room_value")}`,
`内容:${getC("switch_room_content")}`,
`倒计时:${getC("switch_room_countdown")}`,
`参与失败:${getC("switch_room_attend_fail")}`,
];
$("statSwitchRoomHint").textContent = parts.join(" / ");
}
const last = s.fudai_last || {};
setTextIfExists("statLastContent", last.content || "-");
setTextIfExists("statLastCountdown", last.countdown || "-");
const ppl = (typeof last.participants === "number") ? String(last.participants) : "-";
const cop = (typeof last.copies === "number") ? String(last.copies) : "-";
setTextIfExists("statLastPeople", `${ppl} / ${cop}`);
const val = (typeof last.prize_value_yuan === "number") ? String(last.prize_value_yuan) : "-";
setTextIfExists("statLastValue", val);
if ($("statLastUpdated")) {
$("statLastUpdated").textContent = last.updated_ts ? `更新时间:${fmtTime(last.updated_ts)}` : "更新时间:-";
}
// ====== 详细聚合渲染(趋势/分布/Top) ======
const agg = s.agg || {};
const reasonName = {
value_low: "价值过低",
participants_low: "人数过少",
participants_high: "人数过多",
content: "内容不匹配",
countdown_short: "倒计时太短",
countdown_long: "倒计时太长",
unknown: "未知",
};
const switchName = {
no_fudai: "无福袋",
participants: "人数不符合",
value: "价值不符合",
content: "内容不符合",
countdown: "倒计时不符合",
attend_fail: "参与失败",
unknown: "未知",
};
renderTimeline("chartTimeline", agg.timeline);
renderBars("chartSkipReason", agg.skip_reason || {}, reasonName);
renderBars("chartSwitchReason", agg.switch_reason || {}, switchName);
renderBars("chartValueBuckets", agg.value_buckets || {});
renderBars("chartParticipantsBuckets", agg.participants_buckets || {});
renderBars("chartCountdownBuckets", agg.countdown_buckets || {});
renderTopContent("tableTopContent", agg.content_top || []);
// ====== 中奖内容列表 ======
renderWinsTable("tableWins", s.wins || []);
} catch (e) {
// 统计失败不打断其他功能
}
}
function startPolling() {
if (pollTimer) clearInterval(pollTimer);
// 性能优化:日志轮询间隔从 700ms 调整为 800ms,减少服务器压力同时保持实时性
pollTimer = setInterval(pollLogs, 800);
}
function startStatsPolling() {
if (statsTimer) clearInterval(statsTimer);
statsTimer = setInterval(() => {
pollStats();
pollReservations();
pollHighValueRooms();
}, 1200);
}
window.addEventListener("DOMContentLoaded", async () => {
initTabs();
$("btnRefresh").addEventListener("click", refreshDevices);
$("btnLoad").addEventListener("click", async () => { await loadConfig(); });
$("btnSave").addEventListener("click", async () => { await saveConfig(); });
$("btnStart").addEventListener("click", async () => { await startRun(); });
$("btnStop").addEventListener("click", async () => { await stopRun(); });
// 截图按钮
$("btnScreenshot").addEventListener("click", async () => {
const deviceId = $("device").value || "";
if (!deviceId) {
appendLog(["[截图] 请先选择设备"]);
return;
}
try {
appendLog(["[截图] 正在截图..."]);
const result = await apiPost("/api/screenshot", { device_id: deviceId });
if (result.ok) {
appendLog(["[截图] 截图成功,已保存到 pic/screenshot.png"]);
// 刷新截图显示
pollShot();
} else {
appendLog([`[截图] 截图失败: ${result.error || "未知错误"}`]);
}
} catch (e) {
appendLog([`[截图] 截图失败: ${e?.message || e}`]);
}
});
// 截图按钮
$("btnScreenshot").addEventListener("click", async () => {
const deviceId = $("device").value || "";
if (!deviceId) {
appendLog(["[截图] 请先选择设备"]);
return;
}
try {
appendLog(["[截图] 正在截图..."]);
const result = await apiPost("/api/screenshot", { device_id: deviceId });
if (result.ok) {
appendLog(["[截图] 截图成功,已保存到 pic/screenshot.png"]);
// 刷新截图显示
pollShot();
} else {
appendLog([`[截图] 截图失败: ${result.error || "未知错误"}`]);
}
} catch (e) {
appendLog([`[截图] 截图失败: ${e?.message || e}`]);
}
});
await refreshDevices();
await loadConfig();
startPolling();
startStatsPolling();
startShotPolling();
pollLogs();
pollStats();
pollShot();
pollReservations();
pollHighValueRooms();
});