diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs
index 703aec2..ad90087 100644
--- a/src/Febe.Core/Export/ExportEnvironment.cs
+++ b/src/Febe.Core/Export/ExportEnvironment.cs
@@ -49,6 +49,9 @@ public sealed record ExportEnvironment
/// Time allowed to a check of a destination folder (a disconnected share must not block).
public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10);
+ /// Writes the probe file of a folder check (a seam: tests make it fail or hang); null: the real file.
+ public Action? WriteProbe { get; init; }
+
/// How often a waiting job looks whether the engine session ended.
public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5);
@@ -59,7 +62,7 @@ public sealed record ExportEnvironment
public long GroupBytes { get; init; } = 1L << 30;
/// The checker of destination folders of this environment.
- public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout);
+ public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
/// The protected folders now (Data, library, account folders, /importa) and the extra ones.
public Task FolderContextAsync(IReadOnlyList? extra, CancellationToken ct) =>
diff --git a/src/Febe.Core/Export/ExportFolderCheck.cs b/src/Febe.Core/Export/ExportFolderCheck.cs
index fa7a4e3..4729d5a 100644
--- a/src/Febe.Core/Export/ExportFolderCheck.cs
+++ b/src/Febe.Core/Export/ExportFolderCheck.cs
@@ -107,13 +107,19 @@ public sealed class ExportFolderException : IOException
/// looked for, read-only. Everything that touches the disk runs in the background with a timeout (10 s by default): a
/// disconnected share never blocks the caller.
///
-public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null)
+/// The mount table (the root of a file system is refused).
+/// Time allowed to the checks on disk; 10 s when null.
+///
+/// Writes the probe file at the full path given (a seam: tests make it fail or hang); null writes «Febe» in a new file.
+///
+public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null, Action? writeProbe = null)
{
/// Prefix of the probe file (a temporary file of : .febe-prova-*.part).
public const string ProbePrefix = SafeFileWriter.TempPrefix + "prova-";
private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts));
private readonly TimeSpan _timeout = timeout ?? TimeSpan.FromSeconds(10);
+ private readonly Action _writeProbe = writeProbe ?? WriteProbeFile;
/// A new probe file name: .febe-prova-<12 hex>.part.
public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix;
@@ -290,7 +296,7 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
/// parents of each protected folder (the candidate contains it, or is it) and, for each parent of the candidate, at the
/// same relative path under each protected folder (the candidate is inside it).
///
- private static ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList protectedFolders)
+ private ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList protectedFolders)
{
var name = NewProbeName();
var probe = Path.Combine(full, name);
@@ -298,9 +304,7 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
{
try
{
- using var stream = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None);
- stream.Write("Febe"u8);
- stream.Flush(flushToDisk: true);
+ _writeProbe(probe);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -352,6 +356,13 @@ public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout =
}
}
+ private static void WriteProbeFile(string path)
+ {
+ using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
+ stream.Write("Febe"u8);
+ stream.Flush(flushToDisk: true);
+ }
+
private static bool Exists(string path)
{
try
diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs
index 0580b1e..964213d 100644
--- a/src/Febe.Data/Stores/ExportStore.cs
+++ b/src/Febe.Data/Stores/ExportStore.cs
@@ -1,3 +1,4 @@
+using System.Globalization;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage;
@@ -896,10 +897,14 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original'
""";
- /// The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by).
+ ///
+ /// The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by). +state
+ /// keeps the planner off ix_export_copy_destination, which without statistics it took to read every Superseded and
+ /// Removed copy of the destination for each chunk of SHA-256.
+ ///
internal static string ReplacedStatesSql(string shaList) => $"""
SELECT account_id, superseded_by_sha256, state, id FROM export_copy
- WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND state IN ('Superseded', 'Removed')
+ WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed')
""";
private const string CandidateColumns =
@@ -1040,10 +1045,18 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
var changed = 0;
foreach (var chunk in copyIds.Distinct().Chunk(IdChunk))
{
- var command = w.Command(string.Empty).With("@at", Sql.Time(at));
- var list = command.AddList("i", chunk);
+ // The write context keeps one prepared command per SQL text: the text names its parameters, so a
+ // second chunk of the same size reuses the command with new values (one built on an empty text and
+ // filled in afterwards would be the first chunk's command again, its parameters still there).
+ var names = string.Join(", ", chunk.Select((_, i) => string.Create(CultureInfo.InvariantCulture, $"@i{i}")));
// A Superseded row keeps the SHA-256 of the file that replaced it: still never copied again by itself.
- command.CommandText = $"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({list}) AND state IN ('Copied', 'Superseded')";
+ var command = w.Command($"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({names}) AND state IN ('Copied', 'Superseded')")
+ .With("@at", Sql.Time(at));
+ for (var i = 0; i < chunk.Length; i++)
+ {
+ command.With(string.Create(CultureInfo.InvariantCulture, $"@i{i}"), chunk[i]);
+ }
+
changed += command.ExecuteNonQuery();
}
diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs
index ae2f6a8..eb8e9b6 100644
--- a/tests/Febe.Tests/Data/ExportConstraintTests.cs
+++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs
@@ -564,6 +564,9 @@ public sealed class ExportConstraintTests
await using var db = await TestDatabase.OpenAsync(temp);
var w = await CreateAsync(db);
await FillAsync(db, w);
+ // Two copies of the files of the world, so that the «Copie» filter has copies and history to look at.
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"));
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Removed });
// Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity.
var setShape = await PlanAsync(
@@ -627,6 +630,51 @@ public sealed class ExportConstraintTests
}
}
+ // The lookups of tappa E2 (WP1.11). The handful of destinations in use may be read whole; never the copies.
+ var shas = string.Join(", ", Enumerable.Range(0, 3).Select(i => $"@x{i}"));
+ (string, object?)[] Shas(params (string, object?)[] more) => [.. Enumerable.Range(0, 3).Select(i => ($"@x{i}", (object?)Make.Sha(i * 7))), .. more];
+ // «Una copia sola» may sort the few rows of one SHA-256 (its key is in the index the planner picks either way).
+ var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[]
+ {
+ ("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false),
+ ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original")], true),
+ ("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false),
+ ("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false),
+ };
+ foreach (var (name, sql, parameters, sortAllowed) in lookupsE2)
+ {
+ var plan = await PlanAsync(db, sql, parameters);
+ var copies = plan.Replace("SCAN export_destination", string.Empty, StringComparison.Ordinal);
+ var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan;
+ if (!plan.Contains("SEARCH export_copy USING", StringComparison.Ordinal) || !plan.Contains("sha256=?", StringComparison.Ordinal)
+ || copies.Contains("SCAN", StringComparison.Ordinal) || withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal))
+ {
+ problems.Add($"{name}: {plan}");
+ }
+ }
+
+ // The «Copie» filter: the two prefilter lists of the grouped mosaic read the copies of the destinations in use
+ // through ix_export_copy_destination, and the files through their SHA-256.
+ var x = await db.ReadAsync(ExportFilterSql.Load, default);
+ foreach (var filter in new[] { Core.Storage.LibraryCopiesFilter.Copied, Core.Storage.LibraryCopiesFilter.RemovedOrSuperseded })
+ {
+ var term = ExportFilterSql.EntryTerm(x, filter);
+ var start = term.IndexOf("+e.id IN (", StringComparison.Ordinal) + "+e.id IN (".Length;
+ var end = term.IndexOf(") AND EXISTS", start, StringComparison.Ordinal);
+ Assert.IsGreaterThan(start, end, term);
+ var plan = await PlanAsync(db, term[start..end]);
+ // With statistics that say the files are fewer than the copies (this small world), the planner may walk the
+ // SHA-256 index of the files first; the copies are always searched by destination and state.
+ var searchesCopies = plan.Contains("SEARCH c USING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal)
+ || plan.Contains("SEARCH c USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal);
+ var otherScans = plan.Replace("SCAN m2 USING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal)
+ .Replace("SCAN m2 USING COVERING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal).Contains("SCAN", StringComparison.Ordinal);
+ if (!searchesCopies || !plan.Contains("m2 USING", StringComparison.Ordinal) || otherScans || plan.Contains("TEMP B-TREE", StringComparison.Ordinal))
+ {
+ problems.Add($"prefiltro {filter}: {plan}");
+ }
+ }
+
Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}");
}
diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs
index 74f5b51..fbb28fb 100644
--- a/tests/Febe.Tests/Data/ExportStoreTests.cs
+++ b/tests/Febe.Tests/Data/ExportStoreTests.cs
@@ -1,4 +1,5 @@
using Febe.Core.Domain;
+using Febe.Core.Export;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Tests.Support;
@@ -482,6 +483,191 @@ public sealed class ExportStoreTests
Assert.AreEqual(0, await db.Exports.RelinkOrphanCopiesAsync(again.Id));
}
+ [TestMethod]
+ public async Task AccountSwitchesAreListedInBulk()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ var third = await db.Accounts.AddAsync(Make.Account("anna.demo", "300"));
+ Assert.IsEmpty(await db.Exports.ListAccountExportSwitchesAsync());
+
+ await db.Exports.SetAccountExportEnabledAsync(w.Marta, false);
+ await db.Exports.SetAccountExportEnabledAsync(third.Id, true);
+ var switches = await db.Exports.ListAccountExportSwitchesAsync();
+ Assert.HasCount(2, switches);
+ Assert.IsFalse(switches[w.Marta]);
+ Assert.IsTrue(switches[third.Id]);
+ Assert.IsFalse(switches.ContainsKey(w.Luca), "no row: «Esporta questo account» is on by default");
+
+ // Removing an account takes its switch with it.
+ await db.Accounts.DeleteAsync(third.Id);
+ CollectionAssert.AreEquivalent(new[] { w.Marta }, (await db.Exports.ListAccountExportSwitchesAsync()).Keys.ToArray());
+ }
+
+ [TestMethod]
+ public async Task ReplacedCopiesAreFoundBySupersedingSha()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ var older = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) });
+ var newer = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) });
+ await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(6) });
+
+ Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!.Id, "the newest row first");
+ Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5).ToUpperInvariant()))!.Id);
+ Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(5)), "another account");
+ Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Marta, Make.Sha(5)), "another destination");
+ Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(1)), "by the file now in the library, not by the old one");
+
+ // «Controlla le copie» turned it into Removed: it keeps the SHA-256 that replaced it and is still found.
+ Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([newer.Id], Make.T0.AddDays(1)));
+ var removed = (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!;
+ Assert.AreEqual((newer.Id, ExportCopyState.Removed, Make.Sha(5)), (removed.Id, removed.State, removed.SupersededBySha256));
+ Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(older.Id))!.State);
+ }
+
+ [TestMethod]
+ public async Task CopiesElsewhereIgnoreRetiredDestinations()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original));
+ var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own));
+ var general = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia));
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed });
+
+ Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id, "the newest Copied row");
+ Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Jpg), "another format");
+ Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2), ExportVariant.Whole, ExportFormat.Original));
+
+ await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1));
+ Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id);
+ await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1));
+ Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original), "a retired folder is not in use");
+
+ // A copy whose account was removed has no account to be «per un altro account».
+ var third = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"G:\Nuova"));
+ var orphan = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg", destination: third.Id));
+ await db.Accounts.DeleteAsync(w.Marta);
+ Assert.IsNull((await db.Exports.GetCopyAsync(orphan.Id))!.AccountId);
+ Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original));
+ }
+
+ [TestMethod]
+ public async Task CopyStatesAreReadInBatch()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ // 1,000 originals of marta.demo in the general folder (more than one chunk of 900 parameters): every tenth is
+ // Removed, every tenth plus one Superseded, every tenth plus two Failed, the rest Copied; none for luca.demo.
+ await InsertCopiesAsync(db, w, i => (i % 10) switch { 0 => "Removed", 1 => "Superseded", 2 => "Failed", _ => "Copied" });
+
+ var keys = Enumerable.Range(0, 1000).Select(i => (w.Marta, Make.Sha(100 + i)))
+ .Append((w.Luca, Make.Sha(100)))
+ .Append((w.Marta, Make.Sha(5001))) // the file that superseded the copy of number 1
+ .Append((w.Marta, Make.Sha(4000)))
+ .ToList();
+ var states = await db.Exports.GetCopyStatesAsync(w.General, keys);
+ Assert.HasCount(1001, states);
+ for (var i = 0; i < 1000; i++)
+ {
+ var expected = (i % 10) switch { 0 => ExportCopyState.Removed, 1 => ExportCopyState.Superseded, 2 => ExportCopyState.Failed, _ => ExportCopyState.Copied };
+ Assert.AreEqual(expected, states[(w.Marta, Make.Sha(100 + i))], i.ToString(System.Globalization.CultureInfo.InvariantCulture));
+ }
+
+ Assert.AreEqual(ExportCopyState.Superseded, states[(w.Marta, Make.Sha(5001))]);
+ Assert.IsFalse(states.ContainsKey((w.Luca, Make.Sha(100))));
+ Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(4000))));
+ Assert.IsEmpty(await db.Exports.GetCopyStatesAsync(w.Own, keys));
+
+ // A new Copied row of a removed copy is the current state; the history stays behind it.
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/0 (2).jpg") with { SourceSha256 = Make.Sha(100), CopySha256 = Make.Sha(100) });
+ Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.General, [(w.Marta, Make.Sha(100))]))[(w.Marta, Make.Sha(100))]);
+ }
+
+ [TestMethod]
+ public async Task MissingCopiesAreMarkedRemovedInOneTransaction()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ await InsertCopiesAsync(db, w, i => (i % 4) switch { 0 => "Superseded", 1 => "Failed", 2 => "Removed", _ => "Copied" });
+ var all = await db.Exports.ListCopiesAsync(w.General, limit: 2000);
+ Assert.HasCount(1000, all);
+ Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync([], Make.T0));
+
+ // Every id, twice, over two chunks: only the Copied and Superseded rows change, each once.
+ var ids = all.Select(c => c.Id).Concat(all.Select(c => c.Id)).ToList();
+ Assert.AreEqual(500, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(3)));
+ var after = (await db.Exports.ListCopiesAsync(w.General, limit: 2000)).ToDictionary(c => c.Id);
+ foreach (var before in all)
+ {
+ var now = after[before.Id];
+ if (before.State is ExportCopyState.Copied or ExportCopyState.Superseded)
+ {
+ Assert.AreEqual((ExportCopyState.Removed, Make.T0.AddDays(3)), (now.State, now.StateChangedAt));
+ Assert.AreEqual(before.SupersededBySha256, now.SupersededBySha256, "a superseded copy keeps the file that replaced it");
+ }
+ else
+ {
+ Assert.AreEqual(before, now);
+ }
+ }
+
+ Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(4)), "idempotent");
+ }
+
+ [TestMethod]
+ public async Task CandidatesFollowTheLibraryFilter()
+ {
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await CreateAsync(db);
+ var story = await db.Entries.AddAsync(Make.Entry(w.Luca, "556", Make.T0.AddDays(1), EntryKind.Story), [Make.Stored(Make.Photo(1), Make.Sha(3), "storie/s.jpg"), Make.Stored(Make.Photo(2), Make.Sha(4), "storie/s2.jpg")]);
+ var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = w.Luca, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 });
+ await db.Highlights.AddItemAsync(highlight.Id, story.Stored.Entry.Id);
+ var waiting = await db.Entries.AddAsync(Make.Entry(w.Luca, "557", Make.T0.AddDays(2)), [Make.Photo(1)]);
+
+ var lucaFilter = new ExportSelection.Filter(new LibraryFilter { AccountIds = [w.Luca] }, MosaicMode.Grouped);
+ var luca = await db.Exports.ListCandidatesAsync(lucaFilter, 0, 100);
+ CollectionAssert.AreEqual(new[] { w.LucaMedia, story.Stored.Media[0].Id, story.Stored.Media[1].Id }, luca.Select(c => c.MediaId).ToArray(), "an entry still to download is not in the library");
+ var first = luca.Single(c => c.MediaId == story.Stored.Media[0].Id);
+ Assert.AreEqual((story.Stored.Entry.Id, w.Luca, EntryKind.Story, MediaKind.Photo, Make.Sha(3), "storie/s.jpg", 1, true),
+ (first.EntryId, first.AccountId, first.EntryKind, first.MediaKind, first.Sha256, first.RelativePath, first.Position, first.InHighlight));
+ Assert.IsFalse(luca[0].InHighlight);
+
+ // Pages by media id.
+ var page = await db.Exports.ListCandidatesAsync(lucaFilter, w.LucaMedia, 1);
+ Assert.AreEqual(story.Stored.Media[0].Id, page.Single().MediaId);
+
+ // An explicit choice of an entry that is not downloaded yet: listed, to be counted «non presente in libreria».
+ var chosen = await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([waiting.Stored.Entry.Id]), 0, 100);
+ Assert.AreEqual((waiting.Stored.Media[0].Id, MediaState.ToDownload, (string?)null), (chosen.Single().MediaId, chosen[0].State, chosen[0].Sha256));
+ }
+
+ /// 1,000 whole copies of marta.demo in the general folder, SHA-256 100.. with the state chosen per number (a Superseded one by 5000 + n).
+ private static Task InsertCopiesAsync(FebeDatabase db, ExportWorld w, Func stateOf) =>
+ db.WriteAsync(
+ x =>
+ {
+ var insert = x.Command("""
+ INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256, relative_path, bytes, copy_sha256, copied_at)
+ VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, CASE WHEN @p IS NULL THEN NULL ELSE 10 END, CASE WHEN @p IS NULL THEN NULL ELSE @h END, 0)
+ """);
+ for (var i = 0; i < 1000; i++)
+ {
+ var state = stateOf(i);
+ insert.With("@d", w.General).With("@a", w.Marta).With("@h", Make.Sha(100 + i)).With("@s", state)
+ .With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null)
+ .With("@p", state == "Failed" ? null : $"marta.demo/{i}.jpg").ExecuteNonQuery();
+ }
+ },
+ default);
+
private static Task<(string? InstagramId, string? Username)> RemovedAccountAsync(FebeDatabase db, long copyId) =>
db.ReadAsync(
c =>
diff --git a/tests/Febe.Tests/Export/ExportCopierTests.cs b/tests/Febe.Tests/Export/ExportCopierTests.cs
new file mode 100644
index 0000000..f4ed1e4
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportCopierTests.cs
@@ -0,0 +1,391 @@
+using System.Security.Cryptography;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// The copy job on real folders (spec §4.10 «Come si copia», §4.10 l.272-274; the E2 row: «nessuna sovrascrittura»,
+/// «adozione», «radice mai creata»). The cases already in (account segment, «Tolto»,
+/// adoption next to a taken name, missing root, sessions and space, FAT32, leftovers after a restart) are not repeated.
+///
+[TestClass]
+public sealed class ExportCopierTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task CopiesOriginalsByteForByteAndRecordsThem()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "950", Make.T0.AddDays(-3)), [ExportTestBed.Photo(1, 21), TestFile.Video(2, 70_000)]);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var items = await bed.ItemsAsync(start.Runs.Single().Id, ct);
+ Assert.HasCount(2, items);
+ foreach (var media in post.Media)
+ {
+ var item = items.Single(i => i.MediaId == media.Id);
+ Assert.AreEqual((ExportItemState.Copied, ExportVariant.Whole, ExportFormat.Original), (item.State, item.Variant, item.Format));
+ var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
+ Assert.AreEqual((ExportCopyState.Copied, ExportCopyOrigin.Written), (copy.State, copy.Origin));
+ Assert.AreEqual((usb.Id, bed.Marta.Id, media.Id), (copy.DestinationId, copy.AccountId, copy.MediaId));
+ Assert.AreEqual((media.Sha256, media.Sha256, media.Bytes), (copy.SourceSha256, copy.CopySha256, copy.Bytes));
+ Assert.AreEqual(item.RelativePath, copy.RelativePath);
+ Assert.AreEqual("marta.demo/" + media.RelativePath, copy.RelativePath);
+ Assert.AreEqual(bed.Clock.Now, copy.CopiedAt);
+
+ var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!));
+ Assert.AreEqual(media.Sha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(file, ct))));
+ Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(file)); // «libreria.data-file-pubblicazione» is on
+ }
+
+ Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
+ var run = await bed.RunAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual((ExportRunState.Completed, ExportRunKind.Copy, ExportRunOrigin.Manual), (run.State, run.Kind, run.Origin));
+ var completed = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Single(e => e.Code == "esportazione-completata");
+ Assert.AreEqual(EventSeverity.Success, completed.Severity);
+ }
+
+ [TestMethod]
+ public async Task TheFileTimeIsLeftAloneWhenTheLibrarySaysSo()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "951", 22);
+ await bed.Db.Settings.SetAsync(Core.Storage.SettingKeys.SetFileTimeToPublication, "false", ct);
+ await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.AreNotEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ }
+
+ [TestMethod]
+ public async Task TheRootIsNeverCreatedWhenTheDiskGoesDuringAJob()
+ {
+ var ct = TestContext.CancellationToken;
+ var unplug = new Unplug();
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = unplug });
+ var post = await bed.PostAsync(bed.Marta, "952", 23, 24);
+ var usb = await bed.GeneralAsync(ct: ct);
+ unplug.Root = bed.Usb;
+ unplug.When = path => path.EndsWith("_2.jpg", StringComparison.Ordinal); // the disk goes while the second file starts
+
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var run = await bed.RunAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual(ExportRunState.Paused, run.State);
+ Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created again");
+ Assert.IsTrue(post.Media.All(m => File.Exists(bed.LibraryFile(bed.Marta, m))), "the library is untouched");
+ var items = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value);
+ Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State);
+ Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State);
+ Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(items[post.Media[0].Id].CopyId!.Value, ct))!.State, "never «Tolto» because the disk went");
+ Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+
+ // Plugged in again (empty): «Riprendi» writes the second file only.
+ unplug.When = _ => false;
+ Directory.CreateDirectory(bed.Usb);
+ await bed.Service.ResumeAsync([run.Id], ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[1])));
+ }
+
+ [TestMethod]
+ public async Task AnIdenticalFileAtThePathIsAdoptedAndASameSizeDifferentFileIsNot()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var same = await bed.PostAsync(bed.Marta, "953", 25);
+ var other = await bed.PostAsync(bed.Marta, "954", 26);
+ await bed.GeneralAsync(ct: ct);
+
+ // An earlier copy by hand, with its own date, and a file of the same size but other bytes.
+ var adopted = bed.GeneralCopy(bed.Marta, same.Media[0]);
+ var foreign = bed.GeneralCopy(bed.Marta, other.Media[0]);
+ Directory.CreateDirectory(Path.GetDirectoryName(adopted)!);
+ File.Copy(bed.LibraryFile(bed.Marta, same.Media[0]), adopted);
+ var handDate = new DateTime(2020, 5, 1, 12, 0, 0, DateTimeKind.Utc);
+ File.SetLastWriteTimeUtc(adopted, handDate);
+ var bytes = await File.ReadAllBytesAsync(bed.LibraryFile(bed.Marta, other.Media[0]), ct);
+ bytes[^3] ^= 0x01;
+ await File.WriteAllBytesAsync(foreign, bytes, ct);
+ var before = Fingerprint.Of(bed.Usb);
+
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value);
+ var adoption = items[same.Media[0].Id];
+ Assert.AreEqual(ExportItemState.Adopted, adoption.State);
+ var copy = (await bed.Db.Exports.GetCopyAsync(adoption.CopyId!.Value, ct))!;
+ Assert.AreEqual((ExportCopyState.Copied, ExportCopyOrigin.Adopted), (copy.State, copy.Origin));
+ Assert.AreEqual(handDate, File.GetLastWriteTimeUtc(adopted), "adopted, not written again");
+
+ var written = items[other.Media[0].Id];
+ Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (written.State, written.Note));
+ StringAssert.EndsWith(written.RelativePath, " (2).jpg");
+
+ // Both files that were there are exactly as they were; one new file beside them.
+ var after = Fingerprint.Of(bed.Usb);
+ foreach (var (path, print) in before)
+ {
+ Assert.AreEqual(print, after[path], path);
+ }
+
+ Assert.AreEqual(before.Count + 1, after.Count);
+ Assert.IsTrue(after.ContainsKey(written.RelativePath!));
+ }
+
+ [TestMethod]
+ public async Task AnOrphanRowOnThePathIsRelinkedOnAdoption()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ await bed.PostAsync(bed.Marta, "955", 27);
+ await bed.GeneralAsync(ct: ct);
+ var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
+
+ // marta.demo is removed from Febe (her copy stays, without an account) and another account with that name comes:
+ // another Instagram id, so the copy does not come back by itself.
+ await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
+ Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
+ Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId);
+ var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
+ Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId);
+ await bed.PostAsync(again, "955", 27); // the same post, the same bytes
+
+ var files = Fingerprint.Of(bed.Usb);
+ var start = await bed.CopyAccountAsync(again, ct: ct);
+ var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual((ExportItemState.Adopted, copyId), (item.State, item.CopyId));
+ var relinked = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
+ Assert.AreEqual((again.Id, ExportCopyState.Copied), (relinked.AccountId, relinked.State));
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
+ Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(again.Id)), ct)).Files);
+ }
+
+ [TestMethod]
+ public async Task AResumedItemAdoptsItsOwnFileAfterACrash()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "956", 28);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var planned = "marta.demo/" + post.Media[0].RelativePath;
+
+ // Before the crash: the planned name was taken by another file, ours was renamed «(2)», the record never came.
+ var taken = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(planned));
+ Directory.CreateDirectory(Path.GetDirectoryName(taken)!);
+ await File.WriteAllBytesAsync(taken, [7, 7, 7], ct);
+ var ours = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(ExportPaths.NumberedName(bed.Usb, planned, 2)));
+ File.Copy(bed.LibraryFile(bed.Marta, post.Media[0]), ours);
+ var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = bed.Clock.Now }, ct);
+ await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = bed.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
+ var pending = (await bed.ItemsAsync(run.Id, ct)).Single();
+ await bed.Db.Exports.UpdateItemsAsync([pending with { RelativePath = planned }], ct);
+ var files = Fingerprint.Of(bed.Usb);
+
+ Assert.AreEqual(1, await bed.Service.RecoverAsync(ct));
+ await bed.Service.ResumeAsync(null, ct);
+ await bed.Service.WaitAsync(ct);
+
+ var item = (await bed.ItemsAsync(run.Id, ct)).Single();
+ Assert.AreEqual(ExportItemState.Adopted, item.State);
+ Assert.AreEqual(ExportPaths.NumberedName(bed.Usb, planned, 2), item.RelativePath);
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "no second file, nothing overwritten");
+ Assert.AreEqual(ExportCopyOrigin.Adopted, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.Origin);
+ }
+
+ [TestMethod]
+ public async Task ACorruptedReadIsNotRenamedAndAFailedCopyIsRetried()
+ {
+ var ct = TestContext.CancellationToken;
+ var corrupt = true;
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = new CorruptingExportFileSystem(_ => Volatile.Read(ref corrupt)) });
+ var post = await bed.PostAsync(bed.Marta, "957", 29);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual((ExportItemState.Failed, ExportText.Notes.SourceChanged), (item.State, item.Note));
+ Assert.AreEqual("Il file della libreria non corrisponde a quello registrato.", item.LastError);
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb), "no final file, no .part left");
+ var failed = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
+ Assert.AreEqual(ExportCopyState.Failed, failed.State);
+ Assert.IsNull(failed.RelativePath);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State, "the job goes on");
+ Assert.AreEqual(EventSeverity.Warning, (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Single(e => e.Code == "esportazione-completata").Severity);
+ Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 1, 0, 1), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
+
+ // The cable is fixed: the next «Copia in…» tries again, on the same copy row.
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ Assert.AreEqual(1, plan.Files);
+ Volatile.Write(ref corrupt, false);
+ var again = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var retried = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual((ExportItemState.Copied, failed.Id), (retried.State, retried.CopyId));
+ var copy = (await bed.Db.Exports.GetCopyAsync(failed.Id, ct))!;
+ Assert.AreEqual((ExportCopyState.Copied, (string?)null), (copy.State, copy.LastError));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
+ }
+
+ [TestMethod]
+ public async Task AFileMissingInTheLibraryIsReportedNotDownloaded()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var present = await bed.PostAsync(bed.Marta, "958", 30, 31);
+ var waiting = await bed.Db.Entries.AddAsync(Make.Entry(bed.Marta.Id, "959", Make.T0.AddDays(-2)), [Make.Photo(1)], ct); // still to download
+ await bed.GeneralAsync(ct: ct);
+ File.Delete(bed.LibraryFile(bed.Marta, present.Media[1])); // gone from the disk behind Febe's back
+
+ var request = new ExportJobRequest(new ExportSelection.Entries([present.Entry.Id, waiting.Stored.Entry.Id]));
+ var plan = await bed.Service.PlanAsync(request, ct);
+ Assert.AreEqual((2, 1), (plan.Files, plan.Missing)); // the plan reads the database only
+
+ var start = await bed.CopyAsync(request, ct);
+ var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value);
+ Assert.HasCount(2, items); // the file to download has no item: it is only counted
+ Assert.AreEqual(ExportItemState.Copied, items[present.Media[0].Id].State);
+ var missing = items[present.Media[1].Id];
+ Assert.AreEqual((ExportItemState.Missing, ExportText.Notes.SourceMissing), (missing.State, missing.Note));
+ Assert.AreEqual("File non presente in libreria", ExportText.Note(missing.Note!));
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+ Assert.IsFalse(File.Exists(bed.LibraryFile(bed.Marta, present.Media[1])), "nothing is downloaded or restored");
+ var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual(1, report.ByState[ExportItemState.Missing]);
+ }
+
+ [TestMethod]
+ public async Task NotEnoughSpacePausesTheDestinationAtTheMargin()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "960", 32);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var bytes = post.Media[0].Bytes!.Value;
+
+ bed.Disk.Free = bytes + ExportSpace.Margin - 1;
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var run = await bed.RunAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual(ExportRunState.Paused, run.State);
+ var paused = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
+ Assert.IsNotNull(paused.PausedAt);
+ Assert.AreEqual(run.LastError, paused.LastError);
+ StringAssert.Contains(paused.LastError, "margine di 64 MB");
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb));
+ Assert.IsTrue((await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Destinations.Single().Paused);
+
+ bed.Disk.Free = bytes + ExportSpace.Margin; // exactly the margin is enough
+ await bed.Service.ResumeAsync([run.Id], ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
+ Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+ }
+
+ [TestMethod]
+ public async Task AProbeFailurePausesAndResumeCarriesOn()
+ {
+ var ct = TestContext.CancellationToken;
+ var probes = 0;
+ var failAt = -1;
+ await using var bed = await ExportTestBed.CreateAsync(env => env with
+ {
+ GroupFiles = 1, // a probe before every file
+ WriteProbe = path =>
+ {
+ if (Interlocked.Increment(ref probes) == Volatile.Read(ref failAt))
+ {
+ throw new IOException("Il supporto è protetto da scrittura.");
+ }
+
+ File.WriteAllText(path, "Febe");
+ },
+ });
+ var post = await bed.PostAsync(bed.Marta, "961", 33, 34);
+ var usb = await bed.GeneralAsync(ct: ct);
+ Volatile.Write(ref failAt, Volatile.Read(ref probes) + 2); // the probe before the second file fails
+
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var run = await bed.RunAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual(ExportRunState.Paused, run.State);
+ StringAssert.StartsWith(run.LastError, $"Febe non riesce a scrivere in {Path.GetFullPath(bed.Usb)}");
+ var items = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value);
+ Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State);
+ Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State);
+ Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+ var alert = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportPause.PausedEventCode).ToList();
+ Assert.HasCount(1, alert);
+ Assert.AreNotEqual(EventSeverity.Error, alert[0].Severity, "a pause, never the red strip");
+
+ await bed.Service.ResumeAsync(null, ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
+ Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(run.Id, ct)).Single(i => i.MediaId == post.Media[1].Id).State);
+ Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+ Assert.HasCount(2, Fingerprint.Of(bed.Usb));
+ }
+
+ [TestMethod]
+ public async Task ThePartFilesOfADiscardedRunAreCleanedOnlyInItsFolders()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "962", 35);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var relative = "marta.demo/" + post.Media[0].RelativePath;
+ var folder = Path.GetDirectoryName(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(relative)))!;
+ var elsewhere = bed.Temp.Combine("usb", "altro");
+ Directory.CreateDirectory(folder);
+ Directory.CreateDirectory(elsewhere);
+ var ours = Path.Combine(folder, ".febe-0123456789ab.part");
+ var notInAFolderOfItems = Path.Combine(elsewhere, ".febe-ba9876543210.part");
+ var alberto = Path.Combine(folder, "appunti.part"); // not one of our names
+ foreach (var file in new[] { ours, notInAFolderOfItems, alberto })
+ {
+ await File.WriteAllBytesAsync(file, [9], ct);
+ }
+
+ var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
+ await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = bed.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct);
+ var item = (await bed.ItemsAsync(run.Id, ct)).Single();
+ await bed.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct);
+
+ await bed.Service.DiscardAsync(run.Id, ct);
+ Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State);
+ Assert.IsFalse(File.Exists(ours));
+ Assert.IsTrue(File.Exists(notInAFolderOfItems));
+ Assert.IsTrue(File.Exists(alberto));
+ await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([run.Id], ct));
+ }
+
+ /// The real file system; opening a chosen library file first takes the destination disk away.
+ private sealed class Unplug : IExportFileSystem
+ {
+ public string? Root { get; set; }
+
+ public Func When { get; set; } = _ => false;
+
+ public Stream OpenRead(string path)
+ {
+ if (Root is { } root && When(path) && Directory.Exists(root))
+ {
+ Directory.Delete(root, recursive: true);
+ }
+
+ return ExportFileSystem.Instance.OpenRead(path);
+ }
+
+ public Task ComputeSha256Async(string path, CancellationToken ct) => ExportFileSystem.Instance.ComputeSha256Async(path, ct);
+
+ public bool FileExists(string path) => ExportFileSystem.Instance.FileExists(path);
+
+ public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path);
+ }
+}
diff --git a/tests/Febe.Tests/Export/ExportDestinationsTests.cs b/tests/Febe.Tests/Export/ExportDestinationsTests.cs
new file mode 100644
index 0000000..8e6583a
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportDestinationsTests.cs
@@ -0,0 +1,281 @@
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// Destinations and «Esporta questo account» (spec §4.10 «Destinazioni»; decisions D1, D2, D8 and WP1.10 of tappa E2).
+///
+[TestClass]
+public sealed class ExportDestinationsTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task TheAccountSwitchIsOnWhenNothingIsRecorded()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ Assert.IsTrue(ExportAccounts.IsEnabled(null));
+ Assert.IsNull(await bed.Db.Exports.GetAccountExportEnabledAsync(bed.Marta.Id, ct));
+ Assert.IsEmpty(await bed.Db.Exports.ListAccountExportSwitchesAsync(ct));
+
+ var before = await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct);
+ Assert.IsTrue(before.Enabled);
+ Assert.IsFalse(before.Exports); // no folder yet
+ await bed.GeneralAsync(ct: ct);
+ var all = await bed.Service.Destinations.ResolveAllAsync(ct);
+ Assert.IsTrue(all[bed.Marta.Id].Exports && all[bed.Luca.Id].Exports);
+ Assert.IsTrue(all[bed.Marta.Id].Wants(ContentTypes.Stories));
+ Assert.IsEmpty(await bed.Db.Exports.ListAccountExportSwitchesAsync(ct)); // reading never writes a row
+ }
+
+ [TestMethod]
+ public async Task TheSwitchOffIsRemembered()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ await bed.GeneralAsync(ct: ct);
+ await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
+
+ var again = new ExportDestinations(bed.Environment); // another service reads the database, not a cache
+ var marta = await again.ResolveAsync(bed.Marta.Id, ct);
+ Assert.IsFalse(marta.Enabled);
+ Assert.IsTrue(marta.HasDestination);
+ Assert.IsFalse(marta.Exports);
+ Assert.IsFalse(marta.Wants(ContentTypes.PostPhotos));
+ Assert.IsTrue((await again.ResolveAllAsync(ct))[bed.Luca.Id].Exports);
+ Assert.IsFalse((await bed.Db.Exports.ListAccountExportSwitchesAsync(ct))[bed.Marta.Id]);
+
+ await again.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
+ Assert.IsTrue(await bed.Db.Exports.GetAccountExportEnabledAsync(bed.Marta.Id, ct)); // a row with «on» now
+ Assert.IsTrue((await again.ResolveAsync(bed.Marta.Id, ct)).Exports);
+ await Assert.ThrowsExactlyAsync(() => again.SetAccountEnabledAsync(9999, false, ct));
+ }
+
+ [TestMethod]
+ public async Task TheOwnFolderReplacesTheGeneralOne()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var general = await bed.GeneralAsync(ct: ct);
+ var own = await bed.OwnAsync(bed.Marta, "marta", ContentTypes.PostPhotos, ct);
+
+ var all = await bed.Service.Destinations.ResolveAllAsync(ct);
+ Assert.AreEqual(own.Id, all[bed.Marta.Id].Destination!.Id);
+ Assert.IsTrue(all[bed.Marta.Id].IsOwn);
+ Assert.IsFalse(all[bed.Marta.Id].Wants(ContentTypes.Stories)); // the own folder's types, not the general ones
+ Assert.AreEqual(general.Id, all[bed.Luca.Id].Destination!.Id);
+ Assert.IsFalse(all[bed.Luca.Id].IsOwn);
+ Assert.AreEqual(own.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id);
+ Assert.AreEqual("marta", ExportDestinations.Label(own));
+
+ var second = await Assert.ThrowsExactlyAsync(() => bed.GeneralAsync(folder: bed.Temp.Combine("marta"), ct: ct));
+ StringAssert.StartsWith(second.Message, "C'è già una cartella generale");
+ Directory.CreateDirectory(bed.Temp.Combine("marta2"));
+ var twice = await Assert.ThrowsExactlyAsync(() => bed.OwnAsync(bed.Marta, "marta2", ct: ct));
+ StringAssert.StartsWith(twice.Message, "@marta.demo ha già una cartella sua");
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(
+ new DestinationSpec(ExportScope.Account, null, bed.Temp.Combine("marta2"), null, ContentTypes.All, null, null, null), ct));
+
+ // «Usa la cartella generale»: the own folder goes, the general one is back.
+ await bed.Service.Destinations.RetireAsync(own.Id, ct);
+ Assert.AreEqual(general.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id);
+ }
+
+ [TestMethod]
+ public async Task RetiringKeepsTheCopiesAndTheFiles()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "910", 1, 2);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
+ Assert.HasCount(2, copies);
+ var files = Fingerprint.Of(bed.Usb);
+ Assert.HasCount(2, files);
+
+ await bed.Service.Destinations.RetireAsync(usb.Id, ct);
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the files stay");
+ var retired = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
+ Assert.IsTrue(retired.IsRetired);
+ foreach (var copy in copies)
+ {
+ Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!.State);
+ }
+
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State);
+ Assert.IsFalse((await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).HasDestination);
+ var status = await bed.Service.Destinations.StatusAsync(usb.Id, ct);
+ Assert.AreEqual((false, "Questa cartella è stata tolta."), (status.Reachable, status.Problem));
+ Assert.AreEqual(2, status.Counts[ExportCopyState.Copied]);
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(
+ usb.Id, new DestinationSpec(ExportScope.General, null, bed.Usb, "Altro", ContentTypes.All, null, null, null), ct));
+ await bed.Service.Destinations.RetireAsync(usb.Id, ct); // twice: nothing happens
+
+ // Nothing is due any more: the plan says the files are not exported.
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct);
+ Assert.AreEqual((0, 2), (plan.Files, plan.NotExported));
+
+ // A new general folder on the same disk starts from nothing: the files there are adopted, never written twice.
+ var back = await bed.GeneralAsync(ct: ct);
+ var again = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.IsTrue((await bed.ItemsAsync(again.Runs.Single().Id, ct)).All(i => i.State == ExportItemState.Adopted));
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "adopted, not written");
+ Assert.AreNotEqual(usb.Id, back.Id);
+ }
+
+ [TestMethod]
+ public async Task ChangingTheFolderRetiresAndAddsAndIsRefusedWithAnUnfinishedRun()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var usb = await bed.GeneralAsync(ct: ct);
+ var nas = bed.Temp.Combine("nas");
+ Directory.CreateDirectory(nas);
+ DestinationSpec Spec(string path, string? label = null) => new(ExportScope.General, null, path, label, ContentTypes.PostPhotos | ContentTypes.Stories, null, null, null);
+
+ // The same folder: the row changes in place.
+ var renamed = await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed.Usb + Path.DirectorySeparatorChar, " Disco nero "), ct);
+ Assert.AreEqual(usb.Id, renamed.Destination.Id);
+ Assert.AreEqual("Disco nero", (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.Label);
+ Assert.AreEqual(ContentTypes.PostPhotos | ContentTypes.Stories, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes);
+
+ // Another folder, while a job writes to the old one: refused, nothing changes.
+ var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
+ var refused = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(usb.Id, Spec(nas), ct));
+ Assert.AreEqual(ExportDestinations.UnfinishedRunText, refused.Message);
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.RetireAsync(usb.Id, ct));
+ Assert.IsFalse((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.IsRetired);
+ Assert.AreEqual(usb.Id, (await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed.Usb, "Solo il nome"), ct)).Destination.Id); // the label still changes
+
+ // The job is gone: the old row is retired, a new one is added.
+ await bed.Service.DiscardAsync(run.Id, ct);
+ var moved = await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(nas), ct);
+ Assert.AreNotEqual(usb.Id, moved.Destination.Id);
+ Assert.AreEqual(Path.GetFullPath(nas), moved.Destination.RootPath);
+ Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.IsRetired);
+ Assert.AreEqual(moved.Destination.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id);
+ Assert.HasCount(1, await bed.Db.Exports.ListDestinationsAsync(includeRetired: false, ct));
+
+ // A folder that cannot be a destination leaves the destination as it was.
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(moved.Destination.Id, Spec(bed.Temp.Combine("assente")), ct));
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(
+ moved.Destination.Id, new DestinationSpec(ExportScope.Account, bed.Marta.Id, nas, null, ContentTypes.All, null, null, null), ct));
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(9999, Spec(nas), ct));
+ Assert.IsFalse((await bed.Db.Exports.GetDestinationAsync(moved.Destination.Id, ct))!.IsRetired);
+ }
+
+ [TestMethod]
+ public async Task SchemesAreValidatedLikeTheLibraryOnes()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ DestinationSpec Spec(string? general, string? highlight = null, string? profile = null) =>
+ new(ExportScope.General, null, bed.Usb, null, ContentTypes.All, general, highlight, profile);
+
+ var unknown = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{inventato}"), ct));
+ StringAssert.StartsWith(unknown.Message, "Schema: Segnaposto sconosciuto: {inventato}.");
+ var collection = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{raccolta}\{codice}_{n}"), ct));
+ StringAssert.StartsWith(collection.Message, "Schema: {raccolta} si usa solo nello schema per le raccolte in evidenza.");
+ var profile = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(null, null, @"{raccolta}\{codice}"), ct));
+ StringAssert.StartsWith(profile.Message, "Schema per le foto del profilo: {raccolta} si usa solo");
+ var brace = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(null, @"{raccolta\{codice}"), ct));
+ StringAssert.StartsWith(brace.Message, "Schema per le raccolte in evidenza: ");
+ Assert.IsEmpty(await bed.Db.Exports.ListDestinationsAsync(includeRetired: true, ct));
+
+ // Warnings do not block, and come back with their prefix; blank schemes are «Come la libreria».
+ var saved = await bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{codice}", @"{account}\{data}_{codice}_{n}", " "), ct);
+ CollectionAssert.Contains(saved.Warnings.ToList(), "Schema: Senza {n} i file di un post con più foto o video hanno lo stesso nome: Febe aggiunge un numero per distinguerli.");
+ CollectionAssert.Contains(saved.Warnings.ToList(), "Schema per le raccolte in evidenza: Senza {raccolta} i contenuti delle diverse raccolte finiscono nella stessa cartella.");
+ var stored = (await bed.Db.Exports.GetDestinationAsync(saved.Destination.Id, ct))!;
+ Assert.AreEqual(@"{anno}\{codice}", stored.NamingScheme);
+ Assert.IsNull(stored.ProfileNamingScheme);
+ }
+
+ [TestMethod]
+ public async Task NoTypeIsRefused()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ foreach (var types in new[] { ContentTypes.None, (ContentTypes)64, ContentTypes.Stories | (ContentTypes)128 })
+ {
+ var refused = await Assert.ThrowsExactlyAsync(() => bed.GeneralAsync(types, ct: ct), types.ToString());
+ StringAssert.StartsWith(refused.Message, "Scegli almeno un tipo di contenuto.");
+ }
+
+ var usb = await bed.GeneralAsync(ContentTypes.Tagged, ct: ct);
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(
+ usb.Id, new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.None, null, null, null), ct));
+ Assert.AreEqual(ContentTypes.Tagged, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes);
+ }
+
+ [TestMethod]
+ public async Task AutomaticIsStoredButNothingIsQueued()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ await bed.PostAsync(bed.Marta, "920", 1);
+ var spec = new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.All, null, null, null, Automatic: true, OnlyNew: true);
+ var saved = (await bed.Service.Destinations.CreateAsync(spec, ct)).Destination;
+ var stored = (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!;
+ Assert.IsTrue(stored.Automatic);
+ Assert.AreEqual(Make.T0, stored.AutomaticSince);
+
+ // Tappa E2 does not act on it: no job, nothing written, nothing running.
+ Assert.IsFalse(bed.Service.IsBusy);
+ Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
+ Assert.IsEmpty(Directory.GetFileSystemEntries(bed.Usb));
+
+ // Still on: «da quando» is kept; off: it goes; on with «tutti»: no date.
+ bed.Clock.Now = Make.T0.AddDays(3);
+ await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Label = "Disco" }, ct);
+ Assert.AreEqual(Make.T0, (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince);
+ await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct);
+ Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: false, AutomaticSince: null });
+ await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { OnlyNew = false }, ct);
+ Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: true, AutomaticSince: null });
+ await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct);
+ await bed.Service.Destinations.UpdateAsync(saved.Id, spec, ct);
+ Assert.AreEqual(Make.T0.AddDays(3), (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince);
+ Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
+ }
+
+ [TestMethod]
+ public async Task AnAccountFolderInsideADestinationIsRefusedOnRecheck()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var usb = await bed.GeneralAsync(ct: ct);
+ var own = await bed.OwnAsync(bed.Marta, "marta", ct: ct);
+ Assert.IsEmpty(await bed.Service.Destinations.RecheckAsync(null, ct));
+
+ // The folder Alberto is about to give luca.demo sits inside the general folder.
+ var planned = Path.Combine(bed.Usb, "luca");
+ var conflicts = await bed.Service.Destinations.RecheckAsync([planned], ct);
+ var conflict = conflicts.Single();
+ Assert.AreEqual(usb.Id, conflict.Destination.Id);
+ Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, conflict.Problem.Kind);
+ Assert.AreEqual($"{Path.GetFullPath(bed.Usb)} contiene la cartella di un account: scegli una cartella che non la contenga.", conflict.Problem.Message);
+ Assert.IsFalse(Directory.Exists(planned)); // checked as text: the folder is not created
+
+ // A new library root that would hold marta's own folder.
+ var root = await bed.Service.Destinations.RecheckAgainstAsync([new(bed.Temp.Path, ProtectedFolderKind.Library, null)], ct);
+ CollectionAssert.AreEquivalent(new[] { usb.Id, own.Id }, root.Select(c => c.Destination.Id).ToArray());
+ Assert.IsTrue(root.All(c => c.Problem.Kind == ExportFolderProblemKind.InsideProtected));
+
+ // After a rebuild the account folder really is there: the destination pauses, nothing is interactive.
+ Directory.CreateDirectory(planned);
+ await bed.Db.Accounts.UpdateAsync(bed.Luca with { Folder = planned }, ct);
+ var paused = await bed.Service.Destinations.RecheckAndPauseAsync(ct);
+ Assert.AreEqual(usb.Id, paused.Single().Destination.Id);
+ var row = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!;
+ Assert.IsNotNull(row.PausedAt);
+ StringAssert.Contains(row.LastError, "contiene la cartella dell'account @luca.demo");
+ Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(own.Id, ct))!.PausedAt);
+ Assert.IsFalse(row.IsRetired);
+ }
+}
diff --git a/tests/Febe.Tests/Export/ExportFilterTests.cs b/tests/Febe.Tests/Export/ExportFilterTests.cs
new file mode 100644
index 0000000..5df6c91
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportFilterTests.cs
@@ -0,0 +1,165 @@
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Storage;
+using Febe.Data;
+using Febe.Tests.Data;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// The rules of the «Copie» filter that does not reach (decision D3 of tappa E2):
+/// a file is judged in the effective destination of its account only, «Tolti o superati» takes both states, a content
+/// type the destination does not take is not due, retired destinations do not count, and «Una copia sola» counts the
+/// copies of the other accounts. Marks, account counts, totals and days follow the same rules.
+///
+[TestClass]
+public sealed class ExportFilterTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task RemovedOrSupersededFindsBothStates()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await ExportWorld.CreateAsync(db);
+ await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct); // marta.demo goes to the general folder too
+ // Her file was replaced in the library (Sha(1) → Sha(5)) after its copy.
+ await db.Media.MarkStoredAsync(w.MartaMedia, new StoredFile("post/a.jpg", 2000, Make.Sha(5), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct);
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) }, ct);
+ await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed }, ct);
+
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct));
+ Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
+ Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct), "a «tolto» or «superato» file is not «non ancora copiato»");
+ Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
+ Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct));
+
+ // A newer Copied row for the same file wins over the old state.
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg") with { SourceSha256 = Make.Sha(5), CopySha256 = Make.Sha(5) }, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
+ CollectionAssert.AreEquivalent(new[] { w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct));
+ Assert.AreEqual(ExportMark.Copied, (await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct))[w.MartaEntry]);
+ }
+
+ [TestMethod]
+ public async Task TheFilterFollowsTheEffectiveDestinationOfEachAccount()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await ExportWorld.CreateAsync(db);
+
+ // marta.demo has her own folder: a copy in the general folder does not make her file «copiato».
+ await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"), ct);
+ Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ Assert.AreEqual(ExportMark.None, (await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct))[w.MartaEntry]);
+
+ // Her own folder is retired: the general folder is hers again, with the copy already there.
+ await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
+ Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
+
+ // The general folder is retired as well: nothing is due, so nothing is in any of the three.
+ await db.Exports.RetireDestinationAsync(w.General, Make.T0, ct);
+ foreach (var filter in Enum.GetValues())
+ {
+ Assert.IsEmpty(await EntriesAsync(db, filter, ct), filter.ToString());
+ }
+
+ Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
+ Assert.IsEmpty(await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry], ct));
+ Assert.AreEqual(new LibraryTotals(0, 0), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, ct));
+ }
+
+ [TestMethod]
+ public async Task ExcludedTypesAndSwitchedOffAccountsAreNotDue()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await ExportWorld.CreateAsync(db);
+ var general = (await db.Exports.GetDestinationAsync(w.General, ct))!;
+ await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.All & ~ContentTypes.Tagged }, ct);
+ // A story of luca.demo in a highlight: due for «Evidenza» even without «Storie».
+ var story = await db.Entries.AddAsync(Make.Entry(w.Luca, "556", Make.T0, EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(4), "storie/s.jpg")], ct);
+ var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = w.Luca, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 }, ct);
+ await db.Highlights.AddItemAsync(highlight.Id, story.Stored.Entry.Id, ct);
+
+ // luca.demo's tagged post is not due in a folder without «Taggati».
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, story.Stored.Entry.Id }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ Assert.AreEqual(new ExportAccountCounts(1, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct));
+ Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.LucaEntry], ct)).ContainsKey(w.LucaEntry));
+
+ await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.Highlights }, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, story.Stored.Entry.Id }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.PostPhotos }, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+
+ // Switched off, an account has no due file even in its own folder.
+ await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct);
+ Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ await db.Exports.SetAccountExportEnabledAsync(w.Marta, true, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ }
+
+ [TestMethod]
+ public async Task OneCopyOnlyCountsCopiesOfOtherAccounts()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await ExportWorld.CreateAsync(db);
+ await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); // marta.demo's, in her own folder
+
+ CollectionAssert.AreEquivalent(new[] { w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly }).SaveAsync(db.Settings, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct));
+ Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct));
+ Assert.AreEqual(ExportMark.Copied, (await db.Exports.GetFileMarksAsync([w.LucaMedia], ct))[w.LucaMedia]);
+
+ // Only a copy in a destination in use counts.
+ await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct);
+ CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct));
+ }
+
+ [TestMethod]
+ public async Task FilesModeTotalsAndDaysObeyTheFilter()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await ExportWorld.CreateAsync(db);
+ var other = await db.Entries.AddAsync(
+ Make.Entry(w.Marta, "557", Make.T0.AddDays(3)),
+ [Make.Stored(Make.Photo(1), Make.Sha(6), "post/c1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(7), "post/c2.jpg"), Make.Stored(Make.Photo(3), Make.Sha(8), "post/c3.jpg")],
+ ct);
+ await db.Exports.AddCopyAsync(w.WholeCopy("c2.jpg", destination: w.Own, media: other.Stored.Media[1].Id) with { SourceSha256 = Make.Sha(7), CopySha256 = Make.Sha(7) }, ct);
+
+ var notCopied = new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied, AccountIds = [w.Marta] };
+ var copied = notCopied with { Copies = LibraryCopiesFilter.Copied };
+ Assert.AreEqual(new LibraryTotals(2, 1), await db.Entries.GetLibraryTotalsAsync(notCopied, ct)); // a partly copied entry is «non ancora copiato»
+ Assert.AreEqual(new LibraryTotals(0, 0), await db.Entries.GetLibraryTotalsAsync(copied, ct));
+ Assert.AreEqual(3, (await db.Entries.CountLibraryByDayAsync(notCopied, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
+ Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(copied, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count));
+ var days = await db.Entries.CountLibraryByDayAsync(notCopied, TestZones.Rome, ct: ct);
+ Assert.HasCount(2, days);
+ Assert.AreEqual(ExportMark.Partly, (await db.Exports.GetEntryMarksAsync([other.Stored.Entry.Id], ct))[other.Stored.Entry.Id]);
+ Assert.AreEqual(new ExportAccountCounts(4, 3, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct));
+
+ // The «Copia i file in…» selection of the filter takes exactly the files the mosaic shows.
+ var selection = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(notCopied, MosaicMode.Files), 0, 100, ct);
+ CollectionAssert.AreEquivalent(
+ new[] { w.MartaMedia, other.Stored.Media[0].Id, other.Stored.Media[2].Id },
+ selection.Select(c => c.MediaId).ToArray());
+ var byEntries = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(notCopied, MosaicMode.Grouped), 0, 100, ct);
+ Assert.HasCount(4, byEntries);
+ }
+
+ private static async Task EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) =>
+ [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)];
+}
diff --git a/tests/Febe.Tests/Export/ExportFolderCheckTests.cs b/tests/Febe.Tests/Export/ExportFolderCheckTests.cs
new file mode 100644
index 0000000..90cfc55
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportFolderCheckTests.cs
@@ -0,0 +1,287 @@
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// «Cartelle rifiutate» of spec §4.10 (decision D13 of tappa E2): textual checks, then the identity test with a probe
+/// written only in the candidate. Failures of the disk are injected through the probe seam, never provoked with
+/// permissions (the CI runs as root, which writes anywhere).
+///
+[TestClass]
+public sealed class ExportFolderCheckTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task AMissingFolderIsRefusedAndNeverCreated()
+ {
+ using var temp = new TempFolder();
+ var missing = temp.Combine("disco", "Febe");
+ var verdict = await Check().CheckAsync(missing, Context(temp), TestContext.CancellationToken);
+ Assert.AreEqual(ExportFolderProblemKind.Missing, verdict.Problem!.Kind);
+ Assert.StartsWith($"La cartella {Path.GetFullPath(missing)} non esiste. Febe non crea mai la cartella di una destinazione", verdict.Problem.Message);
+ Assert.IsFalse(Directory.Exists(temp.Combine("disco")));
+ Assert.IsFalse(verdict.Accepted);
+ }
+
+ [TestMethod]
+ public async Task AFileIsNotAFolder()
+ {
+ using var temp = new TempFolder();
+ var file = temp.Combine("copie.txt");
+ await File.WriteAllTextAsync(file, "testo", TestContext.CancellationToken);
+ var verdict = await Check().CheckAsync(file, Context(temp), TestContext.CancellationToken);
+ Assert.AreEqual(ExportFolderProblemKind.NotAFolder, verdict.Problem!.Kind);
+ Assert.AreEqual($"{Path.GetFullPath(file)} è un file: scegli una cartella.", verdict.Problem.Message);
+ Assert.AreEqual("testo", await File.ReadAllTextAsync(file, TestContext.CancellationToken));
+ }
+
+ [TestMethod]
+ public async Task TheRootOfADiskIsRefused()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var context = Context(temp);
+
+ // Windows: «C:\», textually; Linux: «/».
+ var root = Path.GetPathRoot(temp.Path)!;
+ var verdict = await Check().CheckAsync(root, context, ct);
+ Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, verdict.Problem!.Kind, verdict.Problem.Message);
+ StringAssert.Contains(verdict.Problem.Message, "è la radice di un disco o di una condivisione");
+
+ // Linux: a mount point that shows the root of its file system (a USB disk mounted there) is a root too; one that
+ // shows a folder of its file system is not (Windows decides from the path alone).
+ var usb = temp.Combine("usb");
+ var nas = temp.Combine("nas");
+ Directory.CreateDirectory(usb);
+ Directory.CreateDirectory(nas);
+ var mounts = new FixedMounts(ExportRootTests.Mount(usb, "/"), ExportRootTests.Mount(nas, "/condivisa/foto"));
+ var onMount = await new ExportFolderCheck(mounts).CheckAsync(usb, context, ct);
+ if (OperatingSystem.IsWindows())
+ {
+ Assert.IsTrue(onMount.Accepted, onMount.Problem?.Message);
+ }
+ else
+ {
+ Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, onMount.Problem!.Kind);
+ }
+
+ Assert.IsTrue((await new ExportFolderCheck(mounts).CheckAsync(nas, context, ct)).Accepted);
+ Directory.CreateDirectory(Path.Combine(usb, "Febe"));
+ Assert.IsTrue((await new ExportFolderCheck(mounts).CheckAsync(Path.Combine(usb, "Febe"), context, ct)).Accepted);
+ }
+
+ [TestMethod]
+ [DataRow(ProtectedFolderKind.Data, "la cartella dei dati di Febe")]
+ [DataRow(ProtectedFolderKind.Library, "la cartella della libreria")]
+ [DataRow(ProtectedFolderKind.Account, "la cartella dell'account @marta.demo")]
+ [DataRow(ProtectedFolderKind.Import, "la cartella delle importazioni")]
+ public async Task FoldersInsideOrContainingDataLibraryAccountsOrImportAreRefused(ProtectedFolderKind kind, string description)
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var guarded = temp.Combine("dentro", "protetta");
+ var inside = Path.Combine(guarded, "sotto");
+ var outside = temp.Combine("fuori");
+ Directory.CreateDirectory(inside);
+ Directory.CreateDirectory(outside);
+ var context = new ExportFolderContext([new(Path.GetFullPath(guarded), kind, kind == ProtectedFolderKind.Account ? "marta.demo" : null)], ExportRootOptions.AnyFolder);
+ var check = Check();
+
+ var same = (await check.CheckAsync(guarded, context, ct)).Problem!;
+ Assert.AreEqual((ExportFolderProblemKind.SameAsProtected, $"{Path.GetFullPath(guarded)} è {description}: scegli un'altra cartella."), (same.Kind, same.Message));
+ var within = (await check.CheckAsync(inside, context, ct)).Problem!;
+ Assert.AreEqual((ExportFolderProblemKind.InsideProtected, $"{Path.GetFullPath(inside)} è dentro {description}: scegli una cartella fuori."), (within.Kind, within.Message));
+ var containing = (await check.CheckAsync(temp.Combine("dentro"), context, ct)).Problem!;
+ Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, containing.Kind);
+ Assert.AreEqual($"{Path.GetFullPath(temp.Combine("dentro"))} contiene {description}: scegli una cartella che non la contenga.", containing.Message);
+ Assert.IsTrue(same.IsOverlap && within.IsOverlap && containing.IsOverlap);
+
+ Assert.IsTrue((await check.CheckAsync(outside, context, ct)).Accepted);
+ Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
+ }
+
+ [TestMethod]
+ public async Task AnAccountFolderOutsideTheLibraryCountsToo()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var elsewhere = bed.Temp.Combine("archivio", "luca");
+ Directory.CreateDirectory(Path.Combine(elsewhere, "post"));
+ await bed.Db.Accounts.UpdateAsync(bed.Luca with { Folder = elsewhere }, ct);
+ var import = bed.Temp.Combine("importa");
+ Directory.CreateDirectory(import);
+
+ var context = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, import, ExportRootOptions.AnyFolder, null, ct);
+ var kinds = context.Protected.Select(p => (p.Kind, p.Username)).ToList();
+ CollectionAssert.Contains(kinds, (ProtectedFolderKind.Data, (string?)null));
+ CollectionAssert.Contains(kinds, (ProtectedFolderKind.Library, (string?)null));
+ CollectionAssert.Contains(kinds, (ProtectedFolderKind.Import, (string?)null));
+ Assert.AreEqual(Path.GetFullPath(elsewhere), context.Protected.Single(p => p.Username == "luca.demo").Path);
+
+ var check = Check();
+ var verdict = await check.CheckAsync(Path.Combine(elsewhere, "post"), context, ct);
+ Assert.AreEqual(ExportFolderProblemKind.InsideProtected, verdict.Problem!.Kind);
+ StringAssert.Contains(verdict.Problem.Message, "la cartella dell'account @luca.demo");
+ Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(bed.Temp.Combine("archivio"), context, ct)).Problem!.Kind);
+ Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(import, context, ct)).Problem!.Kind);
+
+ // A folder about to be saved for an account (WP1.10) is protected before it is stored.
+ var future = bed.Temp.Combine("nuova");
+ Directory.CreateDirectory(future);
+ var extra = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, null, ExportRootOptions.AnyFolder, [new(future, ProtectedFolderKind.Account, null)], ct);
+ Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(future, extra, ct)).Problem!.Kind);
+ Assert.IsTrue((await check.CheckAsync(future, context, ct)).Accepted);
+ }
+
+ [TestMethod]
+ public async Task AnAliasIsRecognisedByTheProbeFile()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var library = temp.Combine("libreria");
+ Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
+
+ // A second path to the same folder that no text comparison sees: a symbolic link on Linux; on Windows the
+ // «\\?\» form of the path (a link needs rights a test does not have there).
+ string Alias(string target, string name)
+ {
+ if (OperatingSystem.IsWindows())
+ {
+ return @"\\?\" + Path.GetFullPath(target);
+ }
+
+ var link = temp.Combine(name);
+ Directory.CreateSymbolicLink(link, target);
+ return link;
+ }
+
+ var check = Check();
+ var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder);
+
+ // The candidate is the library under another name, or a folder of it.
+ var same = Alias(library, "alias-libreria");
+ Assert.IsFalse(ExportPaths.IsSameOrInside(same, library) || ExportPaths.IsSameOrInside(library, same), "the text must not tell");
+ Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(same, guarded, ct)).Problem!.Kind);
+ var inside = Alias(Path.Combine(library, "marta.demo"), "alias-account");
+ Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(inside, guarded, ct)).Problem!.Kind);
+
+ // The other direction: the protected folder is known by its other name, the candidate by the real one.
+ var aliased = new ExportFolderContext([new(Alias(library, "alias-protetta"), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder);
+ Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(library, aliased, ct)).Problem!.Kind);
+ Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), aliased, ct)).Problem!.Kind);
+ Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, aliased, ct)).Problem!.Kind);
+
+ Assert.IsEmpty(Fingerprint.Temporaries(temp.Path));
+ }
+
+ [TestMethod]
+ public async Task TheProbeIsWrittenOnlyInTheCandidate()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ await bed.PostAsync(bed.Marta, "901", 1);
+ var import = bed.Temp.Combine("importa");
+ Directory.CreateDirectory(import);
+ await File.WriteAllTextAsync(Path.Combine(import, "IMG_0001.JPG"), "foto", ct);
+ var before = (Data: Fingerprint.Of(bed.Library.Data.Root, DatabaseName(bed)), Library: Fingerprint.Of(bed.Library.Layout.Root), Import: Fingerprint.Of(import));
+ Assert.IsNotEmpty(before.Library);
+
+ var probes = new List();
+ var check = new ExportFolderCheck(new FixedMounts(), writeProbe: path =>
+ {
+ probes.Add(path);
+ File.WriteAllText(path, "Febe");
+ });
+ var context = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, import, ExportRootOptions.AnyFolder, null, ct);
+ Assert.IsTrue((await check.CheckAsync(bed.Usb, context, ct)).Accepted);
+
+ var probe = probes.Single();
+ Assert.AreEqual(Path.GetFullPath(bed.Usb), Path.GetDirectoryName(probe));
+ StringAssert.Matches(Path.GetFileName(probe), new System.Text.RegularExpressions.Regex(@"^\.febe-prova-[0-9a-f]{12}\.part$"));
+ Assert.IsFalse(File.Exists(probe));
+ Assert.IsEmpty(Directory.GetFileSystemEntries(bed.Usb));
+ Fingerprint.AreEqual(before.Data, Fingerprint.Of(bed.Library.Data.Root, DatabaseName(bed)), "Dati");
+ Fingerprint.AreEqual(before.Library, Fingerprint.Of(bed.Library.Layout.Root), "Libreria");
+ Fingerprint.AreEqual(before.Import, Fingerprint.Of(import), "importa");
+ Assert.IsEmpty(Directory.GetFiles(bed.Temp.Path, ExportFolderCheck.ProbePrefix + "*", SearchOption.AllDirectories));
+
+ // A refused folder is refused by its text: no probe at all.
+ Assert.IsFalse((await check.CheckAsync(bed.Library.Layout.Root, context, ct)).Accepted);
+ Assert.HasCount(1, probes);
+ }
+
+ [TestMethod]
+ public async Task AFolderWhereTheProbeCannotBeWrittenIsRefused()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var usb = temp.Combine("usb");
+ Directory.CreateDirectory(usb);
+
+ var readOnly = await new ExportFolderCheck(new FixedMounts(), writeProbe: _ => throw new IOException("Il supporto è protetto da scrittura."))
+ .CheckAsync(usb, Context(temp), ct);
+ Assert.AreEqual(ExportFolderProblemKind.ProbeFailed, readOnly.Problem!.Kind);
+ Assert.AreEqual(
+ $"Febe non riesce a scrivere in {Path.GetFullPath(usb)} (Il supporto è protetto da scrittura.): controlla i permessi o che il disco non sia in sola lettura.",
+ readOnly.Problem.Message);
+
+ var denied = await new ExportFolderCheck(new FixedMounts(), writeProbe: _ => throw new UnauthorizedAccessException("no"))
+ .CheckAsync(usb, Context(temp), ct);
+ Assert.AreEqual(ExportFolderProblemKind.ProbeFailed, denied.Problem!.Kind);
+ StringAssert.Contains(denied.Problem.Message, "(accesso negato)");
+ Assert.IsFalse(denied.Problem.IsOverlap);
+ }
+
+ [TestMethod]
+ [Timeout(30_000, CooperativeCancellation = true)]
+ public async Task ASlowFolderTimesOutWithoutBlocking()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var usb = temp.Combine("usb");
+ Directory.CreateDirectory(usb);
+ using var release = new ManualResetEventSlim();
+ var check = new ExportFolderCheck(new FixedMounts(), TimeSpan.FromMilliseconds(200), _ => release.Wait(TimeSpan.FromSeconds(20)));
+
+ var started = System.Diagnostics.Stopwatch.StartNew();
+ var verdict = await check.CheckAsync(usb, Context(temp), ct);
+ started.Stop();
+ release.Set();
+ Assert.AreEqual(ExportFolderProblemKind.NotResponding, verdict.Problem!.Kind);
+ Assert.AreEqual(
+ "La cartella non risponde entro 0 secondi: controlla che il disco o la condivisione siano collegati, poi riprova.",
+ verdict.Problem.Message);
+ Assert.IsLessThan(TimeSpan.FromSeconds(10), started.Elapsed, "the caller did not wait for the disk");
+ }
+
+ [TestMethod]
+ public async Task APathTooLongIsRefused()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ var deep = temp.Path;
+ while (deep.Length < WindowsFileNames.MaxPathLength + 2)
+ {
+ deep = Path.Combine(deep, new string('c', 40));
+ }
+
+ Directory.CreateDirectory(deep);
+ var verdict = await Check().CheckAsync(deep, Context(temp), ct);
+ Assert.AreEqual(ExportFolderProblemKind.PathTooLong, verdict.Problem!.Kind);
+ StringAssert.Contains(verdict.Problem.Message, "è troppo lungo: i nomi dei file non ci starebbero nei 240 caratteri");
+ Assert.IsEmpty(Directory.GetFileSystemEntries(deep));
+ }
+
+ private static ExportFolderCheck Check() => new(new FixedMounts());
+
+ private static string DatabaseName(ExportTestBed bed) => Path.GetFileName(bed.Library.Data.Database);
+
+ /// A Data folder and a library inside the temporary folder, away from the candidates.
+ private static ExportFolderContext Context(TempFolder temp) => new(
+ [new(Path.GetFullPath(temp.Combine("dati")), ProtectedFolderKind.Data, null), new(Path.GetFullPath(temp.Combine("libreria")), ProtectedFolderKind.Library, null)],
+ ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() });
+}
diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs
index 9e10d0b..7c0bd10 100644
--- a/tests/Febe.Tests/Export/ExportFoundationTests.cs
+++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs
@@ -86,7 +86,7 @@ public sealed class ExportFoundationTests
}
Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind);
- Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, "/")).Kind);
+ Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, ".")).Kind);
}
[TestMethod]
diff --git a/tests/Febe.Tests/Export/ExportPathsTests.cs b/tests/Febe.Tests/Export/ExportPathsTests.cs
new file mode 100644
index 0000000..af336df
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportPathsTests.cs
@@ -0,0 +1,183 @@
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// Where a copy goes below its destination (spec §4.10 «Nomi dei file», §4.7; decision D18 of tappa E2). The default
+/// library scheme names a post of 13 October 2026 08:00 UTC «post/2026/2026-10-13_10-00-00_C<id>_<n>» in Rome.
+///
+[TestClass]
+public sealed class ExportPathsTests
+{
+ private static readonly Account Marta = Make.Account("marta.demo") with { Id = 1 };
+
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public void TheGeneralFolderStartsWithTheAccountSegment()
+ {
+ var segments = ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), Photo(2), null, false, TestZones.Rome);
+ CollectionAssert.AreEqual(new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_2.jpg" }, segments.ToArray());
+
+ // The account segment is sanitized as a folder name (a reserved name on Windows gets changed).
+ var aux = Marta with { Username = "aux" };
+ var first = ExportPaths.Segments(General(), LibraryNaming.Default, aux, Post(), Photo(1), null, false, TestZones.Rome)[0];
+ Assert.AreEqual(WindowsFileNames.SanitizeSegment("aux"), first);
+ Assert.AreNotEqual("aux", first);
+ }
+
+ [TestMethod]
+ public void TheOwnFolderHasNoAccountSegment()
+ {
+ var own = General() with { Scope = ExportScope.Account, AccountId = 1 };
+ var segments = ExportPaths.Segments(own, LibraryNaming.Default, Marta, Post(), Photo(1), null, false, TestZones.Rome);
+ CollectionAssert.AreEqual(new[] { "post", "2026", "2026-10-13_10-00-00_C500_1.jpg" }, segments.ToArray());
+ Assert.AreEqual("post/2026/2026-10-13_10-00-00_C500_1.jpg", ExportPaths.RelativePathFor(own, segments));
+ }
+
+ [TestMethod]
+ public void ComeLaLibreriaFollowsTheCurrentLibrarySchemes()
+ {
+ // The library file was named with an older scheme: the copy follows the scheme of now, not the stored path.
+ var naming = LibraryNaming.Default with { General = NamingScheme.Parse(@"{account}\{anno}-{mese}\{codice}_{n}", NamingSchemeUse.General) };
+ var old = Photo(1) with { RelativePath = "post/2019/vecchio-nome.JPG" };
+ CollectionAssert.AreEqual(
+ new[] { "marta.demo", "2026-10", "C500_1.jpg" },
+ ExportPaths.Segments(General(), naming, Marta, Post(), old, null, false, TestZones.Rome).ToArray());
+
+ // A scheme of the destination wins over the library's; the highlight and profile schemes stay «Come la libreria».
+ var own = General() with { NamingScheme = @"{tipo}\{data}_{n}" };
+ CollectionAssert.AreEqual(new[] { "marta.demo", "post", "2026-10-13_1.jpg" }, ExportPaths.Segments(own, naming, Marta, Post(), old, null, false, TestZones.Rome).ToArray());
+ var highlight = Make.Entry(1, "700", Make.T0, EntryKind.Highlight);
+ CollectionAssert.AreEqual(
+ new[] { "marta.demo", "evidenza", "Mare", "2026-10-13_10-00-00_700_1.jpg" },
+ ExportPaths.Segments(own, naming, Marta, highlight, old, "Mare", true, TestZones.Rome).ToArray());
+ }
+
+ [TestMethod]
+ public async Task ComeLaLibreriaFollowsTheSchemeSavedInTheSettings()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "930", 1);
+ await bed.Db.Settings.SetAsync(SettingKeys.NamingScheme, @"{account}\{anno}\{codice}_{n}", ct);
+ await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.IsTrue(File.Exists(Path.Combine(bed.Usb, "marta.demo", "2026", "C930_1.jpg")));
+ Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ }
+
+ [TestMethod]
+ public void ImportedFilesWithoutDateKeepTheirName()
+ {
+ var imported = Photo(1) with { RelativePath = "importati/vacanze/IMG 0001.JPG" };
+ CollectionAssert.AreEqual(
+ new[] { "marta.demo", "importati", "vacanze", "IMG 0001.JPG" },
+ ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome).ToArray());
+ var own = General() with { Scope = ExportScope.Account, AccountId = 1 };
+ CollectionAssert.AreEqual(
+ new[] { "importati", "vacanze", "IMG 0001.JPG" },
+ ExportPaths.Segments(own, LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome).ToArray());
+
+ // Only a file the import left in «importati/» keeps its path; a scheme of the destination renames it.
+ var renamed = ExportPaths.Segments(own with { NamingScheme = @"{anno}\{codice}_{n}" }, LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome);
+ CollectionAssert.AreEqual(new[] { "2026", "C500_1.jpg" }, renamed.ToArray());
+ Assert.ThrowsExactly(() => ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), Photo(1) with { RelativePath = null }, null, false, TestZones.Rome));
+ }
+
+ [TestMethod]
+ public void AStoryInAHighlightRendersAsHighlightOnlyWithoutStories()
+ {
+ var story = Make.Entry(1, "800", Make.T0, EntryKind.Story);
+ var media = Photo(1) with { RelativePath = "storie/2026/x.jpg" };
+ string[] Render(ContentTypes types, bool inHighlight) =>
+ [.. ExportPaths.Segments(General() with { ContentTypes = types }, LibraryNaming.Default, Marta, story, media, "Estate", inHighlight, TestZones.Rome)];
+
+ CollectionAssert.AreEqual(new[] { "marta.demo", "evidenza", "Estate", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights, inHighlight: true));
+ CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights | ContentTypes.Stories, inHighlight: true));
+ CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Stories, inHighlight: true));
+ CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights, inHighlight: false));
+
+ // The content types of D4.
+ Assert.AreEqual(ContentTypes.Stories | ContentTypes.Highlights, ExportPaths.TypeOf(EntryKind.Story, MediaKind.Video, inHighlight: true));
+ Assert.AreEqual(ContentTypes.Stories, ExportPaths.TypeOf(EntryKind.Story, MediaKind.Photo, inHighlight: false));
+ Assert.AreEqual(ContentTypes.PostVideos, ExportPaths.TypeOf(EntryKind.Post, MediaKind.Video, false));
+ Assert.AreEqual(ContentTypes.Tagged, ExportPaths.TypeOf(EntryKind.Tagged, MediaKind.Video, false));
+ Assert.AreEqual(ContentTypes.ProfilePicture, ExportPaths.TypeOf(EntryKind.ProfilePicture, MediaKind.Photo, false));
+ }
+
+ [TestMethod]
+ public void ProfilePicturesUseTheFirstEightDigitsOfTheSha()
+ {
+ var profile = Make.Entry(1, "900", Make.T0, EntryKind.ProfilePicture);
+ var sha = "abcdef0123456789" + new string('0', 48);
+ var media = Photo(1) with { Sha256 = sha, RelativePath = "profilo/vecchio.jpg" };
+ CollectionAssert.AreEqual(
+ new[] { "marta.demo", "profilo", "2026-10-13_10-00-00_abcdef01_1.jpg" },
+ ExportPaths.Segments(General(), LibraryNaming.Default, Marta, profile, media, null, false, TestZones.Rome).ToArray());
+ var own = General() with { Scope = ExportScope.Account, AccountId = 1, ProfileNamingScheme = @"foto\{codice}" };
+ CollectionAssert.AreEqual(new[] { "foto", "abcdef01.jpg" }, ExportPaths.Segments(own, LibraryNaming.Default, Marta, profile, media, null, false, TestZones.Rome).ToArray());
+ }
+
+ [TestMethod]
+ public void LongPathsAreShortenedTo240WithTheRoot()
+ {
+ var root = Path.Combine(Path.GetTempPath(), new string('r', 120));
+ var deep = General() with { RootPath = root };
+ var segments = new[] { "marta.demo", new string('a', 60), new string('b', 60) + ".jpg" };
+ var fitted = ExportPaths.RelativePathFor(deep, segments);
+ Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + fitted.Length);
+ StringAssert.EndsWith(fitted, ".jpg");
+ StringAssert.StartsWith(fitted, "marta.demo/");
+ Assert.AreEqual("marta.demo/x.jpg", ExportPaths.RelativePathFor(deep, ["marta.demo", "x.jpg"])); // short paths are not touched
+
+ // A root that leaves no room for a name at all.
+ var hopeless = General() with { RootPath = Path.Combine(Path.GetTempPath(), new string('r', 235)) };
+ Assert.ThrowsExactly(() => ExportPaths.RelativePathFor(hopeless, segments));
+
+ // The numbered names of the safe writer fit too, keeping the extension (at the limit the number goes into
+ // the shortened name, as the safe writer does).
+ Assert.AreEqual("a/b/foto.jpg", ExportPaths.NumberedName(root, "a/b/foto.jpg", 1));
+ Assert.AreEqual("a/b/foto (2).jpg", ExportPaths.NumberedName(root, "a/b/foto.jpg", 2));
+ var numbered = ExportPaths.NumberedName(root, fitted, 3);
+ StringAssert.EndsWith(numbered, ".jpg");
+ CollectionAssert.AllItemsAreUnique(new[] { fitted, ExportPaths.NumberedName(root, fitted, 2), numbered });
+ Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length);
+ }
+
+ [TestMethod]
+ public void TheNamingPreviewOfADestinationTakesTheLibrarySchemesWhenNull()
+ {
+ var naming = LibraryNaming.Default with { General = NamingScheme.Parse(@"{account}\{anno}\{codice}_{n}", NamingSchemeUse.General) };
+ var library = NamingPreview.Build(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, TestZones.Rome, "marta.demo");
+ var own = ExportNamingPreview.Build(ExportScope.Account, null, null, null, naming, TestZones.Rome, "marta.demo");
+ Assert.AreEqual(Describe(library), Describe(own));
+
+ var general = ExportNamingPreview.Build(ExportScope.General, @"{tipo}\{codice}_{n}", null, null, naming, TestZones.Rome, "marta.demo");
+ Assert.IsNotEmpty(general.Folders);
+ Assert.IsTrue(general.Folders.All(f => f.Path[0] == "marta.demo"), Describe(general));
+ Assert.IsTrue(general.Folders.Any(f => f.Path.Count > 1 && f.Path[1] == "post"), Describe(general));
+ Assert.IsTrue(general.Folders.Any(f => f.Path.Contains("evidenza")), Describe(general)); // the highlight scheme of the library
+ }
+
+ private static string Describe(NamingPreview preview) =>
+ string.Join(" | ", preview.Folders.Select(f => string.Join('/', f.Path) + ": " + string.Join(", ", f.Files)));
+
+ private static ExportDestination General() => new()
+ {
+ Id = 1,
+ Scope = ExportScope.General,
+ RootPath = Path.Combine(Path.GetTempPath(), "copie"),
+ ContentTypes = ContentTypes.All,
+ CreatedAt = Make.T0,
+ };
+
+ private static Entry Post() => Make.Entry(1, "500", Make.T0);
+
+ private static Media Photo(int position) => Make.Stored(Make.Photo(position), Make.Sha(position), $"post/2026/vecchio_{position}.jpg");
+}
diff --git a/tests/Febe.Tests/Export/ExportRootTests.cs b/tests/Febe.Tests/Export/ExportRootTests.cs
new file mode 100644
index 0000000..a949804
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportRootTests.cs
@@ -0,0 +1,190 @@
+using Febe.Core.Export;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// Where destinations may be chosen (spec §4.10, §11; decision D14 and question Q2 of tappa E2): any folder on Windows;
+/// in Docker only below /esporta, only when it is declared and the folder sits on a mount at /esporta or
+/// below it. The Docker root is a temporary folder and the mount table is given by the test, so this runs on every
+/// platform.
+///
+[TestClass]
+public sealed class ExportRootTests
+{
+ [TestMethod]
+ public void DesktopHasNoRootAndIsActive()
+ {
+ var o = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() };
+ Assert.AreEqual(new ExportRootState(true, null, null), ExportRoots.Evaluate(o));
+ using var temp = new TempFolder();
+ Assert.IsNull(ExportRoots.MountProblem(o, temp.Path));
+ Assert.AreEqual(Path.GetFullPath(temp.Combine("usb")), ExportRoots.Resolve(o, temp.Combine("usb") + Path.DirectorySeparatorChar));
+ Assert.AreEqual(temp.Path, ExportRoots.DisplayPath(o, temp.Path));
+ Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Resolve(o, "usb")));
+ Assert.AreEqual(ExportFolderProblemKind.Empty, Kind(() => ExportRoots.Resolve(o, " ")));
+ }
+
+ [TestMethod]
+ public void DockerNotDeclaredIsOffAndSaysWhy()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(Path.Combine(root, "usb"));
+ var o = ExportRootOptions.Docker(root, declared: false, new FixedMounts(Mount(root)));
+
+ var state = ExportRoots.Evaluate(o);
+ Assert.IsFalse(state.Active);
+ Assert.AreEqual(Path.GetFullPath(root), state.Root);
+ Assert.AreEqual(ExportRoots.NotDeclaredText, state.Problem);
+ StringAssert.Contains(state.Problem, "FEBE_ESPORTA=1");
+ Assert.AreEqual(ExportRoots.NotDeclaredText, ExportRoots.MountProblem(o, Path.Combine(root, "usb")));
+ }
+
+ [TestMethod]
+ public void DockerDeclaredButNotMountedIsOff()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(Path.Combine(root, "usb"));
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(temp.Combine("altro"))));
+ o = o with { ShownAs = "/esporta" };
+
+ var state = ExportRoots.Evaluate(o);
+ Assert.IsFalse(state.Active);
+ Assert.AreEqual("/esporta è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su /esporta.", state.Problem);
+ Assert.AreEqual(state.Problem, ExportRoots.MountProblem(o, Path.Combine(root, "usb")));
+ }
+
+ [TestMethod]
+ public void DockerMountedAtTheRootIsActive()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(Path.Combine(root, "usb", "Febe"));
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(root))) with { ShownAs = "/esporta" };
+
+ Assert.IsTrue(ExportRoots.Evaluate(o).Active);
+ Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb")));
+ Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb", "Febe")));
+ Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb", "Febe")), ExportRoots.Resolve(o, "usb/Febe"));
+ Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb")), ExportRoots.Resolve(o, "usb/"));
+ Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb")), ExportRoots.Resolve(o, Path.Combine(root, "usb")));
+ Assert.AreEqual("/esporta/usb/Febe", ExportRoots.DisplayPath(o, Path.Combine(root, "usb", "Febe")));
+ Assert.AreEqual(ExportFolderProblemKind.OutsideExportRoot, Kind(() => ExportRoots.Resolve(o, temp.Combine("altro"))));
+ }
+
+ [TestMethod]
+ public void DockerSubMountOnlyAcceptsFoldersOnTheMount()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ var usb = Path.Combine(root, "usb");
+ Directory.CreateDirectory(Path.Combine(usb, "Febe"));
+ Directory.CreateDirectory(Path.Combine(root, "immagine"));
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(usb))) with { ShownAs = "/esporta" };
+
+ Assert.IsTrue(ExportRoots.Evaluate(o).Active); // a mount below /esporta is enough (Q2)
+ Assert.IsNull(ExportRoots.MountProblem(o, usb));
+ Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(usb, "Febe")));
+
+ // A folder of /esporta that is not on the mount is the disk of the image: never written.
+ var problem = ExportRoots.MountProblem(o, Path.Combine(root, "immagine"));
+ Assert.AreEqual("/esporta/immagine non è su una cartella montata in /esporta: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di /esporta.", problem);
+ Assert.IsNotNull(ExportRoots.MountProblem(o, Path.Combine(root, "usbx")));
+ }
+
+ [TestMethod]
+ public void ReadOnlyMountIsRefused()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ var nas = Path.Combine(root, "nas");
+ Directory.CreateDirectory(nas);
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root), Mount(nas, readOnly: true))) with { ShownAs = "/esporta" };
+
+ Assert.IsTrue(ExportRoots.Evaluate(o).Active);
+ Assert.AreEqual("/esporta/nas/Febe è montata in sola lettura: Febe non può copiarci nulla.", ExportRoots.MountProblem(o, Path.Combine(nas, "Febe")));
+ Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb")));
+ }
+
+ [TestMethod]
+ public void ParentSegmentsAreRefusedEvenWhenTheyStayInside()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(Path.Combine(root, "usb"));
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" };
+
+ foreach (var chosen in new[] { "usb/../usb", "usb/..", "../esporta/usb", @"usb\..\usb", "usb/../../etc" })
+ {
+ var refused = Assert.ThrowsExactly(() => ExportRoots.Resolve(o, chosen), chosen);
+ Assert.AreEqual(ExportFolderProblemKind.ParentSegment, refused.Kind, chosen);
+ Assert.AreEqual("«..» non è ammesso: scegli una sottocartella di /esporta dall'elenco.", refused.Message);
+ }
+
+ Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Kind(() => ExportRoots.Resolve(ExportRootOptions.AnyFolder, Path.Combine(temp.Path, "..", "x"))));
+ Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Kind(() => ExportRoots.Browse(o, "usb/..")));
+ Assert.AreEqual("..x", Path.GetFileName(ExportRoots.Resolve(o, "usb/..x"))); // a name that only starts with dots is a name
+ }
+
+ [TestMethod]
+ public void TheRootItselfIsRefused()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(root);
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" };
+
+ // («/» alone is a full path on Linux, so it is refused there as outside the root: refused all the same.)
+ foreach (var chosen in new[] { ".", "./", "./.", root, root + Path.DirectorySeparatorChar })
+ {
+ var refused = Assert.ThrowsExactly(() => ExportRoots.Resolve(o, chosen), chosen);
+ Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, refused.Kind, chosen);
+ Assert.AreEqual("Scegli una sottocartella di /esporta: /esporta stessa non è una destinazione.", refused.Message);
+ }
+
+ Assert.AreEqual(ExportFolderProblemKind.Empty, Kind(() => ExportRoots.Resolve(o, string.Empty)));
+ Assert.IsEmpty(ExportRoots.Browse(o, null)); // the picker may open it, just not choose it
+ }
+
+ [TestMethod]
+ public void BrowseListsSubfoldersWithoutLinksOrHiddenOnes()
+ {
+ using var temp = new TempFolder();
+ var root = temp.Combine("esporta");
+ Directory.CreateDirectory(Path.Combine(root, "usb", "Febe"));
+ Directory.CreateDirectory(Path.Combine(root, "nas"));
+ var hidden = Directory.CreateDirectory(Path.Combine(root, ".nascosta"));
+ hidden.Attributes |= FileAttributes.Hidden; // on Linux the dot is enough
+ File.WriteAllText(Path.Combine(root, "file.txt"), "non è una cartella");
+ if (!OperatingSystem.IsWindows())
+ {
+ // A link out of the root (creating one on Windows needs rights a test does not have).
+ Directory.CreateSymbolicLink(Path.Combine(root, "collegamento"), temp.Path);
+ }
+
+ var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" };
+ var top = ExportRoots.Browse(o, null);
+ CollectionAssert.AreEqual(new[] { "nas", "usb" }, top.Select(c => c.Name).ToArray());
+ Assert.AreEqual("usb", top[1].Path); // relative to the root
+ Assert.IsTrue(top[1].HasSubfolders);
+ Assert.IsFalse(top[0].HasSubfolders);
+ Assert.AreEqual("usb/Febe", ExportRoots.Browse(o, "usb").Single().Path);
+
+ var missing = Assert.ThrowsExactly(() => ExportRoots.Browse(o, "assente"));
+ Assert.AreEqual(ExportFolderProblemKind.Missing, missing.Kind);
+ Assert.AreEqual("La cartella /esporta/assente non esiste.", missing.Message);
+
+ // Windows: a full path, and the whole tree is offered (links and hidden folders still skipped).
+ var desktop = ExportRoots.Browse(ExportRootOptions.AnyFolder, root);
+ CollectionAssert.AreEqual(new[] { Path.Combine(Path.GetFullPath(root), "nas"), Path.Combine(Path.GetFullPath(root), "usb") }, desktop.Select(c => c.Path).ToArray());
+ Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Browse(ExportRootOptions.AnyFolder, "usb")));
+ }
+
+ internal static ExportMount Mount(string point, string root = "/", string type = "ext4", bool readOnly = false) =>
+ new(Path.GetFullPath(point), root, type, readOnly);
+
+ private static ExportFolderProblemKind? Kind(Action action) => Assert.ThrowsExactly(action).Kind;
+}
diff --git a/tests/Febe.Tests/Export/ExportSamePostTests.cs b/tests/Febe.Tests/Export/ExportSamePostTests.cs
new file mode 100644
index 0000000..cc31f38
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportSamePostTests.cs
@@ -0,0 +1,127 @@
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// The same file in two places (spec §4.10 l.311-312): «Una copia per account» or «Una copia sola» for a post seen by two
+/// accounts, and a story that is also in a highlight, which is one file and one copy.
+///
+[TestClass]
+public sealed class ExportSamePostTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task OneCopyPerAccountWritesTwoFilesUnderTwoSegments()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var marta = await bed.PostAsync(bed.Marta, "980", 60);
+ var luca = await bed.PostAsync(bed.Luca, "980", 60);
+ Assert.AreEqual(marta.Media[0].Sha256, luca.Media[0].Sha256);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ var started = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct);
+ Assert.AreEqual((2, 0), (started.Plan.Files, started.Plan.AlreadyCopied));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, marta.Media[0])));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, luca.Media[0])));
+ Assert.HasCount(2, Fingerprint.Of(bed.Usb));
+ var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
+ CollectionAssert.AreEquivalent(new long?[] { bed.Marta.Id, bed.Luca.Id }, copies.Select(c => c.AccountId).ToArray());
+ Assert.IsTrue(copies.All(c => c.State == ExportCopyState.Copied));
+ }
+
+ [TestMethod]
+ public async Task OneCopyOnlyWritesOnceAndTheOtherShowsCopied()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var marta = await bed.PostAsync(bed.Marta, "981", 61);
+ var luca = await bed.PostAsync(bed.Luca, "981", 61);
+ await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ // In one job: the plan counts it once and one file is written.
+ var both = new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id]));
+ var plan = await bed.Service.PlanAsync(both, ct);
+ Assert.AreEqual((1, 1), (plan.Files, plan.AlreadyCopied));
+ var started = await bed.CopyAsync(both, ct);
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+ var items = await bed.ItemsAsync(started.Runs.Single().Id, ct);
+ Assert.AreEqual(1, items.Count(i => i.State == ExportItemState.Copied));
+ var other = items.Single(i => i.State != ExportItemState.Copied);
+ Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (other.State, other.Note));
+ var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
+ Assert.AreEqual(copy.Id, other.CopyId);
+
+ // Later, the other account alone: still «Già copiato», nothing written.
+ var otherAccount = copy.AccountId == bed.Marta.Id ? bed.Luca : bed.Marta;
+ var again = await bed.CopyAccountAsync(otherAccount, ct: ct);
+ Assert.AreEqual((0, 1), (again.Plan.Files, again.Plan.AlreadyCopied));
+ Assert.AreEqual(ExportItemState.AlreadyCopied, (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().State);
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+
+ // Back to «Una copia per account»: the other account would get its own.
+ await bed.SetSamePostAsync(SamePostCopies.OnePerAccount, ct);
+ Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(otherAccount.Id)), ct)).Files);
+ await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
+
+ // The one copy goes from the disk: the copier checks the file and writes the other account's copy after all.
+ var copiedAccount = otherAccount == bed.Marta ? bed.Luca : bed.Marta;
+ File.Delete(bed.GeneralCopy(copiedAccount, (copiedAccount == bed.Marta ? marta : luca).Media[0]));
+ var written = await bed.CopyAccountAsync(otherAccount, ct: ct);
+ Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(written.Runs.Single().Id, ct)).Single().State);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(otherAccount, (otherAccount == bed.Marta ? marta : luca).Media[0])));
+ }
+
+ [TestMethod]
+ public async Task AStoryAndItsHighlightAreOneCopy()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var story = await StoryInHighlightAsync(bed, "982", 62, ct);
+ var usb = await bed.GeneralAsync(ContentTypes.Stories | ContentTypes.Highlights, ct: ct);
+
+ var started = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.AreEqual(1, started.Plan.Files);
+ var item = (await bed.ItemsAsync(started.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual(ExportItemState.Copied, item.State);
+ Assert.StartsWith("marta.demo/storie/", item.RelativePath!, "with «Storie» chosen it stays a story");
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+ Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
+
+ // Asked again through the entry: already copied.
+ Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([story.Entry.Id])), ct)).AlreadyCopied);
+ }
+
+ [TestMethod]
+ public async Task AHighlightOnlyDestinationCopiesStoriesInHighlights()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var inHighlight = await StoryInHighlightAsync(bed, "983", 63, ct);
+ await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "984", Make.T0.AddHours(-2), EntryKind.Story), [ExportTestBed.Photo(1, 64)]);
+ await bed.GeneralAsync(ContentTypes.Highlights, ct: ct);
+
+ var started = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.AreEqual((1, 1), (started.Plan.Files, started.Plan.NotExported));
+ var item = (await bed.ItemsAsync(started.Runs.Single().Id, ct)).Single(i => i.State == ExportItemState.Copied);
+ Assert.AreEqual(inHighlight.Media[0].Id, item.MediaId);
+ Assert.StartsWith("marta.demo/evidenza/Estate/", item.RelativePath!);
+ var files = Fingerprint.Of(bed.Usb);
+ Assert.HasCount(1, files);
+ Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "marta.demo", "storie")), "a story outside highlights is not due");
+ }
+
+ private static async Task StoryInHighlightAsync(ExportTestBed bed, string code, int scene, CancellationToken ct)
+ {
+ var highlight = await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = bed.Marta.Id, InstagramId = "h" + code, Title = "Estate", DiscoveredAt = Make.T0 }, ct);
+ var story = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, code, Make.T0.AddHours(-1), EntryKind.Story), [ExportTestBed.Photo(1, scene)]);
+ await bed.Db.Highlights.AddItemAsync(highlight.Id, story.Entry.Id, ct);
+ return story;
+ }
+}
diff --git a/tests/Febe.Tests/Export/ExportServiceTests.cs b/tests/Febe.Tests/Export/ExportServiceTests.cs
new file mode 100644
index 0000000..9c32149
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportServiceTests.cs
@@ -0,0 +1,412 @@
+using System.Collections.Concurrent;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// The export job as the page drives it (spec §4.10, decisions D6, D10, D11 of tappa E2): one run per destination in
+/// the background, «Interrompi», «Riprendi», «Annulla», the restart, the gate shared with the import and the rebuild,
+/// the engine session, «Esporta questo account» and Docker without its mount.
+///
+[TestClass]
+public sealed class ExportServiceTests
+{
+ private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
+
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task TheJobRunsInTheBackgroundOneRunPerDestination()
+ {
+ var ct = TestContext.CancellationToken;
+ var held = new HeldExportFileSystem(SecondFile);
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
+ var marta = await bed.PostAsync(bed.Marta, "990", 70, 71);
+ var luca = await bed.PostAsync(bed.Luca, "991", 72);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var own = await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct);
+ var finished = new ConcurrentQueue();
+ var progress = new ConcurrentQueue();
+ bed.Service.JobFinished += (_, f) => finished.Enqueue(f);
+ bed.Service.ProgressChanged += (_, p) => progress.Enqueue(p);
+
+ var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct);
+ CollectionAssert.AreEqual(new[] { usb.Id, own.Id }, start.Runs.Select(r => r.DestinationId).ToArray());
+ Assert.AreEqual(3, start.Plan.Files);
+ Assert.HasCount(2, start.Plan.Destinations);
+
+ // While it runs: busy, its runs, and a second «Copia in…» or «Controlla le copie» is refused.
+ await held.Reached.Task.WaitAsync(Patience, ct);
+ Assert.IsTrue(bed.Service.IsBusy);
+ CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), bed.Service.ActiveRunIds.ToArray());
+ var busy = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct));
+ Assert.StartsWith("C'è già una copia al lavoro", busy.Message);
+ await Assert.ThrowsExactlyAsync(() => bed.Service.CheckCopiesAsync(usb.Id, ct));
+ var now = await bed.Service.GetProgressAsync(ct);
+ Assert.AreEqual((start.Runs[0].Id, ExportPhase.Copying, "Disco USB"), (now.RunId, now.Phase, now.DestinationLabel));
+ Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct));
+
+ held.Release();
+ await bed.Service.WaitAsync(ct);
+ Assert.IsFalse(bed.Service.IsBusy);
+ Assert.IsEmpty(bed.Service.ActiveRunIds);
+ foreach (var run in start.Runs)
+ {
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
+ }
+
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, marta.Media[1])));
+ Assert.IsTrue(File.Exists(Path.Combine(own.RootPath, Core.Library.LibraryLayout.ToPlatform(luca.Media[0].RelativePath!))));
+ Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "luca.demo")), "Luca's own folder replaces the general one");
+ var job = finished.Single();
+ CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), job.RunIds.ToArray());
+ Assert.IsTrue(progress.Any(p => p.Phase == ExportPhase.Finished));
+ Assert.AreEqual(2, (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Count(e => e.Code == "esportazione-completata"));
+ var last = await bed.Service.GetProgressAsync(ct);
+ Assert.AreEqual((start.Runs[1].Id, ExportPhase.Finished), (last.RunId, last.Phase));
+ }
+
+ [TestMethod]
+ public async Task InterruptStopsAndKeepsWhatIsDoneAndResumeSkipsFinishedItems()
+ {
+ var ct = TestContext.CancellationToken;
+ var block = true;
+ var gated = new GatedExportFileSystem(p => Volatile.Read(ref block) && SecondFile(p));
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
+ var post = await bed.PostAsync(bed.Marta, "992", 73, 74, 75);
+ await bed.GeneralAsync(ct: ct);
+
+ var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ var runId = start.Runs.Single().Id;
+ await gated.Reached.Task.WaitAsync(Patience, ct);
+ await bed.Service.InterruptAsync(ct);
+ Assert.IsFalse(bed.Service.IsBusy);
+
+ var run = await bed.RunAsync(runId, ct);
+ Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError));
+ var items = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value);
+ Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State);
+ Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State);
+ Assert.AreEqual(ExportItemState.Pending, items[post.Media[2].Id].State);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[1])));
+ Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct));
+ var first = File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0]));
+ Assert.HasCount(1, await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
+
+ // «Riprendi»: only the pending items are worked on; the copied one is neither written again nor recorded twice.
+ Volatile.Write(ref block, false);
+ var resumed = await bed.Service.ResumeAsync(ct: ct);
+ Assert.AreEqual(runId, resumed.Single().Id);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(runId, ct)).State);
+ var after = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value);
+ Assert.IsTrue(after.Values.All(i => i.State == ExportItemState.Copied));
+ Assert.AreEqual(items[post.Media[0].Id].CopyId, after[post.Media[0].Id].CopyId);
+ Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct));
+ Assert.AreEqual(first, File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ Assert.HasCount(3, Fingerprint.Of(bed.Usb));
+ Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
+ Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
+ var done = await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([runId], ct));
+ Assert.Contains("già finito", done.Message);
+ }
+
+ [TestMethod]
+ public async Task AJobLeftRunningByAStopIsRecoveredAsInterrupted()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "993", 76);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ // Febe stopped while a job was running: the record still says «in corso».
+ var running = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = Make.T0 }, ct);
+ await bed.Db.Exports.AddItemsAsync([Pending(running.Id, post.Media[0], bed.Marta.Id)], ct);
+ var paused = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Paused, StartedAt = Make.T0, LastError = "Disco USB non è raggiungibile." }, ct);
+
+ Assert.AreEqual(1, await bed.Service.RecoverAsync(ct));
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(running.Id, ct)).State);
+ Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State);
+ Assert.IsFalse(bed.Service.IsBusy, "never resumes by itself");
+ Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(running.Id, ct)).Single().State);
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb));
+ Assert.AreEqual(0, await bed.Service.RecoverAsync(ct));
+ await bed.Service.WaitAsync(ct);
+
+ await bed.Service.ResumeAsync([running.Id], ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(running.Id, ct)).State);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State);
+ }
+
+ [TestMethod]
+ public async Task DiscardLeavesFilesAlone()
+ {
+ var ct = TestContext.CancellationToken;
+ var gated = new GatedExportFileSystem(SecondFile);
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
+ var post = await bed.PostAsync(bed.Marta, "994", 77, 78);
+ var usb = await bed.GeneralAsync(ct: ct);
+ await File.WriteAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), "non toccare", ct);
+
+ var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ var runId = start.Runs.Single().Id;
+ await gated.Reached.Task.WaitAsync(Patience, ct);
+
+ // «Annulla» of the running job interrupts it first.
+ await bed.Service.DiscardAsync(runId, ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.IsFalse(bed.Service.IsBusy);
+ var run = await bed.RunAsync(runId, ct);
+ Assert.AreEqual(ExportRunState.Cancelled, run.State);
+ Assert.IsNotNull(run.CompletedAt);
+ var files = Fingerprint.Of(bed.Usb);
+ Assert.HasCount(2, files);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the copies made stay");
+ Assert.AreEqual("non toccare", await File.ReadAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), ct));
+ Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb));
+ Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().State);
+ Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
+
+ // Nothing to resume, and a second «Annulla» changes nothing.
+ await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([runId], ct));
+ await bed.Service.DiscardAsync(runId, ct);
+ Assert.AreEqual(run, await bed.RunAsync(runId, ct));
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "«Annulla» never removes a copy");
+ await Assert.ThrowsExactlyAsync(() => bed.Service.DiscardAsync(runId + 100, ct));
+ }
+
+ [TestMethod]
+ public async Task ExportImportAndRebuildNeverRunTogether()
+ {
+ var ct = TestContext.CancellationToken;
+ var gated = new GatedExportFileSystem(SecondFile);
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated });
+ await bed.PostAsync(bed.Marta, "995", 79, 80);
+ var usb = await bed.GeneralAsync(ct: ct);
+
+ // A copy holds the gate: the import and the rebuild wait.
+ await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ await gated.Reached.Task.WaitAsync(Patience, ct);
+ Assert.AreEqual(LongWorkKind.Export, bed.Gate.Busy);
+ Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Import, out _, out var holder));
+ Assert.AreEqual(LongWorkKind.Export, holder);
+ Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Rebuild, out _, out _));
+ Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export));
+ await bed.Service.InterruptAsync(ct);
+ Assert.IsNull(bed.Gate.Busy, "the gate is given back however the job ends");
+
+ // A rebuild holds it: no copy starts, resumes or checks, and nothing is recorded.
+ var runs = await bed.Db.Exports.ListRunsAsync(ct);
+ Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _));
+ using (lease)
+ {
+ var expected = LongWorkGate.BusyMessage(LongWorkKind.Export, LongWorkKind.Rebuild);
+ Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct))).Message);
+ Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync(ct: ct))).Message);
+ Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.CheckCopiesAsync(usb.Id, ct))).Message);
+ Assert.IsFalse(bed.Service.IsBusy);
+ CollectionAssert.AreEqual(runs.ToArray(), (await bed.Db.Exports.ListRunsAsync(ct)).ToArray());
+ var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
+ Assert.IsNull(retry.Problem);
+ Assert.IsEmpty(retry.Resumed, "with other long work running the paused jobs wait for «Riprendi»");
+ }
+
+ Assert.IsNull(bed.Gate.Busy);
+ }
+
+ [TestMethod]
+ public async Task NoCopyDuringAnEngineSession()
+ {
+ var ct = TestContext.CancellationToken;
+ WaitingClock? clock = null;
+ await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new WaitingClock(env.Clock) });
+ var post = await bed.PostAsync(bed.Marta, "996", 81);
+ await bed.GeneralAsync(ct: ct);
+ bed.Session.InSession = true;
+ var before = bed.Clock.Now;
+
+ var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ var waiting = await PollAsync(bed, p => p.Phase == ExportPhase.WaitingForSession, ct);
+ Assert.AreEqual(start.Runs.Single().Id, waiting.RunId);
+ await PollUntilAsync(() => clock!.Delays >= 3, ct);
+ Assert.IsTrue(bed.Service.IsBusy);
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb), "nothing is written while the engine works");
+ Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(start.Runs[0].Id, ct)).Single().State);
+
+ bed.Session.InSession = false;
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ var waited = bed.Clock.Now - before;
+ Assert.AreEqual(0, waited.Ticks % TimeSpan.FromSeconds(5).Ticks, "the wait goes by polls of 5 s on the clock");
+ Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(15), waited);
+ }
+
+ [TestMethod]
+ public async Task TheSwitchOffSkipsTheAccount()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var marta = await bed.PostAsync(bed.Marta, "997", 82, 83);
+ var luca = await bed.PostAsync(bed.Luca, "998", 84);
+ await bed.GeneralAsync(ct: ct);
+ var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct);
+ await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
+
+ // Even a manual «Copia in…» of her entry skips her files (decision Q1), in her own folder too.
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id])), ct);
+ Assert.AreEqual((0, 2), (plan.Files, plan.NotExported));
+ var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct);
+ Assert.AreEqual((1, 2), (start.Plan.Files, start.Plan.NotExported));
+ Assert.IsTrue(start.Runs.All(r => r.DestinationId != own.Id));
+ Assert.IsEmpty(Fingerprint.Of(own.RootPath));
+ Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "marta.demo")));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, luca.Media[0])));
+ Assert.IsEmpty((await bed.CopyAccountAsync(bed.Marta, ct: ct)).Runs);
+
+ // Switched on again, her files are due.
+ await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
+ Assert.AreEqual(2, (await bed.CopyAccountAsync(bed.Marta, ct: ct)).Plan.Files);
+ Assert.HasCount(2, Fingerprint.Of(own.RootPath));
+ await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.SetAccountEnabledAsync(9999, false, ct));
+ }
+
+ [TestMethod]
+ public async Task PlanCountsFilesAlreadyCopiedRemovedAndBytes()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "999", 85, 86, 87);
+ await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "1000", Make.T0.AddDays(-2), EntryKind.Tagged), [ExportTestBed.Photo(1, 88)]);
+ var waiting = await bed.Db.Entries.AddAsync(Make.Entry(bed.Marta.Id, "1001", Make.T0.AddDays(-3)), [Make.Photo(1)], ct); // never downloaded
+ var usb = await bed.GeneralAsync(ContentTypes.All & ~ContentTypes.Tagged, ct: ct);
+ await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id, post.Media[1].Id])), ct);
+ File.Delete(bed.GeneralCopy(bed.Marta, post.Media[1]));
+ await bed.Service.CheckCopiesAsync(usb.Id, ct);
+ await bed.Service.WaitAsync(ct);
+ bed.Disk.Free = 123_456_789;
+
+ var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id));
+ var plan = await bed.Service.PlanAsync(request, ct);
+ var third = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[2])).Length;
+ // The account card counts the files of the library: an entry still to download is not one of them.
+ Assert.AreEqual((1, third, 1, 1, 1, 0), (plan.Files, plan.Bytes, plan.AlreadyCopied, plan.RemovedOrSuperseded, plan.NotExported, plan.Missing));
+ var asked = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([waiting.Stored.Entry.Id])), ct);
+ Assert.AreEqual((0, 1), (asked.Files, asked.Missing)); // asked for by itself, it is «non presente in libreria»
+ var destination = plan.Destinations.Single();
+ Assert.AreEqual((usb.Id, "Disco USB", ExportScope.General, (string?)null, 1, third, false, (string?)null, (long?)123_456_789),
+ (destination.DestinationId, destination.Label, destination.Scope, destination.Username, destination.Files, destination.Bytes, destination.Paused, destination.Problem, destination.FreeBytes));
+
+ // With «Copia di nuovo» the removed one is counted among the files to write too.
+ var again = await bed.Service.PlanAsync(request with { CopyAgain = true }, ct);
+ var second = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[1])).Length;
+ Assert.AreEqual((2, third + second, 1, 1), (again.Files, again.Bytes, again.AlreadyCopied, again.RemovedOrSuperseded));
+
+ // The plan is database only: it records and writes nothing.
+ Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+
+ // Only files not exported or not in the library: no job is recorded and nothing starts.
+ var tagged = (await bed.Db.Exports.ListCandidatesAsync(request.Selection, 0, 100, ct)).Single(c => c.EntryKind == EntryKind.Tagged);
+ var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([tagged.MediaId, waiting.Stored.Media[0].Id])), ct);
+ Assert.IsEmpty(nothing.Runs);
+ Assert.AreEqual((1, 1), (nothing.Plan.NotExported, nothing.Plan.Missing));
+ Assert.IsFalse(bed.Service.IsBusy);
+ Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct));
+
+ // An already copied file still makes a job, for its report: «Già copiato», and nothing written.
+ var copied = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct);
+ Assert.AreEqual(ExportItemState.AlreadyCopied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State);
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+ }
+
+ [TestMethod]
+ [DataRow(true, DisplayName = "dichiarato, senza montaggio")]
+ [DataRow(false, DisplayName = "non dichiarato")]
+ public async Task DockerNotMountedWritesNothing(bool declared)
+ {
+ var ct = TestContext.CancellationToken;
+ string? root = null;
+ await using var bed = await ExportTestBed.CreateAsync(env =>
+ {
+ root = Path.Combine(Path.GetDirectoryName(env.DataFolder)!, "esporta");
+ return env with { Root = ExportRootOptions.Docker(root, declared, new FixedMounts()) with { ShownAs = "/esporta" } };
+ });
+ var usb = Path.Combine(root!, "usb");
+ Directory.CreateDirectory(usb);
+ await File.WriteAllTextAsync(Path.Combine(usb, "già qui.txt"), "di Alberto", ct);
+ var files = Fingerprint.Of(root!);
+ await bed.PostAsync(bed.Marta, "1002", 89);
+
+ // A destination recorded when the folder was mounted; now the container runs without it.
+ var destination = await bed.Db.Exports.AddDestinationAsync(Data.ExportWorld.Destination(ExportScope.General, null, usb), ct);
+ var state = ExportRoots.Evaluate(bed.Environment.Root);
+ Assert.IsFalse(state.Active);
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ Assert.IsNotNull(plan.Destinations.Single().Problem);
+
+ var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ var run = await bed.RunAsync(start.Runs.Single().Id, ct);
+ Assert.AreEqual(ExportRunState.Paused, run.State);
+ Assert.AreEqual(state.Problem, run.LastError);
+ Assert.AreEqual(declared, run.LastError != ExportRoots.NotDeclaredText);
+ Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(run.Id, ct)).Single().State);
+ Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(destination.Id, ct))!.PausedAt);
+ Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(destination.Id, ct: ct));
+ Fingerprint.AreEqual(files, Fingerprint.Of(root!), "not a byte in /esporta, not even the probe file");
+
+ // «Controlla le copie» and «Riprova» write nothing either.
+ Assert.IsNotNull((await bed.Service.RetryDestinationAsync(destination.Id, ct)).Problem);
+ await bed.Service.CheckCopiesAsync(destination.Id, ct);
+ await bed.Service.WaitAsync(ct);
+ Fingerprint.AreEqual(files, Fingerprint.Of(root!), "the checks write nothing");
+ Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State);
+ }
+
+ private static bool SecondFile(string path) => path.EndsWith("_2.jpg", StringComparison.Ordinal);
+
+ private static ExportItem Pending(long runId, Media media, long accountId) => new()
+ {
+ RunId = runId,
+ MediaId = media.Id,
+ AccountId = accountId,
+ SourceSha256 = media.Sha256,
+ Variant = ExportVariant.Whole,
+ Format = ExportFormat.Original,
+ State = ExportItemState.Pending,
+ };
+
+ private async Task PollAsync(ExportTestBed bed, Func until, CancellationToken ct)
+ {
+ var deadline = DateTime.UtcNow + Patience;
+ while (true)
+ {
+ var progress = await bed.Service.GetProgressAsync(ct);
+ if (until(progress))
+ {
+ return progress;
+ }
+
+ Assert.IsLessThan(deadline, DateTime.UtcNow, $"never reached; last phase {progress.Phase}");
+ await Task.Delay(10, ct);
+ }
+ }
+
+ private static async Task PollUntilAsync(Func until, CancellationToken ct)
+ {
+ var deadline = DateTime.UtcNow + Patience;
+ while (!until())
+ {
+ Assert.IsLessThan(deadline, DateTime.UtcNow, "never reached");
+ await Task.Delay(10, ct);
+ }
+ }
+}
diff --git a/tests/Febe.Tests/Export/ExportStatesTests.cs b/tests/Febe.Tests/Export/ExportStatesTests.cs
new file mode 100644
index 0000000..ace9b47
--- /dev/null
+++ b/tests/Febe.Tests/Export/ExportStatesTests.cs
@@ -0,0 +1,288 @@
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Import;
+using Febe.Core.Library;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Import.Support;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export;
+
+///
+/// «Tolto» and «Superato» (spec §4.10 l.304, §14.1; decision D9 of tappa E2): a copy whose file went from the
+/// destination, or whose library file changed, is never copied again by itself, only with «Copia di nuovo», and the old
+/// files always stay where they are.
+///
+[TestClass]
+public sealed class ExportStatesTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task RemovedIsRecopiedOnlyWithCopyAgain()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "970", 41);
+ var usb = await bed.GeneralAsync(ct: ct);
+ var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var oldCopy = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
+ File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0]));
+
+ // The next «Copia in…» finds it gone: «Tolto», skipped, not written.
+ var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.AreEqual(ExportItemState.Skipped, (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single().State);
+ Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State);
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb));
+ Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ Assert.IsEmpty(Fingerprint.Of(bed.Usb), "a second «Copia in…» still writes nothing");
+
+ // «Copia di nuovo»: a new row, the old one stays «Tolto» in the history.
+ var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct);
+ Assert.AreEqual((1, 1), (again.Plan.Files, again.Plan.RemovedOrSuperseded));
+ var newCopy = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value;
+ Assert.AreNotEqual(oldCopy, newCopy);
+ Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State);
+ Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(newCopy, ct))!.State);
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
+ Assert.HasCount(2, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
+ Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct));
+ }
+
+ [TestMethod]
+ public async Task ReplacingTheLibraryFileSupersedesTheCopy()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder("importa");
+ await using var bed = await ImportTestBed.CreateAsync(temp);
+ var (marta, library) = await bed.AccountWithPhotoAsync("marta.demo", "60", ImportTestFiles.Resized(60, 800, 600, 400, 300, 70));
+ var usb = temp.Combine("usb");
+ Directory.CreateDirectory(usb);
+ await using var export = new ExportService(Environment(bed.Library));
+ await export.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, usb, null, ContentTypes.All, null, null, null), ct);
+ await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct);
+ await export.WaitAsync(ct);
+ var copy = (await bed.Library.Db.Exports.ListCopiesBySha256Async(library.Media[0].Sha256!, ct)).Single();
+ var files = Fingerprint.Of(usb);
+
+ // An import brings the original, larger: «Tieni il più grande» replaces the library file.
+ var largest = ImportTestFiles.Photo(60, 800, 600, 92);
+ bed.Write("marta.demo/originale.jpg", largest);
+ var run = await bed.AnalyzeAsync();
+ var pair = (await bed.Review.ListDuplicatesAsync(run.Id, ct: ct)).Single();
+ await bed.Review.DecideAsync(run.Id, pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct);
+ await bed.Copier.CopyAsync(run.Id, ct: ct);
+
+ var media = (await bed.Library.Db.Media.GetAsync(library.Media[0].Id, ct))!;
+ Assert.AreNotEqual(copy.SourceSha256, media.Sha256);
+ var superseded = (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!;
+ Assert.AreEqual((ExportCopyState.Superseded, media.Sha256), (superseded.State, superseded.SupersededBySha256));
+ Fingerprint.AreEqual(files, Fingerprint.Of(usb), "the old copy stays, untouched");
+
+ // Never copied again by itself; «Copia di nuovo» writes the new file beside the old one.
+ var plan = await export.PlanAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct);
+ Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
+ await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id), CopyAgain: true), ct);
+ await export.WaitAsync(ct);
+ var after = Fingerprint.Of(usb);
+ Assert.HasCount(2, after);
+ foreach (var (path, print) in files)
+ {
+ Assert.AreEqual(print, after[path], path);
+ }
+
+ Assert.AreEqual(ExportCopyState.Superseded, (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!.State);
+ }
+
+ [TestMethod]
+ public async Task KeepLargerAfterADownloadSupersedes()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var small = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "971", Make.T0.AddDays(-3)), [TestFile.Photo(1, 42, 360, 450)]);
+ var usb = await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
+ var files = Fingerprint.Of(bed.Usb);
+
+ // The same picture comes again, larger, in another post: «Tieni il più grande».
+ var large = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "972", Make.T0), [TestFile.Photo(1, 42, 720, 900)]);
+ var lib = bed.Library;
+ var review = new DownloadDuplicateReview(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index);
+ var pair = (await review.ListAsync(ct: ct)).Single(c => c.Candidate.MediaId == large.Media[0].Id);
+ Assert.AreEqual(small.Media[0].Id, pair.Existing.MediaId);
+ Assert.AreEqual(1, (await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct)).FilesRemoved);
+
+ var superseded = (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!;
+ Assert.AreEqual((ExportCopyState.Superseded, large.Media[0].Sha256), (superseded.State, superseded.SupersededBySha256));
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy of the smaller file stays");
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); // the larger file is «tolto o superato», never copied by itself
+ }
+
+ [TestMethod]
+ public async Task ARefilledSlotAfterRebuildSupersedes()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "973", 43);
+ await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var oldSha = post.Media[0].Sha256!;
+
+ // After a rebuild the file is to download again, the journal's SHA-256 kept; the download brings other bytes.
+ File.Delete(bed.LibraryFile(bed.Marta, post.Media[0]));
+ await bed.Db.Media.UpdateAsync(post.Media[0] with { State = MediaState.ToDownload, RelativePath = null }, ct);
+ var media = (await bed.Db.Media.GetAsync(post.Media[0].Id, ct))!;
+ Assert.AreEqual(oldSha, media.Sha256);
+ var other = ExportTestBed.Photo(1, 44);
+ var saved = await bed.Library.Ingest.SaveMediaAsync(bed.Marta, post.Entry, media, new MediaContent { Content = new MemoryStream(other.Bytes), Extension = ".jpg" }, ct: ct);
+ Assert.AreEqual(MediaSaveOutcome.Stored, saved.Outcome);
+
+ var copy = (await bed.Db.Exports.ListCopiesBySha256Async(oldSha, ct)).Single();
+ Assert.AreEqual((ExportCopyState.Superseded, saved.File!.Sha256), (copy.State, copy.SupersededBySha256));
+ Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the old copy stays");
+ }
+
+ [TestMethod]
+ public async Task SupersededIsNotRecopiedByItselfButCopyAgainWritesANewFile()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "974", 45);
+ var usb = await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
+ var oldFile = bed.GeneralCopy(bed.Marta, post.Media[0]);
+ var oldBytes = await File.ReadAllBytesAsync(oldFile, ct);
+
+ // The library file changes in place (same path, other bytes), as a replacement does.
+ var newBytes = ExportTestBed.Photo(1, 46).Bytes;
+ var library = bed.LibraryFile(bed.Marta, post.Media[0]);
+ await File.WriteAllBytesAsync(library, newBytes, ct);
+ var newSha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(newBytes));
+ await bed.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, newBytes.Length, newSha, null, 96, 120, null, false), MediaState.Downloaded, bed.Clock.Now, ct);
+ Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(bed.Db, bed.Marta.Id, post.Media[0].Sha256, newSha, bed.Clock.Now, ct));
+
+ // By itself: skipped as «Superato», nothing written.
+ var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Superseded, copy.Id), (item.State, item.Note, item.CopyId));
+ Assert.HasCount(1, Fingerprint.Of(bed.Usb));
+
+ // «Copia di nuovo»: the new file goes beside the old one, which is never overwritten.
+ var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct);
+ var written = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single();
+ Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (written.State, written.Note));
+ CollectionAssert.AreEqual(oldBytes, await File.ReadAllBytesAsync(oldFile, ct));
+ CollectionAssert.AreEqual(newBytes, await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(written.RelativePath!)), ct));
+ Assert.AreEqual(ExportCopyState.Superseded, (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!.State);
+ Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).RemovedOrSuperseded);
+ }
+
+ [TestMethod]
+ public async Task SupersessionWaitsWhileAnotherPresentFileHasTheOldSha()
+ {
+ var ct = TestContext.CancellationToken;
+ using var temp = new TempFolder();
+ await using var db = await TestDatabase.OpenAsync(temp);
+ var w = await Data.ExportWorld.CreateAsync(db);
+ // A second post of marta.demo with the same bytes as her first (for instance a story and its highlight).
+ var twin = await db.Entries.AddAsync(Make.Entry(w.Marta, "556", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/twin.jpg")], ct);
+ var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"), ct);
+ var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia), ct);
+
+ // The first file changes: the twin still has the old bytes, so the copy is still of a file of the library.
+ await db.Media.MarkStoredAsync(w.MartaMedia, new StoredFile("post/a.jpg", 2000, Make.Sha(7), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct);
+ Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(7), Make.T0, ct));
+ Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(copy.Id, ct))!.State);
+
+ // The twin changes too: now the copy is superseded, and only marta's (luca.demo still has the old file).
+ await db.Media.MarkStoredAsync(twin.Stored.Media[0].Id, new StoredFile("post/twin.jpg", 2000, Make.Sha(8), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct);
+ Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(8), Make.T0, ct));
+ Assert.AreEqual((ExportCopyState.Superseded, Make.Sha(8)), ((await db.Exports.GetCopyAsync(copy.Id, ct))!.State, (await db.Exports.GetCopyAsync(copy.Id, ct))!.SupersededBySha256));
+ Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(luca.Id, ct))!.State);
+
+ // Nothing to do without an old file, or when nothing changed.
+ Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, null, Make.Sha(8), Make.T0, ct));
+ Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(8), Make.Sha(8).ToUpperInvariant(), Make.T0, ct));
+ }
+
+ [TestMethod]
+ public async Task CheckCopiesMarksMissingFilesRemoved()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "975", 47, 48, 49);
+ var usb = await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var copies = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value);
+ await bed.Db.Exports.UpdateCopyAsync(copies[post.Media[2].Id] with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(99) }, ct);
+ File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0]));
+ File.Delete(bed.GeneralCopy(bed.Marta, post.Media[2]));
+ var files = Fingerprint.Of(bed.Usb);
+
+ // The disk is unplugged first: nothing becomes «Tolto», the folder pauses.
+ Directory.Move(bed.Usb, bed.Temp.Combine("staccato"));
+ await bed.Service.CheckCopiesAsync(usb.Id, ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.IsTrue((await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).All(c => c.State != ExportCopyState.Removed));
+ Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+ Assert.IsFalse(Directory.Exists(bed.Usb));
+
+ Directory.Move(bed.Temp.Combine("staccato"), bed.Usb);
+ await bed.Service.CheckCopiesAsync(usb.Id, ct);
+ await bed.Service.WaitAsync(ct);
+ var after = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value);
+ Assert.AreEqual(ExportCopyState.Removed, after[post.Media[0].Id].State);
+ Assert.AreEqual(ExportCopyState.Copied, after[post.Media[1].Id].State);
+ Assert.AreEqual(ExportCopyState.Removed, after[post.Media[2].Id].State);
+ Assert.AreEqual(Make.Sha(99), after[post.Media[2].Id].SupersededBySha256);
+ Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the check never touches a file");
+ var check = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).First(e => e.Code == "esportazione-controllo");
+ Assert.AreEqual(EventSeverity.Warning, check.Severity);
+ Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct));
+
+ // Idempotent.
+ await bed.Service.CheckCopiesAsync(usb.Id, ct);
+ await bed.Service.WaitAsync(ct);
+ Assert.AreEqual(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, ct: ct)).Count);
+ }
+
+ [TestMethod]
+ public async Task DeletingAnEntryLeavesItsCopies()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var bed = await ExportTestBed.CreateAsync();
+ var post = await bed.PostAsync(bed.Marta, "976", 50);
+ var usb = await bed.GeneralAsync(ct: ct);
+ await bed.CopyAccountAsync(bed.Marta, ct: ct);
+ var files = Fingerprint.Of(bed.Usb);
+ var lib = bed.Library;
+
+ var deleted = await new LibraryDeletion(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index).DeleteAsync(post.Entry.Id, ct: ct);
+ Assert.IsTrue(deleted.Complete);
+ Assert.IsFalse(File.Exists(bed.LibraryFile(bed.Marta, post.Media[0])));
+
+ Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy outside is Alberto's");
+ var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
+ Assert.AreEqual(ExportCopyState.Copied, copy.State);
+ Assert.AreEqual(post.Media[0].Sha256, copy.SourceSha256);
+ var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
+ Assert.AreEqual((0, 0, 0), (plan.Files, plan.AlreadyCopied, plan.Missing)); // a deleted entry is not a candidate
+ }
+
+ private static ExportEnvironment Environment(TestLibrary library) => new()
+ {
+ Storage = library.Db,
+ Layout = () => library.Layout,
+ DataFolder = library.Data.Root,
+ Clock = library.Clock,
+ Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() },
+ Disk = new FakeExportDisk(),
+ };
+}
diff --git a/tests/Febe.Tests/Export/MountInfoTests.cs b/tests/Febe.Tests/Export/MountInfoTests.cs
new file mode 100644
index 0000000..89d319b
--- /dev/null
+++ b/tests/Febe.Tests/Export/MountInfoTests.cs
@@ -0,0 +1,91 @@
+using Febe.Core.Export;
+using Febe.Core.Library;
+
+namespace Febe.Tests.Export;
+
+///
+/// /proc/self/mountinfo as the export reads it (spec §4.10 «Docker e Windows», decision D14 of tappa E2). The
+/// content is always given by the test: nothing reads the mounts of the machine that runs the tests.
+///
+[TestClass]
+public sealed class MountInfoTests
+{
+ [TestMethod]
+ public void ParsesMountPointRootTypeAndOptionsWithOptionalFields()
+ {
+ const string content = """
+ 22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw,errors=remount-ro
+ 40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 propagate_from:2 - vfat /dev/sdb1 rw,fmask=0022
+ 41 22 0:50 / /esporta/nas ro,relatime - cifs //nas/copie rw,vers=3.0
+ """;
+ var mounts = MountInfoTable.Parse(content);
+ Assert.HasCount(3, mounts);
+
+ var usb = mounts[1];
+ Assert.AreEqual((40, 22), (usb.Id, usb.ParentId));
+ Assert.AreEqual("/backup/foto", usb.Root);
+ Assert.AreEqual("/esporta/usb", usb.MountPoint);
+ CollectionAssert.AreEqual(new[] { "rw", "noatime" }, usb.Options.ToArray());
+ Assert.AreEqual("vfat", usb.FileSystemType); // after the optional fields and their separator «-»
+ Assert.AreEqual("/dev/sdb1", usb.Source);
+ Assert.IsFalse(usb.ReadOnly);
+
+ Assert.AreEqual("ext4", mounts[0].FileSystemType);
+ Assert.AreEqual("//nas/copie", mounts[2].Source);
+ Assert.IsTrue(mounts[2].ReadOnly); // the per-mount options say ro, the super options say rw
+ }
+
+ [TestMethod]
+ public void UnescapesSpacesAndTabsInPaths()
+ {
+ var mounts = MountInfoTable.Parse(@"50 22 8:33 /foto\040di\011Marta /esporta/disco\040usb rw - ext4 /dev/sdc\0401 rw");
+ Assert.AreEqual("/foto di\tMarta", mounts.Single().Root);
+ Assert.AreEqual("/esporta/disco usb", mounts[0].MountPoint);
+ Assert.AreEqual("/dev/sdc 1", mounts[0].Source);
+ Assert.AreEqual("/esporta/disco usb", MountInfoTable.FindContaining(mounts, "/esporta/disco usb/Febe")!.MountPoint);
+ }
+
+ [TestMethod]
+ public void SkipsMalformedLines()
+ {
+ const string content = """
+
+ riga senza senso
+ 22 1 8:1 / / rw - ext4 /dev/sda1 rw
+ x 1 8:1 / /a rw - ext4 /dev/sda2 rw
+ 23 y 8:1 / /b rw - ext4 /dev/sda3 rw
+ 24 1 8:1 / /c rw shared:1 ext4 /dev/sda4 rw extra
+ 25 1 8:1 / /d rw -
+ 26 1 8:1 relativa /e rw - ext4 /dev/sda6 rw
+ 27 1 8:1 / relativo rw - ext4 /dev/sda7 rw
+ 28 1 8:1 / /f rw
+ """;
+ var mounts = MountInfoTable.Parse(content.Replace("\n", "\r\n", StringComparison.Ordinal));
+ Assert.AreEqual("/", mounts.Single().MountPoint);
+ Assert.IsEmpty(MountInfoTable.Parse(string.Empty));
+ Assert.IsEmpty(new ProcMountInfo(() => null).All());
+ Assert.IsNull(new ProcMountInfo(() => throw new IOException("letto male")).FindContaining("/esporta/usb"));
+ }
+
+ [TestMethod]
+ public void FindsTheLongestMountContainingAPath()
+ {
+ const string content = """
+ 22 1 8:1 / / rw - ext4 /dev/sda1 rw
+ 40 22 8:17 / /esporta rw - ext4 /dev/sdb1 rw
+ 41 40 8:33 / /esporta/usb rw - vfat /dev/sdc1 rw
+ 42 40 8:49 / /esporta/usb rw - exfat /dev/sdd1 rw
+ """;
+ var mounts = MountInfoTable.Parse(content);
+ Assert.AreEqual("exfat", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe/marta.demo")!.FileSystemType); // the last mount over a point wins
+ Assert.AreEqual("exfat", MountInfoTable.FindContaining(mounts, "/esporta/usb/")!.FileSystemType);
+ Assert.AreEqual("/esporta", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint); // not a prefix of a segment
+ Assert.AreEqual("/esporta", MountInfoTable.FindContaining(mounts, "/esporta")!.MountPoint);
+ Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/dati")!.MountPoint);
+ Assert.IsNull(MountInfoTable.FindContaining([], "/esporta"));
+
+ var proc = new ProcMountInfo(() => content);
+ Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false), proc.FindContaining("/esporta/usb/a"));
+ Assert.HasCount(4, proc.All());
+ }
+}
diff --git a/tests/Febe.Tests/Export/Support/ExportTestBed.cs b/tests/Febe.Tests/Export/Support/ExportTestBed.cs
new file mode 100644
index 0000000..853bcfb
--- /dev/null
+++ b/tests/Febe.Tests/Export/Support/ExportTestBed.cs
@@ -0,0 +1,405 @@
+using System.Security.Cryptography;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Data;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Export.Support;
+
+///
+/// A real library (database, account folders, files saved as the collection pipeline saves them) in a temporary
+/// folder, two accounts, a real destination folder «usb» next to it and the export service with fakes for the disk,
+/// the engine session and the mount table (tappa E2, WP5). Nothing outside the temporary folder is ever touched.
+///
+internal sealed class ExportTestBed : IAsyncDisposable
+{
+ private ExportTestBed(TempFolder temp, TestLibrary library, ExportEnvironment env, Account marta, Account luca, FakeExportDisk disk, FakeSessionState session, LongWorkGate gate)
+ {
+ Temp = temp;
+ Library = library;
+ Environment = env;
+ Service = new ExportService(env);
+ Marta = marta;
+ Luca = luca;
+ Disk = disk;
+ Session = session;
+ Gate = gate;
+ }
+
+ public TempFolder Temp { get; }
+
+ public TestLibrary Library { get; }
+
+ public FebeDatabase Db => Library.Db;
+
+ public ManualClock Clock => Library.Clock;
+
+ public ExportEnvironment Environment { get; }
+
+ public ExportService Service { get; }
+
+ public Account Marta { get; }
+
+ public Account Luca { get; }
+
+ public FakeExportDisk Disk { get; }
+
+ public FakeSessionState Session { get; }
+
+ public LongWorkGate Gate { get; }
+
+ /// The folder of the general destination (created, empty).
+ public string Usb => Temp.Combine("usb");
+
+ ///
+ /// A new bed. changes the environment (a file system seam, a Docker root…) before the
+ /// service is built.
+ ///
+ public static async Task CreateAsync(Func? configure = null)
+ {
+ var temp = new TempFolder("export");
+ var library = await TestLibrary.CreateAsync(temp);
+ var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
+ var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
+ Directory.CreateDirectory(temp.Combine("usb"));
+ var disk = new FakeExportDisk();
+ var session = new FakeSessionState();
+ var gate = new LongWorkGate();
+ var env = new ExportEnvironment
+ {
+ Storage = library.Db,
+ Layout = () => library.Layout,
+ DataFolder = library.Data.Root,
+ Clock = library.Clock,
+ Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() },
+ Disk = disk,
+ Session = session,
+ Gate = gate,
+ };
+ return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate);
+ }
+
+ /// The general folder at (or another folder), every type unless told.
+ public async Task GeneralAsync(ContentTypes types = ContentTypes.All, string? folder = null, string? scheme = null, CancellationToken ct = default) =>
+ (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, folder ?? Usb, "Disco USB", types, scheme, null, null), ct)).Destination;
+
+ /// The own folder of an account, created under the temporary folder.
+ public async Task OwnAsync(Account account, string name, ContentTypes types = ContentTypes.All, CancellationToken ct = default)
+ {
+ var folder = Temp.Combine(name);
+ Directory.CreateDirectory(folder);
+ return (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.Account, account.Id, folder, null, types, null, null, null), ct)).Destination;
+ }
+
+ /// A post of the account with small photos (distinct scenes give distinct bytes; the same scene the same bytes).
+ public Task PostAsync(Account account, string code, params int[] scenes) =>
+ Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [.. scenes.Select((s, i) => Photo(i + 1, s))]);
+
+ /// A small photo (fast to encode).
+ public static TestFile Photo(int position, int scene) => TestFile.Photo(position, scene, 96, 120);
+
+ /// «Copia in…» and waits for the job to end.
+ public async Task CopyAsync(ExportJobRequest request, CancellationToken ct = default)
+ {
+ var start = await Service.StartAsync(request, ct);
+ await Service.WaitAsync(ct);
+ return start;
+ }
+
+ /// «Copia in…» of every file of an account.
+ public Task CopyAccountAsync(Account account, bool copyAgain = false, CancellationToken ct = default) =>
+ CopyAsync(new ExportJobRequest(new ExportSelection.Account(account.Id), copyAgain), ct);
+
+ public async Task> ItemsAsync(long runId, CancellationToken ct = default) =>
+ await Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, Limit = 10_000 }, ct);
+
+ public async Task RunAsync(long runId, CancellationToken ct = default) => (await Db.Exports.GetRunAsync(runId, ct))!;
+
+ /// Where a file of the account goes in the general folder «Come la libreria».
+ public string GeneralCopy(Account account, Media media) => Path.Combine(Usb, account.Username, LibraryLayout.ToPlatform(media.RelativePath!));
+
+ /// The library file.
+ public string LibraryFile(Account account, Media media) => Library.Layout.FullPath(account, media.RelativePath!);
+
+ public Task SetSamePostAsync(SamePostCopies value, CancellationToken ct = default) => (ExportSettings.Default with { SamePost = value }).SaveAsync(Db.Settings, ct);
+
+ public async ValueTask DisposeAsync()
+ {
+ await Service.DisposeAsync();
+ await Library.DisposeAsync();
+ Temp.Dispose();
+ }
+}
+
+/// A disk with settable free space and largest file (null: not measurable, no limit).
+internal sealed class FakeExportDisk(long? free = null, long? max = null) : IExportDisk
+{
+ public long? Free { get; set; } = free;
+
+ public long? Max { get; set; } = max;
+
+ public long? FreeBytes(string root) => Free;
+
+ public long? MaxFileBytes(string root) => Max;
+}
+
+/// An engine session that the test starts and ends.
+internal sealed class FakeSessionState : IEngineSessionState
+{
+ private volatile bool _inSession;
+
+ public bool InSession
+ {
+ get => _inSession;
+ set => _inSession = value;
+ }
+}
+
+/// A clock whose delays really pass a little (so a waiting loop does not spin) and move the time on.
+internal sealed class WaitingClock(IClock inner) : IClock
+{
+ private long _delays;
+
+ public DateTimeOffset Now => inner.Now;
+
+ public TimeZoneInfo LocalZone => inner.LocalZone;
+
+ /// How many delays were asked.
+ public long Delays => Interlocked.Read(ref _delays);
+
+ public async Task Delay(TimeSpan time, CancellationToken ct)
+ {
+ Interlocked.Increment(ref _delays);
+ await inner.Delay(time, ct);
+ await Task.Delay(5, ct);
+ }
+}
+
+/// A mount table given by the test, on any platform (the longest mount point that holds the path wins).
+internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts
+{
+ public ExportMount? FindContaining(string fullPath) =>
+ mounts.Where(m => ExportPaths.IsSameOrInside(fullPath, m.MountPoint)).OrderByDescending(m => ExportPaths.Trim(m.MountPoint).Length).FirstOrDefault();
+
+ public IReadOnlyList All() => mounts;
+}
+
+/// The real file system, but the first read of a blocked file never ends until the job is cancelled.
+internal sealed class GatedExportFileSystem(Func blocks) : IExportFileSystem
+{
+ private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
+
+ /// Set when a blocked file is opened.
+ public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ public Stream OpenRead(string path)
+ {
+ var stream = _inner.OpenRead(path);
+ if (!blocks(path))
+ {
+ return stream;
+ }
+
+ Reached.TrySetResult();
+ return new BlockedStream(stream);
+ }
+
+ public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
+
+ public bool FileExists(string path) => _inner.FileExists(path);
+
+ public long? FileLength(string path) => _inner.FileLength(path);
+
+ private sealed class BlockedStream(Stream inner) : ReadOnlyStream(inner)
+ {
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ await Task.Delay(Timeout.Infinite, cancellationToken);
+ return 0;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ }
+}
+
+///
+/// The real file system, but reading a held file waits until (or until the job is cancelled), so
+/// a test can look at a job while it runs.
+///
+internal sealed class HeldExportFileSystem(Func holds) : IExportFileSystem
+{
+ private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
+ private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ /// Set when a held file is opened.
+ public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ /// Lets every held read go on.
+ public void Release() => _release.TrySetResult();
+
+ public Stream OpenRead(string path)
+ {
+ var stream = _inner.OpenRead(path);
+ if (!holds(path))
+ {
+ return stream;
+ }
+
+ Reached.TrySetResult();
+ return new HeldStream(stream, _release.Task);
+ }
+
+ public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
+
+ public bool FileExists(string path) => _inner.FileExists(path);
+
+ public long? FileLength(string path) => _inner.FileLength(path);
+
+ private sealed class HeldStream(Stream inner, Task release) : Stream
+ {
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => false;
+
+ public override long Length => inner.Length;
+
+ public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ await release.WaitAsync(cancellationToken);
+ return await inner.ReadAsync(buffer, cancellationToken);
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override void Flush()
+ {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ inner.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+}
+
+/// The real file system, but reading a chosen library file gives one byte changed (a failing disk or cable).
+internal sealed class CorruptingExportFileSystem(Func corrupts) : IExportFileSystem
+{
+ private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
+
+ public Stream OpenRead(string path)
+ {
+ var stream = _inner.OpenRead(path);
+ if (!corrupts(path))
+ {
+ return stream;
+ }
+
+ using (stream)
+ {
+ using var copy = new MemoryStream();
+ stream.CopyTo(copy);
+ var bytes = copy.ToArray();
+ bytes[bytes.Length / 2] ^= 0x5A;
+ return new MemoryStream(bytes, writable: false);
+ }
+ }
+
+ public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct);
+
+ public bool FileExists(string path) => _inner.FileExists(path);
+
+ public long? FileLength(string path) => _inner.FileLength(path);
+}
+
+/// A read-only wrapper stream.
+internal abstract class ReadOnlyStream(Stream inner) : Stream
+{
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => false;
+
+ public override long Length => inner.Length;
+
+ public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ inner.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+}
+
+/// Every file of a folder tree (relative path → length and SHA-256): equal before and after means nothing was touched.
+internal static class Fingerprint
+{
+ /// The fingerprint; files whose name starts with (the open database) are left out.
+ public static IReadOnlyDictionary Of(string folder, string? skipPrefix = null)
+ {
+ var files = new SortedDictionary(StringComparer.Ordinal);
+ if (!Directory.Exists(folder))
+ {
+ return files;
+ }
+
+ foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
+ {
+ if (skipPrefix is not null && Path.GetFileName(file).StartsWith(skipPrefix, StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ var bytes = File.ReadAllBytes(file);
+ files[Path.GetRelativePath(folder, file).Replace('\\', '/')] = $"{bytes.Length}:{Convert.ToHexStringLower(SHA256.HashData(bytes))}";
+ }
+
+ return files;
+ }
+
+ public static void AreEqual(IReadOnlyDictionary expected, IReadOnlyDictionary actual, string because)
+ {
+ CollectionAssert.AreEqual(expected.Keys.ToList(), actual.Keys.ToList(), $"{because}: {string.Join(", ", actual.Keys)}");
+ foreach (var (path, print) in expected)
+ {
+ Assert.AreEqual(print, actual[path], $"{because}: {path}");
+ }
+ }
+
+ /// Temporary files of Febe (.febe-*.part: the probe and the writes) anywhere below the folder.
+ public static IReadOnlyList Temporaries(string folder) =>
+ Directory.Exists(folder) ? Directory.GetFiles(folder, SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories) : [];
+}
diff --git a/tests/Febe.Tests/Import/ImportServiceTests.cs b/tests/Febe.Tests/Import/ImportServiceTests.cs
index 9c88d8a..3a31675 100644
--- a/tests/Febe.Tests/Import/ImportServiceTests.cs
+++ b/tests/Febe.Tests/Import/ImportServiceTests.cs
@@ -1,6 +1,9 @@
using System.Collections.Concurrent;
+using Febe.Core.Abstractions;
using Febe.Core.Domain;
+using Febe.Core.Export;
using Febe.Core.Import;
+using Febe.Tests.Export.Support;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
@@ -120,4 +123,32 @@ public sealed class ImportServiceTests
Assert.IsNull(await bed.Library.Db.Settings.GetAsync($"importazione.{run.Id}.ipotesi-stogram"));
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList());
}
+
+ [TestMethod]
+ public async Task AnImportDoesNotStartWhileAnExportRuns()
+ {
+ // A real copy to an external folder holds the gate shared by the import, the export and the rebuild (tappa E2).
+ var held = new HeldExportFileSystem(path => path.EndsWith("_1.jpg", StringComparison.Ordinal));
+ await using var export = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
+ await export.PostAsync(export.Marta, "700", 1);
+ await export.GeneralAsync();
+ await export.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(export.Marta.Id)));
+ await held.Reached.Task.WaitAsync(TimeSpan.FromSeconds(30));
+
+ using var temp = new TempFolder("importa");
+ await using var bed = await ImportTestBed.CreateAsync(temp);
+ bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(330, 200, 150));
+ await using var service = new ImportService(bed.Environment with { Gate = export.Gate });
+ var refused = await Assert.ThrowsExactlyAsync(() => service.StartAsync(bed.Source));
+ Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), refused.Message);
+ Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message);
+ Assert.IsEmpty(await service.ListRunsAsync(), "a refused import records nothing");
+
+ // The copy ends: the import starts.
+ held.Release();
+ await export.Service.WaitAsync();
+ Assert.IsNull(export.Gate.Busy);
+ var run = await service.StartAsync(bed.Source);
+ Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State);
+ }
}