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)", opacity: 1.0, dash: "" }, fudai_attend_ok: { stroke: "var(--primary)", opacity: 0.7, dash: "" }, fudai_attend_fail: { stroke: "var(--primary)", opacity: 0.4, dash: "4 3" }, fudai_result_win: { stroke: "var(--primary)", opacity: 1.0, dash: "2 3" }, fudai_result_no_win:{ stroke: "var(--primary)", opacity: 0.4, dash: "" }, fudai_skip: { stroke: "var(--muted)", opacity: 0.7, dash: "4 3" }, switch_room: { stroke: "var(--muted)", opacity: 1.0, dash: "2 3" }, }); const BUSY_DISABLED_BUTTONS = new Set(["btnStart", "btnSave"]); let logIdx = 0; let pollTimer = null; let statsTimer = null; let shotTimer = null; let lastLogUpdateTime = 0; // 最后成功获取日志的时间 let logErrorCount = 0; // 连续错误计数 let emptyResponseCount = 0; // 连续空响应计数(用于检测索引卡住) // 双日志缓冲与过滤 let runLogBuffer = []; let runLogFilter = ""; const runLogMaxLines = UI_LIMITS.runLogMaxLines; let runLogMode = 'filter'; // 'filter' or 'search' let runSearchResultsBuffer = []; let runSearchActive = false; let actionsLogBuffer = []; let actionsLogFilter = ""; const actionsLogMaxLines = UI_LIMITS.actionsLogMaxLines; let deviceOverviewState = { devices: [], adb: "" }; 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_like_icon_x: 0, yanghao_like_icon_y: 0, yanghao_fav_icon_x: 0, yanghao_fav_icon_y: 0, yanghao_comment_btn_x: 0, yanghao_comment_btn_y: 0, 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: 300, 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, // 是否禁用福袋内容OCR识别(仅前端默认,实际值以 config.json 为准) fudai_disable_content_recognition: false, live_room_match_threshold: 0.8, reservation_back_swipe_delay: 0.6, // 定时禁抢福袋(默认 2-7 点) fudai_quiet_hours_enabled: true, fudai_quiet_start_hour: 2, fudai_quiet_end_hour: 7, // 桌面 GUI 对齐补充 infinite_loop_enabled: false, skip_if_countdown_gt_seconds: 900, reset_after_swipes_action: "swipe", enable_back_on_misses: true, enable_streaming_screenshot: true, swipe_duration_ms: 600, swipe_up_start_y: 1200, swipe_up_end_y: 600, switch_room_wait_after_stage_diag_seconds: 7.0, fansclub_click_delay: 0.6, fansclub_auto_join_wait_seconds: 5.0, fansclub_manual_wait_seconds: 3.0, high_value_fudai_poll_before_seconds: 10.0, high_value_room_revisit_min_interval_seconds: 300, high_value_room_revisit_max_per_run: 5, high_value_room_revisit_min_prize_value: 0, high_value_room_revisit_max_age_days: 30, reservation_back_verify_wait_seconds: 5.0, fudai_disable_task_recognition: false, fudai_exit_after_misses: 30, fudai_click_wait_seconds: 2.0, fudai_detail_template_threshold: 0.7, coupon_template_match_threshold: 0.75, attend_button_red_ratio_threshold: 0.25, fansclub_join_red_ratio_threshold: 0.25, shopping_redpacket_red_ratio_threshold: 0.15, yanghao_only: false, yanghao_icon_match_threshold: 0.72, "debug_captures.async_save": true, "debug_captures.log_on_complete": false, "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, "logging.max_total_size_gb": 10.0, "logging.compress_after_days": 7, "logging.debug_detail_level": "normal", "logging.error_detail_level": "full", "logging.action_log_format": "concise", "logging.log_format_mode": "simple", "logging.monitor_warning_mb": 500, "logging.monitor_critical_mb": 2000, "logging.stage_diag_verbose": true, "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); } function initTheme() { const root = document.documentElement; const btn = $("btnTheme"); const mql = window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null; const apply = (theme) => { root.setAttribute("data-theme", theme); if (btn) btn.setAttribute("aria-label", theme === "dark" ? "切换到浅色" : "切换到深色"); }; // Initial: respect inline-set attribute (set by head bootstrap), or fall back. const initial = root.getAttribute("data-theme") || (mql && mql.matches ? "dark" : "light"); apply(initial); if (btn) { btn.addEventListener("click", () => { const next = root.getAttribute("data-theme") === "dark" ? "light" : "dark"; try { localStorage.setItem("ui-theme", next); } catch (_) {} root.classList.add("isThemeSwitching"); apply(next); setTimeout(() => root.classList.remove("isThemeSwitching"), 260); }); } // Follow system changes only when user hasn't picked manually. if (mql && typeof mql.addEventListener === "function") { mql.addEventListener("change", (ev) => { let saved = null; try { saved = localStorage.getItem("ui-theme"); } catch (_) {} if (saved !== "dark" && saved !== "light") { apply(ev.matches ? "dark" : "light"); } }); } } function ensureToastContainer() { let c = document.getElementById("toastContainer"); if (!c) { c = document.createElement("div"); c.id = "toastContainer"; c.className = "toastContainer"; c.setAttribute("role", "status"); c.setAttribute("aria-live", "polite"); document.body.appendChild(c); } return c; } function toast(message, kind = "info", { duration = 3500 } = {}) { if (!message) return; const container = ensureToastContainer(); const t = document.createElement("div"); t.className = `toast toast-${kind}`; const icon = document.createElement("span"); icon.className = "toastIcon"; icon.setAttribute("aria-hidden", "true"); const ICONS = { success: '', error: '', warn: '', info: '', }; icon.innerHTML = ICONS[kind] || ICONS.info; const body = document.createElement("div"); body.className = "toastBody"; body.textContent = String(message); const close = document.createElement("button"); close.className = "toastClose"; close.type = "button"; close.setAttribute("aria-label", "关闭"); close.innerHTML = ''; t.append(icon, body, close); container.appendChild(t); let timer = setTimeout(remove, duration); function remove() { if (timer) { clearTimeout(timer); timer = null; } t.classList.add("isLeaving"); setTimeout(() => t.remove(), 220); } close.addEventListener("click", remove); t.addEventListener("mouseenter", () => { if (timer) { clearTimeout(timer); timer = null; } }); t.addEventListener("mouseleave", () => { if (!timer) timer = setTimeout(remove, 1500); }); return remove; } function initConfigSearch() { const input = $("configSearch"); const clear = $("configSearchClear"); const empty = $("configSearchEmpty"); if (!input) return; // Cache: rows = [.row], with their lower-case search text + parent panel const rows = Array.from(document.querySelectorAll(".panels .panel .row")); const rowMeta = rows.map((row) => { const textParts = []; row.querySelectorAll(".label, .check span, .hint, span").forEach((el) => { const t = (el.textContent || "").trim(); if (t) textParts.push(t); }); row.querySelectorAll("input[data-key], select[data-key], textarea[data-key]").forEach((el) => { if (el.dataset.key) textParts.push(el.dataset.key); }); return { row, panel: row.closest(".panel"), text: textParts.join(" ").toLowerCase() }; }); // Section titles: when filtering, hide sections that have no visible row after them const allSectionTitles = Array.from(document.querySelectorAll(".panels .panel .sectionTitle")); const apply = (q) => { const query = q.trim().toLowerCase(); if (clear) clear.toggleAttribute("hidden", !query); const countBadge = document.getElementById("configSearchCount"); if (!query) { // Restore all rowMeta.forEach(({ row }) => row.classList.remove("isSearchHidden")); allSectionTitles.forEach((s) => s.classList.remove("isSearchHidden")); document.querySelectorAll(".panel").forEach((p) => p.classList.remove("isSearchAllHidden")); if (empty) empty.hidden = true; if (countBadge) countBadge.hidden = true; // Re-apply normal tab visibility (panels may have been forced visible) const activeTab = document.querySelector(".tabBtn.active[data-target]"); if (activeTab) { const target = activeTab.dataset.target; document.querySelectorAll(".panel[data-panel]").forEach((p) => { const on = p.dataset.panel === target; p.toggleAttribute("hidden", !on); p.classList.toggle("active", on); }); } return; } // While searching: show ALL panels (panels normally hide via [hidden]), then filter rows. document.querySelectorAll(".panel[data-panel]").forEach((p) => { p.removeAttribute("hidden"); p.classList.add("active"); }); let totalVisible = 0; const visibleByPanel = new Map(); rowMeta.forEach(({ row, panel, text }) => { const match = text.includes(query); row.classList.toggle("isSearchHidden", !match); if (match) { totalVisible++; visibleByPanel.set(panel, (visibleByPanel.get(panel) || 0) + 1); } }); // Hide section titles that have no visible row in their following sibling group allSectionTitles.forEach((title) => { let next = title.nextElementSibling; let anyVisible = false; while (next && !next.matches(".sectionTitle")) { if (next.matches(".row") && !next.classList.contains("isSearchHidden")) { anyVisible = true; break; } next = next.nextElementSibling; } title.classList.toggle("isSearchHidden", !anyVisible); }); // Hide panels that have zero visible rows document.querySelectorAll(".panel[data-panel]").forEach((p) => { const visible = visibleByPanel.get(p) || 0; p.toggleAttribute("hidden", visible === 0); }); if (empty) empty.hidden = totalVisible > 0; if (countBadge) { countBadge.hidden = false; countBadge.textContent = `${totalVisible} 项`; } }; let debounceTimer; input.addEventListener("input", () => { clearTimeout(debounceTimer); debounceTimer = setTimeout(() => apply(input.value), 80); }); if (clear) { clear.addEventListener("click", () => { input.value = ""; apply(""); input.focus(); }); } // Platform-aware kbd hint label const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); const kbdMod = $("configSearchKbdMod"); if (kbdMod) kbdMod.textContent = isMac ? "⌘" : "Ctrl"; // ⌘K / Ctrl+K to focus, ESC to clear/blur document.addEventListener("keydown", (e) => { const mod = isMac ? e.metaKey : e.ctrlKey; if (mod && e.key.toLowerCase() === "k") { e.preventDefault(); input.focus(); input.select(); return; } if (e.key === "Escape" && document.activeElement === input) { if (input.value) { input.value = ""; apply(""); } else { input.blur(); } } }); } function initFooter() { // 版本号尝试从 /api/version 拿;拿不到就用 cache-bust 标识做 fallback const verEl = document.getElementById("appFooterVersion"); const buildEl = document.getElementById("appFooterBuild"); (async () => { try { const data = await apiGet("/api/version"); if (verEl && data?.version) verEl.textContent = "v" + data.version; if (buildEl && data?.build) buildEl.textContent = data.build; } catch (_) { const tag = (document.currentScript?.src || document.querySelector('script[src*="app.js"]')?.src || "") .split("v=")[1] || ""; if (verEl) verEl.textContent = tag ? tag.split("-").pop() : "—"; if (buildEl) buildEl.textContent = "本地"; } })(); // FPS 计数(每秒更新一次) const fpsEl = document.getElementById("hudFps"); if (fpsEl && typeof requestAnimationFrame === "function") { let frames = 0, last = performance.now(); const setFps = (n) => { const em = fpsEl.querySelector("em"); if (em) em.textContent = String(n); }; const tick = (now) => { frames++; if (now - last >= 1000) { setFps(Math.round((frames * 1000) / (now - last))); frames = 0; last = now; } requestAnimationFrame(tick); }; requestAnimationFrame(tick); } // PING:每 5s 测一次 /api/version 响应时间 const pingEl = document.getElementById("hudPing"); if (pingEl) { const setPing = (ms) => { const em = pingEl.querySelector("em"); if (em) em.textContent = ms === null ? "—" : String(ms); }; const ping = async () => { const t0 = performance.now(); try { await fetch("/api/version", { cache: "no-store" }); setPing(Math.max(1, Math.round(performance.now() - t0))); } catch (_) { setPing(null); } }; ping(); setInterval(ping, 5000); } } function attachCopyButtons() { // 给指定 statValue 元素绑定一键复制(hover 显示按钮,点击复制文本) const ids = ["statPid", "statTraceId"]; for (const id of ids) { const el = document.getElementById(id); if (!el || el.dataset.copyBound === "1") continue; el.dataset.copyBound = "1"; el.classList.add("hasCopy"); const btn = document.createElement("button"); btn.type = "button"; btn.className = "copyBtn"; btn.setAttribute("aria-label", "复制"); btn.setAttribute("data-tooltip", "复制"); btn.setAttribute("data-tooltip-pos", "bottom"); btn.innerHTML = ''; btn.addEventListener("click", async (e) => { e.stopPropagation(); const text = (el.textContent || "").trim(); if (!text || text === "-") { toast("暂无可复制内容", "warn", { duration: 1800 }); return; } try { await navigator.clipboard.writeText(text); toast("已复制:" + (text.length > 24 ? text.slice(0, 24) + "…" : text), "success", { duration: 1800 }); } catch (err) { // fallback for non-secure context const ta = document.createElement("textarea"); ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); try { document.execCommand("copy"); toast("已复制", "success", { duration: 1800 }); } catch (_) { toast("复制失败", "error", { duration: 2400 }); } document.body.removeChild(ta); } }); el.appendChild(btn); } } function initKeyboardShortcuts() { const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); document.addEventListener("keydown", (e) => { const mod = isMac ? e.metaKey : e.ctrlKey; if (!mod) return; const key = e.key.toLowerCase(); // ⌘S / Ctrl+S → 保存配置 if (key === "s") { e.preventDefault(); const btn = document.getElementById("btnSave"); if (btn && !btn.disabled) btn.click(); return; } // ⌘Enter / Ctrl+Enter → 启动运行 if (key === "enter") { e.preventDefault(); const btn = document.getElementById("btnStart"); if (btn && !btn.disabled) btn.click(); return; } }); } function initHeaderScroll() { const header = document.querySelector(".header"); const scrollTop = document.getElementById("btnScrollTop"); const onScroll = () => { if (header) header.classList.toggle("isScrolled", window.scrollY > 8); if (scrollTop) scrollTop.toggleAttribute("hidden", window.scrollY < 240); }; window.addEventListener("scroll", onScroll, { passive: true }); if (scrollTop) { scrollTop.addEventListener("click", () => { window.scrollTo({ top: 0, behavior: "smooth" }); }); } onScroll(); } function initShotFullscreen() { const btn = document.getElementById("btnShotFullscreen"); const img = document.getElementById("liveShot"); if (!btn || !img) return; btn.addEventListener("click", () => { const target = img.closest(".preview") || img; if (document.fullscreenElement) { document.exitFullscreen?.(); } else if (target.requestFullscreen) { target.requestFullscreen().catch(() => { // fallback:在新标签打开 window.open(img.src, "_blank", "noopener"); }); } else { window.open(img.src, "_blank", "noopener"); } }); } function applyKbdHints() { // 给 [data-kbd-mod="1"] 的按钮自动注入平台对应的修饰键前缀 const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); const prefix = isMac ? "⌘ " : "Ctrl "; document.querySelectorAll('[data-kbd-mod="1"]').forEach((el) => { el.setAttribute("data-kbd-prefix", prefix); }); } function initStickySectionShadow() { // 当 .sectionTitle 真正贴住 sticky top 时加 .isStuck 类 const titles = Array.from(document.querySelectorAll(".sectionTitle")) .filter((el) => !el.matches(".cardTitle, summary, summary *")); if (!titles.length || !("IntersectionObserver" in window)) return; const io = new IntersectionObserver( (entries) => { for (const e of entries) { // intersectionRatio < 1 && top 已到达 sentinel:贴住状态 e.target.classList.toggle("isStuck", e.intersectionRatio < 1 && e.boundingClientRect.top <= 65); } }, { threshold: [1], rootMargin: "-65px 0px 0px 0px" } ); titles.forEach((t) => io.observe(t)); } function initShortcutsHelp() { const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); const mod = isMac ? "⌘" : "Ctrl"; let overlay = null; const ITEMS = [ { keys: [mod, "K"], desc: "聚焦配置搜索" }, { keys: [mod, "S"], desc: "保存配置" }, { keys: [mod, "Enter"], desc: "开始运行" }, { keys: ["Esc"], desc: "清空搜索 / 关闭弹层" }, { keys: ["?"], desc: "显示此帮助" }, ]; const open = () => { if (overlay) return; overlay = document.createElement("div"); overlay.className = "shortcutsOverlay"; overlay.innerHTML = ` `; document.body.appendChild(overlay); requestAnimationFrame(() => overlay.classList.add("isVisible")); overlay.addEventListener("click", (e) => { if (e.target === overlay || e.target.closest(".shortcutsClose")) close(); }); }; const close = () => { if (!overlay) return; overlay.classList.remove("isVisible"); const ref = overlay; setTimeout(() => { try { ref.remove(); } catch (_) {} }, 160); overlay = null; }; document.addEventListener("keydown", (e) => { // 输入框聚焦时不拦截 ? 字符 const inField = /^(INPUT|TEXTAREA|SELECT)$/i.test(document.activeElement?.tagName || ""); if (e.key === "?" && !inField && !e.metaKey && !e.ctrlKey) { e.preventDefault(); overlay ? close() : open(); return; } if (e.key === "Escape" && overlay) { e.preventDefault(); close(); } }); } function updateTabBadge(target, count) { const btn = document.querySelector(`.tabBtn[data-target="${target}"]`); if (!btn) return; const n = Math.max(0, Number(count) || 0); if (n > 0) btn.setAttribute("data-badge", n > 99 ? "99+" : String(n)); else btn.removeAttribute("data-badge"); } function startReservationsCountdownTick() { // 每秒 tick 更新预约卡倒计时与高亮类,无需等待 stats 轮询 setInterval(() => { const items = document.querySelectorAll(".reservationItem[data-future-ts]"); if (!items.length) return; const now = Date.now() / 1000; items.forEach((card) => { const fut = Number(card.dataset.futureTs) || 0; if (!fut) return; const remain = Math.max(0, Math.floor(fut - now)); const remainEl = card.querySelector(".reservationRemain"); if (remainEl) { remainEl.textContent = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : "已到开奖时间"; } card.classList.toggle("isImminent", remain > 0 && remain <= 60); card.classList.toggle("isDue", remain === 0); }); }, 1000); } function initTabs() { const tabButtons = Array.from(document.querySelectorAll(".tabBtn[data-target]")); const panels = Array.from(document.querySelectorAll(".panel[data-panel]")); const sideNav = document.querySelector(".sideNav"); if (tabButtons.length === 0 || panels.length === 0) return; const updateIndicator = (btn) => { if (!sideNav || !btn || sideNav.offsetParent === null) return; // 横向布局(移动端 row)下不绘制竖条 const isRow = getComputedStyle(sideNav).flexDirection !== "column"; if (isRow) { sideNav.style.setProperty("--tab-indicator-opacity", "0"); return; } const navRect = sideNav.getBoundingClientRect(); const btnRect = btn.getBoundingClientRect(); const top = (btnRect.top - navRect.top) + (btnRect.height - 16) / 2; sideNav.style.setProperty("--tab-indicator-y", `${top}px`); sideNav.style.setProperty("--tab-indicator-h", `16px`); sideNav.style.setProperty("--tab-indicator-opacity", "1"); }; const setActive = (target) => { let activeBtn = null; for (const btn of tabButtons) { const isActive = btn.dataset.target === target; btn.classList.toggle("active", isActive); btn.setAttribute("aria-selected", isActive ? "true" : "false"); if (isActive) activeBtn = btn; } for (const panel of panels) { const isActive = panel.dataset.panel === target; panel.toggleAttribute("hidden", !isActive); panel.classList.toggle("active", isActive); } document.body.dataset.activePanel = target || ""; updateIndicator(activeBtn); }; for (const btn of tabButtons) { btn.addEventListener("click", () => { const wasActive = btn.classList.contains("active"); setActive(btn.dataset.target); // Trigger burst pulse on the indicator only when actually switching if (!wasActive && sideNav) { sideNav.classList.remove("isBurst"); void sideNav.offsetWidth; sideNav.classList.add("isBurst"); setTimeout(() => sideNav.classList.remove("isBurst"), 380); } }); } const defaultTarget = tabButtons.find(b => b.classList.contains("active"))?.dataset.target || tabButtons[0].dataset.target; setActive(defaultTarget); // 窗口尺寸变化或字体加载完成时重新计算位置 let resizeTimer; window.addEventListener("resize", () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { const cur = document.querySelector(".tabBtn.active[data-target]"); if (cur) updateIndicator(cur); }, 80); }); if (document.fonts && document.fonts.ready) { document.fonts.ready.then(() => { const cur = document.querySelector(".tabBtn.active[data-target]"); if (cur) updateIndicator(cur); }); } } function classifyLogLine(line) { const s = String(line || ""); if (!s) return ""; // 错误优先 if (/\b(ERROR|FATAL|CRITICAL|TRACEBACK|EXCEPTION|FAILED|FAIL\b)\b/i.test(s)) return "logError"; if (/(失败|错误|异常|未知错误|超时|崩溃)/.test(s)) return "logError"; if (/❌/.test(s)) return "logError"; // 警告 if (/\b(WARN(ING)?)\b/i.test(s)) return "logWarn"; if (/(警告|注意)/.test(s)) return "logWarn"; if (/⚠️/.test(s)) return "logWarn"; // 成功 if (/\b(SUCCESS|OK|DONE|COMPLETED?)\b/i.test(s)) return "logSuccess"; if (/(成功|已保存|完成|启动成功)/.test(s)) return "logSuccess"; if (/(✅|✓)/.test(s)) return "logSuccess"; // Debug if (/\b(DEBUG|TRACE)\b/i.test(s)) return "logDebug"; // INFO 默认 if (/\b(INFO)\b/i.test(s)) return "logInfo"; return ""; } function renderLogLineNode(line) { const cls = classifyLogLine(line); if (!cls) { // 普通行:直接文本节点(性能最佳) return document.createTextNode(String(line ?? "") + "\n"); } const span = document.createElement("span"); span.className = "logLine " + cls; span.textContent = String(line ?? "") + "\n"; return span; } function appendLog(lines) { const log = $("runLog"); if (!lines || lines.length === 0) return; // 记录更新前与底部的距离,用于在非底部时保持视图位置 const distanceFromBottom = log.scrollHeight - log.scrollTop - log.clientHeight; // 是否严格位于底部(仅在几像素内视为底部),避免每次刷新都跳到底部 const wasAtBottom = distanceFromBottom < UI_LIMITS.scrollBottomThresholdPx; // 直接追加到 DOM,同时维护 runLogBuffer 以便支持搜索 for (const ln of lines) runLogBuffer.push(ln); // 限制缓冲 if (runLogBuffer.length > runLogMaxLines) runLogBuffer = runLogBuffer.slice(-runLogMaxLines); // 如果当前处于 run search 结果显示状态,则不改变显示(保持搜索结果不被实时追加打断) if (runSearchActive && runLogMode === 'search') { // 仍保持缓冲更新,但不修改 DOM } else if (runLogFilter) { // 有过滤器时重渲染整个视图 renderRunLog(); } else { // 批量追加:用 fragment + 行级 span 着色 const frag = document.createDocumentFragment(); for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); log.appendChild(frag); } // 性能优化:限制日志长度,避免内存溢出(保留最近较多字符以便桌面端查看) const maxLength = UI_LIMITS.runLogMaxChars; if (log.textContent.length > maxLength) { // 直接基于缓冲重渲染(截断到最新行) runLogBuffer = runLogBuffer.slice(-Math.ceil(runLogMaxLines * 0.6)); renderRunLog(); if (!wasAtBottom) { const newScrollTop = log.scrollHeight - log.clientHeight - distanceFromBottom; log.scrollTop = Math.max(0, newScrollTop); } } // 只有在确实位于底部时才自动滚动到最新内容,避免打断用户查看历史日志 if (wasAtBottom) { log.scrollTop = log.scrollHeight; } } function renderRunLog() { const el = $("runLog"); if (!el) return; const renderInto = (lines) => { el.textContent = ""; if (!lines.length) return; const frag = document.createDocumentFragment(); for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); el.appendChild(frag); }; // 如果处于搜索结果显示状态,优先显示 search 返回的结果 if (runSearchActive && runLogMode === 'search') { const lines = runSearchResultsBuffer || []; const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; renderInto(lines); if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); return; } const filter = (runLogFilter || "").toLowerCase(); let lines = runLogBuffer; if (filter) { lines = runLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); } const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; renderInto(lines); if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); } function appendRunLogLines(lines) { if (!Array.isArray(lines) || lines.length === 0) return; // 使用 appendLog 让现有的 UI 消息也能写入缓冲并利用已有行为 appendLog(lines); } async function fetchActionsLog() { try { const data = await apiGet('/api/actions?lines=500'); const lines = Array.isArray(data.lines) ? data.lines : []; actionsLogBuffer = lines.slice(-actionsLogMaxLines); renderActionsLog(); } catch (e) { console.error('fetchActionsLog error', e); } } function renderActionsLog() { const el = $("actionsLog"); if (!el) return; const filter = (actionsLogFilter || "").toLowerCase(); let lines = actionsLogBuffer; if (filter) lines = actionsLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); // 自动滚到底部 el.scrollTop = el.scrollHeight; } function attachNumberSteppers() { // 给所有 .input[type=number] 包裹 .numStepperWrap + 添加 +/- 按钮 const SVG_UP = ''; const SVG_DOWN = ''; document.querySelectorAll('input.input[type="number"]').forEach((input) => { if (input.dataset.stepperBound === "1") return; if (input.closest(".inline2")) return; // inline2 内不加,避免连体边框冲突 input.dataset.stepperBound = "1"; const wrap = document.createElement("div"); wrap.className = "numStepperWrap"; input.parentNode.insertBefore(wrap, input); wrap.appendChild(input); const btns = document.createElement("span"); btns.className = "numStepperBtns"; const up = document.createElement("button"); up.type = "button"; up.tabIndex = -1; up.className = "numStepperBtn"; up.setAttribute("aria-label", "增加"); up.innerHTML = SVG_UP; const down = document.createElement("button"); down.type = "button"; down.tabIndex = -1; down.className = "numStepperBtn"; down.setAttribute("aria-label", "减少"); down.innerHTML = SVG_DOWN; btns.append(up, down); wrap.appendChild(btns); const fire = (dir) => { try { dir > 0 ? input.stepUp() : input.stepDown(); } catch (_) {} input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); }; const bindHold = (btn, dir) => { let holdTimer, repeatTimer; const cancel = () => { if (holdTimer) { clearTimeout(holdTimer); holdTimer = null; } if (repeatTimer) { clearInterval(repeatTimer); repeatTimer = null; } }; btn.addEventListener("pointerdown", (e) => { if (e.button !== 0) return; e.preventDefault(); fire(dir); holdTimer = setTimeout(() => { repeatTimer = setInterval(() => fire(dir), 80); }, 500); }); btn.addEventListener("pointerup", cancel); btn.addEventListener("pointerleave", cancel); btn.addEventListener("pointercancel", cancel); btn.addEventListener("blur", cancel); }; bindHold(up, 1); bindHold(down, -1); }); } function fmtTime(ts) { if (!ts) return "-"; try { return new Date(ts * 1000).toLocaleString(); } catch { return "-"; } } function fmtNum(v) { if (v === null || typeof v === "undefined") return "-"; const n = Number(v); if (!Number.isFinite(n)) return String(v); return n.toLocaleString("en-US"); } 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; const pad = (n) => String(n).padStart(2, "0"); // mono 格式:HH:MM:SS(>1h)/ MM:SS(其他),方便 tabular-nums 对齐 if (h > 0) return `${pad(h)}:${pad(m)}:${pad(sec)}`; return `${pad(m)}:${pad(sec)}`; } 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"); if (status) status.textContent = `刷新中:${new Date().toLocaleTimeString()}`; } function startShotPolling() { if (shotTimer) clearInterval(shotTimer); 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); const ts = new Date().toLocaleTimeString(); if (status) status.textContent = `已更新:${ts}`; const tsBadge = document.getElementById("liveShotTs"); if (tsBadge) { tsBadge.textContent = ts; tsBadge.hidden = false; } }); 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, UI_LIMITS.screenshotPollMs); } function setTextIfExists(id, text) { const el = $(id); if (!el) return; const next = String(text ?? "-"); // 仅取文本节点(跳过子元素如 .copyBtn / .statTrend)来比较和读取当前值 const getTextOnly = (node) => { let s = ""; for (const ch of node.childNodes) if (ch.nodeType === Node.TEXT_NODE) s += ch.textContent; return s; }; const prev = getTextOnly(el); // 仅对 statValue 有效:值变化时短暂高亮 + 趋势箭头 if (el.classList.contains("statValue") && prev !== next && next !== "-") { el.classList.remove("isFlash"); void el.offsetWidth; el.classList.add("isFlash"); setTimeout(() => el.classList.remove("isFlash"), 700); // 数字字段才显示趋势 const prevNum = Number(prev); const nextNum = Number(next); if (Number.isFinite(prevNum) && Number.isFinite(nextNum) && prevNum !== nextNum) { let trend = el.querySelector(".statTrend"); if (!trend) { trend = document.createElement("span"); trend.className = "statTrend"; el.appendChild(trend); } const isUp = nextNum > prevNum; trend.textContent = isUp ? "▲" : "▼"; trend.classList.toggle("isUp", isUp); trend.classList.toggle("isDown", !isUp); trend.classList.remove("isFading"); void trend.offsetWidth; trend.classList.add("isFading"); // 1s 后自动消失 clearTimeout(trend._fadeTimer); trend._fadeTimer = setTimeout(() => { if (trend) trend.remove(); }, 1100); } } // 替换:保留所有非文本子节点(如 .copyBtn / .statTrend),仅更新文本 for (const ch of Array.from(el.childNodes)) { if (ch.nodeType === Node.TEXT_NODE) ch.remove(); } el.insertBefore(document.createTextNode(next), el.firstChild || null); } 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); } 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 = `
#
内容
次数
`; root.appendChild(head); if (list.length === 0) { const row = document.createElement("div"); row.className = "tableRow"; row.innerHTML = `
-
暂无数据
-
`; 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 = `
#${idx + 1}
${escapeHtml(key)}
${cnt}
`; root.appendChild(row); }); } function escapeHtml(s) { return String(s ?? "") .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } 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 = `
时间
内容
价值
`; root.appendChild(head); if (list.length === 0) { const row = document.createElement("div"); row.className = "tableRow"; row.innerHTML = `
-
暂无中奖记录
-
`; 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 = `
${escapeHtml(fmtTime(ts))}
${escapeHtml(content)}
${escapeHtml(value)}
`; 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; } let maxY = 0; 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); } if (maxY <= 0) { const d = document.createElement("div"); d.className = "hint"; d.textContent = "暂无数据"; root.appendChild(d); return; } 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.classList.add("timelineSvg"); // SVG glow filter(feGaussianBlur + feMerge)让折线带霓虹光晕 const NS_FILTER = "http://www.w3.org/2000/svg"; const defs = document.createElementNS(NS_FILTER, "defs"); const filterId = (containerId || "timeline") + "Glow"; defs.innerHTML = ` `; svg.appendChild(defs); 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); // 水平网格线(4 等分),淡色 dashed const gridSteps = 4; for (let i = 1; i <= gridSteps; i++) { const gy = padT + ((H - padT - padB) * i / gridSteps); const gline = document.createElementNS("http://www.w3.org/2000/svg", "path"); gline.setAttribute("d", `M ${padL} ${gy.toFixed(2)} L ${W - padR} ${gy.toFixed(2)}`); gline.setAttribute("stroke", "var(--border)"); gline.setAttribute("stroke-opacity", "0.5"); gline.setAttribute("stroke-dasharray", "2 4"); gline.setAttribute("fill", "none"); svg.appendChild(gline); } 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", "10"); el.setAttribute("font-family", "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"); 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 轴刻度(0 / mid / max) const yMid = Math.round(maxY / 2); svg.appendChild(mkText(padL - 6, padT + 4, String(maxY), "end")); if (yMid > 0 && yMid < maxY) { svg.appendChild(mkText(padL - 6, padT + (H - padT - padB) / 2 + 4, String(yMid), "end")); } svg.appendChild(mkText(padL - 6, H - padB + 4, "0", "end")); // 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")); for (const k of TIMELINE_SERIES_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", TIMELINE_STROKES[k]?.stroke || "var(--primary)"); p.setAttribute("stroke-width", "1.8"); p.setAttribute("stroke-opacity", String(TIMELINE_STROKES[k]?.opacity ?? 1)); if (TIMELINE_STROKES[k]?.dash) p.setAttribute("stroke-dasharray", TIMELINE_STROKES[k].dash); p.setAttribute("stroke-linecap", "round"); p.setAttribute("stroke-linejoin", "round"); p.setAttribute("filter", `url(#${filterId})`); svg.appendChild(p); } // Crosshair hover layer:垂直线 + 当前 bin 的 dot 圆 + tooltip const NS = "http://www.w3.org/2000/svg"; const crossLine = document.createElementNS(NS, "line"); crossLine.setAttribute("y1", String(padT)); crossLine.setAttribute("y2", String(H - padB)); crossLine.setAttribute("stroke", "var(--text)"); crossLine.setAttribute("stroke-opacity", "0.25"); crossLine.setAttribute("stroke-dasharray", "2 3"); crossLine.setAttribute("pointer-events", "none"); crossLine.setAttribute("visibility", "hidden"); svg.appendChild(crossLine); // 容器(外层 root)作为相对定位锚点 root.style.position = "relative"; const tip = document.createElement("div"); tip.className = "timelineTip"; tip.hidden = true; root.appendChild(tip); const fmtTimeOf = (i) => { if (!startTs || !binSec) return ""; try { return new Date((startTs + i * binSec) * 1000).toLocaleTimeString(); } catch { return ""; } }; const SERIES_LABEL = { fudai_open_detail: "打开详情", fudai_attend_ok: "参与成功", fudai_attend_fail: "参与失败", fudai_result_win: "中奖", fudai_result_no_win: "未中奖", fudai_skip: "跳过", switch_room: "切换直播间", }; const onMove = (ev) => { const rect = svg.getBoundingClientRect(); const xRatio = (ev.clientX - rect.left) / rect.width; if (xRatio < 0 || xRatio > 1) return; const xCoord = padL + (W - padL - padR) * xRatio; // 找最近的 bin let i = Math.round(((xCoord - padL) / Math.max(1, W - padL - padR)) * (bins - 1)); if (i < 0) i = 0; else if (i >= bins) i = bins - 1; const xOnAxis = xAt(i); crossLine.setAttribute("x1", String(xOnAxis)); crossLine.setAttribute("x2", String(xOnAxis)); crossLine.setAttribute("visibility", "visible"); // 生成 tip 内容 const lines = []; let total = 0; for (const k of TIMELINE_SERIES_KEYS) { const arr = Array.isArray(series[k]) ? series[k] : []; const v = Number(arr[i]) || 0; total += v; if (v > 0) lines.push(`${SERIES_LABEL[k] || k}${v}`); } if (total === 0) lines.push(`无事件`); tip.innerHTML = `
${fmtTimeOf(i)}
${lines.join("")}
`; tip.hidden = false; // tip 位置:根据当前 svg 实际宽度比例换算到 root 内 px const actualX = (xOnAxis / W) * rect.width; let leftPx = actualX + 8; if (leftPx + 160 > rect.width) leftPx = actualX - 168; if (leftPx < 0) leftPx = 4; tip.style.left = `${Math.max(0, leftPx)}px`; tip.style.top = `${rect.height * 0.06}px`; }; const onLeave = () => { crossLine.setAttribute("visibility", "hidden"); tip.hidden = true; }; svg.addEventListener("mousemove", onMove); svg.addEventListener("mouseleave", onLeave); root.appendChild(svg); const legend = document.createElement("div"); legend.className = "hint"; legend.textContent = "图例:实线/虚线区分同色不同事件 · 鼠标悬停查看明细"; root.appendChild(legend); } // API 连接状态:连续失败 N 次才算 error,避免轻微抖动闪烁 let _apiFailStreak = 0; const _apiFailThreshold = 2; function setConnState(state) { const dot = document.getElementById("appConnDot"); const txt = document.getElementById("appConnText"); if (!dot || !txt) return; if (state === "ok") { dot.dataset.state = "ok"; txt.textContent = "已连接"; dot.title = "API 通信正常"; } else if (state === "error") { dot.dataset.state = "error"; txt.textContent = "连接异常"; dot.title = "API 请求连续失败,检查后端是否运行"; } else { dot.dataset.state = "idle"; txt.textContent = "就绪"; dot.title = "等待首个 API 请求"; } } function notifyApiOk() { _apiFailStreak = 0; setConnState("ok"); } function notifyApiFail() { _apiFailStreak++; if (_apiFailStreak >= _apiFailThreshold) setConnState("error"); } function renderOverviewSparkline(svgId, timeline) { const svg = document.getElementById(svgId); if (!svg) return; // 把 fudai_open_detail + fudai_attend_ok 两个序列合成一条迷你折线 const series = (timeline && timeline.series) || {}; const keys = ["fudai_open_detail", "fudai_attend_ok"]; const arrs = keys.map((k) => Array.isArray(series[k]) ? series[k] : []); const len = Math.max(...arrs.map((a) => a.length), 0); if (len < 2) { svg.innerHTML = ""; svg.classList.remove("hasData"); return; } const combined = new Array(len).fill(0); for (const arr of arrs) { for (let i = 0; i < arr.length; i++) combined[i] += Number(arr[i]) || 0; } const maxY = Math.max(1, ...combined); // 100x24 viewBox:留 1px 边 const W = 100, H = 24, padY = 1.5; const xAt = (i) => (W * i) / (len - 1); const yAt = (v) => H - padY - ((H - padY * 2) * v) / maxY; let d = ""; for (let i = 0; i < len; i++) { const x = xAt(i).toFixed(2), y = yAt(combined[i]).toFixed(2); d += (i === 0 ? "M" : " L") + x + " " + y; } // 渐变填充区 const dArea = d + ` L ${W} ${H} L 0 ${H} Z`; const NS = "http://www.w3.org/2000/svg"; svg.setAttribute("viewBox", `0 0 ${W} ${H}`); svg.innerHTML = ""; // gradient defs const defs = document.createElementNS(NS, "defs"); const gid = svgId + "Grad"; const grad = document.createElementNS(NS, "linearGradient"); grad.setAttribute("id", gid); grad.setAttribute("x1", "0"); grad.setAttribute("y1", "0"); grad.setAttribute("x2", "0"); grad.setAttribute("y2", "1"); grad.innerHTML = ``; defs.appendChild(grad); svg.appendChild(defs); const area = document.createElementNS(NS, "path"); area.setAttribute("d", dArea); area.setAttribute("fill", `url(#${gid})`); svg.appendChild(area); const line = document.createElementNS(NS, "path"); line.setAttribute("d", d); line.setAttribute("fill", "none"); line.setAttribute("stroke", "currentColor"); line.setAttribute("stroke-width", "1.25"); line.setAttribute("stroke-linecap", "round"); line.setAttribute("stroke-linejoin", "round"); svg.appendChild(line); svg.classList.add("hasData"); } async function apiGet(path) { try { const res = await fetch(path, { cache: "no-store" }); if (!res.ok) { notifyApiFail(); throw new Error(await res.text()); } notifyApiOk(); return await res.json(); } catch (e) { notifyApiFail(); throw e; } } // CSRF token 缓存 let _csrfToken = null; async function getCsrfToken() { if (_csrfToken) return _csrfToken; try { const res = await fetch("/api/csrf-token", { cache: "no-store" }); if (res.ok) { const data = await res.json(); _csrfToken = data.token || ""; } } catch (e) { console.warn("[CSRF] 获取 token 失败:", e); } return _csrfToken || ""; } async function apiPost(path, body) { try { const token = await getCsrfToken(); const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": token, }, body: JSON.stringify(body || {}), }); const data = await res.json(); if (!res.ok) { notifyApiFail(); const errorMsg = data.error || data.message || res.statusText; const error = new Error(errorMsg); error.status = res.status; error.data = data; throw error; } notifyApiOk(); return data; } catch (e) { notifyApiFail(); throw e; } } 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 = UI_COPY.device.autoOption; 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)"; deviceOverviewState = { devices, adb: data.adb || "" }; updateDeviceOverview(); // 选中后在外层包装上反映状态点 decorateDeviceSelect(); sel.addEventListener("change", decorateDeviceSelect); } function decorateDeviceSelect() { const sel = document.getElementById("device"); if (!sel) return; const wrap = sel.closest(".deviceSelectWrap") || (() => { const w = document.createElement("div"); w.className = "deviceSelectWrap"; sel.parentNode.insertBefore(w, sel); w.appendChild(sel); const dot = document.createElement("span"); dot.className = "deviceSelectDot"; dot.setAttribute("aria-hidden", "true"); w.appendChild(dot); return w; })(); const dot = wrap.querySelector(".deviceSelectDot"); const hasDevices = (deviceOverviewState.devices || []).length > 0; const selected = sel.value; // 选中具体设备 → 绿;选 auto + 有在线设备 → 绿;无设备 → 灰 const ok = !!(selected || hasDevices); if (dot) dot.dataset.state = ok ? "ok" : "idle"; } function getConfigBoundElements() { return Array.from(document.querySelectorAll("[data-key]")); } function syncMirrorFields() { const mirrors = Array.from(document.querySelectorAll("[data-mirror-key]")); for (const mirror of mirrors) { const key = mirror.dataset.mirrorKey; const source = document.querySelector(`[data-key="${CSS.escape(key)}"]`); if (!source) continue; const copy = () => { if (mirror.type === "checkbox") mirror.checked = !!source.checked; else mirror.value = source.value; }; copy(); source.addEventListener("input", copy); source.addEventListener("change", copy); mirror.addEventListener("input", () => { if (source.type === "checkbox") source.checked = !!mirror.checked; else source.value = mirror.value; source.dispatchEvent(new Event("input", { bubbles: true })); source.dispatchEvent(new Event("change", { bubbles: true })); }); } } function getConfigValue(cfg, key) { if (!cfg || !key) return undefined; if (Object.prototype.hasOwnProperty.call(cfg, key)) return cfg[key]; if (!String(key).includes(".")) return undefined; let cur = cfg; for (const part of String(key).split(".")) { if (!cur || typeof cur !== "object" || !Object.prototype.hasOwnProperty.call(cur, part)) return undefined; cur = cur[part]; } return cur; } 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 applyConfigToUI(cfg) { for (const el of getConfigBoundElements()) { const key = el.dataset.key; const type = el.dataset.type || "str"; const val = getConfigValue(cfg, key); // 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; if (el.type === "checkbox") { out[key] = coerceValue(type, el.checked, true); } else { out[key] = coerceValue(type, el.value, false); } } return out; } async function loadConfig() { try { const cfg = await apiGet("/api/config"); applyConfigToUI(cfg); toast("配置已加载", "success"); } catch (e) { toast("配置加载失败:" + e.message, "error", { duration: 5000 }); appendLog(["[WEB] 配置加载失败: " + e.message]); } } async function saveConfig() { setButtonBusy("btnSave", true); try { const cfgUpdate = collectConfigFromUI(); await apiPost("/api/config", cfgUpdate); toast("配置已保存", "success"); } catch (e) { toast("保存失败:" + (e?.message || e), "error", { duration: 5000 }); throw e; } finally { setButtonBusy("btnSave", false); } } function selectedDeviceId() { const el = $("device"); return el ? (el.value || "") : ""; } async function postDeviceAction(path, body, successPrefix) { try { const result = await apiPost(path, body || {}); const msg = result.message || result.output || result.error || "完成"; appendLog([`${successPrefix}: ${msg}`]); if (!result.error) toast(`${successPrefix}: ${msg}`, "success"); else toast(`${successPrefix}: ${msg}`, "warn"); if (result.devices) await refreshDevices(); return result; } catch (e) { appendLog([`${successPrefix}失败: ${e?.message || e}`]); toast(`${successPrefix}失败:${e?.message || e}`, "error", { duration: 5000 }); throw e; } } async function forceStopRun() { await postDeviceAction("/api/force-stop", {}, "[WEB] 强制停止"); } async function sendBackKey() { const deviceId = selectedDeviceId(); await postDeviceAction("/api/back-key", { device_id: deviceId }, "[WEB] 返回键"); } async function wifiEnable() { const deviceId = selectedDeviceId(); if (!deviceId) { appendLog(["[WiFi ADB] 请先选择 USB 设备"]); return; } const result = await postDeviceAction("/api/wifi/enable", { device_id: deviceId }, "[WiFi ADB] 启用"); setTextIfExists("wifiStatus", result.message || "已发送启用命令"); } async function wifiConnect() { const ip = ($("wifi_ip")?.value || "").trim(); const port = ($("wifi_port")?.value || "5555").trim() || "5555"; if (!ip) { appendLog(["[WiFi ADB] 请填写设备 IP"]); return; } const result = await postDeviceAction("/api/wifi/connect", { ip, port }, "[WiFi ADB] 连接"); setTextIfExists("wifiStatus", result.message || "连接命令已执行"); } async function wifiDisconnect() { const ip = ($("wifi_ip")?.value || selectedDeviceId() || "").trim(); const port = ($("wifi_port")?.value || "5555").trim() || "5555"; if (!ip) { appendLog(["[WiFi ADB] 请填写 IP 或选择 WiFi 设备"]); return; } const result = await postDeviceAction("/api/wifi/disconnect", { ip, port }, "[WiFi ADB] 断开"); setTextIfExists("wifiStatus", result.message || "断开命令已执行"); } 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); const cfgPart = collectConfigFromUI(); const waitMinutes = cfgPart.infinite_loop_enabled ? 0 : parseInt($("wait_minutes").value || "5", 10); const needswitch = $("needswitch").checked; 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, skip_if_countdown_gt_seconds: cfgPart.skip_if_countdown_gt_seconds, reset_after_swipes_action: cfgPart.reset_after_swipes_action, enable_back_on_misses: cfgPart.enable_back_on_misses, swipe_down_back_enabled: cfgPart.swipe_down_back_enabled, swipe_down_back_count: cfgPart.swipe_down_back_count, 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, high_value_room_revisit_min_interval_seconds: cfgPart.high_value_room_revisit_min_interval_seconds, high_value_room_revisit_max_per_run: cfgPart.high_value_room_revisit_max_per_run, high_value_room_revisit_min_prize_value: cfgPart.high_value_room_revisit_min_prize_value, high_value_room_revisit_max_age_days: cfgPart.high_value_room_revisit_max_age_days, reservation_back_verify_enabled: cfgPart.reservation_back_verify_enabled, reservation_back_swipe_delay: cfgPart.reservation_back_swipe_delay, reservation_back_verify_wait_seconds: cfgPart.reservation_back_verify_wait_seconds, fudai_find_max_attempts: cfgPart.fudai_find_max_attempts, enable_ocr_mode1: cfgPart.enable_ocr_mode1, fudai_template_match_enabled: cfgPart.fudai_template_match_enabled, fudai_template_match_threshold: cfgPart.fudai_template_match_threshold, yanghao_only: cfgPart.yanghao_only, yanghao_seconds: cfgPart.yanghao_recommend_duration_seconds, }); // 检查返回结果 if (result && result.ok === false) { const errorMsg = result.error || "未知错误"; appendLog([`[WEB] 启动失败: ${errorMsg}`]); toast("启动失败:" + (errorMsg === "running" ? "已有进程在运行" : errorMsg), "error", { duration: 5000 }); if (errorMsg === "running") { appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); } return; } appendLog([`[WEB] 已开始运行:device=${deviceId || UI_COPY.device.autoLabel}`]); toast(`已开始运行 · ${deviceId || "自动"}`, "success"); // 启动时自动截图 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 = $("runLog"); 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}`]); toast("启动失败:" + errorMsg, "error", { duration: 5000 }); setRunOverview(UI_COPY.runOverview.failed, errorMsg, RUN_TONE.error); // 如果是"running"错误,显示友好提示 if (errorMsg === "running" || (e.status === 409)) { appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); } } finally { setButtonBusy("btnStart", false); } } 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 || 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 || 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] 已发送停止"]); // 重置并拉取日志,确保能看到后端的停止确认输出 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('runLog'); 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) { appendRunLogLines(retryData.lines); } } return; } // 更新日志索引 logIdx = nextIdx; // API调用成功,更新最后更新时间(不管是否有新日志) lastLogUpdateTime = apiCallTime; // 追加日志 if (Array.isArray(data.lines) && data.lines.length > 0) { appendRunLogLines(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 = `
当前位置:${room_pos}
当前直播间(清洗后):${escapeHtml(current_room_title || '-') }
当前直播间原文:${escapeHtml(current_room_title_raw || '-') }
预约数量:${reservations.length}
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}
原因:${escapeHtml(reason || '-') }
`; container.appendChild(info); updateTabBadge("reservations", reservations.length); 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}秒后` : "已到开奖时间"; // 60s 内开奖:高亮提醒 if (remain > 0 && remain <= 60) card.classList.add("isImminent"); else if (remain === 0) card.classList.add("isDue"); // 把 future_ts 存到卡片,供倒计时 tick 实时刷新 if (future_ts) card.dataset.futureTs = String(future_ts); card.innerHTML = `
#${idx + 1} ${item.prize_value_yuan || 0}元
内容:${escapeHtml(item.content || '-')}
开奖时间:${item.future_str || '-'}
剩余时间:${remainStr}
发现位置:${item.pos_seen || 0}
直播间(清洗后):${escapeHtml(item.room_title || '-')}
直播间原文:${escapeHtml(item.room_title_raw || '-')}
`; 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 = `
记录数量:${total}
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}
原因:${escapeHtml(reason || '-') }
`; 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 = `
#${idx + 1} max ${escapeHtml(maxVal)}元
直播间(清洗后):${escapeHtml(roomTitle)}
直播间原文:${escapeHtml(roomRaw)}
最近位置:${escapeHtml(posSeen)}
首次记录:${escapeHtml(fmtTime(firstSeen))}
最近记录:${escapeHtml(fmtTime(lastSeen))}
记录次数:${escapeHtml(seenCount)}
最近价值:${escapeHtml(lastVal)}元
`; // 让每条记录的 header 可点击以折叠/展开本条详情 list.appendChild(card); try { const header = card.querySelector(`.${UI_CLASS.reservationHeader}`); const body = card.querySelector(`.${UI_CLASS.reservationBody}`); if (header && body) { header.classList.add(UI_CLASS.clickable); header.addEventListener('click', () => { body.classList.toggle(UI_CLASS.collapsed); }); } } 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(`.${UI_CLASS.reservationsList}`); if (listEl) listEl.classList.remove(UI_CLASS.listCollapsed); }); if (btnCollapse) btnCollapse.addEventListener('click', () => { const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); if (listEl) listEl.classList.add(UI_CLASS.listCollapsed); }); } 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()}`); // 数据到位,去掉骨架 document.querySelectorAll(".stat .statValue.skeleton, .stat .statHint.skeleton").forEach((el) => el.classList.remove("skeleton")); const running = s.running ? "运行中" : "未运行"; setTextIfExists("statRunning", running); const runningEl = document.getElementById("statRunning"); if (runningEl) { runningEl.classList.toggle("stateOk", !!s.running); runningEl.classList.toggle("stateMuted", !s.running); } setTextIfExists("statPid", s.pid ?? "-"); setTextIfExists("statUptime", fmtDuration(s.uptime_seconds)); setTextIfExists("statLogLen", fmtNum(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); 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); // 页面标题随运行状态更新 try { const baseTitle = "抖音挂机控制台"; document.title = s.running ? `● ${baseTitle} · 运行中` : baseTitle; } catch (_) {} setTextIfExists("topLogState", UI_COPY.overview.logLines(s.log_len)); setTextIfExists("topLogMeta", UI_COPY.overview.lastLog(s.last_log_ts)); setTextIfExists("statFudaiSeen", fmtNum(getC("fudai_seen"))); setTextIfExists("statFudaiOpen", fmtNum(getC("fudai_open_detail"))); setTextIfExists("statFudaiAttendOk", fmtNum(getC("fudai_attend_ok"))); setTextIfExists("statFudaiAttendFail", fmtNum(getC("fudai_attend_fail"))); setTextIfExists("statFudaiNoWin", fmtNum(getC("fudai_result_no_win"))); setTextIfExists("statFudaiWin", fmtNum(getC("fudai_result_win"))); // 福袋统计语义着色 const colorize = (id, kind, n) => { const el = document.getElementById(id); if (!el) return; el.classList.toggle("stateOk", kind === "ok" && n > 0); el.classList.toggle("stateError", kind === "error" && n > 0); el.classList.toggle("stateWarn", kind === "warn" && n > 0); el.classList.toggle("stateMuted", kind === "muted" && n > 0); }; colorize("statFudaiAttendOk", "ok", getC("fudai_attend_ok")); colorize("statFudaiWin", "ok", getC("fudai_result_win")); colorize("statFudaiAttendFail", "error", getC("fudai_attend_fail")); colorize("statFudaiNoWin", "muted", getC("fudai_result_no_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", fmtNum(getC("fudai_skip_value_low"))); const pLow = getC("fudai_skip_participants_low"); const pHigh = getC("fudai_skip_participants_high"); setTextIfExists("statSkipParticipants", fmtNum(pLow + pHigh)); if ($("statSkipParticipantsHint")) { $("statSkipParticipantsHint").textContent = `低:${pLow} / 高:${pHigh}`; } setTextIfExists("statSkipContent", fmtNum(getC("fudai_skip_content"))); const cdShort = getC("fudai_skip_countdown_short"); const cdLong = getC("fudai_skip_countdown_long"); setTextIfExists("statSkipCountdown", fmtNum(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", fmtNum(fcReq)); if ($("statFansclubHint")) { $("statFansclubHint").textContent = `需手动:${fcManual} / 未解决:${fcUn}`; } const sw = getC("switch_room"); setTextIfExists("statSwitchRoom", fmtNum(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); renderOverviewSparkline("topFudaiSparkline", 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, UI_LIMITS.logPollMs); } function startStatsPolling() { if (statsTimer) clearInterval(statsTimer); statsTimer = setInterval(() => { pollStats(); pollReservations(); pollHighValueRooms(); }, UI_LIMITS.statsPollMs); } window.addEventListener("DOMContentLoaded", async () => { initTheme(); initTabs(); initConfigSearch(); initFooter(); attachCopyButtons(); initShotFullscreen(); initHeaderScroll(); initKeyboardShortcuts(); initShortcutsHelp(); initStickySectionShadow(); attachNumberSteppers(); applyKbdHints(); startReservationsCountdownTick(); // 首屏统计数字加骨架,待第一次 pollStats 成功后移除 document.querySelectorAll(".stat .statValue").forEach((el) => { if ((el.textContent || "").trim() === "-") el.classList.add("skeleton"); }); $("btnRefresh").addEventListener("click", async () => { setButtonBusy("btnRefresh", true); try { await refreshDevices(); const n = (deviceOverviewState.devices || []).length; toast(n > 0 ? `已刷新 · ${n} 台在线` : "已刷新 · 无在线设备", n > 0 ? "success" : "warn"); } catch (e) { toast("刷新失败:" + (e?.message || e), "error", { duration: 4000 }); } finally { setButtonBusy("btnRefresh", false); } }); $("btnLoad").addEventListener("click", async () => { await loadConfig(); }); $("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"); if (btnBackKey) btnBackKey.addEventListener("click", async () => { await sendBackKey(); }); const btnWifiEnable = $("btnWifiEnable"); if (btnWifiEnable) btnWifiEnable.addEventListener("click", async () => { await wifiEnable(); }); const btnWifiConnect = $("btnWifiConnect"); if (btnWifiConnect) btnWifiConnect.addEventListener("click", async () => { await wifiConnect(); }); const btnWifiDisconnect = $("btnWifiDisconnect"); if (btnWifiDisconnect) btnWifiDisconnect.addEventListener("click", async () => { await wifiDisconnect(); }); // 截图按钮 $("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}`]); } }); // 日志搜索与动作日志相关交互绑定 // 日志搜索与动作日志相关交互绑定 const runModeEl = $("runLogMode"); const runSearchEl = $("runLogSearch"); const runSearchBtn = $("btnRunLogSearch"); const runClear = $("btnRunLogClear"); async function doRunLogSearch() { const q = runSearchEl ? String(runSearchEl.value || '') : ''; if (!q) { runSearchActive = false; runSearchResultsBuffer = []; renderRunLog(); return; } try { const data = await apiGet(`/api/logs?q=${encodeURIComponent(q)}&lines=1000`); runSearchResultsBuffer = Array.isArray(data.lines) ? data.lines : []; runSearchActive = true; renderRunLog(); } catch (e) { console.error('doRunLogSearch error', e); } } if (runModeEl) { runModeEl.addEventListener('change', (e) => { runLogMode = String(e.target.value || 'filter'); runSearchActive = false; renderRunLog(); }); } if (runSearchEl) { runSearchEl.addEventListener('input', (e) => { const v = String(e.target.value || ''); if (runLogMode === 'filter') { runLogFilter = v; renderRunLog(); } }); runSearchEl.addEventListener('keydown', async (e) => { if (e.key === 'Enter' && runLogMode === 'search') { await doRunLogSearch(); } }); } if (runSearchBtn) runSearchBtn.addEventListener('click', async () => { await doRunLogSearch(); }); if (runClear) runClear.addEventListener('click', () => { runLogBuffer = []; runSearchResultsBuffer = []; runSearchActive = false; runLogFilter = ''; if (runSearchEl) runSearchEl.value=''; renderRunLog(); }); syncMirrorFields(); const actionsSearchEl = $("actionsLogSearch"); if (actionsSearchEl) { actionsSearchEl.addEventListener('input', (e) => { actionsLogFilter = String(e.target.value || ''); renderActionsLog(); }); } const actionsRefresh = $("btnActionsRefresh"); if (actionsRefresh) actionsRefresh.addEventListener('click', () => { fetchActionsLog(); }); // 首次加载动作日志 fetchActionsLog(); await refreshDevices(); await loadConfig(); startPolling(); startStatsPolling(); startShotPolling(); pollLogs(); pollStats(); pollShot(); pollReservations(); pollHighValueRooms(); });