Chronos Server for Windows is replaced by Settings > Server > Share this library: Chronos Desktop hosts the server engine in its own process over its own index, archive and processing services, job engine and scheduler, so a second PC, the Uploader and render nodes use this PC's library without a Windows service or a second index. - Chronos.Server is a library; Chronos.Server.Host is the console exe that Docker and development runs start. The App references the library and the ASP.NET Core shared framework (no package). - ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and never creates, starts or disposes them; no static log sink, no console lifetime; server.json plus desktop-owned values locked "Set in Chronos Desktop"; only upload-cleanup and audit-cleanup schedules are added. - Both modes: by-id endpoints scoped to the served archive, a client's render export folder dropped; hosted mode exposes server job kinds only. - Desktop: LibraryShare (start after the schedules, stop first, port in use named), Settings > Server sharing rows, Server > This library panel (state, addresses with Copy, ports, fingerprint, temporary admin password, clients, admin panel), own library refused by ConnectFlow and dropped from LAN discovery, the uploads sweep step, thumbnails after scans while sharing, capture scenes server-share and server-share-failed. - Removed: the Windows service hosting of Chronos.Server, its switches and its tests. Refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
329 lines
21 KiB
JavaScript
329 lines
21 KiB
JavaScript
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
|
||
// environment variables are read-only here; ports, TLS and chunk size apply at the next restart. How long job history is
|
||
// kept is a parameter of the Job history clean-up schedule (Jobs › Scheduled, owner review 2, R10); Keep audit shows the
|
||
// Audit log clean-up schedule's age limit (0 while it is off), and saving a new one sets it. Jobs run one at a time
|
||
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
|
||
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
|
||
// read-only (owner review 2); #/about opens here on it. Network (owner review 3): the public ports are the host ports
|
||
// clients use when they differ from the listening ones (a container publishes 8443 as another port) and apply at once;
|
||
// in a container the listening ports are the container's, read-only. Client address is what to type in the Uploader and
|
||
// in Chronos: this host as the browser reached it, on the HTTPS port this page came through (else the public HTTPS port;
|
||
// the proxy's address in TLS mode proxy). When that port is not the saved one, a button fills it in; saving a public HTTPS
|
||
// port other than the page's asks first, as the HTTPS redirect follows it at once. Videos folder (owner review 1, R9) is
|
||
// where the Videos page's Copy to folder puts renders: read-only when CHRONOS_VIDEOS_PATH fixes it, empty turns copying off.
|
||
import { t, applyStrings, languages } from "../i18n.js";
|
||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, confirmDialog, PROXY_WARNING } from "../ui.js";
|
||
import { kindLabel } from "../jobs.js";
|
||
import { icons } from "../icons.js";
|
||
|
||
/** Levels of the priority queue, highest first. */
|
||
const LEVELS = ["high", "normal", "low"];
|
||
/** Log levels, least severe first (the server's wire names). */
|
||
const LOG_LEVELS = ["trace", "debug", "information", "warning", "error", "critical", "none"];
|
||
const ROTATIONS = ["daily", "hourly"];
|
||
/** Settings the server names in error details whose field here has another name. */
|
||
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
|
||
const PEM_FILES = ["tlsCert", "tlsKey"];
|
||
const MB = 1e6;
|
||
const MIB = 1024 * 1024;
|
||
|
||
export async function render(root, { api, info, setMeta, actions }) {
|
||
// Only the About group's database and uptime, filled in when the dashboard answers: the form never waits for its
|
||
// archive statistics, and without them those rows keep a dash.
|
||
const status = api.get("/api/v1/server/dashboard").then((d) => ({ ...d, at: Date.now() }), () => null);
|
||
let dashboard = null;
|
||
let settings;
|
||
try {
|
||
settings = await api.get("/api/v1/server/settings");
|
||
} catch (err) {
|
||
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
|
||
return;
|
||
}
|
||
setMeta("");
|
||
// In the header, like the other pages' main action, so toasts never cover it.
|
||
actions.innerHTML = `<button class="btn primary" type="submit" form="settings-form" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button>`;
|
||
applyStrings(actions);
|
||
|
||
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
||
const locked = (name) => settings.locked.some((l) => same(l, name));
|
||
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
|
||
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
|
||
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
|
||
// Chronos Desktop owns the settings of the library it shares (owner review 5, #67): no variable names them.
|
||
const lockTip = (name) => variable(name) === "desktop" ? t("Admin.Settings.LockedByDesktop.Tip") : t("Admin.Settings.Locked.Tip", variable(name));
|
||
const lock = (name) => locked(name) ? `disabled title="${attr(lockTip(name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
|
||
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
|
||
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
|
||
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
|
||
// A value this page does not know stays listed, so saving the other settings never changes it.
|
||
const choice = (name, value, values, label) => field(name, `<select class="input" name="${name}" ${lock(name)}>${values.concat(values.includes(value) ? [] : [value])
|
||
.map((v) => `<option value="${attr(v)}" ${v === value ? "selected" : ""}>${escapeHtml(t(label(v)))}</option>`).join("")}</select>`);
|
||
const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`);
|
||
// A container's listening port is the template's Target, mapped to a host port: shown, never edited here.
|
||
const listening = (name, value) => settings.inContainer
|
||
? field(`container${cap(name)}`, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" disabled data-i18n-title="Admin.Settings.ContainerPort.Tip">`)
|
||
: number(name, value, 'min="1" max="65535"');
|
||
// Empty: the listening port, which the placeholder shows.
|
||
const publicPort = (name, value, port) => number(name, value ?? "", `min="1" max="65535" placeholder="${attr(port)}"`);
|
||
// This page came through another HTTPS port than the one saved (a container's 8443 published as 8444, Public HTTPS port
|
||
// still empty): a button fills it in, so the redirect, discovery and the client address follow.
|
||
const publicHttps = () => {
|
||
const page = pagePort();
|
||
if (page === null || page === savedHttps() || locked("publicHttpsPort")) return publicPort("publicHttpsPort", settings.publicHttpsPort, settings.httpsPort);
|
||
return field("publicHttpsPort", `<span class="inline"><input class="input narrow num" type="number" name="publicHttpsPort" value="${attr(settings.publicHttpsPort ?? "")}"
|
||
min="1" max="65535" placeholder="${attr(settings.httpsPort)}" data-i18n-title="Admin.Settings.PublicHttpsPort.Tip">
|
||
<button class="btn small" type="button" id="use-page-port" title="${attr(t("Admin.Settings.UsePagePort.Tip", page))}">${escapeHtml(t("Admin.Settings.UsePagePort", page))}</button></span>`);
|
||
};
|
||
|
||
function draw() {
|
||
root.innerHTML = `
|
||
<form class="settings" id="settings-form" novalidate>
|
||
<section class="panel" aria-labelledby="server-title">
|
||
<div class="panel-head"><h2 id="server-title" data-i18n="Admin.Settings.Server"></h2>
|
||
${settings.restartRequired ? `<span class="chip warn" data-i18n="Admin.Settings.Restart" data-i18n-title="Admin.Settings.Restart.Tip"></span>` : ""}</div>
|
||
${text("serverName", settings.serverName)}
|
||
${field("language", `<select class="input" name="language" ${lock("language")}>${languages().concat(languages().includes(settings.language) ? [] : [settings.language])
|
||
.map((code) => `<option value="${attr(code)}" ${code === settings.language ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("")}</select>`)}
|
||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||
${text("videosPath", settings.videosPath, 'dir="ltr" spellcheck="false" autocomplete="off"')}
|
||
</section>
|
||
<section class="panel" aria-labelledby="jobs-title">
|
||
<h2 id="jobs-title" data-i18n="Admin.Settings.Jobs"></h2>
|
||
${number("parallelism", settings.parallelism, 'min="1" max="64"')}
|
||
${field("priorityQueue", `<span class="inline"><input type="checkbox" name="priorityQueue" ${settings.priorityQueue ? "checked" : ""} ${lock("priorityQueue")}></span>`)}
|
||
<div class="priorities" ${settings.priorityQueue ? "" : "hidden"}>
|
||
${settings.jobPriorities.map((p) => `<label class="field"><span>${escapeHtml(kindLabel(p.kind))}</span>
|
||
<select class="input narrow" name="priority:${attr(p.kind)}" title="${attr(t("Admin.Settings.JobPriority.Tip", kindLabel(p.kind)))}">${LEVELS.map((l) =>
|
||
`<option value="${l}" ${l === p.level ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Priority.${cap(l)}`))}</option>`).join("")}</select></label>`).join("")}
|
||
</div>
|
||
</section>
|
||
<section class="panel" aria-labelledby="network-title">
|
||
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
|
||
${listening("httpPort", settings.httpPort)}
|
||
${listening("httpsPort", settings.httpsPort)}
|
||
${publicPort("publicHttpPort", settings.publicHttpPort, settings.httpPort)}
|
||
${publicHttps()}
|
||
${field("clientAddress", `<span class="inline"><input class="input mono" id="client-address" readonly dir="ltr" value="${attr(clientAddress())}" data-i18n-title="Admin.Settings.ClientAddress.Tip">
|
||
<button class="btn icon" type="button" id="copy-address" data-i18n-title="Admin.Settings.CopyAddress.Tip">${icons.copy}</button></span>`)}
|
||
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
|
||
`<option value="${m}" ${m === settings.tlsMode ? "selected" : ""}>${escapeHtml(t(`Admin.Settings.Tls.${cap(m)}`))}</option>`).join("")}</select>`)}
|
||
${text("tlsCert", settings.tlsCert, 'dir="ltr" spellcheck="false"')}
|
||
${text("tlsKey", settings.tlsKey, 'dir="ltr" spellcheck="false"')}
|
||
<div class="field"><span data-i18n="Admin.Settings.Fingerprint"></span><code data-i18n-title="Admin.Settings.Fingerprint.Tip">${fingerprint(info?.tlsFingerprint)}</code></div>
|
||
</section>
|
||
<section class="panel" aria-labelledby="limits-title">
|
||
<h2 id="limits-title" data-i18n="Admin.Settings.Limits"></h2>
|
||
${number("maxUploadMb", Math.round(settings.maxUploadBytes / MB), 'min="1"')}
|
||
${number("chunkSizeMib", settings.chunkSizeBytes / MIB, 'min="0.0625" max="64" step="0.0625"')}
|
||
${number("tokenLifetimeDays", settings.tokenLifetimeDays, 'min="1" max="365"')}
|
||
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
|
||
</section>
|
||
<section class="panel" aria-labelledby="logs-title">
|
||
<h2 id="logs-title" data-i18n="Admin.Settings.Logs"></h2>
|
||
${level("logLevel", settings.logs.fileLevel)}
|
||
${level("consoleLogLevel", settings.logs.consoleLevel)}
|
||
${number("logRetentionDays", settings.logs.retentionDays, 'min="1" max="3650"')}
|
||
${number("logMaxFileMb", settings.logs.maxFileMb, 'min="0" max="10240"')}
|
||
${number("logMaxTotalMb", settings.logs.maxTotalMb, 'min="0" max="1048576"')}
|
||
${choice("logRotation", settings.logs.rotation, ROTATIONS, (r) => `Admin.Settings.Rotation.${cap(r)}`)}
|
||
${number("auditRetentionDays", settings.logs.auditRetentionDays, 'min="0" max="3650"')}
|
||
${number("diagnosticsLogMb", settings.logs.diagnosticsLogMb, 'min="1" max="1024"')}
|
||
</section>
|
||
</form>
|
||
${about()}`;
|
||
applyStrings(root);
|
||
const form = root.querySelector("form");
|
||
escapeReverts(form);
|
||
form.addEventListener("submit", save);
|
||
form.elements.tlsMode.addEventListener("change", () => pemFiles(form));
|
||
pemFiles(form);
|
||
root.querySelector("#use-page-port")?.addEventListener("click", (e) => {
|
||
form.elements.publicHttpsPort.value = String(pagePort());
|
||
e.currentTarget.remove();
|
||
form.elements.publicHttpsPort.focus();
|
||
});
|
||
const address = root.querySelector("#client-address");
|
||
root.querySelector("#copy-address").addEventListener("click", async () => {
|
||
try {
|
||
await navigator.clipboard.writeText(address.value);
|
||
toast(t("Admin.Settings.AddressCopied"));
|
||
} catch {
|
||
address.focus();
|
||
address.select();
|
||
}
|
||
});
|
||
// The levels matter only while the priority queue is on.
|
||
form.elements.priorityQueue.addEventListener("change", () => { root.querySelector(".priorities").hidden = !form.elements.priorityQueue.checked; });
|
||
}
|
||
|
||
/**
|
||
* About, outside the form: nothing to save. The server name and the certificate fingerprint are left to the Server
|
||
* and Network groups above; the uptime counts on from when it was read.
|
||
*/
|
||
function about() {
|
||
const rows = [
|
||
["Admin.About.Version", `<span class="num" dir="ltr">${escapeHtml(info?.version ?? "—")}</span>`],
|
||
["Admin.About.Api", `<span class="num">${escapeHtml(info?.apiVersion ?? "—")}</span>`],
|
||
["Admin.About.Database", `<span id="about-database" dir="ltr">${escapeHtml(database())}</span>`],
|
||
["Admin.About.Uptime", `<span id="about-uptime">${escapeHtml(uptime())}</span>`],
|
||
];
|
||
return `
|
||
<section class="panel about" aria-labelledby="about-title">
|
||
<h2 id="about-title" tabindex="-1" data-i18n="Admin.Settings.About"></h2>
|
||
<div class="brand large"><img src="favicon.svg" alt=""><strong data-i18n="Admin.About.Title"></strong></div>
|
||
<dl>${rows.map(([key, value]) => `<dt data-i18n="${key}"></dt><dd>${value}</dd>`).join("")}</dl>
|
||
</section>`;
|
||
}
|
||
|
||
function database() {
|
||
return dashboard?.database ?? "—";
|
||
}
|
||
|
||
function uptime() {
|
||
return dashboard ? formatDuration(dashboard.uptimeSeconds + (Date.now() - dashboard.at) / 1000) : "—";
|
||
}
|
||
|
||
/**
|
||
* What clients type to reach this server: the host name the browser used (an IPv6 address in brackets) on the port
|
||
* this page came through over HTTPS, which reaches the server whatever is saved; over plain HTTP (this machine), the
|
||
* public HTTPS port, else the HTTPS port; behind a reverse proxy, the proxy's address this page came through.
|
||
*/
|
||
function clientAddress() {
|
||
if (settings.tlsMode === "proxy") return location.origin;
|
||
const host = location.hostname.includes(":") && !location.hostname.startsWith("[") ? `[${location.hostname}]` : location.hostname;
|
||
const port = pagePort() ?? savedHttps();
|
||
return port === 443 ? `https://${host}` : `https://${host}:${port}`;
|
||
}
|
||
|
||
/** The HTTPS port clients are told to use, as saved: the public one, else the one the server listens on. */
|
||
function savedHttps() {
|
||
return settings.publicHttpsPort ?? settings.httpsPort;
|
||
}
|
||
|
||
/** The port this page came through when the browser speaks HTTPS to the server itself (not through a proxy), else null. */
|
||
function pagePort() {
|
||
if (location.protocol !== "https:" || settings.tlsMode === "proxy") return null;
|
||
return Number(location.port || 443);
|
||
}
|
||
|
||
/** The certificate and key files are used only in Own certificate mode; elsewhere they are off and say so. */
|
||
function pemFiles(form) {
|
||
const pem = form.elements.tlsMode.value === "pem";
|
||
for (const name of PEM_FILES.filter((n) => !locked(n))) {
|
||
const input = form.elements[name];
|
||
clearInvalid(input);
|
||
input.disabled = !pem;
|
||
input.title = t(pem ? `Admin.Settings.${cap(name)}.Tip` : "Admin.Settings.PemOnly.Tip");
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The videos folder to send (owner review 1, R9): null keeps it (locked by CHRONOS_VIDEOS_PATH, or not changed), an empty
|
||
* text clears it and turns copying off, else the folder, which the server checks (not inside the archive).
|
||
*/
|
||
function videosPath() {
|
||
const input = root.querySelector('[name="videosPath"]');
|
||
if (!input || input.disabled) return null;
|
||
const next = input.value.trim();
|
||
return next === (settings.videosPath ?? "") ? null : next;
|
||
}
|
||
|
||
async function save(e) {
|
||
e.preventDefault();
|
||
const form = e.target;
|
||
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
|
||
const data = new FormData(form);
|
||
const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name));
|
||
// Text a number field cannot read is sent as -1, which the server refuses, so it is marked rather than cleared.
|
||
const publicValue = (name) => {
|
||
const input = form.elements[name];
|
||
if (input.disabled) return settings[name];
|
||
if (input.validity.badInput) return -1;
|
||
return input.value.trim() === "" ? 0 : Number(input.value);
|
||
};
|
||
// A new public HTTPS port other than the one this page came through moves the HTTPS redirect away from it at once: a
|
||
// typo would send the panel's link to a port where nothing, or another service, answers. Asked once before saving.
|
||
const nextPublic = publicValue("publicHttpsPort");
|
||
const page = pagePort();
|
||
const nextHttps = nextPublic === 0 || nextPublic == null ? settings.httpsPort : nextPublic;
|
||
if (page !== null && nextPublic !== -1 && nextHttps !== savedHttps() && nextHttps !== page && !await confirmDialog({
|
||
title: t("Admin.Settings.PortChangeTitle", nextHttps),
|
||
body: t("Admin.Settings.PortChangeBody", page),
|
||
confirm: t("Admin.Settings.PortChangeConfirm"),
|
||
confirmTip: t("Admin.Settings.PortChangeConfirm.Tip", nextHttps),
|
||
cancel: t("Admin.Common.Keep"),
|
||
cancelTip: t("Admin.Settings.PortChangeKeep.Tip"),
|
||
})) {
|
||
form.elements.publicHttpsPort.focus();
|
||
return;
|
||
}
|
||
const request = {
|
||
...settings,
|
||
serverName: String(value("serverName", settings.serverName)).trim(),
|
||
language: String(value("language", settings.language)),
|
||
parallelism: Number(value("parallelism", settings.parallelism)),
|
||
priorityQueue: form.elements.priorityQueue.disabled ? settings.priorityQueue : form.elements.priorityQueue.checked,
|
||
jobPriorities: settings.jobPriorities.map((p) => ({ kind: p.kind, level: String(data.get(`priority:${p.kind}`) ?? p.level) })),
|
||
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
|
||
httpPort: Number(value("httpPort", settings.httpPort)),
|
||
httpsPort: Number(value("httpsPort", settings.httpsPort)),
|
||
// Empty clears a public port (0); a locked one is sent as it is.
|
||
publicHttpPort: publicValue("publicHttpPort"),
|
||
publicHttpsPort: nextPublic,
|
||
tlsMode: String(value("tlsMode", settings.tlsMode)),
|
||
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
|
||
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
|
||
videosPath: videosPath(),
|
||
maxUploadBytes: Math.round(Number(data.get("maxUploadMb")) * MB),
|
||
chunkSizeBytes: Math.round(Number(data.get("chunkSizeMib")) * MIB),
|
||
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
|
||
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
|
||
logs: {
|
||
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
|
||
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
|
||
retentionDays: Number(value("logRetentionDays", settings.logs.retentionDays)),
|
||
maxFileMb: Number(value("logMaxFileMb", settings.logs.maxFileMb)),
|
||
maxTotalMb: Number(value("logMaxTotalMb", settings.logs.maxTotalMb)),
|
||
rotation: String(value("logRotation", settings.logs.rotation)),
|
||
auditRetentionDays: Number(value("auditRetentionDays", settings.logs.auditRetentionDays)),
|
||
diagnosticsLogMb: Number(value("diagnosticsLogMb", settings.logs.diagnosticsLogMb)),
|
||
},
|
||
};
|
||
try {
|
||
settings = await api.put("/api/v1/server/settings", request);
|
||
draw();
|
||
toast(t("Admin.Common.Saved"));
|
||
} catch (err) {
|
||
const key = String(err.details ?? "").toLowerCase();
|
||
const input = (FIELDS[key] && form.elements[FIELDS[key]]) || [...form.elements].find((el) => el.name && el.name.toLowerCase() === key);
|
||
let message = errorText(err);
|
||
if (input && err.code === "invalid_setting") message = PEM_FILES.includes(input.name) ? t("Admin.Settings.PemMissing") : invalidText(input);
|
||
if (input && !input.disabled) {
|
||
markInvalid(input, message);
|
||
input.focus();
|
||
}
|
||
toast(message, true);
|
||
}
|
||
}
|
||
|
||
draw();
|
||
// Once: the route drops the group, so a later redraw (a language change) leaves the focus where it is.
|
||
if (routeParams().get("group") === "about") {
|
||
history.replaceState(null, "", "#/settings");
|
||
root.querySelector(".about").scrollIntoView({ block: "start" });
|
||
root.querySelector("#about-title").focus({ preventScroll: true });
|
||
}
|
||
// Only the two rows change, so the focus and the form's edits stay; a page left meanwhile is not touched.
|
||
status.then((d) => {
|
||
dashboard = d;
|
||
if (!d || !root.isConnected) return;
|
||
root.querySelector("#about-database").textContent = database();
|
||
root.querySelector("#about-uptime").textContent = uptime();
|
||
});
|
||
}
|
||
|
||
function cap(s) {
|
||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||
}
|