using System.Net; using System.Text; using System.Text.Json; using Febe.Tests.Support; using Febe.Tests.Web.Part2Support; using Febe.Tests.Web.Support; using Febe.Web; namespace Febe.Tests.Web; /// /// Importa over the API (spec §9, mockup 09): the web host builds its own ImportService over the library when the /// composition registers none; the four steps work end to end; a folder without account blocks only its files; the /// duplicates wait with nothing decided; the report and its CSV; the import's own errors become Italian answers. /// [TestClass] public sealed class ImportApiTests { private static async Task WaitForStateAsync(WebTestServer server, long id, params string[] states) { JsonElement progress = default; await Part2.WaitUntilAsync(async () => { progress = await server.GetJsonAsync($"/api/import/{id}/progress"); return !progress.Bool("running") && states.Contains(progress.Str("state")); }, "import state " + string.Join("/", states)); return progress; } [TestMethod] public async Task TheFourStepsFromSourceToReport() { await using var server = await Part2.StartAsync(FebeEdition.Desktop); var source = server.Temp.Combine("vecchio-disco"); Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240612_101500.jpg"), 11); Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240613_101500.jpg"), 12); Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240614_101500.jpg"), 13, 600, 733); Part2.WritePhoto(Path.Combine(source, "Foto sparse", "IMG_20220101_120000.jpg"), 13, 900, 1100); await File.WriteAllTextAsync(Path.Combine(source, "Foto sparse", "note.txt"), "appunti"); var overview = await server.GetJsonAsync("/api/import"); Assert.AreEqual(0, overview.GetProperty("runs").GetArrayLength()); Assert.AreEqual(JsonValueKind.Null, overview.GetProperty("sourceRoot").ValueKind, "desktop: any folder"); var (inspectStatus, info) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = source }); Assert.AreEqual(HttpStatusCode.OK, inspectStatus); Assert.IsTrue(info.Bool("canMove")); CollectionAssert.AreEquivalent(new[] { "anna.prova", "Foto sparse" }, info.Items("folders").Select(f => f.GetString()).ToArray()); // Step 2: the analysis, read-only. var (startStatus, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false }); Assert.AreEqual(HttpStatusCode.OK, startStatus); var id = run.Long("id"); await WaitForStateAsync(server, id, "reviewing"); Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "the analysis touches nothing"); // Step 3: the review. var review = await server.GetJsonAsync($"/api/import/{id}/review"); Assert.AreEqual(5, review.Int("files")); Assert.AreEqual(1, review.GetProperty("outcomes").Int("unrecognized")); Assert.IsTrue(review.Bool("canMove")); var folders = review.Items("folders").ToDictionary(f => f.Str("displayName")); Assert.AreEqual("newArchiveAccount", folders["anna.prova"].GetProperty("target").Str("kind")); Assert.AreEqual("none", folders["Foto sparse"].GetProperty("target").Str("kind")); Assert.IsTrue(folders["Foto sparse"].Bool("blocked"), "a folder without account blocks only its files"); StringAssert.Contains(review.GetProperty("plan").Str("leftOutLabel"), "aspettano la tua decisione", "a duplicate without decision waits"); // The two copies of scene 13 are a probable duplicate inside the source: nothing decided in advance. var duplicates = await server.GetJsonAsync($"/api/import/{id}/duplicates?all=true"); var pair = duplicates.Items("cases").Single(); Assert.AreEqual("pending", pair.Str("decision")); Assert.IsTrue(pair.Bool("insideSource")); StringAssert.StartsWith(pair.GetProperty("candidate").Str("image"), "/api/import/files/"); using (var preview = await server.Client.GetAsync(pair.GetProperty("candidate").Str("image"))) { Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode); Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType); } var (decideStatus, decided) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/duplicates/{pair.Long("pairId")}", new { decision = "keepBoth", applyToAll = false }); Assert.AreEqual(HttpStatusCode.OK, decideStatus); Assert.AreEqual(0, decided.Int("pending")); var afterDecision = await server.GetJsonAsync($"/api/import/{id}/review"); StringAssert.Contains(afterDecision.GetProperty("plan").Str("leftOutLabel"), "1 cartella senza account"); var (targetStatus, updated) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/folders", new { folder = folders["Foto sparse"].Str("folder"), kind = "newArchiveAccount", username = "sparse.prova" }); Assert.AreEqual(HttpStatusCode.OK, targetStatus); var updatedPlan = updated.GetProperty("plan"); Assert.AreEqual(JsonValueKind.Null, updatedPlan.GetProperty("leftOutLabel").ValueKind); Assert.AreEqual(4, updatedPlan.Int("toImport")); Assert.AreEqual("Importa 4 file", updatedPlan.Str("buttonLabel")); var (modeStatus, modePlan) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/mode", new { mode = "copy" }); Assert.AreEqual(HttpStatusCode.OK, modeStatus); Assert.AreEqual("copy", modePlan.Str("mode")); // Step 4: the copy, then the report and the CSV. var (copyStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/copy", new { mode = "copy" }); Assert.AreEqual(HttpStatusCode.OK, copyStatus); await WaitForStateAsync(server, id, "completed"); var report = await server.GetJsonAsync($"/api/import/{id}/report"); Assert.AreEqual(4, report.Int("copied")); Assert.AreEqual(0, report.Int("failed")); Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "«Copia» leaves the originals where they are"); var accounts = await server.GetJsonAsync("/api/accounts"); Assert.IsTrue(accounts.Items("accounts").Any(a => a.Str("username") == "sparse.prova" && a.Str("state") == "archiveOnly")); using var csv = await server.Client.GetAsync($"/api/import/{id}/report.csv"); Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode); Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType); var bytes = await csv.Content.ReadAsByteArrayAsync(); CollectionAssert.AreEqual(Encoding.UTF8.GetPreamble(), bytes.Take(3).ToArray(), "UTF-8 with BOM for Excel"); StringAssert.Contains(Encoding.UTF8.GetString(bytes), ";"); StringAssert.Contains(csv.Content.Headers.ContentDisposition?.ToString() ?? string.Empty, ".csv"); } [TestMethod] public async Task TheAnalysisCanBeInterruptedResumedAndDiscarded() { await using var server = await Part2.StartAsync(FebeEdition.Desktop); var source = server.Temp.Combine("sorgente"); for (var i = 0; i < 6; i++) { Part2.WritePhoto(Path.Combine(source, "luca.prova", $"IMG_2024061{i}_101500.jpg"), 200 + i, 500, 600); } var (_, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false }); var id = run.Long("id"); var (interruptStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/interrupt"); Assert.AreEqual(HttpStatusCode.OK, interruptStatus); var state = (await WaitForStateAsync(server, id, "analysisInterrupted", "reviewing")).Str("state"); if (state == "analysisInterrupted") { var (resumeStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume"); Assert.AreEqual(HttpStatusCode.OK, resumeStatus); await WaitForStateAsync(server, id, "reviewing"); } var (againStatus, again) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume"); Assert.AreEqual(HttpStatusCode.BadRequest, againStatus, "nothing to resume once reviewing"); Assert.IsFalse(string.IsNullOrWhiteSpace(again.Str("message"))); var (discardStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/discard"); Assert.AreEqual(HttpStatusCode.OK, discardStatus); var (gone, _, _) = await server.GetAsync($"/api/import/{id}/review"); Assert.AreEqual(HttpStatusCode.NotFound, gone, "nothing copied: the import disappears"); Assert.HasCount(6, Directory.GetFiles(source, "*", SearchOption.AllDirectories)); } [TestMethod] public async Task ErrorsOfTheImportAreItalianAnswers() { await using (var desktop = await Part2.StartAsync(FebeEdition.Desktop)) { var (status, error) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Temp.Combine("non-esiste") }); Assert.AreEqual(HttpStatusCode.BadRequest, status); Assert.IsFalse(string.IsNullOrWhiteSpace(error.Str("message"))); var (dataStatus, _) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Library.Data.Root }); Assert.AreEqual(HttpStatusCode.BadRequest, dataStatus, "the Data folder is never a source"); var (missing, _, _) = await desktop.GetAsync("/api/import/4242/review"); Assert.AreEqual(HttpStatusCode.NotFound, missing); var (sources, _, _) = await desktop.GetAsync("/api/import/sources"); Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing"); } // Docker: the sources live under /importa (absent on this machine: the listing says so). await using var docker = await Part2.StartAsync(); var overview = await docker.GetJsonAsync("/api/import"); Assert.AreEqual("/importa", overview.Str("sourceRoot")); Assert.IsFalse(overview.Bool("pickFolder")); var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder"); Assert.AreEqual(HttpStatusCode.BadRequest, pick); } }