feat: owner review 2 phase 4b: mass conversion after import #13
No files matched your search
@@ -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
|
||||
|
||||
+1
-1
@@ -138,7 +138,7 @@
|
||||
<data name="Admin.Job.Kind.Import" xml:space="preserve"><value>Import</value></data>
|
||||
<data name="Admin.Job.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
|
||||
<data name="Admin.Job.Kind.Maintenance" xml:space="preserve"><value>Maintenance</value></data>
|
||||
<data name="Admin.Job.Kind.Move" xml:space="preserve"><value>Move</value></data>
|
||||
<data name="Admin.Job.Kind.Move" xml:space="preserve"><value>Reorganize</value></data>
|
||||
<data name="Admin.Job.Kind.Orphans" xml:space="preserve"><value>Orphans</value></data>
|
||||
<data name="Admin.Job.Kind.Proxies" xml:space="preserve"><value>Proxies</value></data>
|
||||
<data name="Admin.Job.Kind.Rebuild" xml:space="preserve"><value>Rebuild</value></data>
|
||||
|
||||
@@ -86,6 +86,8 @@
|
||||
<data name="Archive.Error.NewerFormat" xml:space="preserve"><value>{0} was written by a newer Chronos (format {1}).</value><comment>long: error sentence</comment></data>
|
||||
<data name="Archive.Error.Offline" xml:space="preserve"><value>The archive {0} is offline.</value><comment>long: error sentence</comment></data>
|
||||
<data name="Archive.Error.ReadOnly" xml:space="preserve"><value>The archive {0} is read-only.</value><comment>long: error sentence</comment></data>
|
||||
<data name="Archive.Error.ReorganizeKept.one" xml:space="preserve"><value>{0:N0} sequence was not reorganized as planned: it changed after the plan.</value><comment>long: error sentence of a Reorganize job</comment></data>
|
||||
<data name="Archive.Error.ReorganizeKept.other" xml:space="preserve"><value>{0:N0} sequences were not reorganized as planned: they changed after the plan.</value><comment>long: error sentence of a Reorganize job</comment></data>
|
||||
<data name="Archive.Error.SourceChanged" xml:space="preserve"><value>{0} changed after the plan was made.</value><comment>long: error sentence</comment></data>
|
||||
<data name="Archive.Error.SourceGone" xml:space="preserve"><value>The card or folder {0} is no longer available.</value><comment>long: error sentence</comment></data>
|
||||
<data name="Archive.Error.StalePlan" xml:space="preserve"><value>The archive changed after this plan was made.</value><comment>long: error sentence</comment></data>
|
||||
@@ -151,6 +153,10 @@
|
||||
<data name="Archive.Log.Orphans" xml:space="preserve"><value>Unindexed photos: {0}, missing photos: {1}</value><comment>long: job log line</comment></data>
|
||||
<data name="Archive.Log.ProxiesDone" xml:space="preserve"><value>{0}: made {1}, reused {2}, unreadable {3}, waiting {4}</value><comment>long: job log line; {4} frames whose proxy this host waits for from a client or render node</comment></data>
|
||||
<data name="Archive.Log.ProxiesSent" xml:space="preserve"><value>Proxies for the server: {0} sent, {1} not sent</value><comment>long: job log line; {0} proxies sent; {1} proxies this PC could not make or the server refused</comment></data>
|
||||
<data name="Archive.Log.ReorganizeDropped" xml:space="preserve"><value>Left as it was, changed after the plan: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
|
||||
<data name="Archive.Log.ReorganizeFilesKept" xml:space="preserve"><value>File names kept, photos changed after the plan: {0}</value><comment>long: job log line; {0} sequence title or folder</comment></data>
|
||||
<data name="Archive.Log.Reorganized" xml:space="preserve"><value>Sequences changed: {0}, files renamed: {1}</value><comment>long: job log line of a Reorganize; {0} sequences, {1} photos</comment></data>
|
||||
<data name="Archive.Log.ReorganizedEarlier" xml:space="preserve"><value>The reorganization was completed when the archive was opened</value><comment>long: job log line</comment></data>
|
||||
<data name="Archive.Log.ReportOnly" xml:space="preserve"><value>Report only: nothing was changed.</value><comment>long: job log line</comment></data>
|
||||
<data name="Archive.Log.ScanDone" xml:space="preserve"><value>Folders: {0}, indexed: {1}, adopted: {2}, removed: {3}</value><comment>long: job log line</comment></data>
|
||||
<data name="Archive.Log.SequenceMissing" xml:space="preserve"><value>Sequence not found: {0}</value><comment>long: job log line</comment></data>
|
||||
@@ -214,6 +220,10 @@
|
||||
<data name="Archive.Rename.Summary.one" xml:space="preserve"><value>{0:N0} of {1:N0} changes</value></data>
|
||||
<data name="Archive.Rename.Summary.other" xml:space="preserve"><value>{0:N0} of {1:N0} change</value></data>
|
||||
<data name="Archive.Rename.Template" xml:space="preserve"><value>Template</value></data>
|
||||
<data name="Archive.Reorganize.Blocked.InPlace" xml:space="preserve"><value>Photos kept in place outside originals keep their names.</value><comment>long: why photos keep their names in a Reorganize dry run</comment></data>
|
||||
<data name="Archive.Reorganize.Blocked.Missing" xml:space="preserve"><value>Missing photos keep their names.</value><comment>long: why photos keep their names in a Reorganize dry run</comment></data>
|
||||
<data name="Archive.Reorganize.Blocked.Unhashed" xml:space="preserve"><value>Photos never verified keep their names; verify the sequence first.</value><comment>long: why photos keep their names in a Reorganize dry run</comment></data>
|
||||
<data name="Archive.Reorganize.Blocked.Unreadable" xml:space="preserve"><value>The sequence file cannot be read; its photos keep their names.</value><comment>long: why photos keep their names in a Reorganize dry run</comment></data>
|
||||
<data name="Archive.Retag.Add" xml:space="preserve"><value>Add tags</value></data>
|
||||
<data name="Archive.Retag.Apply" xml:space="preserve"><value>Apply</value></data>
|
||||
<data name="Archive.Retag.Heading.one" xml:space="preserve"><value>Tags of {0:N0} sequence</value></data>
|
||||
|
||||
+1
-1
@@ -76,7 +76,7 @@
|
||||
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Import</value></data>
|
||||
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Light analysis</value></data>
|
||||
<data name="Jobs.Kind.Maintenance" xml:space="preserve"><value>Maintenance</value></data>
|
||||
<data name="Jobs.Kind.Move" xml:space="preserve"><value>Move archive</value></data>
|
||||
<data name="Jobs.Kind.Move" xml:space="preserve"><value>Reorganize</value></data>
|
||||
<data name="Jobs.Kind.Orphans" xml:space="preserve"><value>Orphans</value></data>
|
||||
<data name="Jobs.Kind.Proxies" xml:space="preserve"><value>Proxies</value></data>
|
||||
<data name="Jobs.Kind.Rebuild" xml:space="preserve"><value>Rebuild index</value></data>
|
||||
|
||||
@@ -70,11 +70,13 @@
|
||||
<data name="Server.Error.JobUnavailable" xml:space="preserve"><value>This server cannot run that kind of job.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.LastAdmin" xml:space="preserve"><value>The last administrator cannot be removed or disabled.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.MethodNotAllowed" xml:space="preserve"><value>This method is not allowed here.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NestedTarget" xml:space="preserve"><value>A new folder would lie inside the folder of another sequence.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.NotChronos" xml:space="preserve"><value>That address is not a Chronos Server.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>The photo was deleted from the sequence while it was being uploaded, so it was not added.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>{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.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PlanChanged" xml:space="preserve"><value>The archive changed after the dry run; review the plan again.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>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.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxiesDisabled" xml:space="preserve"><value>This archive makes no proxies.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.ProxyMismatch" xml:space="preserve"><value>The proxy was made from another photo.</value><comment>long</comment></data>
|
||||
|
||||
@@ -138,7 +138,7 @@
|
||||
<data name="Admin.Job.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
|
||||
<data name="Admin.Job.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
|
||||
<data name="Admin.Job.Kind.Maintenance" xml:space="preserve"><value>Manutenzione</value></data>
|
||||
<data name="Admin.Job.Kind.Move" xml:space="preserve"><value>Spostamento</value></data>
|
||||
<data name="Admin.Job.Kind.Move" xml:space="preserve"><value>Riorganizzazione</value></data>
|
||||
<data name="Admin.Job.Kind.Orphans" xml:space="preserve"><value>Orfani</value></data>
|
||||
<data name="Admin.Job.Kind.Proxies" xml:space="preserve"><value>Proxy</value></data>
|
||||
<data name="Admin.Job.Kind.Rebuild" xml:space="preserve"><value>Ricostruzione</value></data>
|
||||
|
||||
@@ -81,6 +81,8 @@
|
||||
<data name="Archive.Error.NewerFormat" xml:space="preserve"><value>{0} è stato scritto da un Chronos più recente (formato {1}).</value></data>
|
||||
<data name="Archive.Error.Offline" xml:space="preserve"><value>L'archivio {0} non è raggiungibile.</value></data>
|
||||
<data name="Archive.Error.ReadOnly" xml:space="preserve"><value>L'archivio {0} è di sola lettura.</value></data>
|
||||
<data name="Archive.Error.ReorganizeKept.one" xml:space="preserve"><value>{0:N0} sequenza non è stata riorganizzata come previsto: è cambiata dopo il piano.</value></data>
|
||||
<data name="Archive.Error.ReorganizeKept.other" xml:space="preserve"><value>{0:N0} sequenze non sono state riorganizzate come previsto: sono cambiate dopo il piano.</value></data>
|
||||
<data name="Archive.Error.SourceChanged" xml:space="preserve"><value>{0} è cambiato dopo la creazione del piano.</value></data>
|
||||
<data name="Archive.Error.SourceGone" xml:space="preserve"><value>La scheda o cartella {0} non è più disponibile.</value></data>
|
||||
<data name="Archive.Error.StalePlan" xml:space="preserve"><value>L'archivio è cambiato dopo la creazione del piano.</value></data>
|
||||
@@ -146,6 +148,10 @@
|
||||
<data name="Archive.Log.Orphans" xml:space="preserve"><value>Foto non indicizzate: {0}, foto mancanti: {1}</value></data>
|
||||
<data name="Archive.Log.ProxiesDone" xml:space="preserve"><value>{0}: create {1}, riusate {2}, illeggibili {3}, in attesa {4}</value></data>
|
||||
<data name="Archive.Log.ProxiesSent" xml:space="preserve"><value>Proxy per il server: {0} inviati, {1} non inviati</value></data>
|
||||
<data name="Archive.Log.ReorganizeDropped" xml:space="preserve"><value>Lasciata com'era, cambiata dopo il piano: {0}</value></data>
|
||||
<data name="Archive.Log.ReorganizeFilesKept" xml:space="preserve"><value>Nomi dei file mantenuti, foto cambiate dopo il piano: {0}</value></data>
|
||||
<data name="Archive.Log.Reorganized" xml:space="preserve"><value>Sequenze cambiate: {0}, file rinominati: {1}</value></data>
|
||||
<data name="Archive.Log.ReorganizedEarlier" xml:space="preserve"><value>La riorganizzazione è stata completata all'apertura dell'archivio</value></data>
|
||||
<data name="Archive.Log.ReportOnly" xml:space="preserve"><value>Solo resoconto: nulla è stato modificato.</value></data>
|
||||
<data name="Archive.Log.ScanDone" xml:space="preserve"><value>Cartelle: {0}, indicizzate: {1}, adottate: {2}, rimosse: {3}</value></data>
|
||||
<data name="Archive.Log.SequenceMissing" xml:space="preserve"><value>Sequenza non trovata: {0}</value></data>
|
||||
@@ -208,6 +214,10 @@
|
||||
<data name="Archive.Rename.Summary.one" xml:space="preserve"><value>{0:N0} di {1:N0} cambia</value></data>
|
||||
<data name="Archive.Rename.Summary.other" xml:space="preserve"><value>{0:N0} di {1:N0} cambiano</value></data>
|
||||
<data name="Archive.Rename.Template" xml:space="preserve"><value>Modello</value></data>
|
||||
<data name="Archive.Reorganize.Blocked.InPlace" xml:space="preserve"><value>Le foto tenute sul posto fuori da originals mantengono il loro nome.</value></data>
|
||||
<data name="Archive.Reorganize.Blocked.Missing" xml:space="preserve"><value>Le foto mancanti mantengono il loro nome.</value></data>
|
||||
<data name="Archive.Reorganize.Blocked.Unhashed" xml:space="preserve"><value>Le foto mai verificate mantengono il loro nome; verifica prima la sequenza.</value></data>
|
||||
<data name="Archive.Reorganize.Blocked.Unreadable" xml:space="preserve"><value>Il file della sequenza non è leggibile; le sue foto mantengono il loro nome.</value></data>
|
||||
<data name="Archive.Retag.Add" xml:space="preserve"><value>Aggiungi tag</value></data>
|
||||
<data name="Archive.Retag.Apply" xml:space="preserve"><value>Applica</value></data>
|
||||
<data name="Archive.Retag.Heading.one" xml:space="preserve"><value>Tag di {0:N0} sequenza</value></data>
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
<data name="Jobs.Kind.Import" xml:space="preserve"><value>Importazione</value></data>
|
||||
<data name="Jobs.Kind.LightAnalyse" xml:space="preserve"><value>Analisi rapida</value></data>
|
||||
<data name="Jobs.Kind.Maintenance" xml:space="preserve"><value>Manutenzione</value></data>
|
||||
<data name="Jobs.Kind.Move" xml:space="preserve"><value>Spostamento archivio</value></data>
|
||||
<data name="Jobs.Kind.Move" xml:space="preserve"><value>Riorganizzazione</value></data>
|
||||
<data name="Jobs.Kind.Orphans" xml:space="preserve"><value>File orfani</value></data>
|
||||
<data name="Jobs.Kind.Proxies" xml:space="preserve"><value>Proxy</value></data>
|
||||
<data name="Jobs.Kind.Rebuild" xml:space="preserve"><value>Ricostruzione indice</value></data>
|
||||
|
||||
@@ -68,11 +68,13 @@
|
||||
<data name="Server.Error.JobUnavailable" xml:space="preserve"><value>Questo server non può eseguire quel tipo di job.</value></data>
|
||||
<data name="Server.Error.LastAdmin" xml:space="preserve"><value>L'ultimo amministratore non può essere rimosso o disattivato.</value></data>
|
||||
<data name="Server.Error.MethodNotAllowed" xml:space="preserve"><value>Metodo non consentito qui.</value></data>
|
||||
<data name="Server.Error.NestedTarget" xml:space="preserve"><value>Una nuova cartella finirebbe dentro la cartella di un'altra sequenza.</value></data>
|
||||
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
|
||||
<data name="Server.Error.NotChronos" xml:space="preserve"><value>Questo indirizzo non è un Chronos Server.</value></data>
|
||||
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
|
||||
<data name="Server.Error.PhotoRemoved" xml:space="preserve"><value>La foto è stata eliminata dalla sequenza mentre veniva caricata, quindi non è stata aggiunta.</value><comment>long</comment></data>
|
||||
<data name="Server.Error.PhotoUnreadable" xml:space="preserve"><value>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.</value></data>
|
||||
<data name="Server.Error.PlanChanged" xml:space="preserve"><value>L'archivio è cambiato dopo la simulazione; rivedi di nuovo il piano.</value></data>
|
||||
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a CHRONOS_TRUSTED_PROXIES.</value></data>
|
||||
<data name="Server.Error.ProxiesDisabled" xml:space="preserve"><value>Questo archivio non crea proxy.</value></data>
|
||||
<data name="Server.Error.ProxyMismatch" xml:space="preserve"><value>Il proxy è stato creato da un'altra foto.</value></data>
|
||||
|
||||
@@ -41,8 +41,11 @@ public static class MassRename
|
||||
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
|
||||
];
|
||||
|
||||
/// <summary>"12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted.</summary>
|
||||
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize);
|
||||
/// <summary>
|
||||
/// "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).
|
||||
/// </summary>
|
||||
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => s.Changes && !s.Carried), setSize);
|
||||
}
|
||||
|
||||
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Indented output for the small files people may open (<c>archive.json</c>, rename journals).</summary>
|
||||
|
||||
@@ -36,6 +36,9 @@ public static class ArchiveLayout
|
||||
/// <summary>Moves of photos restored from the trash that were started but not yet settled in <see cref="SequenceManifestFile"/> and the trash record.</summary>
|
||||
public const string RestoreJournalFile = "restore.pending.json";
|
||||
|
||||
/// <summary>File renames of a Reorganize that were started but not yet recorded in <see cref="SequenceManifestFile"/> and the index.</summary>
|
||||
public const string FileRenameJournalFile = "rename-files.json";
|
||||
|
||||
/// <summary>Folder names inside a sequence folder that never hold a sequence of their own.</summary>
|
||||
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));
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.IO;
|
||||
|
||||
namespace Chronos.Core.Archiving;
|
||||
|
||||
/// <summary>One file of <see cref="FileRenameJournal"/>: its name, the temporary name it passes through and its new name, relative to the sequence folder.</summary>
|
||||
public sealed record FileRenameEntry(Guid FrameId, string From, string Temp, string To, bool Companion = false);
|
||||
|
||||
/// <summary>
|
||||
/// Write-ahead record of the file renames of one sequence (<c>.chronos/rename-files.json</c>, 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 (<see cref="Phase"/> 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 <see cref="Recover"/> (which a writer runs under the sequence's lease, <c>SequenceWriter.ReadLocked</c>):
|
||||
/// 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 (<see cref="Run"/>).
|
||||
/// </summary>
|
||||
/// <param name="FramesVersion">The sidecar's frames version before the renames; the sidecar written after them has the next.</param>
|
||||
/// <param name="Phase">1 while files go to their temporary names, 2 while they go to their new names.</param>
|
||||
public sealed record FileRenameJournal(int FramesVersion, int Phase, IReadOnlyList<FileRenameEntry> Files)
|
||||
{
|
||||
private const string TempPrefix = ".chronos-rename-";
|
||||
|
||||
/// <summary>
|
||||
/// The journal of <paramref name="moves"/> (<see cref="FileRenames.Plan"/>) at <paramref name="framesVersion"/>, each file
|
||||
/// with a temporary name beside it: hidden, of no photo format, unique to this rename (<paramref name="token"/>).
|
||||
/// </summary>
|
||||
public static FileRenameJournal Create(int framesVersion, IReadOnlyList<FileRename> moves, string token)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(moves);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(token);
|
||||
var files = new List<FileRenameEntry>(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));
|
||||
}
|
||||
|
||||
/// <summary>The journal of the sequence; null when there is none, or it was torn while first written (nothing had moved).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the files of a journal just written (<see cref="Write"/>): 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 <see cref="Recover"/> completes the
|
||||
/// renames later. The caller holds the sequence's lease.
|
||||
/// </summary>
|
||||
/// <exception cref="IOException">A file could not be moved (open elsewhere, or a name taken meanwhile); nothing changed.</exception>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completes a rename a crash interrupted (the caller holds the sequence's lease): the files go on to their new names,
|
||||
/// and <paramref name="manifest"/> names them (<see cref="Applied"/>), unless it does already. Returns
|
||||
/// the sidecar to write, or null when it is right as it is; the journal is left in place, <see cref="Delete"/> 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).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="manifest"/> naming the new files of <paramref name="journal"/> (frame order unchanged) one frames
|
||||
/// version further; null when no frame names an old file any more (the sidecar was written already).
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the files back after a failure in <paramref name="phase"/> once <paramref name="done"/> 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using Chronos.Core.Naming;
|
||||
|
||||
namespace Chronos.Core.Archiving;
|
||||
|
||||
/// <summary>Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7); nothing of them is touched.</summary>
|
||||
public enum RenameBlock
|
||||
{
|
||||
/// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary>
|
||||
InPlace,
|
||||
|
||||
/// <summary>Photos whose SHA-256 is not known yet (never verified): a verify hashes them first.</summary>
|
||||
Unhashed,
|
||||
|
||||
/// <summary>Photos whose file is not there.</summary>
|
||||
Missing,
|
||||
|
||||
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// <summary>Frames of a sequence that keep their names, and why.</summary>
|
||||
public sealed record RenameBlocked(RenameBlock Reason, int Frames);
|
||||
|
||||
/// <summary>
|
||||
/// One file of a Reorganize: a frame's photo, or a companion that follows it (<see cref="Companion"/>), from its name to its
|
||||
/// new one; both relative to the sequence folder, forward slashes.
|
||||
/// </summary>
|
||||
public sealed record FileRename(Guid FrameId, string From, string To, bool Companion = false);
|
||||
|
||||
/// <summary>
|
||||
/// The file renames of one sequence: every move, companions included, in frame order; how many frames get a new name; the
|
||||
/// first of them (<see cref="FileRenames.SampleCount"/>) as samples; and the frames that keep their names.
|
||||
/// </summary>
|
||||
public sealed record FileRenamePlan(IReadOnlyList<FileRename> Moves, int Frames, IReadOnlyList<FileRename> Samples, IReadOnlyList<RenameBlocked> Blocked)
|
||||
{
|
||||
public static FileRenamePlan None { get; } = new([], 0, [], []);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="FrameNaming"/>); a name already given, or held
|
||||
/// by a file that stays (a frame left alone, a file no frame lists), gets <c>_2</c>, <c>_3</c>… as filing does, so the same
|
||||
/// frames, template and folder always give the same names. Only photos under <c>originals/</c> whose SHA-256 is known and
|
||||
/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it
|
||||
/// (<see cref="FrameCompanions"/>; one named by a stem two frames share follows the first). The sidecar's frame order never
|
||||
/// changes.
|
||||
/// </summary>
|
||||
public static class FileRenames
|
||||
{
|
||||
/// <summary>Renamed frames a plan shows as samples.</summary>
|
||||
public const int SampleCount = 3;
|
||||
|
||||
private const string Originals = ArchiveLayout.OriginalsFolder + "/";
|
||||
|
||||
/// <param name="title">The sequence title the names use (<c>{title}</c>): the new one when the same Reorganize retitles it.</param>
|
||||
/// <param name="present">Every file in the folders of the sequence's frames, relative to the sequence folder (<see cref="ListPresent"/>).</param>
|
||||
public static FileRenamePlan Plan(SequenceManifest manifest, string? title, PathTemplate template, IReadOnlyCollection<string> present)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(present);
|
||||
var onDisk = new HashSet<string>(present, StringComparer.OrdinalIgnoreCase);
|
||||
int inPlace = 0, unhashed = 0, missing = 0;
|
||||
var eligible = new List<SidecarFrame>();
|
||||
// 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<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var companions = new Dictionary<Guid, List<string>>();
|
||||
// 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<string>(eligible.Select(f => f.File).Concat(companions.Values.SelectMany(c => c)), StringComparer.OrdinalIgnoreCase);
|
||||
var taken = new HashSet<string>(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<FileRename>();
|
||||
var samples = new List<FileRename>();
|
||||
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<RenameBlocked>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every file in the folders that hold the sequence's frames (<c>originals/</c> as a rule), relative to the sequence
|
||||
/// folder; hidden files included, so no name a file holds is ever given.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> ListPresent(SequencePaths sequence, SequenceManifest manifest)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sequence);
|
||||
ArgumentNullException.ThrowIfNull(manifest);
|
||||
var files = new List<string>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A file's path without its extension (<c>originals/2026-09-28_0001</c>).</summary>
|
||||
private static string Stem(string file) => file[..^Path.GetExtension(file).Length];
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
namespace Chronos.Core.Archiving;
|
||||
|
||||
/// <summary>
|
||||
/// The XMP companions of a photo (<c>IMG_0001.xmp</c> or <c>IMG_0001.CR2.xmp</c> beside <c>IMG_0001.CR2</c>): 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 (<c>IMG_0001.XMP</c> too), hidden files included.
|
||||
/// </summary>
|
||||
public static class FrameCompanions
|
||||
{
|
||||
/// <summary>The extension of a companion.</summary>
|
||||
public const string Extension = ".xmp";
|
||||
|
||||
/// <summary>Listing of a photo folder: case-insensitive on every system, nothing skipped.</summary>
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
|
||||
/// <summary>The companions beside <paramref name="file"/> (relative to the sequence folder), relative to the sequence folder.</summary>
|
||||
public static IEnumerable<string> Of(SequencePaths folder, string file) => new Index(folder).Of(file);
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="companion"/> is a companion of <paramref name="file"/> (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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every file in <paramref name="directory"/> (absolute), by name, hidden ones included: what <see cref="Names"/> is
|
||||
/// asked about, and every name a file holds there.
|
||||
/// </summary>
|
||||
public static IEnumerable<string> List(string directory) =>
|
||||
Directory.Exists(directory) ? Directory.EnumerateFiles(directory, "*", Listing).Select(p => Path.GetFileName(p)) : [];
|
||||
|
||||
/// <summary>The folder part of a sequence-relative path with its trailing '/', or empty.</summary>
|
||||
private static string Prefix(string file) => file.Contains('/') ? file[..(file.LastIndexOf('/') + 1)] : string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Names"/>.
|
||||
/// </summary>
|
||||
public sealed class Index(SequencePaths folder)
|
||||
{
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The companions beside <paramref name="file"/> (relative to the sequence folder), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>What the planner needs to know about a sequence to rename it.</summary>
|
||||
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)
|
||||
{
|
||||
/// <summary>The sidecar and the files beside its frames, which a file template renames; null when they cannot be read.</summary>
|
||||
public SequenceFiles? Files { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>One sequence's change: its folder, its title, or both.</summary>
|
||||
/// <summary>A sequence's sidecar as read for a plan, and every file in the folders of its frames (<see cref="FileRenames.ListPresent"/>).</summary>
|
||||
public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection<string> Present);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="Blocked"/>).
|
||||
/// </summary>
|
||||
/// <param name="Carried">The folder moves only because a folder it is inside moves (a sequence nested in another).</param>
|
||||
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);
|
||||
|
||||
/// <summary>Whether applying the step changes anything: the folder, the title or file names.</summary>
|
||||
public bool Changes => MovesFolder || Retitles || FileChanges > 0;
|
||||
|
||||
/// <summary>The sidecar's frames version the file names were planned at; 0 when no file gets a new name.</summary>
|
||||
public int FramesVersion { get; init; }
|
||||
|
||||
/// <summary>Frames whose file gets a new name (their companions follow them).</summary>
|
||||
public int FileChanges { get; init; }
|
||||
|
||||
/// <summary>The first renamed frames (<see cref="FileRenames.SampleCount"/>), old and new name relative to the sequence folder.</summary>
|
||||
public IReadOnlyList<FileRename> FileSamples { get; init; } = [];
|
||||
|
||||
/// <summary>Frames that keep their file names, and why.</summary>
|
||||
public IReadOnlyList<RenameBlocked> Blocked { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The templates of a Reorganize (owner review 2, R7): the folder (<c>{title}</c> = the new title), the file names and the
|
||||
/// title (<c>{title}</c> = the current title); null leaves that part as it is.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// The first template that cannot be used, by its API name (<c>folderTemplate</c>, <c>fileTemplate</c>,
|
||||
/// <c>titleTemplate</c>): blank, not valid as the archive settings' templates (<see cref="PathTemplate.IsValid"/>), or
|
||||
/// with a format a sample cannot be written with (<c>{date:%}</c>); null when every one given can.
|
||||
/// </summary>
|
||||
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<PathTemplate, string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
|
||||
@@ -25,10 +107,36 @@ public sealed class NestedRenameException(string target, string folder)
|
||||
}
|
||||
|
||||
/// <summary>The exact changes a mass rename will make (its dry run); applying it makes exactly these.</summary>
|
||||
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps);
|
||||
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps)
|
||||
{
|
||||
/// <summary>The file template the steps' file names come from; null when files keep their names.</summary>
|
||||
public string? FileTemplate { get; init; }
|
||||
|
||||
/// <summary>The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)").</summary>
|
||||
public IReadOnlyList<Guid> Subjects { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7).</summary>
|
||||
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed)
|
||||
/// <param name="Held">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.</param>
|
||||
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> 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<Guid> Complete
|
||||
AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal));
|
||||
}
|
||||
|
||||
/// <summary>Journals left by interrupted renames.</summary>
|
||||
/// <summary>Journals left by interrupted renames, held ones included.</summary>
|
||||
public static IReadOnlyList<RenameJournal> ListPending(ArchivePaths archive)
|
||||
{
|
||||
if (!Directory.Exists(archive.JournalDirectory)) return [];
|
||||
@@ -50,28 +158,40 @@ public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Complete
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The journal of the plan <paramref name="planId"/>; null when there is none (the plan completed, or never started).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Builds rename plans from folder/title templates (BRIEF §7.1, §12.5).</summary>
|
||||
/// <summary>Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7).</summary>
|
||||
public static class RenamePlanner
|
||||
{
|
||||
/// <summary>
|
||||
/// Expands <paramref name="titleTemplate"/> (where <c>{title}</c> is the current title) and then
|
||||
/// <paramref name="folderTemplate"/> (where <c>{title}</c> 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 <see cref="RenameStep.Carried"/> step after every move, so the index
|
||||
/// follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first.
|
||||
/// With <paramref name="fileTemplate"/> every subject's frames get their names from it as filing names them
|
||||
/// (<see cref="FileRenames.Plan"/>, 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
|
||||
/// (<see cref="RenameSubject.Files"/> 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 <see cref="RenameStep.Carried"/> step after every move, so the index follows its files; a
|
||||
/// selected sequence inside a moving folder that moves elsewhere leaves first.
|
||||
/// </summary>
|
||||
/// <param name="occupied">Every sequence folder of the archive (renamed or not).</param>
|
||||
/// <param name="nested">The archive's other sequences inside a subject's folder, with their titles.</param>
|
||||
/// <exception cref="NestedRenameException">A target lies inside a sequence's folder, or inside another target.</exception>
|
||||
public static RenamePlan Plan(Guid archiveId, IReadOnlyList<RenameSubject> subjects, string? folderTemplate, string? titleTemplate,
|
||||
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null)
|
||||
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? 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<string>(taken, StringComparer.OrdinalIgnoreCase);
|
||||
var own = new List<RenameStep>(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)] };
|
||||
}
|
||||
|
||||
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>), or all its frames kept when its sidecar could not be read.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>Camera body and file format: RAW+JPEG shooting yields two sequences instead of doubled frames.</summary>
|
||||
private static string BodyKey(CardPhoto p) => $"{CameraKey(p)}|{p.Metadata.Format}";
|
||||
@@ -201,14 +186,7 @@ public static class ImportPlanner
|
||||
}
|
||||
|
||||
/// <summary>Adds _2, _3… before the extension when the template gives two photos the same name.</summary>
|
||||
internal static string UniqueName(string name, HashSet<string> 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<string> taken) => FrameNaming.Unique(name, taken.Add);
|
||||
|
||||
private static long? FreeSpace(string path)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Metadata;
|
||||
|
||||
namespace Chronos.Core.Naming;
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="Import.ImportPlanner"/>), 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.
|
||||
/// </summary>
|
||||
public static class FrameNaming
|
||||
{
|
||||
/// <summary>The context of a photo being filed, from its metadata.</summary>
|
||||
/// <param name="fileName">The photo's name on the card or upload source: <c>{name}</c> is its stem, <c>{ext}</c> its extension.</param>
|
||||
/// <param name="capturedAt">The photo's capture time as the sequence orders it.</param>
|
||||
/// <param name="sessionStart">The capture time of the first photo of its session (<c>{sessionstart}</c>).</param>
|
||||
/// <param name="number">1-based number of the photo (<c>{n}</c>, <c>{nsession}</c>).</param>
|
||||
/// <param name="title">The sequence title (<c>{title}</c>).</param>
|
||||
/// <param name="session">1-based session number within the import (<c>{session}</c>); 1 for an upload.</param>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The context of a frame already in a sequence (Reorganize): its sidecar record with the sequence's camera and lens,
|
||||
/// numbered by its index (<c>{n}</c> = index + 1), the sequence as one session starting at its first frame. <c>{name}</c>
|
||||
/// is the name the photo had on the card, <c>{ext}</c> 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.
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The start of a sequence as one session: its first frame's capture time, else when the sequence was made.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="directory"/> (empty or ending with '/') and the name <paramref name="template"/> gives, made unique
|
||||
/// in <paramref name="taken"/> with <c>_2</c>, <c>_3</c>… before the extension, then added to it.
|
||||
/// </summary>
|
||||
public static string FileName(PathTemplate template, NamingContext context, ISet<string> taken, string directory = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(taken);
|
||||
var file = FileName(template, context, candidate => !taken.Contains(candidate), directory);
|
||||
taken.Add(file);
|
||||
return file;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="directory"/> and the name <paramref name="template"/> gives, or the first of <c>stem_2.ext</c>,
|
||||
/// <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.
|
||||
/// </summary>
|
||||
public static string FileName(PathTemplate template, NamingContext context, Func<string, bool> isFree, string directory = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(template);
|
||||
ArgumentNullException.ThrowIfNull(isFree);
|
||||
ArgumentNullException.ThrowIfNull(directory);
|
||||
return Unique(directory + template.ExpandFile(context), isFree);
|
||||
}
|
||||
|
||||
/// <summary><paramref name="file"/>, or the first of <c>stem_2.ext</c>, <c>stem_3.ext</c>… that <paramref name="isFree"/> accepts.</summary>
|
||||
public static string Unique(string file, Func<string, bool> 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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -73,8 +73,8 @@ public sealed class ArchiveService : IJobHandlerProvider
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="JobEngine"/>.
|
||||
/// reports, index backups and clean-ups (owner review 2, R10), the emptying of the trash (R6) and Reorganize (R7,
|
||||
/// <see cref="JobKind.Move"/>); register them on the <see cref="JobEngine"/>.
|
||||
/// </summary>
|
||||
public IReadOnlyList<IJobHandler> 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),
|
||||
];
|
||||
|
||||
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
|
||||
@@ -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<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize (owner review 2, R7): <paramref name="templates"/> over <paramref name="sequenceIds"/>, or
|
||||
/// over every sequence of the archive (by folder) when null. Apply it in a job (<see cref="ArchiveJobs.Reorganize"/>) or
|
||||
/// with <see cref="ApplyRenameAsync"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The archive is unknown, or a sequence is not in it.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanReorganizeAsync(Guid archiveId, IReadOnlyList<Guid>? 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<RenameResult> ApplyRenameAsync(RenamePlan plan, IProgress<int>? 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: applies the Reorganize <paramref name="plan"/> (the dry run of <paramref name="templates"/>,
|
||||
/// <see cref="ArchiveService.PlanReorganizeAsync"/>) as confirmed, refused when the archive changed since
|
||||
/// (<see cref="MoveJobParameters"/>; owner review 2, R7).
|
||||
/// </summary>
|
||||
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<Job> 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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>What a companion's name adds to its photo's stem (<c>.xmp</c>, <c>.CR2.xmp</c>).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="file"/> when it and its companions' names (<paramref name="tails"/> after its stem) are free in
|
||||
/// <paramref name="taken"/> and on disk in <paramref name="folder"/> (none yet: in <paramref name="taken"/> only), else
|
||||
|
||||
@@ -347,7 +347,7 @@ public sealed partial class FrameTrash
|
||||
var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var claimed = new HashSet<string>(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<TrashedPhoto>(removed.Count);
|
||||
foreach (var frame in removed)
|
||||
{
|
||||
@@ -431,35 +431,6 @@ public sealed partial class FrameTrash
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<c>IMG_0001.XMP</c> too).
|
||||
/// </summary>
|
||||
private sealed class CompanionIndex(SequencePaths folder)
|
||||
{
|
||||
private static readonly EnumerationOptions Listing = new() { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 };
|
||||
private readonly Dictionary<string, ILookup<string, string>> _directories = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The XMP files beside a photo that name it (<c>stem.xmp</c> or <c>file.xmp</c>), relative to the sequence folder.</summary>
|
||||
public IEnumerable<string> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo's stem with its folder (<c>originals/IMG_0001</c>): its companions share it.</summary>
|
||||
private static string Stem(string file)
|
||||
{
|
||||
|
||||
@@ -40,6 +40,17 @@ public sealed record EmptyTrashParameters(IReadOnlyList<EmptyTrashItem> Entries,
|
||||
/// <summary>One entry of a confirmed emptying: its name and fingerprint when it was planned.</summary>
|
||||
public sealed record EmptyTrashItem(string Name, string Fingerprint);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/> (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 (<see cref="Core.Archiving.RenamePlan.Fingerprint"/>).
|
||||
/// No file list: the job plans again and refuses when the plan is no longer the one confirmed.
|
||||
/// </summary>
|
||||
public sealed record MoveJobParameters(string? FolderTemplate, string? FileTemplate, string? TitleTemplate, IReadOnlyList<MoveSequence> Sequences, string Fingerprint);
|
||||
|
||||
/// <summary>A sequence of a <see cref="MoveJobParameters"/> and the frames version its file names were planned at.</summary>
|
||||
public sealed record MoveSequence(Guid Id, int FramesVersion);
|
||||
|
||||
/// <summary>A job ready to enqueue.</summary>
|
||||
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
|
||||
|
||||
@@ -52,6 +63,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
|
||||
[JsonSerializable(typeof(BackupParameters))]
|
||||
[JsonSerializable(typeof(CleanupParameters))]
|
||||
[JsonSerializable(typeof(EmptyTrashParameters))]
|
||||
[JsonSerializable(typeof(MoveJobParameters))]
|
||||
[JsonSerializable(typeof(CardProfile))]
|
||||
internal sealed partial class ArchiveJobJson : JsonSerializerContext
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="JobKind.Move"/>: a Reorganize (owner review 2, R7; BRIEF §12.5) of existing sequences with new folder, file
|
||||
/// and title templates (<see cref="MoveJobParameters"/>). 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;
|
||||
/// <see cref="StaleRenamePlanException"/> otherwise, nothing changed), through <see cref="MassRenamer"/>, whose journal makes
|
||||
/// every step resumable. Progress counts the plan's steps (sequences); checkpoint: <c>plan:<id></c> once the plan's
|
||||
/// journal is written. Paused or cancelled, the job stops between two sequences and holds the plan
|
||||
/// (<see cref="MassRenamer.Hold"/>), 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 <see cref="ArchiveServiceOptions.SequenceChanged"/> (<see cref="Change"/>).
|
||||
/// </summary>
|
||||
internal sealed class MoveJobHandler(ChronosDatabase db, MassRenamer renamer, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
|
||||
{
|
||||
/// <summary>The change a Reorganize tells about a sequence (a server's <c>sequenceChanged</c> event).</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Completes a plan this job started; null when its journal went meanwhile (completed at an archive open).</summary>
|
||||
private async Task<RenameResult?> 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);
|
||||
}
|
||||
|
||||
/// <summary>Whether the plan made now is the one confirmed: the same fingerprint, and the frames versions its file names were planned at.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Tells each sequence changed; a failure is logged, never passed on to the job.</summary>
|
||||
private async Task TellAsync(IReadOnlyList<Guid> 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);
|
||||
|
||||
/// <summary>How the job log names a sequence of the plan: its title, else its folder.</summary>
|
||||
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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
: InvalidOperationException(Loc.L("Archive.Error.StalePlan"))
|
||||
@@ -17,9 +18,19 @@ public sealed class StaleRenamePlanException(Guid sequenceId)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders and titles (BRIEF §7, §12.5): <see cref="PlanAsync"/> is the dry run;
|
||||
/// <see cref="ApplyAsync"/> 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 <see cref="ResumePendingAsync"/>.
|
||||
/// 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 (<see cref="Dropped"/>, only when resuming) and those
|
||||
/// whose files kept their names because their photos changed since (<see cref="FilesKept"/>; their folder and title changed).
|
||||
/// </summary>
|
||||
public sealed record RenameResult(IReadOnlyList<Guid> Changed, int Files, IReadOnlyList<Guid> Dropped, IReadOnlyList<Guid> FilesKept);
|
||||
|
||||
/// <summary>
|
||||
/// Mass rename of sequence folders, titles and file names (BRIEF §7, §12.5; Reorganize, owner review 2, R7):
|
||||
/// <see cref="PlanAsync(Archive, IReadOnlyList{Guid}, RenameTemplates, CancellationToken)"/> is the dry run;
|
||||
/// <see cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/> 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 <see cref="ResumePendingAsync"/> (or, for a plan its job held, by <see cref="ResumeAsync"/>). A step's file
|
||||
/// renames have their own journal in the sequence (<see cref="FileRenameJournal"/>).
|
||||
/// </summary>
|
||||
public sealed class MassRenamer
|
||||
{
|
||||
@@ -38,20 +49,35 @@ public sealed class MassRenamer
|
||||
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
|
||||
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default)
|
||||
public Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
PlanAsync(archive, sequenceIds, new RenameTemplates(folderTemplate, null, titleTemplate), cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// The dry run of a Reorganize: the plan of <paramref name="templates"/> over <paramref name="sequenceIds"/>. 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.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">A sequence is not in the archive.</exception>
|
||||
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
|
||||
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> 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<RenameSubject>(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<RenameSubject>();
|
||||
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);
|
||||
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">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.</exception>
|
||||
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
RunAsync(archive, new RenameJournal(plan, []), resuming: false, progress, cancellationToken);
|
||||
/// <summary>The sidecar of a sequence and the files beside its frames; null (logged) when it cannot be read or is another sequence's.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash; returns how many plans were resumed.</summary>
|
||||
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
|
||||
/// <exception cref="StaleRenamePlanException">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).</exception>
|
||||
/// <exception cref="IOException">A file could not be renamed (open elsewhere); the step's files went back to their names.</exception>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
|
||||
ApplyAsync(archive, plan, null, progress is null ? null : n =>
|
||||
{
|
||||
progress.Report(n);
|
||||
return ValueTask.CompletedTask;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="ApplyAsync(Archive, RenamePlan, IProgress{int}?, CancellationToken)"/>
|
||||
/// <param name="started">Told once the plan's journal is written, before any step (a job saves the plan's id as its checkpoint).</param>
|
||||
/// <param name="stepDone">Told after each step with the number of steps done.</param>
|
||||
public Task<RenameResult> ApplyAsync(Archive archive, RenamePlan plan, Func<RenamePlan, ValueTask>? started, Func<int, ValueTask>? stepDone,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return RunAsync(archive, new RenameJournal(plan, []), resuming: false, started, stepDone, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Completes the plan <paramref name="planId"/> from its journal: one an interruption left (as <see cref="ResumePendingAsync"/>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <exception cref="StaleRenamePlanException">A held plan's remaining steps no longer match the archive; nothing more changed.</exception>
|
||||
public async Task<RenameResult?> ResumeAsync(Archive archive, Guid planId, Func<int, ValueTask>? 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the plan <paramref name="planId"/> held (<see cref="RenameJournal.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).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Completes renames interrupted by a crash (not those their job held); returns how many plans were resumed.</summary>
|
||||
public async Task<int> 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;
|
||||
}
|
||||
|
||||
/// <param name="resuming">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.</param>
|
||||
private async Task RunAsync(Archive archive, RenameJournal journal, bool resuming, IProgress<int>? progress, CancellationToken cancellationToken)
|
||||
private async Task<RenameResult> RunAsync(Archive archive, RenameJournal journal, bool resuming, Func<RenamePlan, ValueTask>? started,
|
||||
Func<int, ValueTask>? 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<RenameStep> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
private async Task RefuseStaleAsync(Archive archive, ArchivePaths paths, RenamePlan plan, IReadOnlyList<RenameStep> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frames version of a sequence's sidecar (read without its lease); null when it cannot be read or is another sequence's.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The step whose folder move carries <paramref name="carried"/>: the nearest moving folder around it (as planned).</summary>
|
||||
@@ -127,14 +254,15 @@ public sealed class MassRenamer
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="resuming">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.</param>
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, RenameStep step, IReadOnlyList<RenameStep> carried, bool resuming,
|
||||
CancellationToken cancellationToken)
|
||||
private async Task ApplyStepAsync(Archive archive, ArchivePaths paths, string? fileTemplate, RenameStep step, IReadOnlyList<RenameStep> carried,
|
||||
bool resuming, Tally result, CancellationToken cancellationToken)
|
||||
{
|
||||
var ids = carried.Select(c => c.SequenceId).Append(step.SequenceId).Order().ToList();
|
||||
var locks = new List<IAsyncDisposable>(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<RenameStep>(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 (<see cref="SequenceRepository.RelocateAsync"/>): 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
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>).
|
||||
/// (<see cref="ArchiveIndexer.InStepAsync(Archive, string, SequencePaths, SequenceManifest, CancellationToken)"/>). A step
|
||||
/// that only renames files has nothing to record here.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="FileRenames.Plan"/>, 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 (<see cref="StaleRenamePlanException"/>), or, when resuming, leaves its files as they are. The files
|
||||
/// move in two phases through temporary names under the sequence's journal (<see cref="FileRenameJournal"/>), then the
|
||||
/// sidecar names them (the frame order unchanged, frames version + 1), then the index (<see cref="FrameRepository.RenameFilesAsync"/>),
|
||||
/// 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 (<see cref="SequenceWriter.ReadLocked"/>) 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.
|
||||
/// </summary>
|
||||
/// <returns>False when the step renames no file, or its files kept their names.</returns>
|
||||
private async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
private async Task<List<FrameFileName>> 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<FrameFileName>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
/// <summary>What a run did, as it goes.</summary>
|
||||
private sealed class Tally
|
||||
{
|
||||
public List<Guid> Changed { get; } = [];
|
||||
public List<Guid> Dropped { get; } = [];
|
||||
public List<Guid> FilesKept { get; } = [];
|
||||
public int Files { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,12 @@ public sealed record ArchiveServiceOptions
|
||||
/// </summary>
|
||||
public string? BackupDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Told after a job changed a sequence's folder, title or file names (change <c>reorganized</c>, a Reorganize): a server
|
||||
/// tells its connected clients (BRIEF §14.3). A failure is logged and never fails the job.
|
||||
/// </summary>
|
||||
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
|
||||
|
||||
/// <summary>Half the logical cores, at least one: the parallelism when the host sets none.</summary>
|
||||
public static int DefaultParallelism => Math.Max(1, Environment.ProcessorCount / 2);
|
||||
|
||||
@@ -88,9 +94,11 @@ internal sealed class SequenceWriter(ArchiveServiceOptions options)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sidecar of a locked sequence, undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>),
|
||||
/// settling an interrupted restore from the trash (<see cref="FrameRestoreJournal"/>; 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 (<see cref="FileRenameJournal"/>),
|
||||
/// undoing an interrupted photo deletion (<see cref="FrameRemovalJournal"/>), settling an interrupted restore from the
|
||||
/// trash (<see cref="FrameRestoreJournal"/>; 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.
|
||||
/// </summary>
|
||||
/// <param name="heldEntryLease">The trash entry lease the caller holds already (a restore of that entry), if any.</param>
|
||||
/// <exception cref="InvalidDataException">The sidecar in the folder belongs to another sequence.</exception>
|
||||
@@ -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)
|
||||
|
||||
@@ -19,6 +19,9 @@ public readonly record struct FramePosition(Guid FrameId, int Index);
|
||||
/// <summary>A frame whose content (SHA-256) also exists elsewhere in the archive.</summary>
|
||||
public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId, int Index, string RelativePath);
|
||||
|
||||
/// <summary>A frame's file after a Reorganize renamed it (owner review 2, R7): its archive-relative path and its file name.</summary>
|
||||
public readonly record struct FrameFileName(Guid FrameId, string RelativePath, string FileName);
|
||||
|
||||
/// <summary>Light statistics of one frame, written by the analysis job.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="SequenceRepository.GetForUpdateAsync"/>'s
|
||||
/// order); with <paramref name="toVersion"/> the row's frames version becomes it, when it is still
|
||||
/// <paramref name="fromVersion"/> (the sidecar's before the renames). Frames of other sequences are never touched and
|
||||
/// repeating it is harmless. Returns the number of frames updated.
|
||||
/// </summary>
|
||||
public Task<int> RenameFilesAsync(Guid sequenceId, IReadOnlyList<FrameFileName> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes what a verify found, in one transaction: the <see cref="FrameFlags.Missing"/> and <see cref="FrameFlags.Corrupt"/>
|
||||
/// bits and new hashes. Every other flag stays as stored: decode tiers, duplicates and exclusions belong to other
|
||||
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
public sealed record LibraryFacetsDto(IReadOnlyList<FacetDto> Years, IReadOnlyList<FacetDto> Cameras, IReadOnlyList<FacetDto> Tags);
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/v1/archive/reorganize</c> (owner review 2, R7; administrators of the archive): new folder, file and title
|
||||
/// templates applied to sequences already in the archive, <see cref="SequenceIds"/> or every one with <see cref="All"/>
|
||||
/// (exactly one of the two). A null template keeps that part; at least one is given, each valid as the archive settings'
|
||||
/// templates are. <see cref="DryRun"/> answers the plan (<see cref="ReorganizePlanDto"/>) and changes nothing; the change
|
||||
/// itself sends that plan's <see cref="Fingerprint"/> back (409 <c>plan_changed</c> when the archive changed since) and runs
|
||||
/// as a <c>move</c> job (202).
|
||||
/// </summary>
|
||||
public sealed record ReorganizeRequest(IReadOnlyList<Guid>? SequenceIds, bool All, string? FolderTemplate, string? FileTemplate, string? TitleTemplate,
|
||||
bool DryRun, string? Fingerprint = null);
|
||||
|
||||
/// <summary>A file a Reorganize renames: its name before and after, relative to the sequence folder (<c>originals/…</c>).</summary>
|
||||
public sealed record ReorganizeFileDto(string From, string To);
|
||||
|
||||
/// <summary>
|
||||
/// Photos of a sequence that keep their names in a Reorganize: <see cref="Reason"/> <c>in_place</c> (kept in place outside
|
||||
/// <c>originals/</c>), <c>unhashed</c> (never verified), <c>missing</c> or <c>unreadable</c> (the sequence's sidecar), how many
|
||||
/// (0 for <c>unreadable</c>), and the reason as one localised sentence.
|
||||
/// </summary>
|
||||
public sealed record ReorganizeBlockedDto(string Reason, int Photos, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// One sequence of a Reorganize plan, in the order the steps apply: its folder and title before and after,
|
||||
/// <see cref="Carried"/> 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 (<see cref="FileSamples"/>), and the photos
|
||||
/// that keep their names. A step that changes nothing lists only those.
|
||||
/// </summary>
|
||||
public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried,
|
||||
int FramesVersion, int FileChanges, IReadOnlyList<ReorganizeFileDto> FileSamples, IReadOnlyList<ReorganizeBlockedDto> Blocked);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record ReorganizePlanDto(IReadOnlyList<ReorganizeStepDto> Steps, int Sequences, int Files, int Kept, string Fingerprint);
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
/// <summary><c>/api/v1/archive</c> (admin): templates and proxy policy, scan/rebuild/verify/maintenance jobs, statistics.</summary>
|
||||
/// <summary>
|
||||
/// <c>/api/v1/archive</c> (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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize: folder, file and title templates applied to <c>sequenceIds</c> or, with <c>all</c>, to every sequence of the
|
||||
/// archive (BRIEF §12.5). With <c>dryRun</c> 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 <c>move</c> job (202) that applies exactly that plan, refused when the
|
||||
/// archive changed before it ran. 400 <c>bad_request</c> (details <c>sequenceIds</c>: neither or both of them, none, or
|
||||
/// more than <see cref="LibraryEndpoints.MaxBulkIds"/>; <c>templates</c>: none; <c>fingerprint</c>), 400
|
||||
/// <c>invalid_template</c> (details: <c>folderTemplate</c>, <c>fileTemplate</c> or <c>titleTemplate</c>); 404
|
||||
/// <c>not_found</c> (<c>sequence</c>: not in the archive); 409 <c>nested_target</c> (details: the folder that would lie
|
||||
/// inside a sequence's folder), <c>plan_changed</c> (details: the fingerprint now), <c>job_unavailable</c>; 503
|
||||
/// <c>archive_offline</c>. Audited; the job tells every sequence it changes as <c>sequenceChanged</c>
|
||||
/// (<c>reorganized</c>).
|
||||
/// </summary>
|
||||
private static async Task<IResult> 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);
|
||||
}
|
||||
|
||||
/// <summary>The dry run as the API answers it, with each reason photos keep their names in the request's language.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Wire name of a reason photos keep their names: <c>in_place</c>, <c>unhashed</c>, <c>missing</c>, <c>unreadable</c>.</summary>
|
||||
public static string Wire(RenameBlock reason) => reason switch
|
||||
{
|
||||
RenameBlock.InPlace => "in_place",
|
||||
RenameBlock.Unhashed => "unhashed",
|
||||
RenameBlock.Missing => "missing",
|
||||
_ => "unreadable",
|
||||
};
|
||||
|
||||
private static async Task<IResult> 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));
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ICleanupStep"/>s in DI); a scan
|
||||
/// orphans reports, index backups and clean-ups with the server's own steps, the <see cref="ICleanupStep"/>s in DI, and Reorganize's
|
||||
/// <c>move</c> 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
|
||||
/// (<see cref="Jobs.ServerScheduleHost"/>, owner review 2, R10).
|
||||
@@ -25,9 +28,17 @@ public static class ArchiveModule
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
var db = sp.GetRequiredService<ChronosDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
// 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<ChronosDatabase>(), 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,
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
using System.Text;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Naming;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Core.Tests.Archiving;
|
||||
|
||||
/// <summary>Reorganize (owner review 2, R7): file names planned from a template, and the two-phase renames of a sequence's files.</summary>
|
||||
[Category("archive")]
|
||||
public sealed class ReorganizeTests(TestContext context)
|
||||
{
|
||||
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
|
||||
|
||||
/// <summary>Frames in index order, every one hashed, ten seconds apart.</summary>
|
||||
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<string>? 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<IOException>(() => 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))));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Import, upload and Reorganize name a photo alike (owner review 2, R7).</summary>
|
||||
[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<string>(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))));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>move</c> job.
|
||||
/// </summary>
|
||||
[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);
|
||||
|
||||
/// <summary>Uploads photos ten seconds apart (from <paramref name="firstSecond"/>) into the sequence of <paramref name="key"/>; returns its id.</summary>
|
||||
private static async Task<Guid> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static async Task<Guid> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static async Task<List<string>> 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<StaleRenamePlanException>(() => 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<OperationCanceledException>(() => 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Frame>();
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Reorganize on the server (owner review 2, R7): <c>POST /api/v1/archive/reorganize</c>, its dry run, the <c>move</c> job that
|
||||
/// applies the confirmed plan, and what the request may not do, against the real archive engine.
|
||||
/// </summary>
|
||||
[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<EventHub>().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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
|
||||
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 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user