381 lines
17 KiB
JavaScript
381 lines
17 KiB
JavaScript
const refresh = document.getElementById("refresh");
|
|
const title = document.getElementById("printer-title");
|
|
const status = document.getElementById("printer-status");
|
|
const identityFacts = document.getElementById("identity-facts");
|
|
const settingsSummary = document.getElementById("settings-summary");
|
|
const settingsSyncPill = document.getElementById("settings-sync-pill");
|
|
const settingsMessage = document.getElementById("settings-message");
|
|
const settingsForm = document.getElementById("printer-settings-form");
|
|
const settingsDisplayName = document.getElementById("settings-display-name");
|
|
const settingsControlMode = document.getElementById("settings-control-mode");
|
|
const settingsUIURL = document.getElementById("settings-ui-url");
|
|
const settingsUIAutoDetect = document.getElementById("settings-ui-auto-detect");
|
|
const notificationsSummary = document.getElementById("notifications-summary");
|
|
const notificationsPill = document.getElementById("notifications-pill");
|
|
const notificationsForm = document.getElementById("printer-notifications-form");
|
|
const settingsNotificationsEnabled = document.getElementById("settings-notifications-enabled");
|
|
const settingsNotifyStarted = document.getElementById("settings-notify-started");
|
|
const settingsNotifyPaused = document.getElementById("settings-notify-paused");
|
|
const settingsNotifyResumed = document.getElementById("settings-notify-resumed");
|
|
const settingsNotifyCompleted = document.getElementById("settings-notify-completed");
|
|
const settingsNotifyCanceled = document.getElementById("settings-notify-canceled");
|
|
const settingsNotifyFailed = document.getElementById("settings-notify-failed");
|
|
const settingsNotifyFirstLayer = document.getElementById("settings-notify-first-layer");
|
|
const settingsNotifyThirdLayer = document.getElementById("settings-notify-third-layer");
|
|
const settingsNotificationSnapshotCamera = document.getElementById("settings-notification-snapshot-camera");
|
|
const settingsAppliedSummary = document.getElementById("settings-applied-summary");
|
|
const settingsAppliedPill = document.getElementById("settings-applied-pill");
|
|
const settingsAppliedFacts = document.getElementById("settings-applied-facts");
|
|
const settingsUpgradeLink = document.getElementById("settings-upgrade-link");
|
|
const logoutCSRF = document.getElementById("logout-csrf");
|
|
const backLink = document.getElementById("back-link");
|
|
const agentLink = document.getElementById("agent-link");
|
|
const uiLink = document.getElementById("ui-link");
|
|
const printerOpenLink = document.getElementById("printer-open-link");
|
|
const adminLink = document.getElementById("admin-link");
|
|
|
|
const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").replace(/\/settings\/?$/, ""));
|
|
let settingsDirty = false;
|
|
let lastHealth = null;
|
|
|
|
if (printerID) {
|
|
backLink.href = `/printers/${encodeURIComponent(printerID)}`;
|
|
printerOpenLink.href = `/printers/${encodeURIComponent(printerID)}`;
|
|
if (agentLink) {
|
|
agentLink.href = `/printers/${encodeURIComponent(printerID)}/agent`;
|
|
}
|
|
uiLink.href = `/printers/${encodeURIComponent(printerID)}/ui/`;
|
|
if (settingsUpgradeLink) {
|
|
settingsUpgradeLink.href = `/install?printer_id=${encodeURIComponent(printerID)}`;
|
|
}
|
|
if (adminLink) {
|
|
adminLink.href = `/admin?printer_id=${encodeURIComponent(printerID)}`;
|
|
}
|
|
}
|
|
|
|
async function loadSession() {
|
|
const response = await fetch("/api/session", { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
const session = await response.json();
|
|
if (!session.authenticated) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
window.__KA_SESSION__ = session;
|
|
logoutCSRF.value = session.csrf_token || "";
|
|
}
|
|
|
|
async function loadPrinter() {
|
|
if (!printerID) {
|
|
title.textContent = "Unknown printer";
|
|
return;
|
|
}
|
|
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
identityFacts.innerHTML = fact("Printer", `Unavailable (${response.status})`);
|
|
setStatus("Not reachable", false);
|
|
return;
|
|
}
|
|
const data = await response.json();
|
|
const health = data.health || {};
|
|
const settings = data.settings || {};
|
|
const label = settings.display_name || printerID;
|
|
lastHealth = health;
|
|
|
|
title.textContent = label;
|
|
setStatus(data.connected && health.moonraker_reachable ? "Reachable" : "Not reachable", data.connected && health.moonraker_reachable);
|
|
identityFacts.innerHTML = [
|
|
fact("Printer ID", printerID),
|
|
fact("Display name", settings.display_name || "Not set"),
|
|
fact("Agent hostname", health.hostname || "Unknown"),
|
|
fact("Agent version", health.agent_version || "Unknown"),
|
|
fact("Moonraker", health.moonraker_state || "Unknown"),
|
|
fact("UI source", health.ui_source || "Unknown"),
|
|
].join("");
|
|
|
|
if (settingsDirty) {
|
|
return;
|
|
}
|
|
settingsDisplayName.value = settings.display_name || "";
|
|
settingsControlMode.value = settings.control_mode || "readonly";
|
|
settingsUIURL.value = settings.ui_url || "";
|
|
settingsUIAutoDetect.checked = Boolean(settings.ui_auto_detect);
|
|
if (settingsNotificationsEnabled) {
|
|
settingsNotificationsEnabled.checked = Boolean(settings.print_notifications_enabled);
|
|
}
|
|
if (settingsNotifyStarted) {
|
|
settingsNotifyStarted.checked = Boolean(settings.notify_print_started);
|
|
}
|
|
if (settingsNotifyPaused) {
|
|
settingsNotifyPaused.checked = Boolean(settings.notify_print_paused);
|
|
}
|
|
if (settingsNotifyResumed) {
|
|
settingsNotifyResumed.checked = Boolean(settings.notify_print_resumed);
|
|
}
|
|
if (settingsNotifyCompleted) {
|
|
settingsNotifyCompleted.checked = Boolean(settings.notify_print_completed);
|
|
}
|
|
if (settingsNotifyCanceled) {
|
|
settingsNotifyCanceled.checked = Boolean(settings.notify_print_canceled);
|
|
}
|
|
if (settingsNotifyFailed) {
|
|
settingsNotifyFailed.checked = Boolean(settings.notify_print_failed);
|
|
}
|
|
if (settingsNotifyFirstLayer) {
|
|
settingsNotifyFirstLayer.checked = Boolean(settings.notify_print_first_layer);
|
|
}
|
|
if (settingsNotifyThirdLayer) {
|
|
settingsNotifyThirdLayer.checked = Boolean(settings.notify_print_third_layer);
|
|
}
|
|
renderSnapshotCameraOptions(health.cameras || [], settings.notification_snapshot_camera || "");
|
|
renderNotificationState(settings);
|
|
if (settingsSyncPill) {
|
|
const syncState = computeSettingsSync(settings, health);
|
|
settingsSyncPill.textContent = syncState.state;
|
|
settingsSyncPill.classList.toggle("ok", syncState.synced);
|
|
settingsSyncPill.classList.toggle("warn", !syncState.synced);
|
|
if (settingsSummary) {
|
|
settingsSummary.textContent = syncState.detail;
|
|
}
|
|
}
|
|
renderAppliedState(data.settings_synced, data.settings_sync_state, data.settings_sync_detail, health);
|
|
if (settingsUpgradeLink) {
|
|
settingsUpgradeLink.href = installURL(settings.install);
|
|
}
|
|
}
|
|
|
|
async function saveSettings(event) {
|
|
event.preventDefault();
|
|
setSettingsMessage("Saving settings...", true);
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, {
|
|
method: "PATCH",
|
|
credentials: "same-origin",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-CSRF-Token": logoutCSRF.value || "",
|
|
},
|
|
body: JSON.stringify({
|
|
display_name: settingsDisplayName.value,
|
|
control_mode: settingsControlMode.value,
|
|
ui_url: settingsUIURL.value,
|
|
ui_auto_detect: settingsUIAutoDetect.checked,
|
|
}),
|
|
});
|
|
if (!response.ok) {
|
|
const error = await response.text();
|
|
setSettingsMessage(error || `Failed to save settings (${response.status})`, false);
|
|
return;
|
|
}
|
|
const payload = await response.json().catch(() => ({}));
|
|
settingsDirty = false;
|
|
const syncState = String(payload.settings_sync_state || (payload.settings_synced ? "Synced" : "Pending"));
|
|
const syncDetail = String(payload.settings_sync_detail || "").trim();
|
|
setSettingsMessage(syncDetail ? `Saved. ${syncDetail}` : `Saved. ${syncState}.`, true);
|
|
renderAppliedState(payload.settings_synced, payload.settings_sync_state, payload.settings_sync_detail, lastHealth);
|
|
if (settingsUpgradeLink) {
|
|
settingsUpgradeLink.href = installURL(payload.install || null);
|
|
}
|
|
await loadPrinter();
|
|
}
|
|
|
|
async function saveNotifications(event) {
|
|
event.preventDefault();
|
|
setSettingsMessage("Saving notification settings...", true);
|
|
const payload = {
|
|
print_notifications_enabled: Boolean(settingsNotificationsEnabled && settingsNotificationsEnabled.checked),
|
|
notify_print_started: Boolean(settingsNotifyStarted && settingsNotifyStarted.checked),
|
|
notify_print_paused: Boolean(settingsNotifyPaused && settingsNotifyPaused.checked),
|
|
notify_print_resumed: Boolean(settingsNotifyResumed && settingsNotifyResumed.checked),
|
|
notify_print_completed: Boolean(settingsNotifyCompleted && settingsNotifyCompleted.checked),
|
|
notify_print_canceled: Boolean(settingsNotifyCanceled && settingsNotifyCanceled.checked),
|
|
notify_print_failed: Boolean(settingsNotifyFailed && settingsNotifyFailed.checked),
|
|
notify_print_first_layer: Boolean(settingsNotifyFirstLayer && settingsNotifyFirstLayer.checked),
|
|
notify_print_third_layer: Boolean(settingsNotifyThirdLayer && settingsNotifyThirdLayer.checked),
|
|
notification_snapshot_camera: settingsNotificationSnapshotCamera ? settingsNotificationSnapshotCamera.value : "",
|
|
};
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}/settings`, {
|
|
method: "PATCH",
|
|
credentials: "same-origin",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-CSRF-Token": logoutCSRF.value || "",
|
|
},
|
|
body: JSON.stringify(payload),
|
|
});
|
|
if (!response.ok) {
|
|
const error = await response.text();
|
|
setSettingsMessage(error || `Failed to save notification settings (${response.status})`, false);
|
|
return;
|
|
}
|
|
const payloadResponse = await response.json().catch(() => ({}));
|
|
settingsDirty = false;
|
|
const syncState = String(payloadResponse.settings_sync_state || (payloadResponse.settings_synced ? "Synced" : "Pending"));
|
|
const syncDetail = String(payloadResponse.settings_sync_detail || "").trim();
|
|
setSettingsMessage(syncDetail ? `Notification settings saved. ${syncDetail}` : `Notification settings saved. ${syncState}.`, true);
|
|
renderAppliedState(payloadResponse.settings_synced, payloadResponse.settings_sync_state, payloadResponse.settings_sync_detail, lastHealth);
|
|
if (settingsUpgradeLink) {
|
|
settingsUpgradeLink.href = installURL(payloadResponse.install || null);
|
|
}
|
|
await loadPrinter();
|
|
}
|
|
|
|
function installURL(install) {
|
|
const params = new URLSearchParams({ printer_id: printerID });
|
|
const hostType = String(install && install.host_type ? install.host_type : "").trim().toLowerCase();
|
|
if (hostType) {
|
|
params.set("host_type", hostType);
|
|
}
|
|
return `/install?${params.toString()}`;
|
|
}
|
|
|
|
function setStatus(label, ok) {
|
|
status.textContent = label;
|
|
status.classList.toggle("ok", ok);
|
|
status.classList.toggle("warn", !ok);
|
|
}
|
|
|
|
function setSettingsMessage(text, ok) {
|
|
if (!settingsMessage) {
|
|
return;
|
|
}
|
|
if (!text) {
|
|
settingsMessage.hidden = true;
|
|
settingsMessage.textContent = "";
|
|
settingsMessage.className = "form-message";
|
|
return;
|
|
}
|
|
settingsMessage.hidden = false;
|
|
settingsMessage.textContent = text;
|
|
settingsMessage.className = ok ? "form-message success" : "form-message error";
|
|
}
|
|
|
|
function renderAppliedState(settingsSynced, settingsSyncState, settingsSyncDetail, health) {
|
|
if (!settingsAppliedPill || !settingsAppliedSummary || !settingsAppliedFacts) {
|
|
return;
|
|
}
|
|
const synced = Boolean(settingsSynced);
|
|
const state = String(settingsSyncState || (synced ? "Synced" : "Pending"));
|
|
settingsAppliedPill.textContent = state;
|
|
settingsAppliedPill.classList.toggle("ok", synced);
|
|
settingsAppliedPill.classList.toggle("warn", !synced);
|
|
settingsAppliedSummary.textContent = String(settingsSyncDetail || (synced ? "Agent acknowledged the latest saved settings." : "Waiting for the agent to confirm the latest settings."));
|
|
const sessionVersion = String(window.__KA_SESSION__ && window.__KA_SESSION__.server_version ? window.__KA_SESSION__.server_version : "dev");
|
|
|
|
const appliedMode = String(health && health.control_mode ? health.control_mode : "Unknown");
|
|
const appliedURL = String(health && health.ui_url ? health.ui_url : "Unset");
|
|
const uiSource = String(health && health.ui_source ? health.ui_source : "Unknown");
|
|
const uiReachable = health ? (health.ui_reachable ? "Yes" : "No") : "Unknown";
|
|
const moonraker = String(health && health.moonraker_state ? health.moonraker_state : "Unknown");
|
|
const heartbeat = health && health.checked_at_unix ? new Date(health.checked_at_unix * 1000).toLocaleString() : "Unknown";
|
|
const currentVersion = String(health && health.agent_version ? health.agent_version : "Unknown");
|
|
const upgradeAvailable = currentVersion !== "Unknown" && sessionVersion !== "Unknown" && currentVersion !== sessionVersion;
|
|
if (settingsUpgradeLink && printerID) {
|
|
settingsUpgradeLink.href = `/install?printer_id=${encodeURIComponent(printerID)}`;
|
|
settingsUpgradeLink.textContent = upgradeAvailable ? "Upgrade agent" : "Reinstall agent";
|
|
}
|
|
settingsAppliedFacts.innerHTML = [
|
|
fact("Applied mode", appliedMode),
|
|
fact("Applied UI URL", appliedURL),
|
|
fact("UI source", uiSource),
|
|
fact("UI reachable", uiReachable),
|
|
fact("Moonraker", moonraker),
|
|
fact("Last heartbeat", heartbeat),
|
|
fact("Current agent", currentVersion),
|
|
fact("Available agent", sessionVersion),
|
|
].join("");
|
|
}
|
|
|
|
function renderNotificationState(settings) {
|
|
if (!notificationsPill || !notificationsSummary) {
|
|
return;
|
|
}
|
|
const enabled = Boolean(settings && settings.print_notifications_enabled);
|
|
const deliveryReady = Boolean(settings && settings.notification_delivery_ready);
|
|
const deliverySource = String(settings && settings.notification_delivery_source ? settings.notification_delivery_source : "");
|
|
const lastError = String(settings && settings.last_notification_error ? settings.last_notification_error : "").trim();
|
|
const snapshotCamera = String(settings && settings.notification_snapshot_camera ? settings.notification_snapshot_camera : "").trim();
|
|
const selected = [];
|
|
if (settings && settings.notify_print_started) selected.push("started");
|
|
if (settings && settings.notify_print_paused) selected.push("paused");
|
|
if (settings && settings.notify_print_resumed) selected.push("resumed");
|
|
if (settings && settings.notify_print_completed) selected.push("completed");
|
|
if (settings && settings.notify_print_canceled) selected.push("canceled");
|
|
if (settings && settings.notify_print_failed) selected.push("failed");
|
|
if (settings && settings.notify_print_first_layer) selected.push("first layer");
|
|
if (settings && settings.notify_print_third_layer) selected.push("third layer");
|
|
const ready = enabled && selected.length > 0;
|
|
notificationsPill.textContent = ready ? "On" : "Off";
|
|
notificationsPill.classList.toggle("ok", ready);
|
|
notificationsPill.classList.toggle("warn", !ready);
|
|
if (!enabled) {
|
|
notificationsSummary.textContent = "Print notifications are disabled for this printer.";
|
|
} else if (selected.length === 0) {
|
|
notificationsSummary.textContent = "Enable at least one notification type for this printer.";
|
|
} else if (!deliveryReady) {
|
|
notificationsSummary.textContent = "Notification types are enabled for this printer, but Telegram delivery is not configured in Admin yet.";
|
|
} else if (lastError) {
|
|
notificationsSummary.textContent = `Print notifications are enabled. Last send failed: ${lastError}`;
|
|
} else {
|
|
const cameraText = snapshotCamera ? ` Snapshot camera: ${snapshotCamera}.` : "";
|
|
notificationsSummary.textContent = `Print notifications are enabled for ${selected.join(", ")}. Telegram delivery is configured in Admin${deliverySource ? ` (${deliverySource})` : ""}.${cameraText}`;
|
|
}
|
|
}
|
|
|
|
function renderSnapshotCameraOptions(cameras, selectedCamera) {
|
|
if (!settingsNotificationSnapshotCamera) {
|
|
return;
|
|
}
|
|
const snapshotCameras = Array.isArray(cameras) ? cameras.filter((camera) => camera && camera.has_snapshot && String(camera.name || "").trim() !== "") : [];
|
|
const selected = String(selectedCamera || "").trim();
|
|
const options = ['<option value="">First snapshot-capable camera</option>'];
|
|
let hasSelected = selected === "";
|
|
snapshotCameras.forEach((camera) => {
|
|
const name = String(camera.name || "").trim();
|
|
if (name === selected) {
|
|
hasSelected = true;
|
|
}
|
|
options.push(`<option value="${escapeHTML(name)}">${escapeHTML(name)}</option>`);
|
|
});
|
|
if (selected && !hasSelected) {
|
|
options.push(`<option value="${escapeHTML(selected)}">${escapeHTML(selected)} (unavailable)</option>`);
|
|
}
|
|
settingsNotificationSnapshotCamera.innerHTML = options.join("");
|
|
settingsNotificationSnapshotCamera.value = selected;
|
|
settingsNotificationSnapshotCamera.disabled = snapshotCameras.length === 0 && selected === "";
|
|
}
|
|
|
|
refresh.addEventListener("click", loadPrinter);
|
|
if (settingsForm) {
|
|
settingsForm.addEventListener("submit", saveSettings);
|
|
settingsForm.addEventListener("input", () => {
|
|
settingsDirty = true;
|
|
});
|
|
settingsForm.addEventListener("change", () => {
|
|
settingsDirty = true;
|
|
});
|
|
}
|
|
if (notificationsForm) {
|
|
notificationsForm.addEventListener("submit", saveNotifications);
|
|
notificationsForm.addEventListener("input", () => {
|
|
settingsDirty = true;
|
|
});
|
|
notificationsForm.addEventListener("change", () => {
|
|
settingsDirty = true;
|
|
});
|
|
}
|
|
|
|
if (settingsNotificationSnapshotCamera) {
|
|
settingsNotificationSnapshotCamera.addEventListener("change", () => {
|
|
settingsDirty = true;
|
|
});
|
|
}
|
|
loadSession().then(loadPrinter);
|