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,243 @@
|
||||
using System.Globalization;
|
||||
using Titano.App.Archiving;
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
@@ -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