Files
Chronos/src/Titano.Core/Archiving/SequenceAdopter.cs
T
Claude 55895e8474 feat(core): archive layout, sidecars, leases and thumbnail packs
archive.json and sequence.json with source-generated JSON, forward-compatible
reading (unknown fields kept, unknown enum names tolerated) and atomic writes;
lease files with expiry and stale takeover; thumbs.pack with index, crash-safe
append and random access; folder scanning, in-place adoption, reconcile,
verify, index snapshot, rename planning and thumbnail/proxy rendering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 12:30:14 +00:00

92 lines
4.9 KiB
C#

using Titano.Core.Diagnostics;
using Titano.Core.Metadata;
using Titano.Core.Model;
namespace Titano.Core.Archiving;
/// <summary>Files of a sequence folder that the sidecar does not list, and sidecar frames whose file is gone.</summary>
public sealed record SequenceOrphans(string Folder, IReadOnlyList<string> UnindexedFiles, IReadOnlyList<SidecarFrame> MissingFiles)
{
public bool IsEmpty => UnindexedFiles.Count == 0 && MissingFiles.Count == 0;
}
/// <summary>
/// Builds and reconciles sidecars from the photos found in a folder (BRIEF §7, §12.5 "Adopt folder"). Only light
/// metadata is read; originals are never moved, renamed or rewritten. Hashes are left empty for a verify to fill.
/// </summary>
public static class SequenceAdopter
{
/// <summary>A new sidecar for a folder without one. A folder outside the layout (no <c>originals/</c>) is titled by its name.</summary>
public static SequenceManifest Build(Guid id, SequencePaths sequence, string? createdBy, CancellationToken cancellationToken = default)
{
var (frames, first) = ReadFrames(sequence, ArchiveScanner.ListPhotos(sequence), cancellationToken);
var now = DateTimeOffset.UtcNow;
var inLayout = Directory.Exists(sequence.Originals);
var manifest = new SequenceManifest
{
Id = id,
Title = inLayout ? null : Path.GetFileName(Path.TrimEndingDirectorySeparator(sequence.Folder)),
Camera = first is null ? null : new SidecarCamera { Make = first.Make, Model = first.Model, Serial = first.BodySerial },
Lens = first?.LensModel,
CreatedBy = createdBy,
Created = now,
UpdatedAt = now,
};
return SequenceFrames.Insert(manifest, frames);
}
/// <summary>Unindexed photos and missing frame files of one sequence.</summary>
public static SequenceOrphans FindOrphans(SequencePaths sequence, SequenceManifest manifest)
{
var listed = manifest.Frames.Select(f => f.File).ToHashSet(StringComparer.Ordinal);
var unindexed = ArchiveScanner.ListPhotos(sequence).Where(f => !listed.Contains(f)).ToList();
var missing = manifest.Frames.Where(f => !File.Exists(sequence.File(f.File))).ToList();
return new SequenceOrphans(sequence.RelativeFolder, unindexed, missing);
}
/// <summary>
/// Brings a sidecar in line with its folder: unindexed photos are added (in capture order), frames whose file is
/// gone get <see cref="FrameFlags.Missing"/> and frames whose file came back lose it. Null when nothing changed.
/// </summary>
public static SequenceManifest? Reconcile(SequencePaths sequence, SequenceManifest manifest, CancellationToken cancellationToken = default)
{
var orphans = FindOrphans(sequence, manifest);
var missing = orphans.MissingFiles.Select(f => f.Id).ToHashSet();
var flagChanges = new Dictionary<Guid, Func<SidecarFrame, SidecarFrame>>();
foreach (var frame in manifest.Frames)
{
var isMissing = missing.Contains(frame.Id);
if (isMissing == frame.Flags.HasFlag(FrameFlags.Missing)) continue;
flagChanges[frame.Id] = f => f with { Flags = isMissing ? f.Flags | FrameFlags.Missing : f.Flags & ~FrameFlags.Missing };
}
if (flagChanges.Count == 0 && orphans.UnindexedFiles.Count == 0) return null;
var updated = flagChanges.Count == 0 ? manifest : SequenceFrames.Update(manifest, flagChanges);
var (added, first) = ReadFrames(sequence, orphans.UnindexedFiles, cancellationToken);
if (updated.Camera is null && first is not null)
updated = updated with { Camera = new SidecarCamera { Make = first.Make, Model = first.Model, Serial = first.BodySerial }, Lens = updated.Lens ?? first.LensModel };
return SequenceFrames.Insert(updated, added);
}
private static (List<SidecarFrame> Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList<string> files, CancellationToken cancellationToken)
{
var frames = new List<SidecarFrame>(files.Count);
FrameMetadata? first = null;
foreach (var file in files)
{
cancellationToken.ThrowIfCancellationRequested();
var path = sequence.File(file);
try
{
var metadata = MetadataReader.Read(path, cancellationToken);
if (first is null || (metadata.CapturedAt < first.CapturedAt && metadata.Make is not null)) first = metadata;
frames.Add(SequenceFrames.FromMetadata(Guid.CreateVersion7(), file, Path.GetFileName(file), new FileInfo(path).Length, null, metadata));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("archive", $"Skipped unreadable photo {sequence.ArchiveRelative(file)}", ex);
}
}
return (frames, first);
}
}