feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s

- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #12.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 21:58:39 +01:00
1 parent 9aa818ed47
commit 7e4a3b481d
416 files changed
+15304 -1572

No files matched your search

@@ -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
@@ -45,6 +45,43 @@ public sealed class RenderRepository
return true;
}, cancellationToken);
/// <summary>
/// Rewrites the archive-relative output paths of an archive's renders after the folder of sequence
/// <paramref name="sequenceId"/> moved (a Reorganize, or a move another index of the archive or the user made, which a
/// scan finds): an export inside the folder moved with it. Each render under the old folder whose file
/// <paramref name="follows"/> the folder takes the new path: the caller tells the sequence's own exports there (which
/// follow unless their file stayed behind) from an export of another sequence saved inside it through the Export
/// folder picker (which follows only when its file moved with the folder: a sequence that took the old folder since, by
/// a later Reorganize another index made, keeps its own). An export of the sequence whose path an export of another
/// sequence names follows without asking: that path is the other sequence's now, which brought an export of that name
/// into the old folder. Outputs elsewhere (absolute paths, other folders) stay as they are.
/// </summary>
/// <param name="follows">Whether the render at the first archive-relative path follows to the second one; the third
/// argument is the sequence it is an export of.</param>
/// <remarks>Only paths still under <paramref name="oldFolder"/> change, so repeating it after a crash is harmless.</remarks>
public async Task<int> RebaseFolderAsync(Guid archiveId, Guid sequenceId, string oldFolder, string newFolder, Func<string, string, Guid, bool> follows,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(follows);
// The archive root never moves, and its prefix ("/") would match absolute paths outside the archive.
if (oldFolder.Length == 0) return 0;
// substr counts characters (code points) on both dialects.
var prefix = oldFolder + "/";
var under = await _db.ListAsync(
"SELECT r.id, r.sequence_id, r.output_path FROM renders r JOIN sequences s ON s.id = r.sequence_id WHERE s.archive_id = $1 AND substr(r.output_path, 1, $2) = $3",
[archiveId, prefix.EnumerateRunes().Count(), prefix], r => (Id: r.GetGuid(0), SequenceId: r.GetGuid(1), Path: r.GetString(2)), cancellationToken)
.ConfigureAwait(false);
var rebased = 0;
foreach (var (id, owner, path) in under)
{
var to = newFolder.Length == 0 ? path[prefix.Length..] : newFolder + path[oldFolder.Length..];
var taken = owner == sequenceId && under.Any(o => o.SequenceId != sequenceId && string.Equals(o.Path, path, StringComparison.Ordinal));
if (!taken && !follows(path, to, owner)) continue;
rebased += await _db.ExecuteAsync("UPDATE renders SET output_path = $2 WHERE id = $1", [id, to], cancellationToken).ConfigureAwait(false);
}
return rebased;
}
/// <summary>
/// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot)
/// sees every committed render; SQLite's write lock already does this.
@@ -1,4 +1,6 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Imaging;
using Chronos.Core.Model;
@@ -425,6 +427,75 @@ public sealed class SequenceRepository
}, cancellationToken);
}
/// <summary>
/// A digest of what a Reorganize of <paramref name="sequenceIds"/> (null: every sequence) plans from in the index of
/// <paramref name="archiveId"/> (owner review 2, R7): every sequence of the archive and its folder, which decide the
/// folders that get " (2)" and what a moving folder carries; of the sequences planned, their title, first capture,
/// camera, lens, photo count, frames version and how many of their photos are hashed (only those get a new name, and a
/// verify hashes photos without another frames version); of the others inside their folders, the title. Another value
/// once one of these changes. Any other write (an upload into a sequence not planned, a verify that hashes no photo of
/// a planned sequence, a status, tag or note change) leaves it as it was, and so does a change made on disk alone, which
/// the index does not have.
/// </summary>
public async Task<string> GetStampAsync(Guid archiveId, IReadOnlyCollection<Guid>? sequenceIds, CancellationToken cancellationToken = default)
{
var rows = await _db.ListAsync(
"SELECT id, folder, title, first_capture, camera_make, camera_model, lens, frame_count, frames_version FROM sequences WHERE archive_id = $1 ORDER BY id",
[archiveId], r => (Id: r.GetGuid(0), Folder: r.GetString(1), Title: r.GetStringOrNull(2), Read: string.Create(CultureInfo.InvariantCulture,
$"{r.GetStringOrNull(2)}\u001f{r.GetDateTimeOrNull(3):O}\u001f{r.GetStringOrNull(4)}\u001f{r.GetStringOrNull(5)}\u001f{r.GetStringOrNull(6)}\u001f" +
$"{r.GetInt32(7)}\u001f{r.GetInt32(8)}")), cancellationToken).ConfigureAwait(false);
var selected = sequenceIds?.ToHashSet();
var hashed = await CountHashedAsync(archiveId, selected, cancellationToken).ConfigureAwait(false);
var planned = new HashSet<string>(rows.Where(r => selected?.Contains(r.Id) != false && r.Folder.Length > 0).Select(r => r.Folder),
StringComparer.OrdinalIgnoreCase);
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var row in rows)
{
var read = selected?.Contains(row.Id) != false
? string.Create(CultureInfo.InvariantCulture, $"{row.Read}\u001f{hashed.GetValueOrDefault(row.Id)}")
: Inside(row.Folder) ? row.Title : null;
hash.AppendData(Encoding.UTF8.GetBytes(string.Create(CultureInfo.InvariantCulture, $"{row.Id:N}\u001f{row.Folder}\u001e{read}\n")));
}
return Convert.ToHexStringLower(hash.GetHashAndReset());
// Whether a folder lies inside a planned sequence's folder (RenamePlanner.IsInside), checking each folder around it.
bool Inside(string folder)
{
for (var slash = folder.LastIndexOf('/'); slash > 0; slash = folder.LastIndexOf('/', slash - 1))
{
if (planned.Contains(folder[..slash])) return true;
}
return false;
}
}
/// <summary>
/// How many photos of each of <paramref name="sequenceIds"/> (null: every sequence of <paramref name="archiveId"/>) have
/// their SHA-256 in the index; a sequence without one is not listed.
/// </summary>
private async Task<Dictionary<Guid, long>> CountHashedAsync(Guid archiveId, IReadOnlyCollection<Guid>? sequenceIds, CancellationToken cancellationToken)
{
var counts = new Dictionary<Guid, long>();
if (sequenceIds is null)
{
foreach (var (id, count) in await _db.ListAsync(
"SELECT f.sequence_id, count(*) FROM frames f JOIN sequences s ON s.id = f.sequence_id " +
"WHERE s.archive_id = $1 AND f.sha256 IS NOT NULL GROUP BY f.sequence_id",
[archiveId], r => (r.GetGuid(0), r.GetInt64(1)), cancellationToken).ConfigureAwait(false)) counts[id] = count;
return counts;
}
// 500 ids per statement stays below SQLite's historical 999-variable limit.
foreach (var chunk in sequenceIds.Chunk(500))
{
var p = new SqlParameters();
var ids = string.Join(", ", chunk.Select(id => p.Add(id)));
foreach (var (id, count) in await _db.ListAsync(
$"SELECT sequence_id, count(*) FROM frames WHERE sequence_id IN ({ids}) AND sha256 IS NOT NULL GROUP BY sequence_id",
p.ToArray(), r => (r.GetGuid(0), r.GetInt64(1)), cancellationToken).ConfigureAwait(false)) counts[id] = count;
}
return counts;
}
/// <summary>
/// The sequences of <paramref name="archiveId"/> a rolling verification checks next (owner review 2, R10): those never
/// verified first, then the longest unverified, at most <paramref name="limit"/>. With <paramref name="verifiedBefore"/>