const csrfMeta = document.getElementById("csrf-meta"); const refresh = document.getElementById("refresh"); const form = document.getElementById("install-form"); const status = document.getElementById("install-status"); const facts = document.getElementById("install-facts"); const output = document.getElementById("install-output"); const serverURLInput = form ? form.querySelector("input[name='server_url']") : null; const printerIDInput = form ? form.querySelector("input[name='printer_id']") : null; const hostTypeInput = form ? form.querySelector("select[name='host_type']") : null; const passwordInput = form ? form.querySelector("input[name='password']") : null; let sessionCSRF = csrfMeta ? csrfMeta.content : ""; const installContext = new URL(window.location.href); let activeInstallJobID = ""; let activeInstallPollTimer = null; if (serverURLInput && !serverURLInput.value) { const host = window.location.hostname; if (host !== "localhost" && host !== "127.0.0.1" && host !== "::1") { serverURLInput.value = window.location.origin; } } if (printerIDInput && !printerIDInput.value) { const printerID = installContext.searchParams.get("printer_id"); if (printerID) { printerIDInput.value = printerID; } } if (hostTypeInput) { const hostType = installContext.searchParams.get("host_type"); if (hostType) { hostTypeInput.value = hostType; } } if (passwordInput && !passwordInput.value && printerIDInput && printerIDInput.value) { try { const storedPassword = sessionStorage.getItem(`ka-ssh-password:${printerIDInput.value.trim()}`) || ""; if (storedPassword) { passwordInput.value = storedPassword; } } catch { // Ignore session storage failures. } } if (serverURLInput && !serverURLInput.value) { const serverURL = installContext.searchParams.get("server_url"); if (serverURL) { serverURLInput.value = serverURL; } } function setStatus(message, isError = false) { if (!status) { return; } if (!message) { status.hidden = true; status.textContent = ""; status.className = "form-message"; return; } status.hidden = false; status.textContent = message; status.className = isError ? "form-message error" : "form-message success"; } async function loadSession() { const response = await fetch("/api/session", { credentials: "same-origin" }); if (response.status === 401) { window.location.href = "/login"; return null; } const session = await response.json(); if (!session.authenticated) { window.location.href = "/login"; return null; } if (session.is_admin !== true) { window.location.href = "/dashboard"; return null; } if (session.csrf_token) { sessionCSRF = session.csrf_token; } return session; } async function preloadInstallDetails() { if (!printerIDInput || !printerIDInput.value) { return; } const printerID = printerIDInput.value.trim(); if (!printerID) { return; } try { const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, { credentials: "same-origin", }); if (!response.ok) { return; } const payload = await response.json(); const install = payload && payload.settings ? payload.settings.install : null; if (!install) { return; } if (serverURLInput && !serverURLInput.value && install.server_url) { serverURLInput.value = install.server_url; } const hostInput = form ? form.querySelector("input[name='host']") : null; const portInput = form ? form.querySelector("input[name='port']") : null; const usernameInput = form ? form.querySelector("input[name='username']") : null; const moonrakerInput = form ? form.querySelector("input[name='moonraker_url']") : null; const uiURLInput = form ? form.querySelector("input[name='ui_url']") : null; const uiAutoDetectInput = form ? form.querySelector("input[name='ui_auto_detect']") : null; const hostTypeSelect = form ? form.querySelector("select[name='host_type']") : null; if (hostInput && !hostInput.value && install.host) { hostInput.value = install.host; } if (portInput && !portInput.value && install.port) { portInput.value = String(install.port); } if (usernameInput && !usernameInput.value && install.username) { usernameInput.value = install.username; } if (moonrakerInput && !moonrakerInput.value && install.moonraker_url) { moonrakerInput.value = install.moonraker_url; } if (uiURLInput && !uiURLInput.value && install.ui_url) { uiURLInput.value = install.ui_url; } if (uiAutoDetectInput && install.ui_auto_detect !== undefined) { uiAutoDetectInput.checked = Boolean(install.ui_auto_detect); } if (hostTypeSelect && install.host_type) { hostTypeSelect.value = String(install.host_type); } } catch { return; } } async function runInstall(event) { event.preventDefault(); clearInstallPollTimer(); activeInstallJobID = ""; const data = new FormData(form); const serverURLResult = validateServerURL(String(data.get("server_url") || "").trim()); if (!serverURLResult.ok) { setStatus(serverURLResult.error, true); if (output) { output.textContent = serverURLResult.error; } return; } if (serverURLInput) { serverURLInput.value = serverURLResult.value; } setStatus("Installing printer agent...", false); if (facts) { facts.innerHTML = `
Status
Installing
`; } const payload = { host: String(data.get("host") || "").trim(), server_url: serverURLResult.value, port: Number(data.get("port") || 22), username: String(data.get("username") || "").trim(), password: String(data.get("password") || ""), host_type: String(data.get("host_type") || "standard").trim() || "standard", printer_id: String(data.get("printer_id") || "").trim(), moonraker_url: String(data.get("moonraker_url") || "").trim(), ui_url: String(data.get("ui_url") || "").trim(), ui_auto_detect: Boolean(data.get("ui_auto_detect")), }; try { const response = await fetch("/api/install/ssh", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json", "X-CSRF-Token": sessionCSRF, }, body: JSON.stringify(payload), }); const text = await response.text(); let body = null; try { body = text ? JSON.parse(text) : null; } catch { body = null; } if (response.status === 202 || (response.ok && body && body.job_id)) { const jobID = body?.job_id || ""; if (!jobID) { const message = "Installer job started but no job ID was returned."; setStatus(message, true); if (output) { output.textContent = message; } return; } activeInstallJobID = jobID; setStatus(body?.message || "Installer job started.", false); renderInstallJob({ id: jobID, status: body?.status || "queued", stage: body?.status || "queued", message: body?.message || "Queued installer job.", steps: [{ at: new Date().toISOString(), stage: body?.status || "queued", message: body?.message || "Queued installer job.", }], output: body?.message || "Queued installer job.", }, true); pollInstallJob(jobID); return; } if (!response.ok) { const message = body && body.error ? body.error : text || `Install failed (${response.status})`; setStatus(message, true); if (output) { output.textContent = text || message; } if (facts) { facts.innerHTML = `
Status
Failed
`; } return; } if (body) { renderInstallJob({ id: body.job_id || "", status: "failed", stage: "failed", message: body.error || `Install failed (${response.status})`, output: text || body.error || "", }, true); } } catch (error) { const message = error instanceof Error ? error.message : "Unable to install printer agent."; setStatus(message, true); if (output) { output.textContent = message; } if (facts) { facts.innerHTML = `
Status
Failed
`; } } } async function pollInstallJob(jobID) { clearInstallPollTimer(); if (!jobID) { return; } try { const response = await fetch(`/api/install/ssh/jobs/${encodeURIComponent(jobID)}`, { credentials: "same-origin", }); if (!response.ok) { const text = await response.text(); setStatus(text || `Install job poll failed (${response.status})`, true); if (output) { output.textContent = text || `Install job poll failed (${response.status})`; } return; } const job = await response.json(); renderInstallJob(job, false); if (job && (job.status === "queued" || job.status === "running")) { activeInstallPollTimer = window.setTimeout(() => { pollInstallJob(jobID); }, 1000); return; } if (job && job.result) { renderInstallResponse(job.result); } } catch (error) { const message = error instanceof Error ? error.message : "Unable to poll installer job."; setStatus(message, true); if (output) { output.textContent = message; } } } function renderInstallJob(job, immediate = false) { if (!job) { return; } const statusLabel = String(job.status || "queued"); const stageLabel = String(job.stage || statusLabel); const message = String(job.message || ""); const lines = []; if (job.steps && job.steps.length) { for (const step of job.steps) { const stamp = step.at ? new Date(step.at).toLocaleTimeString() : ""; const prefix = step.stage ? `[${step.stage}]` : "[step]"; lines.push(`${stamp} ${prefix} ${step.message || ""}`.trim()); } } else if (job.output) { const extra = String(job.output).trim(); if (extra) { lines.push(extra); } } if (facts) { facts.innerHTML = [ fact("Status", capitalize(statusLabel)), fact("Stage", stageLabel), fact("Message", message || "Waiting for installer output."), fact("Printer", job.printer_id || printerIDInput?.value || "unknown"), fact("Host", job.host ? `${job.host}:${job.port || 22}` : String(form?.querySelector("input[name='host']")?.value || "unknown")), fact("Host type", job.host_type || String(form?.querySelector("select[name='host_type']")?.value || "standard")), ].join(""); } if (output) { output.textContent = lines.length ? lines.join("\n") : (message || "Waiting for installer output."); output.scrollTop = output.scrollHeight; } if (message) { setStatus(message, statusLabel === "failed"); } else if (!immediate) { setStatus(statusLabel === "running" ? "Installer is still running..." : "Installer job queued.", false); } } function renderInstallResponse(body) { const printerID = body?.printer_id || String(printerIDInput?.value || "unknown"); const postInstallState = body?.post_install_connected === true ? "Confirmed" : "Pending"; const postInstallMessage = body?.post_install_message || "Waiting for agent callback."; setStatus(body?.post_install_connected === true ? `Installed agent for ${printerID} and confirmed callback.` : `Installed agent for ${printerID}. Waiting for callback.`, false); if (facts) { facts.innerHTML = [ fact("Status", "Installed"), fact("Printer", printerID), fact("Host", `${body?.host || String(form?.querySelector("input[name='host']")?.value || "unknown")}:${body?.port || Number(form?.querySelector("input[name='port']")?.value || 22)}`), fact("Host type", body?.host_type || String(form?.querySelector("select[name='host_type']")?.value || "standard")), fact("Remote host", body?.remote_host || "unknown"), fact("Server", body?.server_url || String(form?.querySelector("input[name='server_url']")?.value || "unknown")), fact("Binary", body?.binary_source || "unknown"), fact("Config", body?.config_path || "unknown"), fact("Post-install", postInstallState), fact("Callback", postInstallMessage), fact("Rollback", body?.rollback_performed ? "Available" : "Not needed"), fact("Rollback detail", body?.rollback_message || "None"), ].join(""); } if (output) { output.textContent = JSON.stringify(body || {}, null, 2); output.scrollTop = output.scrollHeight; } if (passwordInput && passwordInput.value) { try { const pid = String(printerIDInput && printerIDInput.value ? printerIDInput.value.trim() : ""); if (pid) { sessionStorage.setItem(`ka-ssh-password:${pid}`, passwordInput.value); } } catch { // Ignore session storage failures. } } } function clearInstallPollTimer() { if (activeInstallPollTimer) { window.clearTimeout(activeInstallPollTimer); activeInstallPollTimer = null; } } function capitalize(value) { const text = String(value || ""); if (!text) { return ""; } return text.charAt(0).toUpperCase() + text.slice(1); } function fact(label, value) { return `
${escapeHTML(label)}
${escapeHTML(value)}
`; } function validateServerURL(value) { if (!value) { return { ok: false, error: "Server URL is required." }; } try { const url = new URL(value); if (url.protocol !== "http:" && url.protocol !== "https:") { return { ok: false, error: "Server URL must start with http:// or https://." }; } const host = url.hostname.toLowerCase(); if (host === "localhost" || host === "127.0.0.1" || host === "::1") { return { ok: false, error: "Server URL must be reachable from the printer host." }; } return { ok: true, value: url.origin.replace(/\/$/, "") }; } catch { return { ok: false, error: "Server URL must be a valid http:// or https:// URL." }; } } function escapeHTML(value) { return String(value) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } refresh.addEventListener("click", () => window.location.reload()); form.addEventListener("submit", runInstall); loadSession().then(() => preloadInstallDetails());