Files
Febe/tests/Febe.Tests/Web/ExportFormatsApiTests.cs
T
Alby96andClaude Opus 5.5 ab0d717424 E3: API di formati e fotogrammi, conversione della libreria e demo
Porta le funzioni della tappa E3 fino all'interfaccia web, così che WP4
possa costruire le schermate su indirizzi veri.

- Impostazioni, cartelle delle copie e «Copia in…» hanno i formati
  (nomi original, jpg, png, webplossless, mp4); il riepilogo dice cosa si
  converte, cosa resta com'è e se c'è perdita. «Copia di nuovo» rifà la
  copia nella sua forma esatta.
- Fotogrammi: informazioni di un video, un fotogramma (anteprima o
  scaricamento), gli istanti di una modalità, «Scarica» di uno o di uno
  zip scritto mentre parte, con il permesso dei lavori lunghi oltre 20.
  Kestrel non vede mai scritture sincrone: il piccolo descrittore che lo
  zip di .NET 10 scrive in modo sincrono parte con la scrittura seguente.
- Conversione della libreria: stato, la domanda «Converti anche i N già
  in libreria?», riprova, pausa e ripresa; il visualizzatore mostra i
  file convertiti, e le eliminazioni li contano.
- Demo: un video H.264 scritto in casa (solo macroblocchi I_PCM) per
  ogni video, una copia in PNG, un fotogramma e due conversioni; la
  conversione non parte mai.

Due prove cambiano con il comportamento: i video della demo ora si
aprono, e un file non copiato può avere il segno «solo fotogramma».

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

198 lines
10 KiB
C#

using System.IO.Compression;
using System.Net;
using System.Text.Json;
using Febe.Core.Codecs.H264;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
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>
/// 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);
}
// ------------------------------------------------------------------------------------------------- support
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);
}
}