// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
import { t, plural, applyStrings, culture } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
import { activityText } from "../audit.js";
const SCAN_BUTTON = ``;
export async function render(root, { api, setMeta, actions, onEvent }) {
let timer = null;
const refresh = () => {
clearTimeout(timer);
timer = setTimeout(load, 1500);
};
async function load() {
let d;
try {
d = await api.get("/api/v1/server/dashboard");
} catch (err) {
root.innerHTML = `
${escapeHtml(errorText(err))}
`;
return;
}
redraw(root, () => draw(d));
}
function draw(d) {
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
applyStrings(actions);
// The space volume's figures (the space path when the server has one), the write volume apart when it differs.
const a = d.archive;
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
const spaceTip = attr(storageTip(a));
const online = d.nodes.filter((n) => n.state !== "offline");
const uploads = lastThirtyDays(d.uploads);
const totalUploads = uploads.reduce((s, u) => s + u.value, 0);
const peak = Math.max(0, ...uploads.map((u) => u.value));
root.innerHTML = `
${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))}
${bar(used)}
${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))}
${writeVolumeLine(a)}
${formatNumber(a.sequences)}${escapeHtml(plural("Admin.Dashboard.SequenceUnit", a.sequences))}
${escapeHtml(`${plural("Admin.Dashboard.PhotoCount", a.photos)} · ${plural("Admin.Dashboard.CameraCount", a.cameras)}`)}
${escapeHtml(plural("Admin.Dashboard.WithoutProxies", a.sequencesWithoutProxies))}
${formatNumber(d.jobs.running)}
${escapeHtml([plural("Admin.Dashboard.QueuedCount", d.jobs.queued), plural("Admin.Dashboard.DoneToday", d.jobs.doneToday),
plural("Admin.Dashboard.FailedToday", d.jobs.failedToday)].join(" · "))}
${escapeHtml([plural("Admin.Dashboard.Parallelism", d.parallelism), ...(d.priorityQueue ? [t("Admin.Dashboard.PriorityQueue")] : [])].join(" · "))}
${formatNumber(online.length)}
${online.slice(0, 2).map((n) => `${escapeHtml(n.clientName)} · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}`).join("")}
${a.byYear.length === 0 ? emptyState("Admin.Dashboard.NoData", SCAN_BUTTON)
: columns(a.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)} · ${formatNumber(y.count)}` })),
{ label: t("Admin.Dashboard.ByYear"), valueLabel: (i) => formatBytes(i.value) })}
${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}
${columns(uploads, { label: t("Admin.Dashboard.Uploads"), sun: true, edgeLabels: true })}
${d.activity.length === 0 ? emptyState("Admin.Dashboard.NoActivity", ``)
: `${d.activity.map((e) => `- ${escapeHtml(activityText(e))}
`).join("")}
`}
${d.activeJobs.length === 0 ? emptyState("Admin.Jobs.Empty", SCAN_BUTTON) : `
${d.activeJobs.map((j) => `
${escapeHtml(kindLabel(j.kind))}
${escapeHtml(j.targetLabel ?? "")}
${escapeHtml(nodeLabel(j, d.nodes))}
${progressCell(j)}${stateCell(j.state)}
`).join("")}
`}
`;
applyStrings(root);
root.querySelectorAll("[data-cancel]").forEach((button) => button.addEventListener("click", async () => {
button.disabled = true;
try {
await api.post(`/api/v1/jobs/${button.dataset.cancel}/cancel`);
refresh();
} catch (err) {
toast(errorText(err), true);
button.disabled = false;
}
}));
root.querySelectorAll("[data-scan]").forEach((button) => button.addEventListener("click", async () => {
try {
await api.post("/api/v1/archive/scan");
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
}
}));
root.querySelector("#reload")?.addEventListener("click", load);
root.querySelectorAll(".table[data-levels]").forEach(fitColumns);
}
onEvent((e) => {
if (e.type === "jobProgress") {
const cell = root.querySelector(`[data-key="${CSS.escape(e.jobId)}"] .progress`);
if (cell) cell.innerHTML = progressCell({ progressDone: e.done, progressTotal: e.total });
} else {
refresh();
}
});
await load();
}
/** Frames per UTC day for the last 30 days, zero-filled; the first and last days are labelled (in UTC, like the keys). */
function lastThirtyDays(days) {
const byDay = new Map(days.map((d) => [d.day, d.frames]));
const short = new Intl.DateTimeFormat(culture(), { day: "numeric", month: "short", timeZone: "UTC" });
const long = new Intl.DateTimeFormat(culture(), { dateStyle: "medium", timeZone: "UTC" });
const items = [];
const today = new Date();
for (let i = 29; i >= 0; i--) {
const day = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - i));
const value = byDay.get(day.toISOString().slice(0, 10)) ?? 0;
items.push({ value, label: i === 29 || i === 0 ? short.format(day) : "", title: `${long.format(day)} · ${formatNumber(value)}` });
}
return items;
}