const adminInstallLink = document.getElementById("admin-install-link"); const adminInstallCopy = document.getElementById("admin-install-copy"); const adminContext = document.getElementById("admin-context"); const adminNotificationsSummary = document.getElementById("admin-notifications-summary"); const adminNotificationsPill = document.getElementById("admin-notifications-pill"); const adminNotificationsForm = document.getElementById("admin-notifications-form"); const adminTelegramEnabled = document.getElementById("admin-telegram-enabled"); const adminTelegramCommandsEnabled = document.getElementById("admin-telegram-commands-enabled"); const adminTelegramBotToken = document.getElementById("admin-telegram-bot-token"); const adminTelegramChatID = document.getElementById("admin-telegram-chat-id"); const adminTelegramTestButton = document.getElementById("admin-telegram-test"); const adminTelegramTestResult = document.getElementById("admin-telegram-test-result"); const adminServerVersion = document.getElementById("admin-server-version"); const adminAvailableVersion = document.getElementById("admin-available-version"); const adminPrinters = document.getElementById("admin-printers"); const adminPrinterCount = document.getElementById("admin-printer-count"); let adminTelegramTokenSet = false; function getCSRFToken() { if (window.__KA_SESSION__ && window.__KA_SESSION__.csrf_token) { return String(window.__KA_SESSION__.csrf_token); } const logoutField = document.getElementById("logout-csrf"); return logoutField ? String(logoutField.value || "") : ""; } function getPrinterID() { const params = new URLSearchParams(window.location.search); return (params.get("printer_id") || "").trim(); } function updateContext() { const printerID = getPrinterID(); if (!printerID) { if (adminInstallCopy) { adminInstallCopy.textContent = "Connect to a printer host over SSH and install the agent."; } if (adminContext) { adminContext.textContent = "Manage printer installs, users, and audit history from one place."; } if (adminInstallLink) { adminInstallLink.href = "/install"; } return; } const encoded = encodeURIComponent(printerID); if (adminInstallLink) { adminInstallLink.href = `/install?printer_id=${encoded}`; } if (adminInstallCopy) { adminInstallCopy.textContent = `Install the agent for printer ${printerID}.`; } if (adminContext) { adminContext.textContent = `Printer context detected for ${printerID}.`; } } function renderVersions(session) { const version = String(session && session.server_version ? session.server_version : "dev"); if (adminServerVersion) { adminServerVersion.textContent = version; } if (adminAvailableVersion) { adminAvailableVersion.textContent = version; } } async function loadNotificationSettings() { if (!adminNotificationsForm) { return; } try { const response = await fetch("/api/notifications", { credentials: "same-origin" }); if (!response.ok) { if (adminNotificationsSummary) { adminNotificationsSummary.textContent = `Unable to load notification settings (${response.status}).`; } return; } const payload = await response.json(); const settings = payload.notifications || {}; if (adminTelegramEnabled) { adminTelegramEnabled.checked = Boolean(settings.telegram_enabled); } if (adminTelegramCommandsEnabled) { adminTelegramCommandsEnabled.checked = Boolean(settings.telegram_commands_enabled); } if (adminTelegramBotToken) { adminTelegramBotToken.value = String(settings.telegram_bot_token || ""); adminTelegramBotToken.placeholder = "123456:ABCDEF"; } adminTelegramTokenSet = Boolean(String(settings.telegram_bot_token || "").trim()); if (adminTelegramChatID) { adminTelegramChatID.value = settings.telegram_chat_id || ""; } renderNotificationSummary(settings); updateTelegramTestButtonState(); } catch (error) { if (adminNotificationsSummary) { adminNotificationsSummary.textContent = "Unable to load notification settings."; } } } async function saveNotificationSettings(event) { event.preventDefault(); if (!adminNotificationsForm) { return; } const payload = { telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), telegram_commands_enabled: Boolean(adminTelegramCommandsEnabled && adminTelegramCommandsEnabled.checked), telegram_chat_id: adminTelegramChatID ? adminTelegramChatID.value : "", }; if (adminTelegramBotToken && adminTelegramBotToken.value.trim() !== "") { payload.telegram_bot_token = adminTelegramBotToken.value.trim(); } const response = await fetch("/api/notifications", { method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json", "X-CSRF-Token": getCSRFToken(), }, body: JSON.stringify(payload), }); if (!response.ok) { const error = await response.text(); if (adminNotificationsSummary) { adminNotificationsSummary.textContent = error || `Failed to save notification settings (${response.status}).`; } return; } await loadNotificationSettings(); } function renderNotificationSummary(settings) { if (!adminNotificationsSummary || !adminNotificationsPill) { return; } const enabled = Boolean(settings && settings.telegram_enabled); const commandsEnabled = Boolean(settings && settings.telegram_commands_enabled); const tokenSet = Boolean(String(settings && settings.telegram_bot_token ? settings.telegram_bot_token : "").trim()) || Boolean(settings && settings.telegram_bot_token_set); const chatSet = Boolean(String(settings && settings.telegram_chat_id ? settings.telegram_chat_id : "").trim()); const ready = (enabled || commandsEnabled) && tokenSet && chatSet; adminNotificationsPill.textContent = ready ? "On" : "Off"; adminNotificationsPill.classList.toggle("ok", ready); adminNotificationsPill.classList.toggle("warn", !ready); if (!enabled && !commandsEnabled) { adminNotificationsSummary.textContent = "Telegram delivery and bot commands are disabled."; } else if (!tokenSet || !chatSet) { adminNotificationsSummary.textContent = "Telegram is enabled, but the bot token or chat ID is missing."; } else if (enabled && commandsEnabled) { adminNotificationsSummary.textContent = "Telegram delivery and bot commands are enabled."; } else if (enabled) { adminNotificationsSummary.textContent = "Telegram delivery is enabled; bot commands are disabled."; } else { adminNotificationsSummary.textContent = "Telegram bot commands are enabled; delivery is disabled."; } } function updateTelegramTestButtonState() { if (!adminTelegramTestButton) { return; } const tokenReady = Boolean(adminTelegramBotToken && adminTelegramBotToken.value.trim() !== ""); const chatReady = Boolean(adminTelegramChatID && adminTelegramChatID.value.trim() !== ""); adminTelegramTestButton.disabled = !(tokenReady && chatReady); } function renderTelegramTestResult(text, kind) { if (!adminTelegramTestResult) { return; } adminTelegramTestResult.textContent = text; adminTelegramTestResult.classList.remove("status-info", "status-ok", "status-error"); if (kind) { adminTelegramTestResult.classList.add(kind); } } async function sendTelegramTestNotification() { if (!adminNotificationsForm) { return; } const payload = { telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), }; const tokenValue = adminTelegramBotToken ? adminTelegramBotToken.value.trim() : ""; if (tokenValue !== "") { payload.telegram_bot_token = tokenValue; } const chatValue = adminTelegramChatID ? adminTelegramChatID.value.trim() : ""; if (chatValue !== "") { payload.telegram_chat_id = chatValue; } renderTelegramTestResult("Sending test notification...", "status-info"); if (adminTelegramTestButton) { adminTelegramTestButton.disabled = true; } try { const response = await fetch("/api/notifications/test", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", "X-CSRF-Token": getCSRFToken(), }, body: JSON.stringify(payload), }); const text = await response.text(); if (!response.ok) { renderTelegramTestResult(text || `Failed to send test notification (${response.status}).`, "status-error"); return; } let message = "Test notification sent."; try { const parsed = text ? JSON.parse(text) : {}; if (parsed && parsed.message) { message = String(parsed.message); } } catch (error) { // Keep the fallback message. } renderTelegramTestResult(message, "status-ok"); } catch (error) { renderTelegramTestResult("Unable to send test notification.", "status-error"); } finally { updateTelegramTestButtonState(); } } async function loadPrinters() { if (!adminPrinters) { return; } try { const response = await fetch("/api/printers", { credentials: "same-origin" }); if (!response.ok) { adminPrinters.innerHTML = `

Unable to load printers (${response.status}).

`; if (adminPrinterCount) { adminPrinterCount.textContent = "Unavailable"; } return; } const payload = await response.json(); const printers = Array.isArray(payload.printers) ? payload.printers : []; if (adminPrinterCount) { adminPrinterCount.textContent = `${printers.length} printer${printers.length === 1 ? "" : "s"}`; } if (printers.length === 0) { adminPrinters.innerHTML = `

No printers are connected right now.

`; return; } const availableVersion = String((window.__KA_SESSION__ && window.__KA_SESSION__.server_version) || "dev"); adminPrinters.innerHTML = printers.map((printer) => { const settings = printer.settings || {}; const health = printer.health || {}; const printerID = String(printer.printer_id || ""); const agentVersion = String(health.agent_version || "Unknown"); const versionMatch = agentVersion && availableVersion && agentVersion === availableVersion; const upgradeText = versionMatch ? "Reinstall" : "Upgrade"; const upgradeLink = printerID ? `/install?printer_id=${encodeURIComponent(printerID)}` : "/install"; return `
${escapeHTML(settings.display_name || printerID || "Unknown printer")}

${escapeHTML(printerID || "Unknown printer")}

Agent
${escapeHTML(agentVersion)}
Available
${escapeHTML(availableVersion)}
Open ${upgradeText}
`; }).join(""); } catch (error) { adminPrinters.innerHTML = `

Unable to load printers.

`; if (adminPrinterCount) { adminPrinterCount.textContent = "Unavailable"; } } } window.__KA_SESSION_PROMISE__ = window.__KA_SESSION_PROMISE__ || Promise.resolve(); window.__KA_SESSION_PROMISE__.finally(() => { updateContext(); renderVersions(window.__KA_SESSION__ || {}); loadNotificationSettings(); loadPrinters(); }); if (adminNotificationsForm) { adminNotificationsForm.addEventListener("submit", saveNotificationSettings); } if (adminTelegramBotToken) { adminTelegramBotToken.addEventListener("input", updateTelegramTestButtonState); } if (adminTelegramChatID) { adminTelegramChatID.addEventListener("input", updateTelegramTestButtonState); } if (adminTelegramCommandsEnabled) { adminTelegramCommandsEnabled.addEventListener("change", () => { renderNotificationSummary({ telegram_enabled: Boolean(adminTelegramEnabled && adminTelegramEnabled.checked), telegram_commands_enabled: Boolean(adminTelegramCommandsEnabled && adminTelegramCommandsEnabled.checked), telegram_bot_token: adminTelegramBotToken ? adminTelegramBotToken.value : "", telegram_bot_token_set: Boolean(adminTelegramBotToken && adminTelegramBotToken.value.trim() !== ""), telegram_chat_id: adminTelegramChatID ? adminTelegramChatID.value : "", }); }); } if (adminTelegramTestButton) { adminTelegramTestButton.addEventListener("click", sendTelegramTestNotification); } function escapeHTML(value) { return String(value) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); }