From 17efb50e11026cf3211273fe9226f5a123712b9b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 27 Oct 2026 12:44:59 +0100 Subject: [PATCH] feat(admin): Reorganize dialog in the Library and after the archive templates change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner review 2, R7 asks to rename and move sequences after import, on the web panel too. The Library's mass bar gets Reorganize… for the selection (every sequence after Select all without a filter, else at most a thousand ids), and saving a changed folder or file template on the Archive page offers it for all sequences in the save toast. The dialog (reorganize.js) has a switch and a field for the folder, file and title templates, prefilled from the archive settings; each change asks POST /archive/reorganize for a dry run, one request at a time, and the table shows every step before and after (title, folder, renamed files with samples, photos that keep their names and why). Apply confirms with the counts of sequences, folders and photos, sends the shown plan's fingerprint back, and the toast links to the queued job; a plan_changed refusal plans again. Server refusals land on the field they name. Toasts can carry an action; the audit entry archive_reorganized reads as a sentence. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 13939dff9a1e8a23ce7802ac38f2ded7fdbc2a74) --- docs/ARCHITECTURE.md | 2 +- i18n/en/Admin.resx | 53 +++ i18n/it/Admin.it.resx | 53 +++ src/Chronos.Server/Admin/web/admin.css | 33 ++ src/Chronos.Server/Admin/web/audit.js | 6 + src/Chronos.Server/Admin/web/pages/archive.js | 29 +- src/Chronos.Server/Admin/web/pages/library.js | 27 +- src/Chronos.Server/Admin/web/reorganize.js | 365 ++++++++++++++++++ src/Chronos.Server/Admin/web/ui.js | 44 ++- .../Hosting/AdminReorganizeTests.cs | 202 ++++++++++ .../Hosting/SystemEndpointTests.cs | 5 +- 11 files changed, 802 insertions(+), 17 deletions(-) create mode 100644 src/Chronos.Server/Admin/web/reorganize.js create mode 100644 tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ca94a3ca..534059ee 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -88,7 +88,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job), API errors, the WebSocket `EventHub` | | `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log | | `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability | -| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time) | +| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back) | ### 2.5 Hosts diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 3dfd7e8c..ff9dd9ae 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -9,6 +9,7 @@ Chronos Server Running for Version + {0} reorganized the archive · {1}long {0} changed the archive layoutlong {0} deleted {1}long {0} started {1}long @@ -343,6 +344,7 @@ Sign in to administer this server User Your user name on this server + Archive reorganized Archive layout Photos deleted Job started @@ -427,6 +429,57 @@ Change password Replace the password and continue to the panel Choose a new password + Reorganize… + Apply folder, file and title templates to the selected sequences; a preview shows every change first + After: + Apply… + Reorganize as the preview shows; a confirmation comes first + Before: + Write a template, or switch this part off.long + Close without changing anything + Carried + Moves only because a folder it is inside moves + Renamed files + Folder + Sequence + Reorganize + Queue the job that moves and renames the originals, each one verified; nothing is overwritten or deleted + {0} photo gets a new name.long + {0} photos get new names.long + {0} folder moves.long + {0} folders move.long + {0} sequence changes.long + {0} sequences change.long + Reorganize now? + Name of each photo as an import gives it, e.g. {date}_{time}_{n:0000}; the files beside a photo follow it + Files + Rename the photos of each sequence; off keeps every file name + {0} file renamedlong + {0} files renamedlong + Folder of each sequence in the archive, e.g. {year}/{date} {camera}; {title} is the new title + Folders + Move each sequence to the folder its template gives; off keeps every folder where it is + A selected sequence is no longer in the archive; close and select again.long + {0}: {1}long: a photo count, then why those photos keep their names + Switch on at least one part to change.long + Nothing to change: these sequences already follow the templates.long + Reorganize… + Apply the new templates to the sequences already in the archive; a preview shows every change first + Open job + Show the job and its log on the Jobs page + Planning… + Preview + What each sequence becomes, in the order the changes apply; nothing has changed yet + Reorganize queued. + This folder stays where it is + Reorganize {0} sequence + Reorganize {0} sequences + Reorganize all sequences + New title of each sequence, e.g. {date} {camera}; {title} is the current title + Titles + Give each sequence the title its template makes; off keeps every title + Reorganize takes at most {0} sequences at once, or every sequence: clear the filters and select all.long + Sequences changed: {0} · files renamed: {1} · names kept: {2}long Administrator Editor Uploader diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 59c94477..89c0ddaf 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -9,6 +9,7 @@ Chronos Server In esecuzione da Versione + {0} ha riorganizzato l'archivio · {1} {0} ha modificato l'organizzazione dell'archivio {0} ha eliminato {1}long {0} ha avviato {1} @@ -343,6 +344,7 @@ Accedi per amministrare questo server Utente Il tuo nome utente su questo server + Archivio riorganizzato Organizzazione archivio Foto eliminate Job avviato @@ -426,6 +428,57 @@ Cambia password Sostituisci la password e continua nel pannello Scegli una nuova password + Riorganizza… + Applica modelli di cartelle, file e titoli alle sequenze selezionate; un'anteprima mostra prima ogni modifica + Dopo: + Applica… + Riorganizza come mostra l'anteprima; prima chiede conferma + Prima: + Scrivi un modello, o disattiva questa parte. + Chiudi senza cambiare niente + Trasportata + Si sposta solo perché si sposta una cartella che la contiene + File rinominati + Cartella + Sequenza + Riorganizza + Metti in coda il job che sposta e rinomina gli originali, verificandoli uno per uno; niente viene sovrascritto o eliminato + {0} foto riceve un nuovo nome. + {0} foto ricevono un nuovo nome. + Si sposta {0} cartella. + Si spostano {0} cartelle. + Cambia {0} sequenza. + Cambiano {0} sequenze. + Riorganizzare ora? + Nome di ogni foto come lo dà un'importazione, es. {date}_{time}_{n:0000}; i file accanto a una foto la seguono + File + Rinomina le foto di ogni sequenza; spento mantiene ogni nome di file + {0} file rinominato + {0} file rinominati + Cartella di ogni sequenza nell'archivio, es. {year}/{date} {camera}; {title} è il nuovo titolo + Cartelle + Sposta ogni sequenza nella cartella data dal modello; spento lascia ogni cartella dov'è + Una sequenza selezionata non è più nell'archivio; chiudi e seleziona di nuovo. + {0}: {1} + Attiva almeno una parte da cambiare. + Niente da cambiare: queste sequenze seguono già i modelli. + Riorganizza… + Applica i nuovi modelli alle sequenze già nell'archivio; un'anteprima mostra prima ogni modifica + Apri job + Mostra il job e il suo log nella pagina Job + Pianificazione… + Anteprima + Cosa diventa ogni sequenza, nell'ordine in cui si applicano le modifiche; ancora non è cambiato niente + Riorganizzazione in coda. + Questa cartella resta dov'è + Riorganizza {0} sequenza + Riorganizza {0} sequenze + Riorganizza tutte le sequenze + Nuovo titolo di ogni sequenza, es. {date} {camera}; {title} è il titolo attuale + Titoli + Dai a ogni sequenza il titolo fatto dal modello; spento mantiene ogni titolo + Riorganizza al massimo {0} sequenze alla volta, o tutte: togli i filtri e seleziona tutto. + Sequenze cambiate: {0} · file rinominati: {1} · nomi mantenuti: {2} Amministratore Editor Caricamento diff --git a/src/Chronos.Server/Admin/web/admin.css b/src/Chronos.Server/Admin/web/admin.css index e23338a1..2a5a8ac9 100644 --- a/src/Chronos.Server/Admin/web/admin.css +++ b/src/Chronos.Server/Admin/web/admin.css @@ -294,6 +294,10 @@ dialog.dialog p { margin: 0; color: var(--text-muted); } #toasts { position: fixed; inset-inline-end: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; } .toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); } .toast.error { border-inline-start-color: var(--error); } +/* A toast with an action (Open job, Reorganize…): the message, then its link or button at the inline end. */ +.toast.with-action { display: flex; align-items: center; gap: 12px; } +.toast.with-action > span { flex: 1 1 auto; min-width: 0; } +.toast.with-action > .btn { flex: none; } /* Directional glyphs (icons.js) point along the reading direction; inside a left-to-right island (photos, time) they do not turn. */ svg.directional:dir(rtl) { transform: scaleX(-1); } @@ -422,6 +426,35 @@ dialog.upload.dragging .drop { border-color: var(--accent); background: var(--ac .upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; } .upload-total .progress-cell { flex: 1 1 0; } +/* Reorganize dialog (owner review 2, R7, reorganize.js): a switch and a field per template, the dry run's totals and its + steps (title, folder and renamed files, the old value struck through above the new one); paths stay left to right. */ +dialog.dialog.reorganize { width: 960px; } +.reorg-fields { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; align-items: center; } +.reorg-fields .field-error { grid-column: 2; color: var(--error); font-size: 12px; overflow-wrap: anywhere; } +.reorg-fields .field-error:empty { display: none; } +.reorg-totals { min-height: 18px; color: var(--text-muted); } +.reorg-preview { max-height: 46vh; overflow: auto; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--bg); } +.reorg-preview:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.reorg-preview.stale .table { opacity: .55; } +.table.reorg { grid-template-columns: minmax(120px, 1fr) minmax(160px, 1.3fr) minmax(160px, 1.3fr); font-size: 12px; } +.table.reorg .thead { position: sticky; top: 0; z-index: 1; padding: 8px 12px; background: var(--bg); } +.table.reorg .row { min-height: 0; padding: 8px 12px; align-items: start; } +.table.reorg .row:hover { background: none; } +.table.reorg .row:last-child { border-bottom: 0; } +.table.reorg .pill { align-self: flex-start; margin-block-start: 4px; } +.change { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.change .was { color: var(--text-muted); text-decoration: line-through; } +.path { font-family: var(--mono); overflow-wrap: anywhere; } +.reorg-samples, .reorg-kept { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; } +.reorg-samples { color: var(--text-muted); } +.reorg-kept { color: var(--warning); } +.reorg-preview .table-foot { padding: 8px 12px; border-top: 1px solid var(--stroke); } +/* Narrow windows: each step's cells one under the other; the column names stay for screen readers. */ +@media (max-width: 700px) { + .table.reorg { grid-template-columns: minmax(0, 1fr); } + .table.reorg .thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +} + /* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */ .about { scroll-margin-block-start: 84px; } .about h2:focus { outline: none; } diff --git a/src/Chronos.Server/Admin/web/audit.js b/src/Chronos.Server/Admin/web/audit.js index b803569e..f7b8d8fa 100644 --- a/src/Chronos.Server/Admin/web/audit.js +++ b/src/Chronos.Server/Admin/web/audit.js @@ -74,6 +74,12 @@ export function detailText(entry) { const [count, size] = details.split(" · "); return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details; } + // Owner review 2, R7: "sequences · files · folder template · file template · title template", a template empty when kept. + case "archive_reorganized": { + const [sequences, files, ...templates] = details.split(" · "); + if (!/^\d+$/.test(sequences) || !/^\d+$/.test(files ?? "")) return details; + return [plural("Admin.Library.Count", Number(sequences)), plural("Admin.Reorganize.FilesRenamed", Number(files)), ...templates.filter(Boolean)].join(" · "); + } default: return details; } diff --git a/src/Chronos.Server/Admin/web/pages/archive.js b/src/Chronos.Server/Admin/web/pages/archive.js index a85593ed..dcb77e65 100644 --- a/src/Chronos.Server/Admin/web/pages/archive.js +++ b/src/Chronos.Server/Admin/web/pages/archive.js @@ -1,7 +1,9 @@ // Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics, and the way to the -// archive's trash (the Library's trash view, owner review 2, R6). +// archive's trash (the Library's trash view, owner review 2, R6). New folder or file templates apply to new sequences; the +// toast of their save offers Reorganize (R7) to apply them to the sequences already in the archive. import { t, plural, applyStrings } from "../i18n.js"; import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js"; +import { openReorganize } from "../reorganize.js"; const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0]; const ACTIONS = ["scan", "rebuild", "verify", "maintenance"]; @@ -71,6 +73,7 @@ export async function render(root, { api, setMeta }) { e.preventDefault(); form.querySelectorAll("[aria-invalid]").forEach(clearInvalid); const data = new FormData(form); + const before = settings; try { settings = await api.put("/api/v1/archive/settings", { ...settings, @@ -86,7 +89,7 @@ export async function render(root, { api, setMeta }) { form.querySelectorAll("option").forEach((option) => { option.defaultSelected = option.selected; }); - toast(t("Admin.Common.Saved")); + savedToast(before, settings); } 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]; @@ -98,6 +101,28 @@ export async function render(root, { api, setMeta }) { toast(message, true); } }); + /** + * Saved; when the folder or file template changed and the archive has sequences, the toast offers Reorganize for all of + * them with the saved templates, the changed ones switched on. + */ + function savedToast(before, saved) { + const changed = [["folder", "folderTemplate"], ["file", "fileTemplate"]].filter(([, field]) => before[field] !== saved[field]).map(([part]) => part); + if (changed.length === 0 || stats.sequences === 0) { + toast(t("Admin.Common.Saved")); + return; + } + toast(t("Admin.Common.Saved"), false, { + label: t("Admin.Reorganize.Offer"), + tip: t("Admin.Reorganize.Offer.Tip"), + run: () => openReorganize({ + api, + target: { all: true }, + templates: { folderTemplate: saved.folderTemplate, fileTemplate: saved.fileTemplate, titleTemplate: saved.titleTemplate ?? "" }, + use: changed, + }), + }); + } + root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => { button.disabled = true; try { diff --git a/src/Chronos.Server/Admin/web/pages/library.js b/src/Chronos.Server/Admin/web/pages/library.js index 573b0286..1fccce80 100644 --- a/src/Chronos.Server/Admin/web/pages/library.js +++ b/src/Chronos.Server/Admin/web/pages/library.js @@ -1,12 +1,14 @@ // Library (owner review 2, R6; BRIEF §14.8): the panel browses, views and deletes sequences and photos and runs mass // operations on them, but never edits a video (no settings, no render). #/library lists the sequences with filters in the // address, #/library?id= opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js). +// Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.js). import { t, plural, applyStrings } from "../i18n.js"; import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, formDialog, markInvalid, emptyState, routeParams, redraw } from "../ui.js"; import { icons } from "../icons.js"; import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage, watchImages, Selection, selectableGrid, chunks, saveFile, sequencesCsv, today, tagList, coverUrl, listed, JOB_ENDED } from "./library/shared.js"; import { renderSequence } from "./library/sequence.js"; import { renderTrash } from "./library/trash.js"; +import { openReorganize } from "../reorganize.js"; const VIEW_KEY = "chronos.admin.library.view"; const PAGE = 100; @@ -256,8 +258,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { if (rows.length === 0) { itemsHost.removeAttribute("role"); itemsHost.removeAttribute("aria-multiselectable"); - const filtered = FILTERS.some((f) => f !== "sort" && filters[f]); - itemsHost.innerHTML = filtered + itemsHost.innerHTML = isFiltered() ? emptyState("Admin.Library.NoMatch", ``) : emptyState("Admin.Library.Empty", ``); applyStrings(itemsHost); @@ -343,6 +344,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { ${escapeHtml(plural("Admin.Library.Selected", selection.size))}${selectAll} ${JOBS.map(job).join("")} + @@ -362,6 +364,8 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { } if (action === "all") return selectAll(); if (action === "csv") return exportCsv(); + // A modal dialog: the button stays enabled, so the focus comes back to it when the dialog closes. + if (action === "reorganize") return reorganize(); button.disabled = true; try { if (action === "job") await queueJobs(button.dataset.kind); @@ -415,6 +419,25 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null); } + /** Whether a filter narrows the list (the sort order does not). */ + function isFiltered() { + return FILTERS.some((f) => f !== "sort" && filters[f]); + } + + /** + * Reorganize (owner review 2, R7) of the selected sequences: every sequence of the archive after Select all without a + * filter, else their ids, at most a bulk request's thousand (one plan, one job). + */ + async function reorganize() { + const everything = matching !== null && !isFiltered() && selection.size === matching.length; + if (!everything && selection.size > BULK_LIMIT) { + toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true); + return; + } + const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle])); + await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }, names }); + } + async function retag() { const datalist = facets.tags.map((f) => ``).join(""); const data = await formDialog({ diff --git a/src/Chronos.Server/Admin/web/reorganize.js b/src/Chronos.Server/Admin/web/reorganize.js new file mode 100644 index 00000000..0b05e6a2 --- /dev/null +++ b/src/Chronos.Server/Admin/web/reorganize.js @@ -0,0 +1,365 @@ +// Reorganize dialog of the admin panel (owner review 2, R7; BRIEF §12.5, §14.8): folder, file and title templates applied +// to sequences already in the archive, the Library's selection or every sequence. Each change of a template asks the +// server for a dry run (nothing is touched) and the table shows what every sequence becomes, in the order the changes +// apply. Apply confirms that very plan by its fingerprint, and the server runs it as a job (kind "move") that moves and +// renames the originals, verified, never overwriting or deleting one. +import { t, plural, applyStrings } from "./i18n.js"; +import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js"; + +const ENDPOINT = "/api/v1/archive/reorganize"; +/** Wait after the last keystroke before the dry run, and the steps the table draws at a time. */ +const PLAN_DELAY = 400; +const PAGE = 200; +/** The parts a Reorganize changes: the template's request field, its switch and its field, with their strings. */ +const PARTS = [ + { key: "folder", field: "folderTemplate", label: "Admin.Reorganize.Folders", use: "Admin.Reorganize.Folders.Tip", tip: "Admin.Reorganize.FolderTemplate.Tip" }, + { key: "file", field: "fileTemplate", label: "Admin.Reorganize.Files", use: "Admin.Reorganize.Files.Tip", tip: "Admin.Reorganize.FileTemplate.Tip" }, + { key: "title", field: "titleTemplate", label: "Admin.Reorganize.Titles", use: "Admin.Reorganize.Titles.Tip", tip: "Admin.Reorganize.TitleTemplate.Tip" }, +]; + +let dialogs = 0; + +/** + * Opens the Reorganize dialog. target is { all: true } (every sequence of the archive) or { sequenceIds } (at most a + * bulk request's thousand); names maps sequence ids to the titles the page shows. templates ({ folderTemplate, + * fileTemplate, titleTemplate }) fills the fields, else the archive's settings do; use lists the parts switched on + * ("folder", "file", "title"), else those with a template. Resolves when the dialog closes: the queued job, or null. + */ +export function openReorganize({ api, target, names = new Map(), templates = null, use = null } = {}) { + return new Promise((resolve) => { + const id = `reorganize-${++dialogs}`; + /** The last dry run, with key: the request it answers. */ + let plan = null; + let shown = PAGE; + let timer = null; + let planning = false; + let again = false; + let loaded = false; + let busy = false; + let queued = null; + /** A message the next plan shows (why the plan was made again). */ + let notice = ""; + const title = target.all ? t("Admin.Reorganize.TitleAll") : plural("Admin.Reorganize.Title", target.sequenceIds.length); + + const dialog = document.createElement("dialog"); + dialog.className = "dialog reorganize"; + dialog.setAttribute("aria-labelledby", `${id}-title`); + dialog.innerHTML = ` +
+

${escapeHtml(title)}

+
${PARTS.map((p) => ` + + + `).join("")} +
+
+ + +
+ + +
+
`; + document.body.appendChild(dialog); + applyStrings(dialog); + const form = dialog.querySelector("form"); + const totals = dialog.querySelector(".reorg-totals"); + const preview = dialog.querySelector(".reorg-preview"); + const rows = dialog.querySelector(".reorg-rows"); + const foot = dialog.querySelector(".table-foot"); + const shownText = dialog.querySelector(".reorg-shown"); + const errorLine = dialog.querySelector(".error"); + const closeButton = dialog.querySelector('[data-act="close"]'); + const applyButton = dialog.querySelector('[data-act="apply"]'); + const check = (p) => dialog.querySelector(`[data-part="${p.key}"]`); + const input = (p) => form.elements[p.field]; + const errorHost = (p) => dialog.querySelector(`[data-error="${p.key}"]`); + + for (const p of PARTS) { + check(p).addEventListener("change", () => { + clearField(p); + showError(""); + drawButtons(); + // A part switched on without a template: its field is where the next step is. + if (check(p).checked && input(p).value.trim() === "") { + input(p).focus(); + clearTimeout(timer); + preview.classList.add("stale"); + return; + } + schedule(0); + }); + input(p).addEventListener("input", () => { + clearField(p); + showError(""); + schedule(PLAN_DELAY); + }); + } + // Enter in a field plans at once; only the Apply button changes anything. + form.addEventListener("submit", (e) => { + e.preventDefault(); + if (loaded && !busy) schedule(0); + }); + closeButton.addEventListener("click", () => { + if (!busy) dialog.close(); + }); + applyButton.addEventListener("click", apply); + dialog.querySelector('[data-act="more"]').addEventListener("click", () => { + shown += PAGE; + drawRows(); + if (foot.hidden) preview.focus(); + }); + // Esc closes, except while the change is being sent. + dialog.addEventListener("cancel", (e) => { + if (busy) e.preventDefault(); + }); + const signedOut = () => dialog.close(); + window.addEventListener("chronos:signed-out", signedOut); + dialog.addEventListener("close", () => { + clearTimeout(timer); + window.removeEventListener("chronos:signed-out", signedOut); + dialog.remove(); + resolve(queued); + }); + dialog.showModal(); + start(); + + /** The templates to start from: given, or the archive's settings (and its title template when it has one). */ + async function start() { + let values = templates; + if (!values) { + try { + const settings = await api.get("/api/v1/archive/settings"); + values = { folderTemplate: settings.folderTemplate, fileTemplate: settings.fileTemplate, titleTemplate: settings.titleTemplate ?? "" }; + } catch (err) { + showError(errorText(err)); + values = {}; + } + } + if (!dialog.open) return; + const on = new Set(use ?? PARTS.filter((p) => String(values[p.field] ?? "").trim() !== "").map((p) => p.key)); + for (const p of PARTS) { + input(p).value = values[p.field] ?? ""; + check(p).checked = on.has(p.key); + } + loaded = true; + drawButtons(); + (PARTS.map(input).find((field) => !field.disabled) ?? check(PARTS[0])).focus(); + schedule(0); + } + + /** The request the fields make (without dryRun); null when no part is switched on. */ + function request() { + const body = target.all ? { all: true } : { all: false, sequenceIds: target.sequenceIds }; + let any = false; + for (const p of PARTS) { + if (!check(p).checked) continue; + body[p.field] = input(p).value.trim(); + any = true; + } + return any ? body : null; + } + + function keyNow() { + return JSON.stringify(request()); + } + + /** Plans again after delay ms; what the table shows until then no longer matches the fields. */ + function schedule(delay) { + clearTimeout(timer); + preview.classList.add("stale"); + drawButtons(); + timer = setTimeout(runPlan, delay); + } + + /** One dry run at a time: a change made while one is answered plans again right after it. */ + async function runPlan() { + if (!loaded || !dialog.open) return; + if (planning) { + again = true; + return; + } + const body = request(); + const blank = PARTS.find((p) => check(p).checked && input(p).value.trim() === ""); + if (!body || blank) { + plan = null; + if (blank) fieldError(blank, t("Admin.Reorganize.Blank")); + drawPlan(); + return; + } + const key = JSON.stringify(body); + planning = true; + totals.textContent = t("Admin.Reorganize.Planning"); + drawButtons(); + try { + const answer = await api.post(ENDPOINT, { ...body, dryRun: true }); + if (!dialog.open) return; + plan = { ...answer, key }; + shown = PAGE; + PARTS.forEach(clearField); + showError(notice); + notice = ""; + } catch (err) { + if (!dialog.open) return; + plan = null; + // A refusal of an older request is not shown: the fields changed since, and the next plan tells. + if (key === keyNow()) showProblem(err); + } finally { + planning = false; + } + if (again) { + again = false; + drawPlan(); + runPlan(); + return; + } + drawPlan(); + } + + function drawPlan() { + const current = plan !== null && plan.key === keyNow(); + preview.classList.toggle("stale", !current); + if (!request()) { + totals.textContent = t("Admin.Reorganize.NothingChosen"); + preview.hidden = true; + } else if (!plan) { + totals.textContent = ""; + preview.hidden = true; + } else if (plan.steps.length === 0) { + totals.textContent = t("Admin.Reorganize.NothingToChange"); + preview.hidden = true; + } else { + totals.textContent = t("Admin.Reorganize.Totals", formatNumber(plan.sequences), formatNumber(plan.files), formatNumber(plan.kept)); + preview.hidden = false; + drawRows(); + } + drawButtons(); + } + + function drawRows() { + const steps = plan.steps; + rows.innerHTML = steps.slice(0, shown).map(rowHtml).join(""); + foot.hidden = steps.length <= shown; + shownText.textContent = t("Admin.Library.Shown", formatNumber(Math.min(shown, steps.length)), formatNumber(steps.length)); + } + + /** One step: the sequence's title, its folder and its renamed files, before and after, with the photos that keep their names. */ + function rowHtml(s) { + const fromTitle = s.fromTitle ?? null; + const toTitle = s.toTitle ?? null; + const name = names.get(s.sequenceId) ?? toTitle ?? fromTitle ?? folderName(s.fromFolder); + const sequence = fromTitle !== toTitle ? change(fromTitle ?? name, toTitle ?? name, "auto") + : `${escapeHtml(name)}`; + const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path") + : `${escapeHtml(s.fromFolder || "/")}`; + const carried = s.carried + ? `${escapeHtml(t("Admin.Reorganize.Carried"))}` : ""; + const samples = (s.fileSamples ?? []).map((f) => `
  • ${escapeHtml(f.from)} → ${escapeHtml(f.to)}
  • `).join(""); + const files = s.fileChanges > 0 + ? `${escapeHtml(formatNumber(s.fileChanges))}${samples ? `
      ${samples}
    ` : ""}` + : `—`; + const kept = (s.blocked ?? []).map((b) => `
  • ${escapeHtml(b.photos > 0 + ? t("Admin.Reorganize.KeptPhotos", plural("Admin.Dashboard.PhotoCount", b.photos), b.message) : b.message)}
  • `).join(""); + return `
    + ${sequence}${carried} + ${folder} + ${files}${kept ? `
      ${kept}
    ` : ""}
    +
    `; + } + + function drawButtons() { + for (const p of PARTS) { + check(p).disabled = busy || !loaded; + input(p).disabled = busy || !loaded || !check(p).checked; + } + applyButton.disabled = busy || planning || plan === null || plan.key !== keyNow() || plan.sequences === 0; + closeButton.disabled = busy; + } + + /** The confirmation names what moves; the plan sent back is the one the table shows (the fields cannot change meanwhile). */ + async function apply() { + if (applyButton.disabled) return; + const chosen = plan; + const moves = chosen.steps.filter((s) => s.fromFolder !== s.toFolder).length; + const body = [plural("Admin.Reorganize.ConfirmSequences", chosen.sequences), + moves > 0 ? plural("Admin.Reorganize.ConfirmFolders", moves) : "", + chosen.files > 0 ? plural("Admin.Reorganize.ConfirmFiles", chosen.files) : ""].filter(Boolean).join(" "); + const confirmed = await confirmDialog({ + title: t("Admin.Reorganize.ConfirmTitle"), + body, + confirm: t("Admin.Reorganize.Confirm"), + confirmTip: t("Admin.Reorganize.Confirm.Tip"), + cancel: t("Admin.Common.Keep"), + cancelTip: t("Admin.Common.Keep.Tip"), + }); + if (!confirmed || !dialog.open || plan !== chosen) return; + busy = true; + showError(""); + drawButtons(); + try { + const job = await api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint }); + queued = job; + busy = false; + dialog.close(); + toast(t("Admin.Reorganize.Queued"), false, + { label: t("Admin.Reorganize.OpenJob"), tip: t("Admin.Reorganize.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` }); + } catch (err) { + busy = false; + if (!dialog.open) return; + if (err?.code === "plan_changed") { + // The archive changed since the dry run: the new plan is shown, and Apply waits for it. + notice = err.message || t("Admin.Error.Unreachable"); + plan = null; + schedule(0); + } else { + showProblem(err); + } + drawButtons(); + (applyButton.disabled ? closeButton : applyButton).focus(); + } + } + + /** A refusal on the field it names (a template, or the folders for a nested target), else under the table. */ + function showProblem(err) { + const part = PARTS.find((p) => p.field === err?.details); + if (err?.code === "invalid_template" && part) fieldError(part, err.message); + else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details); + else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone")); + else showError(errorText(err)); + } + + function fieldError(part, message, path = "") { + markInvalid(input(part), path ? `${message} ${path}` : message); + errorHost(part).innerHTML = escapeHtml(message) + (path ? ` ${escapeHtml(path)}` : ""); + } + + function clearField(part) { + clearInvalid(input(part)); + errorHost(part).textContent = ""; + } + + function showError(message) { + errorLine.textContent = message; + } + }); +} + +/** Old and new value, one above the other; screen readers hear which is which. */ +function change(was, now, dir, cls = "") { + return `${escapeHtml(t("Admin.Reorganize.Before"))} ${escapeHtml(was)}` + + `${escapeHtml(t("Admin.Reorganize.After"))} ${escapeHtml(now)}`; +} + +/** The last part of a sequence folder ("2026/2026-09-28 Roof" → "2026-09-28 Roof"), its name when it has no title. */ +function folderName(folder) { + return String(folder ?? "").split("/").filter(Boolean).pop() ?? "—"; +} diff --git a/src/Chronos.Server/Admin/web/ui.js b/src/Chronos.Server/Admin/web/ui.js index 39f6629d..67637d1a 100644 --- a/src/Chronos.Server/Admin/web/ui.js +++ b/src/Chronos.Server/Admin/web/ui.js @@ -122,25 +122,49 @@ export function emptyState(sentenceKey, button = "") { return `
    ${button}
    `; } -/** Shows a toast at the bottom (inline end) for 8 s (hover pauses). */ -export function toast(message, isError = false) { +/** + * Shows a toast at the bottom (inline end) for 8 s, 15 s with an action (the pointer over it or the keyboard focus in it + * pauses). action ({ label, tip, href } or { label, tip, run }) adds a link or a button after the message, which closes + * the toast. + */ +export function toast(message, isError = false, action = null) { 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.className = `toast${isError ? " error" : ""}${action ? " with-action" : ""}`; item.setAttribute("role", isError ? "alert" : "status"); - item.textContent = message; + item.appendChild(Object.assign(document.createElement("span"), { textContent: message })); + if (action) { + const control = document.createElement(action.href ? "a" : "button"); + control.className = "btn small"; + if (action.href) control.href = action.href; + else control.type = "button"; + control.textContent = action.label; + control.title = action.tip; + control.addEventListener("click", () => { + item.remove(); + action.run?.(); + }); + item.appendChild(control); + } host.appendChild(item); - let remaining = 8000; + let remaining = action ? 15000 : 8000; let started = Date.now(); let timer = setTimeout(() => item.remove(), remaining); - item.addEventListener("mouseenter", () => { + let held = 0; + const pause = () => { + if (held++ > 0) return; clearTimeout(timer); remaining -= Date.now() - started; - }); - item.addEventListener("mouseleave", () => { + }; + const resume = () => { + if (--held > 0) return; started = Date.now(); - timer = setTimeout(() => item.remove(), remaining); - }); + timer = setTimeout(() => item.remove(), Math.max(remaining, 2000)); + }; + item.addEventListener("mouseenter", pause); + item.addEventListener("mouseleave", resume); + item.addEventListener("focusin", pause); + item.addEventListener("focusout", resume); } let dialogs = 0; diff --git a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs new file mode 100644 index 00000000..58b5c706 --- /dev/null +++ b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs @@ -0,0 +1,202 @@ +using System.Globalization; +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Chronos.Core.Codecs.Jpeg; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Protocol; +using Chronos.Server.Storage; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Hosting; + +/// +/// Reorganize on the admin panel (owner review 2, R7; Admin/web/reorganize.js): where the panel offers it (the +/// Library's mass bar, the Archive page's save toast), the dialog module and its strings, and the requests the dialog +/// writes, sent through the cookie session as api.js sends them and read back by the names the dialog reads. +/// +[Category("server")] +public sealed partial class AdminReorganizeTests(TestContext context) +{ + private const string Url = "/api/v1/archive/reorganize"; + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30)); + + [Test] + public async Task TheLibraryAndTheArchivePageOpenTheReorganizeDialog() + { + await using var server = await TestServer.StartAsync(context); + var library = await server.Client.GetStringAsync("/admin/pages/library.js"); + Assert.Contains(@"from ""../reorganize.js""", library); + Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library); + Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library); + // The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand). + Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }", library); + Assert.Contains("selection.size > BULK_LIMIT", library); + var archive = await server.Client.GetStringAsync("/admin/pages/archive.js"); + Assert.Contains(@"from ""../reorganize.js""", archive); + Assert.Contains("target: { all: true }", archive); + + using var response = await server.Client.GetAsync("/admin/reorganize.js"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType); + var dialog = await response.Content.ReadAsStringAsync(); + Assert.True(Regex.IsMatch(dialog, @"export function openReorganize\(\{ api, target, "), "reorganize.js exports openReorganize({ api, target, … })"); + var imports = StaticImport().Matches(dialog).Select(m => m.Groups[1].Value).ToList(); + Assert.SequenceEqual(["./i18n.js", "./ui.js"], imports); + foreach (var module in imports) + { + using var imported = await server.Client.GetAsync("/admin/" + module[2..]); + Assert.Equal(HttpStatusCode.OK, imported.StatusCode, module); + } + // A dry run at every change; Apply sends that plan's fingerprint back and links the job it queued. + Assert.Contains("api.post(ENDPOINT, { ...body, dryRun: true })", dialog); + Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog); + Assert.Contains("#/jobs?job=", dialog); + Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler"); + + var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString)); + var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString)); + foreach (var key in Regex.Matches(dialog + library + archive, @"""(Admin\.Reorganize\.[A-Za-z.]+)""").Select(m => m.Groups[1].Value).Distinct()) + { + var name = en.ContainsKey(key) ? key : key + ".other"; + Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key); + } + Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]); + } + + [Test] + public async Task TheDialogsRequestsPlanAndQueueAReorganize() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + Guid id = default; + for (var i = 0; i < 2; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId; + await UntilIdleAsync(server); + var browser = await Browser.SignInAsync(server); + + // The body the dialog writes: the selection's ids and the parts switched on, then dryRun. + StringContent Body(string tail) => + Json($$"""{"all":false,"sequenceIds":["{{id}}"],"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","titleTemplate":"Roof",{{tail}}}"""); + string fingerprint; + using (var dry = await browser.SendAsync(HttpMethod.Post, Url, Body("\"dryRun\":true"))) + { + await dry.ExpectAsync(HttpStatusCode.OK); + using var plan = JsonDocument.Parse(await dry.Content.ReadAsStringAsync()); + var root = plan.RootElement; + Assert.Equal((1, 2, 0), (root.GetProperty("sequences").GetInt32(), root.GetProperty("files").GetInt32(), root.GetProperty("kept").GetInt32())); + fingerprint = root.GetProperty("fingerprint").GetString()!; + Assert.Equal(64, fingerprint.Length); + var step = root.GetProperty("steps").EnumerateArray().Single(); + Assert.Equal(id, step.GetProperty("sequenceId").GetGuid()); + Assert.True(step.GetProperty("fromFolder").GetString()!.Length > 0, "fromFolder"); + Assert.Equal("reorganized/Roof", step.GetProperty("toFolder").GetString()); + Assert.Equal("Roof", step.GetProperty("toTitle").GetString()); + Assert.False(step.GetProperty("carried").GetBoolean()); + Assert.Equal(2, step.GetProperty("fileChanges").GetInt32()); + var sample = step.GetProperty("fileSamples").EnumerateArray().First(); + Assert.True(sample.GetProperty("from").GetString()!.StartsWith("originals/", StringComparison.Ordinal), "from"); + Assert.Equal("originals/Roof_001.JPG", sample.GetProperty("to").GetString()); + Assert.Equal(0, step.GetProperty("blocked").GetArrayLength()); + } + + // A template the server refuses names its field, in the page's language: the dialog marks that field. + using (var bad = await browser.SendAsync(HttpMethod.Post, Url, Json("""{"all":true,"fileTemplate":"{nope}","dryRun":true}"""))) + { + var error = await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template"); + Assert.Equal("fileTemplate", error.Details); + Assert.Equal(Loc.Get("Server.Error.InvalidTemplate", CultureInfo.GetCultureInfo("it")), error.Message); + } + // A plan that no longer matches is refused with the one there is now: the dialog plans again. + using (var stale = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{new string('0', 64)}\""))) + Assert.Equal(fingerprint, (await stale.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details); + + Guid job; + using (var applied = await browser.SendAsync(HttpMethod.Post, Url, Body($"\"dryRun\":false,\"fingerprint\":\"{fingerprint}\""))) + { + await applied.ExpectAsync(HttpStatusCode.Accepted); + using var queued = JsonDocument.Parse(await applied.Content.ReadAsStringAsync()); + Assert.Equal("move", queued.RootElement.GetProperty("kind").GetString()); + job = queued.RootElement.GetProperty("id").GetGuid(); + } + await UntilJobAsync(browser, job); + var sequence = Assert.NotNull(await server.Database.Sequences.GetAsync(id)); + Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title)); + + // Every sequence (Select all without a filter) with the same templates: nothing is left to change. + using var again = await browser.SendAsync(HttpMethod.Post, Url, + Json("""{"all":true,"folderTemplate":"reorganized/{title}","fileTemplate":"{title}_{n:000}","dryRun":true}""")); + await again.ExpectAsync(HttpStatusCode.OK); + using var none = JsonDocument.Parse(await again.Content.ReadAsStringAsync()); + Assert.Equal(0, none.RootElement.GetProperty("sequences").GetInt32()); + Assert.Equal(0, none.RootElement.GetProperty("steps").GetArrayLength()); + } + + [GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")] + private static partial Regex StaticImport(); + + private static async Task UntilJobAsync(Browser browser, Guid id) + { + var until = DateTime.UtcNow + Wait; + while (true) + { + using var response = await browser.SendAsync(HttpMethod.Get, $"/api/v1/jobs/{id}"); + var job = await response.ReadAsync(ProtocolJson.Default.JobDto); + if (job.State == "done") return; + if (job.State is "failed" or "cancelled") Assert.Fail($"job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}"); + Assert.True(DateTime.UtcNow < until, $"job {job.Kind} still {job.State}"); + await Task.Delay(50); + } + } + + /// Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue). + private static async Task UntilIdleAsync(TestServer server) + { + var until = DateTime.UtcNow + Wait; + foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running }) + { + while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0) + { + Assert.True(DateTime.UtcNow < until, $"jobs still {state}"); + await Task.Delay(50); + } + } + } + + private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json"); + + private static byte[] Photo(int seed) + { + const int width = 96, height = 64; + var pixels = new byte[width * height * 3]; + for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251); + return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 }); + } + + /// The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as api.js does. + private sealed class Browser(HttpClient client, string csrfToken) + { + public static async Task SignInAsync(TestServer server) + { + await server.AdminAsync(); + var cookies = new CookieContainer(); + var client = server.NewCookieClient(cookies); + using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true), + ProtocolJson.Default.LoginRequest); + await login.ExpectAsync(HttpStatusCode.OK); + return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value); + } + + /// JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET. + public async Task SendAsync(HttpMethod method, string url, HttpContent? content = null) + { + using var request = new HttpRequestMessage(method, url) { Content = content }; + request.Headers.Accept.ParseAdd("application/json"); + request.Headers.AcceptLanguage.ParseAdd("it"); + if (method != HttpMethod.Get) request.Headers.Add("X-CSRF-Token", csrfToken); + return await client.SendAsync(request); + } + } +} diff --git a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs index f818b65b..23fca807 100644 --- a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs +++ b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs @@ -184,8 +184,9 @@ public sealed partial class SystemEndpointTests(TestContext context) var seen = await ModulesAsync(server); Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys)); // The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the - // dialog, its hash worker and the in-house SHA-256 the worker imports. - foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" }) + // dialog, its hash worker and the in-house SHA-256 the worker imports; Reorganize (R7) is the dialog the Library and + // the Archive page import. + foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js", "reorganize.js" }) Assert.True(seen.ContainsKey(module), module); }