merge: card import and archive manager screens (card pool, plan, verified erase and format, server destination, tree, charts, maintenance)

Union of the Tooltips resources; sample data keeps the sync server and the
simulated cards; the import test names App.Infrastructure.Formatting fully now
that a test namespace of the same name exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 11:01:34 +00:00
commit 828c64a485
57 files changed
+8742 -23

No files matched your search

@@ -0,0 +1,294 @@
using System.Globalization;
using Titano.App.Archiving;
using Titano.App.Library;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
using Titano.Testing;
namespace Titano.App.Tests.Archiving;
public sealed class ArchiveLogicTests
{
private static readonly Core.Model.Archive Main = new() { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = "/archive" };
public ArchiveLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static Sequence Seq(string title, DateTime? first, int frames = 100, long bytes = 1_000_000, params string[] tags) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Main.Id,
Title = title,
Folder = $"{first?.Year.ToString(CultureInfo.InvariantCulture) ?? "misc"}/{title}",
FirstCapture = first,
FrameCount = frames,
TotalBytes = bytes,
Tags = tags,
};
[Test]
public void TheTreeGroupsByYearNewestFirstWithUndatedLast()
{
var a = Seq("Harbour", new DateTime(2026, 9, 28), 3_600, 72_000_000_000);
var b = Seq("Comet", new DateTime(2026, 8, 13));
var c = Seq("Stars", new DateTime(2025, 8, 2));
var d = Seq("Scans", null);
var tree = ArchiveTree.Build(Main, ArchiveAvailability.Online, [c, d, b, a]);
Assert.Equal("TitanoArchive", tree.Root.Title);
Assert.SequenceEqual(new[] { "2026", "2025", "Undated" }, tree.Root.Children.Select(n => n.Title));
Assert.SequenceEqual(new[] { "Harbour", "Comet" }, tree.Root.Children[0].Children.Select(n => n.Title));
Assert.Equal("3,600 photos · 72 GB", tree.Root.Children[0].Children[0].Detail);
Assert.Equal("2 sequences · 72 GB", tree.Root.Children[0].Detail);
// Collapsed years show only themselves; expanding one reveals its sequences.
Assert.Equal(4, tree.Visible().Count);
tree.Root.Children[1].IsExpanded = true;
Assert.SequenceEqual(new[] { "TitanoArchive", "2026", "2025", "Stars", "Undated" }, tree.Visible().Select(n => n.Title));
var expanded = tree.ExpandedKeys();
var rebuilt = ArchiveTree.Build(Main, ArchiveAvailability.ReadOnly, [a, b, c, d]);
rebuilt.Expand(expanded);
Assert.Equal(5, rebuilt.Visible().Count);
Assert.Equal(ArchiveAvailability.ReadOnly, rebuilt.Availability);
}
[Test]
public void TheMassOperationSetIsTheSelectionOrEverything()
{
var a = Seq("Harbour", new DateTime(2026, 9, 28));
var b = Seq("Comet", new DateTime(2026, 8, 13));
var c = Seq("Stars", new DateTime(2025, 8, 2));
var tree = ArchiveTree.Build(Main, ArchiveAvailability.Online, [a, b, c]);
Assert.Equal(3, ArchiveTree.SetOf(tree, []).Count);
var year = tree.Root.Children[0];
Assert.SequenceEqual(new[] { a.Id, b.Id }, ArchiveTree.SetOf(tree, [year]).Select(s => s.Id));
// A year and one of its sequences count that sequence once.
Assert.Equal(2, ArchiveTree.SetOf(tree, [year, year.Children[1]]).Count);
Assert.Equal(3, ArchiveTree.SetOf(tree, [tree.Root]).Count);
}
private static ArchiveStats Stats() => new(
Sequences: 12,
Photos: 10_000,
Bytes: 9_400_000_000_000,
ByYear: [new YearBucket(2026, 8, 6_000, 2_100_000_000_000), new YearBucket(2024, 4, 4_000, 1_400_000_000_000)],
ByMonth: [new MonthBucket(2024, 3, 2, 1_000), new MonthBucket(2026, 7, 5, 5_000), new MonthBucket(2026, 9, 1, 2_000)],
ByCamera:
[
new CameraBucket("Canon", "Canon EOS R5", 4, 4_100, 0),
new CameraBucket("SONY", "ILCE-7M4", 2, 2_200, 0),
new CameraBucket("NIKON CORPORATION", "NIKON Z 8", 2, 1_400, 0),
new CameraBucket("GoPro", "HERO12 Black", 1, 900, 0),
new CameraBucket("Apple", "iPhone 16 Pro", 1, 600, 0),
new CameraBucket("DJI", "Osmo Action 5 Pro", 1, 500, 0),
new CameraBucket(null, null, 1, 300, 0),
],
ByFormat:
[
new FormatBucket(ImageFileFormat.Cr2, 3_800, 0),
new FormatBucket(ImageFileFormat.Arw, 2_100, 0),
new FormatBucket(ImageFileFormat.Jpeg, 2_000, 0),
new FormatBucket(ImageFileFormat.Nef, 1_400, 0),
new FormatBucket(ImageFileFormat.Dng, 400, 0),
new FormatBucket(ImageFileFormat.Heif, 200, 0),
new FormatBucket(ImageFileFormat.ThreeFr, 60, 0),
new FormatBucket(ImageFileFormat.Unknown, 40, 0),
],
Health: new ArchiveHealth(Unverified: 3, WithWarnings: 1, WithErrors: 0, NotAnalyzed: 2, MissingFrames: 0, CorruptFrames: 0, DuplicateFrames: 5));
[Test]
public void TheSetFilterNarrowsByCameraStatusAndTag()
{
var canon = Seq("Harbour", new DateTime(2026, 9, 28), tags: "sunset") with
{
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
Status = SequenceStatus.AnalyzedLight | SequenceStatus.ProxiesBuilt,
};
var sony = Seq("Comet", new DateTime(2026, 8, 13), tags: "night") with { CameraMake = "SONY", CameraModel = "ILCE-7M4" };
var unknown = Seq("Old", null);
Assert.True(new ArchiveSetFilter().IsEmpty);
Assert.True(new ArchiveSetFilter().Matches(unknown), "no filter keeps everything");
var byCamera = new ArchiveSetFilter(Camera: ArchiveSetFilter.CameraOf(canon));
Assert.True(byCamera.Matches(canon));
Assert.False(byCamera.Matches(sony));
Assert.Equal(Loc.L("Archive.Chart.UnknownCamera"), ArchiveSetFilter.CameraOf(unknown));
Assert.True(new ArchiveSetFilter(Status: StatusFilter.NotAnalysed).Matches(sony));
Assert.False(new ArchiveSetFilter(Status: StatusFilter.NotAnalysed).Matches(canon));
Assert.True(new ArchiveSetFilter(Status: StatusFilter.Proxies).Matches(canon));
Assert.True(new ArchiveSetFilter(Tag: "SUNSET").Matches(canon), "tags compare without case");
Assert.False(new ArchiveSetFilter(Tag: "sunset").Matches(sony));
Assert.Equal(ArchiveSetFilter.CameraOf(canon) + " · Not analysed · sunset",
new ArchiveSetFilter(ArchiveSetFilter.CameraOf(canon), StatusFilter.NotAnalysed, "sunset").Describe());
Assert.Equal(string.Empty, new ArchiveSetFilter().Describe());
}
[Test]
public void ChartsAggregateYearsCamerasAndFormats()
{
var stats = Stats();
var years = ArchiveFigures.StorageByYear(stats);
Assert.SequenceEqual(new[] { "2024", "2026" }, years.Select(b => b.Label));
Assert.Equal("2.1 TB", years[1].ValueText);
var cameras = ArchiveFigures.ByCamera(stats);
Assert.Equal(ArchiveFigures.TopCameras + 1, cameras.Count);
Assert.Equal("Canon EOS R5", cameras[0].Label);
Assert.Equal("41 %", cameras[0].ValueText);
Assert.Equal("SONY ILCE-7M4", cameras[1].Label);
Assert.Equal("Nikon Z 8", cameras[2].Label);
Assert.Equal("2 others", cameras[^1].Label);
Assert.Equal(800, cameras[^1].Value);
Assert.Equal(stats.Photos, (long)cameras.Sum(c => c.Value));
var formats = ArchiveFigures.ByFormat(stats);
Assert.SequenceEqual(new[] { "CR2", "ARW", "JPEG", "NEF", "DNG", "HEIF", "Other" }, formats.Select(f => f.Label));
Assert.Equal(100, formats[^1].Value);
Assert.Equal("3FR", ArchiveFigures.FormatName(ImageFileFormat.ThreeFr));
}
[Test]
public void ThePhotosPerMonthHeatmapHasOneRowPerYearAndNoFuture()
{
var rows = ArchiveFigures.PhotosPerMonth(Stats(), new DateTime(2026, 10, 2));
Assert.SequenceEqual(new[] { "2024", "2025", "2026" }, rows.Select(r => r.Label));
Assert.Equal(1_000, rows[0].Values[2]);
Assert.Equal(0, rows[1].Values[5]);
Assert.Equal(5_000, rows[2].Values[6]);
Assert.Equal(0, rows[2].Values[9]);
Assert.True(double.IsNaN(rows[2].Values[10]));
Assert.Null(rows[2].ToolTips[11]);
Assert.Equal("July 2026 · 5,000 photos · 5 sequences", rows[2].ToolTips[6]);
Assert.Equal(12, ArchiveFigures.MonthLabels().Count);
Assert.Equal("J", ArchiveFigures.MonthLabels()[0]);
Assert.Empty(ArchiveFigures.PhotosPerMonth(Stats() with { ByMonth = [] }, DateTime.Today));
}
[Test]
public void TilesAndHealthSummariseTheIndex()
{
var tiles = ArchiveFigures.Tiles(Stats());
Assert.Equal(5, tiles.Count);
Assert.Equal("10,000", tiles[0].Value);
Assert.Equal("9.4 TB", tiles[2].Value);
Assert.Equal("6", tiles[3].Value);
Assert.Equal("cameras · 8 formats", tiles[3].Caption);
Assert.Equal("2024 – 2026", tiles[4].Value);
var health = ArchiveFigures.Health(Stats(), withoutProxies: 0);
Assert.Equal(HealthAction.Verify, health[0].Action);
Assert.False(health[0].IsOk);
Assert.Equal("3 sequences unverified", health[0].Text);
Assert.True(health[1].IsOk);
Assert.True(health[2].IsOk);
Assert.Equal(HealthAction.Analyse, health[3].Action);
Assert.Equal(HealthAction.Duplicates, health[4].Action);
}
[Test]
public void RenameTemplatesAreCheckedAndThePlanListedByMode()
{
Assert.Null(MassRename.Validate(RenameMode.Titles, "{title} · {camera}"));
Assert.NotNull(MassRename.Validate(RenameMode.Titles, "{title"));
Assert.NotNull(MassRename.Validate(RenameMode.Titles, " "));
Assert.Null(MassRename.Validate(RenameMode.Folders, "{year}/{date} {title}"));
Assert.NotNull(MassRename.Validate(RenameMode.Folders, "{nope}"));
var a = Seq("Harbour", new DateTime(2026, 9, 28));
var b = Seq("Comet", new DateTime(2026, 8, 13));
var subjects = new[] { a, b }.Select(s => new RenameSubject(s.Id, s.Folder, s.Title, s.FirstCapture, "Canon", "Canon EOS R5", null)).ToList();
var titles = RenamePlanner.Plan(Main.Id, subjects, null, "{title} · {camera}", subjects.Select(s => s.Folder), _ => false);
var rows = MassRename.Rows(titles, RenameMode.Titles);
Assert.Equal("Harbour", rows[0].From);
Assert.Equal("Harbour · Canon EOS R5", rows[0].To);
Assert.Equal("2 of 5 change", MassRename.Summary(titles, 5));
Assert.Empty(RenamePlanner.Plan(Main.Id, subjects, "{year}/{title}", null, subjects.Select(s => s.Folder), _ => false).Steps);
var folders = RenamePlanner.Plan(Main.Id, subjects, "{year}/{date} {title}", null, subjects.Select(s => s.Folder), _ => false);
var moves = MassRename.Rows(folders, RenameMode.Folders);
Assert.SequenceEqual(new[] { "2026/Harbour", "2026/Comet" }, moves.Select(r => r.From));
Assert.SequenceEqual(new[] { "2026/2026-09-28 Harbour", "2026/2026-08-13 Comet" }, moves.Select(r => r.To));
}
[Test]
public void RetagAddsAndRemovesWithoutDuplicates()
{
Assert.SequenceEqual(new[] { "sunset", "harbour", "Holy grail" }, Retag.Parse(" sunset, harbour; Holy grail ,SUNSET"));
Assert.Empty(Retag.Parse(" "));
Assert.Null(Retag.Validate("sunset, dusk"));
Assert.NotNull(Retag.Validate(new string('x', 65)));
Assert.Empty(Retag.Parse(new string('x', 65)));
Assert.SequenceEqual(new[] { "harbour", "dusk" }, Retag.Apply(["Sunset", "harbour"], ["dusk", "HARBOUR"], ["sunset"]));
var a = Seq("A", DateTime.Today, tags: ["sunset"]);
var b = Seq("B", DateTime.Today, tags: ["dusk"]);
var changes = Retag.Changes([a, b], ["dusk"], []);
Assert.Equal(a.Id, changes.Single().Sequence.Id);
Assert.SequenceEqual(new[] { "sunset", "dusk" }, changes.Single().Tags);
}
[Test]
public void ReportsListDuplicatesOrphansAndRecentMaintenance()
{
var a = Seq("Harbour", new DateTime(2026, 9, 28));
var b = Seq("Comet", new DateTime(2026, 8, 13));
var locations = new[] { new SequenceLocation(a.Id, a.Folder, a.Title), new SequenceLocation(b.Id, b.Folder, null) };
var groups = new[]
{
new DuplicateGroup("ab", [new DuplicateFrame("ab", Guid.NewGuid(), a.Id, 0, a.Folder + "/originals/IMG_1.CR2"),
new DuplicateFrame("ab", Guid.NewGuid(), b.Id, 4, b.Folder + "/originals/IMG_9.CR2")]),
new DuplicateGroup("cd", [new DuplicateFrame("cd", Guid.NewGuid(), a.Id, 1, a.Folder + "/originals/IMG_2.CR2")]),
};
var duplicates = MaintenanceReports.Duplicates(groups, locations);
Assert.Equal("IMG_1.CR2", duplicates.Single().Title);
Assert.Equal("2 copies", duplicates.Single().Detail);
Assert.Equal(a.Id, duplicates.Single().SequenceId);
Assert.Contains("Comet", duplicates.Single().Places[1]);
var report = new OrphanReport(
[new SequenceOrphans(a.Folder, ["IMG_7.CR2", "IMG_8.CR2"], [])],
[new SequenceLocation(Guid.NewGuid(), "2024/Gone", "Gone")],
["2026/New shoot"]);
var orphans = MaintenanceReports.Orphans(report, locations);
Assert.SequenceEqual(new[] { OrphanKind.UnlistedFiles, OrphanKind.MissingSequence, OrphanKind.NewFolder }, orphans.Select(o => o.Kind));
Assert.Equal("2 photos not in sidecar", orphans[0].Detail);
Assert.Equal(a.Id, orphans[0].SequenceId);
Assert.Null(orphans[2].SequenceId);
var now = DateTimeOffset.UtcNow;
var jobs = new[]
{
new Job { Id = Guid.NewGuid(), Kind = JobKind.Verify, State = JobState.Running, ProgressDone = 71, ProgressTotal = 100, TargetLabel = "TitanoArchive", Created = now },
new Job { Id = Guid.NewGuid(), Kind = JobKind.Scan, State = JobState.Done, Created = now.AddDays(-2), Finished = now.AddDays(-2) },
};
var recent = MaintenanceReports.Recent(jobs, 5);
Assert.Equal("Verify · TitanoArchive", recent[0].Text);
Assert.Equal("71 %", recent[0].StateText);
Assert.Equal(JobState.Done, recent[1].State);
}
[Test]
public void TheScreensWorkOnTheRememberedArchiveElseTheFirst()
{
var other = Main with { Id = Guid.CreateVersion7(), Name = "Travel", RootPath = "/media/travel" };
Assert.Null(CurrentArchive.Pick([], "/archive"));
Assert.Equal(other.Id, CurrentArchive.Pick([Main, other], "/media/travel/")!.Id);
Assert.Equal(Main.Id, CurrentArchive.Pick([Main, other], "/elsewhere")!.Id);
Assert.Equal(Main.Id, CurrentArchive.Pick([Main, other], null)!.Id);
}
[Test]
public void TheSampleReportsFillEveryKindOfReportRow()
{
var locations = Enumerable.Range(1, 6).Select(i => new SequenceLocation(Guid.CreateVersion7(), $"2026/Shoot {i}", $"Shoot {i}")).ToList();
Assert.Equal("2 copies", MaintenanceReports.Duplicates(SampleReports.Duplicates(locations), locations).Single().Detail);
Assert.SequenceEqual(new[] { OrphanKind.UnlistedFiles, OrphanKind.MissingSequence, OrphanKind.NewFolder },
MaintenanceReports.Orphans(SampleReports.Orphans(locations), locations).Select(o => o.Kind));
var folders = SampleReports.Folders(locations);
Assert.Equal(4, folders.Count(f => f.Sidecar is not null));
Assert.Equal(2, folders.Count(f => f.Sidecar is null));
}
}
@@ -0,0 +1,83 @@
using System.Windows.Controls;
using System.Windows.Input;
using Titano.App.Archiving;
using Titano.App.Sections;
using Titano.App.Tests.Windows;
using Titano.Testing;
using Titano.Ui.Controls;
namespace Titano.App.Tests.Archiving;
/// <summary>
/// Every Archive view of <c>--capture</c> (<see cref="ArchiveScenes"/>) on the sample archive, rendered in both themes
/// in the real main window, with what each view must show — and the buttons really enabled, not only their commands.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ArchiveScreenSmokeTests
{
[Test]
public Task EveryArchiveViewRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var archive = app.Shell.Archive;
await ArchiveScenes.ShowAsync(app.Shell, "overview");
Assert.True(archive.IsOverview);
Assert.True(archive.TreeRows[0].IsArchive);
Assert.Equal(StatusKind.Online, archive.TreeRows[0].AvailabilityKind);
Assert.True(archive.TreeRows[1].IsYear);
Assert.True(archive.TreeRows[1].IsExpanded, "the newest year opens with the screen");
Assert.Equal(5, archive.Tiles.Count);
Assert.Equal(2, archive.MonthRows.Count, "one heatmap row per year, 2025 and 2026");
Assert.NotEmpty(archive.StorageBars);
Assert.NotEmpty(archive.CameraBars);
Assert.NotEmpty(archive.FormatBars);
Assert.True(archive.ScanCommand.CanExecute(null), "an online archive can be scanned");
await app.ExpectAsync<ArchiveView>("archive-overview");
Assert.True(ButtonFor(app, archive.ScanCommand).IsEnabled, "the Scan button is enabled once the archive is read");
Assert.True(ButtonFor(app, archive.AnalyseSetCommand).IsEnabled, "mass operations are enabled on the whole archive");
// Expanding another year keeps the selection: the set stays what the user chose.
var year = archive.TreeRows[1];
var tree = app.FindAll<ListBox>().Single(l => l.Name == "Tree");
tree.SelectedItems.Add(year);
var chosen = archive.SetText;
archive.Toggle(archive.TreeRows.Last(r => r.IsYear));
Assert.Equal(chosen, archive.SetText, "opening a year does not change the set");
Assert.True(tree.SelectedItems.Cast<ArchiveTreeRowViewModel>().Any(r => r.Node.Key == year.Node.Key), "the list shows the same selection");
tree.SelectedItems.Clear();
await ArchiveScenes.ShowAsync(app.Shell, "maintenance");
Assert.True(archive.IsMaintenance);
Assert.Equal(5, archive.Health.Count);
Assert.Equal(1, archive.Duplicates!.Count);
Assert.Equal(3, archive.Orphans!.Count, "unlisted photos, a row without sidecar, a folder not indexed");
await app.ExpectAsync<ArchiveView>("archive-maintenance");
await ArchiveScenes.ShowAsync(app.Shell, "rebuild");
var rebuild = Assert.NotNull(archive.Dialog as RebuildDialogViewModel);
Assert.True(rebuild.RebuildCommand.CanExecute(null));
Assert.False(archive.IsContentEnabled, "the screen behind a dialog takes no input");
await app.ExpectAsync<ArchiveView>("archive-rebuild");
await ArchiveScenes.ShowAsync(app.Shell, "move");
var move = Assert.NotNull(archive.Dialog as RenameDialogViewModel);
Assert.NotEmpty(move.Rows, "the dry run lists the folders that change");
await app.ExpectAsync<ArchiveView>("archive-move");
Assert.True(ButtonFor(app, move.ApplyCommand).IsEnabled, "Apply follows the dry run");
move.CloseCommand.Execute(null);
archive.RetagSetCommand.Execute(null);
var retag = Assert.NotNull(archive.Dialog as RetagDialogViewModel);
retag.Add.Text = "sunset";
await app.ExpectAsync<ArchiveView>("archive-retag");
Assert.True(ButtonFor(app, retag.ApplyCommand).IsEnabled, "Apply follows the typed tags");
retag.CloseCommand.Execute(null);
});
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
}
@@ -0,0 +1,65 @@
using System.Globalization;
using Titano.App.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.App.Tests.Import;
public sealed class CardPoolTests
{
private static readonly CardDevice CardA = new(@"F:\", "EOS_DIGITAL", 0x3F2A9C11, 128_000_000_000, 31_800_000_000, true, true);
private static readonly CardDevice GoPro = new(@"E:\", "GOPRO", 0x11112222, 64_000_000_000, 52_600_000_000, true, true);
private static readonly CardDevice Usb = new(@"G:\", "BACKUP", 0x99990000, 2_000_000_000_000, 1_800_000_000_000, true, false);
public CardPoolTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static MediaCard Known(CardDevice device, string nickname, DateTimeOffset seen) => new()
{
Id = Guid.CreateVersion7(),
Identity = device.Identity,
VolumeSerial = device.SerialNumber,
Label = device.Label,
Capacity = device.TotalBytes,
Nickname = nickname,
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
CameraSerial = "0431",
LastSeen = seen,
};
[Test]
public void InsertedVolumesComeFirstThenRememberedCardsThenTheFolder()
{
var away = new CardDevice(@"H:\", "NIKON", 0x55556666, 64_000_000_000, 0, true, true);
var cards = new[] { Known(CardA, "EOS R5 · card A", DateTimeOffset.UtcNow), Known(away, "Z 8 card", DateTimeOffset.UtcNow.AddDays(-3)) };
var pool = CardPool.Build([Usb, CardA, GoPro], cards, @"D:\Shoots\2026");
Assert.SequenceEqual(new[] { GoPro.Identity, CardA.Identity, Usb.Identity, away.Identity, @"D:\Shoots\2026" }, pool.Select(s => s.Key));
Assert.Equal(SourceKind.Card, pool[0].Kind);
Assert.False(pool[0].IsKnown);
Assert.Equal("GOPRO", pool[0].Title);
Assert.Equal("New card", pool[0].StateText);
Assert.Equal("EOS R5 · card A", pool[1].Title);
Assert.Equal("Known card", pool[1].StateText);
Assert.Equal("128 GB · 96.2 GB used", pool[1].Subtitle);
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[1].IdentityText);
Assert.Equal(SourceKind.Drive, pool[2].Kind);
Assert.Equal("no DCIM · 1.8 TB free", pool[2].Subtitle);
Assert.False(pool[3].IsInserted);
Assert.Null(pool[3].Root);
Assert.Equal("Canon EOS R5 · not inserted", pool[3].Subtitle);
Assert.Equal(SourceKind.Folder, pool[4].Kind);
Assert.Equal(@"D:\Shoots\2026", pool[4].Root);
}
[Test]
public void AKnownCardWithoutDcimIsStillACard()
{
var pool = CardPool.Build([Usb], [Known(Usb, "Backup card", DateTimeOffset.UtcNow)], null);
Assert.Equal(SourceKind.Card, pool.Single().Kind);
Assert.Equal("3F2A-9C11", ImportSource.SerialText(0x3F2A9C11));
Assert.Equal("3F2A9C11-EOS_DIGITAL-128000000000", CardA.Identity);
Assert.Equal("EOS_DIGITAL", CardA.ToVolume().Label);
}
}
@@ -0,0 +1,114 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.App.Import;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.App.Tests.Import;
public sealed class ImportChoicesTests
{
[Test]
public void ACardProfileRoundTripsThroughTheForm()
{
var profile = new CardProfile
{
FolderTemplate = "{year}/{title}",
FileTemplate = "{name}",
SessionGapMinutes = 30,
MinimumSessionFrames = 4,
IncludeSubfolders = false,
VerifyCopies = false,
Duplicates = DuplicatePolicy.ImportAgain,
AfterImport = AfterImport.DeleteImported,
Eject = false,
DeepAnalysis = false,
};
var choices = ImportChoices.FromProfile(profile);
Assert.True(choices.SplitSessions);
Assert.Equal(30, choices.GapMinutes);
Assert.Equal(profile, choices.ToProfile());
}
[Test]
public void SessionsOffIsRememberedAsAZeroGapAndNeverSplits()
{
var off = new ImportChoices { SplitSessions = false, GapMinutes = 20 };
Assert.Equal(0, off.ToProfile().SessionGapMinutes);
Assert.Equal(TimeSpan.MaxValue, off.ToOptions().SessionGap);
var back = ImportChoices.FromProfile(off.ToProfile());
Assert.False(back.SplitSessions);
Assert.Equal(new CardProfile().SessionGapMinutes, back.GapMinutes);
Assert.Equal(TimeSpan.FromMinutes(20), (off with { SplitSessions = true }).ToOptions().SessionGap);
}
[Test]
public void OptionsCarryTheFormAndTheTypedTitles()
{
var titles = new Dictionary<string, string> { ["k"] = "Harbour" };
var options = new ImportChoices { MinimumFrames = 0, Duplicates = DuplicatePolicy.ImportAgain, VerifyCopies = false }.ToOptions(titles);
Assert.Equal(1, options.MinimumSessionFrames);
Assert.Equal(DuplicatePolicy.ImportAgain, options.Duplicates);
Assert.False(options.VerifyCopies);
Assert.Equal("Harbour", options.Titles["k"]);
}
[Test]
public void OnlyGroupingAndNamingChoicesNeedANewPlan()
{
var a = new ImportChoices();
Assert.False((a with { Duplicates = DuplicatePolicy.ImportAgain, VerifyCopies = false, Eject = false, AfterImport = AfterImport.FormatCard }).NeedsNewPlan(a));
Assert.False((a with { SplitSessions = false, GapMinutes = 5 }).NeedsNewPlan(a with { SplitSessions = false }));
Assert.True((a with { GapMinutes = 5 }).NeedsNewPlan(a));
Assert.True((a with { MinimumFrames = 2 }).NeedsNewPlan(a));
Assert.True((a with { FileTemplate = "{name}" }).NeedsNewPlan(a));
Assert.True((a with { Destination = ImportDestinationKind.Folder }).NeedsNewPlan(a));
Assert.True((a with { IncludeSubfolders = false }).NeedsNewPlan(a));
Assert.False(a.TitlesChangeNames);
Assert.True((a with { FolderTemplate = "{year}/{Title:upper}" }).TitlesChangeNames);
}
[Test]
public void ACardFollowsItsCameraProfileWhenItJoinedItOrHasNoSettingsYet()
{
var shared = new CardProfile { SessionGapMinutes = 90 };
var defaults = new CardProfile { SessionGapMinutes = 45 };
var own = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30);
var fresh = Card("Canon", "Canon EOS R5", null, daysAgo: 0);
var camera = new CameraProfile("Canon", "Canon EOS R5", shared, []);
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(fresh, camera, defaults), "a new card of a known camera needs no setup");
Assert.Equal(new ResolvedProfile(defaults, false), CameraProfiles.Resolve(fresh, null, defaults));
Assert.Equal(20, CameraProfiles.Resolve(own, camera, defaults).Profile.SessionGapMinutes, "a card with its own settings keeps them");
Assert.False(CameraProfiles.Resolve(own, camera, defaults).FollowsCamera);
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(own, camera.With(own.Id), defaults), "a card that joined follows the shared rules");
var joined = camera.With(own.Id).With(own.Id).With(fresh.Id);
Assert.SequenceEqual([own.Id, fresh.Id], joined.Cards);
Assert.SequenceEqual([fresh.Id], joined.Without(own.Id).Cards);
}
[Test]
public void SplitsAndMergesTravelToThePlanner()
{
var options = new ImportChoices().ToOptions(null, new HashSet<string> { "DCIM/100CANON/IMG_0005.CR2" }, new HashSet<string> { "DCIM/100CANON/IMG_0009.CR2" });
Assert.True(options.SplitBefore.Contains("DCIM/100CANON/IMG_0005.CR2"));
Assert.True(options.MergeAt.Contains("DCIM/100CANON/IMG_0009.CR2"));
Assert.Empty(new ImportChoices().ToOptions().SplitBefore);
}
private static MediaCard Card(string make, string model, CardProfile? profile, int daysAgo) => new()
{
Id = Guid.CreateVersion7(),
Identity = Guid.NewGuid().ToString("N"),
CameraMake = make,
CameraModel = model,
ProfileJson = profile is null ? null : JsonSerializer.Serialize(profile, StoredProfile),
LastSeen = DateTimeOffset.UtcNow.AddDays(-daysAgo),
};
/// <summary>How the card repository stores a profile (camel case, enum names).</summary>
private static readonly JsonSerializerOptions StoredProfile = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Converters = { new JsonStringEnumConverter() } };
}
@@ -0,0 +1,185 @@
using System.Globalization;
using System.IO;
using Titano.App.Import;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Testing;
using static Titano.App.Tests.Import.ImportTestData;
namespace Titano.App.Tests.Import;
/// <summary>Card to archive and card to folder on real files and a real index, and the card-erase gate around them.</summary>
[Category("import")]
public sealed class ImportFlowTests(TestContext context)
{
private static readonly CardVolume Volume = new("3F2A9C11-EOS_DIGITAL-127865454592", 0x3F2A9C11, "EOS_DIGITAL", 127_865_454_592);
[Test]
public async Task AVerifiedArchiveImportUnlocksDeleteAndFormat()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test" });
var archive = await archives.AdoptAsync(context.CreateTempDirectory("archive"), "Main", context.Cancellation);
var card = Card(context.CreateTempDirectory("card"), 10, Start, Start.AddHours(3), Start.AddDays(1));
var media = await archives.Imports.RegisterCardAsync(Volume, context.Cancellation);
var destination = new ArchiveDestination(archives, archive);
var choices = new ImportChoices();
var plan = await destination.PlanAsync(card, choices.ToOptions(), media.Id, null, context.Cancellation);
Assert.Equal(3, plan.Sessions.Count);
Assert.Equal(30, plan.CopyCount);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, null);
Assert.False(before.CanCheck, "no import, no erase");
Assert.False(before.CanDelete);
Assert.False(before.CanFormat);
Assert.Equal(Loc.L("Import.Blocked.NothingImported"), before.CheckBlocker);
var unverified = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
Assert.Empty(unverified.ToDelete);
Job queued;
await using (var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }))
{
await engine.StartAsync(context.Cancellation);
queued = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
await WaitDoneAsync(db, queued.Id);
}
// The verification result comes from the job's own records: every planned copy has its frame.
var job = (await db.Jobs.GetAsync(queued.Id, context.Cancellation))!;
var outcome = await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, media.Id, choices.VerifyCopies, context.Cancellation);
Assert.Equal(30, outcome.Copied);
Assert.True(outcome.IsComplete);
Assert.Equal(30, (await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, null, choices.VerifyCopies, context.Cancellation)).Copied,
"a folder source, without import history, finds its frames in the sessions' sequences");
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.True(afterImport.CanCheck);
Assert.False(afterImport.CanDelete, "the dry run must come first");
Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker);
var snapshot = CardSnapshot.Take(card, Volume.Identity);
var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
var ready = afterImport with { Erase = erase, Card = snapshot };
Assert.True(ready.CanDelete);
Assert.True(ready.CanFormat);
Assert.Equal(30, ready.DeleteCount);
Assert.Equal("30 verified on the card · " + Titano.App.Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText);
Assert.False((ready with { Card = null }).CanDelete, "the dry run lists the card too");
Assert.True(snapshot.IsUnchanged(CardSnapshot.Take(card, Volume.Identity)));
Assert.False(snapshot.IsUnchanged(CardSnapshot.Take(card, "another card")), "another card with the same files is not the checked card");
// A video is not a photo: it never blocks formatting but is named as never imported.
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"), [1, 2, 3]);
var withVideo = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.True(withVideo.CanFormat);
Assert.SequenceEqual(["DCIM/100CANON/MVI_0031.MP4"], withVideo.NotImported);
Assert.Equal("30 verified on the card · " + Titano.App.Infrastructure.Formatting.Bytes(ready.DeleteBytes) + " · 1 other file not imported", withVideo.EraseText);
Assert.False(snapshot.IsUnchanged(withVideo.Card!), "a file added since the check changes the card");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"));
// A photo added to the card after the import is not verified: formatting would lose it.
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"), Jpeg(Start.AddDays(2), 31));
var withPhoto = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.False(withPhoto.CanFormat);
Assert.Equal(Loc.L("Import.Blocked.NotAllVerified"), withPhoto.FormatBlocker);
Assert.True(withPhoto.CanDelete, "the verified photos may still be deleted");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"));
Assert.False((ready with { Outcome = outcome with { Verified = false } }).CanFormat);
Assert.False((ready with { Destination = ImportDestinationKind.Folder }).CanDelete);
Assert.False((ready with { IsInserted = false }).CanDelete);
Assert.False((ready with { IsRemovable = false }).CanEject);
var result = CardEraser.Execute(erase, context.Cancellation);
Assert.Equal(30, result.Deleted);
Assert.Empty(Directory.EnumerateFiles(Path.Combine(card, "DCIM", "100CANON")));
}
[Test]
public async Task AFolderImportCopiesWithoutAnIndexAndFindsItsOwnCopiesAgain()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var card = Card(context.CreateTempDirectory("card"), 8, Start, Start.AddHours(2));
var target = context.CreateTempDirectory("folder");
var destination = new UnindexedDestination(ImportDestinationKind.Folder, target);
var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
Assert.Equal(2, plan.Sessions.Count);
Assert.Equal(16, plan.CopyCount);
var reports = new List<ImportProgress>();
var outcome = await LocalImport.RunAsync(plan, new FolderImportSink(target), verify: true, new Progress(reports), context.Cancellation);
Assert.Equal(16, outcome.Copied);
Assert.True(outcome.IsComplete);
Assert.True(outcome.Verified);
Assert.NotEmpty(reports);
foreach (var (folder, name) in plan.Sessions.SelectMany(s => s.Items.Select(i => (s.Folder, i.FileName))))
Assert.FileExists(Path.Combine(target, folder, name));
var again = await LocalImport.RunAsync(await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation),
new FolderImportSink(target), verify: true, null, context.Cancellation);
Assert.Equal(0, again.Copied);
Assert.Equal(16, again.Duplicates);
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck);
}
[Test]
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrivedWithTheJobsOwnError()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported),
Item(4, Start.AddSeconds(6))));
var errors = ImportOutcome.JobErrors("18:02:11 Not copied: DCIM/100CANON/IMG_0002.CR2 (Disk full)\n18:02:12 Imported 1, skipped 1, failed 1");
var outcome = await ImportOutcome.CheckAsync(plan, true,
(item, _) => Task.FromResult(item.SourcePath.EndsWith("0001.CR2", StringComparison.Ordinal) ? CommitCheck.Copied : CommitCheck.Missing), errors,
context.Cancellation);
Assert.Equal(1, outcome.Copied);
Assert.Equal(1, outcome.Skipped);
Assert.Equal(2, outcome.Failures.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0002.CR2", "Disk full"), outcome.Failures[0]);
Assert.Equal(Loc.L("Import.Result.NotCommitted"), outcome.Failures[1].Message, "no log line for it: not committed");
Assert.False(outcome.IsComplete);
}
[Test]
public void AnAbortedRunCountsWhatTheDestinationCommittedAndFailsTheRest()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(6),
action: ImportAction.SkipImported)));
var items = plan.Sessions[0].Items;
var report = new ImportSinkReport();
report.Committed[items[1].SourcePath] = new SinkCommit(Guid.NewGuid(), items[1].FileName, Duplicate: false);
report.Rejected[items[0].SourcePath] = "Hash mismatch";
var results = new[] { new ImportItemResult(plan.Sessions[0], items[0], ImportItemStatus.Copied, "a", new SinkCommit(null, items[0].FileName, false), null) };
var outcome = ImportOutcome.From(plan, results, verified: true, report, stopped: "Connection lost");
Assert.Equal(1, outcome.Copied, "committed in the batch the abort interrupted");
Assert.Equal(1, outcome.Skipped);
Assert.SequenceEqual(
[new ImportFailure(items[0].SourcePath, "Hash mismatch"), new ImportFailure(items[2].SourcePath, "Connection lost")],
outcome.Failures);
}
private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId)
{
var until = DateTime.UtcNow.AddSeconds(60);
while (DateTime.UtcNow < until)
{
var job = await db.Jobs.GetAsync(jobId, context.Cancellation);
if (job?.State == JobState.Done) return;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"Import job ended {job.State}: {job.Error}\n{job.LogTail}");
await Task.Delay(25, context.Cancellation);
}
Assert.Fail("The import job did not finish");
}
/// <summary>Collects reports synchronously (System.Progress posts to the thread pool).</summary>
private sealed class Progress(List<ImportProgress> into) : IProgress<ImportProgress>
{
public void Report(ImportProgress value) => into.Add(value);
}
}
@@ -0,0 +1,170 @@
using System.Globalization;
using Titano.App.Import;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Testing;
using static Titano.App.Tests.Import.ImportTestData;
namespace Titano.App.Tests.Import;
public sealed class ImportPlansTests
{
public ImportPlansTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static ImportPlan ThreeSessions(long? available = 200_000_000)
{
var duplicate = Guid.CreateVersion7();
return Plan(available, [new ImportProblem("DCIM/100CANON/IMG_0099.CR2", "Access denied")],
Session(1, "2026/2026-09-28 Canon EOS R5", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(8))),
Session(2, "2026/2026-09-29 Canon EOS R5", Item(5, Start.AddDays(1)), Item(6, Start.AddDays(1).AddSeconds(120), action: ImportAction.SkipInArchive, existing: duplicate)),
Session(3, "2026/2026-09-30 Canon EOS R5", Item(7, Start.AddDays(2), action: ImportAction.SkipImported)));
}
[Test]
public void TotalsCountWhatIsCopiedSkippedAndDuplicated()
{
var totals = ImportPlans.Totals(ThreeSessions(), verify: true);
Assert.Equal(3, totals.Sessions);
Assert.Equal(7, totals.Photos);
Assert.Equal(5, totals.CopyCount);
Assert.Equal(5 * 24_000_000L, totals.CopyBytes);
Assert.Equal(1, totals.Duplicates);
Assert.Equal(1, totals.ImportedBefore);
Assert.Equal(1, totals.Problems);
Assert.Equal(80_000_000L, totals.FreeAfter);
Assert.True(totals.HasEnoughSpace);
Assert.Equal(TimeSpan.FromSeconds(3), totals.Estimate);
Assert.Equal("3 sessions · 7 photos · 120 MB · about 3 s", totals.Text);
Assert.Equal("1 duplicate", totals.DuplicatesText);
Assert.Equal("Import 5 photos", totals.ImportText);
Assert.Equal("80 MB free after import", totals.SpaceText);
}
[Test]
public void ASmallDestinationReportsTheMissingSpace()
{
var totals = ImportPlans.Totals(ThreeSessions(available: 100_000_000), verify: false);
Assert.False(totals.HasEnoughSpace);
Assert.Equal("20 MB missing", totals.SpaceText);
Assert.Equal(string.Empty, ImportPlans.Totals(ThreeSessions(available: null), verify: false).SpaceText);
Assert.Equal(TimeSpan.FromSeconds(2), ImportPlans.Totals(ThreeSessions(), verify: false).Estimate);
}
[Test]
public void TheDuplicateChoiceFlipsOnlyPhotosAlreadyInTheArchive()
{
var plan = ThreeSessions();
var again = ImportPlans.WithDuplicates(plan, DuplicatePolicy.ImportAgain);
Assert.Equal(6, again.CopyCount);
var duplicate = again.Sessions[1].Items[1];
Assert.Equal(ImportAction.Copy, duplicate.Action);
Assert.NotNull(duplicate.ExistingFrameId);
Assert.Equal(ImportAction.SkipImported, again.Sessions[2].Items[0].Action);
var skipped = ImportPlans.WithDuplicates(again, DuplicatePolicy.Skip);
Assert.Equal(ImportAction.SkipInArchive, skipped.Sessions[1].Items[1].Action);
Assert.Equal(plan.CopyCount, skipped.CopyCount);
Assert.Equal("Import again", ImportPlans.Details(again, ImportDestinationKind.Archive, true).Rows.Single(r => r.Source.EndsWith("0006.CR2", StringComparison.Ordinal)).ActionText);
}
[Test]
public void TypedTitlesNameTheirSessions()
{
var plan = ThreeSessions();
var titled = ImportPlans.WithTitles(plan, new Dictionary<string, string>
{
[plan.Sessions[0].SessionKey] = " Harbour sunset ",
[plan.Sessions[1].SessionKey] = " ",
["unknown"] = "ignored",
});
Assert.Equal("Harbour sunset", titled.Sessions[0].Title);
Assert.Null(titled.Sessions[1].Title);
Assert.Null(titled.Sessions[2].Title);
Assert.SequenceEqual(plan.Items.Select(i => i.FileName), titled.Items.Select(i => i.FileName));
}
[Test]
public void SessionRowsShowTimesIntervalsAndWhereTheyGo()
{
var plan = ThreeSessions();
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>(["2026/2026-09-29 Canon EOS R5"], StringComparer.OrdinalIgnoreCase));
Assert.Equal(3, rows.Count);
Assert.Equal("4 · 2 s", rows[0].FramesText);
Assert.Equal("2 · 2 min", rows[1].FramesText);
Assert.Equal("1", rows[2].FramesText);
Assert.True(rows[0].IsNew);
Assert.Equal("New · 2026/2026-09-28 Canon EOS R5", rows[0].TargetText);
Assert.False(rows[1].IsNew);
Assert.Equal("Adds to · 2026/2026-09-29 Canon EOS R5", rows[1].TargetText);
Assert.Equal("2026-09-28 Canon EOS R5", rows[0].DefaultTitle);
Assert.Equal("Canon EOS R5", rows[0].CameraText);
Assert.Equal("96 MB", rows[0].SizeText);
Assert.Contains("6:02", rows[0].TimeText);
Assert.Equal("Server", ImportPlans.Sessions(plan, ImportDestinationKind.Server, new HashSet<string>())[0].TargetText);
}
[Test]
public void ShowPlanListsEveryFileItsDestinationAndTheConflicts()
{
var plan = ThreeSessions(available: 100_000_000);
var details = ImportPlans.Details(plan, ImportDestinationKind.Archive, verify: true);
Assert.Equal(plan.FileCount + plan.Sessions.Count, details.Rows.Count);
Assert.Equal(3, details.Rows.Count(r => r.Kind == PlanRowKind.Session));
var first = details.Rows[1];
Assert.Equal("DCIM/100CANON/IMG_0001.CR2", first.Source);
Assert.Equal("2026/2026-09-28 Canon EOS R5/originals/" + plan.Sessions[0].Items[0].FileName, first.Destination);
Assert.Equal("Copy", first.ActionText);
Assert.False(first.IsSkipped);
Assert.True(details.Rows.Single(r => r.Source.EndsWith("0007.CR2", StringComparison.Ordinal)).IsSkipped);
Assert.Equal(3, details.Conflicts.Count);
Assert.Contains("IMG_0099.CR2", details.Conflicts[0]);
Assert.Equal("7 files · copy 5 (120 MB) · 1 imported before · 1 duplicate", details.TotalsText);
var folder = ImportPlans.Details(plan, ImportDestinationKind.Folder, verify: true);
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, folder.Rows[1].Destination);
}
[Test]
public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
{
var plan = ThreeSessions();
var names = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive);
Assert.Equal(3, names.Count);
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, names[0]);
Assert.Equal("→ " + names[0] + " · " + plan.Sessions[0].Items[1].FileName + " · " + plan.Sessions[0].Items[2].FileName, ImportPlans.NamePreview(names));
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestinations(plan, ImportDestinationKind.Server)[0]);
// A name in another folder keeps its folder.
var across = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive, 5);
Assert.Equal(5, across.Count);
Assert.True(ImportPlans.NamePreview(across).EndsWith(" · " + across[4], StringComparison.Ordinal), "the third session's folder is shown");
var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip);
Assert.Empty(ImportPlans.FirstDestinations(nothing, ImportDestinationKind.Archive));
Assert.Equal(string.Empty, ImportPlans.NamePreview([]));
}
[Test]
public void ASessionMergesOnlyIntoTheEarlierSessionOfTheSameCameraAndFormat()
{
var plan = ThreeSessions();
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(rows[0].MergesInto);
Assert.Equal(1, rows[1].MergesInto);
Assert.Equal(2, rows[2].MergesInto);
Assert.Equal("DCIM/100CANON/IMG_0005.CR2", rows[1].FirstPath);
var otherBody = plan with { Sessions = [plan.Sessions[0], plan.Sessions[1] with { CameraSerial = "9999" }, plan.Sessions[2]] };
var split = ImportPlans.Sessions(otherBody, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(split[1].MergesInto, "another camera body never merges");
Assert.Equal(1, split[2].MergesInto, "the earlier session of the same body, skipping the other camera");
}
[Test]
public void ShowPlanOffersASplitOnEveryPhotoButTheFirstOfItsSession()
{
var details = ImportPlans.Details(ThreeSessions(), ImportDestinationKind.Archive, verify: true);
Assert.False(details.Rows[0].CanSplit, "a session heading");
Assert.False(details.Rows[1].CanSplit, "the first photo already starts the session");
Assert.True(details.Rows[2].CanSplit);
}
}
@@ -0,0 +1,98 @@
using System.Windows.Controls;
using System.Windows.Input;
using Titano.App.Import;
using Titano.App.Sections;
using Titano.App.Tests.Windows;
using Titano.Testing;
using Titano.Ui.Controls;
namespace Titano.App.Tests.Import;
/// <summary>
/// Every Import state of <c>--capture</c> (<see cref="ImportScenes"/>) on the simulated cards, rendered in both themes
/// in the real main window, with the figures and gates each state must show — and the buttons really enabled, not
/// only their commands.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ImportScreenSmokeTests
{
[Test]
public Task EveryImportStateRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
var import = app.Shell.Import;
await ShowAsync(app, "inserted");
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts), "the insertion toast");
await app.ExpectAsync<ImportView>("import-inserted");
await ShowAsync(app, "plan");
Assert.Equal(ImportPhase.Ready, import.Phase);
Assert.Equal("EOS R5 · card A", import.SourceTitle);
Assert.Equal(3, import.Sessions.Count, "night, dawn and sunset");
Assert.Equal(50, import.Plan!.CopyCount);
Assert.Equal("Harbour sunset", import.Plan.Sessions[^1].Title);
Assert.Null(import.StartBlocker);
Assert.Empty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
await app.ExpectAsync<ImportView>("import-plan");
Assert.True(ButtonFor(app, import.StartCommand).IsEnabled, "the Import button is enabled once the plan is ready");
Assert.True(ButtonFor(app, import.Sessions[1].MergeCommand).IsEnabled, "a session can merge into the one before");
await ShowAsync(app, "showplan");
Assert.True(import.IsDetailsOpen);
Assert.Equal(50 + 3, import.Details!.Rows.Count);
await app.ExpectAsync<ImportView>("import-showplan");
await ShowAsync(app, "running");
Assert.True(import.IsRunning);
Assert.False(import.IsFormEnabled);
Assert.False(import.Sessions[0].IsEditable, "titles lock while copying");
await app.ExpectAsync<ImportView>("import-running");
Assert.True(ButtonFor(app, import.CancelCommand).IsEnabled, "Cancel is enabled while copying");
await ShowAsync(app, "failed");
Assert.True(import.IsFailed);
await app.ExpectAsync<ImportView>("import-failed");
Assert.True(ButtonFor(app, import.RetryCommand).IsEnabled, "Retry is enabled after a failure");
await ShowAsync(app, "done");
Assert.True(import.IsDone);
var result = import.Result!;
Assert.True(result.IsComplete);
Assert.True(result.OffersDelete);
Assert.True(result.Actions.CanDelete, "a verified import and its dry run allow deleting");
Assert.Equal(49, result.Actions.DeleteCount);
Assert.False(result.Actions.CanFormat, "a photo touched since the import keeps the card from being formatted");
Assert.Empty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
await app.ExpectAsync<ImportView>("import-done");
Assert.True(ButtonFor(app, result.DeleteCommand).IsEnabled, "the Delete button follows the dry run");
await ShowAsync(app, "newcard");
Assert.True(import.IsNicknameOpen, "a new card asks for its nickname");
Assert.Equal("SONY", import.SourceTitle);
Assert.NotEmpty(app.FindAll<ToastHost>().SelectMany(host => host.Toasts));
await app.ExpectAsync<ImportView>("import-newcard");
});
/// <summary>As <c>--capture</c> does: toasts of the previous state go, those of an insertion state stay.</summary>
private static async Task ShowAsync(ScreenSmokeTests.SampleApp app, string state)
{
DismissToasts(app);
await ImportScenes.ShowAsync(app.Shell, state);
if (!ImportScenes.ShowsToast(state)) DismissToasts(app);
}
private static void DismissToasts(ScreenSmokeTests.SampleApp app)
{
foreach (var host in app.FindAll<ToastHost>())
{
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
}
}
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
}
@@ -0,0 +1,76 @@
using System.IO;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Import;
using Titano.Core.Metadata;
namespace Titano.App.Tests.Import;
/// <summary>Synthetic cards (small JPEGs with Exif) and hand-made plans for the Import tests.</summary>
internal static class ImportTestData
{
public static readonly DateTime Start = new(2026, 9, 28, 18, 2, 11);
/// <summary>A real JPEG with Exif make, model, body serial and capture time; each seed gives distinct bytes.</summary>
public static byte[] Jpeg(DateTime captured, int seed)
{
using var image = new ImageBuffer(32, 24);
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 % 32) / 32f);
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured, Iso = 100 });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [exif[4..]] });
}
/// <summary>A card folder with <c>DCIM/100CANON</c>: one series per start time, <paramref name="perSession"/> photos 2 s apart.</summary>
public static string Card(string root, int perSession, params DateTime[] starts)
{
var folder = Path.Combine(root, "DCIM", "100CANON");
Directory.CreateDirectory(folder);
var n = 1;
foreach (var start in starts)
{
for (var i = 0; i < perSession; i++, n++)
File.WriteAllBytes(Path.Combine(folder, $"IMG_{n:0000}.JPG"), Jpeg(start.AddSeconds(2 * i), n));
}
return root;
}
public static PlannedItem Item(int n, DateTime captured, long size = 24_000_000, ImportAction action = ImportAction.Copy, Guid? existing = null) => new()
{
SourcePath = $"DCIM/100CANON/IMG_{n:0000}.CR2",
Size = size,
ModifiedUtc = captured,
CapturedAt = captured,
FileName = $"{captured:yyyy-MM-dd_HH-mm-ss}_{n:0000}.CR2",
Action = action,
ExistingFrameId = existing,
};
public static PlannedSession Session(int number, string folder, params PlannedItem[] items) => new()
{
Number = number,
SessionKey = $"card-0000000{number}-key",
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
Format = ImageFileFormat.Cr2,
Start = items[0].CapturedAt,
End = items[^1].CapturedAt,
Folder = folder,
Items = items,
};
public static ImportPlan Plan(long? available, IReadOnlyList<ImportProblem>? problems = null, params PlannedSession[] sessions) => new()
{
Id = Guid.CreateVersion7(),
SourceRoot = "/card",
DestinationRoot = "/archive",
Sessions = sessions,
Problems = problems ?? [],
AvailableBytes = available,
};
}
@@ -0,0 +1,56 @@
using System.Globalization;
using System.IO;
using Titano.App.Import;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.App.Tests.Import;
/// <summary>The simulated card behind the Import captures plans like a real one and gates the after-import actions.</summary>
[Category("import")]
public sealed class SampleCardsTests(TestContext context)
{
[Test]
public async Task TheSampleCardPlansThreeSessionsAndAllowsOnlyAVerifiedDelete()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "titano.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test" });
var archive = await archives.AdoptAsync(context.CreateTempDirectory("archive"), "Main", context.Cancellation);
var devices = new SampleDeviceMonitor();
await SampleCards.InsertAsync(db, devices, context.CreateTempDirectory("data"));
var contents = devices.Devices.Where(d => d.HasDcim).ToDictionary(d => d.Identity, d => CardContents.Read(d.Root));
var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null, contents);
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind));
Assert.Equal("EOS R5 · card A", pool[0].Title);
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText);
Assert.Equal("Canon EOS R5 · 50 photos", pool[0].ToastText);
Assert.Contains("50 photos", pool[0].Subtitle);
Assert.Equal("SONY", pool[1].Title);
Assert.False(pool[1].IsKnown);
Assert.Equal("12 photos · not yet known to Titano", pool[1].ToastText[(pool[1].ToastText.IndexOf(" · ", StringComparison.Ordinal) + 3)..],
"the camera of its first photo, its photos, and that it is new");
Assert.Equal("GoPro 12", pool[3].Title);
Assert.False(pool[3].IsInserted);
var card = pool[0].Card!;
Assert.Equal(new DateTimeOffset(2026, 9, 21, 19, 40, 0, TimeSpan.Zero), (await db.MediaCards.ListImportsAsync(card.Id, 1, context.Cancellation))[0].ImportedAt);
var plan = await new ArchiveDestination(archives, archive).PlanAsync(pool[0].Root!, new ImportChoices().ToOptions(), card.Id, null, context.Cancellation);
Assert.Equal(3, plan.Sessions.Count);
Assert.SequenceEqual(new[] { 10, 16, 24 }, plan.Sessions.Select(s => s.Items.Count));
Assert.Equal(50, plan.CopyCount);
Assert.Equal("Canon EOS R5", plan.Sessions[0].CameraModel);
var outcome = SampleCards.Outcome(plan);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.False(before.CanDelete, "no dry run yet");
var actions = before with { Erase = SampleCards.Erase(plan), Card = CardSnapshot.Take(pool[0].Root!, pool[0].Key) };
Assert.True(actions.CanDelete);
Assert.Equal(49, actions.DeleteCount);
Assert.Equal(1, actions.KeptCount);
Assert.False(actions.CanFormat, "a kept photo would be lost by formatting");
}
}
@@ -0,0 +1,189 @@
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Cryptography;
using Titano.App.Import;
using Titano.Core.Import;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Testing;
using static Titano.App.Tests.Import.ImportTestData;
namespace Titano.App.Tests.Import;
/// <summary>The "Server" destination over the real protocol client against an in-memory upload endpoint.</summary>
[Category("import")]
public sealed class ServerImportSinkTests(TestContext context)
{
[Test]
public async Task EveryPhotoIsUploadedInChunksUnderItsCardNameAndVerifiedByHash()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start, Start.AddHours(2));
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 256);
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
plan = plan with { Sessions = [plan.Sessions[0] with { Title = "Harbour sunset" }, .. plan.Sessions.Skip(1)] };
var outcome = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation);
Assert.Equal(16, outcome.Copied);
Assert.True(outcome.IsComplete);
Assert.Equal(16, server.Committed.Count);
foreach (var item in plan.Items)
{
var bytes = File.ReadAllBytes(Path.Combine(card, item.SourcePath));
var upload = server.Committed.Single(u => u.FileName == Path.GetFileName(item.SourcePath));
Assert.BytesEqual(bytes, upload.Bytes);
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(bytes)), upload.Sha256);
Assert.True(upload.Chunks > 1, "files larger than a chunk travel in several chunks");
}
Assert.SequenceEqual(plan.Sessions.Select(s => s.SessionKey).Order(StringComparer.Ordinal),
server.Committed.Select(u => u.SessionKey).Distinct().Order(StringComparer.Ordinal));
Assert.Equal("Harbour sunset", server.Titles.Single().Value);
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
}
[Test]
public async Task PhotosTheServerAlreadyHoldsAreNotSentAgain()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096);
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var destination = new UnindexedDestination(ImportDestinationKind.Server, staging);
var plan = await destination.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation);
var chunks = server.ChunkCount;
var again = await LocalImport.RunAsync(plan, new ServerImportSink(client, staging), verify: true, null, context.Cancellation);
Assert.Equal(0, again.Copied);
Assert.Equal(8, again.Duplicates);
Assert.Equal(chunks, server.ChunkCount);
}
[Test]
public async Task AFileTheServerRefusesIsListedAndTheImportGoesOn()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { CorruptFile = "IMG_0003.JPG" };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging);
var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(7, outcome.Copied);
Assert.Equal(7, server.Committed.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single());
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
}
[Test]
public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { SignedOutAfter = 3 };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging);
var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(3, outcome.Copied, "the uploads the server committed before the sign-in was lost");
Assert.Equal(5, outcome.Failures.Count);
Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence");
Assert.False(outcome.IsComplete);
}
[Test]
public async Task TheQuotaIsTheRoomOfAServerImport()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging) { ServerSpace = 1_000 }
.PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
Assert.Equal(1_000L, plan.AvailableBytes);
Assert.False(ImportPlans.Totals(plan, verify: true).HasEnoughSpace, "eight photos do not fit in 1 KB of quota");
var unlimited = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null,
context.Cancellation);
Assert.Null(unlimited.AvailableBytes);
Assert.True(ImportPlans.Totals(unlimited, verify: true).HasEnoughSpace);
}
/// <summary>Start, chunk and complete of BRIEF §14.4, plus the title update; the hash is checked at completion.</summary>
private sealed class FakeUploadServer(int chunkSize) : HttpMessageHandler
{
private readonly Dictionary<Guid, Upload> _open = [];
private readonly Dictionary<string, Guid> _sequences = new(StringComparer.Ordinal);
private readonly Dictionary<string, Guid> _frames = new(StringComparer.Ordinal);
public List<Upload> Committed { get; } = [];
public Dictionary<Guid, string> Titles { get; } = [];
public int ChunkCount { get; private set; }
/// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
public string? CorruptFile { get; init; }
/// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary>
public int? SignedOutAfter { get; init; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var path = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"])
{
var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!;
if (Committed.Count >= SignedOutAfter)
return Json(new ApiError("unauthorized", "Sign in again"), ProtocolJson.Default.ApiError, HttpStatusCode.Unauthorized);
if (_frames.TryGetValue(start.Sha256, out var existing))
return Json(new StartUploadResponse(null, chunkSize, [], true, existing), ProtocolJson.Default.StartUploadResponse);
var upload = new Upload(Guid.NewGuid(), start.FileName, start.Size, start.Sha256, start.SessionKey ?? "user");
_open[upload.Id] = upload;
return Json(new StartUploadResponse(upload.Id, chunkSize, [], false, null), ProtocolJson.Default.StartUploadResponse);
}
if (request.Method == HttpMethod.Put && path is ["api", "v1", "uploads", var id, "chunks", var n])
{
var upload = _open[Guid.Parse(id)];
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF;
upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes;
ChunkCount++;
return Json(new ChunkReceived(int.Parse(n, System.Globalization.CultureInfo.InvariantCulture), [.. upload.Parts.Keys]), ProtocolJson.Default.ChunkReceived);
}
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads", var done, "complete"])
{
var upload = _open[Guid.Parse(done)];
if (Convert.ToHexStringLower(SHA256.HashData(upload.Bytes)) != upload.Sha256)
return Json(new ApiError("hash_mismatch", "Hash mismatch"), ProtocolJson.Default.ApiError, HttpStatusCode.UnprocessableEntity);
_open.Remove(upload.Id);
Committed.Add(upload);
var frame = Guid.NewGuid();
_frames[upload.Sha256] = frame;
if (!_sequences.TryGetValue(upload.SessionKey, out var sequence)) _sequences[upload.SessionKey] = sequence = Guid.NewGuid();
return Json(new CompleteUploadResponse(frame, sequence, Committed.Count(u => u.SessionKey == upload.SessionKey) - 1),
ProtocolJson.Default.CompleteUploadResponse);
}
if (request.Method == HttpMethod.Patch && path is ["api", "v1", "sequences", var sequenceId])
{
var update = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.UpdateSequenceRequest, cancellationToken))!;
Titles[Guid.Parse(sequenceId)] = update.Title!;
return Json(new SequenceDto(Guid.Parse(sequenceId), update.Title, update.Title!, "f", null, null, null, null, null, 0, null, 0, 0, 0, null, [], 0, null,
1, 1, 0, null, DateTimeOffset.UtcNow), ProtocolJson.Default.SequenceDto);
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
private static HttpResponseMessage Json<T>(T value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> type, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = JsonContent.Create(value, type) };
public sealed record Upload(Guid Id, string FileName, long Size, string Sha256, string SessionKey)
{
public SortedDictionary<int, byte[]> Parts { get; } = [];
public byte[] Bytes => [.. Parts.Values.SelectMany(p => p)];
public int Chunks => Parts.Count;
}
}
}
@@ -71,6 +71,30 @@ public abstract class MediaCardRepositoryTests(TestContext context) : Repository
Assert.Equal(0, (await db.MediaCards.GetImportedKeysAsync(card.Id, Ct)).Count);
}
[Test]
public async Task AJobListsOnlyTheFilesItRecorded()
{
var db = await OpenTitanoAsync();
var card = Card();
await db.MediaCards.UpsertAsync(card, Ct);
var modified = new DateTimeOffset(2026, 9, 28, 18, 0, 0, TimeSpan.Zero);
var first = Guid.CreateVersion7();
var second = Guid.CreateVersion7();
await db.MediaCards.RecordImportsAsync(
[
new ImportRecord(card.Id, new ImportKey("DCIM/100CANON/IMG_0002.CR3", 10, modified), null, null, first, TestData.Now),
new ImportRecord(card.Id, new ImportKey("DCIM/100CANON/IMG_0001.CR3", 10, modified), null, null, first, TestData.Now),
new ImportRecord(card.Id, new ImportKey("DCIM/100CANON/IMG_0003.CR3", 10, modified), null, null, second, TestData.Now),
], Ct);
// Importing a file again moves it to the later job.
await db.MediaCards.RecordImportsAsync([new ImportRecord(card.Id, new ImportKey("DCIM/100CANON/IMG_0002.CR3", 10, modified), null, null, second, TestData.Now)], Ct);
Assert.SequenceEqual(["DCIM/100CANON/IMG_0001.CR3"], (await db.MediaCards.ListImportsByJobAsync(card.Id, first, Ct)).Select(r => r.Key.Path));
Assert.SequenceEqual(["DCIM/100CANON/IMG_0002.CR3", "DCIM/100CANON/IMG_0003.CR3"],
(await db.MediaCards.ListImportsByJobAsync(card.Id, second, Ct)).Select(r => r.Key.Path));
Assert.Empty(await db.MediaCards.ListImportsByJobAsync(Card().Id, second, Ct));
}
private static MediaCard Card() => new()
{
Id = Guid.CreateVersion7(),