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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 01:02:37 +01:00
1 parent 724c5bda6f
commit ab0d717424
25 files changed
+2559 -95

No files matched your search

+62 -1
View File
@@ -12,7 +12,8 @@ namespace Febe.Tests.Web;
/// <summary>
/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account
/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real
/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there.
/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. Tappa E3:
/// a copy converted to PNG, a frame of a video and two conversions of the library, which the demo never runs.
/// </summary>
[TestClass]
public sealed class DemoExportTests
@@ -61,12 +62,18 @@ public sealed class DemoExportTests
var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct);
Assert.IsGreaterThanOrEqualTo(2, destinations.Count);
var states = new HashSet<ExportCopyState>();
var forms = new List<ExportCopy>();
foreach (var destination in destinations)
{
Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath);
foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct))
{
states.Add(copy.State);
if (copy.State == ExportCopyState.Copied && copy.Variant != ExportVariant.Whole)
{
forms.Add(copy);
}
var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null;
switch (copy.State)
{
@@ -149,5 +156,59 @@ public sealed class DemoExportTests
}
Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy");
// Tappa E3: the converted copy (by the real engine) and the frame are real files with their SHA-256 (checked above).
var convertedCopy = forms.SingleOrDefault(c => c.Variant == ExportVariant.Converted);
Assert.IsNotNull(convertedCopy, "a copy converted to PNG");
Assert.AreEqual(ExportFormat.Png, convertedCopy.Format);
StringAssert.EndsWith(convertedCopy.RelativePath, ".png");
var frameCopy = forms.Single(c => c.Variant == ExportVariant.Frame);
Assert.AreEqual(TimeSpan.FromMilliseconds(1125), frameCopy.FrameAt, "1.234 s shows the picture shown from 1.125 s");
StringAssert.EndsWith(frameCopy.RelativePath, "_t0m01s125.png");
// The demo video gives frames: the preview of that instant is the frame copied.
var videoId = frameCopy.MediaId!.Value;
var info = await GetAsync($"/api/media/{videoId}/frames/info");
Assert.IsTrue(info.Bool("available"), info.ToString());
Assert.AreEqual(2000L, info.Long("durationMs"));
using (var frame = await client.GetAsync($"/api/media/{videoId}/frame?at=1234&format=png&download=1", ct))
{
Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
Assert.AreEqual("image/png", frame.Content.Headers.ContentType?.MediaType);
Assert.AreEqual(frameCopy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await frame.Content.ReadAsByteArrayAsync(ct))));
}
var video = await demo.Storage.Media.GetAsync(videoId, ct);
var viewer = (await GetAsync($"/api/entries/{video!.EntryId}")).Items("media").Single(m => m.Long("id") == videoId);
Assert.IsTrue(viewer.Bool("framesAvailable"));
var frameRow = viewer.Items("copies").Single(c => c.Str("variant") == "frame");
Assert.AreEqual(1125L, frameRow.Long("frameAtMs"));
Assert.AreEqual("0:01,125", frameRow.Str("frameLabel"));
// Two conversions of the library, which the demo never runs: nothing waits and nothing changes.
var conversion = await GetAsync("/api/export/library-conversion");
Assert.AreEqual(0, conversion.Int("pending"));
Assert.AreEqual(1, conversion.Int("converted"));
Assert.AreEqual(1, conversion.Int("asIs"));
Assert.AreEqual(0, conversion.Int("failed"));
var (rowId, file) = demo.World.ConversionFiles.Single();
var row = await demo.Storage.Conversions.GetAsync(rowId, ct);
Assert.AreEqual(MediaConversionState.Converted, row!.State);
using (var converted = await client.GetAsync($"/api/conversions/{rowId}/file", ct))
{
Assert.AreEqual(HttpStatusCode.OK, converted.StatusCode);
Assert.AreEqual("image/png", converted.Content.Headers.ContentType?.MediaType);
Assert.AreEqual(row.Sha256, Convert.ToHexStringLower(SHA256.HashData(await converted.Content.ReadAsByteArrayAsync(ct))));
}
var photo = await demo.Storage.Media.GetAsync(row.MediaId, ct);
var shown = (await GetAsync($"/api/entries/{photo!.EntryId}")).Items("media").Single(m => m.Long("id") == row.MediaId);
var shownRow = shown.Items("conversions").Single();
Assert.AreEqual("converted", shownRow.Str("state"));
Assert.AreEqual("png", shownRow.Str("format"));
Assert.IsTrue(shownRow.Bool("available"));
await Task.Delay(TimeSpan.FromSeconds(1), ct);
Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(rowId, ct))!.State, "the demo never converts");
Assert.IsTrue(File.Exists(file));
}
}
+5 -2
View File
@@ -219,8 +219,11 @@ public sealed class DemoTests
}
else
{
// Videos have only their cover in the demo.
Assert.AreEqual(HttpStatusCode.NotFound, file.StatusCode);
// Every video of the demo plays its one short H.264 video (tappa E3: «Fotogramma» works in the demo).
Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
Assert.AreEqual("video/mp4", file.Content.Headers.ContentType?.MediaType);
var bytes = await file.Content.ReadAsByteArrayAsync();
Assert.AreEqual("ftyp", System.Text.Encoding.ASCII.GetString(bytes, 4, 4), "a real MP4");
checkedVideos++;
}
}
+2 -1
View File
@@ -139,7 +139,8 @@ public sealed class ExportApiDemoTests
Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark");
var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList();
Assert.IsNotEmpty(notCopied);
Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark");
// Tappa E3: a video with only a frame copied is still to copy, and says so («frameOnly»), never «copiato».
Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null || t.Str("copies") == "frameOnly"), "a file not copied has no mark of a copy");
Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status);
var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList();
@@ -0,0 +1,197 @@
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);
}
}
+82
View File
@@ -0,0 +1,82 @@
using System.IO.Compression;
using Febe.Core.Codecs.H264;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Tests.Support;
using Febe.Web.Export;
namespace Febe.Tests.Web;
/// <summary>
/// The zip of «Scarica» of frames (tappa E3, D14): written while it is sent, through asynchronous writes only (a
/// response body refuses synchronous ones), one entry per frame under the account folder, names made unique.
/// </summary>
[TestClass]
public sealed class FrameServiceTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task TheZipIsWrittenThroughAsynchronousWritesOnly()
{
using var temp = new TempFolder("fotogrammi-zip");
var path = temp.Combine("video.mp4");
await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), TestContext.CancellationToken);
var clock = new ManualClock(Make.T0);
var service = new FrameService(clock);
var instants = new[] { TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.5) };
var plan = new FrameDownloadPlan(FrameMode.Count, ExportFormat.Png, [
new FrameDownloadVideo("marta.demo", path, "post", instants, Make.T0.AddDays(-3)),
new FrameDownloadVideo("marta.demo", path, "post", instants[..1], Make.T0.AddDays(-3)),
]);
using var sent = new MemoryStream();
await service.WriteZipAsync(new AsyncOnlyStream(sent), plan, publicationTime: true, TestContext.CancellationToken);
using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
CollectionAssert.AreEqual(
new[] { "marta.demo/post_f001.png", "marta.demo/post_f002.png", "marta.demo/post_f003.png", "marta.demo/post_f001 (2).png" },
archive.Entries.Select(e => e.FullName).ToArray());
var published = TimeZoneInfo.ConvertTime(Make.T0.AddDays(-3), clock.LocalZone).DateTime;
foreach (var entry in archive.Entries)
{
Assert.AreEqual(entry.Length, entry.CompressedLength, "frames are stored, not compressed");
// The zip keeps local date and time fields at 2 s steps: the time of publication where Febe runs (D18).
Assert.IsLessThanOrEqualTo(2.0, Math.Abs((entry.LastWriteTime.DateTime - published).TotalSeconds), $"{entry.LastWriteTime} vs {published}");
}
}
/// <summary>A response body: asynchronous writes only.</summary>
private sealed class AsyncOnlyStream(Stream inner) : Stream
{
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() => throw new InvalidOperationException("synchronous flush");
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
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 InvalidOperationException("synchronous write");
public override void Write(ReadOnlySpan<byte> buffer) => throw new InvalidOperationException("synchronous write");
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
inner.WriteAsync(buffer, offset, count, cancellationToken);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
inner.WriteAsync(buffer, cancellationToken);
}
}