Files
Febe/tests/Febe.Tests/Web/ExportApiTests.cs
T
Alby96andClaude Opus 5.5 724db13e1b E2: misure del filtro Copie, migrazione 0004 e prove di web e Docker
Il filtro «Copie» con 200.000 elementi stava al limite dei 250 ms
(«Copiati» 249 ms): la migrazione 0004 aggiunge solo l'indice
ix_media_sha256_entry e la finestra scende a 160 ms. Totali e giorni
contano «Copiati» partendo dalle copie e gli altri valori con un solo
passaggio sui file dietro gli elenchi degli SHA-256 copiati (1,5 s ->
0,7 s); hanno un limite loro di 3 s, scritto in decisioni.md con le
misure.

«Copia di nuovo» sceglie un file dell'account che è sul disco: prima
prendeva il primo con quello SHA-256 e, nella demo, a certe ore non
scriveva nulla.

Nuove prove: API delle copie, coerenza della demo, interfaccia nel
browser, opzioni del server, avvio del contenitore con /esporta,
contenuto dell'immagine e modelli, migrazione 4 e scala.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 15:29:59 +01:00

556 lines
32 KiB
C#

using System.Net;
using System.Text.Json;
using Febe.Core.Abstractions;
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;
using Febe.Tests.Web.Support;
using Febe.Web;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// The copies to external folders over the API of a real web host (spec §4.10, §10.3, tappa E2), outside the demo:
/// whether export is available (Docker not declared, not mounted, mounted), the folders of /esporta, the check of a
/// candidate folder, destinations, «Copia in…» from plan to the files on disk, «Controlla le copie» and «Copia di
/// nuovo», the «Copie» filter, the marks, the viewer and the account card, and the exclusive long work. Files are
/// real (saved through <see cref="LibraryIngest"/>), destinations are folders of the temporary folder of the test.
/// </summary>
[TestClass]
public sealed class ExportApiTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheOverviewSaysWhetherExportIsAvailable()
{
// Docker, not declared (the default of the web host): off, and nothing can be chosen or saved.
await using (var server = await WebTestServer.StartAsync())
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("docker"));
Assert.IsFalse(root.Bool("active"));
Assert.IsFalse(root.Bool("pickFolder"));
Assert.AreEqual(ExportRoots.NotDeclaredText, root.Str("problem"));
var (folders, folderError) = await server.SendJsonAsync(HttpMethod.Get, "/api/export/folders");
Assert.AreEqual(HttpStatusCode.BadRequest, folders);
Assert.AreEqual(ExportRoots.NotDeclaredText, folderError.Str("message"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Status);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status);
Assert.IsEmpty(await server.Db.Exports.ListDestinationsAsync(includeRetired: true));
}
// Declared, but nothing is mounted at or below /esporta: still off, with its own reason.
using var esporta = new TempFolder("esporta");
Directory.CreateDirectory(esporta.Combine("usb"));
await using (var server = await StartAsync(ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts()), desktop: false))
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("docker"));
Assert.IsFalse(root.Bool("active"));
Assert.AreNotEqual(ExportRoots.NotDeclaredText, root.Str("problem"));
Assert.IsNotEmpty(root.Str("problem"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status);
}
// Declared and mounted: on.
await using (var server = await StartAsync(Mounted(esporta), desktop: false))
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsTrue(root.Bool("active"), root.ToString());
Assert.AreEqual(JsonValueKind.Null, root.GetProperty("problem").ValueKind);
}
// Windows: any folder, through the picker of the system.
await using (var server = await StartAsync())
{
var root = (await server.GetJsonAsync("/api/export")).GetProperty("root");
Assert.IsFalse(root.Bool("docker"));
Assert.IsTrue(root.Bool("active"));
Assert.AreEqual(JsonValueKind.Null, root.GetProperty("root").ValueKind);
}
}
[TestMethod]
public async Task FoldersAreListedUnderTheExportRootAndDotDotIsRefused()
{
using var esporta = new TempFolder("esporta");
Directory.CreateDirectory(esporta.Combine("usb", "foto"));
Directory.CreateDirectory(esporta.Combine("nas"));
// Hidden as the import picker hides it: a dot folder on Linux, the attribute on Windows.
var hidden = Directory.CreateDirectory(esporta.Combine(".nascosta"));
hidden.Attributes |= FileAttributes.Hidden;
await using var server = await StartAsync(Mounted(esporta), desktop: false);
var list = await server.GetJsonAsync("/api/export/folders");
CollectionAssert.AreEquivalent(new[] { "nas", "usb" }, list.Items("folders").Select(f => f.Str("name")).ToArray(), "no hidden folders");
Assert.AreEqual(string.Empty, list.Str("relative"));
Assert.AreEqual(JsonValueKind.Null, list.GetProperty("parent").ValueKind);
var usb = await server.GetJsonAsync("/api/export/folders?path=usb");
Assert.AreEqual("foto", usb.Items("folders").Single().Str("name"));
Assert.AreEqual(string.Empty, usb.Str("parent"));
foreach (var path in new[] { "..", "usb/../..", "../fuori" })
{
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/export/folders?path={Uri.EscapeDataString(path)}")).Status, path);
}
var check = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Body;
Assert.IsTrue(check.Bool("accepted"), check.ToString());
Assert.AreEqual(Free, check.Long("freeBytes"));
Assert.IsFalse(check.Bool("fat32"));
foreach (var path in new[] { string.Empty, "..", "../fuori", "usb/../.." })
{
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path });
Assert.IsTrue(status == HttpStatusCode.BadRequest || !answer.Bool("accepted"), $"«{path}»: {answer}");
}
// In Docker there is no picker of the system: the page lists the folders of /esporta.
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Status);
Assert.IsFalse(Directory.Exists(esporta.Combine("fuori")), "nothing is ever created");
}
[TestMethod]
public async Task CheckFolderRefusesTheLibraryAndTheDataFolder()
{
await using var server = await StartAsync();
var account = await AddPhotosAsync(server, "marta.demo", 1);
var usb = server.Temp.Combine("usb");
Directory.CreateDirectory(usb);
Directory.CreateDirectory(server.Library.Layout.AccountFolder(account.Account));
var accepted = await CheckAsync(server, usb);
Assert.IsTrue(accepted.Bool("accepted"), accepted.ToString());
Assert.AreEqual(Free, accepted.Long("freeBytes"));
foreach (var refused in new[]
{
server.Library.Layout.Root,
Path.Combine(server.Library.Layout.Root, "dentro"),
server.Library.Data.Root,
server.Library.Layout.AccountFolder(account.Account),
server.Temp.Path,
server.Temp.Combine("non-esiste"),
})
{
if (refused.EndsWith("dentro", StringComparison.Ordinal))
{
Directory.CreateDirectory(refused);
}
var answer = await CheckAsync(server, refused);
Assert.IsFalse(answer.Bool("accepted"), refused);
Assert.IsNotEmpty(answer.Str("problem"), refused);
}
Assert.IsFalse(Directory.Exists(server.Temp.Combine("non-esiste")), "a missing folder is never created");
Assert.IsEmpty(Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "the probe leaves nothing behind");
}
[TestMethod]
public async Task DestinationsAreCreatedUpdatedAndRetired()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 1);
var usb = server.Temp.Combine("usb");
var nas = server.Temp.Combine("nas");
Directory.CreateDirectory(usb);
Directory.CreateDirectory(nas);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, types: []))).Status, "at least one type");
var (status, created) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, label: "Disco USB"));
Assert.AreEqual(HttpStatusCode.OK, status, created.ToString());
var general = created.GetProperty("destination");
Assert.AreEqual("general", general.Str("scope"));
Assert.AreEqual("Disco USB", general.Str("label"));
Assert.HasCount(6, general.Items("types").ToList());
Assert.IsFalse(general.Bool("automatic"));
Assert.AreEqual(general.Long("id"), (await server.GetJsonAsync("/api/export")).GetProperty("general").Long("id"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas))).Status, "one general folder");
// The same folder: the same destination, changed in place.
var (sameStatus, same) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(usb, label: "Chiavetta", types: ["postFoto"]));
Assert.AreEqual(HttpStatusCode.OK, sameStatus, same.ToString());
Assert.AreEqual(general.Long("id"), same.GetProperty("destination").Long("id"));
Assert.AreEqual("Chiavetta", same.GetProperty("destination").Str("label"));
CollectionAssert.AreEqual(new[] { "postFoto" }, same.GetProperty("destination").Items("types").Select(t => t.GetString()).ToArray());
// Another folder: the old destination is retired (it keeps its copies), a new one takes its place.
var (movedStatus, moved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(nas));
Assert.AreEqual(HttpStatusCode.OK, movedStatus, moved.ToString());
var next = moved.GetProperty("destination").Long("id");
Assert.AreNotEqual(general.Long("id"), next);
Assert.IsNotNull((await server.Db.Exports.GetDestinationAsync(general.Long("id")))!.RemovedAt);
// An own folder of the account, then retired: the account goes back to the general folder.
var sua = server.Temp.Combine("sua");
Directory.CreateDirectory(sua);
var (ownStatus, own) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(sua, scope: "account", accountId: marta.Account.Id, types: ["postFoto", "postVideo"]));
Assert.AreEqual(HttpStatusCode.OK, ownStatus, own.ToString());
Assert.AreEqual("marta.demo", own.GetProperty("destination").Str("username"));
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsTrue(card.Bool("hasOwnFolder"));
Assert.AreEqual(own.GetProperty("destination").Long("id"), card.GetProperty("destination").Long("id"));
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual("marta.demo", overview.Items("own").Single().Str("username"));
var (retiredStatus, retired) = await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{own.GetProperty("destination").Long("id")}");
Assert.AreEqual(HttpStatusCode.OK, retiredStatus);
Assert.AreEqual(ExportDestinations.RetiredText, retired.Str("message"));
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsFalse(card.Bool("hasOwnFolder"));
Assert.AreEqual(next, card.GetProperty("destination").Long("id"));
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{next}")).Status);
Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").ValueKind);
Assert.IsTrue(Directory.Exists(usb) && Directory.Exists(nas) && Directory.Exists(sua), "retiring a destination never touches its folder");
}
[TestMethod]
public async Task PlanAndStartCopyTheFilesAndTheProgressFinishes()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 3);
var usb = await GeneralAsync(server);
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(3, plan.Int("files"), plan.ToString());
Assert.IsGreaterThan(0L, plan.Long("bytes"));
Assert.AreEqual(0, plan.Int("alreadyCopied"));
Assert.AreEqual(usb.Id, plan.Items("destinations").Single().Long("id"));
Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "a plan writes nothing");
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
var run = job.Items("runIds").Single().GetInt64();
await WaitIdleAsync(server);
var progress = await server.GetJsonAsync("/api/export/progress");
Assert.IsFalse(progress.Bool("running"));
Assert.AreEqual(JsonValueKind.Null, progress.GetProperty("error").ValueKind, progress.ToString());
var written = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories);
Assert.HasCount(3, written);
Assert.IsTrue(written.All(f => Path.GetRelativePath(usb.Root, f).StartsWith("marta.demo", StringComparison.Ordinal)), "the account segment comes first in the general folder");
CollectionAssert.AreEquivalent(
marta.Files.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(),
written.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(),
"copies byte for byte");
Assert.IsFalse(written.Any(f => f.EndsWith(".part", StringComparison.Ordinal)));
var runs = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().ToList();
var done = runs.Single(r => r.Long("id") == run);
Assert.AreEqual("completed", done.Str("state"));
Assert.AreEqual(3, done.Int("done"));
var report = await server.GetJsonAsync($"/api/export/runs/{run}/report");
Assert.AreEqual(3, report.GetProperty("byState").Int("copied"));
Assert.AreEqual("marta.demo", report.Items("accounts").Single().Str("username"));
Assert.IsEmpty(report.Items("problems").ToList());
var again = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, again.Int("files"));
Assert.AreEqual(3, again.Int("alreadyCopied"));
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual(3, overview.GetProperty("general").GetProperty("counts").Int("copied"));
Assert.AreEqual(0, overview.Int("unfinishedRuns"));
}
[TestMethod]
public async Task CheckCopiesThenCopyAgainWritesTheRemovedFileOnce()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 2);
var usb = await GeneralAsync(server);
await StartAndWaitAsync(server, new { accountId = marta.Account.Id });
// Alberto deletes one copy by hand; «Controlla le copie» finds it «Tolto» and touches no file.
var gone = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).First();
File.Delete(gone);
var kept = Fingerprint.Of(usb.Root);
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{usb.Id}/check")).Status);
var removed = await WaitForAsync(async () =>
{
var copies = await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, 0, 10);
return copies.Count == 1 ? copies[0] : null;
});
await WaitIdleAsync(server);
Fingerprint.AreEqual(kept, Fingerprint.Of(usb.Root), "«Controlla le copie» touches no file");
// The plan skips it by itself; the viewer offers «Copia di nuovo».
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, plan.Int("files"));
Assert.AreEqual(1, plan.Int("removedOrSuperseded"));
var entry = marta.Entries.Single(e => e.Media.Any(m => m.Id == removed.MediaId));
var file = (await server.GetJsonAsync($"/api/entries/{entry.Entry.Id}")).Items("media").Single(m => m.Long("id") == removed.MediaId);
var copy = file.Items("copies").Single();
Assert.AreEqual("removed", copy.Str("state"));
Assert.IsTrue(copy.Bool("canCopyAgain"));
Assert.AreEqual(removed.Id, copy.Long("copyId"));
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
Assert.HasCount(1, job.Items("runIds").ToList());
await WaitIdleAsync(server);
Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories));
Assert.IsTrue(File.Exists(gone), "written again at its place");
Assert.AreEqual(ExportCopyState.Removed, (await server.Db.Exports.GetCopyAsync(removed.Id))!.State, "the old row stays as history");
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id })).Status, "already copied again");
var notRemoved = (await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, 0, 10)).First();
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = notRemoved.Id })).Status, "only a removed or superseded copy");
}
[TestMethod]
public async Task TheLibraryFilterTheMarksTheViewerAndTheCardAgree()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 3);
var pair = await AddPostAsync(server, marta.Account, "coppia", 40, 41);
// No destination: no mark, no «Copie» filter offered, and every count is zero.
var days = await server.GetJsonAsync("/api/library/days");
Assert.IsFalse(days.Bool("hasDestinations"));
Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null));
var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsTrue(card.Bool("enabled"), "«Esporta questo account» is on when nothing is recorded");
Assert.AreEqual(0, card.Int("due"));
Assert.AreEqual(JsonValueKind.Null, card.GetProperty("destination").ValueKind);
Assert.IsFalse((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Bool("canCopy"));
// A destination and the copy of the first photos: one post copied, one in part.
var usb = await GeneralAsync(server);
await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id, pair.Media[0].Id } });
Assert.IsTrue((await server.GetJsonAsync("/api/library/days")).Bool("hasDestinations"));
var tiles = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").ToDictionary(t => t.Long("id"));
Assert.AreEqual("copied", tiles[marta.Entries[0].Entry.Id].Str("copies"));
Assert.AreEqual("partly", tiles[pair.Entry.Id].Str("copies"));
Assert.AreEqual(1, tiles[pair.Entry.Id].Int("copiesDone"));
Assert.AreEqual(2, tiles[pair.Entry.Id].Int("copiesDue"));
Assert.AreEqual(JsonValueKind.Null, tiles[marta.Entries[1].Entry.Id].GetProperty("copies").ValueKind);
// The filter: grouped («Copiati» only when every due file is copied) and per file.
long[] Ids(JsonElement page) => [.. page.Items("tiles").Select(t => t.Long("id"))];
CollectionAssert.AreEquivalent(new[] { marta.Entries[0].Entry.Id }, Ids(await server.GetJsonAsync("/api/library?copies=copied")));
CollectionAssert.AreEquivalent(
new[] { marta.Entries[1].Entry.Id, marta.Entries[2].Entry.Id, pair.Entry.Id },
Ids(await server.GetJsonAsync("/api/library?copies=notCopied")));
Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=removedOrSuperseded")));
Assert.HasCount(2, (await server.GetJsonAsync("/api/library?copies=copied&mode=files")).Items("tiles").ToList());
Assert.AreEqual(3, (await server.GetJsonAsync("/api/library/days?copies=notCopied&mode=files")).Int("files"));
Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?copies=copied")).Int("entries"));
foreach (var bad in new[] { "tutti", "copied,notCopied", "1" })
{
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/library?copies={bad}")).Status, bad);
}
// The viewer: the copy of the file, and «Copia in…».
var entry = await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}");
Assert.IsTrue(entry.Bool("canCopy"));
var media = entry.Items("media").ToDictionary(m => m.Long("id"));
var copy = media[pair.Media[0].Id].Items("copies").Single();
Assert.AreEqual("copied", copy.Str("state"));
Assert.AreEqual("usb", copy.Str("destination"));
Assert.AreEqual("whole", copy.Str("variant"));
Assert.IsFalse(copy.Bool("canCopyAgain"));
Assert.IsFalse(copy.Bool("destinationRetired"));
Assert.IsEmpty(media[pair.Media[1].Id].Items("copies").ToList());
// The card counts what the filter finds; the switch off counts nothing and acts at once.
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.AreEqual(5, card.Int("due"));
Assert.AreEqual(3, card.Int("notCopied"));
Assert.AreEqual(0, card.Int("removedOrSuperseded"));
Assert.AreEqual(usb.Id, card.GetProperty("destination").Long("id"));
var (offStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = false });
Assert.AreEqual(HttpStatusCode.OK, offStatus);
card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export");
Assert.IsFalse(card.Bool("enabled"));
Assert.AreEqual(0, card.Int("due"));
Assert.AreEqual(0, card.Int("notCopied"));
Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=notCopied")));
var off = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body;
Assert.AreEqual(0, off.Int("files"));
Assert.IsGreaterThan(0, off.Int("notExported"), "Q1: the switch off skips manual copies too");
Assert.IsTrue((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Items("media").Any(m => m.Items("copies").Any()), "the copies made stay visible");
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = true })).Status);
Assert.AreEqual(3, (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").Int("notCopied"));
}
[TestMethod]
public async Task RebuildIsRefusedDuringAnExportAndTheCopyWaitsForTheEngineSession()
{
var session = new FakeSessionState { InSession = true };
await using var server = await StartAsync(session: session, clock: new WaitingClock(new ManualClock(Make.T0)));
var marta = await AddPhotosAsync(server, "marta.demo", 2);
var usb = await GeneralAsync(server);
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id });
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
var waiting = await WaitForAsync(async () =>
{
var progress = await server.GetJsonAsync("/api/export/progress");
return progress.Str("phase") == "waitingForSession" ? (JsonElement?)progress : null;
});
Assert.IsTrue(waiting.GetValueOrDefault().Bool("running"));
Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "no copy during an engine session");
var (rebuild, refusal) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "ricostruisci" });
Assert.AreEqual(HttpStatusCode.BadRequest, rebuild);
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Export), refusal.Str("message"));
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id })).Status, "one copy at a time");
session.InSession = false;
await WaitIdleAsync(server);
Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories));
Assert.IsNull(server.App.Services.GetRequiredService<LongWorkGate>().Busy, "the long work is free again once the copy ended");
}
[TestMethod]
public async Task AnAccountFolderInsideADestinationIsRefused()
{
await using var server = await StartAsync();
var marta = await AddPhotosAsync(server, "marta.demo", 1);
var usb = await GeneralAsync(server);
var detail = await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}");
var form = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(detail.GetProperty("settings").GetRawText())!
.ToDictionary(k => k.Key, k => (object?)k.Value);
form["folder"] = Path.Combine(usb.Root, "marta");
var (status, error) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form);
Assert.AreEqual(HttpStatusCode.BadRequest, status);
StringAssert.Contains(error.Str("message"), "cartella di esportazione");
Assert.IsNull((await server.Db.Accounts.GetAsync(marta.Account.Id))!.Folder, "nothing saved");
form["folder"] = server.Temp.Combine("altrove", "marta");
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form)).Status);
Assert.IsNull((await server.Db.Exports.GetDestinationAsync(usb.Id))!.PausedAt);
}
// ------------------------------------------------------------------------------------------------- support
private const long Free = 500_000_000_000;
private static ExportRootOptions Mounted(TempFolder esporta) =>
ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts(new ExportMount(esporta.Path, "/", "ext4", ReadOnly: false)));
/// <summary>A web host of the Windows edition (any folder) or, with a root, the Docker one, with a disk of 500 GB.</summary>
private static Task<WebTestServer> StartAsync(ExportRootOptions? root = null, bool desktop = true, IEngineSessionState? session = null, IClock? clock = null) =>
WebTestServer.StartAsync(
desktop ? new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None } : null,
s =>
{
if (root is not null)
{
s.AddSingleton(root);
}
s.AddSingleton<IExportDisk>(new FakeExportDisk(Free));
if (session is not null)
{
s.AddSingleton(session);
}
if (clock is not null)
{
s.AddSingleton(clock);
}
});
private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new
{
scope,
accountId,
path,
label,
types = types ?? ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"],
namingScheme = (string?)null,
highlightNamingScheme = (string?)null,
profileNamingScheme = (string?)null,
};
/// <summary>The general folder «usb» in the temporary folder of the host.</summary>
private static async Task<(long Id, string Root)> GeneralAsync(WebTestServer server)
{
var root = server.Temp.Combine("usb");
Directory.CreateDirectory(root);
var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root));
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
return (saved.GetProperty("destination").Long("id"), root);
}
private static async Task<JsonElement> CheckAsync(WebTestServer server, string path)
{
var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path });
Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {answer}");
return answer;
}
/// <summary>An account with <paramref name="count"/> posts of one real photo each, saved as the collection does.</summary>
private static async Task<(Account Account, List<EntryWithMedia> Entries, List<string> Files)> AddPhotosAsync(WebTestServer server, string username, int count)
{
var account = await server.Db.Accounts.AddAsync(Make.Account(username));
var entries = new List<EntryWithMedia>();
for (var i = 0; i < count; i++)
{
entries.Add(await AddPostAsync(server, account, $"{username}-{i}", 10 + i));
}
var files = entries.SelectMany(e => e.Media).Select(m => Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(m.RelativePath!))).ToList();
Assert.IsTrue(files.All(File.Exists));
return (account, entries, files);
}
private static async Task<EntryWithMedia> AddPostAsync(WebTestServer server, Account account, string code, params int[] scenes)
{
var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex());
var added = await server.Db.Entries.AddAsync(
Make.Entry(account.Id, code, Make.T0.AddDays(-scenes[0])),
[.. scenes.Select((_, i) => Make.Photo(i + 1))]);
foreach (var (media, scene) in added.Stored.Media.Zip(scenes))
{
await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(scene, 96, 120)), Extension = ".jpg" });
}
await ingest.AppendJournalAsync(added.Stored.Entry.Id);
return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
}
private static async Task StartAndWaitAsync(WebTestServer server, object request)
{
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request);
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString());
await WaitIdleAsync(server);
}
private static async Task WaitIdleAsync(WebTestServer server)
{
for (var i = 0; i < 600; i++)
{
if (!(await server.GetJsonAsync("/api/export/progress")).Bool("running"))
{
return;
}
await Task.Delay(50);
}
Assert.Fail("the copy did not end");
}
private static async Task<T> WaitForAsync<T>(Func<Task<T?>> probe)
{
for (var i = 0; i < 600; i++)
{
if (await probe() is { } found)
{
return found;
}
await Task.Delay(50);
}
Assert.Fail("the expected state did not come");
return default!;
}
}