diff --git a/webui/app.js b/webui/app.js index 9eca3bc..c698720 100644 --- a/webui/app.js +++ b/webui/app.js @@ -1,3 +1,90 @@ +const UI_LIMITS = Object.freeze({ + runLogMaxLines: 50000, + runLogMaxChars: 200000, + actionsLogMaxLines: 5000, + scrollBottomThresholdPx: 5, + screenshotPollMs: 1500, + logPollMs: 800, + statsPollMs: 1200, +}); + +const UI_CLASS = Object.freeze({ + busy: "isBusy", + clickable: "isClickable", + collapsed: "isCollapsed", + listCollapsed: "isListCollapsed", + reservationHeader: "reservationHeader", + reservationBody: "reservationBody", + reservationsList: "reservationsList", + shotEmpty: "isShotEmpty", + statusRunning: "statusRunning", + statusIdle: "statusIdle", + statusError: "statusError", +}); + +const RUN_TONE = Object.freeze({ + running: "running", + idle: "idle", + error: "error", +}); + +const UI_COPY = Object.freeze({ + empty: "-", + device: { + autoOption: "(auto)", + autoLabel: "(auto)", + noOnline: "无在线设备", + adbReady: "ADB 已就绪", + adbMissing: "ADB 未找到", + autoOnline: (count) => `${count} 台在线 / 自动选择`, + }, + runOverview: { + starting: "启动中", + startingMeta: "正在向后端发送启动请求", + failed: "启动失败", + stopping: "停止中", + stoppingMeta: "已请求后端停止运行", + meta: (pid, uptimeSeconds) => `PID ${pid ?? "-"} / 运行时长 ${fmtDuration(uptimeSeconds)}`, + }, + overview: { + logLines: (count) => `${count ?? 0} 行`, + lastLog: (ts) => `最后日志 ${fmtTime(ts)}`, + fudaiState: (opened, attended) => `${opened} / ${attended}`, + fudaiMeta: (seen, wins) => `识别 ${seen} / 中奖 ${wins}`, + }, +}); + +const TIMELINE_SERIES_KEYS = Object.freeze([ + "fudai_open_detail", + "fudai_attend_ok", + "fudai_attend_fail", + "fudai_result_win", + "fudai_result_no_win", + "fudai_skip", + "switch_room", +]); + +const TIMELINE_LAYOUT = Object.freeze({ + width: 900, + height: 220, + paddingLeft: 36, + paddingRight: 14, + paddingTop: 10, + paddingBottom: 26, +}); + +const TIMELINE_STROKES = Object.freeze({ + 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" }, +}); + +const BUSY_DISABLED_BUTTONS = new Set(["btnStart", "btnSave"]); + let logIdx = 0; let pollTimer = null; let statsTimer = null; @@ -8,7 +95,7 @@ let emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住 // 双日志缓冲与过滤 let runLogBuffer = []; let runLogFilter = ""; -const runLogMaxLines = 50000; +const runLogMaxLines = UI_LIMITS.runLogMaxLines; let runLogMode = 'filter'; // 'filter' or 'search' let runSearchResultsBuffer = []; @@ -16,7 +103,8 @@ let runSearchActive = false; let actionsLogBuffer = []; let actionsLogFilter = ""; -const actionsLogMaxLines = 5000; +const actionsLogMaxLines = UI_LIMITS.actionsLogMaxLines; +let deviceOverviewState = { devices: [], adb: "" }; const DEFAULTS = { // 筛选 @@ -109,6 +197,7 @@ const DEFAULTS = { "logging.beautify_output": true, "logging.color_output": true, "logging.show_timestamps": true, + "logging.use_dated_logs": true, "logging.enable_monitor": true, "logging.compress_logs": true, "logging.keep_days": 30, @@ -124,6 +213,10 @@ const DEFAULTS = { "logging.performance_tracking.enabled": true, "logging.performance_tracking.track_function_calls": true, "gui.theme": "litera", + "gui.realtime_status.refresh_interval_ms": 1000, + "gui.realtime_status.tail_items": 50, + log_unified_enabled: true, + log_unified_path: "logs/unified.log", }; function $(id) { return document.getElementById(id); } @@ -144,6 +237,7 @@ function initTabs() { panel.toggleAttribute("hidden", !isActive); panel.classList.toggle("active", isActive); } + document.body.dataset.activePanel = target || ""; }; for (const btn of tabButtons) { @@ -161,7 +255,7 @@ function appendLog(lines) { // 记录更新前与底部的距离,用于在非底部时保持视图位置 const distanceFromBottom = log.scrollHeight - log.scrollTop - log.clientHeight; // 是否严格位于底部(仅在几像素内视为底部),避免每次刷新都跳到底部 - const wasAtBottom = distanceFromBottom < 5; + const wasAtBottom = distanceFromBottom < UI_LIMITS.scrollBottomThresholdPx; // 性能优化:批量追加文本,减少重排次数 const newText = lines.join("\n") + "\n"; @@ -185,7 +279,7 @@ function appendLog(lines) { } // 性能优化:限制日志长度,避免内存溢出(保留最近较多字符以便桌面端查看) - const maxLength = 200000; + const maxLength = UI_LIMITS.runLogMaxChars; if (log.textContent.length > maxLength) { // 在截断文本时,保留用户原来的距离(除非用户确实在底部) log.textContent = log.textContent.slice(-maxLength); @@ -210,7 +304,7 @@ function renderRunLog() { const lines = runSearchResultsBuffer || []; const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); - if (prevScrollBottom < 5) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); return; } @@ -222,7 +316,7 @@ function renderRunLog() { const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); // 尽量保持原来滚动位置;若位于底部则滚到底部 - if (prevScrollBottom < 5) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); } function appendRunLogLines(lines) { @@ -275,12 +369,14 @@ function fmtDuration(seconds) { function pollShot() { const img = $("liveShot"); if (!img) return; + const preview = img.closest(".preview"); // 性能优化:避免重复加载相同的图片(如果正在加载中) if (img.dataset.loading === "true") return; const url = `/pic/screenshot.png?t=${Date.now()}`; img.dataset.loading = "true"; + if (preview) preview.classList.remove(UI_CLASS.shotEmpty); img.src = url; const status = $("liveShotStatus"); @@ -293,18 +389,27 @@ function startShotPolling() { const img = $("liveShot"); const status = $("liveShotStatus"); if (img) { + const preview = img.closest(".preview"); + const syncShotEmpty = () => { + if (!preview) return; + preview.classList.toggle(UI_CLASS.shotEmpty, img.complete && img.naturalWidth === 0); + }; + syncShotEmpty(); img.addEventListener("load", () => { img.dataset.loading = "false"; + if (preview) preview.classList.remove(UI_CLASS.shotEmpty); if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`; }); img.addEventListener("error", () => { img.dataset.loading = "false"; + if (preview) preview.classList.add(UI_CLASS.shotEmpty); if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)"; }); + setTimeout(syncShotEmpty, 0); } // 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力 - shotTimer = setInterval(pollShot, 1500); + shotTimer = setInterval(pollShot, UI_LIMITS.screenshotPollMs); } function setTextIfExists(id, text) { @@ -313,6 +418,36 @@ function setTextIfExists(id, text) { el.textContent = String(text ?? "-"); } +function setButtonBusy(id, busy) { + const btn = $(id); + if (!btn) return; + btn.classList.toggle(UI_CLASS.busy, !!busy); + btn.toggleAttribute("aria-busy", !!busy); + if (BUSY_DISABLED_BUTTONS.has(id)) btn.disabled = !!busy; +} + +function setRunOverview(state, meta, tone) { + setTextIfExists("topRunState", state || UI_COPY.empty); + setTextIfExists("topRunMeta", meta || UI_COPY.empty); + const dot = $("topRunDot"); + if (!dot) return; + dot.classList.remove(UI_CLASS.statusRunning, UI_CLASS.statusIdle, UI_CLASS.statusError); + dot.classList.add(tone === RUN_TONE.running ? UI_CLASS.statusRunning : tone === RUN_TONE.error ? UI_CLASS.statusError : UI_CLASS.statusIdle); +} + +function updateDeviceOverview() { + const devices = Array.isArray(deviceOverviewState.devices) ? deviceOverviewState.devices : []; + const selected = selectedDeviceId(); + if (selected) { + setTextIfExists("topDeviceState", selected); + } else if (devices.length > 0) { + setTextIfExists("topDeviceState", UI_COPY.device.autoOnline(devices.length)); + } else { + setTextIfExists("topDeviceState", UI_COPY.device.noOnline); + } + setTextIfExists("topAdbState", deviceOverviewState.adb ? UI_COPY.device.adbReady : UI_COPY.device.adbMissing); +} + function clearEl(el) { while (el && el.firstChild) el.removeChild(el.firstChild); } @@ -452,18 +587,8 @@ function renderTimeline(containerId, timeline) { 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) { + for (const k of TIMELINE_SERIES_KEYS) { const arr = Array.isArray(series[k]) ? series[k] : []; for (const v of arr) maxY = Math.max(maxY, Number(v) || 0); } @@ -475,18 +600,18 @@ function renderTimeline(containerId, timeline) { return; } - const W = 900; - const H = 220; - const padL = 36; - const padR = 14; - const padT = 10; - const padB = 26; + const W = TIMELINE_LAYOUT.width; + const H = TIMELINE_LAYOUT.height; + const padL = TIMELINE_LAYOUT.paddingLeft; + const padR = TIMELINE_LAYOUT.paddingRight; + const padT = TIMELINE_LAYOUT.paddingTop; + const padB = TIMELINE_LAYOUT.paddingBottom; 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"; + svg.classList.add("timelineSvg"); const axis = document.createElementNS("http://www.w3.org/2000/svg", "path"); axis.setAttribute("d", `M ${padL} ${H - padB} L ${W - padR} ${H - padB}`); @@ -529,17 +654,7 @@ function renderTimeline(containerId, timeline) { 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) { + for (const k of TIMELINE_SERIES_KEYS) { const arr = Array.isArray(series[k]) ? series[k] : []; if (arr.length === 0) continue; let d = ""; @@ -551,9 +666,9 @@ function renderTimeline(containerId, timeline) { 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", TIMELINE_STROKES[k]?.stroke || "var(--primary)"); p.setAttribute("stroke-width", "2"); - if (strokes[k]?.dash) p.setAttribute("stroke-dasharray", strokes[k].dash); + if (TIMELINE_STROKES[k]?.dash) p.setAttribute("stroke-dasharray", TIMELINE_STROKES[k].dash); p.setAttribute("stroke-linecap", "round"); p.setAttribute("stroke-linejoin", "round"); svg.appendChild(p); @@ -598,7 +713,7 @@ async function refreshDevices() { const optAuto = document.createElement("option"); optAuto.value = ""; - optAuto.textContent = "(auto)"; + optAuto.textContent = UI_COPY.device.autoOption; sel.appendChild(optAuto); for (const d of devices) { @@ -609,6 +724,8 @@ async function refreshDevices() { } $("adbStatus").textContent = data.adb ? `adb: ${data.adb}` : "未找到 adb.exe(请安装 platform-tools)"; + deviceOverviewState = { devices, adb: data.adb || "" }; + updateDeviceOverview(); } function getConfigBoundElements() { @@ -717,9 +834,14 @@ async function loadConfig() { } async function saveConfig() { - const cfgUpdate = collectConfigFromUI(); - await apiPost("/api/config", cfgUpdate); - appendLog(["[WEB] 配置已保存到 config.json"]); + setButtonBusy("btnSave", true); + try { + const cfgUpdate = collectConfigFromUI(); + await apiPost("/api/config", cfgUpdate); + appendLog(["[WEB] 配置已保存到 config.json"]); + } finally { + setButtonBusy("btnSave", false); + } } function selectedDeviceId() { @@ -782,6 +904,8 @@ async function wifiDisconnect() { } async function startRun() { + setButtonBusy("btnStart", true); + setRunOverview(UI_COPY.runOverview.starting, UI_COPY.runOverview.startingMeta, RUN_TONE.running); try { const deviceId = $("device").value || ""; const yPianyi = parseInt($("y_pianyi").value || "0", 10); @@ -836,7 +960,7 @@ async function startRun() { return; } - appendLog([`[WEB] 已开始运行:device=${deviceId || '(auto)'}`]); + appendLog([`[WEB] 已开始运行:device=${deviceId || UI_COPY.device.autoLabel}`]); // 启动时自动截图 if (deviceId) { @@ -872,10 +996,13 @@ async function startRun() { console.error("[WEB] startRun error:", e); const errorMsg = e.message || String(e); appendLog([`[WEB] 启动失败: ${errorMsg}`]); + setRunOverview(UI_COPY.runOverview.failed, errorMsg, RUN_TONE.error); // 如果是"running"错误,显示友好提示 if (errorMsg === "running" || (e.status === 409)) { appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); } + } finally { + setButtonBusy("btnStart", false); } } @@ -883,17 +1010,18 @@ 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}`]); + appendLog([`[WEB] 已启动测试养号:device=${deviceId || UI_COPY.device.autoLabel} 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=自定义' : ''}`]); + appendLog([`[WEB] 已启动测试评论:device=${deviceId || UI_COPY.device.autoLabel}${text ? ' text=自定义' : ''}`]); } async function stopRun() { + setRunOverview(UI_COPY.runOverview.stopping, UI_COPY.runOverview.stoppingMeta, RUN_TONE.idle); await apiPost("/api/stop", {}); appendLog(["[WEB] 已发送停止"]); // 重置并拉取日志,确保能看到后端的停止确认输出 @@ -1142,16 +1270,12 @@ async function pollHighValueRooms() { // 让每条记录的 header 可点击以折叠/展开本条详情 list.appendChild(card); try { - const header = card.querySelector('.reservationHeader'); - const body = card.querySelector('.reservationBody'); + const header = card.querySelector(`.${UI_CLASS.reservationHeader}`); + const body = card.querySelector(`.${UI_CLASS.reservationBody}`); if (header && body) { - header.style.cursor = 'pointer'; + header.classList.add(UI_CLASS.clickable); header.addEventListener('click', () => { - if (body.style.display === 'none') { - body.style.display = ''; - } else { - body.style.display = 'none'; - } + body.classList.toggle(UI_CLASS.collapsed); }); } } catch (e) { @@ -1168,12 +1292,12 @@ async function pollHighValueRooms() { 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 = ''; + const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); + if (listEl) listEl.classList.remove(UI_CLASS.listCollapsed); }); if (btnCollapse) btnCollapse.addEventListener('click', () => { - const listEl = container.querySelector('.reservationsList'); - if (listEl) listEl.style.display = 'none'; + const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); + if (listEl) listEl.classList.add(UI_CLASS.listCollapsed); }); } catch (e) { // ignore @@ -1209,12 +1333,23 @@ async function pollStats() { const c = s.counters || {}; const getC = (k) => Number.isFinite(Number(c[k])) ? Number(c[k]) : 0; + setRunOverview( + running, + UI_COPY.runOverview.meta(s.pid, s.uptime_seconds), + s.running ? RUN_TONE.running : RUN_TONE.idle + ); + document.body.classList.toggle("is-running", !!s.running); + setTextIfExists("topLogState", UI_COPY.overview.logLines(s.log_len)); + setTextIfExists("topLogMeta", UI_COPY.overview.lastLog(s.last_log_ts)); + 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("topFudaiState", UI_COPY.overview.fudaiState(getC("fudai_open_detail"), getC("fudai_attend_ok"))); + setTextIfExists("topFudaiMeta", UI_COPY.overview.fudaiMeta(getC("fudai_seen"), getC("fudai_result_win"))); setTextIfExists("statSkipValueLow", getC("fudai_skip_value_low")); @@ -1307,7 +1442,7 @@ async function pollStats() { function startPolling() { if (pollTimer) clearInterval(pollTimer); // 性能优化:日志轮询间隔从 700ms 调整为 800ms,减少服务器压力同时保持实时性 - pollTimer = setInterval(pollLogs, 800); + pollTimer = setInterval(pollLogs, UI_LIMITS.logPollMs); } function startStatsPolling() { @@ -1316,7 +1451,7 @@ function startStatsPolling() { pollStats(); pollReservations(); pollHighValueRooms(); - }, 1200); + }, UI_LIMITS.statsPollMs); } window.addEventListener("DOMContentLoaded", async () => { @@ -1326,6 +1461,8 @@ window.addEventListener("DOMContentLoaded", async () => { $("btnSave").addEventListener("click", async () => { await saveConfig(); }); $("btnStart").addEventListener("click", async () => { await startRun(); }); $("btnStop").addEventListener("click", async () => { await stopRun(); }); + const deviceSelect = $("device"); + if (deviceSelect) deviceSelect.addEventListener("change", updateDeviceOverview); const btnForceStop = $("btnForceStop"); if (btnForceStop) btnForceStop.addEventListener("click", async () => { await forceStopRun(); }); const btnBackKey = $("btnBackKey"); diff --git a/webui/index.html b/webui/index.html index aabbc0b..190ea85 100644 --- a/webui/index.html +++ b/webui/index.html @@ -4,69 +4,102 @@