refactor(webui): extract runtime actions and polling

This commit is contained in:
Your Name committed 2026-06-01 00:35:49 +08:00
1 parent 48d18daef8
commit 3bc997a4d7
3 files changed
+848 -847

No files matched your search

-840
View File
@@ -718,846 +718,6 @@ function updateDeviceOverview() {
setTextIfExists("topAdbState", deviceOverviewState.adb ? UI_COPY.device.adbReady : UI_COPY.device.adbMissing);
}
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 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 tryAutoReconnectLastWifi() {
// 启动时调一次 /api/wifi/auto-reconnect。后端做完所有判断(已在线 / 重连成功 /
// 智能匹配 / 失败),前端只负责把结果反馈到日志和设备下拉。
try {
const resp = await apiPost("/api/wifi/auto-reconnect", {});
if (!resp || resp.ok === false) return;
const action = resp.action || "noop";
if (action === "noop") return;
if (action === "already_online" || action === "reconnected" || action === "matched") {
try {
await refreshDevices();
} catch (_) {}
const sel = $("device");
if (sel && resp.target) {
// 选中设备到下拉框
for (const opt of sel.options) {
if (opt.value === resp.target) {
sel.value = resp.target;
break;
}
}
}
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
appendLog([`[启动] ${resp.message || action}`]);
return;
}
if (action === "failed") {
appendLog([`[启动] ${resp.message || "WiFi 自动重连失败"}`]);
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
return;
}
} catch (e) {
// 启动期任何异常都不打扰用户
console.warn("auto-reconnect failed", e);
}
}
async function wifiScan() {
const btn = $("btnWifiScan");
const status = $("wifiStatus");
const results = $("wifiScanResults");
if (btn) {
btn.disabled = true;
btn.textContent = "扫描中...";
}
if (status) status.textContent = "正在扫描局域网...";
if (results) {
results.style.display = "none";
results.innerHTML = "";
}
try {
const resp = await apiPost("/api/wifi/scan", {});
if (!resp || resp.ok === false) {
const err = (resp && resp.error) || "扫描失败";
appendLog([`[WiFi ADB] 扫描失败: ${err}`]);
if (status) status.textContent = `扫描失败: ${err}`;
return;
}
const devs = Array.isArray(resp.devices) ? resp.devices : [];
const subnet = resp.subnet || "";
if (!devs.length) {
appendLog([`[WiFi ADB] 扫描完成 (${subnet}),未发现开放 5555 端口的设备`]);
if (status) status.textContent = `扫描完成 (${subnet}),未发现设备`;
return;
}
appendLog([
`[WiFi ADB] 扫描完成 (${subnet}),发现 ${devs.length} 台候选: ` +
devs.map((d) => `${d.target}(${d.state})`).join(", "),
]);
// 单个 connected:自动选中
const connected = devs.filter((d) => d.state === "connected");
if (connected.length === 1 && devs.length === 1) {
const d = connected[0];
const ipInput = $("wifi_ip");
if (ipInput) ipInput.value = d.target;
if (status)
status.textContent =
`已发现并连接 ${d.target}` + (d.model ? ` (${d.model})` : "") + ",已记住";
// 刷新设备下拉
try {
await refreshDevices();
} catch (_) {}
return;
}
// 多个候选:渲染列表,点击就填回 IP
if (results) {
results.style.display = "block";
const lines = devs.map((d) => {
const safeTarget = String(d.target || "").replace(/"/g, """);
const stateColor =
d.state === "connected" ? "#0a7d2c" :
d.state === "unauthorized" ? "#b35900" : "#888";
return (
`<div style="margin:4px 0; cursor:pointer; padding:4px 6px; border:1px solid #ddd; border-radius:4px;" ` +
`data-target="${safeTarget}" data-state="${d.state}">` +
`<b>${safeTarget}</b> ` +
`<span style="color:${stateColor}">[${d.state}]</span> ` +
(d.model ? ` <span style="color:#555">${d.model}</span>` : "") +
`</div>`
);
});
results.innerHTML =
`<div style="margin-bottom:4px; color:#555;">点击下方设备使用:</div>` +
lines.join("");
results.querySelectorAll("[data-target]").forEach((el) => {
el.addEventListener("click", () => {
const target = el.getAttribute("data-target");
const state = el.getAttribute("data-state");
if (state !== "connected") {
appendLog([
`[WiFi ADB] ${target} 状态=${state},请先在手机上确认 ADB 调试授权`,
]);
return;
}
const ipInput = $("wifi_ip");
if (ipInput) ipInput.value = target;
if (status) status.textContent = `已选 ${target}`;
appendLog([`[WiFi ADB] 已选 ${target}`]);
try {
refreshDevices();
} catch (_) {}
});
});
}
if (status) status.textContent = `扫描完成,发现 ${devs.length} 台设备`;
} catch (e) {
appendLog([`[WiFi ADB] 扫描异常: ${e}`]);
if (status) status.textContent = `扫描异常: ${e}`;
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = "扫描 WiFi";
}
}
}
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 = `
<div><strong>当前位置:</strong>${room_pos}</div>
<div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>
<div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>
<div><strong>预约数量:</strong>${reservations.length}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
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 = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">${item.prize_value_yuan || 0}元</span>
</div>
<div class="reservationBody">
<div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>
<div><strong>开奖时间:</strong>${item.future_str || '-'}</div>
<div><strong>剩余时间:</strong><span class="reservationRemain">${remainStr}</span></div>
<div><strong>发现位置:</strong>${item.pos_seen || 0}</div>
<div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>
<div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>
</div>
`;
list.appendChild(card);
});
container.appendChild(list);
// 恢复滚动位置(若有)
try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }
} catch (e) {
console.error("poll reservations failed:", e);
const container = $("reservationsContent");
if (!container) return;
clearEl(container);
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = `预约信息获取失败:${e?.message || e}`;
container.appendChild(hint);
}
}
async function pollHighValueRooms() {
try {
const data = await apiGet(`/api/high-value-rooms?t=${Date.now()}`);
const container = $("highValueRoomsContent");
if (!container) return;
// 保留上次滚动位置
const prevList = container.querySelector('.reservationsList');
const prevScroll = prevList ? prevList.scrollTop : 0;
clearEl(container);
const rooms = Array.isArray(data.rooms) ? data.rooms : [];
const updated_ts = Number(data.updated_ts) || 0;
const reason = String(data.reason || "");
const total = Number(data.total) || rooms.length;
const info = document.createElement("div");
info.className = "reservationsInfo";
info.innerHTML = `
<div><strong>记录数量:</strong>${total}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
if (rooms.length === 0) {
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = "暂无记录";
container.appendChild(hint);
return;
}
const list = document.createElement("div");
list.className = "reservationsList";
rooms.forEach((item, idx) => {
const card = document.createElement("div");
card.className = "reservationItem";
const roomTitle = String(item.room_title || "-");
const roomRaw = String(item.room_title_raw_last || "-");
const posSeen = (typeof item.pos_seen === "number") ? item.pos_seen : ((item.pos_seen === null || typeof item.pos_seen === "undefined") ? "-" : String(item.pos_seen));
const firstSeen = Number(item.first_seen_ts) || 0;
const lastSeen = Number(item.last_seen_ts) || 0;
const seenCount = Number(item.seen_count) || 0;
const maxVal = (item.max_prize_value_yuan === null || typeof item.max_prize_value_yuan === "undefined") ? "-" : String(item.max_prize_value_yuan);
const lastVal = (item.last_prize_value_yuan === null || typeof item.last_prize_value_yuan === "undefined") ? "-" : String(item.last_prize_value_yuan);
card.innerHTML = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">max ${escapeHtml(maxVal)}元</span>
</div>
<div class="reservationBody">
<div><strong>直播间(清洗后):</strong>${escapeHtml(roomTitle)}</div>
<div><strong>直播间原文:</strong>${escapeHtml(roomRaw)}</div>
<div><strong>最近位置:</strong>${escapeHtml(posSeen)}</div>
<div><strong>首次记录:</strong>${escapeHtml(fmtTime(firstSeen))}</div>
<div><strong>最近记录:</strong>${escapeHtml(fmtTime(lastSeen))}</div>
<div><strong>记录次数:</strong>${escapeHtml(seenCount)}</div>
<div><strong>最近价值:</strong>${escapeHtml(lastVal)}元</div>
</div>
`;
// 让每条记录的 header 可点击以折叠/展开本条详情
list.appendChild(card);
try {
const header = card.querySelector(`.${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();
+8 -7
View File
@@ -1278,12 +1278,13 @@
</button>
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="js/constants.js?v=console-20260531-split-6"></script>
<script src="js/dom_utils.js?v=console-20260531-split-6"></script>
<script src="js/api_client.js?v=console-20260531-split-6"></script>
<script src="js/log_views.js?v=console-20260531-split-6"></script>
<script src="js/dashboard_renderers.js?v=console-20260531-split-6"></script>
<script src="js/config_form.js?v=console-20260531-split-6"></script>
<script src="app.js?v=console-20260531-split-6"></script>
<script src="js/constants.js?v=console-20260531-split-7"></script>
<script src="js/dom_utils.js?v=console-20260531-split-7"></script>
<script src="js/api_client.js?v=console-20260531-split-7"></script>
<script src="js/log_views.js?v=console-20260531-split-7"></script>
<script src="js/dashboard_renderers.js?v=console-20260531-split-7"></script>
<script src="js/config_form.js?v=console-20260531-split-7"></script>
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
<script src="app.js?v=console-20260531-split-7"></script>
</body>
</html>
+840
View File
@@ -0,0 +1,840 @@
// Runtime actions and polling helpers shared by WebUI classic scripts.
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 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 tryAutoReconnectLastWifi() {
// 启动时调一次 /api/wifi/auto-reconnect。后端做完所有判断(已在线 / 重连成功 /
// 智能匹配 / 失败),前端只负责把结果反馈到日志和设备下拉。
try {
const resp = await apiPost("/api/wifi/auto-reconnect", {});
if (!resp || resp.ok === false) return;
const action = resp.action || "noop";
if (action === "noop") return;
if (action === "already_online" || action === "reconnected" || action === "matched") {
try {
await refreshDevices();
} catch (_) {}
const sel = $("device");
if (sel && resp.target) {
// 选中设备到下拉框
for (const opt of sel.options) {
if (opt.value === resp.target) {
sel.value = resp.target;
break;
}
}
}
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
appendLog([`[启动] ${resp.message || action}`]);
return;
}
if (action === "failed") {
appendLog([`[启动] ${resp.message || "WiFi 自动重连失败"}`]);
const status = $("wifiStatus");
if (status && resp.message) status.textContent = resp.message;
return;
}
} catch (e) {
// 启动期任何异常都不打扰用户
console.warn("auto-reconnect failed", e);
}
}
async function wifiScan() {
const btn = $("btnWifiScan");
const status = $("wifiStatus");
const results = $("wifiScanResults");
if (btn) {
btn.disabled = true;
btn.textContent = "扫描中...";
}
if (status) status.textContent = "正在扫描局域网...";
if (results) {
results.style.display = "none";
results.innerHTML = "";
}
try {
const resp = await apiPost("/api/wifi/scan", {});
if (!resp || resp.ok === false) {
const err = (resp && resp.error) || "扫描失败";
appendLog([`[WiFi ADB] 扫描失败: ${err}`]);
if (status) status.textContent = `扫描失败: ${err}`;
return;
}
const devs = Array.isArray(resp.devices) ? resp.devices : [];
const subnet = resp.subnet || "";
if (!devs.length) {
appendLog([`[WiFi ADB] 扫描完成 (${subnet}),未发现开放 5555 端口的设备`]);
if (status) status.textContent = `扫描完成 (${subnet}),未发现设备`;
return;
}
appendLog([
`[WiFi ADB] 扫描完成 (${subnet}),发现 ${devs.length} 台候选: ` +
devs.map((d) => `${d.target}(${d.state})`).join(", "),
]);
// 单个 connected:自动选中
const connected = devs.filter((d) => d.state === "connected");
if (connected.length === 1 && devs.length === 1) {
const d = connected[0];
const ipInput = $("wifi_ip");
if (ipInput) ipInput.value = d.target;
if (status)
status.textContent =
`已发现并连接 ${d.target}` + (d.model ? ` (${d.model})` : "") + ",已记住";
// 刷新设备下拉
try {
await refreshDevices();
} catch (_) {}
return;
}
// 多个候选:渲染列表,点击就填回 IP
if (results) {
results.style.display = "block";
const lines = devs.map((d) => {
const safeTarget = String(d.target || "").replace(/"/g, "&quot;");
const stateColor =
d.state === "connected" ? "#0a7d2c" :
d.state === "unauthorized" ? "#b35900" : "#888";
return (
`<div style="margin:4px 0; cursor:pointer; padding:4px 6px; border:1px solid #ddd; border-radius:4px;" ` +
`data-target="${safeTarget}" data-state="${d.state}">` +
`<b>${safeTarget}</b> ` +
`<span style="color:${stateColor}">[${d.state}]</span> ` +
(d.model ? ` <span style="color:#555">${d.model}</span>` : "") +
`</div>`
);
});
results.innerHTML =
`<div style="margin-bottom:4px; color:#555;">点击下方设备使用:</div>` +
lines.join("");
results.querySelectorAll("[data-target]").forEach((el) => {
el.addEventListener("click", () => {
const target = el.getAttribute("data-target");
const state = el.getAttribute("data-state");
if (state !== "connected") {
appendLog([
`[WiFi ADB] ${target} 状态=${state},请先在手机上确认 ADB 调试授权`,
]);
return;
}
const ipInput = $("wifi_ip");
if (ipInput) ipInput.value = target;
if (status) status.textContent = `已选 ${target}`;
appendLog([`[WiFi ADB] 已选 ${target}`]);
try {
refreshDevices();
} catch (_) {}
});
});
}
if (status) status.textContent = `扫描完成,发现 ${devs.length} 台设备`;
} catch (e) {
appendLog([`[WiFi ADB] 扫描异常: ${e}`]);
if (status) status.textContent = `扫描异常: ${e}`;
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = "扫描 WiFi";
}
}
}
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 = `
<div><strong>当前位置:</strong>${room_pos}</div>
<div><strong>当前直播间(清洗后):</strong>${escapeHtml(current_room_title || '-') }</div>
<div><strong>当前直播间原文:</strong>${escapeHtml(current_room_title_raw || '-') }</div>
<div><strong>预约数量:</strong>${reservations.length}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
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 = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">${item.prize_value_yuan || 0}元</span>
</div>
<div class="reservationBody">
<div><strong>内容:</strong>${escapeHtml(item.content || '-')}</div>
<div><strong>开奖时间:</strong>${item.future_str || '-'}</div>
<div><strong>剩余时间:</strong><span class="reservationRemain">${remainStr}</span></div>
<div><strong>发现位置:</strong>${item.pos_seen || 0}</div>
<div><strong>直播间(清洗后):</strong>${escapeHtml(item.room_title || '-')}</div>
<div><strong>直播间原文:</strong>${escapeHtml(item.room_title_raw || '-')}</div>
</div>
`;
list.appendChild(card);
});
container.appendChild(list);
// 恢复滚动位置(若有)
try { list.scrollTop = prevScroll; } catch (e) { /* ignore */ }
} catch (e) {
console.error("poll reservations failed:", e);
const container = $("reservationsContent");
if (!container) return;
clearEl(container);
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = `预约信息获取失败:${e?.message || e}`;
container.appendChild(hint);
}
}
async function pollHighValueRooms() {
try {
const data = await apiGet(`/api/high-value-rooms?t=${Date.now()}`);
const container = $("highValueRoomsContent");
if (!container) return;
// 保留上次滚动位置
const prevList = container.querySelector('.reservationsList');
const prevScroll = prevList ? prevList.scrollTop : 0;
clearEl(container);
const rooms = Array.isArray(data.rooms) ? data.rooms : [];
const updated_ts = Number(data.updated_ts) || 0;
const reason = String(data.reason || "");
const total = Number(data.total) || rooms.length;
const info = document.createElement("div");
info.className = "reservationsInfo";
info.innerHTML = `
<div><strong>记录数量:</strong>${total}</div>
<div class="hint">更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}</div>
<div class="hint">原因:${escapeHtml(reason || '-') }</div>
`;
container.appendChild(info);
if (rooms.length === 0) {
const hint = document.createElement("div");
hint.className = "hint";
hint.textContent = "暂无记录";
container.appendChild(hint);
return;
}
const list = document.createElement("div");
list.className = "reservationsList";
rooms.forEach((item, idx) => {
const card = document.createElement("div");
card.className = "reservationItem";
const roomTitle = String(item.room_title || "-");
const roomRaw = String(item.room_title_raw_last || "-");
const posSeen = (typeof item.pos_seen === "number") ? item.pos_seen : ((item.pos_seen === null || typeof item.pos_seen === "undefined") ? "-" : String(item.pos_seen));
const firstSeen = Number(item.first_seen_ts) || 0;
const lastSeen = Number(item.last_seen_ts) || 0;
const seenCount = Number(item.seen_count) || 0;
const maxVal = (item.max_prize_value_yuan === null || typeof item.max_prize_value_yuan === "undefined") ? "-" : String(item.max_prize_value_yuan);
const lastVal = (item.last_prize_value_yuan === null || typeof item.last_prize_value_yuan === "undefined") ? "-" : String(item.last_prize_value_yuan);
card.innerHTML = `
<div class="reservationHeader">
<span class="reservationIndex">#${idx + 1}</span>
<span class="reservationValue">max ${escapeHtml(maxVal)}元</span>
</div>
<div class="reservationBody">
<div><strong>直播间(清洗后):</strong>${escapeHtml(roomTitle)}</div>
<div><strong>直播间原文:</strong>${escapeHtml(roomRaw)}</div>
<div><strong>最近位置:</strong>${escapeHtml(posSeen)}</div>
<div><strong>首次记录:</strong>${escapeHtml(fmtTime(firstSeen))}</div>
<div><strong>最近记录:</strong>${escapeHtml(fmtTime(lastSeen))}</div>
<div><strong>记录次数:</strong>${escapeHtml(seenCount)}</div>
<div><strong>最近价值:</strong>${escapeHtml(lastVal)}元</div>
</div>
`;
// 让每条记录的 header 可点击以折叠/展开本条详情
list.appendChild(card);
try {
const header = card.querySelector(`.${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);
}