Files
Febe/tests/Febe.Tests/Web/ExportFormatsApiTests.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

466 lines
30 KiB
C#

using System.IO.Compression;
using System.Net;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Codecs.H264;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
using Febe.Tests.Alerts.Support;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Library;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Tests.Web;
/// <summary>
/// Formats and frames over the API of a real web host (tappa E3): the formats of the settings and of a folder of the
/// copies (wire names of D21), the conversion of the library (status, question, pause), and frames of a video built by
/// the test (information, one frame, the instants of a mode, «Scarica» of one frame and of a zip).
/// </summary>
[TestClass]
public sealed class ExportFormatsApiTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheFormatsOfTheSettingsAreSavedByTheirWireNames()
{
await using var server = await StartAsync();
var overview = await server.GetJsonAsync("/api/export");
foreach (var name in new[] { "photoFormat", "videoFormat", "libraryPhotoFormat", "libraryVideoFormat" })
{
Assert.AreEqual("original", overview.Str(name), name);
}
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "webplossless", videoFormat = "mp4" });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.IsNotEmpty(saved.Str("message"));
Assert.AreEqual("webplossless", saved.GetProperty("overview").Str("photoFormat"));
overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual("webplossless", overview.Str("photoFormat"));
Assert.AreEqual("mp4", overview.Str("videoFormat"));
Assert.AreEqual("original", overview.Str("libraryPhotoFormat"), "a partial request keeps the rest");
foreach (var wrong in new object[] { new { }, new { photoFormat = "mp4" }, new { videoFormat = "png" }, new { libraryPhotoFormat = "tiff" } })
{
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", wrong)).Status, JsonSerializer.Serialize(wrong));
}
Assert.AreEqual("webplossless", (await server.GetJsonAsync("/api/export")).Str("photoFormat"), "a refused request changes nothing");
// A command from another page is refused, like every other one.
using var foreign = server.Request(HttpMethod.Put, "/api/export/settings", new { photoFormat = "png" }, "http://altro.example");
using var refused = await server.Client.SendAsync(foreign, TestContext.CancellationToken);
Assert.AreEqual(HttpStatusCode.Forbidden, refused.StatusCode);
}
[TestMethod]
public async Task AFolderOfTheCopiesKeepsItsFormats()
{
await using var server = await StartAsync();
var root = server.Temp.Combine("usb");
Directory.CreateDirectory(root);
var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "png", videoFormat: "original"));
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
var destination = saved.GetProperty("destination");
Assert.AreEqual("png", destination.Str("photoFormat"));
Assert.AreEqual("original", destination.Str("videoFormat"));
var stored = await server.Db.Exports.GetDestinationAsync(destination.Long("id"));
Assert.AreEqual(ExportFormat.Png, stored!.PhotoFormat);
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(server.Temp.Combine("nas"), photoFormat: "mp4"))).Status);
}
[TestMethod]
public async Task TheConversionOfTheLibrarySaysWhatItWouldDo()
{
await using var server = await StartAsync();
var status = await server.GetJsonAsync("/api/export/library-conversion");
Assert.AreEqual(0, status.Int("pending"));
Assert.IsFalse(status.Bool("on"));
var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=png");
Assert.AreEqual(0, preview.Int("files"));
foreach (var action in new[] { "pause", "resume", "retry" })
{
var (code, answer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/library-conversion/{action}", new { });
Assert.AreEqual(HttpStatusCode.OK, code, $"{action}: {answer}");
Assert.IsNotEmpty(answer.Str("message"));
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task FramesOfAVideoArePreviewedAndDownloaded()
{
var ct = TestContext.CancellationToken;
await using var server = await StartAsync();
var video = await AddVideoAsync(server);
var info = await server.GetJsonAsync($"/api/media/{video.Id}/frames/info");
Assert.IsTrue(info.Bool("available"), info.ToString());
Assert.AreEqual(2000L, info.Long("durationMs"));
Assert.AreEqual(H264PcmWriter.DemoWidth, info.Int("width"));
// A preview fits the size asked; a download is full size, PNG by default, named by its actual instant.
using (var preview = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&max=120", ct))
{
Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode);
Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType);
}
using (var full = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&download=1", ct))
{
Assert.AreEqual(HttpStatusCode.OK, full.StatusCode);
Assert.AreEqual("image/png", full.Content.Headers.ContentType?.MediaType);
StringAssert.EndsWith(full.Content.Headers.ContentDisposition?.FileNameStar ?? full.Content.Headers.ContentDisposition?.FileName?.Trim('"'), "_t0m01s125.png");
}
var instants = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=numero&count=4");
Assert.AreEqual(4, instants.Int("total"));
var labels = instants.Items("instants").Select(i => i.Str("suffix")).ToList();
CollectionAssert.AreEqual(new[] { "_f001", "_f002", "_f003", "_f004" }, labels);
var over = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=ogni&every=100");
Assert.IsFalse(over.Bool("overCap"));
Assert.AreEqual(20, over.Int("total"));
// «Scarica» of 3 frames: a zip with one entry per frame under the account folder, each a PNG.
var selection = new { mediaIds = new[] { video.Id }, frames = new { mode = "numero", count = 3, format = "png" } };
var (planStatus, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection);
Assert.AreEqual(HttpStatusCode.OK, planStatus, plan.ToString());
Assert.AreEqual(1, plan.Int("videos"));
Assert.AreEqual(3, plan.Int("frames"));
Assert.IsFalse(plan.Bool("needsQuiet"));
var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
Assert.AreEqual(HttpStatusCode.OK, tokenStatus, token.ToString());
using (var zip = await server.Client.GetAsync(token.Str("url"), ct))
{
Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType);
using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read);
Assert.HasCount(3, archive.Entries);
foreach (var entry in archive.Entries)
{
StringAssert.StartsWith(entry.FullName, "marta.demo/");
StringAssert.EndsWith(entry.FullName, ".png");
using var data = entry.Open();
var header = new byte[8];
data.ReadExactly(header);
CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A }, header);
}
}
// A token is used once.
using (var again = await server.Client.GetAsync(token.Str("url"), ct))
{
Assert.AreEqual(HttpStatusCode.NotFound, again.StatusCode);
}
// A photo has no frames.
var (photoStatus, _) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.PhotoId}/frames/info");
Assert.AreEqual(HttpStatusCode.BadRequest, photoStatus);
}
[TestMethod]
public async Task AFormatLeftToTheSettingsIsStoredAsNone()
{
await using var server = await StartAsync();
var root = server.Temp.Combine("usb");
Directory.CreateDirectory(root);
var (_, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "jpg", videoFormat: "mp4"));
var id = saved.GetProperty("destination").Long("id");
Assert.AreEqual((ExportFormat?)ExportFormat.Mp4, (await server.Db.Exports.GetDestinationAsync(id))!.VideoFormat);
// «Come le impostazioni generali» is no format of its own: it follows the settings when they change.
var (status, changed) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(root, photoFormat: "general", videoFormat: "general"));
Assert.AreEqual(HttpStatusCode.OK, status, changed.ToString());
Assert.AreEqual(id, changed.GetProperty("destination").Long("id"), "the same folder: the same destination");
var stored = await server.Db.Exports.GetDestinationAsync(id);
Assert.AreEqual(((ExportFormat?)null, (ExportFormat?)null), (stored!.PhotoFormat, stored.VideoFormat));
Assert.AreEqual(JsonValueKind.Null, changed.GetProperty("destination").GetProperty("photoFormat").ValueKind);
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task CopyInConvertsAsTheRequestAsksAndSaysWhatStaysAsItIs()
{
var ct = TestContext.CancellationToken;
await using var server = await StartAsync();
var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var jpg = await WebLibrary.AddPostAsync(server, marta, "foto-1", Make.T0.AddDays(-1), WebLibrary.Photo(1));
await WebLibrary.AddPostAsync(server, marta, "foto-2", Make.T0.AddDays(-2), WebLibrary.Photo(2));
var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-3), WebLibrary.Image(PngBytes(3), ".png"));
var heic = await WebLibrary.AddPostAsync(server, marta, "heic", Make.T0.AddDays(-4), WebLibrary.Image(Heic, ".heic"));
var usb = server.Temp.Combine("usb");
Directory.CreateDirectory(usb);
var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb));
Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString());
var destinationId = destination.GetProperty("destination").Long("id");
// The plan of each choice: JPG converts the PNG with loss and leaves the HEIC as it is; PNG converts the two JPGs
// without loss; «Originale» (the settings) copies everything as it is and says nothing about it.
async Task<JsonElement> PlanAsync(string? photoFormat) =>
(await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat })).Body;
var toJpg = await PlanAsync("jpg");
Assert.AreEqual((4, 1, true), (toJpg.Int("files"), toJpg.Int("converted"), toJpg.Bool("lossy")), toJpg.ToString());
Assert.AreEqual(("HEIC", 1), toJpg.Items("asIs").Select(a => (a.Str("label"), a.Int("files"))).Single());
StringAssert.StartsWith(toJpg.Str("summary"), "4 file · circa 1 HEIC copiato com'è · circa ");
StringAssert.EndsWith(toJpg.Str("summary"), " · con perdita");
var toPng = await PlanAsync("png");
Assert.AreEqual((4, 2, false), (toPng.Int("files"), toPng.Int("converted"), toPng.Bool("lossy")), toPng.ToString());
Assert.IsFalse(toPng.Str("summary").Contains("con perdita", StringComparison.Ordinal));
var asTheyAre = await PlanAsync(null);
Assert.AreEqual((4, 0, false), (asTheyAre.Int("files"), asTheyAre.Int("converted"), asTheyAre.Bool("lossy")), asTheyAre.ToString());
Assert.IsEmpty(asTheyAre.Items("asIs").ToList());
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat = "mp4" })).Status);
// Copied as PNG: the JPGs converted, the PNG and the HEIC byte for byte, the library untouched.
var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta));
var (started, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Id, photoFormat = "png" });
Assert.AreEqual(HttpStatusCode.OK, started, job.ToString());
await WebLibrary.WaitIdleAsync(server);
Fingerprint.AreEqual(library, Fingerprint.Of(server.Library.Layout.AccountFolder(marta)), "the library is never touched");
var written = Directory.GetFiles(usb, "*", SearchOption.AllDirectories).Select(f => Path.GetExtension(f)).Order(StringComparer.Ordinal).ToArray();
CollectionAssert.AreEqual(new[] { ".heic", ".png", ".png", ".png" }, written);
CollectionAssert.AreEqual(PngBytes(3), await File.ReadAllBytesAsync(CopyPath(usb, png.Media[0], ".png"), ct), "PNG to PNG is a byte copy");
CollectionAssert.AreEqual(Heic, await File.ReadAllBytesAsync(CopyPath(usb, heic.Media[0], ".heic"), ct), "HEIC is copied as it is");
var converted = await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct);
CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G' }, converted[..4]);
// The report says what was copied as it is; the viewer says the form of each copy.
var report = await server.GetJsonAsync($"/api/export/runs/{job.Items("runIds").Single().GetInt64()}/report");
Assert.AreEqual(1, report.Items("accounts").Single().GetProperty("asIs").Int("HEIC"), report.ToString());
Assert.IsTrue(report.Items("notes").Any(n => n.Str("path")?.EndsWith(".heic", StringComparison.Ordinal) == true && n.Str("text").Length > 0), report.ToString());
async Task<string> FormAsync(EntryWithMedia post) =>
(await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single().Items("copies").Select(c => $"{c.Str("state")} {c.Str("variant")} {c.GetProperty("format")}").Single();
Assert.AreEqual("copied converted png", await FormAsync(jpg));
Assert.AreEqual("copied whole ", await FormAsync(png));
Assert.AreEqual("copied whole ", await FormAsync(heic));
// Already copied in another form: a new format applies to the files not yet copied (D3, §16 domanda 28).
var again = await PlanAsync("jpg");
Assert.AreEqual((0, 4, false), (again.Int("files"), again.Int("alreadyCopied"), again.Bool("lossy")), again.ToString());
// A converted copy removed from the folder: «Copia di nuovo» writes that same form, whatever the settings say.
File.Delete(CopyPath(usb, jpg.Media[0], ".png"));
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status);
await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the copy «Tolto»");
await WebLibrary.WaitIdleAsync(server);
var removed = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Single();
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png), (removed.Variant, removed.Format));
var (copiedAgain, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id });
Assert.AreEqual(HttpStatusCode.OK, copiedAgain);
await WebLibrary.WaitIdleAsync(server);
CollectionAssert.AreEqual(converted, await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct), "the same conversion at its place");
Assert.IsFalse(File.Exists(CopyPath(usb, jpg.Media[0], ".jpg")), "not the whole file");
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task TheConversionOfTheLibraryAsksConvertsAndGoesWithTheFiles()
{
var ct = TestContext.CancellationToken;
await using var server = await WebTestServer.StartAsync(
new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None },
s =>
{
s.AddSingleton<IExportDisk>(new FakeExportDisk(500_000_000_000));
// The worker of the composition, with a disk far above the threshold; the test runs its passes.
s.AddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment
{
Storage = sp.GetRequiredService<IFebeStorage>(),
Layout = () => sp.GetRequiredService<FebeLibrary>().Layout,
Clock = sp.GetRequiredService<IClock>(),
Gate = sp.GetRequiredService<LongWorkGate>(),
Session = sp.GetRequiredService<IEngineSessionState>(),
FreeSpace = new FakeFreeSpaceProbe(),
}));
});
var worker = server.App.Services.GetRequiredService<LibraryConversionWorker>();
var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(5), ".png"));
var jpg = await WebLibrary.AddPostAsync(server, marta, "jpg", Make.T0.AddDays(-2), WebLibrary.Photo(6));
// The question: only the PNG would convert to JPG (a JPG is already one).
var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=jpg");
Assert.AreEqual((1, (long)PngBytes(5).Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString());
Assert.IsNotEmpty(preview.Str("text"));
// «Solo i nuovi»: nothing already in the library is queued; a new file is, after its line of the journal.
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg" });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(0, saved.Int("queued"));
var conversion = await server.GetJsonAsync("/api/export/library-conversion");
Assert.AreEqual((true, 0), (conversion.Bool("on"), conversion.Int("pending")));
var later = await WebLibrary.AddPostAsync(server, marta, "nuova", Make.T0, WebLibrary.Image(PngBytes(7), ".png"));
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion")).Int("pending"), "the new file waits for its conversion");
// Off: the queue empties; on with «Anche i N già in libreria»: both PNGs.
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "original" })).Status);
conversion = await server.GetJsonAsync("/api/export/library-conversion");
Assert.AreEqual((false, 0), (conversion.Bool("on"), conversion.Int("pending")));
(status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(2, saved.Int("queued"));
Assert.AreEqual(2, saved.GetProperty("overview").GetProperty("libraryConversion").Int("pending"));
// «Interrompi» holds the queue; «Riprendi» lets it go.
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/pause", new { })).Status);
Assert.IsTrue((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused"));
Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Converted, "paused: nothing converts");
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/resume", new { })).Status);
Assert.IsFalse((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused"));
var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta));
Assert.AreEqual(2, (await worker.RunOnceAsync(ct)).Converted);
conversion = await server.GetJsonAsync("/api/export/library-conversion");
Assert.AreEqual((0, 2, 0), (conversion.Int("pending"), conversion.Int("converted"), conversion.Int("failed")), conversion.ToString());
Assert.AreEqual("Convertiti 2", conversion.Str("text"));
// The converted file is added next to its original, which stays as it was (rule 11).
var original = WebLibrary.PathOf(server, marta, png.Media[0]);
var added = Path.ChangeExtension(original, ".jpg");
Assert.IsTrue(File.Exists(added));
var after = Fingerprint.Of(server.Library.Layout.AccountFolder(marta));
Assert.AreEqual(library.Count + 2, after.Count, "two files added, none changed or taken away");
foreach (var (path, sha) in library)
{
Assert.AreEqual(sha, after[path], path);
}
// The viewer row, the file over the API, and «Mostra nella cartella» where there is no desktop.
var row = (await server.GetJsonAsync($"/api/entries/{png.Entry.Id}")).Items("media").Single().Items("conversions").Single();
Assert.AreEqual(("jpg", "converted", true, Path.GetFileName(added)), (row.Str("format"), row.Str("state"), row.Bool("available"), row.Str("fileName")));
Assert.AreEqual(new FileInfo(added).Length, row.Long("bytes"));
Assert.IsEmpty((await server.GetJsonAsync($"/api/entries/{jpg.Entry.Id}")).Items("media").Single().Items("conversions").ToList(), "a JPG has nothing to convert");
using (var file = await server.Client.GetAsync($"/api/conversions/{row.Long("id")}/file?download=1", ct))
{
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType);
Assert.AreEqual(Path.GetFileName(added), file.Content.Headers.ContentDisposition?.FileNameStar ?? file.Content.Headers.ContentDisposition?.FileName?.Trim('"'));
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(added, ct), await file.Content.ReadAsByteArrayAsync(ct));
}
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/conversions/999999/file")).Status);
var (shown, shownBody) = await server.SendJsonAsync(HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = row.Long("id") });
Assert.AreEqual(HttpStatusCode.BadRequest, shown);
StringAssert.Contains(shownBody.Str("message"), "Scarica");
// «Elimina dalla libreria» counts the converted files that go with the entries.
var (previewStatus, deletion) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { png.Entry.Id, jpg.Entry.Id } });
Assert.AreEqual(HttpStatusCode.OK, previewStatus, deletion.ToString());
Assert.AreEqual((2, 2, 1), (deletion.Int("entries"), deletion.Int("files"), deletion.Int("convertedFiles")));
// «Rimuovi» with the files: the converted files go too, and the message says how many.
var (removed, removal) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/remove", new { deleteFiles = true });
Assert.AreEqual(HttpStatusCode.OK, removed, removal.ToString());
Assert.AreEqual(2, removal.Int("convertedFiles"));
StringAssert.Contains(removal.Str("message"), "e 2 file convertiti");
Assert.IsFalse(File.Exists(added));
Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg")));
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheQuestionOfOneKindNeitherCountsNorQueuesTheOther()
{
var ct = TestContext.CancellationToken;
await using var server = await StartAsync();
var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(8), ".png"));
var video = WebLibrary.DemoVideo(3);
var mov = await WebLibrary.AddPostAsync(server, marta, "mov", Make.T0.AddDays(-2), video with { Extension = ".mov" });
// Photos to JPG, «Solo i nuovi»: the PNG already in the library is left alone.
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = false });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(0, saved.Int("queued"));
// Then videos to MP4: the question counts the MOV only, and «Anche i N» queues it only.
var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?video=mp4");
Assert.AreEqual((1, (long)video.Bytes.Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString());
(status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryVideoFormat = "mp4", convertExisting = true });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(1, saved.Int("queued"));
Assert.IsEmpty(await server.Db.Conversions.ListByMediaAsync(png.Media[0].Id, ct), "the photo refused with «Solo i nuovi» stays so");
Assert.AreEqual(ExportFormat.Mp4, (await server.Db.Conversions.ListByMediaAsync(mov.Media[0].Id, ct)).Single().Format);
// Asked about both (no kind named), the preview counts what both formats would add.
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion/preview")).Int("files"), "the PNG");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TwoQuickChangesOfTheSettingsAreBothKept()
{
await using var server = await StartAsync();
for (var round = 0; round < 10; round++)
{
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "jpg", videoFormat = "mp4" });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
// Two clicks one after the other: two requests at once, each changing one format.
var photo = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "original" });
var video = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { videoFormat = "original" });
foreach (var (code, body) in await Task.WhenAll(photo, video))
{
Assert.AreEqual(HttpStatusCode.OK, code, body.ToString());
}
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual(("original", "original"), (overview.Str("photoFormat"), overview.Str("videoFormat")), $"round {round}");
}
}
// ------------------------------------------------------------------------------------------------- support
/// <summary>A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it.</summary>
private static readonly byte[] Heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]];
private static byte[] PngBytes(int scene)
{
using var image = TestImages.Scene(scene, 64, 48);
return TestImages.Png(image);
}
/// <summary>Where the general folder «usb» has the copy of a file of marta.demo, with the extension of its form.</summary>
private static string CopyPath(string usb, Media media, string extension) =>
Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension)));
private static Task<WebTestServer> StartAsync() =>
WebTestServer.StartAsync(
new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None },
s => s.AddSingleton<IExportDisk>(new FakeExportDisk(500_000_000_000)));
private static object Destination(string path, string? photoFormat = null, string? videoFormat = null) => new
{
scope = "general",
accountId = (long?)null,
path,
label = (string?)null,
types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" },
namingScheme = (string?)null,
highlightNamingScheme = (string?)null,
profileNamingScheme = (string?)null,
photoFormat,
videoFormat,
};
/// <summary>A post of @marta.demo with the demo's 2 s video and a photo, saved as the collection does.</summary>
private static async Task<(long Id, long PhotoId)> AddVideoAsync(WebTestServer server)
{
var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
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, "video-1", Make.T0.AddDays(-1)), [Make.Video(1), Make.Photo(2)]);
var media = added.Stored.Media;
await ingest.SaveMediaAsync(account, added.Stored.Entry, media[0], new MediaContent { Content = new MemoryStream(H264PcmWriter.DemoVideo()), Extension = ".mp4" });
await ingest.SaveMediaAsync(account, added.Stored.Entry, media[1], new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(3, 96, 120)), Extension = ".jpg" });
await ingest.AppendJournalAsync(added.Stored.Entry.Id);
return (media[0].Id, media[1].Id);
}
}