feat(app): import and archive manager logic (plans, card pool, card gate, server sink, tree, charts, reports)
Plain classes behind the Import and Archive screens: plan totals, session rows and the Show plan listing; duplicate and title choices without a new scan; folder and server destinations with the protocol client's chunked, hash-verified uploads; the after-import gate that allows deleting or formatting a card only after a verified archive import and a dry run; the archive tree, chart aggregation, mass rename/retag and maintenance reports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
22 files changed
+2258
No files matched your search
@@ -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(@"F:\ · 128 GB · 96.2 GB used", pool[1].Subtitle);
|
||||
Assert.Equal(@"F:\ · 128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[1].IdentityText);
|
||||
Assert.Equal(SourceKind.Drive, pool[2].Kind);
|
||||
Assert.Equal(@"G:\ · 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,69 @@
|
||||
using Titano.App.Import;
|
||||
using Titano.Core.Import;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
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, plan.FileCount);
|
||||
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);
|
||||
|
||||
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);
|
||||
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
|
||||
await WaitDoneAsync(db, job.Id);
|
||||
}
|
||||
|
||||
var outcome = await ImportOutcome.CheckAsync(plan, choices.VerifyCopies,
|
||||
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct)).Count > 0, context.Cancellation);
|
||||
Assert.Equal(30, outcome.Copied);
|
||||
Assert.True(outcome.IsComplete);
|
||||
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, plan.FileCount);
|
||||
Assert.True(afterImport.CanCheck);
|
||||
Assert.False(afterImport.CanDelete, "the dry run must come first");
|
||||
Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker);
|
||||
|
||||
var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
|
||||
var ready = afterImport with { Erase = erase };
|
||||
Assert.True(ready.CanDelete);
|
||||
Assert.True(ready.CanFormat);
|
||||
Assert.Equal(30, ready.DeleteCount);
|
||||
Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText);
|
||||
|
||||
// A photo added to the card after the import is not verified: formatting would lose it.
|
||||
Assert.False((ready with { CardPhotos = 31 }).CanFormat);
|
||||
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 s in plan.Sessions)
|
||||
foreach (var item in s.Items)
|
||||
Assert.FileExists(Path.Combine(target, s.Folder, item.FileName));
|
||||
|
||||
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, 16).CanCheck);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrived()
|
||||
{
|
||||
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)));
|
||||
var outcome = await ImportOutcome.CheckAsync(plan, true, (item, _) => Task.FromResult(!item.SourcePath.EndsWith("0002.CR2", StringComparison.Ordinal)),
|
||||
context.Cancellation);
|
||||
Assert.Equal(1, outcome.Copied);
|
||||
Assert.Equal(1, outcome.Skipped);
|
||||
Assert.Equal("DCIM/100CANON/IMG_0002.CR2", outcome.Failures.Single().SourcePath);
|
||||
Assert.False(outcome.IsComplete);
|
||||
}
|
||||
|
||||
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,136 @@
|
||||
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 TheNamePreviewIsTheFirstCopiedFile()
|
||||
{
|
||||
var plan = ThreeSessions();
|
||||
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Archive));
|
||||
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Server));
|
||||
var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip);
|
||||
Assert.Null(ImportPlans.FirstDestination(nothing, ImportDestinationKind.Archive));
|
||||
}
|
||||
}
|
||||
@@ -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,147 @@
|
||||
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 AHashTheServerRejectsStopsTheImport()
|
||||
{
|
||||
var card = Card(context.CreateTempDirectory("card"), 8, Start);
|
||||
var staging = context.CreateTempDirectory("staging");
|
||||
var server = new FakeUploadServer(chunkSize: 4096) { Corrupt = true };
|
||||
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 error = await Assert.ThrowsAsync<TitanoApiException>(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), true, null, context.Cancellation));
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, error.Status);
|
||||
Assert.Empty(server.Committed);
|
||||
}
|
||||
|
||||
/// <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 received chunk (a damaged transfer).</summary>
|
||||
public bool Corrupt { 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 (_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 (Corrupt) 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user