merge: archive layout, sidecars, scan/rebuild/verify, card import and ingest

This commit is contained in:
Claude committed 2026-10-02 12:30:53 +00:00
commit e92568a7bb
65 files changed
+7197

No files matched your search

@@ -0,0 +1,182 @@
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveFolderTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private ArchivePaths NewArchive() => new(context.CreateTempDirectory("archive"));
[Test]
public void SequenceFoldersAreFoundInLayoutAndAdoptedForms()
{
var archive = NewArchive();
TestPhotos.WriteSeries(Path.Combine(archive.Root, "2026", "2026-09-28 Canon EOS R5", "originals"), Start, 3, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour"), Start, 2, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour", "selects"), Start, 1, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, ".hidden"), Start, 1, TimeSpan.FromSeconds(10));
File.WriteAllBytes(Path.Combine(archive.Root, "Trips", "._IMG_0001.JPG"), [1]);
Directory.CreateDirectory(Path.Combine(archive.Root, "empty"));
var folders = ArchiveScanner.FindSequenceFolders(archive);
Assert.SequenceEqual(["2026/2026-09-28 Canon EOS R5", "Trips/Harbour", "Trips/Harbour/selects"], folders.Select(f => f.RelativeFolder));
Assert.True(folders.All(f => f.Sidecar is null && f.Photos is not null));
Assert.SequenceEqual(["originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG"],
ArchiveScanner.ListPhotos(archive.Sequence("2026/2026-09-28 Canon EOS R5")));
}
[Test]
public void AdoptionBuildsASidecarInCaptureOrderWithoutTouchingPhotos()
{
var archive = NewArchive();
var folder = Path.Combine(archive.Root, "Harbour sunset");
// File names run against capture order: the sidecar follows capture time.
TestPhotos.Write(Path.Combine(folder, "a.jpg"), Start.AddSeconds(20), 1);
TestPhotos.Write(Path.Combine(folder, "b.jpg"), Start, 2);
TestPhotos.Write(Path.Combine(folder, "c.jpg"), Start.AddSeconds(10), 3);
var before = Directory.GetFiles(folder).ToDictionary(f => f, File.ReadAllBytes);
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), archive.Sequence("Harbour sunset"), "test");
Assert.SequenceEqual(["b.jpg", "c.jpg", "a.jpg"], manifest.Frames.Select(f => f.File));
Assert.SequenceEqual([0, 1, 2], manifest.Frames.Select(f => f.I));
Assert.Equal("Harbour sunset", manifest.Title);
Assert.Equal("Canon EOS R5", manifest.Camera!.Model);
Assert.True(manifest.Frames.All(f => f.Sha256 is null && f.Size > 0 && f.Format == ImageFileFormat.Jpeg && f.W == 48));
foreach (var (path, bytes) in before) Assert.BytesEqual(bytes, File.ReadAllBytes(path));
}
[Test]
public void ReconcileIndexesNewPhotosAndFlagsMissingOnes()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
Assert.Null(SequenceAdopter.Reconcile(sequence, manifest));
File.Delete(files[1]);
TestPhotos.Write(Path.Combine(sequence.Originals, "IMG_0000.JPG"), Start.AddSeconds(-10), 9);
var orphans = SequenceAdopter.FindOrphans(sequence, manifest);
Assert.SequenceEqual(["originals/IMG_0000.JPG"], orphans.UnindexedFiles);
Assert.SequenceEqual(["originals/IMG_0002.JPG"], orphans.MissingFiles.Select(f => f.File));
var reconciled = SequenceAdopter.Reconcile(sequence, manifest)!;
Assert.SequenceEqual(["originals/IMG_0000.JPG", "originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG"],
reconciled.Frames.Select(f => f.File));
Assert.Equal(FrameFlags.Missing, reconciled.Frames[2].Flags);
Assert.Equal(manifest.Frames[0].Id, reconciled.Frames[1].Id);
TestPhotos.Write(files[1], Start.AddSeconds(10), 2);
var restored = SequenceAdopter.Reconcile(sequence, reconciled)!;
Assert.Equal(FrameFlags.None, restored.Frames[2].Flags);
}
[Test]
public async Task VerifyDetectsAFlippedByteAMissingFileAndAChangedFile()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var adopted = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
var hashed = new List<SidecarFrame>();
foreach (var frame in adopted.Frames)
{
var check = await FrameVerifier.CheckAsync(sequence, frame);
Assert.Equal(FrameHealth.Hashed, check.Health);
hashed.Add(check.Updated);
}
var bytes = File.ReadAllBytes(files[0]);
bytes[bytes.Length / 2] ^= 0x01;
File.WriteAllBytes(files[0], bytes);
File.Delete(files[1]);
File.AppendAllText(files[2], "edit");
var health = new List<FrameHealth>();
foreach (var frame in hashed) health.Add((await FrameVerifier.CheckAsync(sequence, frame)).Health);
Assert.SequenceEqual([FrameHealth.Corrupt, FrameHealth.Missing, FrameHealth.Changed, FrameHealth.Ok], health);
var corrupt = await FrameVerifier.CheckAsync(sequence, hashed[0]);
Assert.Equal(FrameFlags.Corrupt, corrupt.Flags);
Assert.Equal(hashed[0].Sha256, corrupt.Updated.Sha256);
}
[Test]
public void TheIndexSnapshotIsUsedOnlyForUnchangedSidecars()
{
var archive = NewArchive();
Directory.CreateDirectory(archive.MetaDirectory);
var stampA = new FileStamp(10, new DateTime(2026, 9, 1, 0, 0, 0, DateTimeKind.Utc));
using (var writer = new IndexSnapshot.Writer(archive.SnapshotPath))
{
writer.Add("a", stampA, "{\"a\":1}"u8);
writer.Add("b/ç", new FileStamp(20, stampA.ModifiedUtc), "{\"b\":2}"u8);
writer.Commit();
}
var snapshot = IndexSnapshot.TryLoad(archive.SnapshotPath)!;
Assert.Equal(2, snapshot.Count);
Assert.BytesEqual("{\"a\":1}"u8, snapshot.TryGet("a", stampA));
Assert.Null(snapshot.TryGet("a", stampA with { Size = 11 }));
Assert.NotNull(snapshot.TryGet("b/ç", new FileStamp(20, stampA.ModifiedUtc)));
var bytes = File.ReadAllBytes(archive.SnapshotPath);
bytes[12] ^= 0x40;
File.WriteAllBytes(archive.SnapshotPath, bytes);
Assert.Null(IndexSnapshot.TryLoad(archive.SnapshotPath));
}
[Test]
public void RenamePlansAvoidTakenFoldersAndMoveIdempotently()
{
var archive = NewArchive();
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old a"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old b"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "2026-09-28 Sunset"));
var a = new RenameSubject(Guid.NewGuid(), "2026/old a", null, Start, "Canon", "Canon EOS R5", null);
var b = new RenameSubject(Guid.NewGuid(), "2026/old b", "Dawn", Start, "Canon", "Canon EOS R5", null);
var plan = RenamePlanner.Plan(Guid.NewGuid(), [a, b], "{year}/{date} {title}", "Sunset",
["2026/old a", "2026/old b"], f => Directory.Exists(archive.FromRelative(f)));
Assert.SequenceEqual(["2026/2026-09-28 Sunset (2)", "2026/2026-09-28 Sunset (3)"], plan.Steps.Select(s => s.ToFolder));
Assert.True(plan.Steps.All(s => s.ToTitle == "Sunset"));
Assert.Equal("Dawn", plan.Steps[1].FromTitle);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
Assert.False(Directory.Exists(archive.FromRelative("2026/old a")));
Assert.True(Directory.Exists(archive.FromRelative("2026/2026-09-28 Sunset (2)")));
var titleOnly = RenamePlanner.Plan(Guid.NewGuid(), [b], null, "{title} morning", ["2026/old b"], _ => false);
Assert.Equal("2026/old b", titleOnly.Steps.Single().ToFolder);
Assert.Equal("Dawn morning", titleOnly.Steps.Single().ToTitle);
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [b], "2026/old b", null, ["2026/old b"], _ => true).Steps);
}
[Test]
public void ThumbnailsAndProxiesAreRenderedFromTheFrame()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
Directory.CreateDirectory(sequence.Originals);
File.WriteAllBytes(Path.Combine(sequence.Originals, "big.jpg"), TestPhotos.Jpeg(Start, 7, width: 640, height: 480, orientation: 6));
var frame = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null).Frames.Single();
var renderer = new FrameImageRenderer(new ImageDecoder([]));
var thumb = renderer.Thumbnail(sequence, frame)!;
Assert.Equal((240, 320), (thumb.Width, thumb.Height));
Assert.Equal(DecodeTier.Native, thumb.Tier);
Assert.Equal(240, JpegDecoder.ReadInfo(thumb.Jpeg).Width);
var proxy = renderer.Proxy(sequence, frame, new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" }, new ProxyPolicy { LongEdge = 400 })!;
Assert.Equal((300, 400), (proxy.Width, proxy.Height));
var exif = MetadataReader.Read(new MemoryStream(proxy.Jpeg), "p.jpg");
Assert.Equal(Start, exif.CapturedAt);
Assert.Equal("Canon EOS R5", exif.Model);
Assert.Equal(1, exif.Orientation);
}
}
@@ -0,0 +1,113 @@
using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class LeaseFileTests(TestContext context)
{
private static void WriteRecord(string path, LeaseRecord record) =>
File.WriteAllBytes(path, JsonSerializer.SerializeToUtf8Bytes(record, ArchiveJson.Default.LeaseRecord));
[Test]
public void ALeaseIsExclusiveUntilReleased()
{
var locks = context.CreateTempDirectory();
using (var a = LeaseFile.TryAcquire(locks, "seq-1", "server"))
{
Assert.NotNull(a);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
using var other = LeaseFile.TryAcquire(locks, "seq-2", "client");
Assert.NotNull(other);
}
using var b = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(b);
Assert.Equal("client", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
}
[Test]
public void AnExpiredLeaseOfACrashedHolderIsTakenOver()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "seq-1"), new LeaseRecord("dead", "crashed", "pc", 1, past, past.AddMinutes(2)));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "survivor");
Assert.NotNull(lease);
Assert.Equal("survivor", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Owner);
Assert.Count(1, Directory.GetFiles(locks));
}
[Test]
public async Task AHeldLeaseIsRenewedPastItsDuration()
{
var locks = context.CreateTempDirectory();
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "server", TimeSpan.FromMilliseconds(300));
Assert.NotNull(lease);
await Task.Delay(900);
Assert.True(lease.IsHeld);
Assert.Greater((LeaseFile.Read(lease.Path)!.Expires - DateTimeOffset.UtcNow).TotalMilliseconds, 0);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client", TimeSpan.FromMilliseconds(300)));
}
[Test]
public void AFreshEmptyLeaseFileIsNotStaleButAnOldOneIs()
{
var locks = context.CreateTempDirectory();
var path = LeaseFile.PathFor(locks, "seq-1");
File.WriteAllBytes(path, []);
Assert.Null(LeaseFile.TryAcquire(locks, "seq-1", "client"));
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddHours(-1));
using var lease = LeaseFile.TryAcquire(locks, "seq-1", "client");
Assert.NotNull(lease);
}
[Test]
public void ALostLeaseIsDetectedAndNotDeletedByItsFormerHolder()
{
var locks = context.CreateTempDirectory();
var lease = LeaseFile.TryAcquire(locks, "seq-1", "slow");
Assert.NotNull(lease);
var now = DateTimeOffset.UtcNow;
WriteRecord(lease.Path, new LeaseRecord("thief", "other", "pc", 2, now, now.AddMinutes(2)));
Assert.False(lease.Renew());
Assert.False(lease.IsHeld);
lease.Dispose();
Assert.Equal("thief", LeaseFile.Read(LeaseFile.PathFor(locks, "seq-1"))!.Token);
}
[Test]
public async Task WaitingForABusyLeaseTimesOutWithItsHolder()
{
var locks = context.CreateTempDirectory();
using var held = LeaseFile.TryAcquire(locks, "seq-1", "server");
var error = await Assert.ThrowsAsync<LeaseUnavailableException>(() =>
LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromMilliseconds(200)));
Assert.Equal("server", error.Holder!.Owner);
}
[Test]
public async Task WaitingForALeaseSucceedsOnceItIsReleased()
{
var locks = context.CreateTempDirectory();
var held = LeaseFile.TryAcquire(locks, "seq-1", "server")!;
var waiting = LeaseFile.AcquireAsync(locks, "seq-1", "client", TimeSpan.FromSeconds(10));
await Task.Delay(100);
held.Dispose();
using var lease = await waiting;
Assert.Equal("client", lease.Record.Owner);
}
[Test]
public void CleanupRemovesOnlyStaleLeasesAndItsDryRunNothing()
{
var locks = context.CreateTempDirectory();
var past = DateTimeOffset.UtcNow.AddMinutes(-10);
WriteRecord(LeaseFile.PathFor(locks, "dead"), new LeaseRecord("t", "crashed", "pc", 1, past, past.AddMinutes(1)));
using var live = LeaseFile.TryAcquire(locks, "live", "server");
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: true));
Assert.Count(2, Directory.GetFiles(locks));
Assert.SequenceEqual(["dead"], LeaseFile.CleanupStale(locks, dryRun: false));
Assert.SequenceEqual([LeaseFile.PathFor(locks, "live")], Directory.GetFiles(locks));
}
}
@@ -0,0 +1,157 @@
using System.Text;
using System.Text.Json;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.IO;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ManifestStoreTests(TestContext context)
{
private static SequenceManifest Sample() => new()
{
Id = Guid.CreateVersion7(),
Title = "Harbour sunset",
Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5", Serial = "0431" },
Lens = "RF24-70mm F2.8 L IS USM",
Frames =
[
new SidecarFrame
{
Id = Guid.CreateVersion7(), I = 0, File = "originals/2026-09-28_18-02-11_0001.CR2", Original = "IMG_0001.CR2", Size = 25_000_000,
Sha256 = new string('a', 64), CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11, 250), UtcOffset = 120,
TimeSource = TimestampSource.ExifOriginal, Exposure = 1.0 / 250, FNumber = 8, Iso = 100, Focal = 24, Bias = -0.3, Wb = 0,
Orientation = 6, W = 8192, H = 5464, Format = ImageFileFormat.Cr2, PreviewOffset = 1234, PreviewLength = 567_890,
Flags = FrameFlags.Excluded,
},
],
Tags = ["sunset", "harbour"],
Rating = 4,
Notes = "Windy",
Status = SequenceStatus.ThumbsBuilt | SequenceStatus.Verified,
Versions = new ManifestVersions { Settings = 3, Frames = 7 },
CreatedBy = "alberto",
Created = new DateTimeOffset(2026, 9, 28, 20, 0, 0, TimeSpan.Zero),
UpdatedAt = new DateTimeOffset(2026, 9, 29, 8, 0, 0, TimeSpan.Zero),
VerifiedAt = new DateTimeOffset(2026, 9, 30, 8, 0, 0, TimeSpan.Zero),
SessionKeys = ["card-1234abcd-20260928-180211"],
};
private string SidecarPath() => Path.Combine(context.CreateTempDirectory(), ".titano", "sequence.json");
private static string Canonical(SequenceManifest m) => JsonSerializer.Serialize(m, ArchiveJson.Default.SequenceManifest);
[Test]
public void SequenceSidecarRoundTripsEveryField()
{
var path = SidecarPath();
var original = Sample();
ManifestStore.WriteSequence(path, original);
var read = ManifestStore.ReadSequence(path);
Assert.Equal(Canonical(original), Canonical(read));
Assert.Equal(original.Frames[0], read.Frames[0] with { Extra = original.Frames[0].Extra });
var json = File.ReadAllText(path);
foreach (var field in new[] { "\"i\":", "\"file\":", "\"sha256\":", "\"capturedAt\":", "\"fNumber\":", "\"w\":", "\"previewOffset\":", "\"flags\":" })
Assert.Contains(field, json);
}
[Test]
public void UnknownFieldsAndEnumValuesFromANewerBuildAreReadAndKept()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var id = Guid.CreateVersion7();
var frameId = Guid.CreateVersion7();
File.WriteAllText(path, $$"""
{
"schemaVersion": 1, "id": "{{id}}", "title": "Comet", "futureBlock": { "a": [1, 2] },
"camera": { "make": "Nikon", "sensorTemp": 31 },
"frames": [ { "id": "{{frameId}}", "i": 0, "file": "x.nef", "size": 10, "format": "Nef2030", "timeSource": "Atomic",
"flags": 4096, "aiScore": 0.9 } ],
"status": 1024, "versions": { "settings": 1, "frames": 2, "renders": 5 },
}
""");
var read = ManifestStore.ReadSequence(path);
Assert.Equal(id, read.Id);
Assert.Equal(ImageFileFormat.Unknown, read.Frames[0].Format);
Assert.Equal(TimestampSource.Unknown, read.Frames[0].TimeSource);
Assert.Equal((FrameFlags)4096, read.Frames[0].Flags);
ManifestStore.WriteSequence(path, read with { Title = "Comet 2026" });
var json = File.ReadAllText(path);
foreach (var kept in new[] { "futureBlock", "sensorTemp", "aiScore", "renders", "4096", "1024" }) Assert.Contains(kept, json);
Assert.Equal("Comet 2026", ManifestStore.ReadSequence(path).Title);
}
[Test]
public void ANewerSchemaIsReadableButNeverRewritten()
{
var path = SidecarPath();
ManifestStore.WriteSequence(path, Sample());
var newer = ManifestStore.ReadSequence(path) with { SchemaVersion = SequenceManifest.CurrentSchemaVersion + 1 };
var before = File.ReadAllBytes(path);
Assert.Throws<NewerFormatException>(() => ManifestStore.WriteSequence(path, newer));
Assert.BytesEqual(before, File.ReadAllBytes(path));
}
[Test]
public void DamagedJsonIsReportedAsInvalidData()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "{ \"id\": ");
Assert.Throws<InvalidDataException>(() => ManifestStore.ReadSequence(path));
File.WriteAllText(path, "{ \"title\": \"no id\" }");
Assert.Throws<InvalidDataException>(() => ManifestStore.ReadSequence(path));
}
[Test]
public void ACrashDuringAWriteLeavesThePreviousSidecarIntact()
{
var path = SidecarPath();
var first = Sample();
ManifestStore.WriteSequence(path, first);
// Simulated crash: the next version was half written to the temporary sibling and never renamed.
var torn = AtomicFile.TempPathFor(path);
File.WriteAllBytes(torn, Encoding.UTF8.GetBytes(Canonical(first with { Title = "Lost" })[..40]));
Assert.Equal(Canonical(first), Canonical(ManifestStore.ReadSequence(path)));
ManifestStore.WriteSequence(path, first with { Title = "Second" });
Assert.Equal("Second", ManifestStore.ReadSequence(path).Title);
Assert.FileExists(torn);
Assert.Equal(2, Directory.GetFiles(Path.GetDirectoryName(path)!).Length);
}
[Test]
public void CreatingASidecarClaimsTheFolderOnce()
{
var path = SidecarPath();
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var a = Sample();
var b = Sample();
Assert.True(ManifestStore.TryCreateSequence(path, a));
Assert.False(ManifestStore.TryCreateSequence(path, b));
Assert.Equal(a.Id, ManifestStore.ReadSequence(path).Id);
Assert.Count(1, Directory.GetFiles(Path.GetDirectoryName(path)!));
}
[Test]
public void ArchiveManifestRoundTripsAndKeepsUnknownFields()
{
var path = Path.Combine(context.CreateTempDirectory(), "archive.json");
File.WriteAllText(path, $$"""
{ "schemaVersion": 1, "id": "{{Guid.CreateVersion7()}}", "name": "Main", "created": "2026-10-02T09:00:00+00:00",
"layoutTemplates": { "folder": "{year}/{title}", "file": "{n:00000}" }, "proxyPolicy": { "longEdge": 2560, "quality": 90 },
"syncPolicy": "mirror" }
""");
var read = ManifestStore.ReadArchive(path);
Assert.Equal("{year}/{title}", read.LayoutTemplates.Folder);
Assert.Equal(2560, read.ProxyPolicy.LongEdge);
ManifestStore.WriteArchive(path, read with { Name = "Studio" });
Assert.Contains("syncPolicy", File.ReadAllText(path));
Assert.Equal("Studio", ManifestStore.ReadArchive(path).Name);
}
}
@@ -0,0 +1,51 @@
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
namespace Titano.Core.Tests.Archiving;
/// <summary>Small real JPEGs with Exif (capture time, camera) made by the in-house encoder; each seed gives distinct bytes.</summary>
internal static class TestPhotos
{
public static byte[] Jpeg(DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431",
int width = 48, int height = 32, int orientation = 1)
{
using var image = new ImageBuffer(width, height);
var random = new Random(seed);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
var level = (float)random.NextDouble();
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % width) / width);
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata
{
Make = make,
Model = model,
BodySerial = serial,
CapturedAt = captured,
ExposureTime = 1.0 / 125,
FNumber = 8,
Iso = 100,
Orientation = orientation,
});
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
public static string Write(string path, DateTime captured, int seed, string make = "Canon", string model = "Canon EOS R5", string? serial = "0431")
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllBytes(path, Jpeg(captured, seed, make, model, serial));
return path;
}
/// <summary>Writes <paramref name="count"/> photos named IMG_0001.JPG… taken every <paramref name="interval"/>.</summary>
public static List<string> WriteSeries(string directory, DateTime start, int count, TimeSpan interval, int firstSeed = 1, string prefix = "IMG_",
string make = "Canon", string model = "Canon EOS R5", int firstNumber = 1)
{
var paths = new List<string>(count);
for (var i = 0; i < count; i++)
paths.Add(Write(Path.Combine(directory, $"{prefix}{firstNumber + i:0000}.JPG"), start + interval * i, firstSeed + i, make, model));
return paths;
}
}
@@ -0,0 +1,165 @@
using Titano.Core.Archiving;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ThumbPackTests(TestContext context)
{
private static byte[] Payload(int seed, int length = 300)
{
var data = new byte[length];
new Random(seed).NextBytes(data);
return data;
}
private static byte[] Hash(int seed) => ThumbPack.Fingerprint(null, $"originals/{seed}.jpg", seed);
private string NewPack() => Path.Combine(context.CreateTempDirectory(), ".titano", "thumbs.pack");
private static void Fill(string path, int count, int seedOffset = 0)
{
using var writer = ThumbPackWriter.Open(path);
for (var i = 0; i < count; i++) writer.Append(i, 320, 213, Hash(i + seedOffset), Payload(i + seedOffset));
}
[Test]
public void EntriesAreReadBackByFrameIndex()
{
var path = NewPack();
Fill(path, 100);
using var reader = ThumbPackReader.Open(path);
Assert.Equal(100, reader.Entries.Count);
Assert.BytesEqual(Payload(57), reader.Read(57));
Assert.BytesEqual(Hash(57), reader.Entries[57].SourceHash);
Assert.Equal(320, reader.Entries[57].Width);
Assert.Null(reader.Read(100));
}
[Test]
public void AppendingAgainReplacesAFrameAndKeepsTheOthers()
{
var path = NewPack();
Fill(path, 3);
using (var writer = ThumbPackWriter.Open(path))
{
Assert.Equal(3, writer.Entries.Count);
writer.Append(1, 200, 100, Hash(99), Payload(99));
writer.Append(3, 200, 100, Hash(3), Payload(3));
}
using var reader = ThumbPackReader.Open(path);
Assert.Equal(4, reader.Entries.Count);
Assert.BytesEqual(Payload(99), reader.Read(1));
Assert.BytesEqual(Payload(0), reader.Read(0));
Assert.BytesEqual(Payload(3), reader.Read(3));
}
[Test]
public void AnIncompleteTailIsIgnoredAndTruncatedByTheNextWriter()
{
var path = NewPack();
Fill(path, 2);
var committed = new FileInfo(path).Length;
// Simulated crash mid-append: an entry header and part of its payload, no index.
using (var stream = new FileStream(path, FileMode.Append))
{
stream.Write("TENT"u8);
stream.Write(BitConverter.GetBytes(2));
stream.Write(new byte[30]);
}
using (var reader = ThumbPackReader.Open(path))
{
Assert.Equal(2, reader.Entries.Count);
Assert.BytesEqual(Payload(1), reader.Read(1));
}
using (var writer = ThumbPackWriter.Open(path))
{
Assert.Equal(committed, new FileInfo(path).Length);
writer.Append(2, 320, 213, Hash(2), Payload(2));
}
using var after = ThumbPackReader.Open(path);
Assert.Equal(3, after.Entries.Count);
Assert.BytesEqual(Payload(2), after.Read(2));
}
[Test]
public void EntriesWrittenAfterTheLastIndexAreFoundWithoutIt()
{
var path = NewPack();
Fill(path, 5);
// Simulated crash after new entries overwrote the old index but before the new index was written.
var withoutIndex = File.ReadAllBytes(path);
using (var reader = ThumbPackReader.Open(path))
{
var end = reader.Entries.Values.Max(e => e.Offset + e.Length);
File.WriteAllBytes(path, withoutIndex[..(int)end]);
}
using var scanned = ThumbPackReader.Open(path);
Assert.Equal(5, scanned.Entries.Count);
for (var i = 0; i < 5; i++) Assert.BytesEqual(Payload(i), scanned.Read(i));
}
[Test]
public void ADamagedThumbnailReadsAsMissing()
{
var path = NewPack();
Fill(path, 3);
long offset;
using (var reader = ThumbPackReader.Open(path)) offset = reader.Entries[1].Offset;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
stream.Position = offset + 10;
var b = stream.ReadByte();
stream.Position = offset + 10;
stream.WriteByte((byte)(b ^ 0xFF));
}
using var damaged = ThumbPackReader.Open(path);
Assert.Null(damaged.Read(1));
Assert.BytesEqual(Payload(2), damaged.Read(2));
}
[Test]
public void AnOpenReaderKeepsReadingWhileAWriterAppends()
{
var path = NewPack();
Fill(path, 3);
using var reader = ThumbPackReader.Open(path);
using (var writer = ThumbPackWriter.Open(path))
{
for (var i = 3; i < 50; i++) writer.Append(i, 320, 213, Hash(i), Payload(i, 2000));
}
Assert.BytesEqual(Payload(0), reader.Read(0));
Assert.BytesEqual(Payload(2), reader.Read(2));
using var fresh = ThumbPackReader.Open(path);
Assert.Equal(50, fresh.Entries.Count);
}
[Test]
public void CompactionDropsReplacedEntries()
{
var path = NewPack();
for (var round = 0; round < 4; round++) Fill(path, 20, seedOffset: round * 100);
long garbage;
using (var reader = ThumbPackReader.Open(path)) garbage = reader.GarbageBytes;
Assert.Greater(garbage, 0);
var before = new FileInfo(path).Length;
ThumbPackWriter.Compact(path);
Assert.Equal(before - garbage, new FileInfo(path).Length);
using var compacted = ThumbPackReader.Open(path);
Assert.Equal(0L, compacted.GarbageBytes);
for (var i = 0; i < 20; i++) Assert.BytesEqual(Payload(i + 300), compacted.Read(i));
}
[Test]
public void AMissingOrForeignFileReadsAsEmpty()
{
var path = NewPack();
using (var none = ThumbPackReader.Open(path)) Assert.Equal(0, none.Entries.Count);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "not a pack");
using (var foreign = ThumbPackReader.Open(path)) Assert.Equal(0, foreign.Entries.Count);
Fill(path, 1);
using var rewritten = ThumbPackReader.Open(path);
Assert.Equal(1, rewritten.Entries.Count);
}
}
@@ -0,0 +1,179 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Tests.Archiving;
using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class ImportExecutorTests(TestContext context)
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
private string Card(int frames = 70)
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, frames, Interval);
return card;
}
private static Task<ImportProgress> RunAsync(ImportPlan plan, IImportSink sink, int startAt = 0, Func<ImportBatch, ValueTask>? committed = null,
CancellationToken cancellationToken = default) =>
new ImportExecutor(plan, sink).RunAsync(startAt, verify: true, committed ?? (_ => ValueTask.CompletedTask), null, cancellationToken);
[Test]
public async Task VerifiedCopyHashesPreservesTheTimeAndNeverOverwrites()
{
var dir = context.CreateTempDirectory();
var source = TestPhotos.Write(Path.Combine(dir, "a.jpg"), Start, 1);
File.SetLastWriteTimeUtc(source, new DateTime(2026, 9, 28, 16, 0, 0, DateTimeKind.Utc));
var target = Path.Combine(dir, "copy", "a.jpg");
var sha = await VerifiedCopy.CopyAsync(source, target, verify: true);
Assert.Equal(await ContentHash.Sha256Async(source), sha);
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
Assert.Equal(File.GetLastWriteTimeUtc(source), File.GetLastWriteTimeUtc(target));
var other = TestPhotos.Write(Path.Combine(dir, "b.jpg"), Start, 2);
await Assert.ThrowsAsync<IOException>(() => VerifiedCopy.CopyAsync(other, target, verify: true));
Assert.BytesEqual(File.ReadAllBytes(source), File.ReadAllBytes(target));
await Assert.ThrowsAsync<FileNotFoundException>(() => VerifiedCopy.CopyAsync(Path.Combine(dir, "gone.jpg"), Path.Combine(dir, "c.jpg"), true));
Assert.FileMissing(Path.Combine(dir, "c.jpg"));
}
[Test]
public async Task APlanIsCopiedExactlyIntoAFolder()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
var batches = new List<ImportBatch>();
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
batches.Add(b);
return ValueTask.CompletedTask;
});
Assert.Equal(70, final.Copied);
Assert.Equal(plan.CopyBytes, final.BytesDone);
Assert.SequenceEqual(plan.Items.Select(i => plan.Sessions[0].Folder + "/" + i.FileName).Order(StringComparer.Ordinal), Files(destination));
Assert.Equal(70, batches[^1].NextItem);
Assert.True(batches.Count >= 3);
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
foreach (var item in plan.Items)
{
Assert.BytesEqual(File.ReadAllBytes(Path.Combine(card, item.SourcePath)),
File.ReadAllBytes(Path.Combine(destination, plan.Sessions[0].Folder, item.FileName)));
}
}
[Test]
public async Task AnInterruptedImportResumesFromItsLastBatch()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
using var cts = new CancellationTokenSource();
var checkpoint = 0;
await Assert.ThrowsAsync<OperationCanceledException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
checkpoint = b.NextItem;
cts.Cancel();
return ValueTask.CompletedTask;
}, cancellationToken: cts.Token));
Assert.True(checkpoint is > 0 and < 70);
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
Assert.Equal(70 - checkpoint, final.Copied);
var reference = context.CreateTempDirectory("reference");
await RunAsync(await PlanAsync(card, reference), new FolderImportSink(reference));
Assert.SequenceEqual(Files(reference), Files(destination));
}
[Test]
public async Task RepeatingCommittedItemsYieldsDuplicatesNotSecondCopies()
{
var card = Card(20);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
await RunAsync(plan, new FolderImportSink(destination));
var again = await RunAsync(plan, new FolderImportSink(destination), startAt: 10);
Assert.Equal(0, again.Copied);
Assert.Equal(10, again.Skipped);
Assert.Equal(20, Files(destination).Count);
}
[Test]
public async Task ARemovedCardStopsTheImportWhichResumesOnReinsertion()
{
var card = Card();
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
var aside = card + "-removed";
var checkpoint = 0;
await Assert.ThrowsAsync<ImportSourceUnavailableException>(() => RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
checkpoint = b.NextItem;
if (Directory.Exists(card)) Directory.Move(card, aside); // the card is pulled after the first batch
return ValueTask.CompletedTask;
}));
Assert.Equal(checkpoint, Files(destination).Count);
Assert.Empty(Directory.EnumerateFiles(new FolderImportSink(destination).StagingDirectory));
Directory.Move(aside, card);
var final = await RunAsync(plan, new FolderImportSink(destination), startAt: checkpoint);
Assert.Equal(70 - checkpoint, final.Copied);
Assert.Equal(70, Files(destination).Count);
}
[Test]
public async Task AFileThatChangedSinceThePlanFailsAloneAndTheRestIsCopied()
{
var card = Card(20);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination);
File.AppendAllText(Path.Combine(card, plan.Sessions[0].Items[5].SourcePath), "edited");
var failed = new List<ImportItemResult>();
var final = await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
failed.AddRange(b.Results.Where(r => r.Status == ImportItemStatus.Failed));
return ValueTask.CompletedTask;
});
Assert.Equal(19, final.Copied);
Assert.Equal(1, final.Failed);
Assert.Equal(plan.Sessions[0].Items[5].SourcePath, failed.Single().Item.SourcePath);
}
[Test]
public async Task ErasingDeletesOnlyFilesWhoseCardAndCopyStillMatch()
{
var card = Card(6);
var destination = context.CreateTempDirectory("dest");
var plan = await PlanAsync(card, destination, new ImportOptions { MinimumSessionFrames = 1 });
var results = new List<ImportItemResult>();
await RunAsync(plan, new FolderImportSink(destination), committed: b =>
{
results.AddRange(b.Results);
return ValueTask.CompletedTask;
});
var candidates = results.Select(r => new EraseCandidate(r.Item.SourcePath, r.Item.Size, r.Sha256!, Path.Combine(destination, r.Commit!.RelativePath)))
.ToList();
// Copy of item 1 damaged after import, card file of item 2 edited, copy of item 3 deleted.
var damaged = File.ReadAllBytes(candidates[1].CopyPath);
damaged[^10] ^= 0xFF;
File.WriteAllBytes(candidates[1].CopyPath, damaged);
File.AppendAllText(Path.Combine(card, candidates[2].SourcePath), "x");
File.Delete(candidates[3].CopyPath);
var erase = await CardEraser.PlanAsync(card, candidates);
Assert.SequenceEqual(
[EraseVerdict.Delete, EraseVerdict.CopyMismatch, EraseVerdict.SourceChanged, EraseVerdict.CopyMissing, EraseVerdict.Delete, EraseVerdict.Delete],
erase.Items.Select(i => i.Verdict));
Assert.Equal(6, Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Count());
var done = CardEraser.Execute(erase);
Assert.Equal(3, done.Deleted);
Assert.Equal(3, done.Kept.Count);
var left = Directory.EnumerateFiles(card, "*.JPG", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(card, f).Replace('\\', '/')).Order();
Assert.SequenceEqual(candidates.Skip(1).Take(3).Select(c => c.SourcePath).Order(), left);
}
}
@@ -0,0 +1,160 @@
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Tests.Archiving;
using Titano.Testing;
using static Titano.Core.Tests.Import.ImportTestKit;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class ImportPlannerTests(TestContext context)
{
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(10);
[Test]
public async Task ADcimCardIsPlannedWithTheDefaultTemplates()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), Start, 10, Interval);
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "._IMG_0001.JPG"), [0, 5, 22]);
File.WriteAllText(Path.Combine(card, "DCIM", "100CANON", "notes.txt"), "x");
TestPhotos.Write(Path.Combine(card, "MISC", "IMG_9999.JPG"), Start, 99);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var session = plan.Sessions.Single();
Assert.Equal("2026/2026-09-28 Canon EOS R5", session.Folder);
Assert.Equal(10, plan.FileCount);
Assert.Equal(10, plan.CopyCount);
Assert.SequenceEqual(
["2026-09-28_18-00-00_0001.JPG", "2026-09-28_18-00-10_0002.JPG", "2026-09-28_18-00-20_0003.JPG"],
session.Items.Take(3).Select(i => i.FileName));
Assert.Equal("DCIM/100CANON/IMG_0001.JPG", session.Items[0].SourcePath);
Assert.Equal(plan.Items.Sum(i => i.Size), plan.CopyBytes);
Assert.NotNull(plan.AvailableBytes);
Assert.True(plan.HasEnoughSpace);
Assert.Empty(plan.Problems);
}
[Test]
public async Task AFlatFolderIncludesSubfoldersOnlyWhenAsked()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
TestPhotos.WriteSeries(Path.Combine(card, "more"), Start.AddSeconds(80), 8, Interval, firstSeed: 50, firstNumber: 9);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(16, (await PlanAsync(card, destination)).FileCount);
Assert.Equal(8, (await PlanAsync(card, destination, new ImportOptions { IncludeSubfolders = false })).FileCount);
}
[Test]
public async Task SessionsAreSplitPerCameraBodyAndNumberedFromOne()
{
var card = context.CreateTempDirectory("card");
var dcim = Path.Combine(card, "DCIM", "100MEDIA");
TestPhotos.WriteSeries(dcim, Start, 10, Interval, prefix: "CAN_");
TestPhotos.WriteSeries(dcim, Start.AddHours(2), 10, Interval, firstSeed: 20, prefix: "CAN_", firstNumber: 11);
TestPhotos.WriteSeries(dcim, Start.AddSeconds(5), 9, Interval, firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
Assert.SequenceEqual(
["2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Nikon Z 8", "2026/2026-09-28 Canon EOS R5 (2)"],
plan.Sessions.Select(s => s.Folder));
Assert.SequenceEqual([1, 2, 3], plan.Sessions.Select(s => s.Number));
Assert.Equal("2026-09-28_20-00-00_0001.JPG", plan.Sessions[2].Items[0].FileName);
Assert.Equal(3, plan.Sessions.Select(s => s.SessionKey).Distinct().Count());
Assert.True(plan.Sessions.All(s => s.Items.All(i => i.SourcePath.Contains(s.CameraModel == "NIKON Z 8" ? "NIK_" : "CAN_"))));
}
[Test]
public async Task NamesTakenTwiceGetASuffix()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 3, Interval);
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = "{date}", MinimumSessionFrames = 1 });
Assert.SequenceEqual(["2026-09-28.JPG", "2026-09-28_2.JPG", "2026-09-28_3.JPG"], plan.Sessions[0].Items.Select(i => i.FileName));
}
[Test]
public async Task ImportedAndArchivedPhotosAreSkippedAfterAHashMatch()
{
var card = context.CreateTempDirectory("card");
var files = TestPhotos.WriteSeries(card, Start, 10, Interval);
var lookup = new FakeLookup();
lookup.Imported.Add("IMG_0001.JPG");
var archived = await ContentHash.Sha256Async(files[1]);
lookup.Archive.Add((new FileInfo(files[1]).Length, Start + Interval, new ArchiveMatch(Guid.NewGuid(), archived)));
lookup.Archive.Add((new FileInfo(files[2]).Length, Start + 2 * Interval, new ArchiveMatch(Guid.NewGuid(), new string('0', 64))));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), lookup: lookup);
var items = plan.Sessions[0].Items;
Assert.Equal(ImportAction.SkipImported, items[0].Action);
Assert.Equal(ImportAction.SkipInArchive, items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, items[1].ExistingFrameId);
Assert.Equal(ImportAction.Copy, items[2].Action);
Assert.Equal(await ContentHash.Sha256Async(files[2]), items[2].Sha256);
Assert.Null(items[3].Sha256);
Assert.Equal(8, plan.CopyCount);
Assert.Equal("2026-09-28_18-00-10_0002.JPG", items[1].FileName);
var again = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { Duplicates = DuplicatePolicy.ImportAgain }, lookup);
Assert.Equal(ImportAction.Copy, again.Sessions[0].Items[1].Action);
Assert.Equal(lookup.Archive[0].Match.FrameId, again.Sessions[0].Items[1].ExistingFrameId);
}
[Test]
public async Task ReplanningGivesStableKeysThatTitlesAndEarlierFoldersAttachTo()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
var destination = context.CreateTempDirectory("archive");
var first = await PlanAsync(card, destination);
var key = first.Sessions[0].SessionKey;
Assert.Equal(key, (await PlanAsync(card, destination)).Sessions[0].SessionKey);
var titled = await PlanAsync(card, destination, new ImportOptions
{
FolderTemplate = "{year}/{date} {title}",
Titles = new Dictionary<string, string> { [key] = "Harbour sunset" },
});
Assert.Equal("2026/2026-09-28 Harbour sunset", titled.Sessions[0].Folder);
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
var lookup = new FakeLookup();
lookup.SessionFolders[key] = "2026/earlier import";
Assert.Equal("2026/earlier import", (await PlanAsync(card, destination, lookup: lookup)).Sessions[0].Folder);
var taken = new FakeLookup();
taken.TakenFolders.Add("2026/2026-09-28 Canon EOS R5");
Assert.Equal("2026/2026-09-28 Canon EOS R5 (2)", (await PlanAsync(card, destination, lookup: taken)).Sessions[0].Folder);
}
[Test]
public async Task UserMergeAndSplitReshapeSessions()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 10, Interval);
TestPhotos.WriteSeries(card, Start.AddHours(3), 10, Interval, firstSeed: 30, firstNumber: 11);
var destination = context.CreateTempDirectory("archive");
Assert.Equal(2, (await PlanAsync(card, destination)).Sessions.Count);
var merged = await PlanAsync(card, destination, new ImportOptions { MergeAt = new HashSet<string> { "IMG_0011.JPG" } });
Assert.Equal(20, merged.Sessions.Single().Items.Count);
Assert.Equal("2026-09-28_21-00-00_0011.JPG", merged.Sessions[0].Items[10].FileName);
var split = await PlanAsync(card, destination, new ImportOptions { SplitBefore = new HashSet<string> { "IMG_0006.JPG" } });
Assert.SequenceEqual([5, 5, 10], split.Sessions.Select(s => s.Items.Count));
}
[Test]
public async Task APhotoWithoutExifIsPlannedAtItsFileTime()
{
var card = context.CreateTempDirectory("card");
TestPhotos.WriteSeries(card, Start, 8, Interval);
var bare = Path.Combine(card, "BARE.JPG");
File.WriteAllBytes(bare, [0xFF, 0xD8, 0xFF, 0xD9]);
File.SetLastWriteTime(bare, Start.AddSeconds(85));
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"));
var item = plan.Items.Single(i => i.SourcePath == "BARE.JPG");
Assert.Equal(Start.AddSeconds(85), item.CapturedAt);
// No camera identity: it forms its own body group rather than joining the Canon session.
Assert.SequenceEqual([8, 1], plan.Sessions.Select(s => s.Items.Count));
}
}
@@ -0,0 +1,48 @@
using Titano.Core.Import;
namespace Titano.Core.Tests.Import;
/// <summary>An <see cref="IImportLookup"/> answered from in-memory sets.</summary>
internal sealed class FakeLookup : IImportLookup
{
public HashSet<string> Imported { get; } = [];
public List<(long Size, DateTime Captured, ArchiveMatch Match)> Archive { get; } = [];
public Dictionary<string, string> SessionFolders { get; } = [];
public HashSet<string> TakenFolders { get; } = new(StringComparer.OrdinalIgnoreCase);
public int CandidateQueries { get; private set; }
public Task<bool> WasImportedAsync(CardFile file, CancellationToken cancellationToken) => Task.FromResult(Imported.Contains(file.RelativePath));
public Task<IReadOnlyList<ArchiveMatch>> FindCandidatesAsync(long size, DateTime capturedAt, CancellationToken cancellationToken)
{
CandidateQueries++;
return Task.FromResult<IReadOnlyList<ArchiveMatch>>(Archive.Where(a => a.Size == size && a.Captured == capturedAt).Select(a => a.Match).ToList());
}
public Task<string?> FindSessionFolderAsync(string sessionKey, CancellationToken cancellationToken) =>
Task.FromResult(SessionFolders.GetValueOrDefault(sessionKey));
public bool IsFolderTaken(string folder) => TakenFolders.Contains(folder);
}
internal static class ImportTestKit
{
public static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
/// <summary>Plans an import of <paramref name="card"/> into <paramref name="destination"/>.</summary>
public static async Task<ImportPlan> PlanAsync(string card, string destination, ImportOptions? options = null, FakeLookup? lookup = null)
{
options ??= new ImportOptions();
var problems = new List<ImportProblem>();
var photos = CardScanner.ReadMetadata(card, CardScanner.Find(card, options.IncludeSubfolders), problems);
return await ImportPlanner.PlanAsync(card, destination, photos, problems, options, lookup ?? new FakeLookup());
}
/// <summary>Every file below <paramref name="root"/> (relative, forward slashes), excluding Titano's metadata folders.</summary>
public static List<string> Files(string root) =>
Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
.Select(f => Path.GetRelativePath(root, f).Replace('\\', '/'))
.Where(f => !f.StartsWith(".titano/", StringComparison.Ordinal))
.Order(StringComparer.Ordinal)
.ToList();
}
@@ -0,0 +1,73 @@
using Titano.Core.Import;
using Titano.Testing;
namespace Titano.Core.Tests.Import;
[Category("import")]
public sealed class SessionSplitterTests
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static readonly TimeSpan Gap = TimeSpan.FromMinutes(45);
/// <summary>Capture times from a compact description: runs of frames 10 s apart, separated by pauses in minutes.</summary>
private static List<DateTime> Times(params (int Frames, int PauseBeforeMinutes)[] runs)
{
var times = new List<DateTime>();
var t = Start;
foreach (var (frames, pause) in runs)
{
t = t.AddMinutes(pause);
for (var i = 0; i < frames; i++)
{
times.Add(t);
t = t.AddSeconds(10);
}
}
return times;
}
private static string Describe(IReadOnlyList<SessionRange> ranges) => string.Join(",", ranges.Select(r => r.Count));
[Theory]
[Case(new[] { 30 }, new[] { 0 }, "30", Name = "one session")]
[Case(new[] { 30, 40 }, new[] { 0, 60 }, "30,40", Name = "pause longer than the gap splits")]
[Case(new[] { 30, 40 }, new[] { 0, 44 }, "70", Name = "pause shorter than the gap does not")]
[Case(new[] { 3, 30 }, new[] { 0, 90 }, "33", Name = "leading test shots join the next session")]
[Case(new[] { 30, 3 }, new[] { 0, 90 }, "33", Name = "trailing test shots join the previous session")]
[Case(new[] { 30, 2, 30 }, new[] { 0, 90, 90 }, "32,30", Name = "small middle group joins the previous session")]
[Case(new[] { 2, 3 }, new[] { 0, 90 }, "5", Name = "only small groups make one session")]
public void AutomaticSessions(int[] frames, int[] pauses, string expected)
{
var times = Times(frames.Zip(pauses).ToArray());
Assert.Equal(expected, Describe(SessionSplitter.Split(times, Gap, 8)));
}
[Test]
public void APauseOfExactlyTheGapDoesNotSplit()
{
var times = new List<DateTime> { Start };
for (var i = 1; i < 10; i++) times.Add(Start.AddSeconds(i));
for (var i = 0; i < 10; i++) times.Add(times[9] + Gap + TimeSpan.FromSeconds(i));
Assert.Equal("20", Describe(SessionSplitter.Split(times, Gap, 8)));
}
[Test]
public void UserSplitsAndMergesOverrideTheRules()
{
var times = Times((30, 0), (40, 60));
// Split before frame 25 (a 5-frame group the user wants on its own) and merge the automatic break at 30.
var ranges = SessionSplitter.Split(times, Gap, 8, i => i == 25 ? true : i == 30 ? false : null);
Assert.Equal("25,45", Describe(ranges));
Assert.Equal(25, ranges[1].Start);
}
[Test]
public void AForcedSmallSessionIsNotMergedAway()
{
var times = Times((30, 0));
Assert.Equal("28,2", Describe(SessionSplitter.Split(times, Gap, 8, i => i == 28 ? true : null)));
}
[Test]
public void NoFramesNoSessions() => Assert.Empty(SessionSplitter.Split([], Gap, 8));
}