Esportazione, tappa E4: video fermi #80

Merged
Alby96 merged 22 commits from funzione/video-fermi into main 2026-12-01 21:56:37 +01:00
17 changed files with 695 additions and 18 deletions
Showing only changes of commit 51150fb611 - Show all commits

No files matched your search

+10
View File
@@ -15,6 +15,7 @@ using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Data;
@@ -942,6 +943,15 @@ public sealed class FebeApp : IAsyncDisposable
if (Web is { } web)
{
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
// «Cerca i video fermi» (tappa E4): the job gives up the video it analyses (nothing stored for it) and ends
// before the database closes; it does not resume at the next start (answer 41).
await Quietly(async () =>
{
var stills = web.Services.GetRequiredService<StillVideoService>();
stills.Dispose();
await stills.Job.ConfigureAwait(false);
}).ConfigureAwait(false);
}
if (Engine is { } engine)
+10 -3
View File
@@ -32,7 +32,7 @@ public static class ExportFrames
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => 1,
FrameMode.At or FrameMode.Still => 1,
FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
@@ -48,7 +48,8 @@ public static class ExportFrames
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
// «Salva il fotogramma»: the caller puts the analysis' instant in At (the planner reads it per video).
FrameMode.At or FrameMode.Still => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
@@ -102,11 +103,17 @@ public static class ExportFrames
/// <summary>
/// The suffix of a frame file, appended to the stem: <c>_t0m12s340</c> (the actual instant: minutes, seconds on two
/// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; <c>_f001</c> (the position among
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto».
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto»; <c>_fotogramma</c>
/// (<see cref="SingleSuffix"/>) for «Salva il fotogramma» of a still video.
/// </summary>
/// <param name="index">0-based position of the instant in the request.</param>
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
{
if (mode == FrameMode.Still)
{
return SingleSuffix;
}
if (mode == FrameMode.Count)
{
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
+13
View File
@@ -34,6 +34,13 @@ public enum FrameMode
/// <summary>«N in tutto»: N frames spread over the video, each in the middle of its share.</summary>
Count,
/// <summary>
/// «Salva il fotogramma» of a still video (tappa E4, answer 45): the one frame the analysis chose (the sharpest
/// looked at, never a dark one), at the instant <c>video_analysis</c> keeps; named <c>…_fotogramma</c>. One video
/// only (answer 46).
/// </summary>
Still,
}
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
@@ -114,6 +121,12 @@ public sealed record ExportPlan(
/// <summary>Frames job: videos that would give more than <see cref="ExportFrames.MaxPerVideo"/> frames (the job is refused).</summary>
public int OverCap { get; init; }
/// <summary>
/// «Salva il fotogramma» (tappa E4): due videos whose analysis is not «Fermo», or that were never analysed (skipped:
/// «Non è un video fermo, o non è stato analizzato»).
/// </summary>
public int NotStill { get; init; }
}
/// <summary>Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»).</summary>
+34 -2
View File
@@ -99,7 +99,12 @@ public sealed class ExportPlanner(ExportEnvironment env)
throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request));
case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount):
throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request));
case FrameMode.At or FrameMode.Every or FrameMode.Count:
case FrameMode.Still when frames.At is not null || frames.Every is not null || frames.Count is not null:
throw new ArgumentException("«Salva il fotogramma» prende il fotogramma scelto dall'analisi: niente istante, intervallo o numero.", nameof(request));
case FrameMode.Still when request.Selection is not ExportSelection.Media { MediaIds.Count: 1 }:
// Answer 46 of Alberto (29 November 2026): only from the viewer, one video.
throw new ArgumentException("«Salva il fotogramma» vale per un video solo, dal visualizzatore.", nameof(request));
case FrameMode.At or FrameMode.Every or FrameMode.Count or FrameMode.Still:
break;
default:
throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request));
@@ -294,6 +299,24 @@ public sealed class ExportPlanner(ExportEnvironment env)
Prediction = ExportPrediction.Converted,
FirstOfVideo = true,
};
if (frames.Mode == FrameMode.Still)
{
// «Salva il fotogramma» (tappa E4): the instant the analysis chose, by SHA-256 of the file; a video
// that is not «Fermo» (or was never analysed) gives nothing.
var analysis = await _env.Storage.VideoAnalyses.GetAsync(c.Sha256!, ct).ConfigureAwait(false);
if (analysis is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } still })
{
yield return frame with { Action = PlannedCopy.NotStill };
continue;
}
var chosen = frame with { FrameAt = still };
yield return seen.Add((destination, c.AccountId, c.Sha256!, (long)still.TotalMilliseconds, frames.Format))
? chosen
: chosen with { Action = PlannedCopy.AlreadyCopied };
continue;
}
var duration = c.Duration ?? TimeSpan.Zero;
if (frames.Mode != FrameMode.At && c.Duration is null)
{
@@ -409,6 +432,9 @@ internal enum PlannedCopy
/// <summary>Frames job: a video over <see cref="ExportFrames.MaxPerVideo"/> frames.</summary>
OverCap,
/// <summary>«Salva il fotogramma» (tappa E4): a video whose analysis is not «Fermo», or that was never analysed.</summary>
NotStill,
}
/// <summary>Counts of a plan while its files go by.</summary>
@@ -441,15 +467,20 @@ internal sealed class PlanTally
public int OverCap { get; private set; }
public int NotStill { get; private set; }
public void Add(PlannedFile file)
{
if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing))
if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing or PlannedCopy.NotStill))
{
Videos++;
}
switch (file.Action)
{
case PlannedCopy.NotStill:
NotStill++;
return;
case PlannedCopy.Missing:
Missing++;
return;
@@ -545,6 +576,7 @@ internal sealed class PlanTally
PhotosSkipped = PhotosSkipped,
Frames = Frames,
OverCap = OverCap,
NotStill = NotStill,
};
}
+10 -1
View File
@@ -11,7 +11,10 @@ internal static class ExportRunSettings
{
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
/// <summary>How the frames of a frames job were asked (tappa E3): <c>Istante</c>, <c>Ogni</c> or <c>Numero:N</c>.</summary>
/// <summary>
/// How the frames of a frames job were asked (tappa E3): <c>Istante</c>, <c>Ogni</c> or <c>Numero:N</c>; <c>Fermo</c>
/// for «Salva il fotogramma» of a still video (tappa E4).
/// </summary>
public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi");
/// <summary>«Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3).</summary>
@@ -36,6 +39,11 @@ internal static class ExportRunSettings
return (FrameMode.Every, 0);
}
if (string.Equals(text, "Fermo", StringComparison.Ordinal))
{
return (FrameMode.Still, 1);
}
return text.StartsWith("Numero:", StringComparison.Ordinal)
&& int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0
? (FrameMode.Count, count)
@@ -49,6 +57,7 @@ internal static class ExportRunSettings
{
FrameMode.At => "Istante",
FrameMode.Every => "Ogni",
FrameMode.Still => "Fermo",
_ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"),
},
ct);
+1 -1
View File
@@ -208,7 +208,7 @@ public sealed class ExportService : IAsyncDisposable
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
{
tally.Add(file);
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap or PlannedCopy.NotStill)
{
continue;
}
@@ -20,6 +20,15 @@ public static class StillVideoText
/// <summary>The bytes on disk are not the ones recorded (the same words as the copies).</summary>
public const string SourceChanged = "Il file della libreria non corrisponde a quello registrato.";
/// <summary>«Salva il fotogramma» of a video whose analysis is not «Fermo», or that was never analysed.</summary>
public const string NotStill = "Non è un video fermo, o non è stato analizzato";
/// <summary>A selection of «Cerca i video fermi» that names nothing.</summary>
public const string NoSelection = "Scegli quali video analizzare: dei file, degli elementi, i risultati del filtro o un account.";
/// <summary>The frame of a still video is saved from the viewer only (answer 46).</summary>
public const string FromViewerOnly = "Il fotogramma di un video fermo si salva dal visualizzatore, con «Salva il fotogramma».";
/// <summary>The job waits for the end of an engine session.</summary>
public const string InSession = "Il motore è in sessione: la ricerca dei video fermi riprende dopo";
+2 -1
View File
@@ -94,7 +94,8 @@ public sealed record MediaDto(
bool Damaged = false,
IReadOnlyList<MediaCopyDto>? Copies = null,
bool? FramesAvailable = null,
IReadOnlyList<MediaConversionDto>? Conversions = null);
IReadOnlyList<MediaConversionDto>? Conversions = null,
StillVideoDto? Still = null);
/// <summary>Everything the viewer shows of an entry.</summary>
public sealed record EntryDto(
+18 -2
View File
@@ -3,6 +3,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
@@ -582,7 +583,8 @@ public static class ExportApi
plan.PhotosSkipped,
plan.Frames,
plan.OverCap,
PlanSummary(plan, frames));
PlanSummary(plan, frames),
plan.NotStill);
}
/// <summary>
@@ -605,6 +607,11 @@ public static class ExportApi
{
parts.Add(ExportFrames.OverCapMessage);
}
if (plan.NotStill > 0)
{
parts.Add(StillVideoText.NotStill);
}
}
else
{
@@ -764,8 +771,15 @@ public static class ExportApi
"istante" or "at" => FrameMode.At,
"ogni" or "every" => FrameMode.Every,
"numero" or "count" => FrameMode.Count,
"fermo" or "still" => FrameMode.Still,
_ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."),
};
if (mode == FrameMode.Still && (body.AtMs is not null || body.EveryMs is not null || body.Count is not null))
{
// The instant is the analysis' own (tappa E4): one asked by the page would be another frame.
throw new BadRequestException("«Salva il fotogramma» prende il fotogramma scelto dall'analisi: niente istante, intervallo o numero.");
}
return new ExportFramesRequest(
mode,
mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null,
@@ -1029,7 +1043,9 @@ public static class ExportApi
[.. start.Runs.Select(r => r.Id)],
Plan(start.Plan, root, frames),
start.Runs.Count == 0
? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria."
? start.Plan.NotStill > 0 && start.Plan.Files == 0
? StillVideoText.NotStill + ": niente da copiare."
: "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria."
: "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione.");
private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary<long, string> labels, IClock clock, bool running)
+54 -3
View File
@@ -158,7 +158,8 @@ public sealed record CopyJobRequestDto(
/// <summary>
/// Which frames (spec §4.10 «Fotogrammi»): <paramref name="Mode"/> <c>istante</c> (at <paramref name="AtMs"/>),
/// <c>ogni</c> (every <paramref name="EveryMs"/>, at least 100) or <c>numero</c> (<paramref name="Count"/> in all, 1 to
/// 1.000); <paramref name="Format"/> <c>jpg</c>, <c>png</c> (the default) or <c>webplossless</c>.
/// 1.000), or <c>fermo</c> («Salva il fotogramma» of one still video, tappa E4: the instant of its analysis, nothing
/// else); <paramref name="Format"/> <c>jpg</c>, <c>png</c> (the default) or <c>webplossless</c>.
/// </summary>
public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null);
@@ -186,7 +187,8 @@ public sealed record ExportPlanDestinationDto(
/// converted, <paramref name="Lossy"/> «con perdita»; a frames job: <paramref name="Videos"/>,
/// <paramref name="PhotosSkipped"/>, <paramref name="Frames"/> and <paramref name="OverCap"/> (videos over 1.000
/// frames: the job is refused). <paramref name="Summary"/>: the line of the dialog («312 file · 41 già copiati, saltati ·
/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»).
/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»). Tappa E4, «Salva il fotogramma»:
/// <paramref name="NotStill"/> videos that are not «Fermo» or were never analysed (skipped).
/// </summary>
public sealed record ExportPlanDto(
int Files,
@@ -204,7 +206,8 @@ public sealed record ExportPlanDto(
int PhotosSkipped = 0,
int Frames = 0,
int OverCap = 0,
string? Summary = null);
string? Summary = null,
int NotStill = 0);
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
@@ -356,3 +359,51 @@ public sealed record ConversionActionRequest(long ConversionId);
/// the library made from them («elimino gli elementi interi, 9 file e 2 file convertiti»).
/// </summary>
public sealed record EntryDeletionPreviewDto(int Entries, int Files, int ConvertedFiles);
// ---------------------------------------------------------------------------------------------- still videos (tappa E4)
/// <summary>
/// The analysis of a video («È un video fermo?», spec §4.10, tappa E4), on <see cref="MediaDto.Still"/> and as the answer
/// of <c>POST /api/media/{id}/still</c>; a video never analysed has none. <paramref name="Outcome"/>: <c>still</c>,
/// <c>moving</c> or <c>notAnalyzable</c>; <paramref name="Current"/>: made by the algorithm of this Febe (otherwise
/// «Analizza di nuovo»); <paramref name="FrameAtMs"/> and <paramref name="FrameLabel"/> («0:01,125»): the frame
/// «Salva il fotogramma» saves, only on <c>still</c>; <paramref name="Note"/>: English codes separated by spaces
/// (<c>FrameNotAvailable</c>, <c>DurationUnknown</c>, <c>Unreadable</c>, <c>TooSlow</c>, <c>AllDark</c>,
/// <c>SingleColor</c>, <c>SmallMotion</c>); <paramref name="Day"/>: the local day of the analysis (yyyy-MM-dd).
/// </summary>
public sealed record StillVideoDto(string Outcome, bool Current, long? FrameAtMs, string? FrameLabel, string? Note, string Day);
/// <summary>
/// The selection of «Cerca i video fermi»: exactly one of <paramref name="MediaIds"/>, <paramref name="EntryIds"/>
/// (every video of those entries), <paramref name="Query"/> with <paramref name="Mode"/>, or <paramref name="AccountId"/>.
/// </summary>
public sealed record StillVideosSelectionRequest(IReadOnlyList<long>? MediaIds, IReadOnlyList<long>? EntryIds, string? Query, string? Mode, long? AccountId = null);
/// <summary>
/// <c>POST /api/still-videos/plan</c>: the confirmation of «Cerca i video fermi», by file (two entries of one video count
/// once). <paramref name="Videos"/> = <paramref name="ToAnalyse"/> + <paramref name="AlreadyAnalysed"/> (skipped) +
/// <paramref name="Missing"/> (not in the library); <paramref name="PhotosSkipped"/>: photos of the selection;
/// <paramref name="Summary"/>: «28 video da analizzare · 12 già analizzati · le 5 foto si saltano»;
/// <paramref name="Waiting"/>: why the job would wait now (an engine session, an import, copies or a rebuild), or null.
/// </summary>
public sealed record StillVideosPlanDto(int Videos, int ToAnalyse, int AlreadyAnalysed, int PhotosSkipped, int Missing, string Summary, string? Waiting);
/// <summary>
/// The job «Cerca i video fermi» (<c>GET /api/still-videos/progress</c>, and the answer of start and stop):
/// <paramref name="Done"/> of <paramref name="Total"/> settled as <paramref name="Still"/>, <paramref name="Moving"/>,
/// <paramref name="NotAnalyzable"/> or <paramref name="Skipped"/> (file gone or changed); <paramref name="Stopped"/>:
/// ended by «Interrompi»; <paramref name="Waiting"/>: why it waits now; <paramref name="CurrentMediaId"/>: the file analysed
/// now; <paramref name="Summary"/>: «Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile».
/// </summary>
public sealed record StillVideosProgressDto(
bool Running,
int Total,
int Done,
int Still,
int Moving,
int NotAnalyzable,
int Skipped,
bool Stopped,
string? Waiting,
long? CurrentMediaId,
string Summary);
+4
View File
@@ -115,4 +115,8 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(FramesTokenDto))]
[JsonSerializable(typeof(ConversionActionRequest))]
[JsonSerializable(typeof(EntryDeletionPreviewDto))]
[JsonSerializable(typeof(StillVideoDto))]
[JsonSerializable(typeof(StillVideosSelectionRequest))]
[JsonSerializable(typeof(StillVideosPlanDto))]
[JsonSerializable(typeof(StillVideosProgressDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
+15 -3
View File
@@ -4,6 +4,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
@@ -63,6 +64,11 @@ public static class FramesApi
{
var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
var request = ExportApi.Frames(new FramesRequestDto(mode ?? "numero", at, every, count, "png"));
if (request.Mode == FrameMode.Still)
{
throw new BadRequestException(StillVideoText.FromViewerOnly);
}
ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Media([id]), Frames: request));
var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false);
var durationMs = (long)info.Duration.TotalMilliseconds;
@@ -231,6 +237,12 @@ public static class FramesApi
private static async Task<FramesSelection> SelectionAsync(FramesSelectionRequest body, IFebeStorage storage, IMediaFileResolver files, FrameService frames, IClock clock, CancellationToken ct)
{
var request = body.Frames is { } f ? ExportApi.Frames(f) : throw new BadRequestException("Scegli quali fotogrammi.");
if (request.Mode == FrameMode.Still)
{
// «Scarica» of «Salva il fotogramma» is /api/media/{id}/still/frame (StillVideosApi).
throw new BadRequestException(StillVideoText.FromViewerOnly);
}
var selection = ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, null), clock).Selection;
ExportPlanner.Validate(new ExportJobRequest(selection, Frames: request));
var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
@@ -387,10 +399,10 @@ public static class FramesApi
// ---------------------------------------------------------------------------------------------- helpers
private sealed record VideoFile(Account Account, Media Media, string Path);
internal sealed record VideoFile(Account Account, Media Media, string Path);
/// <summary>A present video of the library on disk; 404 otherwise.</summary>
private static async Task<VideoFile> VideoAsync(IFebeStorage storage, IMediaFileResolver files, long mediaId, CancellationToken ct)
internal static async Task<VideoFile> VideoAsync(IFebeStorage storage, IMediaFileResolver files, long mediaId, CancellationToken ct)
{
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
if (media.Kind != MediaKind.Video)
@@ -404,7 +416,7 @@ public static class FramesApi
return new VideoFile(account, media, path);
}
private static string Stem(Media media) =>
internal static string Stem(Media media) =>
media.RelativePath is { } relative ? Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(relative)) : "video-" + media.Id.ToString(CultureInfo.InvariantCulture);
/// <summary>The file of a Converted or Superseded conversion of a present account, or null.</summary>
+7 -1
View File
@@ -274,6 +274,9 @@ public static class LibraryApi
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false);
var converted = conversions is null ? [] : await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false);
// «È un video fermo?» (tappa E4): the analyses of the entry's videos, in one read, by SHA-256 of the file.
var videoShas = stored.Media.Where(m => m.Kind == MediaKind.Video && m.Sha256 is { Length: 64 }).Select(m => m.Sha256!.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToList();
var analyses = videoShas.Count == 0 ? null : await storage.VideoAnalyses.GetManyAsync(videoShas, ct).ConfigureAwait(false);
var media = new List<MediaDto>(stored.Media.Count);
foreach (var m in stored.Media)
{
@@ -303,7 +306,10 @@ public static class LibraryApi
damaged,
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false),
await FramesAvailableAsync(frames, m, path, ct).ConfigureAwait(false),
conversions is null ? null : FramesApi.Conversions(conversions, account, converted.Where(c => c.MediaId == m.Id))));
conversions is null ? null : FramesApi.Conversions(conversions, account, converted.Where(c => c.MediaId == m.Id)),
m.Kind == MediaKind.Video && m.Sha256 is { Length: 64 } sha && analyses is not null && analyses.TryGetValue(sha.ToLowerInvariant(), out var analysis)
? StillVideosApi.Dto(analysis, clock)
: null));
}
return new EntryDto(
+142
View File
@@ -0,0 +1,142 @@
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.Web.Export;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>
/// Still videos (spec §4.10, tappa E4), only on request, never in the background: «È un video fermo?» of one video
/// from the viewer (also during an engine session, within 30 s, answer 43), the frame of «Salva il fotogramma» for
/// «Scarica» (<c>…_fotogramma.png</c>, the sharpest frame the analysis looked at, answer 45), and the job «Cerca i video
/// fermi» of a selection with its confirmation, progress and «Interrompi» (answer 41). «Salva il fotogramma» to the
/// folder of the copies goes through <c>/api/export/plan</c> and <c>/start</c> with <c>frames: { mode: "fermo" }</c>.
/// Every command passes the Origin check of the security middleware like any other. Nothing here writes a file.
/// </summary>
public static class StillVideosApi
{
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.MapPost("/api/media/{id:long}/still", async (long id, StillVideoService stills, IClock clock, CancellationToken ct) =>
{
var answer = await stills.AnalyseNowAsync(id, ct).ConfigureAwait(false);
return answer.Kind switch
{
StillVideoAnswerKind.Analysed => ApiHttp.Json(Dto(answer.Analysis!, clock), FebeJsonContext.Default.StillVideoDto),
StillVideoAnswerKind.NotAVideo => throw new BadRequestException(answer.Message!),
StillVideoAnswerKind.SourceChanged => throw new ApiStatusException(409, answer.Message!),
StillVideoAnswerKind.TooSlow => throw new ApiStatusException(503, answer.Message!),
_ => throw new NotFoundException(answer.Message ?? StillVideoText.NotFound),
};
});
endpoints.MapGet("/api/media/{id:long}/still/frame", async (long id, string? format, int? max, string? download, HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
{
var video = await FramesApi.VideoAsync(storage, files, id, ct).ConfigureAwait(false);
var analysis = video.Media.Sha256 is { Length: 64 } sha ? await storage.VideoAnalyses.GetAsync(sha.ToLowerInvariant(), ct).ConfigureAwait(false) : null;
if (analysis is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } at })
{
throw new ApiStatusException(409, StillVideoText.NotStill + ".");
}
int? side = max is { } m ? Math.Clamp(m, 16, FrameService.MaxPreview) : null;
var chosen = string.IsNullOrWhiteSpace(format) && side is not null ? ExportFormat.Jpg : ExportApi.ParseFrameFormat(format);
var frame = await frames.FrameAsync(video.Path, video.Media.Sha256, at, chosen, side, ct).ConfigureAwait(false);
// A new analysis can choose another frame at the same address: never kept by the browser.
context.Response.Headers.CacheControl = "private, no-cache";
if (download is "1" or "true")
{
var name = FrameService.FileName(FramesApi.Stem(video.Media), FrameMode.Still, frame.Actual, 0, 1, chosen);
return Results.File(frame.Data, frame.ContentType, name);
}
return Results.File(frame.Data, frame.ContentType);
});
endpoints.MapPost("/api/still-videos/plan", async (HttpContext context, StillVideoService stills, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.StillVideosSelectionRequest).ConfigureAwait(false);
var selection = Selection(body, clock);
var plan = await ExportApi.GuardAsync(() => stills.PlanAsync(selection, ct)).ConfigureAwait(false);
return ApiHttp.Json(
new StillVideosPlanDto(plan.Videos, plan.ToAnalyse, plan.AlreadyAnalysed, plan.PhotosSkipped, plan.Missing, StillVideoText.PlanSummary(plan), Waiting(gate, session)),
FebeJsonContext.Default.StillVideosPlanDto);
});
endpoints.MapPost("/api/still-videos/start", async (HttpContext context, StillVideoService stills, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.StillVideosSelectionRequest).ConfigureAwait(false);
var selection = Selection(body, clock);
var progress = await ExportApi.GuardAsync(() => stills.StartAsync(selection, ct)).ConfigureAwait(false);
return ApiHttp.Json(Progress(progress), FebeJsonContext.Default.StillVideosProgressDto);
});
endpoints.MapGet("/api/still-videos/progress", (StillVideoService stills) =>
ApiHttp.Json(Progress(stills.Progress), FebeJsonContext.Default.StillVideosProgressDto));
endpoints.MapPost("/api/still-videos/stop", (StillVideoService stills) =>
ApiHttp.Json(Progress(stills.Stop()), FebeJsonContext.Default.StillVideosProgressDto));
}
/// <summary>The analysis of a video as the viewer shows it.</summary>
public static StillVideoDto Dto(VideoAnalysis analysis, IClock clock)
{
ArgumentNullException.ThrowIfNull(analysis);
ArgumentNullException.ThrowIfNull(clock);
var still = analysis.Outcome == VideoAnalysisOutcome.Still ? analysis.FrameAt : null;
return new StillVideoDto(
Outcome(analysis.Outcome),
analysis.Algorithm >= StillVideoAnalyzer.Algorithm,
still is { } at ? ExportFrames.ActualMs(at) : null,
still is { } shown ? ExportFrames.Label(shown) : null,
analysis.Note,
ApiMapping.Day(DateOnly.FromDateTime(LocalCalendar.ToLocal(analysis.AnalyzedAt, clock.LocalZone))));
}
/// <summary>The wire name of an outcome: <c>still</c>, <c>moving</c>, <c>notAnalyzable</c>.</summary>
public static string Outcome(VideoAnalysisOutcome outcome) => outcome switch
{
VideoAnalysisOutcome.Still => "still",
VideoAnalysisOutcome.Moving => "moving",
_ => "notAnalyzable",
};
private static StillVideosProgressDto Progress(StillVideoProgress p) => new(
p.Running,
p.Total,
p.Done,
p.Still,
p.Moving,
p.NotAnalyzable,
p.Skipped,
p.Stopped,
p.Waiting,
p.CurrentMediaId,
StillVideoText.Summary(p));
/// <summary>Exactly one selection, as «Copia in…» and «Fotogrammi…» take it.</summary>
private static ExportSelection Selection(StillVideosSelectionRequest body, IClock clock)
{
var chosen = (body.MediaIds is { Count: > 0 } ? 1 : 0) + (body.EntryIds is { Count: > 0 } ? 1 : 0) + (body.Query is not null ? 1 : 0) + (body.AccountId is not null ? 1 : 0);
if (chosen != 1)
{
throw new BadRequestException(StillVideoText.NoSelection);
}
return ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, body.AccountId), clock).Selection;
}
/// <summary>Why the job would wait now (the dialog says it), or null.</summary>
private static string? Waiting(LongWorkGate gate, IEngineSessionState session) =>
session.InSession ? StillVideoText.InSession : gate.Busy is not null ? StillVideoText.LongWork : null;
}
+4
View File
@@ -112,6 +112,8 @@ public static class FebeWeb
var clock = sp.GetRequiredService<IClock>();
var changes = sp.GetRequiredService<LibraryChanges>();
var files = sp.GetRequiredService<IMediaFileResolver>();
// Italian text and exception type names only (never paths), to the log of the composition (Febe's in FebeApp).
var logger = sp.GetService<ILoggerFactory>()?.CreateLogger("Febe.VideoFermi");
return new StillVideoService(new StillVideoEnvironment
{
Storage = sp.GetRequiredService<IFebeStorage>(),
@@ -120,6 +122,7 @@ public static class FebeWeb
Gate = sp.GetRequiredService<LongWorkGate>(),
Session = sp.GetRequiredService<IEngineSessionState>(),
Changed = accountId => changes.Publish(new LibraryChange(clock.Now, accountId, "fermi")),
Log = logger is null ? null : message => logger.LogWarning("{Message}", message),
});
});
services.AddHttpContextAccessor();
@@ -185,6 +188,7 @@ public static class FebeWeb
ImportApi.Map(endpoints);
ExportApi.Map(endpoints);
FramesApi.Map(endpoints);
StillVideosApi.Map(endpoints);
DuplicatesApi.Map(endpoints);
SearchApi.Map(endpoints);
RemoteViewSocket.Map(endpoints);
+4 -1
View File
@@ -76,6 +76,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
| `ExportRootOptions` (Core, copie esterne §4.10) | Docker: `/esporta` **non dichiarata** (nulla si scrive); desktop: qualsiasi cartella | Server: `--esporta`/`FEBE_ESPORTA` (attiva solo se c'è un montaggio su `/esporta` o sotto); dimostrazione: la sua `esporta`, mostrata come `/esporta` (`ShownAs`) |
| `IExportDisk` (Core) | `SystemExportDisk` (spazio libero delle lettere di unità, FAT32 dal tipo del file system) | Desktop: `WindowsExportDisk` (anche le condivisioni di rete come `\\nas\foto`); prove e dimostrazione: misure fisse |
| `IEngineSessionState` (Core) | `NoEngineSession`: le copie non aspettano mai | `Febe.App`: `RuntimeSessionState` sul motore (fra una sessione e l'altra, D10) |
| `StillVideoService` (Core, tappa E4) | Uno solo sull'archivio, sui file della libreria (`IMediaFileResolver`), su `LongWorkGate` e `IEngineSessionState`, con lo SHA-256 controllato prima di ogni analisi; il registro riceve solo testo italiano e nomi di eccezioni | La dimostrazione ne vuole uno con `VerifySource = false` (i suoi SHA-256 non sono quelli dei file); le prove, budget diversi. `Febe.App` usa il ripiego e lo chiude all'arresto prima dell'archivio |
| `ExportHub` (`Export/`) | Costruisce l'unico `ExportService` al primo uso (e segna «interrotto» ciò che l'arresto ha fermato, `Recovered`); a lavoro finito pubblica `LibraryChange` con motivo `export` | Nessuno |
- `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già
@@ -143,8 +144,10 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `GET /api/export/library-conversion`, `GET /library-conversion/preview?photo=&video=`, `POST /library-conversion/retry`, `/pause`, `/resume` | Conversione della libreria (tappa E3): `pending`, `converted`, `failed`, `asIs`, `paused`, `waiting`, `text`; la domanda «Converti anche i N già in libreria?» (`{ files, bytes, text }`); «Riprova», «Metti in pausa», «Riprendi» |
| `GET /api/export/folders?path=`, `POST /api/export/pick-folder` (`{ destinationId }`), `/check-folder` (`{ path }`), `/naming-preview` | Scelta della cartella: in Docker l'elenco sotto `/esporta` (solo se attiva; `..` è 400), sul desktop la finestra del sistema; controllo con spazio libero e FAT32; «Risultato» dei nomi |
| `POST /api/export/destinations`, `PUT/DELETE /api/export/destinations/{id}`, `GET /{id}/status`, `POST /{id}/resume`, `/{id}/check` | Cartelle: tipi `postFoto`, `postVideo`, `storie`, `evidenza`, `taggati`, `profilo`; `photoFormat` e `videoFormat` (vuoti o `general`: come le impostazioni generali); un cambio di cartella dà un id nuovo; togliere non cancella nulla; «Riprova» (sonda, poi riprende i lavori in pausa); «Controlla le copie» |
| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain, photoFormat?, videoFormat?, frames? }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo (con `asIs`, `converted`, `lossy`, `videos`, `photosSkipped`, `frames`, `overCap`, `summary`), avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato nella sua forma esatta. `frames` (`{ mode: "istante"\|"ogni"\|"numero", atMs, everyMs, count, format }`) copia fotogrammi dei video invece dei file; non va insieme ai formati |
| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain, photoFormat?, videoFormat?, frames? }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo (con `asIs`, `converted`, `lossy`, `videos`, `photosSkipped`, `frames`, `overCap`, `summary`), avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato nella sua forma esatta. `frames` (`{ mode: "istante"\|"ogni"\|"numero", atMs, everyMs, count, format }`) copia fotogrammi dei video invece dei file; non va insieme ai formati. `mode: "fermo"` (tappa E4) è «Salva il fotogramma» → «Nella cartella delle copie»: un solo file (`mediaIds` di uno), solo `format`, l'istante è quello dell'analisi, nome `…_fotogramma.<ext>`; un video non «Fermo» o mai analizzato si salta (`notStill`, «Non è un video fermo, o non è stato analizzato») |
| `GET /api/media/{id}/frames/info`, `GET /api/media/{id}/frame?at=ms&format=&max=&download=1`, `GET /api/media/{id}/frames/instants?mode=&at=&every=&count=` (ms) | Fotogrammi (`Api/FramesApi.cs`, `Export/FrameService.cs`): se un video li dà; un fotogramma (anteprima con `max` fino a 480 px, JPG; scaricamento a piena risoluzione, PNG se non si sceglie, nome con l'istante vero); gli istanti di una modalità con etichette e suffissi. Uno alla volta, 30 s al più (503 dopo) |
| `POST /api/media/{id}/still`, `GET /api/media/{id}/still/frame?format=&max=&download=1` | Video fermi (`Api/StillVideosApi.cs`, `StillVideoService` di Core, tappa E4), solo a richiesta: «È un video fermo?» analizza subito un video (anche durante una sessione del motore, una analisi alla volta, 30 s al più: 503 «L'analisi richiede troppo tempo: avviala dalla selezione», niente salvato; 400 una foto, 404 file assente, 409 file cambiato) e risponde con `still` (`outcome` `still`\|`moving`\|`notAnalyzable`, `current`, `frameAtMs`, `frameLabel`, `note` in codici inglesi, `day`), lo stesso che ha ogni video del visualizzatore in `media[].still` (null se mai analizzato). Il fotogramma di «Salva il fotogramma» → «Scarica»: quello scelto dall'analisi (il più nitido, mai uno scuro), PNG se non si sceglie, nome `…_fotogramma.<ext>`, `max` per l'anteprima (JPG); 409 se il video non è «Fermo». Mai in cache |
| `POST /api/still-videos/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId }`, uno solo), `GET /api/still-videos/progress`, `POST /api/still-videos/stop` | «Cerca i video fermi»: conteggi della conferma per file (`toAnalyse`, `alreadyAnalysed`, `photosSkipped`, `missing`, `summary`, `waiting` se ora aspetterebbe); un lavoro in memoria, un video alla volta, mai durante una sessione del motore né con importazione, copie, ricostruzione o uno zip di fotogrammi (aspetta, `waiting` dice perché), 2 minuti per video (oltre «Non analizzabile»); avanzamento con `summary` («Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile»); «Interrompi» non salva il video in corso. Non riprende da solo alla riapertura; i già analizzati si saltano. Ogni esito salvato pubblica `LibraryChange` con motivo `fermi` |
| `POST /api/frames/plan`, `POST /api/frames/download-token` (`{ mediaIds \| entryIds \| query+mode, frames }`), `GET /api/frames/download/{token}` | «Fotogrammi…» → «Scarica»: riepilogo; un gettone in memoria (5 minuti, una volta sola); un fotogramma è un'immagine, da 2 a 500 uno zip scritto mentre parte (senza compressione, `<account>/<nome>`). Oltre 20 serve il motore fermo e nessun altro lavoro lungo (409 altrimenti) |
| `GET /api/conversions/{id}/file[?download=1]`, `POST /api/conversions/show-in-folder` (`{ conversionId }`), `POST /api/entries/delete-preview` (`{ ids }`) | File convertiti della libreria (`conversions` di ogni file del visualizzatore, con `framesAvailable` per i video e `frameAtMs`, `frameLabel`, `notes` nelle copie); quanti file e file convertiti toglierebbe «Elimina dalla libreria» |
| `GET /api/export/progress`, `GET /api/export/runs?limit=`, `POST /api/export/interrupt`, `/resume`, `/runs/{id}/resume`, `/runs/{id}/discard`, `GET /runs/{id}/report` | Scheda Esportazione della Dashboard: avanzamento, lavori, interruzione, ripresa, annullamento (i file copiati restano), resoconto (al più 200 problemi) |
+358
View File
@@ -0,0 +1,358 @@
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));
}
[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 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);
// 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), (started.Bool("running"), started.Int("total")), started.ToString());
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]
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"));
}
// ------------------------------------------------------------------------------------------------- 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('"');
}