852 lines
31 KiB
JavaScript
852 lines
31 KiB
JavaScript
const refresh = document.getElementById("refresh");
|
|
const title = document.getElementById("printer-title");
|
|
const status = document.getElementById("printer-status");
|
|
const healthFacts = document.getElementById("health-facts");
|
|
const infoFacts = document.getElementById("info-facts");
|
|
const cameraList = document.getElementById("camera-list");
|
|
const healthLink = document.getElementById("health-link");
|
|
const infoLink = document.getElementById("info-link");
|
|
const printStatusLink = document.getElementById("print-status-link");
|
|
const recentJobsLink = document.getElementById("recent-jobs-link");
|
|
const printActionRow = document.getElementById("print-action-row");
|
|
const uiLink = document.getElementById("ui-link");
|
|
const uiFacts = document.getElementById("ui-facts");
|
|
const logoutCSRF = document.getElementById("logout-csrf");
|
|
const settingsPanel = document.getElementById("printer-settings-panel");
|
|
const settingsSyncPill = document.getElementById("settings-sync-pill");
|
|
const settingsSyncSummary = document.getElementById("settings-sync-summary");
|
|
const printStatusFacts = document.getElementById("print-status-facts");
|
|
const recentJobsList = document.getElementById("recent-jobs-list");
|
|
const printActionBanner = document.getElementById("print-action-banner");
|
|
const mmuMaterials = document.getElementById("mmu-materials");
|
|
const mmuMaterialsFacts = document.getElementById("mmu-materials-facts");
|
|
const temperaturePanel = document.getElementById("temperature-panel");
|
|
const temperatureFacts = document.getElementById("temperature-facts");
|
|
const adminLink = document.getElementById("admin-link");
|
|
const agentLink = document.getElementById("agent-link");
|
|
const settingsLink = document.getElementById("settings-link");
|
|
const settingsEditLink = document.getElementById("settings-edit-link");
|
|
const settingsFacts = document.getElementById("settings-facts");
|
|
|
|
const printerID = decodeURIComponent(window.location.pathname.replace(/^\/printers\//, "").split("/")[0] || "");
|
|
const liveCameras = new Set();
|
|
let currentCameraSignature = "";
|
|
let printStatusRequestInFlight = false;
|
|
let currentControlMode = "readonly";
|
|
let currentTemperatureSummary = "";
|
|
let currentPrintState = "";
|
|
let printActionBannerTimer = null;
|
|
const printActionConfirmationTimeoutMs = 5000;
|
|
const printActionConfirmationPollMs = 500;
|
|
const recentJobReplayInFlight = new Set();
|
|
let recentJobReplayModal = null;
|
|
let recentJobReplayModalResolver = null;
|
|
let recentJobReplayModalKeyHandler = null;
|
|
|
|
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 || "";
|
|
if (settingsPanel) {
|
|
settingsPanel.hidden = !session.is_admin;
|
|
}
|
|
if (agentLink && printerID) {
|
|
agentLink.href = `/printers/${encodeURIComponent(printerID)}/agent`;
|
|
}
|
|
if (adminLink && printerID) {
|
|
adminLink.href = `/admin?printer_id=${encodeURIComponent(printerID)}`;
|
|
}
|
|
if (settingsLink && printerID) {
|
|
settingsLink.href = `/printers/${encodeURIComponent(printerID)}/settings`;
|
|
}
|
|
if (settingsEditLink && printerID) {
|
|
settingsEditLink.href = `/printers/${encodeURIComponent(printerID)}/settings`;
|
|
}
|
|
}
|
|
|
|
async function loadPrinter() {
|
|
if (!printerID) {
|
|
title.textContent = "Unknown printer";
|
|
return;
|
|
}
|
|
|
|
title.textContent = printerID;
|
|
healthLink.href = `/api/printers/${encodeURIComponent(printerID)}/health`;
|
|
infoLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/printer/info`;
|
|
if (printStatusLink) {
|
|
printStatusLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status`;
|
|
}
|
|
if (recentJobsLink) {
|
|
recentJobsLink.href = `/p/${encodeURIComponent(printerID)}/moonraker/server/history/list?limit=5&order=desc`;
|
|
}
|
|
const response = await fetch(`/api/printers/${encodeURIComponent(printerID)}`, { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
renderHealth(null, false);
|
|
infoFacts.innerHTML = fact("Moonraker", `Unavailable (${response.status})`);
|
|
renderPrintStatus(null, `HTTP ${response.status}`, "readonly");
|
|
return;
|
|
}
|
|
const data = await response.json();
|
|
renderHealth(data, true);
|
|
const label = (data.settings && data.settings.display_name ? String(data.settings.display_name).trim() : "") || printerID;
|
|
title.textContent = label;
|
|
const syncState = computeSettingsSync(data.settings || {}, data.health || {});
|
|
currentControlMode = data.control_mode || "readonly";
|
|
const detailPrintStatus = data.health?.print_status || data.print_status || null;
|
|
currentTemperatureSummary = formatTemperatureSummary(detailPrintStatus);
|
|
renderUI(data.health || {}, data.settings || {}, data.control_mode || "readonly", data.access || "unknown", syncState);
|
|
renderPrintStatus(data.print_status || data.health?.print_status || null, data.print_status_error || "", data.control_mode || "readonly");
|
|
renderMmuMaterials(detailPrintStatus);
|
|
renderTemperatureFacts(detailPrintStatus);
|
|
renderRecentJobs(data.recent_jobs || [], data.recent_jobs_error || "");
|
|
renderSettings(data.health || {}, data.settings || {}, data.control_mode || "readonly", syncState);
|
|
updateUILink(data.health || {});
|
|
if (data.info) {
|
|
renderInfo(data.info);
|
|
return;
|
|
}
|
|
infoFacts.innerHTML = fact("Moonraker", data.info_error || "No printer info available.");
|
|
}
|
|
|
|
function renderMmuMaterials(printStatus) {
|
|
if (!mmuMaterials || !mmuMaterialsFacts) {
|
|
return;
|
|
}
|
|
const state = collectMmuMaterialState(printStatus);
|
|
if (!state.visible) {
|
|
mmuMaterials.hidden = true;
|
|
mmuMaterialsFacts.innerHTML = "";
|
|
return;
|
|
}
|
|
mmuMaterials.hidden = false;
|
|
mmuMaterialsFacts.innerHTML = state.disabled
|
|
? mmuMaterialChipHtml({ label: state.label, value: "Disabled", color: "" }, true)
|
|
: state.rows.map((row) => mmuMaterialChipHtml(row, false)).join("");
|
|
}
|
|
|
|
function renderTemperatureFacts(printStatus) {
|
|
if (!temperaturePanel || !temperatureFacts) {
|
|
return;
|
|
}
|
|
const state = collectTemperatureState(printStatus);
|
|
if (!state.visible) {
|
|
temperaturePanel.hidden = true;
|
|
temperatureFacts.innerHTML = "";
|
|
return;
|
|
}
|
|
temperaturePanel.hidden = false;
|
|
temperatureFacts.innerHTML = state.rows.map((row) => fact(row.label, row.value)).join("");
|
|
}
|
|
|
|
async function refreshPrintStatus() {
|
|
if (!printerID || printStatusRequestInFlight || !printStatusFacts) {
|
|
return;
|
|
}
|
|
printStatusRequestInFlight = true;
|
|
try {
|
|
const result = await fetchPrintStatus();
|
|
if (!result.ok) {
|
|
renderPrintStatus(null, result.error, currentControlMode);
|
|
return;
|
|
}
|
|
renderPrintStatus(result.status, "", currentControlMode);
|
|
} catch (error) {
|
|
renderPrintStatus(null, error instanceof Error ? error.message : "failed to refresh print status", currentControlMode);
|
|
} finally {
|
|
printStatusRequestInFlight = false;
|
|
}
|
|
}
|
|
|
|
async function fetchPrintStatus() {
|
|
const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/objects/query?print_stats&display_status`, {
|
|
credentials: "same-origin",
|
|
});
|
|
if (!response.ok) {
|
|
return { ok: false, error: `HTTP ${response.status}` };
|
|
}
|
|
const payload = await response.json();
|
|
return {
|
|
ok: true,
|
|
status: payload.result ? payload.result.status || payload.result : payload,
|
|
};
|
|
}
|
|
|
|
function renderUI(health, settings, controlMode, accessLevel, syncState) {
|
|
uiFacts.innerHTML = [
|
|
fact("Reachable", health.ui_reachable ? "Yes" : "No"),
|
|
fact("Source", health.ui_source || "Unknown"),
|
|
fact("Configured UI", settings.ui_url || "Auto"),
|
|
fact("Agent UI", health.ui_url || "Unavailable"),
|
|
fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"),
|
|
fact("Desired mode", controlMode),
|
|
fact("Applied mode", health.control_mode || "Unknown"),
|
|
fact("Sync", syncState.state),
|
|
fact("Sync detail", syncState.detail),
|
|
fact("Access", accessLevel || "Unknown"),
|
|
].join("");
|
|
}
|
|
|
|
function renderSettings(health, settings, controlMode, syncState) {
|
|
if (!settingsPanel || settingsPanel.hidden) {
|
|
return;
|
|
}
|
|
if (settingsSyncPill) {
|
|
settingsSyncPill.textContent = syncState.state;
|
|
settingsSyncPill.classList.toggle("ok", syncState.synced);
|
|
settingsSyncPill.classList.toggle("warn", !syncState.synced);
|
|
}
|
|
if (settingsSyncSummary) {
|
|
const appliedMode = health.control_mode || "Unknown";
|
|
const lastSeen = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "no heartbeat yet";
|
|
settingsSyncSummary.textContent = `${syncState.detail} Last heartbeat ${lastSeen}; applied mode ${appliedMode}.`;
|
|
}
|
|
if (settingsFacts) {
|
|
settingsFacts.innerHTML = [
|
|
fact("Display name", settings.display_name || "Not set"),
|
|
fact("Control mode", settings.control_mode || controlMode || "readonly"),
|
|
fact("UI URL", settings.ui_url || "Auto-detect"),
|
|
fact("Auto-detect", settings.ui_auto_detect ? "On" : "Off"),
|
|
fact("Agent UI", health.ui_url || "Unavailable"),
|
|
fact("Sync", syncState.state),
|
|
fact("Sync detail", syncState.detail),
|
|
].join("");
|
|
}
|
|
}
|
|
|
|
function updateUILink(health) {
|
|
const uiRoute = `/printers/${encodeURIComponent(printerID)}/ui/`;
|
|
if (health.ui_reachable) {
|
|
uiLink.href = uiRoute;
|
|
uiLink.removeAttribute("aria-disabled");
|
|
uiLink.classList.remove("disabled");
|
|
uiLink.textContent = "Open Printer UI";
|
|
return;
|
|
}
|
|
uiLink.href = "#";
|
|
uiLink.setAttribute("aria-disabled", "true");
|
|
uiLink.classList.add("disabled");
|
|
uiLink.textContent = "UI unavailable";
|
|
}
|
|
|
|
function renderHealth(data, loaded) {
|
|
if (!loaded || !data) {
|
|
setStatus("Not reachable", false);
|
|
healthFacts.innerHTML = fact("Agent", "Unknown");
|
|
renderCameras([]);
|
|
return;
|
|
}
|
|
|
|
const health = data.health || {};
|
|
const reachable = data.connected && health.moonraker_reachable === true;
|
|
setStatus(reachable ? (health.moonraker_state || "Reachable") : "Not reachable", reachable);
|
|
|
|
const checked = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat";
|
|
healthFacts.innerHTML = [
|
|
fact("Agent", data.connected ? "Connected" : "Disconnected"),
|
|
fact("Moonraker", health.moonraker_reachable ? "Reachable" : "Not reachable"),
|
|
fact("State", health.moonraker_state || "Unknown"),
|
|
fact("Message", health.moonraker_message || "No status message yet."),
|
|
fact("Agent version", health.agent_version || "Unknown"),
|
|
fact("Host", health.hostname || "Unknown"),
|
|
fact("Last heartbeat", checked),
|
|
].join("");
|
|
renderCameras(health.cameras || []);
|
|
}
|
|
|
|
function renderInfo(info) {
|
|
infoFacts.innerHTML = [
|
|
fact("Hostname", info.hostname || "Unknown"),
|
|
fact("Software", info.software_version || "Unknown"),
|
|
fact("CPU", info.cpu_info || "Unknown"),
|
|
fact("Config", info.config_file || "Unknown"),
|
|
fact("Log", info.log_file || "Unknown"),
|
|
].join("");
|
|
}
|
|
|
|
function renderPrintStatus(status, error, controlMode) {
|
|
if (!printStatusFacts) {
|
|
return;
|
|
}
|
|
if (!status) {
|
|
currentPrintState = "";
|
|
printStatusFacts.innerHTML = [
|
|
fact("State", error ? `Unavailable (${error})` : "Unknown"),
|
|
].join("");
|
|
if (printActionRow) {
|
|
printActionRow.innerHTML = "";
|
|
}
|
|
setPrintActionBanner("", "");
|
|
return;
|
|
}
|
|
const printStats = status.print_stats || status;
|
|
const displayStatus = status.display_status || status;
|
|
const state = String(printStats.state || "Unknown");
|
|
currentPrintState = normalizePrintState(state);
|
|
const filename = String(printStats.filename || "No file loaded");
|
|
const progress = formatProgress(displayStatus.progress);
|
|
const duration = formatDuration(printStats.print_duration);
|
|
const totalDuration = formatDuration(printStats.total_duration);
|
|
const message = String(printStats.message || displayStatus.message || "No status message yet.");
|
|
const filamentUsed = formatFilament(printStats.filament_used);
|
|
const remaining = formatDuration(printStats.estimated_time_remaining || printStats.estimated_duration);
|
|
const rows = [
|
|
fact("State", state),
|
|
fact("File", filename),
|
|
fact("Progress", progress),
|
|
fact("Print duration", duration),
|
|
fact("Total duration", totalDuration),
|
|
fact("Remaining", remaining),
|
|
fact("Filament", filamentUsed),
|
|
fact("Message", message),
|
|
];
|
|
if (currentTemperatureSummary) {
|
|
rows.push(fact("Temps", currentTemperatureSummary));
|
|
}
|
|
printStatusFacts.innerHTML = rows.join("");
|
|
renderPrintActionRow(state, controlMode);
|
|
}
|
|
|
|
function renderPrintActionRow(state, controlMode) {
|
|
if (!printActionRow) {
|
|
return;
|
|
}
|
|
const isFull = String(controlMode || "").toLowerCase() === "full";
|
|
const normalizedState = String(state || "").toLowerCase();
|
|
printActionRow.innerHTML = [
|
|
printActionButton("Pause", "pause", "secondary", isFull && normalizedState === "printing"),
|
|
printActionButton("Resume", "resume", "primary", isFull && normalizedState === "paused"),
|
|
printActionButton("Cancel", "cancel", "secondary", isFull && (normalizedState === "printing" || normalizedState === "paused" || normalizedState === "resuming")),
|
|
printActionButton("Emergency Stop", "emergency_stop", "danger", isFull),
|
|
].join("");
|
|
bindPrintActions();
|
|
}
|
|
|
|
function printActionButton(label, action, kind, enabled) {
|
|
const disabled = enabled ? "" : " disabled aria-disabled=\"true\"";
|
|
const title = enabled ? "" : " title=\"Unavailable in the current print state\"";
|
|
return `<button type="button" class="button ${escapeHTML(kind)} print-action-button"${disabled}${title} data-print-action="${escapeHTML(action)}">${escapeHTML(label)}</button>`;
|
|
}
|
|
|
|
function setPrintActionBanner(message, kind) {
|
|
if (!printActionBanner) {
|
|
return;
|
|
}
|
|
if (printActionBannerTimer) {
|
|
clearTimeout(printActionBannerTimer);
|
|
printActionBannerTimer = null;
|
|
}
|
|
const text = String(message || "").trim();
|
|
if (!text) {
|
|
printActionBanner.hidden = true;
|
|
printActionBanner.textContent = "";
|
|
printActionBanner.className = "print-action-banner";
|
|
return;
|
|
}
|
|
printActionBanner.hidden = false;
|
|
printActionBanner.textContent = text;
|
|
printActionBanner.className = `print-action-banner ${escapeHTML(kind || "info")}`;
|
|
printActionBannerTimer = setTimeout(() => {
|
|
if (!printActionBanner) {
|
|
return;
|
|
}
|
|
printActionBanner.hidden = true;
|
|
printActionBanner.textContent = "";
|
|
printActionBanner.className = "print-action-banner";
|
|
printActionBannerTimer = null;
|
|
}, 8000);
|
|
}
|
|
|
|
function normalizePrintState(value) {
|
|
return String(value || "").trim().toLowerCase();
|
|
}
|
|
|
|
function prettyPrintAction(action) {
|
|
if (action === "emergency_stop") {
|
|
return "Emergency stop";
|
|
}
|
|
return action.charAt(0).toUpperCase() + action.slice(1);
|
|
}
|
|
|
|
function isPrintActionConfirmed(action, state) {
|
|
const normalized = normalizePrintState(state);
|
|
if (!normalized) {
|
|
return false;
|
|
}
|
|
switch (action) {
|
|
case "pause":
|
|
return normalized === "paused";
|
|
case "resume":
|
|
return normalized === "printing";
|
|
case "cancel":
|
|
return normalized === "cancelled" || normalized === "canceled" || normalized === "idle" || normalized === "standby" || normalized === "error";
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function waitForPrintActionConfirmation(action, baselineState) {
|
|
const deadline = Date.now() + printActionConfirmationTimeoutMs;
|
|
let lastState = normalizePrintState(baselineState);
|
|
while (Date.now() < deadline) {
|
|
await sleep(printActionConfirmationPollMs);
|
|
let result;
|
|
try {
|
|
result = await fetchPrintStatus();
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (!result.ok) {
|
|
continue;
|
|
}
|
|
const payload = result.status || {};
|
|
const printStats = payload.print_stats || payload;
|
|
const state = normalizePrintState(printStats.state || "Unknown");
|
|
lastState = state || lastState;
|
|
if (isPrintActionConfirmed(action, state)) {
|
|
return { confirmed: true, state };
|
|
}
|
|
}
|
|
return { confirmed: false, state: lastState || "unknown" };
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function runPrintAction(action) {
|
|
if (!printerID) {
|
|
return;
|
|
}
|
|
const baselineState = currentPrintState;
|
|
setPrintActionBanner(`Sending ${prettyPrintAction(action).toLowerCase()}...`, "info");
|
|
const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/print/${encodeURIComponent(action)}`, {
|
|
method: "POST",
|
|
credentials: "same-origin",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: "{}",
|
|
});
|
|
if (response.status === 403) {
|
|
const text = await response.text();
|
|
setStatus("Not reachable", false);
|
|
renderPrintStatus(null, text || "blocked by read-only printer control policy", currentControlMode);
|
|
setPrintActionBanner(text || "blocked by read-only printer control policy", "error");
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
const text = `HTTP ${response.status}`;
|
|
renderPrintStatus(null, text, currentControlMode);
|
|
setPrintActionBanner(text, "error");
|
|
return;
|
|
}
|
|
if (action === "emergency_stop") {
|
|
setPrintActionBanner("Emergency stop accepted.", "success");
|
|
await loadPrinter();
|
|
return;
|
|
}
|
|
setPrintActionBanner(`${prettyPrintAction(action)} accepted. Confirming state...`, "info");
|
|
const confirmation = await waitForPrintActionConfirmation(action, baselineState);
|
|
if (confirmation.confirmed) {
|
|
setPrintActionBanner(`${prettyPrintAction(action)} confirmed: ${confirmation.state}.`, "success");
|
|
} else {
|
|
setPrintActionBanner(`${prettyPrintAction(action)} sent. Current state: ${confirmation.state}.`, "warn");
|
|
}
|
|
await loadPrinter();
|
|
}
|
|
|
|
async function replayRecentJob(filename, label, button) {
|
|
if (!printerID || !filename) {
|
|
return;
|
|
}
|
|
const normalizedLabel = String(label || "print again").trim() || "print again";
|
|
const key = filename;
|
|
if (recentJobReplayInFlight.has(key)) {
|
|
return;
|
|
}
|
|
recentJobReplayInFlight.add(key);
|
|
if (button) {
|
|
button.disabled = true;
|
|
}
|
|
setPrintActionBanner(`Starting ${normalizedLabel.toLowerCase()}...`, "info");
|
|
try {
|
|
const response = await fetch(`/p/${encodeURIComponent(printerID)}/moonraker/printer/print/start?filename=${encodeURIComponent(filename)}`, {
|
|
method: "POST",
|
|
credentials: "same-origin",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: "{}",
|
|
});
|
|
if (response.status === 403) {
|
|
const text = await response.text();
|
|
setPrintActionBanner(text || "blocked by read-only printer control policy", "error");
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
const text = await response.text();
|
|
setPrintActionBanner(text || `HTTP ${response.status}`, "error");
|
|
return;
|
|
}
|
|
setPrintActionBanner(`${normalizedLabel} accepted. Refreshing printer state...`, "success");
|
|
setTimeout(loadPrinter, 1000);
|
|
} catch (error) {
|
|
setPrintActionBanner(error instanceof Error ? error.message : `Failed to start ${normalizedLabel.toLowerCase()}.`, "error");
|
|
} finally {
|
|
recentJobReplayInFlight.delete(key);
|
|
if (button) {
|
|
button.disabled = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
function closeRecentJobReplayModal(result) {
|
|
if (recentJobReplayModalKeyHandler) {
|
|
document.removeEventListener("keydown", recentJobReplayModalKeyHandler);
|
|
recentJobReplayModalKeyHandler = null;
|
|
}
|
|
if (recentJobReplayModal) {
|
|
recentJobReplayModal.remove();
|
|
recentJobReplayModal = null;
|
|
}
|
|
if (recentJobReplayModalResolver) {
|
|
const resolve = recentJobReplayModalResolver;
|
|
recentJobReplayModalResolver = null;
|
|
resolve(result);
|
|
}
|
|
}
|
|
|
|
function openRecentJobReplayModal(job) {
|
|
if (recentJobReplayModal) {
|
|
closeRecentJobReplayModal(false);
|
|
}
|
|
return new Promise((resolve) => {
|
|
recentJobReplayModalResolver = resolve;
|
|
const backdrop = document.createElement("div");
|
|
backdrop.className = "modal-backdrop";
|
|
backdrop.innerHTML = `
|
|
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="recent-job-replay-title">
|
|
<h3 id="recent-job-replay-title">Start print again?</h3>
|
|
<div class="modal-field">
|
|
<span>File</span>
|
|
<strong>${escapeHTML(job.filename || "Unknown job")}</strong>
|
|
</div>
|
|
<div class="modal-field">
|
|
<span>Status</span>
|
|
<strong>${escapeHTML(job.statusLabel || "unknown")}</strong>
|
|
</div>
|
|
<div class="modal-field">
|
|
<span>Action</span>
|
|
<strong>${escapeHTML(job.actionLabel || "Print again")}</strong>
|
|
</div>
|
|
<p class="panel-subtitle">This will start the selected file on the current printer.</p>
|
|
<div class="modal-actions">
|
|
<button type="button" class="button secondary" data-replay-cancel>Cancel</button>
|
|
<button type="button" class="button primary" data-replay-confirm>Start print</button>
|
|
</div>
|
|
</div>
|
|
`;
|
|
const cancelButton = backdrop.querySelector("[data-replay-cancel]");
|
|
const confirmButton = backdrop.querySelector("[data-replay-confirm]");
|
|
const finish = (value) => {
|
|
if (recentJobReplayModal === backdrop) {
|
|
closeRecentJobReplayModal(value);
|
|
}
|
|
};
|
|
backdrop.addEventListener("click", (event) => {
|
|
if (event.target === backdrop) {
|
|
finish(false);
|
|
}
|
|
});
|
|
cancelButton.addEventListener("click", () => finish(false));
|
|
confirmButton.addEventListener("click", () => finish(true));
|
|
recentJobReplayModalKeyHandler = (event) => {
|
|
if (recentJobReplayModal !== backdrop) {
|
|
return;
|
|
}
|
|
if (event.key === "Escape") {
|
|
event.preventDefault();
|
|
finish(false);
|
|
}
|
|
};
|
|
document.addEventListener("keydown", recentJobReplayModalKeyHandler);
|
|
recentJobReplayModal = backdrop;
|
|
document.body.appendChild(backdrop);
|
|
confirmButton.focus();
|
|
});
|
|
}
|
|
|
|
function bindPrintActions() {
|
|
if (!printActionRow) {
|
|
return;
|
|
}
|
|
printActionRow.querySelectorAll("[data-print-action]").forEach((button) => {
|
|
button.addEventListener("click", async () => {
|
|
if (button.disabled) {
|
|
return;
|
|
}
|
|
const action = button.dataset.printAction;
|
|
if (!action) {
|
|
return;
|
|
}
|
|
button.disabled = true;
|
|
try {
|
|
await runPrintAction(action);
|
|
} finally {
|
|
button.disabled = false;
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function renderRecentJobs(jobs, error) {
|
|
if (!recentJobsList) {
|
|
return;
|
|
}
|
|
if (!Array.isArray(jobs) || jobs.length === 0) {
|
|
recentJobsList.innerHTML = `<p class="empty-state">${escapeHTML(error || "No recent jobs found.")}</p>`;
|
|
return;
|
|
}
|
|
recentJobsList.innerHTML = jobs.map((job) => {
|
|
const filename = String(job.filename || "Unknown job");
|
|
const status = String(job.status || "unknown");
|
|
const normalizedStatus = status.toLowerCase();
|
|
const duration = formatDuration(job.total_duration || job.print_duration);
|
|
const started = formatHistoryTime(job.start_time);
|
|
const ended = formatHistoryTime(job.end_time);
|
|
const message = String(job.message || "");
|
|
const isFullControl = String(currentControlMode || "").toLowerCase() === "full";
|
|
const canReplay = isFullControl && ["completed", "cancelled", "canceled", "failed", "error", "aborted"].includes(normalizedStatus);
|
|
const replayLabel = normalizedStatus === "completed" ? "Print again" : (["failed", "error"].includes(normalizedStatus) ? "Restart" : "Reprint");
|
|
const replayTitle = canReplay ? "" : " title=\"Unavailable in the current print state\"";
|
|
return `
|
|
<section class="job-row">
|
|
<div class="job-row-top">
|
|
<strong>${escapeHTML(filename)}</strong>
|
|
<span class="status-pill ${normalizedStatus === "completed" ? "ok" : "warn"}">${escapeHTML(status)}</span>
|
|
</div>
|
|
<dl class="printer-facts job-facts">
|
|
<div><dt>Duration</dt><dd>${escapeHTML(duration)}</dd></div>
|
|
<div><dt>Started</dt><dd>${escapeHTML(started)}</dd></div>
|
|
<div><dt>Ended</dt><dd>${escapeHTML(ended)}</dd></div>
|
|
<div><dt>Message</dt><dd>${escapeHTML(message || "No message")}</dd></div>
|
|
</dl>
|
|
<div class="card-actions job-actions">
|
|
<button type="button" class="button secondary job-replay-button" data-job-filename="${escapeHTML(filename)}" data-job-label="${escapeHTML(replayLabel)}"${replayTitle}${canReplay ? "" : " disabled aria-disabled=\"true\""}>${escapeHTML(replayLabel)}</button>
|
|
</div>
|
|
</section>
|
|
`;
|
|
}).join("");
|
|
bindRecentJobActions();
|
|
}
|
|
|
|
function bindRecentJobActions() {
|
|
if (!recentJobsList) {
|
|
return;
|
|
}
|
|
recentJobsList.querySelectorAll("[data-job-filename]").forEach((button) => {
|
|
button.addEventListener("click", async () => {
|
|
if (button.disabled) {
|
|
return;
|
|
}
|
|
const filename = button.dataset.jobFilename;
|
|
const label = button.dataset.jobLabel || "Print again";
|
|
const statusLabel = button.closest(".job-row")?.querySelector(".status-pill")?.textContent || "unknown";
|
|
if (!filename) {
|
|
return;
|
|
}
|
|
try {
|
|
const confirmed = await openRecentJobReplayModal({
|
|
filename,
|
|
statusLabel,
|
|
actionLabel: label,
|
|
});
|
|
if (!confirmed) {
|
|
return;
|
|
}
|
|
await replayRecentJob(filename, label, button);
|
|
} finally {
|
|
closeRecentJobReplayModal(false);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function renderCameras(cameras) {
|
|
const signature = JSON.stringify(cameras.map((camera) => ({
|
|
name: camera.name,
|
|
has_snapshot: camera.has_snapshot,
|
|
has_stream: camera.has_stream,
|
|
aspect_ratio: camera.aspect_ratio,
|
|
rotation: camera.rotation,
|
|
flip_horizontal: camera.flip_horizontal,
|
|
flip_vertical: camera.flip_vertical,
|
|
})));
|
|
if (signature === currentCameraSignature) {
|
|
return;
|
|
}
|
|
currentCameraSignature = signature;
|
|
|
|
if (cameras.length === 0) {
|
|
cameraList.innerHTML = '<p class="empty-state">No cameras are configured for this agent.</p>';
|
|
return;
|
|
}
|
|
|
|
cameraList.innerHTML = cameras.map((camera) => {
|
|
const cameraKey = camera.name;
|
|
const snapshotURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/snapshot`;
|
|
const streamURL = `/p/${encodeURIComponent(printerID)}/camera/${encodeURIComponent(camera.name)}/stream`;
|
|
const live = liveCameras.has(cameraKey);
|
|
const transform = cameraTransform(camera);
|
|
const aspect = camera.aspect_ratio ? camera.aspect_ratio.replace(":", " / ") : "16 / 9";
|
|
const preview = camera.has_snapshot
|
|
? `<img class="camera-preview" style="aspect-ratio: ${escapeHTML(aspect)}; transform: ${escapeHTML(transform)};" data-camera-name="${escapeHTML(camera.name)}" data-snapshot-url="${snapshotURL}" data-stream-url="${streamURL}" data-live="${live ? "true" : "false"}" src="${live && camera.has_stream ? streamURL : withCacheBust(snapshotURL)}" alt="${escapeHTML(camera.name)} camera preview" data-error-count="0">`
|
|
: '<div class="camera-preview camera-placeholder">No snapshot</div>';
|
|
const streamLink = camera.has_stream
|
|
? `<a class="button primary" href="${streamURL}" target="_blank" rel="noreferrer">Open Stream</a>`
|
|
: "";
|
|
const liveToggle = camera.has_stream && camera.has_snapshot
|
|
? `<button class="button secondary camera-live-toggle" type="button" data-camera-name="${escapeHTML(camera.name)}">${live ? "Show Snapshot" : "Live Preview"}</button>`
|
|
: "";
|
|
const snapshotLink = camera.has_snapshot
|
|
? `<a class="button secondary" href="${snapshotURL}" target="_blank" rel="noreferrer">Snapshot</a>`
|
|
: "";
|
|
|
|
return `
|
|
<section class="camera-card">
|
|
${preview}
|
|
<div class="camera-card-footer">
|
|
<div>
|
|
<strong>${escapeHTML(camera.name)}</strong>
|
|
<p>${escapeHTML(cameraMeta(camera))}</p>
|
|
</div>
|
|
<div class="card-actions">${liveToggle}${streamLink}${snapshotLink}</div>
|
|
</div>
|
|
</section>
|
|
`;
|
|
}).join("");
|
|
bindCameraControls();
|
|
refreshSnapshots();
|
|
}
|
|
|
|
function bindCameraControls() {
|
|
document.querySelectorAll(".camera-live-toggle").forEach((button) => {
|
|
button.addEventListener("click", () => {
|
|
const cameraName = button.dataset.cameraName;
|
|
if (!cameraName) {
|
|
return;
|
|
}
|
|
const image = document.querySelector(`.camera-preview[data-camera-name="${cssEscape(cameraName)}"]`);
|
|
if (!image) {
|
|
return;
|
|
}
|
|
const currentlyLive = liveCameras.has(cameraName);
|
|
if (currentlyLive) {
|
|
liveCameras.delete(cameraName);
|
|
image.dataset.live = "false";
|
|
image.src = withCacheBust(image.dataset.snapshotUrl);
|
|
button.textContent = "Live Preview";
|
|
} else {
|
|
liveCameras.add(cameraName);
|
|
image.dataset.live = "true";
|
|
image.src = image.dataset.streamUrl;
|
|
button.textContent = "Show Snapshot";
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function refreshSnapshots() {
|
|
document.querySelectorAll(".camera-preview[data-live='false']").forEach((image) => {
|
|
if (image.dataset.snapshotUrl) {
|
|
image.src = withCacheBust(image.dataset.snapshotUrl);
|
|
}
|
|
});
|
|
}
|
|
|
|
cameraList.addEventListener("error", (event) => {
|
|
const image = event.target;
|
|
if (!image.classList || !image.classList.contains("camera-preview")) {
|
|
return;
|
|
}
|
|
const count = Number(image.dataset.errorCount || "0") + 1;
|
|
image.dataset.errorCount = String(count);
|
|
if (count >= 3) {
|
|
image.classList.add("camera-preview-error");
|
|
image.alt = `${image.dataset.cameraName || "Camera"} unavailable`;
|
|
}
|
|
}, true);
|
|
|
|
cameraList.addEventListener("load", (event) => {
|
|
const image = event.target;
|
|
if (!image.classList || !image.classList.contains("camera-preview")) {
|
|
return;
|
|
}
|
|
image.dataset.errorCount = "0";
|
|
image.classList.remove("camera-preview-error");
|
|
}, true);
|
|
|
|
function withCacheBust(url) {
|
|
return `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`;
|
|
}
|
|
|
|
function cssEscape(value) {
|
|
if (window.CSS && CSS.escape) {
|
|
return CSS.escape(value);
|
|
}
|
|
return String(value).replaceAll('"', '\\"');
|
|
}
|
|
|
|
function cameraTransform(camera) {
|
|
const transforms = [];
|
|
if (camera.flip_horizontal) {
|
|
transforms.push("scaleX(-1)");
|
|
}
|
|
if (camera.flip_vertical) {
|
|
transforms.push("scaleY(-1)");
|
|
}
|
|
if (camera.rotation) {
|
|
transforms.push(`rotate(${Number(camera.rotation)}deg)`);
|
|
}
|
|
return transforms.join(" ") || "none";
|
|
}
|
|
|
|
function cameraMeta(camera) {
|
|
const parts = [];
|
|
if (camera.location) {
|
|
parts.push(camera.location);
|
|
}
|
|
if (camera.service) {
|
|
parts.push(camera.service);
|
|
}
|
|
if (camera.source) {
|
|
parts.push(camera.source);
|
|
}
|
|
return parts.join(" / ") || "Configured camera";
|
|
}
|
|
|
|
function setStatus(label, ok) {
|
|
status.textContent = label;
|
|
status.classList.toggle("ok", ok);
|
|
status.classList.toggle("warn", !ok);
|
|
}
|
|
|
|
refresh.addEventListener("click", loadPrinter);
|
|
loadSession().then(loadPrinter);
|
|
setInterval(loadPrinter, 15000);
|
|
setInterval(refreshPrintStatus, 500);
|
|
setInterval(refreshSnapshots, 500);
|