diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a5f2d4ec..ca94a3ca 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -40,9 +40,9 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Render` | Render plan (timing modes), preparation pass, geometry, `RenderPipeline`, self-test suite | | `Export` | Preset resolution, encoder selection with fallbacks, output naming | | `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | -| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans | +| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`; `FrameCompanions`: the XMP files that follow a photo) | | `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) | -| `Naming` | Folder/file templates and tokens | +| `Naming` | Folder/file templates and tokens; `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize) | | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Diagnostics` | `Log` (never throws: a line its sink cannot write is dropped), `FileLogSink` with `LogFileOptions` (level, daily or hourly files, numbered parts past a size, pruning by age and by the total size, never the file being written), synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | @@ -58,7 +58,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Jobs` | `JobEngine` (one job at a time; reviews the priority queue and makes a lower running job yield, requeued with its checkpoint; no history purge, the housekeeping schedule's clean-up does it), `JobPriorityQueue` (a level per job kind, the claim order, settings round trip), `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs that never interrupt their parent), `JobThroughput`/`JobEta` (rate and bounded time left) | | `Scheduling` | `Scheduler` (one per host: seeds the host's system schedules, claims due runs by compare-and-set, catch-up, clock changes, create/edit/reset/delete/run now as API v1 DTOs), `ScheduleRecurrence` (the in-house `every:`/`daily:`/`weekly:`/`monthly:` form, wall-clock times across DST), `ScheduleActions` (action names, parameters, availability, the archive jobs a run queues), `IScheduleHost` and `SystemSchedule` (what the server and the desktop supply), `ScheduleOutcome`, `ScheduleMapping` (model ↔ DTO) | | `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` | -| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer`, `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed), job handlers | +| `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance`, `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; steps move the folder, then the title, then the files under the plan's journal in `journal/`, a plan its job held left to that job; the file renames of a step checked against the planned frames version, then sidecar, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed), job handlers | | `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers | | `Sync` | `SyncService` (sync table of one server: compare, link by content, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, no I/O), `SyncTombstones` (photos either side removed are not offered back, a replaced photo counts as its replacement), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) | @@ -85,7 +85,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) | | `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) | | `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` | -| `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), API errors, the WebSocket `EventHub` | +| `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) | @@ -115,7 +115,8 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Backup` | `Housekeeping/BackupJobHandler` (via `ArchiveService.CreateJobHandlers`; an SQLite index file only) | yes | SQLite only | | `Cleanup` | `Housekeeping/CleanupJobHandler` (shared steps, plus the host's from `ArchiveServiceOptions.CleanupSteps`) | yes | yes | | `EmptyTrash` | `Archiving/Jobs/EmptyTrashJobHandler` (erases exactly a confirmed plan's trash entries; refuses a stale fingerprint) | yes | yes | -| `Adopt`, `Move` | none: done synchronously (`ArchiveService` actions) | — | — | +| `Move` | `Archiving/Jobs/MoveJobHandler` (Reorganize: plans again from the templates, applies the plan only while it is the one confirmed, holds it when paused or cancelled) | yes | yes | +| `Adopt` | none: done synchronously (`ArchiveService` actions) | — | — | A job engine claims only kinds it has handlers for. Light analysis is queued by the engine (`JobContext` follow-up) after an import or a scan that indexed something; screens never queue it again. Recurring work is queued by the host's diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 2a20d805..3dfd7e8c 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -138,7 +138,7 @@ Import Light analysis Maintenance - Move + Reorganize Orphans Proxies Rebuild diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 5b747fd9..e282f81f 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -86,6 +86,8 @@ {0} was written by a newer Chronos (format {1}).long: error sentence The archive {0} is offline.long: error sentence The archive {0} is read-only.long: error sentence + {0:N0} sequence was not reorganized as planned: it changed after the plan.long: error sentence of a Reorganize job + {0:N0} sequences were not reorganized as planned: they changed after the plan.long: error sentence of a Reorganize job {0} changed after the plan was made.long: error sentence The card or folder {0} is no longer available.long: error sentence The archive changed after this plan was made.long: error sentence @@ -151,6 +153,10 @@ Unindexed photos: {0}, missing photos: {1}long: job log line {0}: made {1}, reused {2}, unreadable {3}, waiting {4}long: job log line; {4} frames whose proxy this host waits for from a client or render node Proxies for the server: {0} sent, {1} not sentlong: job log line; {0} proxies sent; {1} proxies this PC could not make or the server refused + Left as it was, changed after the plan: {0}long: job log line; {0} sequence title or folder + File names kept, photos changed after the plan: {0}long: job log line; {0} sequence title or folder + Sequences changed: {0}, files renamed: {1}long: job log line of a Reorganize; {0} sequences, {1} photos + The reorganization was completed when the archive was openedlong: job log line Report only: nothing was changed.long: job log line Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}long: job log line Sequence not found: {0}long: job log line @@ -214,6 +220,10 @@ {0:N0} of {1:N0} changes {0:N0} of {1:N0} change Template + Photos kept in place outside originals keep their names.long: why photos keep their names in a Reorganize dry run + Missing photos keep their names.long: why photos keep their names in a Reorganize dry run + Photos never verified keep their names; verify the sequence first.long: why photos keep their names in a Reorganize dry run + The sequence file cannot be read; its photos keep their names.long: why photos keep their names in a Reorganize dry run Add tags Apply Tags of {0:N0} sequence diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index 767a399a..d60462c4 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -76,7 +76,7 @@ Import Light analysis Maintenance - Move archive + Reorganize Orphans Proxies Rebuild index diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 48a6e115..9131c2eb 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -70,11 +70,13 @@ This server cannot run that kind of job.long The last administrator cannot be removed or disabled.long This method is not allowed here.long + A new folder would lie inside the folder of another sequence.long Not found.long That address is not a Chronos Server.long Change your password first.long The photo was deleted from the sequence while it was being uploaded, so it was not added.long {0} cannot be read, and without its hash other copies would not learn it was deleted; close the program using it or check its permissions, then try again.long + The archive changed after the dry run; review the plan again.long This page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to CHRONOS_TRUSTED_PROXIES.long This archive makes no proxies.long The proxy was made from another photo.long diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 9e799f85..59c94477 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -138,7 +138,7 @@ Importazione Analisi rapida Manutenzione - Spostamento + Riorganizzazione Orfani Proxy Ricostruzione diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index e8c71356..445a82c3 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -81,6 +81,8 @@ {0} è stato scritto da un Chronos più recente (formato {1}). L'archivio {0} non è raggiungibile. L'archivio {0} è di sola lettura. + {0:N0} sequenza non è stata riorganizzata come previsto: è cambiata dopo il piano. + {0:N0} sequenze non sono state riorganizzate come previsto: sono cambiate dopo il piano. {0} è cambiato dopo la creazione del piano. La scheda o cartella {0} non è più disponibile. L'archivio è cambiato dopo la creazione del piano. @@ -146,6 +148,10 @@ Foto non indicizzate: {0}, foto mancanti: {1} {0}: create {1}, riusate {2}, illeggibili {3}, in attesa {4} Proxy per il server: {0} inviati, {1} non inviati + Lasciata com'era, cambiata dopo il piano: {0} + Nomi dei file mantenuti, foto cambiate dopo il piano: {0} + Sequenze cambiate: {0}, file rinominati: {1} + La riorganizzazione è stata completata all'apertura dell'archivio Solo resoconto: nulla è stato modificato. Cartelle: {0}, indicizzate: {1}, adottate: {2}, rimosse: {3} Sequenza non trovata: {0} @@ -208,6 +214,10 @@ {0:N0} di {1:N0} cambia {0:N0} di {1:N0} cambiano Modello + Le foto tenute sul posto fuori da originals mantengono il loro nome. + Le foto mancanti mantengono il loro nome. + Le foto mai verificate mantengono il loro nome; verifica prima la sequenza. + Il file della sequenza non è leggibile; le sue foto mantengono il loro nome. Aggiungi tag Applica Tag di {0:N0} sequenza diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 7021dc93..643ae63f 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -76,7 +76,7 @@ Importazione Analisi rapida Manutenzione - Spostamento archivio + Riorganizzazione File orfani Proxy Ricostruzione indice diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index a3102434..53defcb3 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -68,11 +68,13 @@ Questo server non può eseguire quel tipo di job. L'ultimo amministratore non può essere rimosso o disattivato. Metodo non consentito qui. + Una nuova cartella finirebbe dentro la cartella di un'altra sequenza. Non trovato. Questo indirizzo non è un Chronos Server. Cambia prima la password. La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.long Impossibile leggere {0}: senza il suo hash le altre copie non saprebbero che è stato eliminato. Chiudi il programma che lo usa o controlla i permessi, poi riprova. + L'archivio è cambiato dopo la simulazione; rivedi di nuovo il piano. Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a CHRONOS_TRUSTED_PROXIES. Questo archivio non crea proxy. Il proxy è stato creato da un'altra foto. diff --git a/src/Chronos.App/Archive/MassOperations.cs b/src/Chronos.App/Archive/MassOperations.cs index d0ee149c..83784304 100644 --- a/src/Chronos.App/Archive/MassOperations.cs +++ b/src/Chronos.App/Archive/MassOperations.cs @@ -41,8 +41,11 @@ public static class MassRename : new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)), ]; - /// "12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted. - public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize); + /// + /// "12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted, and so are + /// those that change nothing (their files keep their names). + /// + public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => s.Changes && !s.Carried), setSize); } /// Adding and removing tags on a set of sequences (BRIEF §12.5 Retag). diff --git a/src/Chronos.Core/Archiving/ArchiveJson.cs b/src/Chronos.Core/Archiving/ArchiveJson.cs index 2417406b..0a39227b 100644 --- a/src/Chronos.Core/Archiving/ArchiveJson.cs +++ b/src/Chronos.Core/Archiving/ArchiveJson.cs @@ -16,6 +16,7 @@ namespace Chronos.Core.Archiving; [JsonSerializable(typeof(IngestJournal))] [JsonSerializable(typeof(FrameRemovalJournal))] [JsonSerializable(typeof(RenameJournal))] +[JsonSerializable(typeof(FileRenameJournal))] internal sealed partial class ArchiveJson : JsonSerializerContext; /// Indented output for the small files people may open (archive.json, rename journals). diff --git a/src/Chronos.Core/Archiving/ArchiveLayout.cs b/src/Chronos.Core/Archiving/ArchiveLayout.cs index 3b4a01f1..471b755a 100644 --- a/src/Chronos.Core/Archiving/ArchiveLayout.cs +++ b/src/Chronos.Core/Archiving/ArchiveLayout.cs @@ -36,6 +36,9 @@ public static class ArchiveLayout /// Moves of photos restored from the trash that were started but not yet settled in and the trash record. public const string RestoreJournalFile = "restore.pending.json"; + /// File renames of a Reorganize that were started but not yet recorded in and the index. + public const string FileRenameJournalFile = "rename-files.json"; + /// Folder names inside a sequence folder that never hold a sequence of their own. public static bool IsReservedFolder(string name) => name.Equals(MetaFolder, StringComparison.OrdinalIgnoreCase) @@ -104,6 +107,7 @@ public sealed class SequencePaths public string IngestJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.IngestJournalFile); public string RemovalJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RemovalJournalFile); public string RestoreJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.RestoreJournalFile); + public string FileRenameJournalPath => Path.Combine(MetaDirectory, ArchiveLayout.FileRenameJournalFile); public string Proxy(int index) => Path.Combine(Proxies, ArchiveLayout.ProxyFileName(index)); diff --git a/src/Chronos.Core/Archiving/FileRenameJournal.cs b/src/Chronos.Core/Archiving/FileRenameJournal.cs new file mode 100644 index 00000000..f0669627 --- /dev/null +++ b/src/Chronos.Core/Archiving/FileRenameJournal.cs @@ -0,0 +1,190 @@ +using System.Text.Json; +using Chronos.Core.Diagnostics; +using Chronos.Core.IO; + +namespace Chronos.Core.Archiving; + +/// One file of : its name, the temporary name it passes through and its new name, relative to the sequence folder. +public sealed record FileRenameEntry(Guid FrameId, string From, string Temp, string To, bool Companion = false); + +/// +/// Write-ahead record of the file renames of one sequence (.chronos/rename-files.json, Reorganize, owner review 2, R7): +/// the sidecar's frames version they were planned at and every file with its old, temporary and new name. The files move +/// in two phases, every file to its temporary name ( 1) and then every file to its new name (phase 2), so +/// chains such as A→B, B→C and swaps never meet a name another file still holds; nothing is ever written over. The journal +/// is written before the first move and goes once the sidecar and the index name the new files, so a crash in between is +/// completed by (which a writer runs under the sequence's lease, SequenceWriter.ReadLocked): +/// files still at their old name go on to their new one, those at their temporary name too, and the sidecar follows. A +/// failure while the files move (a file open elsewhere) puts every file back instead (). +/// +/// The sidecar's frames version before the renames; the sidecar written after them has the next. +/// 1 while files go to their temporary names, 2 while they go to their new names. +public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyList Files) +{ + private const string TempPrefix = ".chronos-rename-"; + + /// + /// The journal of () at , each file + /// with a temporary name beside it: hidden, of no photo format, unique to this rename (). + /// + public static FileRenameJournal Create(int framesVersion, IReadOnlyList moves, string token) + { + ArgumentNullException.ThrowIfNull(moves); + ArgumentException.ThrowIfNullOrWhiteSpace(token); + var files = new List(moves.Count); + for (var i = 0; i < moves.Count; i++) + { + var move = moves[i]; + var directory = move.From[..(move.From.LastIndexOf('/') + 1)]; + files.Add(new FileRenameEntry(move.FrameId, move.From, $"{directory}{TempPrefix}{token}-{i:D6}.tmp", move.To, move.Companion)); + } + return new FileRenameJournal(framesVersion, 1, files); + } + + public static void Write(SequencePaths sequence, FileRenameJournal journal) + { + ArgumentNullException.ThrowIfNull(sequence); + Directory.CreateDirectory(sequence.MetaDirectory); + AtomicFile.WriteAllBytes(sequence.FileRenameJournalPath, JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJson.Default.FileRenameJournal)); + } + + /// The journal of the sequence; null when there is none, or it was torn while first written (nothing had moved). + public static FileRenameJournal? Read(SequencePaths sequence) + { + ArgumentNullException.ThrowIfNull(sequence); + if (!File.Exists(sequence.FileRenameJournalPath)) return null; + try + { + return JsonSerializer.Deserialize(AtomicFile.ReadAllBytes(sequence.FileRenameJournalPath), ArchiveJson.Default.FileRenameJournal); + } + catch (JsonException) + { + return null; + } + } + + public static void Delete(SequencePaths sequence) + { + ArgumentNullException.ThrowIfNull(sequence); + if (File.Exists(sequence.FileRenameJournalPath)) File.Delete(sequence.FileRenameJournalPath); + } + + /// + /// Moves the files of a journal just written (): every file to its temporary name, the journal at + /// phase 2, every file to its new name. On a failure every file goes back to its old name, the journal goes, and the + /// failure is thrown: nothing changed. When even that fails the journal stays, and completes the + /// renames later. The caller holds the sequence's lease. + /// + /// A file could not be moved (open elsewhere, or a name taken meanwhile); nothing changed. + public static FileRenameJournal Run(SequencePaths sequence, FileRenameJournal journal) + { + ArgumentNullException.ThrowIfNull(sequence); + ArgumentNullException.ThrowIfNull(journal); + var done = 0; + var phase = 1; + try + { + foreach (var file in journal.Files) + { + Move(sequence, file.From, file.Temp); + done++; + } + journal = journal with { Phase = 2 }; + Write(sequence, journal); + phase = 2; + done = 0; + foreach (var file in journal.Files) + { + Move(sequence, file.Temp, file.To); + done++; + } + return journal; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("archive", $"Renaming the files of {sequence.RelativeFolder} failed; they go back to their names", ex); + if (Undo(sequence, journal, phase, done)) Delete(sequence); + throw; + } + } + + /// + /// Completes a rename a crash interrupted (the caller holds the sequence's lease): the files go on to their new names, + /// and names them (), unless it does already. Returns + /// the sidecar to write, or null when it is right as it is; the journal is left in place, it once + /// the result is written. A file found nowhere is logged, and its frame names the new file all the same (a verify then + /// flags it missing, as it would have at its old name). + /// + public static SequenceManifest? Recover(SequencePaths sequence, SequenceManifest manifest) + { + ArgumentNullException.ThrowIfNull(sequence); + ArgumentNullException.ThrowIfNull(manifest); + if (Read(sequence) is not { } journal) return null; + foreach (var file in journal.Files) + { + // In phase 2 no file is at its old name any more: what is there now came since, and stays. + if (journal.Phase == 1 && Exists(sequence, file.From) && !Exists(sequence, file.Temp)) Move(sequence, file.From, file.Temp); + } + foreach (var file in journal.Files) + { + if (Exists(sequence, file.Temp) && !Exists(sequence, file.To)) Move(sequence, file.Temp, file.To); + else if (!Exists(sequence, file.To)) Log.Warning("archive", $"{sequence.ArchiveRelative(file.To)} was not found after an interrupted rename"); + } + Log.Warning("archive", $"An interrupted rename of the files of {sequence.RelativeFolder} was completed"); + return Applied(manifest, journal); + } + + /// + /// naming the new files of (frame order unchanged) one frames + /// version further; null when no frame names an old file any more (the sidecar was written already). + /// + public static SequenceManifest? Applied(SequenceManifest manifest, FileRenameJournal journal) + { + ArgumentNullException.ThrowIfNull(manifest); + ArgumentNullException.ThrowIfNull(journal); + var renamed = journal.Files.Where(f => !f.Companion).ToDictionary(f => f.FrameId, f => f); + var changed = false; + var frames = manifest.Frames.Select(f => + { + if (!renamed.TryGetValue(f.Id, out var file) || !string.Equals(f.File, file.From, StringComparison.Ordinal)) return f; + changed = true; + return f with { File = file.To }; + }).ToList(); + if (!changed) return null; + return manifest with + { + Frames = frames, + Versions = manifest.Versions with { Frames = manifest.Versions.Frames + 1 }, + UpdatedAt = DateTimeOffset.UtcNow, + }; + } + + /// + /// Puts the files back after a failure in once of its moves were made; + /// false when one could not go back. Once every file is at its temporary name again the journal says phase 1, so a + /// failure from there on leaves a journal that completes the renames instead. + /// + private static bool Undo(SequencePaths sequence, FileRenameJournal journal, int phase, int done) + { + try + { + if (phase == 2) + { + for (var i = done - 1; i >= 0; i--) Move(sequence, journal.Files[i].To, journal.Files[i].Temp); + Write(sequence, journal with { Phase = 1 }); + done = journal.Files.Count; + } + for (var i = done - 1; i >= 0; i--) Move(sequence, journal.Files[i].Temp, journal.Files[i].From); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Error("archive", $"The files of {sequence.RelativeFolder} could not all go back after a failed rename; the journal completes it later", ex); + return false; + } + } + + private static bool Exists(SequencePaths sequence, string file) => File.Exists(sequence.File(file)); + + private static void Move(SequencePaths sequence, string from, string to) => File.Move(sequence.File(from), sequence.File(to), overwrite: false); +} diff --git a/src/Chronos.Core/Archiving/FileRenames.cs b/src/Chronos.Core/Archiving/FileRenames.cs new file mode 100644 index 00000000..f538673b --- /dev/null +++ b/src/Chronos.Core/Archiving/FileRenames.cs @@ -0,0 +1,140 @@ +using Chronos.Core.Naming; + +namespace Chronos.Core.Archiving; + +/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7); nothing of them is touched. +public enum RenameBlock +{ + /// Photos adopted in place, outside originals/: they belong to a tree someone else keeps. + InPlace, + + /// Photos whose SHA-256 is not known yet (never verified): a verify hashes them first. + Unhashed, + + /// Photos whose file is not there. + Missing, + + /// The sequence's sidecar cannot be read, or belongs to another sequence. + Unreadable, +} + +/// Frames of a sequence that keep their names, and why. +public sealed record RenameBlocked(RenameBlock Reason, int Frames); + +/// +/// One file of a Reorganize: a frame's photo, or a companion that follows it (), from its name to its +/// new one; both relative to the sequence folder, forward slashes. +/// +public sealed record FileRename(Guid FrameId, string From, string To, bool Companion = false); + +/// +/// The file renames of one sequence: every move, companions included, in frame order; how many frames get a new name; the +/// first of them () as samples; and the frames that keep their names. +/// +public sealed record FileRenamePlan(IReadOnlyList Moves, int Frames, IReadOnlyList Samples, IReadOnlyList Blocked) +{ + public static FileRenamePlan None { get; } = new([], 0, [], []); +} + +/// +/// Plans the new file names of a sequence's frames from a file template (Reorganize, owner review 2, R7; BRIEF §7.1, §12.5). +/// Frames are named in index order exactly as filing names them (); a name already given, or held +/// by a file that stays (a frame left alone, a file no frame lists), gets _2, _3… as filing does, so the same +/// frames, template and folder always give the same names. Only photos under originals/ whose SHA-256 is known and +/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it +/// (; one named by a stem two frames share follows the first). The sidecar's frame order never +/// changes. +/// +public static class FileRenames +{ + /// Renamed frames a plan shows as samples. + public const int SampleCount = 3; + + private const string Originals = ArchiveLayout.OriginalsFolder + "/"; + + /// The sequence title the names use ({title}): the new one when the same Reorganize retitles it. + /// Every file in the folders of the sequence's frames, relative to the sequence folder (). + public static FileRenamePlan Plan(SequenceManifest manifest, string? title, PathTemplate template, IReadOnlyCollection present) + { + ArgumentNullException.ThrowIfNull(manifest); + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(present); + var onDisk = new HashSet(present, StringComparer.OrdinalIgnoreCase); + int inPlace = 0, unhashed = 0, missing = 0; + var eligible = new List(); + // Companions are claimed in frame order by every frame, renamed or not: one a frame left alone claims stays with it. + var claimed = new HashSet(StringComparer.OrdinalIgnoreCase); + var companions = new Dictionary>(); + // By the name they give without ".xmp": a photo's path without its extension, or its whole path. + var xmp = onDisk.Where(f => f.EndsWith(FrameCompanions.Extension, StringComparison.OrdinalIgnoreCase)) + .ToLookup(f => f[..^FrameCompanions.Extension.Length], StringComparer.OrdinalIgnoreCase); + foreach (var frame in manifest.Frames) + { + var own = xmp[Stem(frame.File)].Concat(xmp[frame.File]).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.Ordinal) + .Where(c => FrameCompanions.Names(c, frame.File) && claimed.Add(c)).ToList(); + if (!frame.File.StartsWith(Originals, StringComparison.OrdinalIgnoreCase)) inPlace++; + else if (frame.Sha256 is null) unhashed++; + else if (!onDisk.Contains(frame.File)) missing++; + else + { + eligible.Add(frame); + companions[frame.Id] = own; + } + } + + // What stays where it is: files no renamed frame or companion moves away from, and every frame left alone. + var moving = new HashSet(eligible.Select(f => f.File).Concat(companions.Values.SelectMany(c => c)), StringComparer.OrdinalIgnoreCase); + var taken = new HashSet(onDisk.Where(f => !moving.Contains(f)), StringComparer.OrdinalIgnoreCase); + foreach (var frame in manifest.Frames.Where(f => !companions.ContainsKey(f.Id))) taken.Add(frame.File); + + var moves = new List(); + var samples = new List(); + var renamed = 0; + foreach (var frame in eligible) + { + var own = companions[frame.Id]; + var tails = own.ConvertAll(c => FrameCompanions.Tail(c, frame.File)); + var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)]; + var file = FrameNaming.FileName(template, FrameNaming.Context(frame, manifest, title), + candidate => !taken.Contains(candidate) && tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)), directory); + taken.Add(file); + foreach (var tail in tails) taken.Add(Stem(file) + tail); + if (string.Equals(file, frame.File, StringComparison.Ordinal)) continue; + var move = new FileRename(frame.Id, frame.File, file); + moves.Add(move); + if (samples.Count < SampleCount) samples.Add(move); + renamed++; + for (var c = 0; c < own.Count; c++) + { + var to = Stem(file) + tails[c]; + if (!string.Equals(to, own[c], StringComparison.Ordinal)) moves.Add(new FileRename(frame.Id, own[c], to, Companion: true)); + } + } + var blocked = new List(); + if (inPlace > 0) blocked.Add(new RenameBlocked(RenameBlock.InPlace, inPlace)); + if (unhashed > 0) blocked.Add(new RenameBlocked(RenameBlock.Unhashed, unhashed)); + if (missing > 0) blocked.Add(new RenameBlocked(RenameBlock.Missing, missing)); + return new FileRenamePlan(moves, renamed, samples, blocked); + } + + /// + /// Every file in the folders that hold the sequence's frames (originals/ as a rule), relative to the sequence + /// folder; hidden files included, so no name a file holds is ever given. + /// + public static IReadOnlyList ListPresent(SequencePaths sequence, SequenceManifest manifest) + { + ArgumentNullException.ThrowIfNull(sequence); + ArgumentNullException.ThrowIfNull(manifest); + var files = new List(); + foreach (var prefix in manifest.Frames.Select(f => f.File[..(f.File.LastIndexOf('/') + 1)]).Distinct(StringComparer.OrdinalIgnoreCase)) + { + var directory = prefix.Length == 0 ? sequence.Folder : sequence.File(prefix.TrimEnd('/')); + // Listed as the trash lists companions (FrameCompanions), so both find the same XMP files. + files.AddRange(FrameCompanions.List(directory).Select(n => prefix + n)); + } + return files; + } + + /// A file's path without its extension (originals/2026-09-28_0001). + private static string Stem(string file) => file[..^Path.GetExtension(file).Length]; +} diff --git a/src/Chronos.Core/Archiving/FrameCompanions.cs b/src/Chronos.Core/Archiving/FrameCompanions.cs new file mode 100644 index 00000000..60da1912 --- /dev/null +++ b/src/Chronos.Core/Archiving/FrameCompanions.cs @@ -0,0 +1,83 @@ +namespace Chronos.Core.Archiving; + +/// +/// The XMP companions of a photo (IMG_0001.xmp or IMG_0001.CR2.xmp beside IMG_0001.CR2): files that go +/// where their photo goes, into the trash with it (owner review 2, R6) and to its new name when Reorganize renames it (R7). +/// One rule for both: an XMP file in the photo's folder named after its stem or its whole name, whatever their case, on +/// every system (IMG_0001.XMP too), hidden files included. +/// +public static class FrameCompanions +{ + /// The extension of a companion. + public const string Extension = ".xmp"; + + /// Listing of a photo folder: case-insensitive on every system, nothing skipped. + private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 }; + + /// The companions beside (relative to the sequence folder), relative to the sequence folder. + public static IEnumerable Of(SequencePaths folder, string file) => new Index(folder).Of(file); + + /// + /// Whether is a companion of (both relative to the sequence folder): + /// an XMP file in the same folder named after the photo's stem or after its whole name, whatever their case. + /// + public static bool Names(string companion, string file) + { + ArgumentNullException.ThrowIfNull(companion); + ArgumentNullException.ThrowIfNull(file); + if (!Prefix(companion).Equals(Prefix(file), StringComparison.OrdinalIgnoreCase)) return false; + var name = Path.GetFileName(companion); + if (!Path.GetExtension(name).Equals(Extension, StringComparison.OrdinalIgnoreCase)) return false; + var named = Path.GetFileNameWithoutExtension(name); + var photo = Path.GetFileName(file); + return named.Equals(Path.GetFileNameWithoutExtension(photo), StringComparison.OrdinalIgnoreCase) + || named.Equals(photo, StringComparison.OrdinalIgnoreCase); + } + + /// What a companion's name adds to its photo's stem (.xmp, .CR2.xmp). + public static string Tail(string companion, string photo) + { + ArgumentNullException.ThrowIfNull(companion); + ArgumentNullException.ThrowIfNull(photo); + var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo)); + var name = Path.GetFileName(companion); + return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name); + } + + /// + /// Every file in (absolute), by name, hidden ones included: what is + /// asked about, and every name a file holds there. + /// + public static IEnumerable List(string directory) => + Directory.Exists(directory) ? Directory.EnumerateFiles(directory, "*", Listing).Select(p => Path.GetFileName(p)) : []; + + /// The folder part of a sequence-relative path with its trailing '/', or empty. + private static string Prefix(string file) => file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty; + + /// + /// The XMP files of a sequence's photo folders, each folder listed once (a deletion of thousands of photos does not list + /// it again for each), matched by . + /// + public sealed class Index(SequencePaths folder) + { + private readonly Dictionary> _directories = new(StringComparer.Ordinal); + + /// The companions beside (relative to the sequence folder), relative to the sequence folder. + public IEnumerable Of(string file) + { + ArgumentNullException.ThrowIfNull(file); + var prefix = Prefix(file); + if (!_directories.TryGetValue(prefix, out var named)) + { + named = List(Path.GetDirectoryName(folder.File(file))!) + .Where(n => Path.GetExtension(n).Equals(Extension, StringComparison.OrdinalIgnoreCase)) + .ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase); + _directories[prefix] = named; + } + var name = Path.GetFileName(file); + var stem = Path.GetFileNameWithoutExtension(name); + var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]); + return matches.Select(n => prefix + n).Where(c => Names(c, file)); + } + } +} diff --git a/src/Chronos.Core/Archiving/MassRename.cs b/src/Chronos.Core/Archiving/MassRename.cs index e6dfc83f..2d014611 100644 --- a/src/Chronos.Core/Archiving/MassRename.cs +++ b/src/Chronos.Core/Archiving/MassRename.cs @@ -1,4 +1,6 @@ using System.Globalization; +using System.Security.Cryptography; +using System.Text; using System.Text.Json; using Chronos.Core.IO; using Chronos.Core.Localization; @@ -7,13 +9,93 @@ using Chronos.Core.Naming; namespace Chronos.Core.Archiving; /// What the planner needs to know about a sequence to rename it. -public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens); +public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens) +{ + /// The sidecar and the files beside its frames, which a file template renames; null when they cannot be read. + public SequenceFiles? Files { get; init; } +} -/// One sequence's change: its folder, its title, or both. +/// A sequence's sidecar as read for a plan, and every file in the folders of its frames (). +public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection Present); + +/// +/// One sequence's change: its folder, its title, the names of its files (Reorganize, owner review 2, R7), or several of +/// them. A step that changes nothing lists only why files keep their names (). +/// /// The folder moves only because a folder it is inside moves (a sequence nested in another). public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false) { public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal); + + public bool Retitles => !string.Equals(FromTitle, ToTitle, StringComparison.Ordinal); + + /// Whether applying the step changes anything: the folder, the title or file names. + public bool Changes => MovesFolder || Retitles || FileChanges > 0; + + /// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. + public int FramesVersion { get; init; } + + /// Frames whose file gets a new name (their companions follow them). + public int FileChanges { get; init; } + + /// The first renamed frames (), old and new name relative to the sequence folder. + public IReadOnlyList FileSamples { get; init; } = []; + + /// Frames that keep their file names, and why. + public IReadOnlyList Blocked { get; init; } = []; +} + +/// +/// The templates of a Reorganize (owner review 2, R7): the folder ({title} = the new title), the file names and the +/// title ({title} = the current title); null leaves that part as it is. +/// +public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null) +{ + private static readonly NamingContext Sample = new() + { + CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11), + SessionStart = new DateTime(2026, 9, 28, 18, 2, 11), + CameraMake = "Canon", + CameraModel = "Canon EOS R5", + Lens = "RF15-35mm F2.8 L IS USM", + Iso = 100, + ExposureTime = 1.0 / 250, + FNumber = 8, + OriginalName = "IMG_4211", + Extension = "CR2", + Title = "Sunset", + }; + + public bool IsEmpty => Folder is null && File is null && Title is null; + + /// + /// The first template that cannot be used, by its API name (folderTemplate, fileTemplate, + /// titleTemplate): blank, not valid as the archive settings' templates (), or + /// with a format a sample cannot be written with ({date:%}); null when every one given can. + /// + public string? Problem() + { + if (Unusable(Folder, t => t.ExpandFolder(Sample))) return "folderTemplate"; + if (Unusable(File, t => t.ExpandFile(Sample))) return "fileTemplate"; + if (Unusable(Title, t => t.ExpandFile(Sample))) return "titleTemplate"; + return null; + } + + private static bool Unusable(string? template, Func expand) + { + if (template is null) return false; + if (string.IsNullOrWhiteSpace(template)) return true; + var parsed = PathTemplate.Parse(template); + if (!parsed.IsValid) return true; + try + { + return expand(parsed).Length == 0; + } + catch (FormatException) + { + return true; + } + } } /// A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned. @@ -25,10 +107,36 @@ public sealed class NestedRenameException(string target, string folder) } /// The exact changes a mass rename will make (its dry run); applying it makes exactly these. -public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Steps); +public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Steps) +{ + /// The file template the steps' file names come from; null when files keep their names. + public string? FileTemplate { get; init; } + + /// The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)"). + public IReadOnlyList Subjects { get; init; } = []; + + /// + /// A digest of what the plan changes (its steps in order, as a dry run shows them, and the file template), the same for + /// two plans of the same archive state: what a confirmation sends back so the change made is the one that was shown. + /// + public string Fingerprint() + { + var text = new StringBuilder(FileTemplate).Append('\n'); + foreach (var s in Steps) + { + text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FramesVersion}|{s.FileChanges}|"); + foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';'); + foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};"); + text.Append('\n'); + } + return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString()))); + } +} /// A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7). -public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Completed) +/// The job applying the plan was paused or cancelled between two steps: an archive open leaves the plan to +/// that job, which completes it when it runs again. +public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Completed, bool Held = false) { public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json"); @@ -38,7 +146,7 @@ public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Complete AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal)); } - /// Journals left by interrupted renames. + /// Journals left by interrupted renames, held ones included. public static IReadOnlyList ListPending(ArchivePaths archive) { if (!Directory.Exists(archive.JournalDirectory)) return []; @@ -50,28 +158,40 @@ public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList Complete return list; } + /// The journal of the plan ; null when there is none (the plan completed, or never started). + public static RenameJournal? Read(ArchivePaths archive, Guid planId) + { + var path = PathFor(archive, planId); + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), ArchiveJson.Default.RenameJournal) : null; + } + public static void Delete(ArchivePaths archive, Guid planId) => File.Delete(PathFor(archive, planId)); } -/// Builds rename plans from folder/title templates (BRIEF §7.1, §12.5). +/// Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7). public static class RenamePlanner { /// /// Expands (where {title} is the current title) and then /// (where {title} is the new title) for every subject. A target folder /// that is any current sequence folder, exists on disk or was given to an earlier subject gets " (2)", " (3)"…. - /// Null templates leave that part unchanged; subjects without a change produce no step. A folder that moves takes - /// the sequences inside it along: each gets a step after every move, so the index - /// follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first. + /// With every subject's frames get their names from it as filing names them + /// (, with the new title), counted and sampled in its step, and the frames that keep + /// their names are listed there with the reason; a subject whose sidecar could not be read + /// ( null) keeps them all. Null templates leave that part unchanged; subjects without a + /// change produce no step, unless frames of theirs keep their names. A folder that moves takes the sequences inside + /// it along: each gets a step after every move, so the index follows its files; a + /// selected sequence inside a moving folder that moves elsewhere leaves first. /// /// Every sequence folder of the archive (renamed or not). /// The archive's other sequences inside a subject's folder, with their titles. /// A target lies inside a sequence's folder, or inside another target. public static RenamePlan Plan(Guid archiveId, IReadOnlyList subjects, string? folderTemplate, string? titleTemplate, - IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null) + IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null, string? fileTemplate = null) { var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate); var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate); + var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate); var taken = occupied.ToList(); var claimed = new HashSet(taken, StringComparer.OrdinalIgnoreCase); var own = new List(subjects.Count); @@ -95,7 +215,8 @@ public static class RenamePlanner newFolder = expanded.Equals(s.Folder, StringComparison.OrdinalIgnoreCase) ? expanded : Unique(expanded, claimed, existsOnDisk); claimed.Add(newFolder); } - own.Add(new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle)); + var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle); + own.Add(file is null ? step : WithFiles(step, s.Files, file, newTitle)); } var moving = own.Where(s => s.MovesFolder).ToList(); @@ -114,11 +235,25 @@ public static class RenamePlanner steps.Add((step with { ToFolder = carrier.ToFolder + step.FromFolder[carrier.FromFolder.Length..], Carried = true }, 1)); else if (step.MovesFolder) steps.Add((step, -moving.Count(m => m != step && IsInside(m.FromFolder, step.FromFolder)))); - else if (step.FromTitle != step.ToTitle) + else if (step.Retitles || step.FileChanges > 0 || step.Blocked.Count > 0) steps.Add((step, 0)); } // Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last. - return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]); + return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]) { FileTemplate = fileTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)] }; + } + + /// The step with the file renames of its sequence (), or all its frames kept when its sidecar could not be read. + private static RenameStep WithFiles(RenameStep step, SequenceFiles? files, PathTemplate template, string? title) + { + if (files is null) return step with { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] }; + var plan = FileRenames.Plan(files.Manifest, title, template, files.Present); + return step with + { + FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0, + FileChanges = plan.Frames, + FileSamples = plan.Samples, + Blocked = plan.Blocked, + }; } /// diff --git a/src/Chronos.Core/Import/ImportPlanner.cs b/src/Chronos.Core/Import/ImportPlanner.cs index 80775b14..2ca4cbd8 100644 --- a/src/Chronos.Core/Import/ImportPlanner.cs +++ b/src/Chronos.Core/Import/ImportPlanner.cs @@ -137,23 +137,8 @@ public static class ImportPlanner }; } - private static NamingContext Context(CardPhoto photo, DateTime sessionStart, int session, int number, string? title) => new() - { - CapturedAt = photo.CaptureTime, - SessionStart = sessionStart, - Session = session, - Number = number, - NumberInSession = number, - CameraMake = photo.Metadata.Make, - CameraModel = photo.Metadata.Model, - Lens = photo.Metadata.LensModel, - Iso = photo.Metadata.Iso, - ExposureTime = photo.Metadata.ExposureTime, - FNumber = photo.Metadata.FNumber, - OriginalName = Path.GetFileNameWithoutExtension(photo.File.RelativePath), - Extension = Path.GetExtension(photo.File.RelativePath).TrimStart('.'), - Title = title, - }; + private static NamingContext Context(CardPhoto photo, DateTime sessionStart, int session, int number, string? title) => + FrameNaming.Context(photo.Metadata, photo.File.RelativePath, photo.CaptureTime, sessionStart, number, title, session); /// Camera body and file format: RAW+JPEG shooting yields two sequences instead of doubled frames. private static string BodyKey(CardPhoto p) => $"{CameraKey(p)}|{p.Metadata.Format}"; @@ -201,14 +186,7 @@ public static class ImportPlanner } /// Adds _2, _3… before the extension when the template gives two photos the same name. - internal static string UniqueName(string name, HashSet taken) - { - var candidate = name; - var stem = Path.GetFileNameWithoutExtension(name); - var extension = Path.GetExtension(name); - for (var n = 2; !taken.Add(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{stem}_{n}{extension}"); - return candidate; - } + internal static string UniqueName(string name, HashSet taken) => FrameNaming.Unique(name, taken.Add); private static long? FreeSpace(string path) { diff --git a/src/Chronos.Core/Naming/FrameNaming.cs b/src/Chronos.Core/Naming/FrameNaming.cs new file mode 100644 index 00000000..f7b920d0 --- /dev/null +++ b/src/Chronos.Core/Naming/FrameNaming.cs @@ -0,0 +1,125 @@ +using System.Globalization; +using Chronos.Core.Archiving; +using Chronos.Core.Metadata; + +namespace Chronos.Core.Naming; + +/// +/// The values a file template sees for one photo and the unique name it gives (BRIEF §7.1), shared by everything that +/// names frames: a card or folder import (), an upload filed by the archive ingest, and +/// Reorganize, which renames the frames of a sequence already in the archive (owner review 2, R7). The same photo in the +/// same place therefore gets the same name whichever of them names it. +/// +public static class FrameNaming +{ + /// The context of a photo being filed, from its metadata. + /// The photo's name on the card or upload source: {name} is its stem, {ext} its extension. + /// The photo's capture time as the sequence orders it. + /// The capture time of the first photo of its session ({sessionstart}). + /// 1-based number of the photo ({n}, {nsession}). + /// The sequence title ({title}). + /// 1-based session number within the import ({session}); 1 for an upload. + public static NamingContext Context(FrameMetadata metadata, string fileName, DateTime capturedAt, DateTime sessionStart, int number, string? title, + int session = 1) + { + ArgumentNullException.ThrowIfNull(metadata); + ArgumentNullException.ThrowIfNull(fileName); + return new NamingContext + { + CapturedAt = capturedAt, + SessionStart = sessionStart, + Session = session, + Number = number, + NumberInSession = number, + CameraMake = metadata.Make, + CameraModel = metadata.Model, + Lens = metadata.LensModel, + Iso = metadata.Iso, + ExposureTime = metadata.ExposureTime, + FNumber = metadata.FNumber, + OriginalName = Path.GetFileNameWithoutExtension(fileName), + Extension = Path.GetExtension(fileName).TrimStart('.'), + Title = title, + }; + } + + /// + /// The context of a frame already in a sequence (Reorganize): its sidecar record with the sequence's camera and lens, + /// numbered by its index ({n} = index + 1), the sequence as one session starting at its first frame. {name} + /// is the name the photo had on the card, {ext} the extension of the file as it is now. These are the values an + /// upload of the same photos in capture order was named with; a frame without a capture time takes the session start, + /// so a dry run and its application always agree. + /// + public static NamingContext Context(SidecarFrame frame, SequenceManifest sequence, string? title) + { + ArgumentNullException.ThrowIfNull(frame); + ArgumentNullException.ThrowIfNull(sequence); + var start = SessionStart(sequence); + var file = Path.GetFileName(frame.File); + return new NamingContext + { + CapturedAt = frame.CapturedAt ?? start, + SessionStart = start, + Session = 1, + Number = frame.I + 1, + NumberInSession = frame.I + 1, + CameraMake = sequence.Camera?.Make, + CameraModel = sequence.Camera?.Model, + Lens = sequence.Lens, + Iso = frame.Iso, + ExposureTime = frame.Exposure, + FNumber = frame.FNumber, + OriginalName = Path.GetFileNameWithoutExtension(frame.Original ?? file), + Extension = Path.GetExtension(file).TrimStart('.'), + Title = title, + }; + } + + /// The start of a sequence as one session: its first frame's capture time, else when the sequence was made. + public static DateTime SessionStart(SequenceManifest sequence) + { + ArgumentNullException.ThrowIfNull(sequence); + return sequence.Frames.Count > 0 && sequence.Frames[0].CapturedAt is { } first + ? first + : DateTime.SpecifyKind(sequence.Created.UtcDateTime, DateTimeKind.Unspecified); + } + + /// + /// (empty or ending with '/') and the name gives, made unique + /// in with _2, _3… before the extension, then added to it. + /// + public static string FileName(PathTemplate template, NamingContext context, ISet taken, string directory = "") + { + ArgumentNullException.ThrowIfNull(taken); + var file = FileName(template, context, candidate => !taken.Contains(candidate), directory); + taken.Add(file); + return file; + } + + /// + /// and the name gives, or the first of stem_2.ext, + /// stem_3.ext… that accepts. + /// + public static string FileName(PathTemplate template, NamingContext context, Func isFree, string directory = "") + { + ArgumentNullException.ThrowIfNull(template); + ArgumentNullException.ThrowIfNull(isFree); + ArgumentNullException.ThrowIfNull(directory); + return Unique(directory + template.ExpandFile(context), isFree); + } + + /// , or the first of stem_2.ext, stem_3.ext… that accepts. + public static string Unique(string file, Func isFree) + { + ArgumentNullException.ThrowIfNull(file); + ArgumentNullException.ThrowIfNull(isFree); + var slash = file.LastIndexOf('/'); + var directory = file[..(slash + 1)]; + var name = file[(slash + 1)..]; + var stem = Path.GetFileNameWithoutExtension(name); + var extension = Path.GetExtension(name); + var candidate = file; + for (var n = 2; !isFree(candidate); n++) candidate = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{extension}"); + return candidate; + } +} diff --git a/src/Chronos.Data/Archiving/ArchiveIngest.cs b/src/Chronos.Data/Archiving/ArchiveIngest.cs index 36e1147d..3ae9ffcd 100644 --- a/src/Chronos.Data/Archiving/ArchiveIngest.cs +++ b/src/Chronos.Data/Archiving/ArchiveIngest.cs @@ -435,10 +435,9 @@ public sealed class ArchiveIngest : IArchiveIngest if (!incoming.TryGetValue(frame.Id, out var entry)) continue; var staged = entry.Pending.Frame; var captured = frame.CapturedAt ?? DateTime.Now; - var name = staged.PlannedName ?? template.ExpandFile(Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title)); - var file = directory + name; - var stem = Path.GetFileNameWithoutExtension(name); - for (var n = 2; !taken.Add(file); n++) file = string.Create(CultureInfo.InvariantCulture, $"{directory}{stem}_{n}{Path.GetExtension(name)}"); + var file = staged.PlannedName is { } planned + ? FrameNaming.Unique(directory + planned, taken.Add) + : FrameNaming.FileName(template, Naming(staged, captured, start ?? captured, frame.I + 1, manifest.Title), taken, directory); named[frame.Id] = entry.Frame with { File = file }; } return named; @@ -539,22 +538,8 @@ public sealed class ArchiveIngest : IArchiveIngest ? client : frame.Metadata.CapturedAt ?? frame.ClientCapturedAt ?? DateTime.Now; - private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) => new() - { - CapturedAt = captured, - SessionStart = sessionStart, - Number = number, - NumberInSession = number, - CameraMake = frame.Metadata.Make, - CameraModel = frame.Metadata.Model, - Lens = frame.Metadata.LensModel, - Iso = frame.Metadata.Iso, - ExposureTime = frame.Metadata.ExposureTime, - FNumber = frame.Metadata.FNumber, - OriginalName = Path.GetFileNameWithoutExtension(frame.OriginalFileName), - Extension = Path.GetExtension(frame.OriginalFileName).TrimStart('.'), - Title = title, - }; + private static NamingContext Naming(StagedFrame frame, DateTime captured, DateTime sessionStart, int number, string? title) => + FrameNaming.Context(frame.Metadata, frame.OriginalFileName, captured, sessionStart, number, title); private sealed class CommitQueue { diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index a095c057..a2c1be2b 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -73,8 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider /// /// Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs, the read-only duplicates and orphans - /// reports, index backups and clean-ups (owner review 2, R10) and the emptying of the trash (R6); register them on the - /// . + /// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7, + /// ); register them on the . /// public IReadOnlyList CreateJobHandlers() => [ @@ -90,6 +90,7 @@ public sealed class ArchiveService : IJobHandlerProvider new Housekeeping.BackupJobHandler(_db, _writer.Options.BackupDirectory), new Housekeeping.CleanupJobHandler(_db, CleanupSteps, TimeProvider.System), new EmptyTrashJobHandler(_db, Trash), + new MoveJobHandler(_db, Renamer, _writer.Options.SequenceChanged), ]; /// Makes a new, empty archive and indexes it. @@ -351,7 +352,23 @@ public sealed class ArchiveService : IJobHandlerProvider await Renamer.PlanAsync(await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false), sequenceIds, folderTemplate, titleTemplate, cancellationToken).ConfigureAwait(false); - public async Task ApplyRenameAsync(RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => + /// + /// The dry run of a Reorganize (owner review 2, R7): over , or + /// over every sequence of the archive (by folder) when null. Apply it in a job () or + /// with . + /// + /// The archive is unknown, or a sequence is not in it. + /// A new folder would lie inside a sequence's folder. + public async Task PlanReorganizeAsync(Guid archiveId, IReadOnlyList? sequenceIds, RenameTemplates templates, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(templates); + var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false); + var ids = sequenceIds ?? [.. (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id)]; + return await Renamer.PlanAsync(archive, ids, templates, cancellationToken).ConfigureAwait(false); + } + + public async Task ApplyRenameAsync(RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => await Renamer.ApplyAsync(await LoadArchiveAsync(plan.ArchiveId, cancellationToken).ConfigureAwait(false), plan, progress, cancellationToken) .ConfigureAwait(false); @@ -567,6 +584,24 @@ public static class ArchiveJobs JobPriority.User); } + /// + /// : applies the Reorganize (the dry run of , + /// ) as confirmed, refused when the archive changed since + /// (; owner review 2, R7). + /// + public static ArchiveJobRequest Reorganize(Archive archive, RenamePlan plan, RenameTemplates templates) + { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(templates); + // The sequences that have a step, in the order the plan was made for: the others change nothing, now or when planned again. + var steps = plan.Steps.ToDictionary(s => s.SequenceId); + var sequences = plan.Subjects.Where(steps.ContainsKey).Select(id => new MoveSequence(id, steps[id].FramesVersion)).ToList(); + return new(JobKind.Move, [archive.Id], archive.Name, + Json(new MoveJobParameters(templates.Folder, templates.File, templates.Title, sequences, plan.Fingerprint()), ArchiveJobJson.Default.MoveJobParameters), + JobPriority.User); + } + public static Task EnqueueAsync(this JobEngine engine, ArchiveJobRequest request, Guid? createdBy = null, CancellationToken cancellationToken = default) => engine.EnqueueAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority, createdBy, cancellationToken); diff --git a/src/Chronos.Data/Archiving/FrameTrash.Restore.cs b/src/Chronos.Data/Archiving/FrameTrash.Restore.cs index 2679f883..7462b80f 100644 --- a/src/Chronos.Data/Archiving/FrameTrash.Restore.cs +++ b/src/Chronos.Data/Archiving/FrameTrash.Restore.cs @@ -176,7 +176,7 @@ public sealed partial class FrameTrash continue; } var original = photo.Files[0]; - var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList(); + var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList(); var file = FreeName(folder, original.From, tails, taken); var stem = file[..^Path.GetExtension(file).Length]; taken.Add(file); @@ -417,7 +417,7 @@ public sealed partial class FrameTrash if (folder is null && sequenceId is { } known && await _db.Sequences.GetAsync(known, CancellationToken.None).ConfigureAwait(false) is { } row) folder = paths.Sequence(row.Folder); var original = photo.Files[0]; - var tails = photo.Files.Skip(1).Select(c => CompanionTail(c.From, original.From)).ToList(); + var tails = photo.Files.Skip(1).Select(c => FrameCompanions.Tail(c.From, original.From)).ToList(); var planned = FreeName(folder, ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(original.From), tails, names); var inEntry = Path.Combine(entryFolder, original.Path); var path = Path.Combine(staging, original.Path); @@ -475,7 +475,7 @@ public sealed partial class FrameTrash names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(placed)); foreach (var companion in photo.Files.Skip(1)) { - var beside = stem + CompanionTail(companion.From, original.From); + var beside = stem + FrameCompanions.Tail(companion.From, original.From); names.Add(ArchiveLayout.OriginalsFolder + "/" + Path.GetFileName(beside)); try { @@ -563,14 +563,6 @@ public sealed partial class FrameTrash return all.Count > 0 ? all : null; } - /// What a companion's name adds to its photo's stem (.xmp, .CR2.xmp). - private static string CompanionTail(string companion, string photo) - { - var stem = Path.GetFileNameWithoutExtension(Path.GetFileName(photo)); - var name = Path.GetFileName(companion); - return name.StartsWith(stem, StringComparison.OrdinalIgnoreCase) ? name[stem.Length..] : Path.GetExtension(name); - } - /// /// when it and its companions' names ( after its stem) are free in /// and on disk in (none yet: in only), else diff --git a/src/Chronos.Data/Archiving/FrameTrash.cs b/src/Chronos.Data/Archiving/FrameTrash.cs index b3a15935..c652574e 100644 --- a/src/Chronos.Data/Archiving/FrameTrash.cs +++ b/src/Chronos.Data/Archiving/FrameTrash.cs @@ -347,7 +347,7 @@ public sealed partial class FrameTrash var used = new HashSet(StringComparer.OrdinalIgnoreCase); var claimed = new HashSet(StringComparer.OrdinalIgnoreCase); var keptStems = kept.Select(f => Stem(f.File)).ToHashSet(StringComparer.OrdinalIgnoreCase); - var companions = new CompanionIndex(folder); + var companions = new FrameCompanions.Index(folder); var photos = new List(removed.Count); foreach (var frame in removed) { @@ -431,35 +431,6 @@ public sealed partial class FrameTrash return Convert.ToHexStringLower(hash.GetHashAndReset()); } - /// - /// The XMP files of a sequence's photo directories, each directory listed once (a deletion of thousands of photos does - /// not list it again for each) and case-insensitively on every system (IMG_0001.XMP too). - /// - private sealed class CompanionIndex(SequencePaths folder) - { - private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 }; - private readonly Dictionary> _directories = new(StringComparer.Ordinal); - - /// The XMP files beside a photo that name it (stem.xmp or file.xmp), relative to the sequence folder. - public IEnumerable Of(string file) - { - var prefix = file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty; - if (!_directories.TryGetValue(prefix, out var named)) - { - var directory = Path.GetDirectoryName(folder.File(file))!; - named = (System.IO.Directory.Exists(directory) ? System.IO.Directory.EnumerateFiles(directory, "*.xmp", Listing) : []) - .Select(p => Path.GetFileName(p)) - .Where(n => Path.GetExtension(n).Equals(".xmp", StringComparison.OrdinalIgnoreCase)) - .ToLookup(n => Path.GetFileNameWithoutExtension(n), StringComparer.OrdinalIgnoreCase); - _directories[prefix] = named; - } - var name = Path.GetFileName(file); - var stem = Path.GetFileNameWithoutExtension(name); - var matches = stem.Equals(name, StringComparison.OrdinalIgnoreCase) ? named[stem] : named[stem].Concat(named[name]); - return matches.Select(n => prefix + n); - } - } - /// A photo's stem with its folder (originals/IMG_0001): its companions share it. private static string Stem(string file) { diff --git a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs index 4c284bed..2263938c 100644 --- a/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs +++ b/src/Chronos.Data/Archiving/Jobs/ArchiveJobParameters.cs @@ -40,6 +40,17 @@ public sealed record EmptyTrashParameters(IReadOnlyList Entries, /// One entry of a confirmed emptying: its name and fingerprint when it was planned. public sealed record EmptyTrashItem(string Name, string Fingerprint); +/// +/// (Reorganize, owner review 2, R7): target = the archive; the templates (null keeps that part), +/// the sequences the confirmed plan changes in the order it was made for, each with the frames version its file names +/// were planned at (0 when none is renamed), and the plan's fingerprint (). +/// No file list: the job plans again and refuses when the plan is no longer the one confirmed. +/// +public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList Sequences, string Fingerprint); + +/// A sequence of a and the frames version its file names were planned at. +public sealed record MoveSequence(Guid Id, int FramesVersion); + /// A job ready to enqueue. public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets, string? Label, string? ParametersJson, JobPriority Priority); @@ -52,6 +63,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList Targets [JsonSerializable(typeof(BackupParameters))] [JsonSerializable(typeof(CleanupParameters))] [JsonSerializable(typeof(EmptyTrashParameters))] +[JsonSerializable(typeof(MoveJobParameters))] [JsonSerializable(typeof(CardProfile))] internal sealed partial class ArchiveJobJson : JsonSerializerContext { diff --git a/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs new file mode 100644 index 00000000..7cc55943 --- /dev/null +++ b/src/Chronos.Data/Archiving/Jobs/MoveJobHandler.cs @@ -0,0 +1,127 @@ +using Chronos.Core.Archiving; +using Chronos.Core.Diagnostics; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Data.Jobs; + +namespace Chronos.Data.Archiving.Jobs; + +/// +/// : a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file +/// and title templates (). The job plans again from the templates and applies the plan only +/// when it is still the one confirmed (its fingerprint and the frames versions its file names were planned at; +/// otherwise, nothing changed), through , whose journal makes +/// every step resumable. Progress counts the plan's steps (sequences); checkpoint: plan:<id> once the plan's +/// journal is written. Paused or cancelled, the job stops between two sequences and holds the plan +/// (), which an archive open then leaves to it; resumed or retried, it completes the rest when +/// it still fits. A plan whose journal is gone completed meanwhile (at an archive open). Sequences left as they were, or +/// whose files kept their names, because they changed after the plan are logged and fail the job at the end, after the +/// others changed. Each sequence changed is told to (). +/// +internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func? sequenceChanged) : IJobHandler +{ + /// The change a Reorganize tells about a sequence (a server's sequenceChanged event). + public const string Change = "reorganized"; + + private const string Prefix = "plan:"; + + public JobKind Kind => JobKind.Move; + + public async Task RunAsync(JobContext context) + { + var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false); + var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.MoveJobParameters, new MoveJobParameters(null, null, null, [], string.Empty)); + if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Move job {context.Job.Id} has no confirmed plan."); + var paths = new ArchivePaths(archive.RootPath); + var planId = PlanOf(context.Checkpoint); + RenamePlan plan; + RenameResult? result; + try + { + if (planId is { } resumed) + { + if (RenameJournal.Read(paths, resumed) is not { } journal || await ResumeAsync(context, archive, journal).ConfigureAwait(false) is not { } done) + { + context.Log(Loc.L("Archive.Log.ReorganizedEarlier")); + await context.ReportAsync(context.Total, context.Total).ConfigureAwait(false); + return; + } + (plan, result) = (journal.Plan, done); + } + else + { + plan = await renamer.PlanAsync(archive, [.. parameters.Sequences.Select(s => s.Id)], + new RenameTemplates(parameters.FolderTemplate, parameters.FileTemplate, parameters.TitleTemplate), context.Cancellation).ConfigureAwait(false); + if (!IsConfirmed(plan, parameters)) throw new StaleRenamePlanException(Guid.Empty); + var total = Steps(plan); + await context.ReportAsync(0, total).ConfigureAwait(false); + result = await renamer.ApplyAsync(archive, plan, p => + { + planId = p.Id; + return context.CheckpointAsync(Checkpoint(p.Id), 0, total); + }, n => context.CheckpointAsync(Checkpoint(plan.Id), n, total), context.Cancellation).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (planId is { } id && context.Cancellation.IsCancellationRequested) + { + // Paused or cancelled by a user, not a yield to another job or the host stopping: the rest waits for this job. + if (await db.Jobs.GetAsync(context.Job.Id, CancellationToken.None).ConfigureAwait(false) is { State: JobState.Paused or JobState.Cancelled } + && MassRenamer.Hold(archive, id)) + Log.Info("archive", $"Reorganize {id} held by its job {context.Job.Id}"); + throw; + } + context.Log(Loc.L("Archive.Log.Reorganized", result.Changed.Count, result.Files)); + foreach (var id in result.Dropped) context.Log(Loc.L("Archive.Log.ReorganizeDropped", Name(plan, id))); + foreach (var id in result.FilesKept) context.Log(Loc.L("Archive.Log.ReorganizeFilesKept", Name(plan, id))); + await TellAsync(result.Changed).ConfigureAwait(false); + var kept = result.Dropped.Count + result.FilesKept.Count; + if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ReorganizeKept", kept)); + } + + /// Completes a plan this job started; null when its journal went meanwhile (completed at an archive open). + private async Task ResumeAsync(JobContext context, Archive archive, RenameJournal journal) + { + var total = Steps(journal.Plan); + await context.ReportAsync(journal.Completed.Count, total).ConfigureAwait(false); + return await renamer.ResumeAsync(archive, journal.Plan.Id, n => context.CheckpointAsync(Checkpoint(journal.Plan.Id), n, total), context.Cancellation) + .ConfigureAwait(false); + } + + /// Whether the plan made now is the one confirmed: the same fingerprint, and the frames versions its file names were planned at. + private static bool IsConfirmed(RenamePlan plan, MoveJobParameters parameters) + { + if (!string.Equals(plan.Fingerprint(), parameters.Fingerprint, StringComparison.Ordinal)) return false; + var versions = parameters.Sequences.ToDictionary(s => s.Id, s => s.FramesVersion); + return plan.Steps.Where(s => s.FileChanges > 0).All(s => versions.TryGetValue(s.SequenceId, out var version) && version == s.FramesVersion); + } + + /// Tells each sequence changed; a failure is logged, never passed on to the job. + private async Task TellAsync(IReadOnlyList changed) + { + if (sequenceChanged is null) return; + foreach (var id in changed) + { + try + { + await sequenceChanged(id, Change, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) + { + Log.Warning("archive", $"The change of sequence {id} was not told", ex); + } + } + } + + private static int Steps(RenamePlan plan) => plan.Steps.Count(s => s.Changes); + + /// How the job log names a sequence of the plan: its title, else its folder. + private static string Name(RenamePlan plan, Guid id) => + plan.Steps.FirstOrDefault(s => s.SequenceId == id) is { } step ? step.ToTitle ?? step.FromTitle ?? step.FromFolder : id.ToString(); + + private static string Checkpoint(Guid planId) => Prefix + planId.ToString("N"); + + private static Guid? PlanOf(string? checkpoint) => + checkpoint is not null && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) && Guid.TryParseExact(checkpoint[Prefix.Length..], "N", out var id) + ? id + : null; +} diff --git a/src/Chronos.Data/Archiving/MassRenamer.cs b/src/Chronos.Data/Archiving/MassRenamer.cs index b6130be4..21df1c69 100644 --- a/src/Chronos.Data/Archiving/MassRenamer.cs +++ b/src/Chronos.Data/Archiving/MassRenamer.cs @@ -2,13 +2,14 @@ using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Localization; using Chronos.Core.Model; +using Chronos.Core.Naming; using Chronos.Data.Repositories; namespace Chronos.Data.Archiving; /// /// The plan no longer matches the archive: a sequence moved or vanished since it was made, or one was indexed inside a -/// folder the plan moves. +/// folder the plan moves, or the photos of a sequence whose files it renames changed. /// public sealed class StaleRenamePlanException(Guid sequenceId) : InvalidOperationException(Loc.L("Archive.Error.StalePlan")) @@ -17,9 +18,19 @@ public sealed class StaleRenamePlanException(Guid sequenceId) } /// -/// Mass rename of sequence folders and titles (BRIEF §7, §12.5): is the dry run; -/// makes exactly the planned changes to folders, sidecars and the index, step by step, with a -/// journal on the archive so an interrupted rename is completed by . +/// What applying a plan did: the sequences changed (in the order of the plan), the frames whose files got a new name, the +/// sequences left as they were because they changed since the plan (, only when resuming) and those +/// whose files kept their names because their photos changed since (; their folder and title changed). +/// +public sealed record RenameResult(IReadOnlyList Changed, int Files, IReadOnlyList Dropped, IReadOnlyList FilesKept); + +/// +/// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7): +/// is the dry run; +/// makes exactly the planned changes to +/// folders, files, sidecars and the index, step by step, with a journal on the archive so an interrupted rename is +/// completed by (or, for a plan its job held, by ). A step's file +/// renames have their own journal in the sequence (). /// public sealed class MassRenamer { @@ -38,20 +49,35 @@ public sealed class MassRenamer /// New title template ({title} = the current title), or null to keep titles. /// Sequences nested in a folder that moves are part of the plan (they move with it); see . /// A new folder would lie inside a sequence's folder. - public async Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, string? folderTemplate, string? titleTemplate, - CancellationToken cancellationToken = default) + public Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, string? folderTemplate, string? titleTemplate, + CancellationToken cancellationToken = default) => + PlanAsync(archive, sequenceIds, new RenameTemplates(folderTemplate, null, titleTemplate), cancellationToken); + + /// + /// The dry run of a Reorganize: the plan of over . With a file + /// template each sequence's sidecar is read (without its lease) with the files beside its frames, so the plan names + /// exactly the files the apply will rename while nothing changes. A sequence created without photos, which has no + /// folder yet, is left out. + /// + /// A sequence is not in the archive. + /// A new folder would lie inside a sequence's folder. + public async Task PlanAsync(Archive archive, IReadOnlyList sequenceIds, RenameTemplates templates, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(archive); + ArgumentNullException.ThrowIfNull(sequenceIds); + ArgumentNullException.ThrowIfNull(templates); var paths = new ArchivePaths(archive.RootPath); var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false); var subjects = new List(sequenceIds.Count); - foreach (var id in sequenceIds) + foreach (var id in sequenceIds.Distinct()) { if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id) throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds)); - subjects.Add(Subject(s)); + if (ArchiveIngest.AwaitsFolder(s, paths)) continue; + subjects.Add(Subject(s) with { Files = templates.File is null ? null : ReadFiles(paths, s) }); } var nested = new List(); - if (folderTemplate is not null) + if (templates.Folder is not null) { var selected = sequenceIds.ToHashSet(); foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder)))) @@ -59,51 +85,115 @@ public sealed class MassRenamer if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner)); } } - return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder), - folder => Directory.Exists(paths.Sequence(folder).Folder), nested); + return RenamePlanner.Plan(archive.Id, subjects, templates.Folder, templates.Title, locations.Select(l => l.Folder), + folder => Directory.Exists(paths.Sequence(folder).Folder), nested, templates.File); } private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens); - /// Applies a plan; each completed step is journaled before the next starts. - /// A sequence is no longer where the plan expects it, or a folder that moves holds - /// a sequence the plan does not take along; nothing of that step was changed. - public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => - RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken); + /// The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read or is another sequence's. + private static SequenceFiles? ReadFiles(ArchivePaths paths, Sequence sequence) + { + var folder = paths.Sequence(sequence.Folder); + try + { + var manifest = ManifestStore.ReadSequence(folder.ManifestPath); + if (manifest.Id == sequence.Id) return new SequenceFiles(manifest, FileRenames.ListPresent(folder, manifest)); + Log.Warning("archive", $"{folder.ManifestPath} belongs to sequence {manifest.Id}, not {sequence.Id}; its files keep their names"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + Log.Warning("archive", $"The sidecar of {sequence.DisplayTitle} cannot be read; its files keep their names", ex); + } + return null; + } - /// Completes renames interrupted by a crash; returns how many plans were resumed. + /// Applies a plan; each completed step is journaled before the next starts. + /// A sequence is no longer where the plan expects it, a folder that moves holds + /// a sequence the plan does not take along, or the photos of a sequence whose files it renames changed; nothing of that + /// step was changed (a step found stale only once its folder moved keeps its folder and title, and its journal has the + /// next open complete the rest). + /// A file could not be renamed (open elsewhere); the step's files went back to their names. + public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) => + ApplyAsync(archive, plan, null, progress is null ? null : n => + { + progress.Report(n); + return ValueTask.CompletedTask; + }, cancellationToken); + + /// + /// Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint). + /// Told after each step with the number of steps done. + public Task ApplyAsync(Archive archive, RenamePlan plan, Func? started, Func? stepDone, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken); + } + + /// + /// Completes the plan from its journal: one an interruption left (as + /// does), or one its job held, whose remaining steps are checked as a plan applied anew (a sequence changed since refuses + /// the rest, and that journal goes). Null when there is no journal: the plan completed (here, or at an archive open). + /// + /// A held plan's remaining steps no longer match the archive; nothing more changed. + public async Task ResumeAsync(Archive archive, Guid planId, Func? stepDone = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(archive); + if (RenameJournal.Read(new ArchivePaths(archive.RootPath), planId) is not { } journal) return null; + return await RunAsync(archive, journal with { Held = false }, resuming: !journal.Held, null, stepDone, cancellationToken).ConfigureAwait(false); + } + + /// + /// Marks the plan held (): its job was paused or cancelled between + /// two steps, so an archive open leaves the rest to that job. False when it has no journal (it completed). + /// + public static bool Hold(Archive archive, Guid planId) + { + ArgumentNullException.ThrowIfNull(archive); + var paths = new ArchivePaths(archive.RootPath); + if (RenameJournal.Read(paths, planId) is not { } journal) return false; + RenameJournal.Write(paths, journal with { Held = true }); + return true; + } + + /// Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed. public async Task ResumePendingAsync(Archive archive, CancellationToken cancellationToken = default) { var paths = new ArchivePaths(archive.RootPath); - var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id).ToList(); - foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, cancellationToken).ConfigureAwait(false); + var pending = RenameJournal.ListPending(paths).Where(j => j.Plan.ArchiveId == archive.Id && !j.Held).ToList(); + foreach (var journal in pending) await RunAsync(archive, journal, resuming: true, null, null, cancellationToken).ConfigureAwait(false); return pending.Count; } /// Steps whose sequence the index no longer knows are dropped instead of failing the rename: /// their sidecars still carry the ids, so the next scan indexes them wherever they ended up. - private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress? progress, CancellationToken cancellationToken) + private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, Func? started, + Func? stepDone, CancellationToken cancellationToken) { var paths = new ArchivePaths(archive.RootPath); ArchiveVolume.EnsureWritable(paths); if (journal.Plan.ArchiveId != archive.Id) throw new ArgumentException("The plan belongs to another archive.", nameof(journal)); var completed = journal.Completed.ToHashSet(); + // A step that changes nothing (its files kept their names, and why) has nothing to apply. + var steps = journal.Plan.Steps.Where(s => s.Changes).ToList(); if (!resuming) { - // A plan made before another change is refused before anything moves: a sequence moved, or one was indexed - // inside a folder that moves (a scan adopted a subfolder copied in since the dry run). - foreach (var step in journal.Plan.Steps) + try { - if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder) - throw new StaleRenamePlanException(step.SequenceId); + await RefuseStaleAsync(archive, paths, journal.Plan, [.. steps.Where(s => !completed.Contains(s.SequenceId))], cancellationToken).ConfigureAwait(false); + } + catch (StaleRenamePlanException) when (completed.Count > 0 || File.Exists(RenameJournal.PathFor(paths, journal.Plan.Id))) + { + // A held plan that no longer fits: what it applied stays, the rest never will. + RenameJournal.Delete(paths, journal.Plan.Id); + Log.Warning("archive", $"The rest of rename {journal.Plan.Id} no longer matches the archive; it was given up"); + throw; } - var planned = journal.Plan.Steps.Select(s => s.SequenceId).ToHashSet(); - if (await StrangerInsideAsync(archive, journal.Plan.Steps.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken) - .ConfigureAwait(false) is { } stranger) - throw new StaleRenamePlanException(stranger.Id); } RenameJournal.Write(paths, journal); - var steps = journal.Plan.Steps; + if (started is not null) await started(journal.Plan).ConfigureAwait(false); + var result = new Tally(); foreach (var step in steps) { if (completed.Contains(step.SequenceId)) continue; @@ -112,13 +202,50 @@ public sealed class MassRenamer IReadOnlyList carried = step.MovesFolder && !step.Carried ? [.. steps.Where(c => c.Carried && !completed.Contains(c.SequenceId) && Carrier(steps, c) == step)] : []; - await ApplyStepAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false); + await ApplyStepAsync(archive, paths, journal.Plan.FileTemplate, step, carried, resuming, result, cancellationToken).ConfigureAwait(false); completed.Add(step.SequenceId); foreach (var c in carried) completed.Add(c.SequenceId); RenameJournal.Write(paths, journal with { Completed = [.. completed] }); - progress?.Report(completed.Count); + if (stepDone is not null) await stepDone(completed.Count).ConfigureAwait(false); } RenameJournal.Delete(paths, journal.Plan.Id); + return new RenameResult(result.Changed, result.Files, result.Dropped, result.FilesKept); + } + + /// + /// A plan made before another change is refused before anything moves: a sequence moved, one was indexed inside a + /// folder that moves (a scan adopted a subfolder copied in since the dry run), or the photos of a sequence whose files + /// it renames changed (another frames version in its sidecar). + /// + private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList remaining, CancellationToken cancellationToken) + { + foreach (var step in remaining) + { + if ((await _db.Sequences.GetAsync(step.SequenceId, cancellationToken).ConfigureAwait(false))?.Folder != step.FromFolder) + throw new StaleRenamePlanException(step.SequenceId); + } + var planned = plan.Steps.Select(s => s.SequenceId).ToHashSet(); + if (await StrangerInsideAsync(archive, remaining.Where(s => s.MovesFolder && !s.Carried), planned, cancellationToken).ConfigureAwait(false) is { } stranger) + throw new StaleRenamePlanException(stranger.Id); + if (plan.FileTemplate is null) return; + foreach (var step in remaining.Where(s => s.FileChanges > 0)) + { + if (FramesVersionOf(paths.Sequence(step.FromFolder), step.SequenceId) != step.FramesVersion) throw new StaleRenamePlanException(step.SequenceId); + } + } + + /// The frames version of a sequence's sidecar (read without its lease); null when it cannot be read or is another sequence's. + private static int? FramesVersionOf(SequencePaths sequence, Guid sequenceId) + { + try + { + var manifest = ManifestStore.ReadSequence(sequence.ManifestPath); + return manifest.Id == sequenceId ? manifest.Versions.Frames : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + return null; + } } /// The step whose folder move carries : the nearest moving folder around it (as planned). @@ -127,14 +254,15 @@ public sealed class MassRenamer /// /// Applies a step, and the steps of the sequences its folder carries, under all their leases: sequence leases, then - /// for a move the thumbnail leases, each by sequence id (the order trash and pack compaction take them in). No - /// writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or - /// before its index row follows. + /// for a move or file renames the thumbnail leases, each by sequence id (the order trash and pack compaction take them + /// in). No writer of a carried sequence (ingest, an editor save, a thumbnail pass) works in the folder while it moves or + /// its files are renamed, or before its index row follows. Once the folder moved the step goes to its end whatever + /// the caller cancels. /// /// A step whose sequence the index no longer has where the plan says is dropped instead of /// failing the rename: its sidecar still carries the id, so the next scan indexes it wherever it ended up. - private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList carried, bool resuming, - CancellationToken cancellationToken) + private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList carried, + bool resuming, Tally result, CancellationToken cancellationToken) { var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList(); var locks = new List(ids.Count); @@ -142,7 +270,7 @@ public sealed class MassRenamer try { foreach (var id in ids) locks.Add(await _writer.LockAsync(paths, id, cancellationToken).ConfigureAwait(false)); - if (step.MovesFolder) + if (step.MovesFolder || step.FileChanges > 0 || carried.Any(c => c.FileChanges > 0)) { foreach (var id in ids) { @@ -151,17 +279,31 @@ public sealed class MassRenamer } } // Checked before anything moves; a dropped step drops the sequences it would have carried, which stay inside it. - if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) return; + if (!await StandsAsync(step, resuming, cancellationToken).ConfigureAwait(false)) + { + result.Dropped.Add(step.SequenceId); + return; + } var follow = new List(carried.Count); foreach (var c in carried) { if (await StandsAsync(c, resuming, cancellationToken).ConfigureAwait(false)) follow.Add(c); + else result.Dropped.Add(c.SequenceId); + } + if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) + { + result.Dropped.Add(step.SequenceId); + result.Dropped.AddRange(follow.Select(c => c.SequenceId)); + return; } - if (!await CarriesAllInsideAsync(archive, paths, step, carried, resuming, cancellationToken).ConfigureAwait(false)) return; RenamePlanner.MoveFolder(paths, step); - await RecordAsync(archive, paths, step, cancellationToken).ConfigureAwait(false); - // Moved with their carrier: only their sidecars and index rows follow. - foreach (var c in follow) await RecordAsync(archive, paths, c, cancellationToken).ConfigureAwait(false); + // Moved with their carrier: only their sidecars and index rows follow, and the names of their files. + foreach (var s in follow.Prepend(step)) + { + await RecordAsync(archive, paths, s, CancellationToken.None).ConfigureAwait(false); + var renamed = await RenameFilesAsync(archive, paths, fileTemplate, s, resuming, result, CancellationToken.None).ConfigureAwait(false); + if (s.MovesFolder || s.Retitles || renamed) result.Changed.Add(s.SequenceId); + } } finally { @@ -215,16 +357,18 @@ public sealed class MassRenamer /// The index row changes in its folder and title only (): a settings edit /// committed meanwhile stays, and frames another process listed in the sidecar are left to the next scan, for which /// the folder keeps no stamps unless the index held it as it was - /// (). + /// (). A step + /// that only renames files has nothing to record here. /// private async Task RecordAsync(Archive archive, ArchivePaths paths, RenameStep step, CancellationToken cancellationToken) { + if (!step.MovesFolder && !step.Retitles) return; var sequence = paths.Sequence(step.ToFolder); var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); // The folder moved with its files' stamps, which the index recorded at its old place. var inStep = await _indexer.InStepAsync(archive, step.FromFolder, sequence, manifest, cancellationToken).ConfigureAwait(false); // A step that only moves the folder keeps the title, which an edit may have changed since the plan. - var retitle = step.FromTitle != step.ToTitle; + var retitle = step.Retitles; if (retitle && manifest.Title != step.ToTitle) { manifest = manifest with @@ -244,4 +388,83 @@ public sealed class MassRenamer } if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); } + + /// + /// The file renames of a step, under the leases its step holds, once its folder is in place (Reorganize, owner review 2, + /// R7). The renames are planned again from the sidecar read under the lease (, with the + /// step's title, the one the dry run showed), which names exactly what the dry run showed while its frames version is the plan's: another one + /// refuses the step (), or, when resuming, leaves its files as they are. The files + /// move in two phases through temporary names under the sequence's journal (), then the + /// sidecar names them (the frame order unchanged, frames version + 1), then the index (), + /// then the journal goes. When nothing moves here but the index names other files than the sidecar, a writer completed + /// the renames after a crash () before the index followed, and the index is synced + /// from the sidecar. Proxies (named by frame index), thumbnails (by index and content hash), renders and exports need + /// nothing. + /// + /// False when the step renames no file, or its files kept their names. + private async Task RenameFilesAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, bool resuming, Tally result, + CancellationToken cancellationToken) + { + if (fileTemplate is null || step.FileChanges == 0) return false; + var sequence = paths.Sequence(step.ToFolder); + var manifest = SequenceWriter.ReadLocked(sequence, step.SequenceId); + var inStep = await _indexer.InStepAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false); + var plan = FileRenames.Plan(manifest, step.ToTitle, PathTemplate.Parse(fileTemplate), FileRenames.ListPresent(sequence, manifest)); + var before = manifest.Versions.Frames; + if (plan.Moves.Count > 0 && before != step.FramesVersion) + { + if (!resuming) throw new StaleRenamePlanException(step.SequenceId); + Log.Warning("archive", $"The files of {sequence.RelativeFolder} keep their names: its photos changed after the plan was made"); + result.FilesKept.Add(step.SequenceId); + return false; + } + if (plan.Moves.Count > 0) + { + var journal = FileRenameJournal.Create(before, plan.Moves, Guid.NewGuid().ToString("N")[..8]); + FileRenameJournal.Write(sequence, journal); + journal = FileRenameJournal.Run(sequence, journal); + manifest = FileRenameJournal.Applied(manifest, journal) ?? manifest; + ManifestStore.WriteSequence(sequence.ManifestPath, manifest); + result.Files += plan.Frames; + Log.Info("archive", $"{sequence.RelativeFolder}: {plan.Frames} file(s) renamed, {plan.Moves.Count - plan.Frames} companion(s) with them"); + await _db.Frames.RenameFilesAsync(manifest.Id, await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false), before, + manifest.Versions.Frames, cancellationToken).ConfigureAwait(false); + if (inStep) await _indexer.RecordStampsAsync(archive, sequence, step.SequenceId, cancellationToken).ConfigureAwait(false); + } + else if ((await BehindAsync(sequence, manifest, cancellationToken).ConfigureAwait(false)).Count > 0) + { + // Photos copied in by hand meanwhile are left to the next scan's reconcile (the photo stamp stays as recorded). + await _indexer.SyncAsync(archive, sequence, manifest, null, SequenceStatus.None, photosChanged: true, cancellationToken).ConfigureAwait(false); + } + FileRenameJournal.Delete(sequence); + return true; + } + + /// The frames the index names by another file than the sidecar does, with the sidecar's path and name; frames the index does not have are left to the next scan. + private async Task> BehindAsync(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken) + { + const int page = 1000; + var files = manifest.Frames.ToDictionary(f => f.Id, f => f.File); + var behind = new List(); + for (var last = -1; ;) + { + var rows = await _db.Frames.ListBySequenceAsync(manifest.Id, last, page, cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + if (!files.TryGetValue(row.Id, out var file)) continue; + var path = sequence.ArchiveRelative(file); + if (row.RelativePath != path) behind.Add(new FrameFileName(row.Id, path, Path.GetFileName(file))); + } + if (rows.Count < page) return behind; + last = rows[^1].Index; + } + } + /// What a run did, as it goes. + private sealed class Tally + { + public List Changed { get; } = []; + public List Dropped { get; } = []; + public List FilesKept { get; } = []; + public int Files { get; set; } + } } diff --git a/src/Chronos.Data/Archiving/SequenceWriter.cs b/src/Chronos.Data/Archiving/SequenceWriter.cs index 9fef2594..6d6fa277 100644 --- a/src/Chronos.Data/Archiving/SequenceWriter.cs +++ b/src/Chronos.Data/Archiving/SequenceWriter.cs @@ -51,6 +51,12 @@ public sealed record ArchiveServiceOptions /// public string? BackupDirectory { get; init; } + /// + /// Told after a job changed a sequence's folder, title or file names (change reorganized, a Reorganize): a server + /// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job. + /// + public Func? SequenceChanged { get; init; } + /// Half the logical cores, at least one: the parallelism when the host sets none. public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2); @@ -88,9 +94,11 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options) } /// - /// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (), - /// settling an interrupted restore from the trash (; left for later while its trash - /// entry is busy) and completing an interrupted ingest batch first. + /// Reads the sidecar of a locked sequence, completing an interrupted Reorganize of its files (), + /// undoing an interrupted photo deletion (), settling an interrupted restore from the + /// trash (; left for later while its trash entry is busy) and completing an interrupted + /// ingest batch first. A sidecar a rename recovery rewrites leaves the index behind it until the rename resumes or the + /// next scan reads it. /// /// The trash entry lease the caller holds already (a restore of that entry), if any. /// The sidecar in the folder belongs to another sequence. @@ -99,6 +107,15 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options) var manifest = ManifestStore.ReadSequence(sequence.ManifestPath); if (manifest.Id != sequenceId) throw new InvalidDataException($"{sequence.ManifestPath} belongs to sequence {manifest.Id}, not {sequenceId}."); + if (File.Exists(sequence.FileRenameJournalPath)) + { + if (FileRenameJournal.Recover(sequence, manifest) is { } renamed) + { + ManifestStore.WriteSequence(sequence.ManifestPath, renamed); + manifest = renamed; + } + FileRenameJournal.Delete(sequence); + } FrameRemovalJournal.Recover(sequence, manifest); FrameTrash.RecoverRestore(sequence, manifest, heldEntryLease); if (IngestJournal.Recover(sequence, manifest) is { } recovered) diff --git a/src/Chronos.Data/Repositories/FrameRepository.cs b/src/Chronos.Data/Repositories/FrameRepository.cs index a55a0f3d..9be83374 100644 --- a/src/Chronos.Data/Repositories/FrameRepository.cs +++ b/src/Chronos.Data/Repositories/FrameRepository.cs @@ -19,6 +19,9 @@ public readonly record struct FramePosition(Guid FrameId, int Index); /// A frame whose content (SHA-256) also exists elsewhere in the archive. public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath); +/// A frame's file after a Reorganize renamed it (owner review 2, R7): its archive-relative path and its file name. +public readonly record struct FrameFileName(Guid FrameId, string RelativePath, string FileName); + /// Light statistics of one frame, written by the analysis job. public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh); @@ -292,6 +295,60 @@ public sealed class FrameRepository [sequenceId, newFolder, length, length, prefix], cancellationToken); } + /// + /// Rewrites the paths and file names of frames of one sequence after a Reorganize renamed their files (owner review 2, + /// R7), in one transaction that locks the sequence's row first ('s + /// order); with the row's frames version becomes it, when it is still + /// (the sidecar's before the renames). Frames of other sequences are never touched and + /// repeating it is harmless. Returns the number of frames updated. + /// + public Task RenameFilesAsync(Guid sequenceId, IReadOnlyList files, int? fromVersion = null, int? toVersion = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(files); + return _db.InTransactionAsync(async session => + { + var updated = 0; + if (_db.Sql.IsPostgres) + { + // The row before its frames, as every writer of a sequence's frames; SQLite's write lock already serialises writers. + await session.ExecuteAsync($"SELECT id FROM sequences WHERE id = $1{_db.Sql.ForUpdate}", [sequenceId], cancellationToken).ConfigureAwait(false); + // One UPDATE … FROM (VALUES …) per batch instead of a round trip per frame. + for (var start = 0; start < files.Count; start += Batch) + { + var count = Math.Min(Batch, files.Count - start); + var sql = new StringBuilder("UPDATE frames AS f SET relative_path = v.p, file_name = v.n FROM (VALUES "); + var args = new DbParam[count * 3 + 1]; + args[0] = sequenceId; + for (var i = 0; i < count; i++) + { + var file = files[start + i]; + sql.Append(i > 0 ? ", (" : "(").Append('$').Append(3 * i + 2).Append(", $").Append(3 * i + 3).Append(", $").Append(3 * i + 4).Append(')'); + args[3 * i + 1] = file.FrameId; + args[3 * i + 2] = file.RelativePath; + args[3 * i + 3] = file.FileName; + } + sql.Append(") AS v(id, p, n) WHERE f.id = v.id AND f.sequence_id = $1"); + updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false); + } + } + else + { + foreach (var file in files) + { + updated += await session.ExecuteAsync("UPDATE frames SET relative_path = $3, file_name = $4 WHERE id = $1 AND sequence_id = $2", + [file.FrameId, sequenceId, file.RelativePath, file.FileName], cancellationToken).ConfigureAwait(false); + } + } + if (toVersion is { } to && fromVersion is { } from) + { + await session.ExecuteAsync("UPDATE sequences SET frames_version = $3, updated_at = $4 WHERE id = $1 AND frames_version = $2", + [sequenceId, from, to, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false); + } + return updated; + }, cancellationToken); + } + /// /// Writes what a verify found, in one transaction: the and /// bits and new hashes. Every other flag stays as stored: decode tiers, duplicates and exclusions belong to other diff --git a/src/Chronos.Protocol/Library.cs b/src/Chronos.Protocol/Library.cs index 5e8af34a..75efd271 100644 --- a/src/Chronos.Protocol/Library.cs +++ b/src/Chronos.Protocol/Library.cs @@ -81,3 +81,39 @@ public sealed record FacetDto(string Value, int Sequences, string? Label = null) /// sequences first) and tags in use (by name) of the archive's sequences, for the admin panel's Library filters. /// public sealed record LibraryFacetsDto(IReadOnlyList Years, IReadOnlyList Cameras, IReadOnlyList Tags); + +/// +/// POST /api/v1/archive/reorganize (owner review 2, R7; administrators of the archive): new folder, file and title +/// templates applied to sequences already in the archive, or every one with +/// (exactly one of the two). A null template keeps that part; at least one is given, each valid as the archive settings' +/// templates are. answers the plan () and changes nothing; the change +/// itself sends that plan's back (409 plan_changed when the archive changed since) and runs +/// as a move job (202). +/// +public sealed record ReorganizeRequest(IReadOnlyList? SequenceIds, bool All, string? FolderTemplate, string? FileTemplate, string? TitleTemplate, + bool DryRun, string? Fingerprint = null); + +/// A file a Reorganize renames: its name before and after, relative to the sequence folder (originals/…). +public sealed record ReorganizeFileDto(string From, string To); + +/// +/// Photos of a sequence that keep their names in a Reorganize: in_place (kept in place outside +/// originals/), unhashed (never verified), missing or unreadable (the sequence's sidecar), how many +/// (0 for unreadable), and the reason as one localised sentence. +/// +public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message); + +/// +/// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after, +/// when it only moves with a folder it is inside, the frames version its file names were planned at +/// (0 when none changes), how many photos get a new name with the first of them (), and the photos +/// that keep their names. A step that changes nothing lists only those. +/// +public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried, + int FramesVersion, int FileChanges, IReadOnlyList FileSamples, IReadOnlyList Blocked); + +/// +/// The dry run of a Reorganize: its steps, the sequences that change (carried ones included), the photos renamed, the photos +/// that keep their names, and the fingerprint the change sends back. +/// +public sealed record ReorganizePlanDto(IReadOnlyList Steps, int Sequences, int Files, int Kept, string Fingerprint); diff --git a/src/Chronos.Protocol/ProtocolJson.cs b/src/Chronos.Protocol/ProtocolJson.cs index e68f6d1e..0bdf7cf1 100644 --- a/src/Chronos.Protocol/ProtocolJson.cs +++ b/src/Chronos.Protocol/ProtocolJson.cs @@ -87,4 +87,6 @@ namespace Chronos.Protocol; [JsonSerializable(typeof(BulkItemResult))] [JsonSerializable(typeof(BulkResultDto))] [JsonSerializable(typeof(LibraryFacetsDto))] +[JsonSerializable(typeof(ReorganizeRequest))] +[JsonSerializable(typeof(ReorganizePlanDto))] public sealed partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs index 1bfee04e..323c7865 100644 --- a/src/Chronos.Server/Api/ArchiveEndpoints.cs +++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Mvc; using Chronos.Core.Archiving; +using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Naming; using Chronos.Data; @@ -13,12 +14,16 @@ using Chronos.Server.Storage; namespace Chronos.Server.Api; -/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics. +/// +/// /api/v1/archive (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics, and +/// Reorganize (owner review 2, R7): new templates applied to sequences already in the archive. +/// public static class ArchiveEndpoints { public static void Map(RouteGroupBuilder api) { var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive); + archive.MapPost("/reorganize", ReorganizeAsync); // The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll. archive.MapGet("/settings", async (HttpContext c, ServerArchive a, ChronosDatabase db, [FromServices] ArchiveService? archives) => Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto)); @@ -122,6 +127,77 @@ public static class ArchiveEndpoints return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto); } + /// + /// Reorganize: folder, file and title templates applied to sequenceIds or, with all, to every sequence of the + /// archive (BRIEF §12.5). With dryRun the plan, nothing touched: per sequence its folder and title before and after, + /// the photos renamed with the first of them, and the photos that keep their names and why. Otherwise the request carries + /// that plan's fingerprint and the server queues a move job (202) that applies exactly that plan, refused when the + /// archive changed before it ran. 400 bad_request (details sequenceIds: neither or both of them, none, or + /// more than ; templates: none; fingerprint), 400 + /// invalid_template (details: folderTemplate, fileTemplate or titleTemplate); 404 + /// not_found (sequence: not in the archive); 409 nested_target (details: the folder that would lie + /// inside a sequence's folder), plan_changed (details: the fingerprint now), job_unavailable; 503 + /// archive_offline. Audited; the job tells every sequence it changes as sequenceChanged + /// (reorganized). + /// + private static async Task ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive, + [FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit) + { + var ct = context.RequestAborted; + if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds }) + return ApiErrors.BadRequest(context, "bad_request", "sequenceIds"); + var templates = new RenameTemplates(request.FolderTemplate, request.FileTemplate, request.TitleTemplate); + if (templates.IsEmpty) return ApiErrors.BadRequest(context, "bad_request", "templates"); + if (templates.Problem() is { } field) return ApiErrors.BadRequest(context, "invalid_template", field); + if (!request.DryRun && string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint"); + if (ArchiveService.GetAvailability(archive.Current) != ArchiveAvailability.Online) + return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline"); + RenamePlan plan; + try + { + plan = await LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, request.All ? null : request.SequenceIds, templates, ct); + } + catch (NestedRenameException ex) + { + return ApiErrors.Conflict(context, "nested_target", ex.Target); + } + catch (ArgumentException) + { + return ApiErrors.NotFound(context, "sequence"); + } + var fingerprint = plan.Fingerprint(); + if (request.DryRun) return Results.Json(Plan(context, plan, fingerprint), ProtocolJson.Default.ReorganizePlanDto); + if (!string.Equals(fingerprint, request.Fingerprint, StringComparison.Ordinal)) return ApiErrors.Conflict(context, "plan_changed", fingerprint); + if (!host.CanRun(JobKind.Move)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.Move)); + var job = await host.Engine.EnqueueAsync(ArchiveJobs.Reorganize(archive.Current, plan, templates), caller.Id, ct); + await audit.WriteAsync(caller, context, "archive_reorganized", "job", job.Id.ToString(), + $"{plan.Steps.Count(s => s.Changes)} · {plan.Steps.Sum(s => s.FileChanges)} · {templates.Folder} · {templates.File} · {templates.Title}"); + return Results.Json(Dto.Job(job), ProtocolJson.Default.JobDto, statusCode: StatusCodes.Status202Accepted); + } + + /// The dry run as the API answers it, with each reason photos keep their names in the request's language. + private static ReorganizePlanDto Plan(HttpContext context, RenamePlan plan, string fingerprint) + { + var culture = RequestCulture.Of(context); + return new ReorganizePlanDto( + [.. plan.Steps.Select(s => new ReorganizeStepDto(s.SequenceId, s.FromFolder, s.ToFolder, s.FromTitle, s.ToTitle, s.Carried, s.FramesVersion, + s.FileChanges, [.. s.FileSamples.Select(f => new ReorganizeFileDto(f.From, f.To))], + [.. s.Blocked.Select(b => new ReorganizeBlockedDto(Wire(b.Reason), b.Frames, Loc.Get("Archive.Reorganize.Blocked." + b.Reason, culture) ?? Wire(b.Reason)))]))], + plan.Steps.Count(s => s.Changes), + plan.Steps.Sum(s => s.FileChanges), + plan.Steps.Sum(s => s.Blocked.Sum(b => b.Frames)), + fingerprint); + } + + /// Wire name of a reason photos keep their names: in_place, unhashed, missing, unreadable. + public static string Wire(RenameBlock reason) => reason switch + { + RenameBlock.InPlace => "in_place", + RenameBlock.Unhashed => "unhashed", + RenameBlock.Missing => "missing", + _ => "unreadable", + }; + private static async Task EnqueueAsync(HttpContext context, Caller caller, ServerArchive archive, JobEngineHost host, AuditLog audit, JobKind kind) { if (!host.CanRun(kind)) return ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(kind)); diff --git a/src/Chronos.Server/Storage/ArchiveModule.cs b/src/Chronos.Server/Storage/ArchiveModule.cs index 0f7aaf94..6e00c265 100644 --- a/src/Chronos.Server/Storage/ArchiveModule.cs +++ b/src/Chronos.Server/Storage/ArchiveModule.cs @@ -3,14 +3,17 @@ using Chronos.Data; using Chronos.Data.Archiving; using Chronos.Data.Housekeeping; using Chronos.Data.Jobs; +using Chronos.Protocol; using Chronos.Server.Configuration; +using Chronos.Server.Events; namespace Chronos.Server.Storage; /// /// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and /// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance, the duplicates and -/// orphans reports, index backups and clean-ups with the server's own steps, the s in DI); a scan +/// orphans reports, index backups and clean-ups with the server's own steps, the s in DI, and Reorganize's +/// move jobs, which tell connected clients of the sequences they change); a scan /// queues thumbnails and proxies of what it indexes, as an upload does. Decoding is managed only (BRIEF §4.2). Recurring /// work (the periodic scan, the nightly backup of an SQLite index, clean-ups) is queued by the server's system schedules /// (, owner review 2, R10). @@ -25,9 +28,17 @@ public static class ArchiveModule services.AddSingleton(sp => { var options = sp.GetRequiredService(); + var db = sp.GetRequiredService(); + var events = sp.GetRequiredService(); // Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1). - return new ArchiveService(sp.GetRequiredService(), new ArchiveServiceOptions + return new ArchiveService(db, new ArchiveServiceOptions { + // A Reorganize tells connected clients of every sequence it changed (BRIEF §14.3). + SequenceChanged = async (id, change, ct) => + { + if (await db.Sequences.GetAsync(id, ct) is { } sequence) + events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion)); + }, Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, diff --git a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs new file mode 100644 index 00000000..90674335 --- /dev/null +++ b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs @@ -0,0 +1,226 @@ +using System.Text; +using Chronos.Core.Archiving; +using Chronos.Core.Naming; +using Chronos.Testing; + +namespace Chronos.Core.Tests.Archiving; + +/// Reorganize (owner review 2, R7): file names planned from a template, and the two-phase renames of a sequence's files. +[Category("archive")] +public sealed class ReorganizeTests(TestContext context) +{ + private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0); + + /// Frames in index order, every one hashed, ten seconds apart. + private static SequenceManifest Sequence(params string[] files) => new() + { + Id = Guid.NewGuid(), + Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" }, + Versions = new ManifestVersions { Frames = 4 }, + Frames = [.. files.Select((f, i) => new SidecarFrame + { + Id = Guid.NewGuid(), + I = i, + File = f, + Original = $"IMG_{i + 1:0000}{Path.GetExtension(f)}", + Sha256 = new string((char)('a' + i % 6), 64), + CapturedAt = Start.AddSeconds(10 * i), + })], + }; + + private static FileRenamePlan Plan(SequenceManifest manifest, string template, string? title = null, IEnumerable? extra = null) => + FileRenames.Plan(manifest, title, PathTemplate.Parse(template), [.. manifest.Frames.Select(f => f.File), .. extra ?? []]); + + [Test] + public void FramesAreNamedInIndexOrderAndNamesTakenGetNumbersAsFilingDoes() + { + var manifest = Sequence("originals/c.JPG", "originals/a.JPG", "originals/b.JPG", "originals/d.JPG"); + var plan = Plan(manifest, "{date}"); + Assert.SequenceEqual(["originals/2026-09-28.JPG", "originals/2026-09-28_2.JPG", "originals/2026-09-28_3.JPG", "originals/2026-09-28_4.JPG"], + plan.Moves.Select(m => m.To)); + Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), plan.Moves.Select(m => m.FrameId)); + Assert.Equal(4, plan.Frames); + Assert.SequenceEqual(plan.Moves.Take(FileRenames.SampleCount), plan.Samples); + Assert.Empty(plan.Blocked); + } + + [Test] + public void AChainOfNamesIsPlannedAndAFileNoFrameListsKeepsItsName() + { + // Frame 1 now holds the name frame 0 gets, frame 2 the one frame 1 gets: 2→1, 3→2, 4→3. A file no frame lists holds "4". + var manifest = Sequence("originals/2.JPG", "originals/3.JPG", "originals/4.JPG"); + var plan = Plan(manifest, "{n:0}"); + Assert.SequenceEqual(["originals/2.JPG>originals/1.JPG", "originals/3.JPG>originals/2.JPG", "originals/4.JPG>originals/3.JPG"], + plan.Moves.Select(m => $"{m.From}>{m.To}")); + + var stray = Plan(manifest, "{n:0}", extra: ["originals/1.jpg", "originals/notes.txt"]); + Assert.Equal("originals/1_2.JPG", stray.Moves[0].To); + } + + [Test] + public void PhotosInPlaceUnhashedOrMissingKeepTheirNamesAndHoldThem() + { + var manifest = Sequence("IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG"); + manifest = manifest with { Frames = [manifest.Frames[0], manifest.Frames[1] with { Sha256 = null }, manifest.Frames[2], manifest.Frames[3]] }; + // The third photo is not on disk; the fourth would take its name. + var plan = FileRenames.Plan(manifest, "IMG_0003", PathTemplate.Parse("{title}"), ["IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0004.JPG"]); + Assert.SequenceEqual([(RenameBlock.InPlace, 1), (RenameBlock.Unhashed, 1), (RenameBlock.Missing, 1)], plan.Blocked.Select(b => (b.Reason, b.Frames))); + Assert.Equal("originals/IMG_0004.JPG>originals/IMG_0003_2.JPG", plan.Moves.Select(m => $"{m.From}>{m.To}").Single()); + Assert.Equal(1, plan.Frames); + } + + [Test] + public void CompanionsFollowTheirPhotoAndTheirNamesAreKeptFree() + { + var manifest = Sequence("originals/A.CR2", "originals/B.CR2"); + var plan = Plan(manifest, "{n:0000}", extra: ["originals/A.xmp", "originals/B.CR2.xmp", "originals/0001.xmp"]); + // "0001.xmp" belongs to no frame: the first photo, whose companion would take it, gets the next free name. + Assert.SequenceEqual(["originals/A.CR2>originals/0001_2.CR2", "originals/A.xmp>originals/0001_2.xmp", + "originals/B.CR2>originals/0002.CR2", "originals/B.CR2.xmp>originals/0002.CR2.xmp"], plan.Moves.Select(m => $"{m.From}>{m.To}")); + Assert.SequenceEqual([false, true, false, true], plan.Moves.Select(m => m.Companion)); + Assert.Equal(2, plan.Frames); + Assert.Count(2, plan.Samples); + } + + [Test] + public void NamesGivenOnceStayAsTheyAre() + { + var manifest = Sequence("originals/x.JPG", "originals/y.JPG"); + var plan = Plan(manifest, "{date}_{n:000}"); + var renamed = FileRenameJournal.Applied(manifest, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))!; + Assert.Equal(manifest.Versions.Frames + 1, renamed.Versions.Frames); + Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), renamed.Frames.Select(f => f.Id)); + Assert.Empty(Plan(renamed, "{date}_{n:000}").Moves); + Assert.Null(FileRenameJournal.Applied(renamed, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))); + } + + [Test] + public void APlanWithAFileTemplateCountsSamplesAndListsWhatKeepsItsName() + { + var renamed = Sequence("originals/a.JPG", "originals/b.JPG"); + var adopted = Sequence("a.JPG"); + var subjects = new[] + { + new RenameSubject(renamed.Id, "s/one", "Trip", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(renamed, [.. renamed.Frames.Select(f => f.File)]) }, + new RenameSubject(adopted.Id, "s/two", "Adopted", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(adopted, ["a.JPG"]) }, + new RenameSubject(Guid.NewGuid(), "s/three", null, Start, "Canon", "Canon EOS R5", null), + }; + var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, null, "{title} 2026", ["s/one", "s/two", "s/three"], _ => false, fileTemplate: "{title}_{n:00}"); + Assert.Equal("{title}_{n:00}", plan.FileTemplate); + Assert.SequenceEqual(subjects.Select(s => s.SequenceId), plan.Subjects); + var one = plan.Steps.Single(s => s.SequenceId == renamed.Id); + Assert.Equal((2, 4), (one.FileChanges, one.FramesVersion)); + // The new title names the files. + Assert.SequenceEqual(["originals/Trip 2026_01.JPG", "originals/Trip 2026_02.JPG"], one.FileSamples.Select(f => f.To)); + var two = plan.Steps.Single(s => s.SequenceId == adopted.Id); + Assert.Equal((0, 0), (two.FileChanges, two.FramesVersion)); + Assert.Equal((RenameBlock.InPlace, 1), (two.Blocked.Single().Reason, two.Blocked.Single().Frames)); + Assert.True(two.Changes, "its title changes"); + var three = plan.Steps.Single(s => s.SequenceId == subjects[2].SequenceId); + Assert.Equal(RenameBlock.Unreadable, three.Blocked.Single().Reason); + + // Nothing but kept names: listed, changes nothing. + var keptOnly = RenamePlanner.Plan(Guid.NewGuid(), [subjects[1]], null, null, ["s/two"], _ => false, fileTemplate: "{n}"); + Assert.False(keptOnly.Steps.Single().Changes); + } + + [Test] + public void TheFingerprintFollowsWhatThePlanChanges() + { + var manifest = Sequence("originals/a.JPG"); + RenamePlan Make(SequenceManifest m) => RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(m.Id, "s", "T", Start, null, null, null) + { Files = new SequenceFiles(m, [.. m.Frames.Select(f => f.File)]) }], null, null, ["s"], _ => false, fileTemplate: "{n:000}"); + var plan = Make(manifest); + Assert.Equal(64, plan.Fingerprint().Length); + Assert.Equal(plan.Fingerprint(), Make(manifest).Fingerprint()); + Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Versions = new ManifestVersions { Frames = 5 } }).Fingerprint()); + } + + [Test] + public void TemplatesAreCheckedAsTheArchiveSettingsAre() + { + Assert.Null(new RenameTemplates("{year}/{title}", "{date}_{n}", "{title} 2026").Problem()); + Assert.Equal("folderTemplate", new RenameTemplates(Folder: " ").Problem()); + Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem()); + Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem()); + Assert.Equal("titleTemplate", new RenameTemplates(Title: "{title").Problem()); + Assert.True(new RenameTemplates().IsEmpty); + } + + private SequencePaths Folder(out ArchivePaths archive) + { + archive = new ArchivePaths(context.CreateTempDirectory("archive")); + var sequence = archive.Sequence("s"); + Directory.CreateDirectory(sequence.Originals); + Directory.CreateDirectory(sequence.MetaDirectory); + return sequence; + } + + private static void Write(SequencePaths sequence, string file, string text) => File.WriteAllText(sequence.File(file), text, Encoding.UTF8); + + private static string Read(SequencePaths sequence, string file) => File.ReadAllText(sequence.File(file), Encoding.UTF8); + + [Test] + public void FilesMoveInTwoPhasesSoChainsAndSwapsNeverMeet() + { + var sequence = Folder(out _); + Write(sequence, "originals/a.jpg", "A"); + Write(sequence, "originals/b.jpg", "B"); + Write(sequence, "originals/c.jpg", "C"); + Guid x = Guid.NewGuid(), y = Guid.NewGuid(), z = Guid.NewGuid(); + // A swap (a↔b) and a chain into a name that frees up (c→a's place is taken by b, so c→d). + var journal = FileRenameJournal.Create(7, [new FileRename(x, "originals/a.jpg", "originals/b.jpg"), new FileRename(y, "originals/b.jpg", "originals/a.jpg"), + new FileRename(z, "originals/c.jpg", "originals/d.jpg")], "t1"); + FileRenameJournal.Write(sequence, journal); + var done = FileRenameJournal.Run(sequence, journal); + Assert.Equal(2, done.Phase); + Assert.Equal(("A", "B", "C"), (Read(sequence, "originals/b.jpg"), Read(sequence, "originals/a.jpg"), Read(sequence, "originals/d.jpg"))); + Assert.FileMissing(sequence.File("originals/c.jpg")); + Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp)))); + Assert.True(journal.Files.All(f => Path.GetFileName(f.Temp).StartsWith(".chronos-rename-t1-", StringComparison.Ordinal)), "hidden, never a photo"); + } + + [Test] + public void AFailedMovePutsEveryFileBackAndChangesNothing() + { + var sequence = Folder(out _); + Write(sequence, "originals/a.jpg", "A"); + Write(sequence, "originals/b.jpg", "B"); + var journal = FileRenameJournal.Create(1, [new FileRename(Guid.NewGuid(), "originals/a.jpg", "originals/x.jpg"), + new FileRename(Guid.NewGuid(), "originals/b.jpg", "originals/y.jpg")], "t2"); + FileRenameJournal.Write(sequence, journal); + // Another file took the second name after the plan: nothing is written over it, and the first file goes back. + Write(sequence, "originals/y.jpg", "other"); + Assert.Throws(() => FileRenameJournal.Run(sequence, journal)); + Assert.Equal(("A", "B", "other"), (Read(sequence, "originals/a.jpg"), Read(sequence, "originals/b.jpg"), Read(sequence, "originals/y.jpg"))); + Assert.FileMissing(sequence.File("originals/x.jpg")); + Assert.Null(FileRenameJournal.Read(sequence)); + } + + [Theory] + [Case(1)] + [Case(2)] + public void ARenameACrashInterruptedIsCompleted(int phase) + { + var sequence = Folder(out _); + var manifest = Sequence("originals/2.jpg", "originals/3.jpg", "originals/4.jpg"); + foreach (var f in manifest.Frames) Write(sequence, f.File, f.Id.ToString()); + var plan = Plan(manifest, "{n:0}"); + var journal = FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t3") with { Phase = phase }; + FileRenameJournal.Write(sequence, journal); + // Phase 1: the first file reached its temporary name. Phase 2: every file did, and the first its new name. + File.Move(sequence.File(journal.Files[0].From), sequence.File(journal.Files[0].Temp)); + if (phase == 2) + { + foreach (var f in journal.Files.Skip(1)) File.Move(sequence.File(f.From), sequence.File(f.Temp)); + File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To)); + } + + var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)); + Assert.SequenceEqual(["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File)); + Assert.Equal(manifest.Versions.Frames + 1, recovered.Versions.Frames); + foreach (var f in recovered.Frames) Assert.Equal(f.Id.ToString(), Read(sequence, f.File)); + Assert.FileMissing(sequence.File("originals/4.jpg")); + Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp)))); + } +} diff --git a/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs b/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs new file mode 100644 index 00000000..2f011079 --- /dev/null +++ b/tests/Chronos.Core.Tests/Naming/FrameNamingTests.cs @@ -0,0 +1,116 @@ +using Chronos.Core.Archiving; +using Chronos.Core.Import; +using Chronos.Core.Metadata; +using Chronos.Core.Model; +using Chronos.Core.Naming; +using Chronos.Core.Tests.Archiving; +using Chronos.Testing; +using static Chronos.Core.Tests.Import.ImportTestKit; + +namespace Chronos.Core.Tests.Naming; + +/// Import, upload and Reorganize name a photo alike (owner review 2, R7). +[Category("naming")] +public sealed class FrameNamingTests(TestContext context) +{ + private const string EveryToken = "{date}_{time}_{hm}_{sessionstart}_{n:0000}_{nsession}_{camera}_{lens}_{iso}_{shutter}_{aperture}_{name}_{title}"; + + private static FrameMetadata Metadata(DateTime captured) => new() + { + Make = "Canon", + Model = "Canon EOS R5", + LensModel = "RF15-35mm F2.8 L IS USM", + Iso = 400, + ExposureTime = 1.0 / 250, + FNumber = 8, + CapturedAt = captured, + TimestampSource = TimestampSource.ExifOriginal, + }; + + [Test] + public void AFrameInItsSequenceIsNamedAsTheUploadOfItsPhotoWas() + { + var start = new DateTime(2026, 9, 28, 18, 2, 11); + var template = PathTemplate.Parse(EveryToken); + var frames = Enumerable.Range(0, 3) + .Select(i => SequenceFrames.FromMetadata(Guid.NewGuid(), $"originals/x{i}.CR3", $"IMG_{4211 + i}.CR3", 100, new string('a', 64), Metadata(start.AddSeconds(5 * i)))) + .ToList(); + var first = Metadata(start); + var manifest = SequenceFrames.Insert(new SequenceManifest + { + Id = Guid.NewGuid(), + Camera = new SidecarCamera { Make = first.Make, Model = first.Model }, + Lens = first.LensModel, + }, frames); + + for (var i = 0; i < 3; i++) + { + var filed = template.ExpandFile(FrameNaming.Context(Metadata(start.AddSeconds(5 * i)), $"IMG_{4211 + i}.CR3", start.AddSeconds(5 * i), start, i + 1, "Harbour")); + Assert.Equal(filed, template.ExpandFile(FrameNaming.Context(manifest.Frames[i], manifest, "Harbour"))); + } + Assert.Equal("2026-09-28_18-02-16_18-02_2026-09-28 18-02_0002_0002_Canon EOS R5_RF15-35mm F2.8 L IS USM_400_1-250_f8_IMG_4212_Harbour.CR3", + template.ExpandFile(FrameNaming.Context(manifest.Frames[1], manifest, "Harbour"))); + } + + [Test] + public void AFrameWithoutACaptureTimeTakesTheStartOfItsSequence() + { + var created = new DateTimeOffset(2026, 10, 1, 9, 30, 0, TimeSpan.Zero); + var manifest = new SequenceManifest + { + Id = Guid.NewGuid(), + Created = created, + Frames = [new SidecarFrame { Id = Guid.NewGuid(), File = "originals/a.jpg", Original = "DSC_0001.JPG" }], + }; + var context = FrameNaming.Context(manifest.Frames[0], manifest, null); + Assert.Equal(new DateTime(2026, 10, 1, 9, 30, 0), context.CapturedAt); + Assert.Equal(context.CapturedAt, context.SessionStart); + Assert.Equal("DSC_0001", context.OriginalName); + Assert.Equal("jpg", context.Extension); + Assert.Equal(1, context.Number); + } + + [Test] + public void TakenNamesGetNumbersBeforeTheExtensionAsFilingGivesThem() + { + var template = PathTemplate.Parse("{date}"); + var context = FrameNaming.Context(Metadata(new DateTime(2026, 9, 28, 18, 0, 0)), "IMG_1.JPG", new DateTime(2026, 9, 28, 18, 0, 0), + new DateTime(2026, 9, 28, 18, 0, 0), 1, null); + var taken = new HashSet(StringComparer.OrdinalIgnoreCase) { "originals/2026-09-28.jpg" }; + Assert.Equal("originals/2026-09-28_2.JPG", FrameNaming.FileName(template, context, taken, "originals/")); + Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, taken, "originals/")); + Assert.Contains("originals/2026-09-28_3.JPG", taken); + Assert.Equal("a/IMG_5_2.CR2", FrameNaming.Unique("a/IMG_5.CR2", f => f != "a/IMG_5.CR2")); + } + + [Test] + public async Task AnImportedSessionIsNamedAsReorganizeNamesItsFrames() + { + var card = context.CreateTempDirectory("card"); + TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 4, TimeSpan.FromSeconds(10)); + const string fileTemplate = "{date}_{time}_{n:0000}_{camera}_{name}"; + var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate }); + var session = plan.Sessions.Single(); + + // The sequence the import files: the plan's names, each frame from its photo's metadata, the camera of the first. + var frames = session.Items.Select(item => + { + var metadata = MetadataReader.Read(Path.Combine(card, item.SourcePath)); + return SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath), item.Size, new string('b', 64), + metadata, item.CapturedAt); + }).ToList(); + var first = MetadataReader.Read(Path.Combine(card, session.Items[0].SourcePath)); + var manifest = SequenceFrames.Insert(new SequenceManifest + { + Id = Guid.NewGuid(), + Camera = new SidecarCamera { Make = first.Make, Model = first.Model }, + Lens = first.LensModel, + }, frames); + + var reorganized = FileRenames.Plan(manifest, session.Title, PathTemplate.Parse(fileTemplate), [.. manifest.Frames.Select(f => f.File)]); + Assert.Empty(reorganized.Moves); + Assert.Equal(0, reorganized.Frames); + Assert.SequenceEqual(session.Items.Select(i => i.FileName), + manifest.Frames.Select(f => PathTemplate.Parse(fileTemplate).ExpandFile(FrameNaming.Context(f, manifest, session.Title)))); + } +} diff --git a/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs new file mode 100644 index 00000000..79088761 --- /dev/null +++ b/tests/Chronos.Data.Tests/Archiving/ReorganizeTests.cs @@ -0,0 +1,280 @@ +using System.Security.Cryptography; +using Chronos.Core.Archiving; +using Chronos.Core.Import; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Core.Naming; +using Chronos.Data.Archiving; +using Chronos.Testing; +using static Chronos.Data.Tests.Archiving.ArchiveFixture; + +namespace Chronos.Data.Tests.Archiving; + +/// +/// Reorganize (owner review 2, R7): new folder, file and title templates applied to sequences already in the archive, with a +/// dry run, two-phase file renames under a journal, crash recovery, stale plans and the move job. +/// +[Category("archive")] +public sealed class ReorganizeTests(TestContext context) +{ + private static IngestRequest Upload(ArchiveFixture fx, (string Path, long Size, string Sha256) staged, string name, string key) => + new(fx.Archive.Id, null, null, key, staged.Path, name, staged.Size, staged.Sha256, null, null); + + /// Uploads photos ten seconds apart (from ) into the sequence of ; returns its id. + private static async Task UploadAsync(ArchiveFixture fx, int count, int firstSeed = 1, int firstSecond = 0, string key = "upload-1") + { + Guid id = default; + for (var i = 0; i < count; i++) + { + var staged = fx.Stage(Start.AddSeconds(firstSecond + 10 * i), firstSeed + i); + id = (await fx.Service.Ingest.CommitAsync(Upload(fx, staged, $"IMG_{firstSeed + i:0000}.JPG", key), fx.Ct)).SequenceId; + } + return id; + } + + /// + /// A sequence whose names follow "{n:0}" no more: two photos filed as 1 and 2, then an earlier one filed before them as 1_2. + /// Renamed with "{n:0}" again they chain: 1_2→1, 1→2, 2→3. + /// + private static async Task ChainAsync(ArchiveFixture fx) + { + await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n:0}" } }, fx.Ct); + await UploadAsync(fx, 2, firstSeed: 2, firstSecond: 10); + var id = await UploadAsync(fx, 1, firstSeed: 1); + Assert.SequenceEqual(["originals/1_2.JPG", "originals/1.JPG", "originals/2.JPG"], await FilesAsync(fx, id)); + return id; + } + + /// + /// The files of a sequence as its sidecar names them, after checking that the index names the same files in the same + /// order at the same frames version, that every file holds its frame's photo and that no journal is left. + /// + private static async Task> FilesAsync(ArchiveFixture fx, Guid id) + { + var sequence = Assert.NotNull(await fx.Db.Sequences.GetAsync(id)); + var folder = fx.Paths.Sequence(sequence.Folder); + var sidecar = ManifestStore.ReadSequence(folder.ManifestPath); + var rows = await fx.Db.Frames.ListBySequenceAsync(id); + Assert.SequenceEqual(sidecar.Frames.Select(f => f.Id), rows.Select(r => r.Id)); + Assert.Equal(sidecar.Versions.Frames, sequence.FramesVersion); + Assert.Equal(sidecar.Title, sequence.Title); + foreach (var (frame, row) in sidecar.Frames.Zip(rows)) + { + Assert.Equal(folder.ArchiveRelative(frame.File), row.RelativePath); + Assert.Equal(Path.GetFileName(frame.File), row.FileName); + Assert.Equal(frame.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(folder.File(frame.File))))); + } + Assert.Null(FileRenameJournal.Read(folder)); + Assert.Empty(Directory.EnumerateFiles(folder.Originals, ".chronos-rename-*")); + return [.. sidecar.Frames.Select(f => f.File)]; + } + + [Test] + public async Task FilesAreRenamedExactlyAsTheDryRunSaid() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 3); + var before = await FilesAsync(fx, id); + var version = (await fx.Db.Sequences.GetAsync(id))!.FramesVersion; + var templates = new RenameTemplates(File: "{title}_{n:000}", Title: "Roof"); + + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct); + var step = plan.Steps.Single(); + Assert.Equal((3, version, "Roof"), (step.FileChanges, step.FramesVersion, step.ToTitle)); + Assert.SequenceEqual(before.Zip(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], (f, t) => $"{f}>{t}"), + step.FileSamples.Select(s => $"{s.From}>{s.To}")); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + + var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.Equal(3, result.Files); + Assert.SequenceEqual([id], result.Changed); + Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], await FilesAsync(fx, id)); + Assert.Equal(version + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion); + Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + Assert.Equal(0, (await fx.ScanAsync()).Indexed); + // Applied again, the templates change nothing. + Assert.False((await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct)).Steps.Any(s => s.Changes)); + } + + [Test] + public async Task UploadsAndImportsAreNamedAsReorganizeNamesThem() + { + await using var fx = await CreateAsync(context); + await UploadAsync(fx, 3); + var card = context.CreateTempDirectory("card"); + Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start.AddDays(1), 4, firstSeed: 30); + var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card, + new ImportOptions { FolderTemplate = fx.Archive.FolderTemplate, FileTemplate = fx.Archive.FileTemplate }, null, null, fx.Ct); + var engine = await fx.StartEngineAsync(); + await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, import, null), cancellationToken: fx.Ct)).Id, JobState.Done); + Assert.Count(2, await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)); + + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, null, new RenameTemplates(File: fx.Archive.FileTemplate), fx.Ct); + Assert.Empty(plan.Steps); + Assert.Count(2, plan.Subjects); + } + + [Test] + public async Task AChainOfNewNamesIsRenamedThroughTemporaryNames() + { + await using var fx = await CreateAsync(context); + var id = await ChainAsync(fx); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct); + Assert.Equal(3, plan.Steps.Single().FileChanges); + await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id)); + } + + [Theory] + [Case(1)] + [Case(2)] + public async Task ARenameACrashInterruptedIsCompletedAtTheNextOpen(int phase) + { + await using var fx = await CreateAsync(context); + var id = await ChainAsync(fx); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:0}"), fx.Ct); + + // The process stopped inside the step: the plan's journal and the sequence's, files part-way through their phase. + RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); + var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder); + var manifest = ManifestStore.ReadSequence(folder.ManifestPath); + var moves = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0}"), FileRenames.ListPresent(folder, manifest)).Moves; + var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "crash") with { Phase = phase }; + FileRenameJournal.Write(folder, journal); + File.Move(folder.File(journal.Files[0].From), folder.File(journal.Files[0].Temp)); + if (phase == 2) + { + foreach (var file in journal.Files.Skip(1)) File.Move(folder.File(file.From), folder.File(file.Temp)); + File.Move(folder.File(journal.Files[0].Temp), folder.File(journal.Files[0].To)); + } + + await fx.Service.OpenAsync(fx.Archive.RootPath, fx.Ct); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + Assert.SequenceEqual(["originals/1.JPG", "originals/2.JPG", "originals/3.JPG"], await FilesAsync(fx, id)); + Assert.Equal(manifest.Versions.Frames + 1, (await fx.Db.Sequences.GetAsync(id))!.FramesVersion); + } + + [Test] + public async Task APlanWhosePhotosChangedIsRefusedOrResumedWithoutTheirNames() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 2); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}", Title: "Roof"), fx.Ct); + // A photo arrives after the dry run: the names shown are no longer the ones the template gives. + await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5); + var before = await FilesAsync(fx, id); + + var stale = await Assert.ThrowsAsync(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct)); + Assert.Equal(id, stale.SequenceId); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + Assert.Null((await fx.Db.Sequences.GetAsync(id))!.Title); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + + // Interrupted before its step began, the plan resumes: the title changes, the files keep their names. + RenameJournal.Write(fx.Paths, new RenameJournal(plan, [])); + Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct)); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + Assert.Equal("Roof", (await fx.Db.Sequences.GetAsync(id))!.Title); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } + + [Test] + public async Task CompanionsMoveWithTheirPhoto() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 2); + var before = await FilesAsync(fx, id); + var folder = fx.Paths.Sequence((await fx.Db.Sequences.GetAsync(id))!.Folder); + File.WriteAllText(folder.File(Path.ChangeExtension(before[0], ".xmp")), "first"); + File.WriteAllText(folder.File(before[1] + ".xmp"), "second"); + await fx.ScanAsync(); + + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct); + Assert.Equal(2, plan.Steps.Single().FileChanges); + await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, id)); + Assert.Equal("first", File.ReadAllText(folder.File("originals/001.xmp"))); + Assert.Equal("second", File.ReadAllText(folder.File("originals/002.JPG.xmp"))); + Assert.SequenceEqual(["001.JPG", "001.xmp", "002.JPG", "002.JPG.xmp"], Directory.EnumerateFiles(folder.Originals).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Equal(0, (await fx.ScanAsync()).Indexed); + } + + [Test] + public async Task PhotosAdoptedInPlaceKeepTheirNames() + { + await using var fx = await CreateAsync(context); + Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3); + await fx.ScanAsync(); + var id = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single().Id; + + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(File: "{n:000}"), fx.Ct); + var step = plan.Steps.Single(); + Assert.False(step.Changes); + Assert.Equal((RenameBlock.InPlace, 3), (step.Blocked.Single().Reason, step.Blocked.Single().Frames)); + var result = await fx.Service.ApplyRenameAsync(plan, null, fx.Ct); + Assert.Empty(result.Changed); + Assert.SequenceEqual(["IMG_0001.JPG", "IMG_0002.JPG", "IMG_0003.JPG"], ManifestStore.ReadSequence(fx.Paths.Sequence("inbox/a").ManifestPath).Frames.Select(f => f.File)); + } + + [Test] + public async Task AMoveJobAppliesTheConfirmedPlanAndRefusesOneTheArchiveOutgrew() + { + await using var fx = await CreateAsync(context); + var id = await UploadAsync(fx, 3); + var engine = await fx.StartEngineAsync(); + var templates = new RenameTemplates(Folder: "reorganized/{date}", File: "{n:000}"); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct); + var job = await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, plan, templates), cancellationToken: fx.Ct); + Assert.Equal(JobKind.Move, job.Kind); + var done = await fx.WaitForAsync(job.Id, JobState.Done); + Assert.Equal((1, 1), (done.ProgressDone, done.ProgressTotal)); + Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 3), done.LogTail); + Assert.Equal("reorganized/2026-09-28", (await fx.Db.Sequences.GetAsync(id))!.Folder); + Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG", "originals/003.JPG"], await FilesAsync(fx, id)); + + var back = new RenameTemplates(File: "{date}_{n:0000}"); + var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], back, fx.Ct); + await UploadAsync(fx, 1, firstSeed: 9, firstSecond: 5); + var before = await FilesAsync(fx, id); + var refused = await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Reorganize(fx.Archive, again, back), cancellationToken: fx.Ct)).Id, JobState.Failed); + Assert.Equal(Loc.L("Archive.Error.StalePlan"), refused.Error); + Assert.SequenceEqual(before, await FilesAsync(fx, id)); + Assert.Empty(RenameJournal.ListPending(fx.Paths)); + } + + [Test] + public async Task AHeldPlanWaitsForItsJob() + { + await using var fx = await CreateAsync(context); + var first = await UploadAsync(fx, 2); + var second = await UploadAsync(fx, 2, firstSeed: 20, firstSecond: 3600, key: "upload-2"); + var templates = new RenameTemplates(File: "{n:000}"); + var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [first, second], templates, fx.Ct); + Assert.Count(2, plan.Steps); + var untouched = await FilesAsync(fx, second); + + // The job stops after the first sequence (paused) and holds its plan: an archive open leaves the rest alone. + using var cts = new CancellationTokenSource(); + await Assert.ThrowsAsync(() => fx.Service.Renamer.ApplyAsync(fx.Archive, plan, null, _ => + { + cts.Cancel(); + return ValueTask.CompletedTask; + }, cts.Token)); + Assert.True(MassRenamer.Hold(fx.Archive, plan.Id)); + Assert.Equal(0, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct)); + Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, first)); + Assert.SequenceEqual(untouched, await FilesAsync(fx, second)); + Assert.True(Assert.NotNull(RenameJournal.Read(fx.Paths, plan.Id)).Held); + + // Resumed from its checkpoint, the job completes it; once its journal is gone a run finds the plan complete. + var engine = await fx.StartEngineAsync(); + var request = ArchiveJobs.Reorganize(fx.Archive, plan, templates); + var resumed = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done); + Assert.Contains(Loc.L("Archive.Log.Reorganized", 1, 2), resumed.LogTail); + Assert.SequenceEqual(["originals/001.JPG", "originals/002.JPG"], await FilesAsync(fx, second)); + Assert.Null(RenameJournal.Read(fx.Paths, plan.Id)); + var later = await fx.WaitForAsync((await fx.EnqueueWithCheckpointAsync(engine, request, "plan:" + plan.Id.ToString("N"))).Id, JobState.Done); + Assert.Contains(Loc.L("Archive.Log.ReorganizedEarlier"), later.LogTail); + } +} diff --git a/tests/Chronos.Data.Tests/Repositories/CatalogRepositoryTests.cs b/tests/Chronos.Data.Tests/Repositories/CatalogRepositoryTests.cs index b63f81e4..aae1b752 100644 --- a/tests/Chronos.Data.Tests/Repositories/CatalogRepositoryTests.cs +++ b/tests/Chronos.Data.Tests/Repositories/CatalogRepositoryTests.cs @@ -361,6 +361,43 @@ public abstract class CatalogRepositoryTests(TestContext context) : RepositoryTe Assert.True((await Chronos.Data.Processing.SequenceFrames.ListAsync(db, sequence.Id, Ct)).All(f => (f.Flags, f.PreviewWidth, f.PreviewHeight) == (FrameFlags.None, 4, 3))); } + [Test] + public async Task FramesTakeTheNamesAReorganizeGaveTheirFiles() + { + var db = await OpenChronosAsync(); + var archive = TestData.Archive(); + await db.Archives.UpsertAsync(archive, Ct); + var sequence = TestData.Sequence(archive.Id) with { FramesVersion = 3 }; + var other = TestData.Sequence(archive.Id); + await db.Sequences.UpsertAsync(sequence, Ct); + await db.Sequences.UpsertAsync(other, Ct); + // More frames than one batched PostgreSQL statement holds, and a frame of another sequence named in the same call. + const int count = 1203; + var frames = Enumerable.Range(0, count).Select(i => TestData.Frame(sequence.Id, i)).ToList(); + var foreign = TestData.Frame(other.Id, 0); + await db.Frames.BulkInsertAsync([.. frames, foreign], Ct); + + var renamed = frames.Take(count - 1).Select(f => new FrameFileName(f.Id, $"s/originals/{count - f.Index:00000}.cr3", $"{count - f.Index:00000}.cr3")).ToList(); + Assert.Equal(count - 1, await db.Frames.RenameFilesAsync(sequence.Id, [.. renamed, new FrameFileName(foreign.Id, "x/y.cr3", "y.cr3")], 3, 4, Ct)); + var read = new List(); + for (var last = -1; ;) + { + var page = await db.Frames.ListBySequenceAsync(sequence.Id, last, 1000, Ct); + read.AddRange(page); + if (page.Count < 1000) break; + last = page[^1].Index; + } + Assert.SequenceEqual(frames.Select(f => f.Id), read.Select(f => f.Id)); + Assert.SequenceEqual([.. renamed.Select(r => (r.RelativePath, r.FileName)), (frames[^1].RelativePath, frames[^1].FileName)], + read.Select(f => (f.RelativePath, f.FileName))); + Assert.Equal((foreign.RelativePath, foreign.FileName), (await db.Frames.GetAsync(foreign.Id, Ct)) is { } f2 ? (f2.RelativePath, f2.FileName) : default); + Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion); + + // A row another writer moved past the version the renames started from keeps its own. + await db.Frames.RenameFilesAsync(sequence.Id, [], 3, 9, Ct); + Assert.Equal(4, (await db.Sequences.GetAsync(sequence.Id, Ct))!.FramesVersion); + } + [Test] public async Task RendersKeepTheSequenceCountInStep() { diff --git a/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs new file mode 100644 index 00000000..c72330ad --- /dev/null +++ b/tests/Chronos.Server.Tests/Api/ReorganizeTests.cs @@ -0,0 +1,187 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.Extensions.DependencyInjection; +using Chronos.Core.Codecs.Jpeg; +using Chronos.Core.Model; +using Chronos.Protocol; +using Chronos.Server.Events; +using Chronos.Server.Storage; +using Chronos.Testing; + +namespace Chronos.Server.Tests.Api; + +/// +/// Reorganize on the server (owner review 2, R7): POST /api/v1/archive/reorganize, its dry run, the move job that +/// applies the confirmed plan, and what the request may not do, against the real archive engine. +/// +[Category("server")] +public sealed class ReorganizeTests(TestContext context) +{ + private const string Url = "/api/v1/archive/reorganize"; + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30)); + + [Test] + public async Task AReorganizeIsDryRunThenAppliedByAJob() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + Guid id = default; + for (var i = 0; i < 3; i++) id = (await Uploads.UploadAsync(editor, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: "roof")).SequenceId; + await UntilIdleAsync(server); + var before = await server.Database.Frames.ListBySequenceAsync(id); + + var request = new ReorganizeRequest([id], false, "reorganized/{title}", "{title}_{n:000}", "Roof", DryRun: true); + ReorganizePlanDto plan; + using (var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest)) + plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto); + Assert.Equal((1, 3, 0), (plan.Sequences, plan.Files, plan.Kept)); + var step = plan.Steps.Single(); + Assert.Equal((id, "reorganized/Roof", "Roof", 3), (step.SequenceId, step.ToFolder, step.ToTitle, step.FileChanges)); + Assert.SequenceEqual(["originals/Roof_001.JPG", "originals/Roof_002.JPG", "originals/Roof_003.JPG"], step.FileSamples.Select(f => f.To)); + Assert.Equal(64, plan.Fingerprint.Length); + Assert.SequenceEqual(before.Select(f => f.RelativePath), (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.RelativePath)); + + using (var missing = await admin.PostAsJsonAsync(Url, request with { DryRun = false }, ProtocolJson.Default.ReorganizeRequest)) + Assert.Equal("fingerprint", (await missing.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details); + using (var wrong = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = "0123" }, ProtocolJson.Default.ReorganizeRequest)) + Assert.Equal(plan.Fingerprint, (await wrong.ExpectErrorAsync(HttpStatusCode.Conflict, "plan_changed")).Details); + + using var events = server.Services.GetRequiredService().Subscribe(); + JobDto job; + using (var applied = await admin.PostAsJsonAsync(Url, request with { DryRun = false, Fingerprint = plan.Fingerprint }, ProtocolJson.Default.ReorganizeRequest)) + { + await applied.ExpectAsync(HttpStatusCode.Accepted); + job = await applied.ReadAsync(ProtocolJson.Default.JobDto); + } + Assert.Equal("move", job.Kind); + await UntilJobAsync(admin, job.Id, "done"); + + var sequence = (await server.Database.Sequences.GetAsync(id))!; + Assert.Equal(("reorganized/Roof", "Roof"), (sequence.Folder, sequence.Title)); + var after = await server.Database.Frames.ListBySequenceAsync(id); + Assert.SequenceEqual(before.Select(f => f.Id), after.Select(f => f.Id)); + Assert.SequenceEqual(["reorganized/Roof/originals/Roof_001.JPG", "reorganized/Roof/originals/Roof_002.JPG", "reorganized/Roof/originals/Roof_003.JPG"], + after.Select(f => f.RelativePath)); + foreach (var (was, now) in before.Zip(after)) + Assert.Equal(was.Sha256, Uploads.Sha(File.ReadAllBytes(Path.Combine(server.Options.ArchivePath, now.RelativePath)))); + Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "archive_reorganized", 10, null)).Items); + + var until = DateTime.UtcNow + Wait; + while (true) + { + using var timeout = new CancellationTokenSource(until - DateTime.UtcNow); + var e = await events.Reader.ReadAsync(timeout.Token); + if (e is SequenceChangedEvent { Change: "reorganized" } changed && changed.SequenceId == id) + { + Assert.Equal(sequence.FramesVersion, changed.FramesVersion); + break; + } + } + } + + [Test] + public async Task AReorganizeAsksForTheArchiveAndAValidRequest() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var (editor, _, _) = await server.UserAsync("alberto", "editor"); + var admin = await server.AdminAsync(); + var a = (await Uploads.UploadAsync(editor, Photo(1), "a.jpg", sessionKey: "a")).SequenceId; + var b = (await Uploads.UploadAsync(editor, Photo(2), "b.jpg", sessionKey: "b")).SequenceId; + await UntilIdleAsync(server); + var valid = new ReorganizeRequest([a], false, null, "{n:000}", null, DryRun: true); + + using (var forbidden = await editor.PostAsJsonAsync(Url, valid, ProtocolJson.Default.ReorganizeRequest)) + await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden"); + foreach (var (bad, details) in new[] + { + (valid with { All = true }, "sequenceIds"), + (valid with { SequenceIds = null }, "sequenceIds"), + (valid with { SequenceIds = [] }, "sequenceIds"), + (valid with { FileTemplate = null }, "templates"), + }) + { + using var response = await admin.PostAsJsonAsync(Url, bad, ProtocolJson.Default.ReorganizeRequest); + Assert.Equal(details, (await response.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details); + } + using (var template = await admin.PostAsJsonAsync(Url, valid with { FileTemplate = "{nope}" }, ProtocolJson.Default.ReorganizeRequest)) + Assert.Equal("fileTemplate", (await template.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details); + using (var blank = await admin.PostAsJsonAsync(Url, valid with { FolderTemplate = " " }, ProtocolJson.Default.ReorganizeRequest)) + Assert.Equal("folderTemplate", (await blank.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_template")).Details); + using (var unknown = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = [Guid.NewGuid()] }, ProtocolJson.Default.ReorganizeRequest)) + await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found"); + + // One sequence's new folder inside the other's: refused, nothing planned. + var host = (await server.Database.Sequences.GetAsync(a))!.Folder; + using (var nested = await admin.PostAsJsonAsync(Url, new ReorganizeRequest([b], false, host + "/inside", null, null, DryRun: true), + ProtocolJson.Default.ReorganizeRequest)) + Assert.Equal(host + "/inside", (await nested.ExpectErrorAsync(HttpStatusCode.Conflict, "nested_target")).Details); + + using (var all = await admin.PostAsJsonAsync(Url, valid with { SequenceIds = null, All = true }, ProtocolJson.Default.ReorganizeRequest)) + { + var plan = await all.ReadAsync(ProtocolJson.Default.ReorganizePlanDto); + Assert.Equal((2, 2), (plan.Sequences, plan.Files)); + Assert.SequenceEqual(new[] { a, b }.Order(), plan.Steps.Select(s => s.SequenceId).Order()); + } + Assert.Empty((await server.Database.Jobs.ListAsync(JobState.Queued, JobKind.Move)).Items); + } + + [Test] + public async Task PhotosThatKeepTheirNamesAreToldWhy() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var admin = await server.AdminAsync(); + // Photos copied into the archive by hand and found by a scan stay where they are. + var folder = Path.Combine(server.Options.ArchivePath, "trips"); + Directory.CreateDirectory(folder); + for (var i = 0; i < 2; i++) await File.WriteAllBytesAsync(Path.Combine(folder, $"IMG_{i:0000}.JPG"), Photo(i)); + using (var scan = await admin.PostAsync("/api/v1/archive/scan", null)) await scan.ExpectAsync(HttpStatusCode.Accepted); + await UntilIdleAsync(server); + var id = (await server.Database.Sequences.ListLocationsAsync((await server.Database.Archives.ListAsync()).Single().Id)).Single().Id; + + var request = new ReorganizeRequest([id], false, null, "{n:000}", null, DryRun: true); + admin.DefaultRequestHeaders.AcceptLanguage.ParseAdd("it"); + using var dry = await admin.PostAsJsonAsync(Url, request, ProtocolJson.Default.ReorganizeRequest); + var plan = await dry.ReadAsync(ProtocolJson.Default.ReorganizePlanDto); + Assert.Equal((0, 0, 2), (plan.Sequences, plan.Files, plan.Kept)); + var blocked = plan.Steps.Single().Blocked.Single(); + Assert.Equal(("in_place", 2), (blocked.Reason, blocked.Photos)); + Assert.Equal(Chronos.Core.Localization.Loc.Get("Archive.Reorganize.Blocked.InPlace", System.Globalization.CultureInfo.GetCultureInfo("it")), blocked.Message); + } + + private static async Task UntilJobAsync(HttpClient client, Guid id, string state) + { + var until = DateTime.UtcNow + Wait; + while (true) + { + using var response = await client.GetAsync($"/api/v1/jobs/{id}"); + var job = await response.ReadAsync(ProtocolJson.Default.JobDto); + if (job.State == state) 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 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 }); + } +}