using Chronos.Core.Diagnostics;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
namespace Chronos.Core.Archiving;
/// Files of a sequence folder that the sidecar does not list, and sidecar frames whose file is gone.
public sealed record SequenceOrphans(string Folder, IReadOnlyList UnindexedFiles, IReadOnlyList MissingFiles)
{
public bool IsEmpty => UnindexedFiles.Count == 0 && MissingFiles.Count == 0;
}
///
/// 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.
///
public static class SequenceAdopter
{
/// A new sidecar for a folder without one. A folder outside the layout (no originals/) is titled by its name.
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);
}
/// Unindexed photos and missing frame files of one sequence.
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);
}
///
/// Brings a sidecar in line with its folder: unindexed photos are added (in capture order), frames whose file is
/// gone get and frames whose file came back lose it. Null when nothing changed.
///
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>();
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);
// Photos that cannot be read yet (held open by another program, no read permission, a placeholder not downloaded)
// stay unindexed: with nothing else changed, nothing changed.
if (added.Count == 0 && flagChanges.Count == 0) return null;
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 Frames, FrameMetadata? First) ReadFrames(SequencePaths sequence, IReadOnlyList files, CancellationToken cancellationToken)
{
var frames = new List(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);
}
}