Il passaggio che segue la ripresa di un giro non rifà il lavoro di recupero (prova delle cartelle in pausa, ripresa dei lavori fermati da un errore): un lavoro che si ferma di nuovo aspetta il giro dopo invece di essere ripreso all'infinito senza dormire. Il giro misura lo spazio per il lavoro automatico che riprenderebbe, non per una pausa di Alberto, così una pausa per spazio non va e viene con un evento nuovo ogni volta. «Annulla» tiene lontane le partenze automatiche finché il lavoro è annullato; «Esporta questo account» spento ferma subito la copia automatica; «Cerca i video fermi» chiede di fermarsi a una copia automatica partita dopo di lei; un file che manca sul disco non crea più un lavoro automatico a ogni passaggio. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
624 lines
40 KiB
C#
624 lines
40 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.Library.StillVideos;
|
|
using Febe.Core.Storage;
|
|
using Febe.Tests.Codecs.Containers;
|
|
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>
|
|
/// Still videos over the API of a real web host (spec §4.10, tappa E4, D7, D8, D9, D15), with videos built by the test
|
|
/// (<see cref="PcmVideos"/>): «È un video fermo?» from the viewer and what the entry says afterwards, its answers for a
|
|
/// photo, a missing or changed file and an analysis past its time, «Salva il fotogramma» with «Scarica» (the frame the
|
|
/// analysis chose, <c>…_fotogramma.png</c>) and to the folder of the copies (an <c>export_copy</c> row of a frame, never
|
|
/// overwritten, «già copiato» the second time), and «Cerca i video fermi» with its counts, its wait for an engine session,
|
|
/// «Interrompi» and its end.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class StillVideosApiTests
|
|
{
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task TheViewerAnalysesAVideoAndTheEntrySaysIt()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(FadeInStill(3)), WebLibrary.Video(Moving()), WebLibrary.Photo(4));
|
|
var (still, moving, photo) = (post.Media[0], post.Media[1], post.Media[2]);
|
|
|
|
// Before: nothing is known, the viewer offers «È un video fermo?».
|
|
var before = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").ToList();
|
|
Assert.IsTrue(before.All(m => m.GetProperty("still").ValueKind == JsonValueKind.Null), "no analysis yet");
|
|
|
|
server.Clock.Now = Make.T0.AddHours(3);
|
|
var (status, analysed) = await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{still.Id}/still");
|
|
Assert.AreEqual(HttpStatusCode.OK, status, analysed.ToString());
|
|
Assert.AreEqual(("still", true), (analysed.Str("outcome"), analysed.Bool("current")));
|
|
var frameAt = analysed.Long("frameAtMs");
|
|
Assert.IsGreaterThan(300L, frameAt, "the sharpest frame, after the fade from black (answer 45)");
|
|
Assert.AreEqual(ExportFrames.Label(TimeSpan.FromMilliseconds(frameAt)), analysed.Str("frameLabel"));
|
|
Assert.AreEqual($"{LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone):yyyy-MM-dd}", analysed.Str("day"));
|
|
var row = await server.Db.VideoAnalyses.GetAsync(still.Sha256!, ct);
|
|
Assert.AreEqual((VideoAnalysisOutcome.Still, StillVideoAnalyzer.Algorithm, TimeSpan.FromMilliseconds(frameAt)), (row!.Outcome, row.Algorithm, row.FrameAt!.Value));
|
|
|
|
var other = (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{moving.Id}/still")).Body;
|
|
Assert.AreEqual("moving", other.Str("outcome"));
|
|
Assert.AreEqual(JsonValueKind.Null, other.GetProperty("frameAtMs").ValueKind);
|
|
Assert.AreEqual(JsonValueKind.Null, other.GetProperty("frameLabel").ValueKind);
|
|
|
|
// The viewer reads them from the entry; a photo has none.
|
|
var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").ToDictionary(m => m.Long("id"));
|
|
Assert.AreEqual(("still", frameAt), (shown[still.Id].GetProperty("still").Str("outcome"), shown[still.Id].GetProperty("still").Long("frameAtMs")));
|
|
Assert.AreEqual("moving", shown[moving.Id].GetProperty("still").Str("outcome"));
|
|
Assert.AreEqual(JsonValueKind.Null, shown[photo.Id].GetProperty("still").ValueKind);
|
|
|
|
// A photo, an unknown file.
|
|
var (photoStatus, photoBody) = await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{photo.Id}/still");
|
|
Assert.AreEqual((HttpStatusCode.BadRequest, StillVideoText.NotAVideo), (photoStatus, photoBody.Str("message")));
|
|
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Post, "/api/media/999999/still")).Status);
|
|
|
|
// A video Febe cannot decode is «Non analizzabile», with its reason.
|
|
var noise = new byte[40_000];
|
|
new Random(5).NextBytes(noise);
|
|
var junk = await WebLibrary.AddPostAsync(server, marta, "rumore", Make.T0.AddDays(-2), WebLibrary.Video(noise));
|
|
var notAnalyzable = (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{junk.Media[0].Id}/still")).Body;
|
|
Assert.AreEqual(("notAnalyzable", VideoAnalysisNotes.FrameNotAvailable), (notAnalyzable.Str("outcome"), notAnalyzable.Str("note")));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task AMissingOrChangedFileAndASlowAnalysisStoreNothing()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var gone = (await WebLibrary.AddPostAsync(server, marta, "andato", Make.T0.AddDays(-1), WebLibrary.Video(Still(5)))).Media[0];
|
|
var changed = (await WebLibrary.AddPostAsync(server, marta, "cambiato", Make.T0.AddDays(-2), WebLibrary.Video(Still(6)))).Media[0];
|
|
|
|
File.Delete(WebLibrary.PathOf(server, marta, gone));
|
|
var (goneStatus, goneBody) = await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{gone.Id}/still");
|
|
Assert.AreEqual(HttpStatusCode.NotFound, goneStatus);
|
|
Assert.IsNotEmpty(goneBody.Str("message"));
|
|
|
|
await File.WriteAllBytesAsync(WebLibrary.PathOf(server, marta, changed), Still(7), ct);
|
|
var (changedStatus, changedBody) = await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{changed.Id}/still");
|
|
Assert.AreEqual((HttpStatusCode.Conflict, StillVideoText.SourceChanged), (changedStatus, changedBody.Str("message")));
|
|
Assert.IsNull(await server.Db.VideoAnalyses.GetAsync(gone.Sha256!, ct));
|
|
Assert.IsNull(await server.Db.VideoAnalyses.GetAsync(changed.Sha256!, ct));
|
|
|
|
// Past its 30 seconds the viewer says to use the selection, and stores nothing (answer 43).
|
|
await using var slow = await WebTestServer.StartAsync(
|
|
Options,
|
|
s => s.AddSingleton(sp => new StillVideoService(new StillVideoEnvironment
|
|
{
|
|
Storage = sp.GetRequiredService<IFebeStorage>(),
|
|
Resolve = sp.GetRequiredService<IMediaFileResolver>().Resolve,
|
|
Clock = sp.GetRequiredService<IClock>(),
|
|
ViewerBudget = TimeSpan.Zero,
|
|
})));
|
|
var video = (await WebLibrary.AddPostAsync(slow, await AccountAsync(slow), "lento", Make.T0.AddDays(-1), WebLibrary.Video(Still(8)))).Media[0];
|
|
var (slowStatus, slowBody) = await slow.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still");
|
|
Assert.AreEqual((HttpStatusCode.ServiceUnavailable, StillVideoText.TooSlow), (slowStatus, slowBody.Str("message")));
|
|
Assert.IsNull(await slow.Db.VideoAnalyses.GetAsync(video.Sha256!, ct));
|
|
|
|
// Analysed before: the selection would skip it, so the answer does not send there.
|
|
await slow.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.Moving, slow.Clock.Now), ct);
|
|
var (keptStatus, keptBody) = await slow.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still");
|
|
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, keptStatus);
|
|
StringAssert.StartsWith(keptBody.Str("message"), StillVideoText.TooSlowKept);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task ScaricaGivesTheChosenFrameNamedFotogramma()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(FadeInStill(9)), WebLibrary.Video(Moving()));
|
|
var (still, moving) = (post.Media[0], post.Media[1]);
|
|
|
|
// Not analysed yet, or not still: there is no frame to save.
|
|
var (notYet, notYetBody) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{still.Id}/still/frame?download=1");
|
|
Assert.AreEqual(HttpStatusCode.Conflict, notYet);
|
|
StringAssert.StartsWith(notYetBody.Str("message"), StillVideoText.NotStill);
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{moving.Id}/still")).Status);
|
|
Assert.AreEqual(HttpStatusCode.Conflict, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{moving.Id}/still/frame")).Status);
|
|
|
|
var frameAt = (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{still.Id}/still")).Body.Long("frameAtMs");
|
|
byte[] saved;
|
|
using (var response = await server.Client.GetAsync($"/api/media/{still.Id}/still/frame?download=1", ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.AreEqual("image/png", response.Content.Headers.ContentType?.MediaType, "PNG by default (answer 35)");
|
|
Assert.AreEqual(Stem(still) + "_fotogramma.png", FileName(response));
|
|
Assert.IsTrue(response.Headers.CacheControl?.NoCache, "a new analysis may choose another frame");
|
|
saved = await response.Content.ReadAsByteArrayAsync(ct);
|
|
}
|
|
|
|
// The very frame at the instant of the analysis, as «Questo istante» would give it.
|
|
using (var same = await server.Client.GetAsync($"/api/media/{still.Id}/frame?at={frameAt}&format=png", ct))
|
|
{
|
|
CollectionAssert.AreEqual(await same.Content.ReadAsByteArrayAsync(ct), saved);
|
|
}
|
|
|
|
// Other formats, and the 480 px preview of the dialog.
|
|
using (var webp = await server.Client.GetAsync($"/api/media/{still.Id}/still/frame?format=webplossless&download=1", ct))
|
|
{
|
|
Assert.AreEqual(Stem(still) + "_fotogramma.webp", FileName(webp));
|
|
}
|
|
|
|
using (var preview = await server.Client.GetAsync($"/api/media/{still.Id}/still/frame?max=480", ct))
|
|
{
|
|
Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType);
|
|
Assert.IsNull(FileName(preview));
|
|
}
|
|
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{still.Id}/still/frame?format=gif")).Status);
|
|
|
|
// The frames of a selection never take this mode: only the viewer saves the frame of a still video (answer 46).
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{still.Id}/frames/instants?mode=fermo")).Status);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", new { mediaIds = new[] { still.Id }, frames = new { mode = "fermo" } })).Status);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task TheFrameGoesToTheFolderOfTheCopiesNeverOverwritten()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(FadeInStill(10)), WebLibrary.Video(Moving()));
|
|
var (still, moving) = (post.Media[0], post.Media[1]);
|
|
var usb = server.Temp.Combine("usb");
|
|
Directory.CreateDirectory(usb);
|
|
var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb));
|
|
Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString());
|
|
var destinationId = destination.GetProperty("destination").Long("id");
|
|
object Request(long media, string format = "png") => new { mediaIds = new[] { media }, frames = new { mode = "fermo", format } };
|
|
|
|
// Never analysed: nothing to copy, and the dialog says why.
|
|
var none = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", Request(still.Id))).Body;
|
|
Assert.AreEqual((0, 1, 0), (none.Int("frames"), none.Int("notStill"), none.Int("videos")), none.ToString());
|
|
StringAssert.Contains(none.Str("summary"), StillVideoText.NotStill);
|
|
var (noneStatus, noneJob) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", Request(still.Id));
|
|
Assert.AreEqual(HttpStatusCode.OK, noneStatus, noneJob.ToString());
|
|
Assert.IsEmpty(noneJob.Items("runIds").ToList());
|
|
StringAssert.StartsWith(noneJob.Str("message"), StillVideoText.NotStill);
|
|
|
|
var frameAt = (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{still.Id}/still")).Body.Long("frameAtMs");
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{moving.Id}/still")).Status);
|
|
Assert.AreEqual(1, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", Request(moving.Id))).Body.Int("notStill"), "«In movimento»: not still");
|
|
|
|
// One video only, from the viewer (answer 46), and nothing but the format.
|
|
foreach (var wrong in new object[]
|
|
{
|
|
new { mediaIds = new[] { still.Id, moving.Id }, frames = new { mode = "fermo", format = "png" } },
|
|
new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "fermo", format = "png" } },
|
|
new { mediaIds = new[] { still.Id }, frames = new { mode = "fermo", format = "png", count = 3 } },
|
|
})
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", wrong)).Status, JsonSerializer.Serialize(wrong));
|
|
}
|
|
|
|
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", Request(still.Id))).Body;
|
|
Assert.AreEqual((1, 1, 0), (plan.Int("videos"), plan.Int("frames"), plan.Int("notStill")), plan.ToString());
|
|
Assert.AreEqual("1 fotogramma da 1 video", plan.Str("summary"));
|
|
|
|
await WebLibrary.StartAndWaitAsync(server, Request(still.Id));
|
|
var frame = Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(still.RelativePath!, null) + "_fotogramma.png"));
|
|
Assert.IsTrue(File.Exists(frame), string.Join(", ", Directory.GetFiles(usb, "*", SearchOption.AllDirectories)));
|
|
Assert.HasCount(1, Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "only the frame: the video is not copied");
|
|
var copy = (await server.Db.Exports.ListCopiesAsync(destinationId, null, 0, 10, ct)).Single();
|
|
Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(frameAt)), (copy.State, copy.Variant, copy.Format, copy.FrameAt!.Value));
|
|
|
|
// The viewer row and the mark of the entry, as for any frame (E3): the video is not «Copiato».
|
|
var row = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(m => m.Long("id") == still.Id).Items("copies").Single();
|
|
Assert.AreEqual(("copied", "frame", frameAt), (row.Str("state"), row.Str("variant"), row.Long("frameAtMs")));
|
|
var tile = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").Single(t => t.Long("id") == post.Entry.Id);
|
|
Assert.AreEqual("frameOnly", tile.Str("copies"), tile.ToString());
|
|
|
|
// Asked again: «già copiato», the file is not written twice.
|
|
var before = await File.ReadAllBytesAsync(frame, ct);
|
|
await WebLibrary.StartAndWaitAsync(server, Request(still.Id));
|
|
Assert.HasCount(1, Directory.GetFiles(usb, "*", SearchOption.AllDirectories));
|
|
CollectionAssert.AreEqual(before, await File.ReadAllBytesAsync(frame, ct));
|
|
Assert.HasCount(1, await server.Db.Exports.ListCopiesAsync(destinationId, null, 0, 10, ct));
|
|
|
|
// A file of that name that Febe did not write is never overwritten: the frame gets a number.
|
|
File.Delete(frame);
|
|
await File.WriteAllBytesAsync(frame, [1, 2, 3], ct);
|
|
await server.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = server.Clock.Now }, ct);
|
|
await WebLibrary.StartAndWaitAsync(server, Request(still.Id, "png"));
|
|
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(frame, ct), "not overwritten");
|
|
Assert.HasCount(2, Directory.GetFiles(usb, "*_fotogramma*.png", SearchOption.AllDirectories));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task CopiaDiNuovoKeepsTheNameFotogramma()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var still = (await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(FadeInStill(10)))).Media[0];
|
|
var usb = server.Temp.Combine("usb");
|
|
Directory.CreateDirectory(usb);
|
|
var destinationId = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb))).Body.GetProperty("destination").Long("id");
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{still.Id}/still")).Status);
|
|
await WebLibrary.StartAndWaitAsync(server, new { mediaIds = new[] { still.Id }, frames = new { mode = "fermo", format = "png" } });
|
|
|
|
async Task<ExportCopy> AgainAsync()
|
|
{
|
|
var copy = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single();
|
|
File.Delete(Path.Combine(usb, LibraryLayout.ToPlatform(copy.RelativePath!)));
|
|
await server.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = server.Clock.Now }, ct);
|
|
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = copy.Id });
|
|
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
|
|
await WebLibrary.WaitIdleAsync(server);
|
|
var again = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single();
|
|
Assert.AreEqual((copy.FrameAt, copy.Format), (again.FrameAt, again.Format));
|
|
Assert.IsTrue(File.Exists(Path.Combine(usb, LibraryLayout.ToPlatform(again.RelativePath!))), again.RelativePath);
|
|
return again;
|
|
}
|
|
|
|
var first = await AgainAsync();
|
|
StringAssert.EndsWith(first.RelativePath, "_fotogramma.png", "not the name of «Questo istante»");
|
|
|
|
// A file of that name that Febe did not write: the number, and «Copia di nuovo» of the numbered one too.
|
|
var taken = Path.Combine(usb, LibraryLayout.ToPlatform(first.RelativePath!));
|
|
File.Delete(taken);
|
|
await server.Db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed, StateChangedAt = server.Clock.Now }, ct);
|
|
await File.WriteAllBytesAsync(taken, [1, 2, 3], ct);
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = first.Id })).Status);
|
|
await WebLibrary.WaitIdleAsync(server);
|
|
StringAssert.EndsWith((await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single().RelativePath, "_fotogramma (2).png");
|
|
StringAssert.EndsWith((await AgainAsync()).RelativePath, "_fotogramma (2).png");
|
|
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(taken, ct), "never overwritten");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task CercaIVideoFermiCountsWaitsStopsAndEnds()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
var session = new FakeSessionState();
|
|
await using var server = await StartAsync(session);
|
|
var marta = await AccountAsync(server);
|
|
var first = await WebLibrary.AddPostAsync(server, marta, "uno", Make.T0.AddDays(-1), WebLibrary.Video(Still(11)), WebLibrary.Video(Moving()), WebLibrary.Photo(4));
|
|
var second = await WebLibrary.AddPostAsync(server, marta, "due", Make.T0.AddDays(-2), WebLibrary.Video(Still(12)));
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{second.Media[0].Id}/still")).Status);
|
|
var selection = new { entryIds = new[] { first.Entry.Id, second.Entry.Id } };
|
|
|
|
var idle = await server.GetJsonAsync("/api/still-videos/progress");
|
|
Assert.AreEqual((false, 0), (idle.Bool("running"), idle.Int("total")));
|
|
|
|
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body;
|
|
Assert.AreEqual((3, 2, 1, 1, 0), (plan.Int("videos"), plan.Int("toAnalyse"), plan.Int("alreadyAnalysed"), plan.Int("photosSkipped"), plan.Int("missing")), plan.ToString());
|
|
Assert.AreEqual("2 video da analizzare · 1 già analizzato · la foto si salta", plan.Str("summary"));
|
|
Assert.AreEqual(JsonValueKind.Null, plan.GetProperty("waiting").ValueKind);
|
|
|
|
// An automatic copy is no reason to wait: the search makes it give way at once (answer 49); an import is.
|
|
var gate = server.App.Services.GetRequiredService<LongWorkGate>();
|
|
Assert.IsTrue(gate.TryEnterYielding(LongWorkKind.Export, out var automatic, out _, out _));
|
|
using (automatic)
|
|
{
|
|
Assert.AreEqual(JsonValueKind.Null, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.GetProperty("waiting").ValueKind);
|
|
}
|
|
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var import, out _));
|
|
using (import)
|
|
{
|
|
Assert.AreEqual(StillVideoText.LongWork, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Str("waiting"));
|
|
}
|
|
|
|
// During an engine session it waits, and says so (answer 41); «Interrompi» ends it with nothing stored.
|
|
session.InSession = true;
|
|
Assert.AreEqual(StillVideoText.InSession, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Str("waiting"));
|
|
var started = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", selection)).Body;
|
|
Assert.AreEqual((true, 2, 2), (started.Bool("running"), started.Int("total"), started.Int("added")), started.ToString());
|
|
var twice = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", selection)).Body;
|
|
Assert.AreEqual((true, 2, 0), (twice.Bool("running"), twice.Int("total"), twice.Int("added")), "queued already: nothing added");
|
|
await WebLibrary.WaitAsync(async () => (await server.GetJsonAsync("/api/still-videos/progress")).Str("waiting") == StillVideoText.InSession, "the job waits for the session");
|
|
var stopped = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/stop")).Body;
|
|
Assert.IsTrue(stopped.Bool("stopped"));
|
|
await WebLibrary.WaitAsync(async () => !(await server.GetJsonAsync("/api/still-videos/progress")).Bool("running"), "«Interrompi» ends the job");
|
|
Assert.IsNull(await server.Db.VideoAnalyses.GetAsync(first.Media[0].Sha256!, ct));
|
|
Assert.IsNull(await server.Db.VideoAnalyses.GetAsync(first.Media[1].Sha256!, ct));
|
|
|
|
// Started again after the session: it analyses what is left, the one already analysed is skipped.
|
|
session.InSession = false;
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", selection)).Status);
|
|
await WebLibrary.WaitAsync(async () => !(await server.GetJsonAsync("/api/still-videos/progress")).Bool("running"), "the job ends");
|
|
var done = await server.GetJsonAsync("/api/still-videos/progress");
|
|
Assert.AreEqual((2, 2, 1, 1, 0, false), (done.Int("total"), done.Int("done"), done.Int("still"), done.Int("moving"), done.Int("notAnalyzable"), done.Bool("stopped")), done.ToString());
|
|
Assert.AreEqual("Analizzati 2 video: 1 fermo, 1 in movimento", done.Str("summary"));
|
|
var shown = (await server.GetJsonAsync($"/api/entries/{first.Entry.Id}")).Items("media").ToList();
|
|
CollectionAssert.AreEqual(new[] { "still", "moving" }, shown.Take(2).Select(m => m.GetProperty("still").Str("outcome")).ToArray());
|
|
Assert.AreEqual(0, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Int("toAnalyse"));
|
|
|
|
// Exactly one selection.
|
|
foreach (var wrong in new object[] { new { }, new { entryIds = new[] { first.Entry.Id }, mediaIds = new[] { first.Media[0].Id } } })
|
|
{
|
|
var (status, body) = await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", wrong);
|
|
Assert.AreEqual((HttpStatusCode.BadRequest, StillVideoText.NoSelection), (status, body.Str("message")));
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task TheLibraryFilterVideoFermiShowsWhatTheAnalysisFound()
|
|
{
|
|
// Answer 40: «Video fermi» among the kinds of the library, kind=stillvideos; only what was analysed and is still.
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Photo(4), WebLibrary.Video(Still(3)), WebLibrary.Video(Moving()));
|
|
var other = await WebLibrary.AddPostAsync(server, marta, "mosso", Make.T0.AddDays(-2), WebLibrary.Video(PcmVideos.Mp4(12, i => PcmVideos.Photo(200 + i))));
|
|
Assert.AreEqual(0, (await server.GetJsonAsync("/api/library/days?kind=stillvideos")).Int("entries"), "nothing analysed yet: analysis is on request");
|
|
|
|
foreach (var media in new[] { post.Media[1], post.Media[2], other.Media[0] })
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{media.Id}/still")).Status);
|
|
}
|
|
|
|
var grouped = await server.GetJsonAsync("/api/library?kind=stillvideos&limit=50");
|
|
CollectionAssert.AreEqual(new[] { post.Entry.Id }, grouped.Items("tiles").Select(t => t.Long("id")).ToArray());
|
|
Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?kind=stillvideos")).Int("entries"));
|
|
var files = await server.GetJsonAsync("/api/library?mode=files&kind=StillVideos&limit=50");
|
|
CollectionAssert.AreEqual(new[] { post.Media[1].Id }, files.Items("tiles").Select(t => t.GetProperty("cover").Long("mediaId")).ToArray(), "only the still video, not the photo nor the moving video of the post");
|
|
Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?mode=files&kind=stillvideos")).Int("files"));
|
|
Assert.AreEqual(1, (await server.GetJsonAsync($"/api/library/days?kind=stillvideos&accounts={marta.Id}")).Int("entries"));
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?kind=fermi")).Status);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CommandsOfStillVideosComeOnlyFromFebesPages()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "fermo", Make.T0.AddDays(-1), WebLibrary.Video(Still(13)));
|
|
var selection = new { mediaIds = new[] { post.Media[0].Id } };
|
|
foreach (var (path, body) in new (string, object?)[]
|
|
{
|
|
($"/api/media/{post.Media[0].Id}/still", null),
|
|
("/api/still-videos/plan", selection),
|
|
("/api/still-videos/start", selection),
|
|
("/api/still-videos/stop", null),
|
|
})
|
|
{
|
|
using var request = server.Request(HttpMethod.Post, path, body, "http://altro.example");
|
|
using var response = await server.Client.SendAsync(request, ct);
|
|
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path);
|
|
}
|
|
|
|
Assert.IsNull(await server.Db.VideoAnalyses.GetAsync(post.Media[0].Sha256!, ct), "nothing was analysed");
|
|
Assert.IsFalse((await server.GetJsonAsync("/api/still-videos/progress")).Bool("running"));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task EverySelectionIsCountedAndTheSameFileIsAnalysedOnce()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var luca = await server.Db.Accounts.AddAsync(Make.Account("luca.demo", "200"));
|
|
var same = Still(14);
|
|
var first = await WebLibrary.AddPostAsync(server, marta, "uno", Make.T0.AddDays(-1), WebLibrary.Video(same), WebLibrary.Photo(4), WebLibrary.Photo(5));
|
|
var twin = (await server.Db.Entries.AddAsync(
|
|
Make.Entry(marta.Id, "due", Make.T0.AddDays(-2)),
|
|
[Make.Stored(Make.Video(1), first.Media[0].Sha256!, first.Media[0].RelativePath!)],
|
|
ct)).Stored;
|
|
var other = await WebLibrary.AddPostAsync(server, luca, "tre", Make.T0.AddDays(-3), WebLibrary.Video(Moving()));
|
|
Assert.AreEqual(first.Media[0].Sha256, twin.Media[0].Sha256);
|
|
|
|
async Task<JsonElement> PlanAsync(object selection)
|
|
{
|
|
var (status, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, plan.ToString());
|
|
return plan;
|
|
}
|
|
|
|
// The files, the entries, a filter in both modes, an account: one file counts once, the photos are told apart.
|
|
foreach (var (selection, toAnalyse, photos) in new (object, int, int)[]
|
|
{
|
|
(new { mediaIds = new[] { first.Media[0].Id, first.Media[1].Id } }, 1, 1),
|
|
(new { mediaIds = new[] { first.Media[1].Id, first.Media[2].Id } }, 0, 2),
|
|
(new { entryIds = new[] { first.Entry.Id, twin.Entry.Id, other.Entry.Id } }, 2, 2),
|
|
(new { query = $"accounts={marta.Id}", mode = "grouped" }, 1, 2),
|
|
(new { query = "kind=videos", mode = "files" }, 2, 0),
|
|
(new { query = "kind=stillvideos", mode = "files" }, 0, 0),
|
|
(new { accountId = luca.Id }, 1, 0),
|
|
})
|
|
{
|
|
var plan = await PlanAsync(selection);
|
|
Assert.AreEqual((toAnalyse, photos), (plan.Int("toAnalyse"), plan.Int("photosSkipped")), $"{JsonSerializer.Serialize(selection)}: {plan}");
|
|
}
|
|
|
|
// Photos only: nothing to start, and the job does not.
|
|
var none = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", new { mediaIds = new[] { first.Media[1].Id } })).Body;
|
|
Assert.AreEqual((false, 0), (none.Bool("running"), none.Int("total")), none.ToString());
|
|
|
|
// Analysed once, under either post; the second asks nothing more.
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", new { accountId = marta.Id })).Status);
|
|
await WebLibrary.WaitAsync(async () => !(await server.GetJsonAsync("/api/still-videos/progress")).Bool("running"), "the job ends");
|
|
Assert.AreEqual(1, (await server.GetJsonAsync("/api/still-videos/progress")).Int("still"));
|
|
var shown = (await server.GetJsonAsync($"/api/entries/{twin.Entry.Id}")).Items("media").Single().GetProperty("still");
|
|
Assert.AreEqual("still", shown.Str("outcome"), "the same file under another post has the same analysis");
|
|
var tiles = (await server.GetJsonAsync("/api/library?kind=stillvideos&limit=50")).Items("tiles").Select(t => t.Long("id")).ToArray();
|
|
CollectionAssert.AreEquivalent(new[] { first.Entry.Id, twin.Entry.Id }, tiles);
|
|
Assert.AreEqual(1, (await PlanAsync(new { query = "kind=stillvideos", mode = "grouped" })).Int("alreadyAnalysed"));
|
|
|
|
// An analysis of an algorithm newer than this Febe's is current (there is none older than 1 yet).
|
|
await server.Db.VideoAnalyses.SetAsync(new VideoAnalysis(other.Media[0].Sha256!, StillVideoAnalyzer.Algorithm + 1, VideoAnalysisOutcome.Moving, server.Clock.Now), ct);
|
|
var newer = (await server.GetJsonAsync($"/api/entries/{other.Entry.Id}")).Items("media").Single().GetProperty("still");
|
|
Assert.AreEqual(("moving", true), (newer.Str("outcome"), newer.Bool("current")), newer.ToString());
|
|
Assert.AreEqual(0, (await PlanAsync(new { accountId = luca.Id })).Int("toAnalyse"));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task TheFrameOfAPhotoAnUnknownOrAMissingFileIsRefused()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(Still(15)), WebLibrary.Photo(4));
|
|
var video = post.Media[0];
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still")).Status);
|
|
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{post.Media[1].Id}/still/frame")).Status);
|
|
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/media/999999/still/frame")).Status);
|
|
|
|
// Another file in its place: the analysis was of the old one, so there is no frame to save.
|
|
var sha = video.Sha256!;
|
|
await server.Db.Media.UpdateAsync((await server.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = Make.Sha(91) }, ct);
|
|
var (replaced, body) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.Id}/still/frame");
|
|
Assert.AreEqual(HttpStatusCode.Conflict, replaced);
|
|
StringAssert.StartsWith(body.Str("message"), StillVideoText.NotStill);
|
|
await server.Db.Media.UpdateAsync((await server.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = sha }, ct);
|
|
|
|
File.Delete(WebLibrary.PathOf(server, marta, video));
|
|
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.Id}/still/frame?download=1")).Status);
|
|
Assert.AreEqual(VideoAnalysisOutcome.Still, (await server.Db.VideoAnalyses.GetAsync(sha, ct))!.Outcome, "what was found of the file stays");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task TheOpenPagesHearOfAnAnalysisOnce()
|
|
{
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var video = (await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(Still(16)))).Media[0];
|
|
var changes = server.Changes.SubscribeAsync().GetAsyncEnumerator();
|
|
var next = changes.MoveNextAsync().AsTask();
|
|
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still")).Status);
|
|
|
|
Assert.IsTrue(await next.WaitAsync(TimeSpan.FromSeconds(20)), "the library of the open pages is read again");
|
|
Assert.AreEqual(("fermi", (long?)marta.Id), (changes.Current.Reason, changes.Current.AccountId));
|
|
await changes.DisposeAsync();
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(60_000, CooperativeCancellation = true)]
|
|
public async Task AChangeFollowedAtOnceByAnAnalysisIsNotLost()
|
|
{
|
|
// The Dashboard and the accounts skip «fermi»: during «Cerca i video fermi» a copy that ends must still reach them.
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, "/api/eventi");
|
|
request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin");
|
|
using var response = await server.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
|
|
using var reader = new StreamReader(await response.Content.ReadAsStreamAsync(ct));
|
|
using var done = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
|
|
// Again and again: the stream may not be listening to the library yet when its first line comes.
|
|
var publishing = Task.Run(
|
|
async () =>
|
|
{
|
|
while (!done.IsCancellationRequested)
|
|
{
|
|
server.Changes.Publish(new LibraryChange(server.Clock.Now, null, "export"));
|
|
for (var i = 1; i <= 40; i++)
|
|
{
|
|
server.Changes.Publish(new LibraryChange(server.Clock.Now, i, "fermi"));
|
|
}
|
|
|
|
await Task.Delay(3000, done.Token).ContinueWith(_ => { }, TaskScheduler.Default);
|
|
}
|
|
},
|
|
CancellationToken.None);
|
|
|
|
var reasons = new HashSet<string>();
|
|
var library = false;
|
|
while (reasons.Count < 2 && await reader.ReadLineAsync(ct) is { } line)
|
|
{
|
|
if (line.StartsWith("event: ", StringComparison.Ordinal))
|
|
{
|
|
library = line == "event: libreria";
|
|
}
|
|
else if (library && line.StartsWith("data: ", StringComparison.Ordinal))
|
|
{
|
|
using var json = JsonDocument.Parse(line[6..]);
|
|
reasons.Add(json.RootElement.Str("reason"));
|
|
}
|
|
}
|
|
|
|
await done.CancelAsync();
|
|
await publishing;
|
|
CollectionAssert.AreEquivalent(new[] { "export", "fermi" }, reasons.ToArray());
|
|
}
|
|
|
|
[TestMethod]
|
|
public void PendingChangesKeepOneForEachReason()
|
|
{
|
|
var pending = new PendingLibraryChanges();
|
|
Assert.IsFalse(pending.Any);
|
|
pending.Add(new LibraryChange(Make.T0, 1, "stored"));
|
|
pending.Add(new LibraryChange(Make.T0.AddSeconds(1), 2, "export"));
|
|
pending.Add(new LibraryChange(Make.T0.AddSeconds(2), 1, "fermi"));
|
|
pending.Add(new LibraryChange(Make.T0.AddSeconds(3), 1, "stored"));
|
|
pending.Add(new LibraryChange(Make.T0.AddSeconds(4), 3, "fermi"));
|
|
Assert.IsTrue(pending.Any);
|
|
CollectionAssert.AreEqual(
|
|
new[] { ("export", (long?)2), ("stored", 1), ("fermi", null) },
|
|
pending.Take().Select(c => (c.Reason, c.AccountId)).ToArray(),
|
|
"the account only if it is the same");
|
|
Assert.IsFalse(pending.Any);
|
|
Assert.IsEmpty(pending.Take());
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------- support
|
|
|
|
private static readonly FebeWebOptions Options = new() { Edition = FebeEdition.Desktop, Access = AccessMode.None };
|
|
|
|
private static Task<WebTestServer> StartAsync(IEngineSessionState? session = null) =>
|
|
WebTestServer.StartAsync(
|
|
Options,
|
|
s =>
|
|
{
|
|
s.AddSingleton<IExportDisk>(new FakeExportDisk(500_000_000_000));
|
|
if (session is not null)
|
|
{
|
|
s.AddSingleton(session);
|
|
}
|
|
});
|
|
|
|
private static Task<Account> AccountAsync(WebTestServer server) => server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
|
|
|
/// <summary>A still picture for 12 pictures (0,4 s); <paramref name="seed"/> makes each one another file.</summary>
|
|
private static byte[] Still(int seed)
|
|
{
|
|
var photo = PcmVideos.Photo(seed);
|
|
return PcmVideos.Mp4(12, _ => photo);
|
|
}
|
|
|
|
/// <summary>One second of a photo, the first nine pictures fading in from black (the frame chosen comes after).</summary>
|
|
private static byte[] FadeInStill(int seed)
|
|
{
|
|
var photo = PcmVideos.Photo(seed);
|
|
return PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(photo, i / 9.0) : photo, audio: true);
|
|
}
|
|
|
|
private static byte[] Moving() => PcmVideos.Mp4(12, i => PcmVideos.Photo(100 + i));
|
|
|
|
private static string Stem(Media media) => Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(media.RelativePath!));
|
|
|
|
private static string? FileName(HttpResponseMessage response) =>
|
|
response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName?.Trim('"');
|
|
}
|