diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 04fc6a2b..a7bc25c0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -89,7 +89,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, with `ReorganizePlanCache`: a dry run's plan, made apart from its request, kept a few minutes while what it reads from the index stays, for the same dry run and its confirmation; Convert's dry run and `convert` 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 (the archive module's `SequenceChanged` publishes `sequenceChanged` `reorganized`), uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step; `UploadService.ReceiveAgainAsync`: a verified upload whose filing was refused for now goes back to receiving, 503), render store (files a render under the sequence's lease, where the index has the folder then; `FolderMovedException`, 503 `folder_moved`, when the sequence is not in it); `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; `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) | +| `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; `convert.js` the Convert dialog of the Library's selection: format, JPEG quality and a mode chosen at every run (Replace or New sequence, never preselected), a debounced dry run of `POST /archive/convert` per sequence (photos converted, left as they are and why, blocked, size before and after, the space line), Apply that confirms Replace by a typed word and sends the shown plan's fingerprint back) | ### 2.5 Hosts diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index ede437a0..995367c7 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -9,6 +9,7 @@ Chronos Server Running for Version + {0} queued a conversion · {1}long {0} reorganized the archive · {1}long {0} changed the archive layoutlong {0} deleted {1}long @@ -83,6 +84,62 @@ Type the name exactly as shown to confirm Type the word exactly as shown; upper or lower case does not matter Type the word above first + Convert… + Convert the photos of the selected sequences to JPEG, TIFF-16 or linear DNG; a preview shows every sequence first + Convert… + Convert as the preview shows; a confirmation comes first + Close without converting anything + Choose Replace or New sequence to convert.long + Choose Replace or New sequence first + Converted + Sequence + Size + Unchanged + Convert + Queue the job that converts the photos into new sequences, each conversion verified; the originals are not touched + Replace + Queue the job that converts the photos, verifies each conversion and moves the originals to the trash + {0} photo is converted into a copy in a new sequence; the original stays as it is.long + {0} photos are converted into copies in a new sequence beside each one; the originals stay as they are.long + Convert to {0} in new sequences?long + {0} photo in {1} is replaced by its conversion; the original goes to the trash, restorable until it is emptied.long + {0} photos in {1} are replaced by their conversions; the originals go to the trash, restorable until it is emptied.long + Replace the originals with {0}?long + Format + JPEGinvariant: a file format's name + 8-bit JPEG with full colour detail at the quality set beside: the smallest files, opened by every program + Linear DNG + 16-bit linear DNG compressed without loss: the archival choice, opened by raw editors + TIFF-16invariant: a file format's name + 16-bit sRGB TIFF compressed without loss: large files that keep every tone for editing + A selected sequence is no longer in the archive; close and select again.long + Mode + New sequence + The converted copies go into a new sequence beside each one; the originals and their sequence stay exactly as they are + Replace + The converted files become the sequence's photos; the originals go to the archive's trash, restorable until it is emptied + Free some space on the archive's volume first + Nothing in the preview converts + Nothing to convert: every photo stays as it is, for the reasons shown.long + Open job + Show the job and its log on the Jobs page + {0} · {1} · {2}invariant; a sequence's title, the photos it converts, and their size before and after + Planning… + Preview + What each sequence converts and leaves as it is, with the size before and after (an estimate); nothing has changed yet + Quality + JPEG quality from 1 to 100; 95 keeps fine detail, lower values make smaller files + Write a whole number from 1 to 100.long + Conversion queued. + replacethe word typed to confirm replacing the originals, lower case + Size of the photos converted now, then the estimate after + {0} → {1}invariant; a size before and the estimated size after + {0}: {1}long: a photo count, then why those photos stay as they are + Convert {0} sequence + Convert {0} sequences + Convert all sequences + Convert takes at most {0} sequences at once, or every sequence: clear the filters and select all.long + Sequences converted: {0} · photos: {1} · unchanged: {2} · size: {3} → {4}long Recent activity All logs Open the audit log @@ -345,6 +402,7 @@ Sign in to administer this server User Your user name on this server + Photos converted Archive reorganized Archive layout Photos deleted @@ -823,9 +881,12 @@ {0} · {1} · {2}invariant; an entry's kind, title and size Restore Put the photos back into their sequence (a new one if it is gone); each is checked against its SHA-256 first + Put the originals back in place of their conversions while those are unchanged (the conversions go to the trash), else into a new sequence; each is checked against its SHA-256 first Move the sequence's folder back into the library as it is (next to its old place if that is taken); its photos are not hash-checked: Verify does that {0} photo restored into a new sequence.long {0} photos restored into a new sequence.long + {0} original is back in {1}; its conversion is in the trash.long + {0} originals are back in {1}; their conversions are in the trash.long {0} photo is back in {1}.long {0} photos are back in {1}.long {0} is back in the library.long diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index ff728d09..2f3b154f 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 messo in coda una conversione · {1} {0} ha riorganizzato l'archivio · {1} {0} ha modificato l'organizzazione dell'archivio {0} ha eliminato {1}long @@ -83,6 +84,58 @@ Digita il nome esattamente come mostrato per confermare Digita la parola come mostrata; maiuscole e minuscole non contano Prima digita la parola qui sopra + Converti… + Converti le foto delle sequenze selezionate in JPEG, TIFF-16 o DNG lineare; prima un'anteprima mostra ogni sequenza + Converti… + Converti come mostra l'anteprima; prima chiede conferma + Chiudi senza convertire nulla + Scegli Sostituisci o Nuova sequenza per convertire. + Prima scegli Sostituisci o Nuova sequenza + Convertite + Sequenza + Dimensione + Invariate + Converti + Metti in coda il job che converte le foto in nuove sequenze, verificando ogni conversione; gli originali non vengono toccati + Sostituisci + Metti in coda il job che converte le foto, verifica ogni conversione e sposta gli originali nel cestino + {0} foto viene convertita in una copia in una nuova sequenza; l'originale resta com'è. + {0} foto vengono convertite in copie, in una nuova sequenza accanto a ognuna; gli originali restano come sono. + Convertire in {0} in nuove sequenze? + {0} foto in {1} viene sostituita dalla sua conversione; l'originale va nel cestino, ripristinabile finché non viene svuotato. + {0} foto in {1} vengono sostituite dalle loro conversioni; gli originali vanno nel cestino, ripristinabili finché non viene svuotato. + Sostituire gli originali con {0}? + Formato + JPEG a 8 bit con il colore a piena risoluzione, alla qualità indicata accanto: i file più piccoli, aperti da ogni programma + DNG lineare + DNG lineare a 16 bit compresso senza perdita: la scelta per l'archivio, aperta dagli editor raw + TIFF sRGB a 16 bit compresso senza perdita: file grandi che conservano ogni tono per la modifica + Una sequenza selezionata non è più nell'archivio; chiudi e seleziona di nuovo. + Modalità + Nuova sequenza + Le copie convertite vanno in una nuova sequenza accanto a ognuna; gli originali e la loro sequenza restano esattamente come sono + Sostituisci + I file convertiti diventano le foto della sequenza; gli originali vanno nel cestino dell'archivio, ripristinabili finché non viene svuotato + Prima libera spazio sul volume dell'archivio + Nell'anteprima non c'è niente da convertire + Niente da convertire: ogni foto resta com'è, per i motivi indicati. + Apri job + Mostra il job e il suo log nella pagina Job + Pianificazione… + Anteprima + Cosa converte e cosa lascia com'è ogni sequenza, con la dimensione prima e dopo (una stima); niente è ancora cambiato + Qualità + Qualità JPEG da 1 a 100; 95 conserva i dettagli fini, valori più bassi danno file più piccoli + Scrivi un numero intero da 1 a 100. + Conversione in coda. + sostituisci + Dimensione delle foto convertite ora, poi la stima dopo + {0}: {1} + Converti {0} sequenza + Converti {0} sequenze + Converti tutte le sequenze + Converti al massimo {0} sequenze alla volta, o tutte: togli i filtri e seleziona tutto. + Sequenze convertite: {0} · foto: {1} · invariate: {2} · dimensione: {3} → {4} Attività recenti Tutti i log Apri il registro di controllo @@ -345,6 +398,7 @@ Accedi per amministrare questo server Utente Il tuo nome utente su questo server + Foto convertite Archivio riorganizzato Organizzazione archivio Foto eliminate @@ -820,9 +874,12 @@ Foto Ripristina Rimetti le foto nella loro sequenza (una nuova se non c'è più); prima ognuna viene controllata con il suo SHA-256 + Rimetti gli originali al posto delle conversioni finché queste sono invariate (le conversioni vanno nel cestino), altrimenti in una nuova sequenza; prima ognuno viene controllato con il suo SHA-256 Riporta la cartella della sequenza nella libreria così com'è (accanto al suo vecchio posto se è occupato); le sue foto non vengono controllate con l'hash: lo fa Verifica {0} foto ripristinata in una nuova sequenza.long {0} foto ripristinate in una nuova sequenza.long + {0} originale è di nuovo in {1}; la sua conversione è nel cestino. + {0} originali sono di nuovo in {1}; le loro conversioni sono nel cestino. {0} foto è di nuovo in {1}.long {0} foto sono di nuovo in {1}.long {0} è di nuovo nella libreria.long diff --git a/src/Chronos.Server/Admin/web/admin.css b/src/Chronos.Server/Admin/web/admin.css index 2a5a8ac9..0e87f5d9 100644 --- a/src/Chronos.Server/Admin/web/admin.css +++ b/src/Chronos.Server/Admin/web/admin.css @@ -433,14 +433,15 @@ dialog.dialog.reorganize { width: 960px; } .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; } +/* A dry run's table, Reorganize's and Convert's: scrolls inside the dialog, dimmed while it no longer matches the fields. */ +.reorg-preview, .plan-preview { max-height: 46vh; overflow: auto; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--bg); } +.reorg-preview:focus-visible, .plan-preview:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.reorg-preview.stale .table, .plan-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 .thead, .table.convert .thead { position: sticky; top: 0; z-index: 1; padding: 8px 12px; background: var(--bg); } +.table.reorg .row, .table.convert .row { min-height: 0; padding: 8px 12px; align-items: start; } +.table.reorg .row:hover, .table.convert .row:hover { background: none; } +.table.reorg .row:last-child, .table.convert .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; } @@ -448,11 +449,29 @@ dialog.dialog.reorganize { width: 960px; } .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); } +.reorg-preview .table-foot, .plan-preview .table-foot { padding: 8px 12px; border-top: 1px solid var(--stroke); } + +/* Convert dialog (owner review 2, R7, convert.js): format, JPEG quality and mode side by side (the mode never preselected), + the dry run's totals and space line, then per sequence the photos converted, those left as they are with why (what + blocks the whole sequence first, ▲ in the warning colour) and the size before and after. */ +dialog.dialog.convert { width: 960px; } +.convert-fields { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 12px 32px; } +.convert-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; } +.convert-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; } +.convert-choice[aria-invalid="true"] { outline: 2px solid var(--error); outline-offset: 4px; border-radius: var(--radius); } +.convert-quality .input { width: 88px; } +.convert-summary { display: grid; gap: 4px; min-height: 18px; color: var(--text-muted); } +.convert-space.short { color: var(--error); } +.convert-next { color: var(--text); } +.table.convert { grid-template-columns: minmax(140px, 1.3fr) max-content minmax(160px, 1.6fr) max-content; font-size: 12px; } +.plan-notes { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; color: var(--text-muted); } +.plan-notes .blocked { color: var(--warning); } + /* 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; } + .table.reorg, .table.convert { grid-template-columns: minmax(0, 1fr); } + .table.reorg .thead, .table.convert .thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .table.convert .end { justify-self: start; } } /* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */ diff --git a/src/Chronos.Server/Admin/web/audit.js b/src/Chronos.Server/Admin/web/audit.js index f7b8d8fa..464ac69a 100644 --- a/src/Chronos.Server/Admin/web/audit.js +++ b/src/Chronos.Server/Admin/web/audit.js @@ -80,6 +80,13 @@ export function detailText(entry) { 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(" · "); } + // Owner review 2, R7: "sequences · photos · target · mode", e.g. "2 · 120 · linear-dng · replace". + case "archive_converted": { + const [sequences, photos, target, mode] = details.split(" · "); + if (!/^\d+$/.test(sequences) || !/^\d+$/.test(photos ?? "")) return details; + return [plural("Admin.Library.Count", Number(sequences)), plural("Admin.Dashboard.PhotoCount", Number(photos)), + wireLabel("Admin.Convert.Format.", target), wireLabel("Admin.Convert.Mode.", mode)].filter(Boolean).join(" · "); + } default: return details; } @@ -107,6 +114,13 @@ function scheduleNameIn(parts) { return scheduleName({ systemKey, name: (systemKey ? parts.slice(1) : parts).join(" · ") }); } +/** A code of the API in words by its key under prefix ("linear-dng" → Admin.Convert.Format.LinearDng); else as recorded. */ +function wireLabel(prefix, code) { + if (!code) return ""; + const key = prefix + pascal(code); + return has(key) ? t(key) : code; +} + function splitLast(details) { const at = details.lastIndexOf(" · "); return at < 0 ? [details] : [details.slice(0, at), details.slice(at + 3)]; diff --git a/src/Chronos.Server/Admin/web/convert.js b/src/Chronos.Server/Admin/web/convert.js new file mode 100644 index 00000000..b917d50d --- /dev/null +++ b/src/Chronos.Server/Admin/web/convert.js @@ -0,0 +1,399 @@ +// Convert dialog of the admin panel (owner review 2, R7; BRIEF §12.5, §14.8): the photos of the Library's selection, or of +// every sequence, converted to JPEG, TIFF-16 or linear DNG. What happens to the originals is chosen at every run, never +// preselected: Replace (the converted files become the sequence's photos, the originals go to the archive's trash) or New +// sequence (converted copies in a new sequence, the source untouched). Each change asks the server for a dry run (nothing +// is touched) and the table shows, per sequence, what converts, what stays as it is and why, and the size before and +// after. Apply confirms that very plan by its fingerprint (Replace by typing a word), and the server runs it as a job +// (kind "convert") that verifies every converted file before anything changes. +import { t, plural, applyStrings } from "./i18n.js"; +import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js"; +import { listed } from "./pages/library/shared.js"; + +const ENDPOINT = "/api/v1/archive/convert"; +/** Wait after the last keystroke in Quality before the dry run, and the steps the table draws at a time. */ +const PLAN_DELAY = 400; +const PAGE = 200; +const DEFAULT_QUALITY = 95; +/** The formats, as the API names them, with their strings; linear DNG, the archival choice, is the one chosen first. */ +const TARGETS = [ + { value: "jpeg", label: "Admin.Convert.Format.Jpeg", tip: "Admin.Convert.Format.Jpeg.Tip" }, + { value: "tiff16", label: "Admin.Convert.Format.Tiff16", tip: "Admin.Convert.Format.Tiff16.Tip" }, + { value: "linear-dng", label: "Admin.Convert.Format.LinearDng", tip: "Admin.Convert.Format.LinearDng.Tip" }, +]; +const ARCHIVAL = "linear-dng"; +/** What happens to the originals; no default: the person converting chooses every time. */ +const MODES = [ + { value: "replace", label: "Admin.Convert.Mode.Replace", tip: "Admin.Convert.Mode.Replace.Tip" }, + { value: "new-sequence", label: "Admin.Convert.Mode.NewSequence", tip: "Admin.Convert.Mode.NewSequence.Tip" }, +]; +/** + * The mode the dry run is asked with while none is chosen: what converts does not depend on the mode, so the table shows + * the plan at once; Apply waits for a choice, and a choice other than this one plans again (the fingerprint names it). + */ +const PREVIEW_MODE = "new-sequence"; + +let dialogs = 0; + +/** + * Opens the Convert 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. Resolves when the dialog closes: the queued + * job, or null. + */ +export function openConvert({ api, target, names = new Map() } = {}) { + return new Promise((resolve) => { + const id = `convert-${++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 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.Convert.TitleAll") : plural("Admin.Convert.Title", target.sequenceIds.length); + const radio = (name, o, checked) => ``; + + const dialog = document.createElement("dialog"); + dialog.className = "dialog convert"; + dialog.setAttribute("aria-labelledby", `${id}-title`); + dialog.innerHTML = ` +
+

${escapeHtml(title)}

+
+
+ ${TARGETS.map((o) => radio("target", o, o.value === ARCHIVAL)).join("")}
+ +
+ ${MODES.map((o) => radio("mode", o, false)).join("")}
+
+
+ + + +
+ + +
+ + +
+
`; + document.body.appendChild(dialog); + applyStrings(dialog); + const form = dialog.querySelector("form"); + const quality = form.elements.quality; + const qualityField = dialog.querySelector(".convert-quality"); + const targetSet = dialog.querySelector('[data-field="target"]'); + const modeSet = dialog.querySelector('[data-field="mode"]'); + const totals = dialog.querySelector(".convert-totals"); + const space = dialog.querySelector(".convert-space"); + const next = dialog.querySelector(".convert-next"); + const preview = dialog.querySelector(".plan-preview"); + const rows = dialog.querySelector(".convert-rows"); + const foot = dialog.querySelector(".table-foot"); + const shownText = dialog.querySelector(".convert-shown"); + const errorLine = dialog.querySelector(".error"); + const closeButton = dialog.querySelector('[data-act="close"]'); + const applyButton = dialog.querySelector('[data-act="apply"]'); + + for (const set of [targetSet, modeSet]) { + set.addEventListener("change", () => { + clearInvalid(set); + showError(""); + drawQuality(); + // Choosing the mode the table was planned with needs no new dry run. + if (!planning && plan !== null && plan.key === keyNow()) drawPlan(); + else schedule(0); + }); + } + quality.addEventListener("input", () => { + clearInvalid(quality); + showError(""); + schedule(PLAN_DELAY); + }); + // Enter in Quality plans at once; only the Apply button changes anything. + form.addEventListener("submit", (e) => { + e.preventDefault(); + if (!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(); + drawQuality(); + targetSet.querySelector("input:checked").focus(); + schedule(0); + + /** The value of a choice's checked radio button, null while none is. */ + function chosen(set) { + return set.querySelector("input:checked")?.value ?? null; + } + + /** The quality typed, a whole number from 1 to 100, else null. */ + function qualityValue() { + const text = quality.value.trim(); + const n = Number(text); + return /^\d+$/.test(text) && n >= 1 && n <= 100 ? n : null; + } + + /** The request the fields make (without dryRun); its quality only for a JPEG, its mode the preview's until one is chosen. */ + function request() { + const body = target.all ? { all: true } : { all: false, sequenceIds: target.sequenceIds }; + const format = chosen(targetSet); + body.target = format; + body.quality = format === "jpeg" ? qualityValue() : null; + body.mode = chosen(modeSet) ?? PREVIEW_MODE; + return body; + } + + function keyNow() { + return JSON.stringify(request()); + } + + /** Quality is a JPEG's alone: hidden for the lossless formats. */ + function drawQuality() { + qualityField.hidden = chosen(targetSet) !== "jpeg"; + } + + /** 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 (!dialog.open) return; + if (planning) { + again = true; + return; + } + if (chosen(targetSet) === "jpeg" && qualityValue() === null) { + plan = null; + fieldError(quality, t("Admin.Convert.QualityRange")); + drawPlan(); + return; + } + const body = request(); + const key = JSON.stringify(body); + planning = true; + totals.textContent = t("Admin.Convert.Planning"); + drawButtons(); + try { + const answer = await api.post(ENDPOINT, { ...body, dryRun: true }); + if (!dialog.open) return; + plan = { ...answer, key }; + shown = PAGE; + 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 (!plan) { + totals.textContent = ""; + space.hidden = true; + next.hidden = true; + preview.hidden = true; + } else { + totals.textContent = plan.photos === 0 ? t("Admin.Convert.NothingToConvert") + : t("Admin.Convert.Totals", formatNumber(plan.sequences), formatNumber(plan.photos), formatNumber(plan.skipped), + formatBytes(plan.bytesBefore), formatBytes(plan.bytesAfter)); + space.hidden = plan.photos === 0; + space.textContent = plan.space.message; + space.classList.toggle("short", !plan.space.enough); + next.hidden = plan.photos === 0 || !plan.space.enough || chosen(modeSet) !== null; + preview.hidden = plan.steps.length === 0; + if (!preview.hidden) 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 sequence: its title and folder, the photos converted (or what blocks it), the photos left as they are with why, + * and the size of those converted before and after (an estimate). + */ + function rowHtml(s) { + const name = names.get(s.sequenceId) || s.title || folderName(s.folder); + const blocked = s.blocked ?? []; + const skipped = s.skipped ?? []; + const converts = blocked.length === 0 && s.photos > 0; + const count = converts ? `${escapeHtml(formatNumber(s.photos))}` : `—`; + // What blocks the whole sequence first, then the photos left as they are. + const notes = [...blocked.map((b) => `
  • ${escapeHtml(b.message)}
  • `), + ...skipped.map((k) => `
  • ${escapeHtml(t("Admin.Convert.SkippedPhotos", plural("Admin.Dashboard.PhotoCount", k.photos), k.message))}
  • `)]; + const left = notes.length > 0 ? `` : `—`; + const size = converts + ? `${escapeHtml(t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter)))}` + : `—`; + return `
    + ${escapeHtml(name)} + ${escapeHtml(s.folder || "/")} + ${count} + ${left} + ${size} +
    `; + } + + /** Apply waits for a current plan that converts something, with the space it needs, and for the mode; its tooltip says which. */ + function drawButtons() { + for (const field of form.querySelectorAll("input")) field.disabled = busy; + const current = plan !== null && plan.key === keyNow() && !planning; + const mode = chosen(modeSet); + const reason = !current ? null + : plan.photos === 0 ? "Admin.Convert.Nothing.Tip" + : !plan.space.enough ? "Admin.Convert.NoSpace.Tip" + : mode === null ? "Admin.Convert.ChooseMode.Tip" : null; + applyButton.disabled = busy || !current || reason !== null; + applyButton.title = t(reason ?? "Admin.Convert.Apply.Tip"); + closeButton.disabled = busy; + } + + /** + * Replace asks for a word to be typed (the originals leave the sequence for the trash); New sequence for a plain + * confirmation. The plan sent back is the one the table shows (the fields cannot change meanwhile). + */ + async function apply() { + if (applyButton.disabled) return; + const shownPlan = plan; + const body = JSON.parse(shownPlan.key); + const format = targetLabel(body.target); + const going = shownPlan.steps.filter((s) => (s.blocked ?? []).length === 0 && s.photos > 0); + const list = listed(going.map((s) => t("Admin.Convert.PlanItem", names.get(s.sequenceId) || s.title || folderName(s.folder), + plural("Admin.Dashboard.PhotoCount", s.photos), t("Admin.Convert.SizeChange", formatBytes(s.bytesBefore), formatBytes(s.bytesAfter))))); + const replace = body.mode === "replace"; + const confirmed = await confirmDialog(replace ? { + title: t("Admin.Convert.ConfirmReplaceTitle", format), + body: plural("Admin.Convert.ConfirmReplace", shownPlan.photos, plural("Admin.Library.Count", shownPlan.sequences)), + list, + confirm: t("Admin.Convert.Confirm.Replace"), + confirmTip: t("Admin.Convert.Confirm.Replace.Tip"), + cancel: t("Admin.Common.Keep"), + cancelTip: t("Admin.Common.Keep.Tip"), + typed: t("Admin.Convert.ReplaceWord"), + typedKind: "word", + } : { + title: t("Admin.Convert.ConfirmNewTitle", format), + body: plural("Admin.Convert.ConfirmNew", shownPlan.photos), + list, + confirm: t("Admin.Convert.Confirm.New"), + confirmTip: t("Admin.Convert.Confirm.New.Tip"), + cancel: t("Admin.Common.Keep"), + cancelTip: t("Admin.Common.Keep.Tip"), + }); + if (!confirmed || !dialog.open || plan !== shownPlan) return; + busy = true; + showError(""); + drawButtons(); + try { + const job = await api.post(ENDPOINT, { ...body, dryRun: false, fingerprint: shownPlan.fingerprint }); + queued = job; + busy = false; + dialog.close(); + toast(t("Admin.Convert.Queued"), false, + { label: t("Admin.Convert.OpenJob"), tip: t("Admin.Convert.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` }); + } catch (err) { + busy = false; + if (!dialog.open) return; + if (err?.code === "plan_changed" || err?.code === "not_enough_space" || err?.code === "nothing_to_convert") { + // The archive changed since the dry run (or its volume filled up): the new plan is shown, and Apply waits for it. + notice = err.code === "plan_changed" ? err.message || t("Admin.Error.Unreachable") : errorText(err); + plan = null; + schedule(0); + } else { + showProblem(err); + } + drawButtons(); + (applyButton.disabled ? closeButton : applyButton).focus(); + } + } + + /** A refusal on the field it names (quality, format, mode), else under the table. */ + function showProblem(err) { + const field = err?.code === "bad_request" ? { quality, target: targetSet, mode: modeSet }[err.details] : undefined; + if (field === quality) fieldError(quality, t("Admin.Convert.QualityRange")); + else if (field) fieldError(field, errorText(err)); + else if (err?.code === "not_found") showError(t("Admin.Convert.Gone")); + else showError(errorText(err)); + } + + /** The field's error border with the message as its tooltip (DESIGN §4), and the message in the dialog's alert line. */ + function fieldError(field, message) { + markInvalid(field, message); + showError(message); + } + + function showError(message) { + errorLine.textContent = message; + } + }); +} + +/** A format's name in the panel's language ("jpeg" → "JPEG", "linear-dng" → "Linear DNG"). */ +function targetLabel(value) { + const known = TARGETS.find((o) => o.value === value); + return known ? t(known.label) : String(value ?? ""); +} + +/** 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/pages/library.js b/src/Chronos.Server/Admin/web/pages/library.js index bf5a13c0..7ba07159 100644 --- a/src/Chronos.Server/Admin/web/pages/library.js +++ b/src/Chronos.Server/Admin/web/pages/library.js @@ -1,7 +1,8 @@ // 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). +// Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.js), Convert (R7) converts its +// photos to JPEG, TIFF-16 or linear DNG (convert.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"; @@ -9,6 +10,7 @@ import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage import { renderSequence } from "./library/sequence.js"; import { renderTrash } from "./library/trash.js"; import { openReorganize } from "../reorganize.js"; +import { openConvert } from "../convert.js"; const VIEW_KEY = "chronos.admin.library.view"; const PAGE = 100; @@ -345,6 +347,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { ${JOBS.map(job).join("")} + @@ -364,8 +367,9 @@ 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. + // Modal dialogs: the button stays enabled, so the focus comes back to it when the dialog closes. if (action === "reorganize") return reorganize(); + if (action === "convert") return convert(); button.disabled = true; try { if (action === "job") await queueJobs(button.dataset.kind); @@ -425,20 +429,36 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) { } /** - * Reorganize (owner review 2, R7) of the selected sequences: their ids, at most a bulk request's thousand (one plan, - * one job). Beyond that, every sequence of the archive, but only while the selection is exactly what Select all - * fetched without a filter and the archive has not grown since: a sequence unticked or added later is never included. + * What a plan-first mass operation (owner review 2, R7: Reorganize, Convert) works on: the selected sequences' ids, at + * most a bulk request's thousand (one plan, one job). Beyond that, every sequence of the archive, but only while the + * selection is exactly what Select all fetched without a filter and the archive has not grown since: a sequence unticked + * or added later is never included. Null, with tooMany's toast, otherwise. */ - async function reorganize() { + function planTarget(tooMany) { const ids = [...selection.ids]; const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length && ids.length === matching.length && matching.every((s) => selection.has(s.id)); if (!everything && ids.length > BULK_LIMIT) { - toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true); - return; + toast(t(tooMany, formatNumber(BULK_LIMIT)), true); + return null; } + return everything ? { all: true } : { sequenceIds: ids }; + } + + /** Reorganize of the selected sequences: new folder, file and title templates, with a dry run. */ + async function reorganize() { + const target = planTarget("Admin.Reorganize.TooMany"); + if (!target) return; const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle])); - await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }, names }); + await openReorganize({ api, target, names }); + } + + /** Convert of the selected sequences' photos: the format and, at every run, Replace or New sequence, with a dry run. */ + async function convert() { + const target = planTarget("Admin.Convert.TooMany"); + if (!target) return; + const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle])); + await openConvert({ api, target, names }); } async function retag() { diff --git a/src/Chronos.Server/Admin/web/pages/library/trash.js b/src/Chronos.Server/Admin/web/pages/library/trash.js index 658858a8..4aee5ac7 100644 --- a/src/Chronos.Server/Admin/web/pages/library/trash.js +++ b/src/Chronos.Server/Admin/web/pages/library/trash.js @@ -78,7 +78,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba ${escapeHtml(e.deletedBy ?? "—")} ${escapeHtml(formatDateTime(e.deletedAt))} + data-i18n-title="${restoreTip(e.kind)}" ${restoring.has(e.name) ? "disabled" : ""}> `).join("") || `
    ${emptyState("Admin.Trash.IsEmpty", ``)}
    `; @@ -104,8 +104,11 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba else draw(); return; } + // A replaced entry (owner review 2, R7) swaps back: its originals take their conversions' place, which go to the trash. const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title) - : result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)]; + : result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) + : result.kind === "replaced" ? plural("Admin.Trash.RestoredOriginals", result.photos, entry.title) + : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)]; // The server says, in the page's language, how many photos stayed in the trash and why (one sentence per reason). if (result.kept.length > 0 && result.message) lines.push(result.message); toast(lines.join(" "), result.kept.length > 0); @@ -212,6 +215,11 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba await load(); } +/** What Restore does to an entry of this kind: a sequence's folder back, photos back, or originals back in place of their conversions. */ +function restoreTip(kind) { + return kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : kind === "replaced" ? "Admin.Trash.RestoreReplaced.Tip" : "Admin.Trash.RestorePhotos.Tip"; +} + function kindLabel(kind) { return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos"); } diff --git a/tests/Chronos.Server.Tests/Hosting/AdminConvertTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminConvertTests.cs new file mode 100644 index 00000000..7fb863ef --- /dev/null +++ b/tests/Chronos.Server.Tests/Hosting/AdminConvertTests.cs @@ -0,0 +1,255 @@ +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.Imaging; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Protocol; +using Chronos.Server.Storage; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Hosting; + +/// +/// Convert on the admin panel (owner review 2, R7; Admin/web/convert.js): the Library's mass bar offers it, the dialog +/// module and its strings, the mode it never preselects and the typed confirmation of Replace, the audit entry read as a +/// sentence, 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, through the trash's undo of a Replace. +/// +[Category("server")] +public sealed partial class AdminConvertTests(TestContext context) +{ + private const string Url = "/api/v1/archive/convert"; + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(60)); + + [Test] + public async Task TheLibraryMassBarOpensTheConvertDialog() + { + await using var server = await TestServer.StartAsync(context); + var library = await server.Client.GetStringAsync("/admin/pages/library.js"); + Assert.Contains(@"from ""../convert.js""", library); + Assert.Contains(@"data-mass=""convert"" data-i18n=""Admin.Convert.Action"" data-i18n-title=""Admin.Convert.Action.Tip""", library); + Assert.Contains(@"if (action === ""convert"") return convert();", library); + // The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand). + Assert.Contains(@"const target = planTarget(""Admin.Convert.TooMany"");", library); + Assert.Contains("openConvert({ api, target, names })", library); + + using var response = await server.Client.GetAsync("/admin/convert.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 openConvert\(\{ api, target, "), "convert.js exports openConvert({ api, target, … })"); + var imports = StaticImport().Matches(dialog).Select(m => m.Groups[1].Value).ToList(); + Assert.SequenceEqual(["./i18n.js", "./ui.js", "./pages/library/shared.js"], imports); + foreach (var module in imports) + { + using var imported = await server.Client.GetAsync("/admin/" + module[2..]); + Assert.Equal(HttpStatusCode.OK, imported.StatusCode, module); + } + // Linear DNG, the archival choice, is the format chosen first; the mode is chosen at every run, never preselected. + Assert.Contains(@"TARGETS.map((o) => radio(""target"", o, o.value === ARCHIVAL))", dialog); + Assert.Contains(@"MODES.map((o) => radio(""mode"", o, false))", dialog); + Assert.Contains(@"const ARCHIVAL = ""linear-dng"";", dialog); + Assert.Contains(@"mode === null ? ""Admin.Convert.ChooseMode.Tip""", dialog); + // A dry run at every change; Replace has the word typed, New sequence a plain confirmation; Apply sends the shown + // plan's fingerprint back and links the job it queued. + Assert.Contains("api.post(ENDPOINT, { ...body, dryRun: true })", dialog); + Assert.Contains("api.post(ENDPOINT, { ...body, dryRun: false, fingerprint: shownPlan.fingerprint })", dialog); + Assert.True(Regex.IsMatch(dialog, @"confirmDialog\(replace \? \{[^}]*typed: t\(""Admin\.Convert\.ReplaceWord""\),\s+typedKind: ""word"",\s+\} : \{[^}]*\}\)", RegexOptions.Singleline), + "Replace asks for the word, New sequence does not"); + Assert.Contains("#/jobs?job=", dialog); + // The panel runs under a strict CSP: no inline handlers or styles. + Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler"); + Assert.True(!dialog.Contains(" style=", StringComparison.Ordinal), "inline style"); + + var audit = await server.Client.GetStringAsync("/admin/audit.js"); + Assert.Contains(@"case ""archive_converted"":", audit); + var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js"); + Assert.Contains(@"result.kind === ""replaced"" ? plural(""Admin.Trash.RestoredOriginals""", trash); + + 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)); + // Every whole key in quotes (not the prefixes audit.js completes with a wire name). + var keys = Regex.Matches(dialog + library + audit + trash, @"""(Admin\.(?:Convert\.[A-Za-z]+|Trash\.Restore[A-Za-z]*)(?:\.[A-Za-z]+)*)""") + .Select(m => m.Groups[1].Value).Distinct().ToList(); + Assert.Greater(keys.Count, 40); + foreach (var key in keys) + { + var name = en.ContainsKey(key) ? key : key + ".other"; + Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key); + } + // The audit entry's parts by the keys audit.js builds from the wire names. + foreach (var key in new[] { "Admin.Convert.Format.Jpeg", "Admin.Convert.Format.Tiff16", "Admin.Convert.Format.LinearDng", "Admin.Convert.Mode.Replace", + "Admin.Convert.Mode.NewSequence", "Admin.Logs.Action.ArchiveConverted", "Admin.Activity.ArchiveConverted" }) + Assert.True(en.ContainsKey(key) && it.ContainsKey(key), key); + Assert.Equal("Converti…", it["Admin.Convert.Action"]); + Assert.Equal("DNG lineare", it["Admin.Convert.Format.LinearDng"]); + } + + [Test] + public async Task TheDialogsRequestsPlanQueueAndUndoAConversion() + { + 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); + var italian = CultureInfo.GetCultureInfo("it"); + + // The body the dialog writes: the selection's ids, the format, the quality for a JPEG only, the mode (the preview's + // while none is chosen), then dryRun. + StringContent Body(string target, string quality, string mode, string tail) => + Json($$"""{"all":false,"sequenceIds":["{{id}}"],"target":"{{target}}","quality":{{quality}},"mode":"{{mode}}",{{tail}}}"""); + string preview; + using (var dry = await browser.SendAsync(HttpMethod.Post, Url, Body("linear-dng", "null", "new-sequence", "\"dryRun\":true"))) + { + await dry.ExpectAsync(HttpStatusCode.OK); + using var plan = JsonDocument.Parse(await dry.Content.ReadAsStringAsync()); + var root = plan.RootElement; + Assert.Equal(("linear-dng", "new-sequence"), (root.GetProperty("target").GetString(), root.GetProperty("mode").GetString())); + Assert.Equal((1, 2, 0), (root.GetProperty("sequences").GetInt32(), root.GetProperty("photos").GetInt32(), root.GetProperty("skipped").GetInt32())); + Assert.True(root.GetProperty("bytesBefore").GetInt64() > 0 && root.GetProperty("bytesAfter").GetInt64() > 0, "sizes"); + var space = root.GetProperty("space"); + Assert.True(space.GetProperty("enough").GetBoolean(), "enough"); + Assert.False(string.IsNullOrWhiteSpace(space.GetProperty("message").GetString())); + preview = root.GetProperty("fingerprint").GetString()!; + Assert.Equal(64, preview.Length); + var step = root.GetProperty("steps").EnumerateArray().Single(); + Assert.Equal(id, step.GetProperty("sequenceId").GetGuid()); + Assert.True(step.GetProperty("folder").GetString()!.Length > 0, "folder"); + Assert.Equal(JsonValueKind.String, step.GetProperty("title").ValueKind); + Assert.Equal(2, step.GetProperty("photos").GetInt32()); + Assert.True(step.GetProperty("bytesAfter").GetInt64() > 0, "bytesAfter"); + Assert.Equal((0, 0), (step.GetProperty("skipped").GetArrayLength(), step.GetProperty("blocked").GetArrayLength())); + } + + // Replace chosen: the same photos, another fingerprint, so the dialog plans again before Apply. + string fingerprint; + using (var dry = await browser.SendAsync(HttpMethod.Post, Url, Body("linear-dng", "null", "replace", "\"dryRun\":true"))) + { + using var plan = JsonDocument.Parse(await dry.Content.ReadAsStringAsync()); + Assert.Equal(2, plan.RootElement.GetProperty("photos").GetInt32()); + fingerprint = plan.RootElement.GetProperty("fingerprint").GetString()!; + Assert.NotEqual(preview, fingerprint); + } + + // A quality the server refuses names its field: the dialog marks Quality. + using (var bad = await browser.SendAsync(HttpMethod.Post, Url, Body("jpeg", "0", "replace", "\"dryRun\":true"))) + Assert.Equal("quality", (await bad.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details); + // JPEG to JPEG converts nothing: the table says why, in the page's language. + using (var same = await browser.SendAsync(HttpMethod.Post, Url, Body("jpeg", "90", "replace", "\"dryRun\":true"))) + { + using var plan = JsonDocument.Parse(await same.Content.ReadAsStringAsync()); + Assert.Equal(0, plan.RootElement.GetProperty("photos").GetInt32()); + var skipped = plan.RootElement.GetProperty("steps")[0].GetProperty("skipped").EnumerateArray().Single(); + Assert.Equal(("same_format", 2), (skipped.GetProperty("reason").GetString(), skipped.GetProperty("photos").GetInt32())); + Assert.Equal(Loc.Get("Archive.Convert.Skipped.SameFormat", italian), skipped.GetProperty("message").GetString()); + } + // 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("linear-dng", "null", "replace", $"\"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("linear-dng", "null", "replace", $"\"dryRun\":false,\"fingerprint\":\"{fingerprint}\""))) + { + await applied.ExpectAsync(HttpStatusCode.Accepted); + using var queued = JsonDocument.Parse(await applied.Content.ReadAsStringAsync()); + Assert.Equal("convert", queued.RootElement.GetProperty("kind").GetString()); + job = queued.RootElement.GetProperty("id").GetGuid(); + } + await UntilJobAsync(browser, job); + Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Dng), "converted"); + // The audit entry audit.js reads: sequences · photos · target · mode. + var entry = (await server.Database.Audit.ListAsync(null, "archive_converted", 10, null)).Items.Single(); + Assert.Equal("1 · 2 · linear-dng · replace", entry.Details); + + // The originals wait in the trash as a replaced entry; its Restore swaps them back (the toast the page shows). + string name; + using (var list = await browser.SendAsync(HttpMethod.Get, "/api/v1/archive/trash")) + { + using var trash = JsonDocument.Parse(await list.Content.ReadAsStringAsync()); + var replaced = trash.RootElement.GetProperty("entries").EnumerateArray().Single(e => e.GetProperty("kind").GetString() == "replaced"); + Assert.Equal(2, replaced.GetProperty("photos").GetInt32()); + name = replaced.GetProperty("name").GetString()!; + } + using (var restore = await browser.SendAsync(HttpMethod.Post, $"/api/v1/archive/trash/{Uri.EscapeDataString(name)}/restore")) + { + await restore.ExpectAsync(HttpStatusCode.OK); + using var result = JsonDocument.Parse(await restore.Content.ReadAsStringAsync()); + Assert.Equal(("replaced", false, 2), (result.RootElement.GetProperty("kind").GetString(), result.RootElement.GetProperty("newSequence").GetBoolean(), + result.RootElement.GetProperty("photos").GetInt32())); + } + Assert.True((await server.Database.Frames.ListBySequenceAsync(id)).All(f => f.Format == ImageFileFormat.Jpeg), "swapped back"); + } + + [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/AdminReorganizeTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs index c3408506..b69cc2f0 100644 --- a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs +++ b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs @@ -32,9 +32,12 @@ public sealed partial class AdminReorganizeTests(TestContext context) 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: its ids up to a thousand (one request); beyond, every sequence only while the selection is exactly - // what Select all fetched without a filter, the archive no larger since; a sequence unticked or added is never in it. - Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }", library); + // The selection (planTarget, shared with Convert): its ids up to a thousand (one request); beyond, every sequence only + // while the selection is exactly what Select all fetched without a filter, the archive no larger since; a sequence + // unticked or added is never in it. + Assert.Contains(@"const target = planTarget(""Admin.Reorganize.TooMany"");", library); + Assert.Contains("openReorganize({ api, target, names })", library); + Assert.Contains("return everything ? { all: true } : { sequenceIds: ids };", library); Assert.Contains("const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&", library); Assert.Contains("ids.length === matching.length && matching.every((s) => selection.has(s.id));", library); Assert.Contains("if (!everything && ids.length > BULK_LIMIT) {", library); diff --git a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs index 23fca807..ba59de75 100644 --- a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs +++ b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs @@ -185,8 +185,8 @@ public sealed partial class SystemEndpointTests(TestContext context) 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; 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" }) + // the Archive page import, Convert (R7) the one the Library 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", "reorganize.js", "convert.js" }) Assert.True(seen.ContainsKey(module), module); }