feat(server): admin panel pages for dashboard, users, archive, jobs, settings and logs

Vanilla ES modules under a strict CSP (bars and charts are SVG, no inline
styles), cookie session with CSRF header, first sign-in password change,
live updates over the events WebSocket, language menu fed by
/api/v1/i18n. Every label and tooltip is an Admin.* resource (en, it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:41:42 +00:00
1 parent 145ecf33d2
commit 26016f1621
16 files changed
+2029 -106

No files matched your search

+151 -33
View File
@@ -1,4 +1,4 @@
/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only). */
/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only), mockups Admin.html and AdminUsers.html. */
:root {
--bg: #f3f3f3;
--chrome: #ffffff;
@@ -15,12 +15,14 @@
--on-accent: #ffffff;
--accent-selected: #e8f1fa;
--sun: #e08a1e;
--sun-soft: #fff4e5;
--success: #0f7b4f;
--warning: #9a6700;
--error: #c42b1c;
--radius: 6px;
--radius-card: 8px;
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
--mono: Consolas, "Cascadia Mono", ui-monospace, monospace;
}
* { box-sizing: border-box; }
@@ -28,73 +30,189 @@ html, body { height: 100%; }
body { margin: 0; font: 13px/1.45 var(--font); color: var(--text); background: var(--bg); }
button, input, select { font: inherit; color: inherit; }
a { color: var(--accent); }
a:hover { color: #004c8c; }
h1, h2 { margin: 0; }
h2 { font-size: 14px; font-weight: 600; }
.num { font-variant-numeric: tabular-nums; }
.mono { font-family: var(--mono); }
.muted { color: var(--text-muted); }
.right { text-align: right; justify-self: end; }
.nowrap { white-space: nowrap; }
.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.spacer { flex: 1; }
[hidden] { display: none !important; }
/* Shell */
.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; }
.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 20px; }
.brand img { width: 28px; height: 28px; }
.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; position: sticky; top: 0; height: 100vh; }
.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 18px; }
.brand img { width: 22px; height: 22px; }
.brand strong { display: block; font-size: 14px; }
.brand span { display: block; font-size: 11px; color: var(--text-muted); }
.nav a { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 12px; border-radius: var(--radius); color: var(--text); text-decoration: none; margin-bottom: 2px; }
.brand.large img { width: 40px; height: 40px; }
.brand.large strong { font-size: 18px; }
.nav { display: grid; gap: 2px; }
.nav a { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 10px; border-radius: var(--radius); color: var(--text); text-decoration: none; }
.nav a:hover { background: var(--card-hover); }
.nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; }
.nav svg { width: 16px; height: 16px; flex: none; }
.nav .badge { margin-left: auto; min-width: 18px; height: 16px; padding: 0 5px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 10px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; }
.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 12px 8px 0; display: flex; align-items: center; gap: 10px; }
.avatar { width: 28px; height: 28px; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; }
.nav svg { flex: none; }
.badge { margin-left: auto; min-width: 18px; padding: 0 6px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 11px; font-weight: 600; text-align: center; }
.badge.quiet { background: none; color: var(--text-muted); font-weight: 400; }
.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 8px 10px 0; display: flex; align-items: center; gap: 10px; }
.user .who { flex: 1; min-width: 0; }
.user .who strong { display: block; }
.user .who span { color: var(--text-muted); font-size: 11px; }
.main { display: flex; flex-direction: column; min-width: 0; }
.header { height: 60px; display: flex; align-items: center; gap: 12px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); }
.header h1 { font-size: 18px; font-weight: 600; margin: 0; }
.header { min-height: 60px; display: flex; align-items: center; gap: 14px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); flex-wrap: wrap; }
.header h1 { font-size: 18px; font-weight: 600; }
.header .meta { color: var(--text-muted); }
.header .spacer { flex: 1; }
.content { padding: 24px; display: grid; gap: 20px; }
.header .actions { display: flex; align-items: center; gap: 8px; }
.header .language { width: auto; }
.content { padding: 24px; display: grid; gap: 20px; align-content: start; }
/* Controls */
.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; color: var(--text); white-space: nowrap; }
.btn:hover { background: var(--card-hover); border-color: var(--stroke-strong); }
.btn:focus-visible, .input:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.btn:focus-visible, .input:focus-visible, .chip:focus-visible, .link:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); font-weight: 600; }
.btn.primary:hover { background: var(--accent-hover); }
.btn.destructive { border-color: var(--error); color: var(--error); background: transparent; }
.btn.subtle { border-color: transparent; background: transparent; }
.btn.icon { width: 32px; padding: 0; }
.btn.icon { width: 32px; min-width: 32px; padding: 0; }
.btn.small { height: 28px; padding: 0 10px; font-size: 12px; }
.btn:disabled { opacity: .4; cursor: default; }
.btn[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); }
.link { border: 0; background: none; padding: 0; color: var(--text); cursor: pointer; text-align: left; }
.link:hover { color: var(--accent); }
.input { height: 32px; width: 100%; padding: 0 10px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); }
.input:hover { border-color: var(--stroke-strong); }
.input:focus { border-color: var(--accent); outline: none; }
.input[aria-invalid="true"] { border-color: var(--error); }
select.input { padding-right: 24px; }
.input:disabled, .input[readonly] { background: var(--bg); color: var(--text-muted); }
.input.small { height: 28px; width: auto; font-size: 12px; }
.input.narrow { width: 120px; }
.input.search { width: 220px; }
input[type="checkbox"], input[type="radio"] { accent-color: var(--accent); margin: 0; }
.chips, .button-row { display: flex; gap: 8px; flex-wrap: wrap; }
.chip { height: 24px; padding: 0 10px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); font-size: 11px; cursor: pointer; }
.chip[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.chip.warn { border-color: var(--warning); color: var(--warning); cursor: default; display: inline-flex; align-items: center; }
.segmented { display: inline-flex; }
.segmented .btn { border-radius: 0; margin-left: -1px; }
.segmented .btn:first-child { border-radius: var(--radius) 0 0 var(--radius); }
.segmented .btn:last-child { border-radius: 0 var(--radius) var(--radius) 0; }
.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 18px 20px; }
.panel h2 { font-size: 14px; font-weight: 600; margin: 0 0 12px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; }
.tile .label { color: var(--text-muted); }
.tile .value { font-size: 28px; font-weight: 600; margin-top: 4px; }
.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); margin-left: 6px; }
.tile .sub { color: var(--text-muted); margin-top: 6px; }
.progress { height: 6px; border-radius: 3px; background: var(--stroke); overflow: hidden; margin-top: 10px; }
.progress > div { height: 6px; background: var(--accent); }
/* Panels and tiles */
.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 16px 18px; display: grid; gap: 10px; align-content: start; min-width: 0; }
.panel.flush { padding: 0; gap: 0; overflow: hidden; }
.panel-head { display: flex; align-items: center; gap: 12px; }
.panel-head h2 { flex: 1; }
.panel-head.padded { padding: 12px 18px; border-bottom: 1px solid var(--stroke); }
.empty { padding: 24px 18px; color: var(--text-muted); }
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 20px; }
.tile { gap: 8px; }
.tile .label, .tile .sub { font-size: 12px; color: var(--text-muted); }
.tile .value { font-size: 26px; font-weight: 600; display: flex; align-items: baseline; gap: 6px; }
.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); }
.grid { display: grid; gap: 20px; }
.grid.two { grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); }
.grid.wide-right { grid-template-columns: minmax(300px, 1fr) minmax(400px, 1.4fr); }
.status-ok { color: var(--success); }
.status-warn { color: var(--warning); }
.status-err { color: var(--error); }
/* Bars and charts (SVG attributes only: the panel runs under a strict CSP) */
svg.bar { width: 100%; height: 6px; display: block; }
svg.bar .track { fill: var(--stroke); }
svg.bar .fill { fill: var(--accent); }
svg.bar.muted .fill { fill: var(--text-faint); }
svg.chart { width: 100%; height: auto; max-height: 220px; }
svg.chart .axis { stroke: var(--stroke); }
svg.chart .column { fill: var(--accent); }
svg.chart.sun .column { fill: var(--sun); }
svg.chart text { font: 10px var(--font); text-anchor: middle; }
svg.chart .value { fill: var(--text); }
svg.chart .label { fill: var(--text-muted); }
.progress-cell { display: flex; align-items: center; gap: 8px; min-width: 0; }
.progress-cell svg.bar { flex: 1; min-width: 40px; }
/* Tables (grid rows, 52 px in the admin) */
.table { display: grid; min-width: 0; }
.table .thead, .table .row { display: grid; gap: 12px; align-items: center; padding: 0 18px; }
.table .thead { font-size: 11px; color: var(--text-muted); padding-top: 10px; padding-bottom: 10px; border-bottom: 1px solid var(--stroke); }
.table .row { min-height: 52px; border-bottom: 1px solid var(--stroke); }
.table .row:hover { background: var(--card-hover); }
.table .row.dim { color: var(--text-muted); }
.table.compact .row { min-height: 32px; padding: 0; grid-template-columns: 1fr auto auto auto; border-bottom: 0; }
.table.compact .row:hover { background: none; }
.table.users .thead, .table.users .row { grid-template-columns: minmax(180px, 1.4fr) 100px minmax(160px, 1.3fr) 130px 100px 100px minmax(200px, auto); }
.table.jobs .thead, .table.jobs .row { grid-template-columns: 110px minmax(160px, 1.5fr) 100px minmax(120px, 1fr) 110px 90px minmax(220px, auto); }
.table.jobs-mini .thead, .table.jobs-mini .row { grid-template-columns: 96px minmax(120px, 1.5fr) 92px minmax(100px, 1fr) 90px 80px; padding: 0; min-height: 40px; }
.table.jobs-mini .row { border-bottom: 0; }
.table.nodes .thead, .table.nodes .row { grid-template-columns: minmax(140px, 1fr) 120px minmax(140px, 1fr) 170px 100px auto; }
.table.audit .thead, .table.audit .row { grid-template-columns: 170px 120px 170px minmax(160px, 1fr) 130px; min-height: 40px; }
.table-foot { display: flex; align-items: center; gap: 16px; padding: 10px 18px; font-size: 12px; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
.who { display: flex; align-items: center; gap: 10px; min-width: 0; }
.stack { display: flex; flex-direction: column; min-width: 0; }
.stack small { font-size: 11px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.avatar { width: 30px; height: 30px; flex: none; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; }
.avatar.uploader { background: var(--sun-soft); color: var(--warning); }
.row.dim .avatar { background: #eeeeee; color: var(--text-muted); }
.state { white-space: nowrap; }
.state.running { color: var(--accent); }
.state.done { color: var(--success); }
.state.failed { color: var(--error); }
.state.paused { color: var(--warning); }
.state.queued, .state.cancelled { color: var(--text-muted); }
.activity { display: grid; grid-template-columns: 64px 1fr; column-gap: 12px; row-gap: 9px; font-size: 12px; }
pre.log { margin: 0; padding: 12px 18px; background: var(--bg); border-top: 1px solid var(--stroke); font: 12px/1.5 var(--mono); white-space: pre-wrap; overflow: auto; max-height: 260px; }
pre.log.tall { max-height: 60vh; border-top: 0; }
/* Forms */
.split { display: grid; grid-template-columns: 1fr auto; gap: 20px; align-items: start; }
.side { width: 340px; }
.form { display: grid; gap: 12px; }
.form label { display: grid; gap: 6px; color: var(--text-muted); }
.form label.check, label.check { display: flex; align-items: center; gap: 8px; color: var(--text); }
.form fieldset { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
.form legend { color: var(--text-muted); margin-bottom: 8px; }
.form h2 { font-size: 16px; }
.inline { display: flex; align-items: center; gap: 8px; }
.buttons { display: flex; gap: 8px; justify-content: flex-end; }
.error { color: var(--error); min-height: 18px; }
.settings { display: grid; gap: 20px; }
.field { display: grid; grid-template-columns: 180px minmax(0, 420px); align-items: center; gap: 12px; color: var(--text-muted); }
.settings-form .field { grid-template-columns: 140px minmax(0, 1fr); }
/* Dialogs and toasts */
dialog.dialog { border: 1px solid var(--stroke); border-radius: 12px; padding: 20px 22px; width: 420px; max-width: calc(100vw - 32px); box-shadow: 0 8px 24px rgba(0, 0, 0, .18); }
dialog.dialog::backdrop { background: rgba(0, 0, 0, .25); }
dialog.dialog form { display: grid; gap: 14px; }
dialog.dialog h2 { font-size: 16px; }
dialog.dialog p { margin: 0; color: var(--text-muted); }
#toasts { position: fixed; right: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; }
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; background: var(--card); border: 1px solid var(--stroke); border-left: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px rgba(0, 0, 0, .12); }
.toast.error { border-left-color: var(--error); }
/* About */
.about dl { display: grid; grid-template-columns: 180px 1fr; gap: 8px 16px; margin: 0; }
.about dt { color: var(--text-muted); }
.about dd { margin: 0; overflow-wrap: anywhere; }
/* Login */
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
.login form { width: 360px; max-width: 100%; display: grid; gap: 14px; }
.login .brand { padding: 0 0 8px; }
.login h1 { font-size: 16px; font-weight: 600; }
.login label { display: grid; gap: 6px; color: var(--text-muted); }
.login .error { color: var(--error); min-height: 18px; }
.login .row { display: flex; gap: 8px; }
@media (max-width: 800px) {
@media (max-width: 900px) {
.shell { grid-template-columns: 1fr; }
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; }
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; position: static; height: auto; }
.sidebar .brand, .sidebar .user { display: none; }
.nav { display: flex; gap: 4px; }
.nav a span { display: none; }
.nav a span:not(.badge) { display: none; }
.split, .grid.wide-right { grid-template-columns: 1fr; }
.side { width: auto; }
.field { grid-template-columns: 1fr; }
}
+82 -13
View File
@@ -1,13 +1,16 @@
// Same API as the desktop clients: cookie session + double-submit CSRF token for the web admin (BRIEF §14.2).
// Same API as the desktop clients: cookie session + CSRF header for the web admin (BRIEF §14.2).
import { culture } from "./i18n.js";
export class ApiFailure extends Error {
constructor(status, code, message) {
constructor(status, code, message, details) {
super(message);
this.status = status;
this.code = code;
this.details = details;
}
}
const SESSION_KEY = "titano.admin.user";
let currentUser = null;
function csrfToken() {
const m = document.cookie.match(/(?:^|; )titano_csrf=([^;]+)/);
@@ -15,15 +18,27 @@ function csrfToken() {
}
async function request(method, url, body) {
const headers = { Accept: "application/json" };
const headers = { Accept: "application/json", "Accept-Language": culture() };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
const res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
if (res.status === 401 && url !== "/api/v1/auth/login") sessionStorage.removeItem(SESSION_KEY);
let res;
try {
res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
} catch {
throw new ApiFailure(0, "unreachable", "");
}
if (res.status === 401 && url !== "/api/v1/auth/login") {
currentUser = null;
window.dispatchEvent(new Event("titano:signed-out"));
}
if (!res.ok) {
let err = { code: "http_" + res.status, message: res.statusText };
try { err = await res.json(); } catch { /* non-JSON error */ }
throw new ApiFailure(res.status, err.code, err.message);
try {
err = await res.json();
} catch {
// Not a JSON error body.
}
throw new ApiFailure(res.status, err.code, err.message, err.details);
}
return res.status === 204 ? null : res.json();
}
@@ -31,17 +46,71 @@ async function request(method, url, body) {
export const api = {
get: (url) => request("GET", url),
post: (url, body) => request("POST", url, body ?? {}),
put: (url, body) => request("PUT", url, body),
patch: (url, body) => request("PATCH", url, body),
del: (url) => request("DELETE", url),
isSignedIn: () => sessionStorage.getItem(SESSION_KEY) !== null,
user: () => JSON.parse(sessionStorage.getItem(SESSION_KEY) ?? "null"),
user: () => currentUser,
/** Restores the session from the cookie; null when signed out. */
async resume() {
try {
currentUser = await request("GET", "/api/v1/auth/me");
} catch {
currentUser = null;
}
return currentUser;
},
async signIn(username, password) {
const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true });
sessionStorage.setItem(SESSION_KEY, JSON.stringify(r.user));
currentUser = r.user;
return r;
},
async changePassword(currentPassword, newPassword) {
await request("POST", "/api/v1/auth/password", { currentPassword, newPassword });
currentUser = await request("GET", "/api/v1/auth/me");
},
async signOut() {
try { await request("POST", "/api/v1/auth/logout", {}); } catch { /* already gone */ }
sessionStorage.removeItem(SESSION_KEY);
try {
await request("POST", "/api/v1/auth/logout", {});
} catch {
// Already signed out.
}
currentUser = null;
},
/** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */
events(onEvent) {
let socket = null;
let stopped = false;
let delay = 1000;
const connect = () => {
if (stopped) return;
socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`);
socket.onopen = () => {
delay = 1000;
};
socket.onmessage = (m) => {
try {
onEvent(JSON.parse(m.data));
} catch {
// Ignore malformed or unknown events.
}
};
socket.onclose = () => {
if (stopped) return;
setTimeout(connect, delay);
delay = Math.min(delay * 2, 30000);
};
};
connect();
return {
stop() {
stopped = true;
socket?.close();
},
};
},
};
+126 -27
View File
@@ -1,42 +1,53 @@
// Titano Server admin panel — vanilla ES modules, no build step (BRIEF §14.8).
import { api, ApiFailure } from "./api.js";
import { t, loadStrings, applyStrings } from "./i18n.js";
import { t, loadStrings, applyStrings, setLanguage, languages, culture } from "./i18n.js";
import { icons } from "./icons.js";
import { escapeHtml, attr, errorText, nativeName } from "./ui.js";
const app = document.getElementById("app");
const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"];
const pageIcon = { dashboard: "dashboard", users: "users", archive: "archive", jobs: "jobs", settings: "settings", logs: "logs", about: "about" };
let info = null;
let events = null;
const listeners = new Set();
async function start() {
await loadStrings(navigator.language);
await loadStrings();
info = await api.get("/api/v1/server/info").catch(() => null);
await api.resume();
window.addEventListener("hashchange", render);
window.addEventListener("titano:signed-out", () => {
events?.stop();
events = null;
render();
});
render();
}
function currentPage() {
const p = location.hash.replace(/^#\/?/, "");
const p = location.hash.replace(/^#\/?/, "").split("?")[0];
return pages.includes(p) ? p : "dashboard";
}
function render() {
if (!api.isSignedIn()) {
renderLogin();
return;
}
const user = api.user();
if (!user) return renderLogin();
if (user.mustChangePassword) return renderPasswordChange();
renderShell(currentPage());
}
function renderLogin() {
function brand() {
return `<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>`;
}
function renderLogin(message = "") {
app.innerHTML = `
<main class="login">
<form novalidate>
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
<label><span data-i18n="Admin.Login.User"></span><input class="input" name="username" autocomplete="username" required></label>
<label><span data-i18n="Admin.Login.Password"></span><input class="input" name="password" type="password" autocomplete="current-password" required></label>
<div class="error" role="alert"></div>
${brand()}
<label><span data-i18n="Admin.Login.User"></span><input class="input" name="username" autocomplete="username" required data-i18n-title="Admin.Login.User.Tip"></label>
<label><span data-i18n="Admin.Login.Password"></span><input class="input" name="password" type="password" autocomplete="current-password" required data-i18n-title="Admin.Login.Password.Tip"></label>
<div class="error" role="alert">${escapeHtml(message)}</div>
<button class="btn primary" type="submit" data-i18n="Admin.Login.SignIn" data-i18n-title="Admin.Login.SignIn.Tip"></button>
</form>
</main>`;
@@ -48,10 +59,56 @@ function renderLogin() {
error.textContent = "";
const data = new FormData(form);
try {
await api.signIn(String(data.get("username")), String(data.get("password")));
const r = await api.signIn(String(data.get("username")), String(data.get("password")));
if (r.user.role !== "admin") {
await api.signOut();
error.textContent = t("Admin.Login.NotAdmin");
return;
}
render();
} catch (err) {
error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable");
error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : errorText(err);
}
});
form.querySelector("input").focus();
}
function renderPasswordChange() {
app.innerHTML = `
<main class="login">
<form novalidate>
${brand()}
<h1 data-i18n="Admin.Password.Title"></h1>
<label><span data-i18n="Admin.Password.Current"></span><input class="input" name="current" type="password" autocomplete="current-password" required data-i18n-title="Admin.Password.Current.Tip"></label>
<label><span data-i18n="Admin.Password.New"></span><input class="input" name="next" type="password" autocomplete="new-password" required data-i18n-title="Admin.Password.New.Tip"></label>
<label><span data-i18n="Admin.Password.Repeat"></span><input class="input" name="repeat" type="password" autocomplete="new-password" required data-i18n-title="Admin.Password.Repeat.Tip"></label>
<div class="error" role="alert"></div>
<div class="row">
<button class="btn" type="button" id="cancel" data-i18n="Admin.SignOut" data-i18n-title="Admin.SignOut.Tip"></button>
<span class="spacer"></span>
<button class="btn primary" type="submit" data-i18n="Admin.Password.Save" data-i18n-title="Admin.Password.Save.Tip"></button>
</div>
</form>
</main>`;
applyStrings(app);
const form = app.querySelector("form");
const error = form.querySelector(".error");
app.querySelector("#cancel").addEventListener("click", async () => {
await api.signOut();
render();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
const data = new FormData(form);
if (data.get("next") !== data.get("repeat")) {
error.textContent = t("Admin.Password.Mismatch");
return;
}
try {
await api.changePassword(String(data.get("current")), String(data.get("next")));
render();
} catch (err) {
error.textContent = errorText(err);
}
});
form.querySelector("input").focus();
@@ -59,40 +116,82 @@ function renderLogin() {
function renderShell(page) {
const nav = pages.map((p) => `
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[pageIcon[p]]}<span data-i18n="Admin.Nav.${cap(p)}"></span></a>`).join("");
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[p]}<span data-i18n="Admin.Nav.${cap(p)}"></span><span class="badge" id="badge-${p}" hidden></span></a>`).join("");
const user = api.user();
const options = languages().map((code) => `<option value="${attr(code)}" ${code === culture() ? "selected" : ""}>${escapeHtml(nativeName(code))}</option>`).join("");
app.innerHTML = `
<div class="shell">
<aside class="sidebar">
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
${brand()}
<nav class="nav">${nav}</nav>
<div class="user">
<div class="avatar">${escapeHtml((user?.username ?? "?").slice(0, 1).toUpperCase())}</div>
<div class="who"><strong>${escapeHtml(user?.username ?? "")}</strong><span data-i18n="Admin.Role.${cap(user?.role ?? "viewer")}"></span></div>
<button class="btn icon subtle" id="signout" data-i18n-title="Admin.SignOut.Tip" aria-label="${escapeHtml(t("Admin.SignOut.Tip"))}">${icons.power}</button>
<div class="avatar">${escapeHtml(user.username.slice(0, 1).toUpperCase())}</div>
<div class="who"><strong>${escapeHtml(user.username)}</strong><span data-i18n="Admin.Role.Admin"></span></div>
<button class="btn icon" id="signout" data-i18n-title="Admin.SignOut.Tip">${icons.power}</button>
</div>
</aside>
<div class="main">
<header class="header"><h1 data-i18n="Admin.Nav.${cap(page)}"></h1><span class="meta" id="meta"></span><span class="spacer"></span></header>
<header class="header">
<h1 data-i18n="Admin.Nav.${cap(page)}"></h1>
<span class="meta" id="meta"></span>
<span class="spacer"></span>
<span class="actions" id="actions"></span>
<select class="input language" id="language" data-i18n-title="Admin.Language.Tip">${options}</select>
</header>
<section class="content" id="content"></section>
</div>
</div>`;
applyStrings(app);
app.querySelector("#signout").addEventListener("click", async () => {
events?.stop();
events = null;
await api.signOut();
render();
});
app.querySelector("#language").addEventListener("change", async (e) => {
await setLanguage(e.target.value);
render();
});
events ??= api.events((e) => listeners.forEach((fn) => fn(e)));
listeners.clear();
updateBadges();
listeners.add((e) => {
if (e.type === "jobState") updateBadges();
});
const content = app.querySelector("#content");
const context = {
api,
info,
meta: app.querySelector("#meta"),
actions: app.querySelector("#actions"),
onEvent: (fn) => listeners.add(fn),
};
import(`./pages/${page}.js`)
.then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") }))
.catch(() => {
content.innerHTML = `<div class="panel"><span data-i18n="Admin.Error.Unreachable"></span></div>`;
applyStrings(content);
.then((m) => m.render(content, context))
.catch((err) => {
content.innerHTML = `<div class="panel empty"><span>${escapeHtml(errorText(err))}</span></div>`;
});
}
export function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
let badgeTimer = null;
/** Running jobs and accounts, as nav badges (refreshed at most every two seconds). */
function updateBadges() {
if (badgeTimer) return;
badgeTimer = setTimeout(() => {
badgeTimer = null;
}, 2000);
api.get("/api/v1/jobs?state=running&limit=100").then((page) => setBadge("jobs", page.items.length, true)).catch(() => {});
api.get("/api/v1/users").then((users) => setBadge("users", users.length, false)).catch(() => {});
}
function setBadge(page, count, accent) {
const badge = document.getElementById(`badge-${page}`);
if (!badge) return;
badge.hidden = count === 0;
badge.textContent = String(count);
badge.classList.toggle("quiet", !accent);
}
function cap(s) {
+46 -7
View File
@@ -1,9 +1,17 @@
// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps.
const LANGUAGE_KEY = "titano.admin.language";
let strings = {};
export async function loadStrings(culture) {
/** Loads the strings of the chosen language (remembered per browser), else of the browser's language. */
export async function loadStrings(requested) {
let preferred = requested;
try {
const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`);
preferred ??= localStorage.getItem(LANGUAGE_KEY);
} catch {
// Storage may be blocked; the browser language is used.
}
try {
const res = await fetch(`/api/v1/i18n/${encodeURIComponent(preferred || navigator.language || "en")}`);
strings = await res.json();
} catch {
strings = {};
@@ -12,16 +20,47 @@ export async function loadStrings(culture) {
document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr";
}
export async function setLanguage(code) {
try {
localStorage.setItem(LANGUAGE_KEY, code);
} catch {
// Only this session uses the language then.
}
await loadStrings(code);
}
/** The current culture (e.g. "it"), used for numbers, dates and the Accept-Language of API calls. */
export function culture() {
return strings.$culture || "en";
}
/** Languages with translated strings, as codes. */
export function languages() {
return (strings.$languages || "en").split(",");
}
/** Localized string for key with {0}, {1}… placeholders filled from args. */
export function t(key, ...args) {
const s = strings[key];
if (s === undefined) return `⟦${key}⟧`;
return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? ""));
return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => String(args[Number(i)] ?? ""));
}
/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */
/** True when the catalog has the key (for keys built from data, e.g. audit actions). */
export function has(key) {
return strings[key] !== undefined;
}
/** Fills data-i18n (text), data-i18n-title (tooltip, also the accessible name of icon buttons) and data-i18n-placeholder. */
export function applyStrings(root) {
root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); });
root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); });
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); });
root.querySelectorAll("[data-i18n]").forEach((el) => {
el.textContent = t(el.dataset.i18n);
});
root.querySelectorAll("[data-i18n-title]").forEach((el) => {
el.title = t(el.dataset.i18nTitle);
if (el.classList.contains("icon")) el.setAttribute("aria-label", el.title);
});
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
el.placeholder = t(el.dataset.i18nPlaceholder);
});
}
+1
View File
@@ -12,5 +12,6 @@ export const icons = {
refresh: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
close: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4 4 L12 12 M12 4 L4 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
copy: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
};
+41
View File
@@ -0,0 +1,41 @@
// Job and node labels shared by the dashboard and the Jobs page.
import { t, has } from "./i18n.js";
import { escapeHtml, attr, bar } from "./ui.js";
export function pascal(text) {
return String(text).split(/[-_]/).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
}
export function kindLabel(kind) {
const key = `Admin.Job.Kind.${pascal(kind)}`;
return has(key) ? t(key) : kind;
}
export function stateLabel(state) {
const key = `Admin.Job.State.${pascal(state)}`;
return has(key) ? t(key) : state;
}
/** Where a job runs: this server, a render node by name, or nowhere yet. */
export function nodeLabel(job, nodes) {
if (!job.nodeId) return "—";
if (job.nodeId.startsWith("server:")) return t("Admin.Jobs.Server");
return nodes.find((n) => n.id === job.nodeId)?.clientName ?? "—";
}
export function progressCell(job) {
if (job.progressTotal <= 0) return `<div class="progress-cell">${bar(0, true)}<span class="muted">—</span></div>`;
const fraction = job.progressDone / job.progressTotal;
return `<div class="progress-cell">${bar(fraction)}<span class="num">${Math.floor(fraction * 100)} %</span></div>`;
}
export function stateCell(state) {
const glyph = { running: "◐", queued: "○", paused: "❚❚", done: "●", failed: "✕", cancelled: "○" }[state] ?? "";
return `<span class="state ${attr(state)}">${glyph} ${escapeHtml(stateLabel(state))}</span>`;
}
/** Node encoders as "NVENC HEVC/H.264/AV1". */
export function encoders(node) {
const names = [...new Set(node.encoders.map((e) => e.codec.toUpperCase()))];
return names.join("/");
}
+15 -6
View File
@@ -1,12 +1,21 @@
// About: version, API, database, uptime and the certificate fingerprint clients are asked to trust.
import { applyStrings } from "../i18n.js";
import { escapeHtml } from "../app.js";
import { escapeHtml, formatDuration } from "../ui.js";
export async function render(root, { info }) {
export async function render(root, { api, info }) {
const dashboard = await api.get("/api/v1/server/dashboard").catch(() => null);
const rows = [
["Admin.About.Name", info?.name],
["Admin.About.Version", info?.version],
["Admin.About.Api", info?.apiVersion],
["Admin.About.Database", dashboard?.database],
["Admin.About.Uptime", dashboard ? formatDuration(dashboard.uptimeSeconds) : null],
["Admin.About.Fingerprint", info?.tlsFingerprint],
];
root.innerHTML = `
<div class="panel">
<h2 data-i18n="Admin.About.Title"></h2>
<p class="num">Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}</p>
<p class="num"><span data-i18n="Admin.About.Fingerprint"></span> ${escapeHtml(info?.tlsFingerprint ?? "–")}</p>
<div class="panel about">
<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 class="${key.endsWith("Fingerprint") ? "mono" : "num"}">${escapeHtml(value ?? "—")}</dd>`).join("")}</dl>
</div>`;
applyStrings(root);
}
@@ -0,0 +1,109 @@
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
import { t, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, bar, columns, toast, errorText } from "../ui.js";
const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0];
const ACTIONS = ["scan", "rebuild", "verify", "maintenance"];
export async function render(root, { api, meta }) {
let settings;
let stats;
try {
[settings, stats] = await Promise.all([api.get("/api/v1/archive/settings"), api.get("/api/v1/archive/stats")]);
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
meta.textContent = settings.rootPath;
const used = stats.capacityBytes > 0 ? (stats.capacityBytes - stats.freeBytes) / stats.capacityBytes : 0;
const sizes = PROXY_SIZES.includes(settings.proxyLongEdge) ? PROXY_SIZES : [settings.proxyLongEdge, ...PROXY_SIZES];
const proxyOptions = sizes.map((size) => `<option value="${size}" ${size === settings.proxyLongEdge ? "selected" : ""}>${escapeHtml(proxyLabel(size))}</option>`).join("");
root.innerHTML = `
<div class="tiles">
<div class="panel tile"><span class="label" data-i18n="Admin.Dashboard.Sequences"></span><span class="value num">${formatNumber(stats.sequences)}</span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(stats.photos), formatNumber(stats.cameras)))}</span></div>
<div class="panel tile"><span class="label" data-i18n="Admin.Archive.Originals"></span><span class="value">${escapeHtml(formatBytes(stats.bytes))}</span>
<span class="sub">${escapeHtml(stats.firstYear ? `${stats.firstYear}–${stats.lastYear}` : "—")}</span></div>
<div class="panel tile"><span class="label" data-i18n="Admin.Dashboard.Storage"></span><span class="value">${escapeHtml(formatBytes(stats.freeBytes))}<small data-i18n="Admin.Archive.FreeShort"></small></span>
${bar(used)}<span class="sub">${escapeHtml(t("Admin.Dashboard.Of", formatBytes(stats.capacityBytes)))}</span></div>
<div class="panel tile"><span class="label" data-i18n="Admin.Archive.Health"></span><span class="value num">${formatNumber(stats.unverifiedSequences)}<small data-i18n="Admin.Archive.Unverified"></small></span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(stats.sequencesWithoutProxies)))}</span></div>
</div>
<div class="grid two">
<form class="panel form settings-form" novalidate>
<h2 data-i18n="Admin.Archive.Layout"></h2>
<label class="field"><span data-i18n="Admin.Archive.Name"></span><input class="input" name="name" value="${attr(settings.name)}" data-i18n-title="Admin.Archive.Name.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.FolderTemplate"></span><input class="input mono" name="folderTemplate" value="${attr(settings.folderTemplate)}" data-i18n-title="Admin.Archive.FolderTemplate.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.FileTemplate"></span><input class="input mono" name="fileTemplate" value="${attr(settings.fileTemplate)}" data-i18n-title="Admin.Archive.FileTemplate.Tip"></label>
<label class="field"><span data-i18n="Admin.Archive.Proxies"></span><select class="input" name="proxyLongEdge" data-i18n-title="Admin.Archive.Proxies.Tip">${proxyOptions}</select></label>
<div class="buttons"><button class="btn primary" type="submit" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button></div>
</form>
<div class="panel">
<h2 data-i18n="Admin.Archive.Maintenance"></h2>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}</div>
<h2 data-i18n="Admin.Archive.ByCamera"></h2>
<div class="table compact">
${stats.byCamera.slice(0, 8).map((c) => `<div class="row"><span>${escapeHtml(c.key || "—")}</span><span class="num right">${formatNumber(c.count)}</span><span class="num right">${escapeHtml(formatBytes(c.bytes))}</span></div>`).join("")
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
</div>
</div>
</div>
<div class="grid two charts">
<div class="panel"><h2 data-i18n="Admin.Dashboard.ByYear"></h2>
${stats.byYear.length === 0 ? `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`
: columns(stats.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)}` })), { valueLabel: (i) => formatBytes(i.value) })}</div>
<div class="panel"><h2 data-i18n="Admin.Archive.ByFormat"></h2>
<div class="table compact">
${stats.byFormat.map((f) => `<div class="row"><span>${escapeHtml(f.key.toUpperCase())}</span><span class="num right">${formatNumber(f.count)}</span><span class="num right">${escapeHtml(formatBytes(f.bytes))}</span></div>`).join("")
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
</div></div>
</div>`;
applyStrings(root);
const form = root.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach((el) => el.removeAttribute("aria-invalid"));
const data = new FormData(form);
try {
settings = await api.put("/api/v1/archive/settings", {
...settings,
name: String(data.get("name")).trim(),
folderTemplate: String(data.get("folderTemplate")),
fileTemplate: String(data.get("fileTemplate")),
proxyLongEdge: Number(data.get("proxyLongEdge")),
});
toast(t("Admin.Common.Saved"));
} catch (err) {
// Errors name the field in details; the field gets the error border and the message as its tooltip.
const field = err.details && form.elements[err.details];
if (field) {
field.setAttribute("aria-invalid", "true");
field.title = errorText(err);
}
toast(errorText(err), true);
}
});
root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => {
button.disabled = true;
try {
await api.post(`/api/v1/archive/${button.dataset.action}`);
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
} finally {
button.disabled = false;
}
}));
}
function proxyLabel(size) {
if (size === -1) return t("Admin.Archive.ProxiesOff");
if (size === 0) return t("Admin.Archive.ProxiesFull");
return t("Admin.Archive.ProxiesEdge", size);
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+129 -16
View File
@@ -1,18 +1,131 @@
// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only.
import { applyStrings } from "../i18n.js";
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
import { t, has, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders, pascal } from "../jobs.js";
export async function render(root, { api, t, info, meta }) {
const health = await api.get("/health").catch(() => null);
meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : "";
root.innerHTML = `
<div class="tiles">
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Server"></div>
<div class="value">${health?.status === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-err">✕</span>`}<small>${health?.status ?? ""}</small></div>
<div class="sub num">${info?.name ?? ""}</div></div>
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Archive"></div>
<div class="value">${health?.checks?.archive === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-warn">▲</span>`}<small>${health?.checks?.archive ?? ""}</small></div></div>
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Api"></div>
<div class="value num">${info?.apiVersion ?? "–"}</div><div class="sub">${(info?.capabilities ?? []).join(" · ")}</div></div>
</div>`;
applyStrings(root);
export async function render(root, { api, meta, 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 = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
meta.textContent = t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, d.tlsMode,
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff"));
const a = d.archive;
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
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 = `
<div class="tiles">
<div class="panel tile">
<span class="label" data-i18n="Admin.Dashboard.Storage"></span>
<span class="value">${escapeHtml(formatBytes(a.capacityBytes - a.freeBytes))}<small>${escapeHtml(t("Admin.Dashboard.Of", formatBytes(a.capacityBytes)))}</small></span>
${bar(used)}
<span class="sub">${escapeHtml(t("Admin.Dashboard.Free", formatBytes(a.freeBytes)))} · ${escapeHtml(t("Admin.Dashboard.Originals", formatBytes(a.bytes)))}</span>
</div>
<div class="panel tile">
<span class="label" data-i18n="Admin.Dashboard.Archive"></span>
<span class="value num">${formatNumber(a.sequences)}<small data-i18n="Admin.Dashboard.Sequences"></small></span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.PhotosCameras", formatNumber(a.photos), formatNumber(a.cameras)))}</span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.NoProxies", formatNumber(a.sequencesWithoutProxies)))}</span>
</div>
<div class="panel tile">
<span class="label" data-i18n="Admin.Dashboard.Jobs"></span>
<span class="value num">${formatNumber(d.jobs.running)}<small data-i18n="Admin.Dashboard.Running"></small></span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.JobCounts", formatNumber(d.jobs.queued), formatNumber(d.jobs.doneToday), formatNumber(d.jobs.failedToday)))}</span>
<span class="sub">${escapeHtml(t("Admin.Dashboard.Workers", formatNumber(d.workers)))}</span>
</div>
<div class="panel tile">
<span class="label" data-i18n="Admin.Dashboard.Nodes"></span>
<span class="value num">${formatNumber(online.length)}<small data-i18n="Admin.Dashboard.Online"></small></span>
${online.slice(0, 2).map((n) => `<span class="sub">${escapeHtml(n.clientName)} · ${escapeHtml(encoders(n))} · ${escapeHtml(stateLabel(n.state))}</span>`).join("")}
</div>
</div>
<div class="grid two charts">
<div class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.ByYear"></h2></div>
${a.byYear.length === 0 ? `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`
: columns(a.byYear.map((y) => ({ label: y.key, value: y.bytes, title: `${y.key} · ${formatBytes(y.bytes)} · ${formatNumber(y.count)}` })), { valueLabel: (i) => formatBytes(i.value) })}
</div>
<div class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Uploads"></h2>
<span class="muted">${escapeHtml(t("Admin.Dashboard.UploadTotals", formatNumber(totalUploads), formatNumber(peak)))}</span></div>
${columns(uploads, { sun: true })}
</div>
</div>
<div class="grid wide-right">
<div class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Activity"></h2><a href="#/logs?view=audit" data-i18n="Admin.Dashboard.AllLogs" data-i18n-title="Admin.Dashboard.AllLogs.Tip"></a></div>
<div class="activity">${d.activity.map((e) => `<span class="muted num">${escapeHtml(formatTime(e.at))}</span><span>${escapeHtml(activityText(e))}</span>`).join("")}</div>
${d.activity.length === 0 ? `<p class="muted" data-i18n="Admin.Dashboard.NoActivity"></p>` : ""}
</div>
<div class="panel">
<div class="panel-head"><h2 data-i18n="Admin.Dashboard.Jobs"></h2><a href="#/jobs" data-i18n="Admin.Dashboard.Queue" data-i18n-title="Admin.Dashboard.Queue.Tip"></a></div>
${d.activeJobs.length === 0 ? `<p class="muted" data-i18n="Admin.Jobs.Empty"></p>` : `
<div class="table jobs-mini">
<div class="thead"><span data-i18n="Admin.Jobs.Kind"></span><span data-i18n="Admin.Jobs.Target"></span><span data-i18n="Admin.Jobs.Node"></span><span data-i18n="Admin.Jobs.Progress"></span><span data-i18n="Admin.Jobs.State"></span><span></span></div>
${d.activeJobs.map((j) => `
<div class="row" data-job="${attr(j.id)}">
<span>${escapeHtml(kindLabel(j.kind))}</span><span class="ellipsis">${escapeHtml(j.targetLabel ?? "")}</span><span>${escapeHtml(nodeLabel(j, d.nodes))}</span>
<span class="progress">${progressCell(j)}</span><span>${stateCell(j.state)}</span>
<button class="btn small" data-cancel="${attr(j.id)}" data-i18n="${j.state === "queued" ? "Admin.Jobs.Remove" : "Admin.Jobs.Cancel"}" data-i18n-title="${j.state === "queued" ? "Admin.Jobs.Remove.Tip" : "Admin.Jobs.Cancel.Tip"}"></button>
</div>`).join("")}
</div>`}
</div>
</div>`;
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;
}
}));
}
onEvent((e) => {
if (e.type === "jobProgress") {
const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`);
if (cell) cell.innerHTML = progressCell({ progressDone: e.done, progressTotal: e.total });
} else {
refresh();
}
});
await load();
}
/** One sentence per audit entry, e.g. "alberto signed in" (unknown actions show their code). */
function activityText(entry) {
const key = `Admin.Activity.${pascal(entry.action)}`;
return has(key) ? t(key, entry.username ?? "—", entry.details ?? "") : `${entry.username ?? ""} ${entry.action}`;
}
/** Frames per UTC day for the last 30 days, zero-filled. */
function lastThirtyDays(days) {
const byDay = new Map(days.map((d) => [d.day, d.frames]));
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 key = day.toISOString().slice(0, 10);
const value = byDay.get(key) ?? 0;
const label = i === 29 || i === 0 ? new Intl.DateTimeFormat(document.documentElement.lang, { day: "numeric", month: "short" }).format(day) : "";
items.push({ value, label, title: `${key} · ${formatNumber(value)}` });
}
return items;
}
+163
View File
@@ -0,0 +1,163 @@
// Jobs (BRIEF §14.8): queue and history with cancel/pause/resume/retry/priority, log tails, render nodes.
import { t, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatTime, formatDateTime, toast, errorText, confirmDialog } from "../ui.js";
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
const FILTERS = ["all", "running", "queued", "paused", "failed", "done", "cancelled"];
const PRIORITIES = ["background", "normal", "user"];
export async function render(root, { api, meta, onEvent }) {
let filter = "all";
let jobs = [];
let nodes = [];
let cursor = null;
const expanded = new Set();
let timer = null;
root.innerHTML = `
<div class="chips" role="group">${FILTERS.map((f) => `<button class="chip" data-filter="${f}" aria-pressed="${f === filter}" data-i18n="Admin.Jobs.Filter.${cap(f)}" data-i18n-title="Admin.Jobs.Filter.Tip"></button>`).join("")}</div>
<div class="panel flush">
<div class="table jobs">
<div class="thead"><span data-i18n="Admin.Jobs.Kind"></span><span data-i18n="Admin.Jobs.Target"></span><span data-i18n="Admin.Jobs.Node"></span>
<span data-i18n="Admin.Jobs.Progress"></span><span data-i18n="Admin.Jobs.State"></span><span data-i18n="Admin.Jobs.Created"></span><span></span></div>
<div id="rows"></div>
</div>
<div class="table-foot"><span class="spacer"></span><button class="btn small" id="more" hidden data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</div>
<div class="panel flush">
<div class="panel-head padded"><h2 data-i18n="Admin.Jobs.Nodes"></h2></div>
<div class="table nodes">
<div class="thead"><span data-i18n="Admin.Jobs.NodeName"></span><span data-i18n="Admin.Jobs.Owner"></span><span data-i18n="Admin.Jobs.Encoders"></span>
<span data-i18n="Admin.Jobs.Heartbeat"></span><span data-i18n="Admin.Jobs.State"></span><span></span></div>
<div id="nodes"></div>
</div>
</div>`;
applyStrings(root);
root.querySelectorAll("[data-filter]").forEach((chip) => chip.addEventListener("click", () => {
filter = chip.dataset.filter;
root.querySelectorAll("[data-filter]").forEach((c) => c.setAttribute("aria-pressed", String(c === chip)));
load();
}));
root.querySelector("#more").addEventListener("click", () => load(true));
async function load(more = false) {
try {
const state = filter === "all" ? "" : `&state=${filter}`;
const page = await api.get(`/api/v1/jobs?limit=50${state}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
jobs = more ? jobs.concat(page.items) : page.items;
cursor = page.nextCursor;
nodes = await api.get("/api/v1/nodes");
} catch (err) {
toast(errorText(err), true);
return;
}
const running = jobs.filter((j) => j.state === "running").length;
meta.textContent = t("Admin.Jobs.Meta", running, nodes.filter((n) => n.state !== "offline").length);
draw();
}
function draw() {
const host = root.querySelector("#rows");
host.innerHTML = jobs.map((j) => `
<div class="row" data-job="${attr(j.id)}">
<button class="link" data-toggle="${attr(j.id)}" aria-expanded="${expanded.has(j.id)}" data-i18n-title="Admin.Jobs.Log.Tip">${escapeHtml(kindLabel(j.kind))}</button>
<span class="ellipsis">${escapeHtml(j.targetLabel ?? "")}</span>
<span>${escapeHtml(nodeLabel(j, nodes))}</span>
<span class="progress">${progressCell(j)}</span>
<span>${stateCell(j.state)}</span>
<span class="muted">${escapeHtml(formatTime(j.created))}</span>
<span class="row-actions">${buttons(j)}</span>
</div>
${expanded.has(j.id) ? `<pre class="log">${escapeHtml(j.error ? `${j.logTail ?? ""}\n${j.error}`.trim() : j.logTail ?? "")}</pre>` : ""}`).join("")
|| `<div class="empty" data-i18n="Admin.Jobs.Empty"></div>`;
applyStrings(host);
host.querySelectorAll("[data-toggle]").forEach((b) => b.addEventListener("click", () => {
const id = b.dataset.toggle;
if (!expanded.delete(id)) expanded.add(id);
draw();
}));
host.querySelectorAll("[data-act]").forEach((b) => b.addEventListener("click", () => act(b.closest(".row").dataset.job, b.dataset.act)));
host.querySelectorAll("select[data-priority]").forEach((s) => s.addEventListener("change", () => setPriority(s.dataset.priority, s.value)));
root.querySelector("#more").hidden = !cursor;
const nodeHost = root.querySelector("#nodes");
nodeHost.innerHTML = nodes.map((n) => `
<div class="row" data-node="${attr(n.id)}">
<span><strong>${escapeHtml(n.clientName)}</strong></span><span>${escapeHtml(n.username)}</span>
<span class="ellipsis" title="${attr(n.encoders.map((e) => e.name).join(", "))}">${escapeHtml(encoders(n))}</span>
<span class="muted">${escapeHtml(formatDateTime(n.lastHeartbeat))}</span>
<span class="state ${n.state === "offline" ? "cancelled" : n.state === "busy" ? "running" : "done"}">${n.state === "offline" ? "○" : "●"} ${escapeHtml(stateLabel(n.state))}</span>
<span class="row-actions"><button class="btn small destructive" data-forget="${attr(n.id)}" data-i18n="Admin.Jobs.Forget" data-i18n-title="Admin.Jobs.Forget.Tip"></button></span>
</div>`).join("") || `<div class="empty" data-i18n="Admin.Jobs.NoNodes"></div>`;
applyStrings(nodeHost);
nodeHost.querySelectorAll("[data-forget]").forEach((b) => b.addEventListener("click", () => forget(nodes.find((n) => n.id === b.dataset.forget))));
}
function buttons(job) {
const button = (act, key) => `<button class="btn small" data-act="${act}" data-i18n="Admin.Jobs.${key}" data-i18n-title="Admin.Jobs.${key}.Tip"></button>`;
const priority = `<select class="input small" data-priority="${attr(job.id)}" data-i18n-title="Admin.Jobs.Priority.Tip">${PRIORITIES.map((p) =>
`<option value="${p}" ${p === job.priority ? "selected" : ""}>${escapeHtml(t(`Admin.Jobs.Priority.${cap(p)}`))}</option>`).join("")}</select>`;
switch (job.state) {
case "running": return button("pause", "Pause") + button("cancel", "Cancel");
case "queued": return priority + button("pause", "Pause") + button("cancel", "Remove");
case "paused": return priority + button("resume", "Resume") + button("cancel", "Cancel");
case "failed":
case "cancelled": return button("retry", "Retry");
default: return "";
}
}
async function act(id, action) {
try {
await api.post(`/api/v1/jobs/${id}/${action}`);
await load();
} catch (err) {
toast(errorText(err), true);
}
}
async function setPriority(id, priority) {
try {
await api.post(`/api/v1/jobs/${id}/priority`, { priority });
} catch (err) {
toast(errorText(err), true);
}
}
async function forget(node) {
const confirmed = await confirmDialog({
title: t("Admin.Jobs.ForgetTitle", node.clientName),
confirm: t("Admin.Jobs.Forget"),
confirmTip: t("Admin.Jobs.Forget.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
try {
await api.del(`/api/v1/nodes/${node.id}`);
await load();
} catch (err) {
toast(errorText(err), true);
}
}
onEvent((e) => {
if (e.type === "jobProgress") {
const job = jobs.find((j) => j.id === e.jobId);
if (job) {
job.progressDone = e.done;
job.progressTotal = e.total;
const cell = root.querySelector(`[data-job="${CSS.escape(e.jobId)}"] .progress`);
if (cell) cell.innerHTML = progressCell(job);
}
} else if (e.type === "jobState" || e.type === "nodeState") {
clearTimeout(timer);
timer = setTimeout(load, 800);
}
});
await load();
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+104
View File
@@ -0,0 +1,104 @@
// Logs (BRIEF §14.8): server log tail and downloads, sign-in log, audit log.
import { t, has, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatDateTime, toast, errorText, routeParams } from "../ui.js";
import { pascal } from "../jobs.js";
const VIEWS = ["server", "signins", "audit"];
const LINES = [100, 300, 1000];
export async function render(root, { api, meta, actions }) {
let view = VIEWS.includes(routeParams().get("view")) ? routeParams().get("view") : "server";
let lines = 300;
let audit = [];
let cursor = null;
actions.innerHTML = `<div class="segmented" role="group">${VIEWS.map((v) =>
`<button class="btn" data-view="${v}" aria-pressed="${v === view}" data-i18n="Admin.Logs.View.${cap(v)}" data-i18n-title="Admin.Logs.View.${cap(v)}.Tip"></button>`).join("")}</div>`;
applyStrings(actions);
actions.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
view = b.dataset.view;
actions.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
history.replaceState(null, "", `#/logs?view=${view}`);
show();
}));
async function show() {
meta.textContent = "";
if (view === "server") await showServerLog();
else await showAudit(false);
}
async function showServerLog() {
let tail;
let files;
try {
[tail, files] = await Promise.all([api.get(`/api/v1/logs?lines=${lines}`), api.get("/api/v1/logs/files")]);
} catch (err) {
toast(errorText(err), true);
return;
}
meta.textContent = tail.file;
root.innerHTML = `
<div class="panel flush">
<div class="panel-head padded">
<select class="input small" id="lines" data-i18n-title="Admin.Logs.Lines.Tip">${LINES.map((n) => `<option value="${n}" ${n === lines ? "selected" : ""}>${escapeHtml(t("Admin.Logs.LineCount", n))}</option>`).join("")}</select>
<span class="spacer"></span>
<button class="btn small" id="refresh" data-i18n="Admin.Common.Refresh" data-i18n-title="Admin.Logs.Refresh.Tip"></button>
</div>
<pre class="log tall">${escapeHtml(tail.lines.join("\n"))}</pre>
</div>
<div class="panel">
<h2 data-i18n="Admin.Logs.Files"></h2>
<div class="table compact">${files.map((f) => `
<div class="row"><span class="mono">${escapeHtml(f.name)}</span><span class="num right">${escapeHtml(formatBytes(f.size))}</span>
<span class="muted">${escapeHtml(formatDateTime(f.modified))}</span>
<a class="btn small" href="/api/v1/logs/files/${encodeURIComponent(f.name)}" download="${attr(f.name)}" data-i18n="Admin.Logs.Download" data-i18n-title="Admin.Logs.Download.Tip"></a></div>`).join("")}
</div>
</div>`;
applyStrings(root);
const pre = root.querySelector("pre");
pre.scrollTop = pre.scrollHeight;
root.querySelector("#lines").addEventListener("change", (e) => {
lines = Number(e.target.value);
showServerLog();
});
root.querySelector("#refresh").addEventListener("click", showServerLog);
}
async function showAudit(more) {
const action = view === "signins" ? "&action=login" : "";
try {
const page = await api.get(`/api/v1/audit?limit=100${action}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
audit = more ? audit.concat(page.items) : page.items;
cursor = page.nextCursor;
} catch (err) {
toast(errorText(err), true);
return;
}
root.innerHTML = `
<div class="panel flush">
<div class="table audit">
<div class="thead"><span data-i18n="Admin.Logs.When"></span><span data-i18n="Admin.Logs.Who"></span><span data-i18n="Admin.Logs.What"></span>
<span data-i18n="Admin.Logs.Details"></span><span data-i18n="Admin.Logs.From"></span></div>
${audit.map((e) => `
<div class="row"><span class="num">${escapeHtml(formatDateTime(e.at))}</span><span>${escapeHtml(e.username ?? "—")}</span>
<span>${escapeHtml(actionLabel(e.action))}</span><span class="ellipsis" title="${attr(e.details ?? "")}">${escapeHtml(e.details ?? "")}</span>
<span class="mono">${escapeHtml(e.remoteAddress ?? "")}</span></div>`).join("") || `<div class="empty" data-i18n="Admin.Logs.Empty"></div>`}
</div>
<div class="table-foot"><span class="spacer"></span><button class="btn small" id="more" ${cursor ? "" : "hidden"} data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</div>`;
applyStrings(root);
root.querySelector("#more").addEventListener("click", () => showAudit(true));
}
await show();
}
function actionLabel(action) {
const key = `Admin.Logs.Action.${pascal(action)}`;
return has(key) ? t(key) : action;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
@@ -0,0 +1,108 @@
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment
// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart.
import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName } from "../ui.js";
/** Setting → environment variable that can fix it (BRIEF §14.9). */
const VARIABLES = {
serverName: "TITANO_SERVER_NAME", httpPort: "TITANO_HTTP_PORT", httpsPort: "TITANO_HTTPS_PORT", tlsMode: "TITANO_TLS_MODE",
tlsCert: "TITANO_TLS_CERT", tlsKey: "TITANO_TLS_KEY", language: "TITANO_LANG", workers: "TITANO_WORKERS", discovery: "TITANO_DISCOVERY",
};
const MB = 1e6;
const MIB = 1024 * 1024;
export async function render(root, { api, info, meta }) {
let settings;
try {
settings = await api.get("/api/v1/server/settings");
} catch (err) {
root.innerHTML = `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
return;
}
const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase());
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", VARIABLES[name] ?? 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" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value) => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${lock(name)}>`);
function draw() {
meta.textContent = "";
root.innerHTML = `
<form class="settings" novalidate>
<section class="panel">
<div class="panel-head"><h2 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>`)}
${number("workers", settings.workers, 'min="1" max="64"')}
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
</section>
<section class="panel">
<h2 data-i18n="Admin.Settings.Network"></h2>
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
${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)}
${text("tlsKey", settings.tlsKey)}
${field("fingerprint", `<input class="input mono" readonly value="${attr(info?.tlsFingerprint ?? "—")}" data-i18n-title="Admin.Settings.Fingerprint.Tip">`)}
</section>
<section class="panel">
<h2 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"')}
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
</section>
<div class="buttons"><button class="btn primary" type="submit" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button></div>
</form>`;
applyStrings(root);
root.querySelector("form").addEventListener("submit", save);
}
async function save(e) {
e.preventDefault();
const form = e.target;
const data = new FormData(form);
const value = (name, fallback) => (form.elements[name]?.disabled ? fallback : data.get(name));
const request = {
...settings,
serverName: String(value("serverName", settings.serverName)).trim(),
language: String(value("language", settings.language)),
workers: Number(value("workers", settings.workers)),
discovery: form.elements.discovery.disabled ? settings.discovery : form.elements.discovery.checked,
httpPort: Number(value("httpPort", settings.httpPort)),
httpsPort: Number(value("httpsPort", settings.httpsPort)),
tlsMode: String(value("tlsMode", settings.tlsMode)),
tlsCert: String(value("tlsCert", settings.tlsCert ?? "")).trim() || null,
tlsKey: String(value("tlsKey", settings.tlsKey ?? "")).trim() || null,
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")),
jobHistoryDays: Number(data.get("jobHistoryDays")),
};
try {
settings = await api.put("/api/v1/server/settings", request);
draw();
toast(t("Admin.Common.Saved"));
} catch (err) {
toast(errorText(err), true);
const name = err.details && Object.keys(form.elements).find((k) => k.toLowerCase() === String(err.details).toLowerCase());
const input = name ? form.elements[name] : null;
if (input) {
input.setAttribute("aria-invalid", "true");
input.title = errorText(err);
}
}
}
draw();
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+234
View File
@@ -0,0 +1,234 @@
// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset.
import { t, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText } from "../ui.js";
import { icons } from "../icons.js";
const ROLES = ["viewer", "uploader", "editor", "admin"];
const TB = 1e12;
const RENDER_NODE = 32;
export async function render(root, { api, info, meta, actions }) {
let users = [];
let filter = "";
let freeBytes = 0;
let tokenDays = 30;
actions.innerHTML = `
<input class="input search" type="search" id="search" data-i18n-placeholder="Admin.Users.Search" data-i18n-title="Admin.Users.Search.Tip" aria-label="${attr(t("Admin.Users.Search"))}">
<button class="btn primary" id="new" data-i18n="Admin.Users.New" data-i18n-title="Admin.Users.New.Tip"></button>`;
applyStrings(actions);
actions.querySelector("#search").addEventListener("input", (e) => {
filter = e.target.value.trim().toLowerCase();
drawTable();
});
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<div class="panel flush">
<div class="table users">
<div class="thead"><span data-i18n="Admin.Users.User"></span><span data-i18n="Admin.Users.Role"></span><span data-i18n="Admin.Users.Quota"></span>
<span data-i18n="Admin.Users.LastSeen"></span><span class="right" data-i18n="Admin.Users.Uploads"></span><span data-i18n="Admin.Users.Status"></span><span></span></div>
<div id="rows"></div>
</div>
<div class="table-foot"><span id="policy" class="muted"></span><span class="spacer"></span>
<a href="#/logs?view=signins" data-i18n="Admin.Users.SignInLog" data-i18n-title="Admin.Users.SignInLog.Tip"></a></div>
</div>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
async function load() {
try {
const [list, stats, settings] = await Promise.all([
api.get("/api/v1/users"),
api.get("/api/v1/archive/stats").catch(() => null),
api.get("/api/v1/server/settings").catch(() => null),
]);
users = list;
freeBytes = stats?.freeBytes ?? 0;
tokenDays = settings?.tokenLifetimeDays ?? tokenDays;
} catch (err) {
toast(errorText(err), true);
return;
}
const active = users.filter((u) => !u.user.disabled).length;
meta.textContent = t("Admin.Users.Meta", formatNumber(users.length), formatNumber(active));
root.querySelector("#policy").textContent = t("Admin.Users.Policy", info?.limits?.passwordMinLength ?? 10, tokenDays);
drawTable();
}
function drawTable() {
const rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter));
const host = root.querySelector("#rows");
host.innerHTML = rows.map((row) => {
const u = row.user;
const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null]
.filter(Boolean).join(" · ");
const quota = u.quotaBytes > 0
? `<div class="progress-cell">${bar(u.usedBytes / u.quotaBytes, u.disabled)}<span class="num nowrap">${escapeHtml(t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes)))}</span></div>`
: `<span class="muted">${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}</span>`;
const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—";
const buttons = u.disabled
? `<button class="btn small" data-act="enable" data-i18n="Admin.Users.Enable" data-i18n-title="Admin.Users.Enable.Tip"></button>
<button class="btn small destructive" data-act="delete" data-i18n="Admin.Users.Delete" data-i18n-title="Admin.Users.Delete.Tip"></button>`
: `<button class="btn small" data-act="edit" data-i18n="Admin.Users.Edit" data-i18n-title="Admin.Users.Edit.Tip"></button>
<button class="btn small" data-act="reset" data-i18n="Admin.Users.Reset" data-i18n-title="Admin.Users.Reset.Tip"></button>
${u.id === api.user().id ? "" : `<button class="btn small" data-act="disable" data-i18n="Admin.Users.Disable" data-i18n-title="Admin.Users.Disable.Tip"></button>`}`;
return `
<div class="row${u.disabled ? " dim" : ""}" data-id="${attr(u.id)}">
<span class="who"><span class="avatar ${attr(u.role)}">${escapeHtml(u.username.slice(0, 1).toUpperCase())}</span>
<span class="stack"><strong>${escapeHtml(u.username)}</strong><small>${escapeHtml(subtitle)}</small></span></span>
<span data-i18n="Admin.Role.${cap(u.role)}"></span>
<span>${quota}</span>
<span class="ellipsis">${escapeHtml(seen)}</span>
<span class="num right">${formatNumber(row.uploadsLast30Days)}</span>
<span class="${u.disabled ? "muted" : "state done"}">${u.disabled ? "○" : "●"} <span data-i18n="${u.disabled ? "Admin.Users.Disabled" : "Admin.Users.Active"}"></span></span>
<span class="row-actions">${buttons}</span>
</div>`;
}).join("") || `<div class="empty" data-i18n="Admin.Users.Empty"></div>`;
applyStrings(host);
host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => {
const row = users.find((u) => u.user.id === button.closest(".row").dataset.id);
act(button.dataset.act, row.user);
}));
}
async function act(action, user) {
try {
if (action === "edit") return openForm(user);
if (action === "reset") {
const r = await api.post(`/api/v1/users/${user.id}/reset-password`, {});
showPassword(r);
} else if (action === "disable" || action === "enable") {
await api.patch(`/api/v1/users/${user.id}`, { disabled: action === "disable" });
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Users.DeleteTitle", user.username),
body: t("Admin.Users.DeleteBody"),
confirm: t("Admin.Users.DeleteConfirm"),
confirmTip: t("Admin.Users.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: user.username,
});
if (!confirmed) return;
await api.del(`/api/v1/users/${user.id}`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
function openForm(user) {
const side = root.querySelector("#side");
const editing = user !== null;
const quotaTb = editing && user.quotaBytes > 0 ? +(user.quotaBytes / TB).toFixed(3) : 0;
const renderNode = editing ? (user.permissions & RENDER_NODE) !== 0 : false;
side.hidden = false;
side.innerHTML = `
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Users.EditTitle" : "Admin.Users.New"}"></h2>
<label><span data-i18n="Admin.Users.Username"></span>
<input class="input" name="username" required autocomplete="off" value="${attr(user?.username ?? "")}" ${editing ? "disabled" : ""} data-i18n-title="Admin.Users.Username.Tip"></label>
<label><span data-i18n="Admin.Users.DisplayName"></span>
<input class="input" name="displayName" autocomplete="off" value="${attr(user?.displayName ?? "")}" data-i18n-title="Admin.Users.DisplayName.Tip"></label>
<fieldset><legend data-i18n="Admin.Users.Role"></legend>
${ROLES.map((r) => `<label class="check"><input type="radio" name="role" value="${r}" ${(user?.role ?? "editor") === r ? "checked" : ""} data-i18n-title="Admin.Users.Role.${cap(r)}.Tip"><span data-i18n="Admin.Role.${cap(r)}"></span></label>`).join("")}
</fieldset>
<label><span data-i18n="Admin.Users.Quota"></span>
<span class="inline"><input class="input narrow" name="quota" type="number" min="0" step="0.1" value="${quotaTb}" data-i18n-title="Admin.Users.Quota.Tip"><span>TB</span>
<small class="muted">${escapeHtml(t("Admin.Users.FreeOnServer", formatBytes(freeBytes)))}</small></span></label>
${editing ? "" : `
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" name="password" autocomplete="off" value="${attr(generatePassword())}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="regenerate" data-i18n-title="Admin.Users.Regenerate.Tip">${icons.refresh}</button></span></label>
<label class="check"><input type="checkbox" checked disabled data-i18n-title="Admin.Users.MustChangeFlag.Tip"><span data-i18n="Admin.Users.MustChangeFlag"></span></label>`}
<label class="check"><input type="checkbox" name="renderNode" ${renderNode ? "checked" : ""} data-i18n-title="Admin.Users.RenderNode.Tip"><span data-i18n="Admin.Users.RenderNode"></span></label>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Users.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Users.Create.Tip"}"></button>
</div>
</form>`;
applyStrings(side);
const form = side.querySelector("form");
side.querySelector("#close").addEventListener("click", () => {
side.hidden = true;
});
side.querySelector("#regenerate")?.addEventListener("click", () => {
form.elements.password.value = generatePassword();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
const error = form.querySelector(".error");
error.textContent = "";
const data = new FormData(form);
const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB);
try {
if (editing) {
await api.patch(`/api/v1/users/${user.id}`, {
displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on",
});
side.hidden = true;
} else {
const r = await api.post("/api/v1/users", {
username: String(data.get("username")).trim(), displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes,
password: String(data.get("password")), allowRenderNode: data.get("renderNode") === "on",
});
showPassword(r);
}
await load();
} catch (err) {
error.textContent = errorText(err);
}
});
form.querySelector("input:not([disabled])").focus();
}
/** The one-time password of a new or reset account, shown once in the side panel. */
function showPassword(result) {
const side = root.querySelector("#side");
side.hidden = false;
side.innerHTML = `
<div class="form">
<h2>${escapeHtml(result.user.username)}</h2>
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" readonly value="${attr(result.temporaryPassword)}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="copy" data-i18n-title="Admin.Users.Copy.Tip">${icons.copy}</button></span></label>
<div class="buttons"><button class="btn" type="button" id="close" data-i18n="Admin.Common.Close" data-i18n-title="Admin.Common.Close.Tip"></button></div>
</div>`;
applyStrings(side);
side.querySelector("#copy").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(result.temporaryPassword);
toast(t("Admin.Users.Copied"));
} catch {
side.querySelector("input").select();
}
});
side.querySelector("#close").addEventListener("click", () => {
side.hidden = true;
});
}
await load();
}
/** Three groups of four unambiguous characters, like the server's own temporary passwords. */
function generatePassword() {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
const chars = [];
while (chars.length < 12) {
// Bytes at or above 248 (8 × 31) are skipped so every character is equally likely.
for (const b of crypto.getRandomValues(new Uint8Array(16))) {
if (b < 248 && chars.length < 12) chars.push(alphabet[b % alphabet.length]);
}
}
return `${chars.slice(0, 4).join("")}-${chars.slice(4, 8).join("")}-${chars.slice(8).join("")}`;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+146
View File
@@ -0,0 +1,146 @@
// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP.
import { t, culture } from "./i18n.js";
export function escapeHtml(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
/** Escaped attribute value for title="…" tooltips. */
export const attr = escapeHtml;
export function formatNumber(n) {
return new Intl.NumberFormat(culture()).format(n ?? 0);
}
/** 9.4 TB, 610 GB … (decimal units, like disk vendors and the desktop client). */
export function formatBytes(bytes) {
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let value = Number(bytes ?? 0);
let unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
const digits = value >= 100 || unit === 0 ? 0 : 1;
return `${new Intl.NumberFormat(culture(), { maximumFractionDigits: digits }).format(value)} ${units[unit]}`;
}
export function formatTime(iso) {
if (!iso) return "—";
const date = new Date(iso);
const sameDay = new Date().toDateString() === date.toDateString();
return new Intl.DateTimeFormat(culture(), sameDay ? { timeStyle: "short" } : { dateStyle: "medium" }).format(date);
}
export function formatDateTime(iso) {
return iso ? new Intl.DateTimeFormat(culture(), { dateStyle: "short", timeStyle: "medium" }).format(new Date(iso)) : "—";
}
export function formatDuration(seconds) {
const s = Math.max(0, Math.round(seconds ?? 0));
if (s >= 86400) return t("Common.Duration.Days", Math.floor(s / 86400), Math.floor((s % 86400) / 3600));
if (s >= 3600) return t("Common.Duration.Hours", Math.floor(s / 3600), Math.floor((s % 3600) / 60));
if (s >= 60) return t("Common.Duration.Minutes", Math.floor(s / 60));
return t("Common.Duration.Seconds", s);
}
/** 6 px progress bar drawn as SVG (attributes, not inline styles). */
export function bar(fraction, muted = false) {
const width = Math.max(0, Math.min(100, Math.round((fraction ?? 0) * 100)));
return `<svg class="bar${muted ? " muted" : ""}" viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">` +
`<rect class="track" width="100" height="6" rx="3"/><rect class="fill" width="${width}" height="6" rx="3"/></svg>`;
}
/**
* Column chart: values with labels under each bar and, when given, the value above it.
* Bars use the accent colour, or the sun colour for upload activity.
*/
export function columns(items, { sun = false, valueLabel = null, height = 190 } = {}) {
const width = 400;
const base = height - 30;
const max = Math.max(1, ...items.map((i) => i.value));
const step = width / Math.max(1, items.length);
const barWidth = Math.max(2, Math.min(32, step * 0.65));
let svg = `<svg class="chart${sun ? " sun" : ""}" viewBox="0 0 ${width} ${height}" role="img">`;
svg += `<line class="axis" x1="0" y1="${base}" x2="${width}" y2="${base}"/>`;
items.forEach((item, i) => {
const h = item.value > 0 ? Math.max(2, (item.value / max) * (base - 18)) : 0;
const x = i * step + (step - barWidth) / 2;
svg += `<rect class="column" x="${x.toFixed(1)}" y="${(base - h).toFixed(1)}" width="${barWidth.toFixed(1)}" height="${h.toFixed(1)}" rx="2"><title>${escapeHtml(item.title ?? "")}</title></rect>`;
if (valueLabel) svg += `<text class="value" x="${(x + barWidth / 2).toFixed(1)}" y="${(base - h - 5).toFixed(1)}">${escapeHtml(valueLabel(item))}</text>`;
if (item.label) svg += `<text class="label" x="${(x + barWidth / 2).toFixed(1)}" y="${base + 16}">${escapeHtml(item.label)}</text>`;
});
return svg + "</svg>";
}
/** Shows a toast at the bottom right for 8 s (hover pauses). */
export function toast(message, isError = false) {
const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" }));
const item = document.createElement("div");
item.className = `toast${isError ? " error" : ""}`;
item.setAttribute("role", isError ? "alert" : "status");
item.textContent = message;
host.appendChild(item);
let remaining = 8000;
let started = Date.now();
let timer = setTimeout(() => item.remove(), remaining);
item.addEventListener("mouseenter", () => {
clearTimeout(timer);
remaining -= Date.now() - started;
});
item.addEventListener("mouseleave", () => {
started = Date.now();
timer = setTimeout(() => item.remove(), remaining);
});
}
/**
* Two-button confirmation dialog (safe action left and default). Resolves true when the destructive action is chosen;
* with `typed`, that button stays disabled until the text is typed.
*/
export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) {
return new Promise((resolve) => {
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.innerHTML = `
<form method="dialog">
<h2>${escapeHtml(title)}</h2>
${body ? `<p>${escapeHtml(body)}</p>` : ""}
${typed ? `<input class="input" name="typed" autocomplete="off" title="${attr(typed)}" aria-label="${attr(typed)}" placeholder="${attr(typed)}">` : ""}
<div class="buttons">
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
<button class="btn destructive" value="ok" title="${attr(confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
</div>
</form>`;
document.body.appendChild(dialog);
const ok = dialog.querySelector('button[value="ok"]');
dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => {
ok.disabled = e.target.value !== typed;
});
dialog.addEventListener("close", () => {
resolve(dialog.returnValue === "ok");
dialog.remove();
});
dialog.showModal();
});
}
/** The localised message of an API failure, or the generic one when the server was not reached. */
export function errorText(err) {
return err?.message && err.status ? err.message : t("Admin.Error.Unreachable");
}
/** Query parameters of the hash route (#/logs?view=signins). */
export function routeParams() {
return new URLSearchParams(location.hash.split("?")[1] ?? "");
}
/** A language's own name ("Italiano"), for language menus. */
export function nativeName(code) {
try {
const name = new Intl.DisplayNames([code], { type: "language" }).of(code) ?? code;
return name.charAt(0).toLocaleUpperCase(code) + name.slice(1);
} catch {
return code;
}
}