diff --git a/docs/decisioni.md b/docs/decisioni.md
index 1e4ec59..3715297 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -629,3 +629,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file |
| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella |
| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie |
+| 2026-11-28 | Tappa E3: lo **zip dei fotogrammi** si scrive con l'API asincrona di `ZipArchive` (`CreateAsync`, `OpenAsync`, `DisposeAsync`) su `Response.Body`, senza abilitare l'I/O sincrono di Kestrel: .NET 10 scrive ancora in modo sincrono il piccolo descrittore di ogni voce, che `FrameService` tiene in memoria (al più 64 KB) e manda con la scrittura asincrona seguente. Il video della dimostrazione è scritto in casa (`H264PcmWriter`: solo macroblocchi I_PCM, 240×432, 8 fotogrammi al secondo, 2 s) | Un `Write` sincrono sul corpo della risposta è rifiutato da Kestrel; abilitarlo terrebbe un thread fermo per ogni lettore lento |
diff --git a/src/Febe.Core/Codecs/H264/H264PcmWriter.cs b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
new file mode 100644
index 0000000..6582402
--- /dev/null
+++ b/src/Febe.Core/Codecs/H264/H264PcmWriter.cs
@@ -0,0 +1,322 @@
+using Febe.Core.Codecs.Containers;
+
+namespace Febe.Core.Codecs.H264;
+
+///
+/// One picture of an I_PCM stream in 4:2:0: is Width × Height luma samples, and
+/// are Width/2 × Height/2, row by row. Width and height are multiples of 16.
+///
+public sealed class H264PcmPicture
+{
+ public H264PcmPicture(int width, int height)
+ {
+ if (width <= 0 || height <= 0 || width % 16 != 0 || height % 16 != 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(width), "Larghezza e altezza devono essere multipli di 16.");
+ }
+
+ Width = width;
+ Height = height;
+ Y = new byte[width * height];
+ Cb = new byte[width / 2 * (height / 2)];
+ Cr = new byte[width / 2 * (height / 2)];
+ }
+
+ public int Width { get; }
+
+ public int Height { get; }
+
+ public byte[] Y { get; }
+
+ public byte[] Cb { get; }
+
+ public byte[] Cr { get; }
+}
+
+///
+/// Writes H.264 streams made only of IDR pictures of I_PCM macroblocks (ITU-T H.264 §7.3: Baseline parameter sets, one
+/// slice per picture, every sample written as it is), muxed in MP4 with . Every pixel is known
+/// and every picture is an exact start for a decoder: the demo's video (frames in --demo) and the tests use it.
+/// Nothing is compressed, so the files are large (about 1,5 bytes per pixel per picture): for short, small videos only.
+///
+public static class H264PcmWriter
+{
+ /// Width of the demo video (15 macroblocks, no cropping).
+ public const int DemoWidth = 240;
+
+ /// Height of the demo video (27 macroblocks, no cropping).
+ public const int DemoHeight = 432;
+
+ /// Pictures per second of the demo video.
+ public const int DemoFps = 8;
+
+ /// Pictures of the demo video (two seconds).
+ public const int DemoPictures = 16;
+
+ /// The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI.
+ public static byte[] Sps(int width, int height)
+ {
+ var bits = new Bits();
+ bits.Write(66, 8); // profile_idc: Baseline
+ bits.Write(0, 8); // constraint_set flags
+ bits.Write(30, 8); // level_idc 3.0
+ bits.Ue(0); // seq_parameter_set_id
+ bits.Ue(0); // log2_max_frame_num_minus4
+ bits.Ue(2); // pic_order_cnt_type: output order = decoding order
+ bits.Ue(1); // max_num_ref_frames
+ bits.Write(0, 1); // gaps_in_frame_num_value_allowed_flag
+ bits.Ue((uint)(width / 16) - 1); // pic_width_in_mbs_minus1
+ bits.Ue((uint)(height / 16) - 1); // pic_height_in_map_units_minus1
+ bits.Write(1, 1); // frame_mbs_only_flag
+ bits.Write(1, 1); // direct_8x8_inference_flag
+ bits.Write(0, 1); // frame_cropping_flag
+ bits.Write(0, 1); // vui_parameters_present_flag
+ return Nal(0x67, bits);
+ }
+
+ /// The picture parameter set (CAVLC, one slice group, deblocking control present).
+ public static byte[] Pps()
+ {
+ var bits = new Bits();
+ bits.Ue(0); // pic_parameter_set_id
+ bits.Ue(0); // seq_parameter_set_id
+ bits.Write(0, 1); // entropy_coding_mode_flag: CAVLC
+ bits.Write(0, 1); // bottom_field_pic_order_in_frame_present_flag
+ bits.Ue(0); // num_slice_groups_minus1
+ bits.Ue(0); // num_ref_idx_l0_default_active_minus1
+ bits.Ue(0); // num_ref_idx_l1_default_active_minus1
+ bits.Write(0, 1); // weighted_pred_flag
+ bits.Write(0, 2); // weighted_bipred_idc
+ bits.Se(0); // pic_init_qp_minus26
+ bits.Se(0); // pic_init_qs_minus26
+ bits.Se(0); // chroma_qp_index_offset
+ bits.Write(1, 1); // deblocking_filter_control_present_flag
+ bits.Write(0, 1); // constrained_intra_pred_flag
+ bits.Write(0, 1); // redundant_pic_cnt_present_flag
+ return Nal(0x68, bits);
+ }
+
+ /// An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code.
+ /// The samples.
+ /// idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate).
+ public static byte[] Idr(H264PcmPicture picture, int idrPicId)
+ {
+ ArgumentNullException.ThrowIfNull(picture);
+ var bits = new Bits(picture.Y.Length * 3 / 2 + 1024);
+ bits.Ue(0); // first_mb_in_slice
+ bits.Ue(7); // slice_type: I (all slices of the picture)
+ bits.Ue(0); // pic_parameter_set_id
+ bits.Write(0, 4); // frame_num
+ bits.Ue((uint)idrPicId);
+ bits.Write(0, 1); // no_output_of_prior_pics_flag
+ bits.Write(0, 1); // long_term_reference_flag
+ bits.Se(0); // slice_qp_delta
+ bits.Ue(1); // disable_deblocking_filter_idc: off
+ var mbWidth = picture.Width / 16;
+ var mbHeight = picture.Height / 16;
+ var chromaWidth = picture.Width / 2;
+ for (var my = 0; my < mbHeight; my++)
+ {
+ for (var mx = 0; mx < mbWidth; mx++)
+ {
+ bits.Ue(25); // mb_type: I_PCM
+ bits.Align(); // pcm_alignment_zero_bit
+ for (var y = 0; y < 16; y++)
+ {
+ bits.Bytes(picture.Y.AsSpan(((my * 16) + y) * picture.Width + (mx * 16), 16));
+ }
+
+ foreach (var plane in new[] { picture.Cb, picture.Cr })
+ {
+ for (var y = 0; y < 8; y++)
+ {
+ bits.Bytes(plane.AsSpan(((my * 8) + y) * chromaWidth + (mx * 8), 8));
+ }
+ }
+ }
+ }
+
+ return Nal(0x65, bits);
+ }
+
+ /// The avcC of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes.
+ public static byte[] AvcConfiguration(byte[] sps, byte[] pps)
+ {
+ ArgumentNullException.ThrowIfNull(sps);
+ ArgumentNullException.ThrowIfNull(pps);
+ return
+ [
+ 1, sps[1], sps[2], sps[3], 0xFF, 0xE1,
+ (byte)(sps.Length >> 8), (byte)sps.Length, .. sps,
+ 1, (byte)(pps.Length >> 8), (byte)pps.Length, .. pps,
+ ];
+ }
+
+ ///
+ /// Writes an MP4 of pictures at per second, picture i given by
+ /// , every one an IDR sync sample.
+ ///
+ /// Where the file goes (from its current position).
+ /// Width, a multiple of 16.
+ /// Height, a multiple of 16.
+ /// Pictures.
+ /// Pictures per second.
+ /// The samples of picture i (called once per picture, in order).
+ /// The creation date of the movie; null writes none.
+ public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func picture, DateTimeOffset? created = null)
+ {
+ ArgumentNullException.ThrowIfNull(output);
+ ArgumentNullException.ThrowIfNull(picture);
+ ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
+ ArgumentOutOfRangeException.ThrowIfLessThan(fps, 1);
+ var sps = Sps(width, height);
+ var pps = Pps();
+ var samples = new List(count);
+ for (var i = 0; i < count; i++)
+ {
+ var p = picture(i);
+ if (p.Width != width || p.Height != height)
+ {
+ throw new ArgumentException("Ogni fotogramma deve avere le dimensioni del video.", nameof(picture));
+ }
+
+ var nal = Idr(p, i % 2);
+ var sample = new byte[nal.Length + 4];
+ System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(sample, nal.Length);
+ nal.CopyTo(sample, 4);
+ samples.Add(sample);
+ }
+
+ const int Ticks = 1000;
+ var track = new Mp4OutputTrack
+ {
+ IsVideo = true,
+ Timescale = (long)fps * Ticks,
+ Samples = [.. samples.Select((s, i) => new Mp4OutputSample(s.Length, (long)i * Ticks, (long)i * Ticks, true))],
+ WriteSample = (i, s) => s.Write(samples[i]),
+ Width = width,
+ Height = height,
+ AvcConfiguration = AvcConfiguration(sps, pps),
+ LastSampleDuration = Ticks,
+ };
+ Mp4Writer.Write(output, [track], created);
+ }
+
+ ///
+ /// The demo's video: ×, pictures per second for
+ /// two seconds, a diagonal gradient that moves to the right with colours that change over time.
+ ///
+ public static byte[] DemoVideo()
+ {
+ using var output = new MemoryStream();
+ WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, DemoPicture, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
+ return output.ToArray();
+ }
+
+ /// Picture of the demo video (luma 16-235, chroma 16-240: no zero byte).
+ public static H264PcmPicture DemoPicture(int index)
+ {
+ var p = new H264PcmPicture(DemoWidth, DemoHeight);
+ var shift = index * 219 / DemoPictures;
+ for (var y = 0; y < DemoHeight; y++)
+ {
+ for (var x = 0; x < DemoWidth; x++)
+ {
+ var ramp = ((x * 219 / DemoWidth) + (y * 219 / DemoHeight / 2) + 219 - shift) % 219;
+ p.Y[(y * DemoWidth) + x] = (byte)(16 + ramp);
+ }
+ }
+
+ var chromaWidth = DemoWidth / 2;
+ for (var y = 0; y < DemoHeight / 2; y++)
+ {
+ for (var x = 0; x < chromaWidth; x++)
+ {
+ p.Cb[(y * chromaWidth) + x] = (byte)(64 + (y * 128 / (DemoHeight / 2)));
+ p.Cr[(y * chromaWidth) + x] = (byte)(64 + ((x * 64 / chromaWidth) + (index * 64 / DemoPictures)));
+ }
+ }
+
+ return p;
+ }
+
+ /// A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention).
+ private static byte[] Nal(byte header, Bits bits)
+ {
+ bits.Write(1, 1); // rbsp_stop_one_bit
+ bits.Align();
+ var rbsp = bits.ToArray();
+ var output = new List(rbsp.Length + (rbsp.Length / 64) + 2) { header };
+ var zeros = 0;
+ foreach (var b in rbsp)
+ {
+ // Never two zero bytes followed by a byte up to 3 (§7.4.1).
+ if (zeros >= 2 && b <= 3)
+ {
+ output.Add(3);
+ zeros = 0;
+ }
+
+ output.Add(b);
+ zeros = b == 0 ? zeros + 1 : 0;
+ }
+
+ return [.. output];
+ }
+
+ /// A big-endian bit writer for the RBSP.
+ private sealed class Bits(int capacity = 64)
+ {
+ private readonly List _bytes = new(capacity);
+ private int _current;
+ private int _used;
+
+ public void Write(uint value, int count)
+ {
+ for (var i = count - 1; i >= 0; i--)
+ {
+ _current = (_current << 1) | (int)((value >> i) & 1);
+ if (++_used == 8)
+ {
+ _bytes.Add((byte)_current);
+ _current = 0;
+ _used = 0;
+ }
+ }
+ }
+
+ public void Ue(uint value)
+ {
+ var code = value + 1;
+ var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
+ Write(0, length - 1);
+ Write(code, length);
+ }
+
+ public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
+
+ public void Align()
+ {
+ while (_used != 0)
+ {
+ Write(0, 1);
+ }
+ }
+
+ /// Whole bytes, after .
+ public void Bytes(ReadOnlySpan data)
+ {
+ if (_used != 0)
+ {
+ throw new InvalidOperationException("Bytes only at a byte boundary.");
+ }
+
+ foreach (var b in data)
+ {
+ _bytes.Add(b);
+ }
+ }
+
+ public byte[] ToArray() => _used == 0 ? [.. _bytes] : throw new InvalidOperationException("Not aligned.");
+ }
+}
diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs
index ac8d073..e08db03 100644
--- a/src/Febe.Web/Api/AccountsApi.cs
+++ b/src/Febe.Web/Api/AccountsApi.cs
@@ -422,6 +422,7 @@ public static class AccountsApi
var deleted = 0;
var problems = 0;
+ var converted = 0;
var deletion = library.Deletion;
while (true)
{
@@ -436,13 +437,15 @@ public static class AccountsApi
var result = await deletion.DeleteAsync(entry.Id, DeletionMode.AllowReturn, ct).ConfigureAwait(false);
deleted += result.Found ? 1 : 0;
problems += result.FailedFiles.Count;
+ converted += result.ConvertedFiles;
}
}
await storage.Accounts.DeleteAsync(id, ct).ConfigureAwait(false);
- var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}."
+ var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}"
+ + (converted > 0 ? $" e {ItalianText.Count(converted, "file convertito", "file convertiti")}." : ".")
+ (problems > 0 ? $" {ItalianText.Count(problems, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: restano nella sua cartella." : string.Empty);
- return new RemoveAccountDto("removed", deleted, problems, message);
+ return new RemoveAccountDto("removed", deleted, problems, message, converted);
}
// ------------------------------------------------------------------------------------------ following and adding
diff --git a/src/Febe.Web/Api/ApiErrorMiddleware.cs b/src/Febe.Web/Api/ApiErrorMiddleware.cs
index f0e01fe..0d01f3f 100644
--- a/src/Febe.Web/Api/ApiErrorMiddleware.cs
+++ b/src/Febe.Web/Api/ApiErrorMiddleware.cs
@@ -39,6 +39,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
+ ApiStatusException a => (a.Status, ex.Message),
DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message),
_ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."),
};
diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs
index 6f9df0b..854375b 100644
--- a/src/Febe.Web/Api/ApiMapping.cs
+++ b/src/Febe.Web/Api/ApiMapping.cs
@@ -298,3 +298,30 @@ public sealed class NotFoundException : Exception
{
}
}
+
+/// An answer with another status and an Italian message: 409 (busy, in session), 503 (too slow).
+public sealed class ApiStatusException : Exception
+{
+ public ApiStatusException()
+ {
+ }
+
+ public ApiStatusException(string message)
+ : base(message)
+ {
+ }
+
+ public ApiStatusException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ }
+
+ public ApiStatusException(int status, string message)
+ : base(message)
+ {
+ Status = status;
+ }
+
+ /// The HTTP status (409 when not given).
+ public int Status { get; } = 409;
+}
diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs
index fe62860..301d2bf 100644
--- a/src/Febe.Web/Api/Dtos.cs
+++ b/src/Febe.Web/Api/Dtos.cs
@@ -92,7 +92,9 @@ public sealed record MediaDto(
bool Available,
string State,
bool Damaged = false,
- IReadOnlyList? Copies = null);
+ IReadOnlyList? Copies = null,
+ bool? FramesAvailable = null,
+ IReadOnlyList? Conversions = null);
/// Everything the viewer shows of an entry.
public sealed record EntryDto(
@@ -117,7 +119,8 @@ public sealed record EntryDto(
public sealed record EntryIdsRequest(IReadOnlyList Ids, string? Mode);
-public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList Problems, string Message);
+/// What «Elimina dalla libreria» did; : converted files of the library deleted too (tappa E3).
+public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList Problems, string Message, int ConvertedFiles = 0);
/// Export by keys, or by the current filter when no keys are given.
public sealed record ExportRequest(IReadOnlyList? Ids, string? Query);
@@ -222,7 +225,7 @@ public sealed record CheckNowDto(string Status, string Message, string? Token);
public sealed record RemoveAccountRequest(bool DeleteFiles);
-public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message);
+public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message, int ConvertedFiles = 0);
public sealed record ParseRequest(string Text);
diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs
index a922b45..f7ee225 100644
--- a/src/Febe.Web/Api/ExportApi.cs
+++ b/src/Febe.Web/Api/ExportApi.cs
@@ -2,6 +2,7 @@ using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
+using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebUtilities;
+using ItalianText = Febe.Core.Engine.ItalianText;
namespace Febe.Web.Api;
@@ -35,52 +37,85 @@ public static class ExportApi
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) =>
- {
- var service = await hub.GetAsync(ct).ConfigureAwait(false);
- var root = hub.RootFor(context);
- var d = SettingsApi.Deps.From(services);
- var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
- var state = ExportRoots.Evaluate(root);
- var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
- var names = await UsernamesAsync(storage, ct).ConfigureAwait(false);
- var mapped = new List(destinations.Count);
- foreach (var destination in destinations)
- {
- var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
- mapped.Add(Destination(destination, names, counts, root, clock));
- }
+ ApiHttp.Json(await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportOverviewDto));
- var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
- var active = service.ActiveRunIds;
- var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id));
- var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
- return ApiHttp.Json(
- new ExportOverviewDto(
- new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder),
- SamePost(settings.SamePost),
- mapped.FirstOrDefault(x => x.Scope == "general"),
- [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)],
- active,
- unfinished,
- new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)),
- FebeJsonContext.Default.ExportOverviewDto);
- });
-
- endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) =>
+ endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false);
- var samePost = body.SamePost?.Trim().ToLowerInvariant() switch
+ var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ var after = before;
+ if (body.SamePost is { } samePostText)
{
- "oneperaccount" => SamePostCopies.OnePerAccount,
- "oneonly" => SamePostCopies.OneOnly,
- _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
+ after = after with
+ {
+ SamePost = samePostText.Trim().ToLowerInvariant() switch
+ {
+ "oneperaccount" => SamePostCopies.OnePerAccount,
+ "oneonly" => SamePostCopies.OneOnly,
+ _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
+ },
+ };
+ }
+
+ after = after with
+ {
+ PhotoFormat = ParseFormat(body.PhotoFormat, MediaKind.Photo) ?? after.PhotoFormat,
+ VideoFormat = ParseFormat(body.VideoFormat, MediaKind.Video) ?? after.VideoFormat,
+ LibraryPhotoFormat = ParseFormat(body.LibraryPhotoFormat, MediaKind.Photo) ?? after.LibraryPhotoFormat,
+ LibraryVideoFormat = ParseFormat(body.LibraryVideoFormat, MediaKind.Video) ?? after.LibraryVideoFormat,
};
- var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
- await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false);
+ if (body.SamePost is null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null && body.ConvertExisting is null)
+ {
+ throw new BadRequestException("Niente da salvare: scegli un'impostazione.");
+ }
+
+ await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false);
+ await queue.OnSettingsChangedAsync(before, after, ct).ConfigureAwait(false);
+ var queued = 0;
+ if (body.ConvertExisting == true && after.ConvertsLibrary)
+ {
+ queued = await queue.EnqueueExistingAsync(after, ct).ConfigureAwait(false);
+ }
+
changes.Publish(new LibraryChange(clock.Now, null, "export"));
- return ApiHttp.Message(samePost == SamePostCopies.OneOnly
- ? "Fatto: lo stesso post in due account si copia una volta sola."
- : "Fatto: lo stesso post in due account si copia una volta per ciascun account.");
+ var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false);
+ return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto);
+ });
+
+ endpoints.MapGet("/api/export/library-conversion", async (IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct) =>
+ ApiHttp.Json(await ConversionAsync(storage, worker, ct).ConfigureAwait(false), FebeJsonContext.Default.LibraryConversionDto));
+
+ endpoints.MapGet("/api/export/library-conversion/preview", async (string? photo, string? video, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct) =>
+ {
+ var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ settings = settings with
+ {
+ LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat,
+ LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat,
+ };
+ var preview = settings.ConvertsLibrary ? await queue.PreviewExistingAsync(settings, ct).ConfigureAwait(false) : new LibraryConversionPreview(0, 0);
+ return ApiHttp.Json(new LibraryConversionPreviewDto(preview.Files, preview.Bytes, PreviewText(preview)), FebeJsonContext.Default.LibraryConversionPreviewDto);
+ });
+
+ endpoints.MapPost("/api/export/library-conversion/retry", async (LibraryConversionQueue queue, LibraryChanges changes, IClock clock, CancellationToken ct) =>
+ {
+ var reset = await queue.RetryFailedAsync(ct).ConfigureAwait(false);
+ changes.Publish(new LibraryChange(clock.Now, null, "export"));
+ return ApiHttp.Message(reset == 0
+ ? "Nessuna conversione da riprovare."
+ : $"{Core.Engine.ItalianText.Count(reset, "file torna", "file tornano")} in coda per la conversione.");
+ });
+
+ endpoints.MapPost("/api/export/library-conversion/pause", async (LibraryConversionQueue queue, CancellationToken ct) =>
+ {
+ await queue.SetPausedAsync(true, ct).ConfigureAwait(false);
+ return ApiHttp.Message("Conversione della libreria interrotta: i file già convertiti restano, riprendi quando vuoi.");
+ });
+
+ endpoints.MapPost("/api/export/library-conversion/resume", async (LibraryConversionQueue queue, CancellationToken ct) =>
+ {
+ await queue.SetPausedAsync(false, ct).ConfigureAwait(false);
+ return ApiHttp.Message("La conversione della libreria riprende.");
});
endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) =>
@@ -228,7 +263,7 @@ public static class ExportApi
var request = Request(body, clock);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false);
- return ApiHttp.Json(Plan(plan, hub.RootFor(context)), FebeJsonContext.Default.ExportPlanDto);
+ return ApiHttp.Json(Plan(plan, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportPlanDto);
});
endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) =>
@@ -237,7 +272,7 @@ public static class ExportApi
var request = Request(body, clock);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false);
- return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
+ return ApiHttp.Json(Job(start, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportJobDto);
});
endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
@@ -275,18 +310,25 @@ public static class ExportApi
throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
}
+ // The same form only (tappa E3, D11): a JPG copy taken again is not «già copiato» because of a whole one.
if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c =>
- c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant))
+ c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && SameForm(c, copy)))
{
throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella.");
}
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
+ // The file the copy was made from comes first, then one of the same kind.
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
- var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0];
+ var kind = copy.MediaId is { } copiedId ? (await storage.Media.GetAsync(copiedId, ct).ConfigureAwait(false))?.Kind : null;
+ var location = present
+ .Where(l => account is not null && files.Resolve(account, l.Media) is not null)
+ .OrderBy(l => l.Media.Id == copy.MediaId ? 0 : l.Media.Kind == kind ? 1 : 2)
+ .FirstOrDefault() ?? present[0];
var service = await hub.GetAsync(ct).ConfigureAwait(false);
- var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false);
+ var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt);
+ var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true, Exact: exact), ct)).ConfigureAwait(false);
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
});
@@ -382,8 +424,9 @@ public static class ExportApi
Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)),
ItemCounts(report.ByState),
report.BytesCopied,
- [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed))],
- [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]),
+ [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed, a.AsIs))],
+ [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))],
+ [.. report.Notes.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]),
FebeJsonContext.Default.ExportReportDto);
});
}
@@ -498,7 +541,9 @@ public static class ExportApi
reachable,
freeBytes,
destination.IsOrphan,
- destination.RemovedAccountUsername);
+ destination.RemovedAccountUsername,
+ destination.PhotoFormat is { } photo ? FormatName(photo) : null,
+ destination.VideoFormat is { } video ? FormatName(video) : null);
}
/// A destination with its counts, read from the database.
@@ -536,7 +581,7 @@ public static class ExportApi
counts.Failed);
}
- public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root)
+ public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root, bool frames = false)
{
ArgumentNullException.ThrowIfNull(plan);
return new ExportPlanDto(
@@ -547,7 +592,267 @@ public static class ExportApi
plan.NotExported,
plan.Missing,
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))],
- plan.HasDestination);
+ plan.HasDestination,
+ [.. plan.AsIs.Select(a => new ExportPlanAsIsDto(a.Label, a.Files))],
+ plan.Converted,
+ plan.Lossy,
+ plan.Videos,
+ plan.PhotosSkipped,
+ plan.Frames,
+ plan.OverCap,
+ PlanSummary(plan, frames));
+ }
+
+ ///
+ /// The line of «Copia in…» (tappa E3, §10.3): «312 file · 41 già copiati, saltati · circa 3 HEIC copiati come sono ·
+ /// circa 4,2 GB · con perdita»; for frames «12 fotogrammi da 4 video · le 3 foto si saltano».
+ ///
+ public static string PlanSummary(ExportPlan plan, bool frames)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ var parts = new List();
+ if (frames)
+ {
+ parts.Add($"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(plan.Videos)} video");
+ if (plan.PhotosSkipped > 0)
+ {
+ parts.Add(PhotosSkippedText(plan.PhotosSkipped));
+ }
+
+ if (plan.OverCap > 0)
+ {
+ parts.Add(ExportFrames.OverCapMessage);
+ }
+ }
+ else
+ {
+ parts.Add(ItalianText.Count(plan.Files, "file", "file"));
+ if (plan.AlreadyCopied > 0)
+ {
+ parts.Add(plan.AlreadyCopied == 1 ? "1 già copiato, saltato" : $"{ItalianText.Number(plan.AlreadyCopied)} già copiati, saltati");
+ }
+
+ foreach (var asIs in plan.AsIs.Where(a => a.Files > 0))
+ {
+ parts.Add($"circa {ItalianText.Number(asIs.Files)} {asIs.Label} {(asIs.Files == 1 ? "copiato com'è" : "copiati come sono")}");
+ }
+
+ if (plan.Bytes > 0)
+ {
+ parts.Add("circa " + ItalianText.Bytes(plan.Bytes));
+ }
+ }
+
+ if (plan.Lossy)
+ {
+ parts.Add("con perdita");
+ }
+
+ return string.Join(" · ", parts);
+ }
+
+ /// «Le 4 foto si saltano» (frames are taken from videos only).
+ public static string PhotosSkippedText(int photos) =>
+ photos == 1 ? "la foto si salta" : $"le {ItalianText.Number(photos)} foto si saltano";
+
+ /// The wire name of a format (D21): original, jpg, png, webplossless, mp4.
+ public static string FormatName(ExportFormat format) => format.ToString().ToLowerInvariant();
+
+ ///
+ /// A format of from its wire name; null for null or empty (nothing chosen). 400 for a name
+ /// that is not a format of that kind.
+ ///
+ public static ExportFormat? ParseFormat(string? text, MediaKind kind)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return null;
+ }
+
+ var name = text.Trim();
+ var format = Enum.GetValues().FirstOrDefault(f => string.Equals(FormatName(f), name, StringComparison.OrdinalIgnoreCase), (ExportFormat)(-1));
+ var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
+ if (!Enum.IsDefined(format) || !fits)
+ {
+ throw new BadRequestException(kind == MediaKind.Photo
+ ? "Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita."
+ : "Per i video si sceglie Originale o MP4.");
+ }
+
+ return format;
+ }
+
+ /// A frame format from its wire name: JPG, PNG or WEBP senza perdita; PNG when none is given (§16, domanda 35).
+ public static ExportFormat ParseFrameFormat(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return ExportFormat.Png;
+ }
+
+ var format = ParseFormat(text, MediaKind.Photo);
+ return format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless
+ ? format.Value
+ : throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.");
+ }
+
+ /// Which frames, from the page's request.
+ public static ExportFramesRequest Frames(FramesRequestDto body)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ var mode = body.Mode?.Trim().ToLowerInvariant() switch
+ {
+ "istante" or "at" => FrameMode.At,
+ "ogni" or "every" => FrameMode.Every,
+ "numero" or "count" => FrameMode.Count,
+ _ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."),
+ };
+ return new ExportFramesRequest(
+ mode,
+ mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null,
+ mode == FrameMode.Every && body.EveryMs is { } every ? TimeSpan.FromMilliseconds(every) : null,
+ mode == FrameMode.Count ? body.Count : null,
+ ParseFrameFormat(body.Format));
+ }
+
+ /// Two copy rows of the same form: variant, format and frame instant (the full identity of §4.10 without the file).
+ public static bool SameForm(ExportCopy a, ExportCopy b)
+ {
+ ArgumentNullException.ThrowIfNull(a);
+ ArgumentNullException.ThrowIfNull(b);
+ return a.Variant == b.Variant && a.Format == b.Format && a.FrameAt == b.FrameAt;
+ }
+
+ /// The wire name of a state of a conversion of the library; a failure that never converts is asIs.
+ public static string ConversionState(MediaConversion conversion)
+ {
+ ArgumentNullException.ThrowIfNull(conversion);
+ return conversion.State switch
+ {
+ MediaConversionState.Pending => "pending",
+ MediaConversionState.Converted => "converted",
+ MediaConversionState.Failed when LibraryConversionText.IsAsIs(conversion.LastError) => "asIs",
+ MediaConversionState.Failed => "failed",
+ MediaConversionState.Superseded => "superseded",
+ _ => "removed",
+ };
+ }
+
+ /// The state of the conversion of the library, for the settings and the Dashboard.
+ public static async Task ConversionAsync(IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(storage);
+ ArgumentNullException.ThrowIfNull(worker);
+ var status = await worker.StatusAsync(ct).ConfigureAwait(false);
+ var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ var parts = new List();
+ if (status.Pending > 0)
+ {
+ parts.Add("In coda " + ItalianText.Number(status.Pending));
+ }
+
+ if (status.Converted > 0)
+ {
+ parts.Add("convertiti " + ItalianText.Number(status.Converted));
+ }
+
+ if (status.Failed > 0)
+ {
+ parts.Add("non riusciti " + ItalianText.Number(status.Failed));
+ }
+
+ if (status.AsIs > 0)
+ {
+ parts.Add("non si convertono " + ItalianText.Number(status.AsIs));
+ }
+
+ var text = parts.Count == 0 ? "Nessun file convertito" : ItalianText.Capitalize(string.Join(" · ", parts));
+ if (status.Paused)
+ {
+ text = "In pausa · " + text;
+ }
+
+ return new LibraryConversionDto(status.Pending, status.Converted, status.Failed, status.AsIs, status.Paused, status.Waiting, text, settings.ConvertsLibrary);
+ }
+
+ private static string PreviewText(LibraryConversionPreview preview) => preview.Files switch
+ {
+ 0 => "Nessun file già in libreria da convertire.",
+ 1 => $"Anche quello già in libreria: l'originale occupa circa {ItalianText.Bytes(preview.Bytes)}; il convertito può occupare di più.",
+ var n => $"Anche i {ItalianText.Number(n)} già in libreria: gli originali occupano circa {ItalianText.Bytes(preview.Bytes)}; i convertiti possono occupare di più.",
+ };
+
+ private static string SettingsMessage(ExportSettings before, ExportSettings after, ExportSettingsRequest body, int queued)
+ {
+ var parts = new List();
+ if (body.SamePost is not null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null)
+ {
+ return after.SamePost == SamePostCopies.OneOnly
+ ? "Fatto: lo stesso post in due account si copia una volta sola."
+ : "Fatto: lo stesso post in due account si copia una volta per ciascun account.";
+ }
+
+ if (before.PhotoFormat != after.PhotoFormat || before.VideoFormat != after.VideoFormat)
+ {
+ parts.Add("i nuovi formati valgono per i file non ancora copiati");
+ }
+
+ if (before.ConvertsLibrary != after.ConvertsLibrary || before.LibraryPhotoFormat != after.LibraryPhotoFormat || before.LibraryVideoFormat != after.LibraryVideoFormat)
+ {
+ parts.Add(!after.ConvertsLibrary
+ ? "la conversione della libreria è spenta, i file convertiti restano dove sono"
+ : queued > 0
+ ? $"si convertono i nuovi file e {ItalianText.Count(queued, "file già in libreria", "file già in libreria")}"
+ : "si convertono i nuovi file; l'originale resta");
+ }
+ else if (queued > 0)
+ {
+ parts.Add($"{ItalianText.Count(queued, "file già in libreria entra", "file già in libreria entrano")} in coda");
+ }
+
+ return parts.Count == 0 ? "Fatto." : "Fatto: " + string.Join("; ", parts) + ".";
+ }
+
+ /// Impostazioni → Esportazione: root, destinations, settings, formats and the conversion of the library.
+ public static async Task OverviewAsync(HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(hub);
+ ArgumentNullException.ThrowIfNull(storage);
+ ArgumentNullException.ThrowIfNull(library);
+ ArgumentNullException.ThrowIfNull(clock);
+ ArgumentNullException.ThrowIfNull(services);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var root = hub.RootFor(context);
+ var d = SettingsApi.Deps.From(services);
+ var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
+ var state = ExportRoots.Evaluate(root);
+ var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
+ var names = await UsernamesAsync(storage, ct).ConfigureAwait(false);
+ var mapped = new List(destinations.Count);
+ foreach (var destination in destinations)
+ {
+ var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
+ mapped.Add(Destination(destination, names, counts, root, clock));
+ }
+
+ var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ var active = service.ActiveRunIds;
+ var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id));
+ var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
+ var worker = services.GetService(typeof(LibraryConversionWorker)) as LibraryConversionWorker;
+ return new ExportOverviewDto(
+ new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder),
+ SamePost(settings.SamePost),
+ mapped.FirstOrDefault(x => x.Scope == "general"),
+ [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)],
+ active,
+ unfinished,
+ new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders),
+ FormatName(settings.PhotoFormat),
+ FormatName(settings.VideoFormat),
+ FormatName(settings.LibraryPhotoFormat),
+ FormatName(settings.LibraryVideoFormat),
+ worker is null ? null : await ConversionAsync(storage, worker, ct).ConfigureAwait(false));
}
/// The request of a «Copia in…»: exactly one selection.
@@ -581,7 +886,16 @@ public static class ExportApi
selection = new ExportSelection.Account(body.AccountId!.Value);
}
- return new ExportJobRequest(selection, body.CopyAgain);
+ var photo = ParseFormat(body.PhotoFormat, MediaKind.Photo);
+ var video = ParseFormat(body.VideoFormat, MediaKind.Video);
+ var formats = photo is null && video is null ? null : new ExportFormatChoice(photo, video);
+ var frames = body.Frames is { } f ? Frames(f) : null;
+ if (frames is not null && formats is not null)
+ {
+ throw new BadRequestException("I fotogrammi non si chiedono insieme ai formati delle copie.");
+ }
+
+ return new ExportJobRequest(selection, body.CopyAgain, Formats: formats, Frames: frames);
}
// ---------------------------------------------------------------------------------------------- helpers
@@ -630,7 +944,13 @@ public static class ExportApi
Clean(body.HighlightNamingScheme),
Clean(body.ProfileNamingScheme),
body.Automatic,
- body.OnlyNew);
+ body.OnlyNew,
+ DestinationFormat(body.PhotoFormat, MediaKind.Photo),
+ DestinationFormat(body.VideoFormat, MediaKind.Video));
+
+ /// A destination's format: null, empty or general is «Come le impostazioni generali».
+ private static ExportFormat? DestinationFormat(string? text, MediaKind kind) =>
+ string.Equals(text?.Trim(), "general", StringComparison.OrdinalIgnoreCase) ? null : ParseFormat(text, kind);
private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
@@ -646,9 +966,9 @@ public static class ExportApi
_ => "finished",
};
- private static ExportJobDto Job(ExportStart start, ExportRootOptions root) => new(
+ private static ExportJobDto Job(ExportStart start, ExportRootOptions root, bool frames = false) => new(
[.. start.Runs.Select(r => r.Id)],
- Plan(start.Plan, root),
+ 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."
: "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione.");
diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs
index 56b1111..ac732ef 100644
--- a/src/Febe.Web/Api/ExportDtos.cs
+++ b/src/Febe.Web/Api/ExportDtos.cs
@@ -43,11 +43,16 @@ public sealed record ExportDestinationDto(
bool? Reachable = null,
long? FreeBytes = null,
bool Orphan = false,
- string? FormerUsername = null);
+ string? FormerUsername = null,
+ string? PhotoFormat = null,
+ string? VideoFormat = null);
///
/// GET /api/export: Impostazioni → Esportazione and the notice of the Dashboard. :
/// onePerAccount or oneOnly. : interrupted or paused jobs («Riprendi»).
+/// Formats (tappa E3) on the wire: original, jpg, png, webplossless, mp4; the
+/// library ones are original while the conversion of the library is off. :
+/// the state of that conversion.
///
public sealed record ExportOverviewDto(
ExportRootDto Root,
@@ -56,10 +61,44 @@ public sealed record ExportOverviewDto(
IReadOnlyList Own,
IReadOnlyList ActiveRunIds,
int UnfinishedRuns,
- ExportSchemesDto Library);
+ ExportSchemesDto Library,
+ string PhotoFormat = "original",
+ string VideoFormat = "original",
+ string LibraryPhotoFormat = "original",
+ string LibraryVideoFormat = "original",
+ LibraryConversionDto? LibraryConversion = null);
-/// PUT /api/export/settings: «Lo stesso post in due account», onePerAccount or oneOnly.
-public sealed record ExportSettingsRequest(string SamePost);
+///
+/// The conversion of the library (tappa E3, spec §4.10): files in the queue, converted, failed («Riprova»), that never
+/// convert (: «non si convertono»), «In pausa», and why it waits (Italian, null when it does
+/// not): an import, a copy or a rebuild at work, an engine session, low space. : the status line
+/// («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»). : a library format is
+/// chosen.
+///
+public sealed record LibraryConversionDto(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, string Text, bool On);
+
+///
+/// PUT /api/export/settings, every field optional (null keeps it): «Lo stesso post in due account»
+/// (onePerAccount or oneOnly), the formats of the copies and of the library (wire names).
+/// : the answer «Anche i N già in libreria» when a library format is turned on.
+///
+public sealed record ExportSettingsRequest(
+ string? SamePost = null,
+ string? PhotoFormat = null,
+ string? VideoFormat = null,
+ string? LibraryPhotoFormat = null,
+ string? LibraryVideoFormat = null,
+ bool? ConvertExisting = null);
+
+/// What PUT /api/export/settings did: a message, the overview after the change, the files queued.
+public sealed record ExportSettingsSavedDto(string Message, ExportOverviewDto Overview, int Queued = 0);
+
+///
+/// «Converti anche i N file già in libreria?»: that would enter the queue, the bytes of their
+/// originals («circa») and the line of the question («gli originali occupano circa 3,1 GB; i convertiti possono occupare
+/// di più»).
+///
+public sealed record LibraryConversionPreviewDto(int Files, long Bytes, string Text);
/// Docker: the subfolders of a folder of /esporta. is "" for the root.
public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList Folders);
@@ -88,7 +127,9 @@ public sealed record ExportDestinationRequest(
string? HighlightNamingScheme,
string? ProfileNamingScheme,
bool Automatic = false,
- bool OnlyNew = true);
+ bool OnlyNew = true,
+ string? PhotoFormat = null,
+ string? VideoFormat = null);
/// A saved destination (a change of folder gives a new id) and the warnings of its schemes.
public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList Warnings);
@@ -97,7 +138,10 @@ public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination,
/// What a «Copia in…» copies: exactly one of (files of «Tutte le foto» or the viewer),
/// (a grouped selection), (the filter of the Libreria, as its query
/// string, with grouped or files) or (every file of
-/// the account). : «Copia di nuovo anche i tolti o superati».
+/// the account). : «Copia di nuovo anche i tolti o superati». Tappa E3:
+/// / override the destination's for this request only
+/// (null: as the destination); makes it a frames job («Fotogrammi…» → «Nella cartella delle
+/// copie»), without formats.
///
public sealed record CopyJobRequestDto(
IReadOnlyList? MediaIds,
@@ -105,7 +149,20 @@ public sealed record CopyJobRequestDto(
string? Query,
string? Mode,
long? AccountId,
- bool CopyAgain = false);
+ bool CopyAgain = false,
+ string? PhotoFormat = null,
+ string? VideoFormat = null,
+ FramesRequestDto? Frames = null);
+
+///
+/// Which frames (spec §4.10 «Fotogrammi»): istante (at ),
+/// ogni (every , at least 100) or numero ( in all, 1 to
+/// 1.000); jpg, png (the default) or webplossless.
+///
+public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null);
+
+/// Files of a plan copied as they are, of one kind («3 HEIC copiati come sono»).
+public sealed record ExportPlanAsIsDto(string Label, int Files);
/// A destination of a plan. : why it cannot be written now (paused, not reachable).
public sealed record ExportPlanDestinationDto(
@@ -123,7 +180,12 @@ public sealed record ExportPlanDestinationDto(
///
/// The summary of «Copia in…» (spec §10.3). /: what will be written
/// (with «Copia di nuovo» the tolti/superati too). : of accounts that are not exported
-/// (switch off, no destination, type not taken). : not in the library.
+/// (switch off, no destination, type not taken). : not in the library. Tappa E3:
+/// files predicted copied as they are («circa»), predicted
+/// converted, «con perdita»; a frames job: ,
+/// , and (videos over 1.000
+/// frames: the job is refused). : the line of the dialog («312 file · 41 già copiati, saltati ·
+/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»).
///
public sealed record ExportPlanDto(
int Files,
@@ -133,7 +195,15 @@ public sealed record ExportPlanDto(
int NotExported,
int Missing,
IReadOnlyList Destinations,
- bool HasDestination = true);
+ bool HasDestination = true,
+ IReadOnlyList? AsIs = null,
+ int Converted = 0,
+ bool Lossy = false,
+ int Videos = 0,
+ int PhotosSkipped = 0,
+ int Frames = 0,
+ int OverCap = 0,
+ string? Summary = null);
/// The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.
public sealed record ExportJobDto(IReadOnlyList RunIds, ExportPlanDto Plan, string Message);
@@ -174,24 +244,33 @@ public sealed record ExportRunDto(
int Done,
bool Running = false);
-/// The files of one account in a job ( counts written and adopted files).
-public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
+///
+/// The files of one account in a job ( counts written and adopted files).
+/// : files copied as they are, by kind («HEIC» → 3).
+///
+public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed, IReadOnlyDictionary? AsIs = null);
/// A file of the report that needs a look, with its reason in Italian.
public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text);
-/// The report of a job (at most 200 problems).
+///
+/// The report of a job (at most 200 problems). (tappa E3): files copied or adopted with a note
+/// (what a conversion could not keep, a file copied as it is), at most 200.
+///
public sealed record ExportReportDto(
ExportRunDto Run,
IReadOnlyDictionary ByState,
long BytesCopied,
IReadOnlyList Accounts,
- IReadOnlyList Problems);
+ IReadOnlyList Problems,
+ IReadOnlyList? Notes = null);
///
/// A copy of a file of the viewer (spec §4.6, §4.10). : copied, removed, superseded, failed;
-/// : whole (tappa E2 copies originals only). : with «Una copia
-/// sola», the account it was copied for when it is another one. : «Copia di nuovo».
+/// : whole, converted or frame; : the wire name of a converted copy or
+/// of a frame (null for a whole one); and («0:01,25») for a
+/// frame. : with «Una copia sola», the account it was copied for when it is another one.
+/// : «Copia di nuovo» of that same form. : why it failed.
///
public sealed record MediaCopyDto(
long CopyId,
@@ -203,7 +282,17 @@ public sealed record MediaCopyDto(
long? FrameAtMs,
LocalTimeDto At,
string? ForAccount,
- bool CanCopyAgain);
+ bool CanCopyAgain,
+ string? FrameLabel = null,
+ string? Notes = null);
+
+///
+/// A converted file of the library next to its original (tappa E3, spec §4.10): (wire name),
+/// pending, converted, failed, asIs («non si converte»),
+/// superseded or removed, its size, and : what was not kept, or why it failed or
+/// does not convert. : the file is on disk («Scarica», «Mostra nella cartella»).
+///
+public sealed record MediaConversionDto(long Id, string Format, string State, long? Bytes, string? Notes, bool Available, string? FileName);
///
/// «Copie esterne» of the account card. : the effective one (its own folder, else the
@@ -218,3 +307,51 @@ public sealed record ExportAccountDto(
int NotCopied,
int RemovedOrSuperseded,
int Failed);
+
+// ---------------------------------------------------------------------------------------------- frames (tappa E3)
+
+///
+/// GET /api/media/{id}/frames/info: whether frames can be taken from the video (:
+/// «Fotogramma non disponibile per questo video»), its length and its size as shown (rotation applied).
+///
+public sealed record FrameInfoDto(bool Available, string? Unavailable, long DurationMs, int Width, int Height, bool HasAudio);
+
+///
+/// One instant of a frames request: the one asked for, the one really shown (the frame's identity, ms rounded up), its
+/// label («0:01,25») and the suffix of its file name (_t0m01s250, _f001).
+///
+public sealed record FrameInstantDto(int Index, long RequestedMs, long ActualMs, string Label, string Suffix);
+
+///
+/// GET /api/media/{id}/frames/instants: the instants of a mode for one video (at most 1.000). :
+/// how many it asks; : why none is given (over 1.000, not available).
+///
+public sealed record FrameInstantsDto(long DurationMs, int Total, bool OverCap, string? Problem, IReadOnlyList Instants);
+
+///
+/// The frames of a selection («Fotogrammi…» from the selection bars): exactly one of ,
+/// (every video of those entries) or with ,
+/// and which frames.
+///
+public sealed record FramesSelectionRequest(IReadOnlyList? MediaIds, IReadOnlyList? EntryIds, string? Query, string? Mode, FramesRequestDto? Frames);
+
+///
+/// POST /api/frames/plan: what «Scarica» would give. : videos without frames (or
+/// not on disk); : videos over 1.000 frames; : more than
+/// 500 frames («Nella cartella delle copie»); : more than 20 (only outside engine sessions
+/// and other long work). : why «Scarica» cannot run now; : the line
+/// of the dialog («12 fotogrammi da 4 video · le 3 foto si saltano»).
+///
+public sealed record FramesPlanDto(int Videos, int PhotosSkipped, int NotAvailable, int Frames, int OverCap, bool TooManyToDownload, bool NeedsQuiet, string? Problem, string Summary);
+
+/// A download of frames ready: open once within 5 minutes.
+public sealed record FramesTokenDto(string Token, int Frames, string Url);
+
+/// A converted file of the library («Mostra nella cartella»).
+public sealed record ConversionActionRequest(long ConversionId);
+
+///
+/// What «Elimina dalla libreria» would remove (tappa E3, spec §4.6): the entries, their files and the converted files of
+/// the library made from them («elimino gli elementi interi, 9 file e 2 file convertiti»).
+///
+public sealed record EntryDeletionPreviewDto(int Entries, int Files, int ConvertedFiles);
diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs
index afb1c94..8049afc 100644
--- a/src/Febe.Web/Api/FebeJsonContext.cs
+++ b/src/Febe.Web/Api/FebeJsonContext.cs
@@ -105,4 +105,14 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(IReadOnlyList))]
[JsonSerializable(typeof(ExportReportDto))]
[JsonSerializable(typeof(ExportAccountDto))]
+[JsonSerializable(typeof(ExportSettingsSavedDto))]
+[JsonSerializable(typeof(LibraryConversionDto))]
+[JsonSerializable(typeof(LibraryConversionPreviewDto))]
+[JsonSerializable(typeof(FrameInfoDto))]
+[JsonSerializable(typeof(FrameInstantsDto))]
+[JsonSerializable(typeof(FramesSelectionRequest))]
+[JsonSerializable(typeof(FramesPlanDto))]
+[JsonSerializable(typeof(FramesTokenDto))]
+[JsonSerializable(typeof(ConversionActionRequest))]
+[JsonSerializable(typeof(EntryDeletionPreviewDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
diff --git a/src/Febe.Web/Api/FramesApi.cs b/src/Febe.Web/Api/FramesApi.cs
new file mode 100644
index 0000000..ccd47aa
--- /dev/null
+++ b/src/Febe.Web/Api/FramesApi.cs
@@ -0,0 +1,424 @@
+using System.Globalization;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Core.Library.Conversion;
+using Febe.Core.Storage;
+using Febe.Web.Export;
+using Febe.Web.Library;
+using Febe.Web.Native;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.AspNetCore.StaticFiles;
+using ItalianText = Febe.Core.Engine.ItalianText;
+
+namespace Febe.Web.Api;
+
+///
+/// Frames of videos and the converted files of the library (spec §4.10, tappa E3): what a video allows, a frame at an
+/// instant (previews of the dialog «Fotogrammi…» and «Scarica» of one frame), the instants of a mode, the plan of
+/// «Scarica» for a selection and its download (one image, or a zip made while it is sent), and the files of the
+/// conversion of the library («Scarica», «Mostra nella cartella»). Frames to a folder of the copies go through
+/// /api/export/plan and /start with frames. Nothing here writes a file.
+///
+public static class FramesApi
+{
+ private static readonly FileExtensionContentTypeProvider ContentTypes = new();
+
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ ArgumentNullException.ThrowIfNull(endpoints);
+
+ endpoints.MapGet("/api/media/{id:long}/frames/info", async (long id, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
+ {
+ var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
+ var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false);
+ return ApiHttp.Json(
+ new FrameInfoDto(info.Available, info.Unavailable, (long)info.Duration.TotalMilliseconds, info.Width, info.Height, info.HasAudio),
+ FebeJsonContext.Default.FrameInfoDto);
+ });
+
+ endpoints.MapGet("/api/media/{id:long}/frame", async (long id, long? at, string? format, int? max, string? download, HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
+ {
+ var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
+ 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 instant = TimeSpan.FromMilliseconds(Math.Max(0, at ?? 0));
+ var frame = await frames.FrameAsync(video.Path, video.Media.Sha256, instant, chosen, side, ct).ConfigureAwait(false);
+ if (download is "1" or "true")
+ {
+ context.Response.Headers.CacheControl = "private, no-cache";
+ var name = FrameService.FileName(Stem(video.Media), FrameMode.At, frame.Actual, 0, 1, chosen);
+ return Results.File(frame.Data, frame.ContentType, name);
+ }
+
+ // The same file, instant, size and format always give the same picture.
+ context.Response.Headers.CacheControl = "private, max-age=600";
+ return Results.File(frame.Data, frame.ContentType);
+ });
+
+ endpoints.MapGet("/api/media/{id:long}/frames/instants", async (long id, string? mode, long? at, long? every, int? count, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
+ {
+ var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
+ var request = ExportApi.Frames(new FramesRequestDto(mode ?? "numero", at, every, count, "png"));
+ 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;
+ if (!info.Available)
+ {
+ return ApiHttp.Json(new FrameInstantsDto(durationMs, 0, false, info.Unavailable ?? VideoFrameReader.NotAvailableMessage, []), FebeJsonContext.Default.FrameInstantsDto);
+ }
+
+ var total = ExportFrames.FrameCount(info.Duration, request);
+ if (total > ExportFrames.MaxPerVideo)
+ {
+ return ApiHttp.Json(new FrameInstantsDto(durationMs, (int)Math.Min(total, int.MaxValue), true, ExportFrames.OverCapMessage, []), FebeJsonContext.Default.FrameInstantsDto);
+ }
+
+ var (_, targets) = await frames.LocateAsync(video.Path, video.Media.Sha256, request, ct).ConfigureAwait(false);
+ var list = targets.Select(t => new FrameInstantDto(
+ t.Index,
+ (long)t.Requested.TotalMilliseconds,
+ ExportFrames.ActualMs(t.Actual),
+ ExportFrames.Label(t.Actual),
+ ExportFrames.Suffix(request.Mode, t.Actual, t.Index, targets.Count))).ToList();
+ return ApiHttp.Json(new FrameInstantsDto(durationMs, list.Count, false, null, list), FebeJsonContext.Default.FrameInstantsDto);
+ });
+
+ endpoints.MapPost("/api/frames/plan", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false);
+ var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false);
+ var problem = Problem(plan, gate, session);
+ return ApiHttp.Json(
+ new FramesPlanDto(plan.VideoCount, plan.Photos, plan.NotAvailable, plan.Frames, plan.OverCap, plan.Frames > FrameService.MaxDownload, plan.Frames > FrameService.MaxAnyTime, problem, Summary(plan)),
+ FebeJsonContext.Default.FramesPlanDto);
+ });
+
+ endpoints.MapPost("/api/frames/download-token", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false);
+ var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false);
+ if (plan.Frames == 0)
+ {
+ throw new BadRequestException(plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText);
+ }
+
+ if (plan.Frames > FrameService.MaxDownload)
+ {
+ throw new BadRequestException(FrameService.TooManyText);
+ }
+
+ if (Problem(plan, gate, session) is { } problem)
+ {
+ throw new ApiStatusException(409, problem);
+ }
+
+ var token = frames.Register(new FrameDownloadPlan(plan.Request.Mode, plan.Request.Format, plan.Videos));
+ return ApiHttp.Json(new FramesTokenDto(token, plan.Frames, "/api/frames/download/" + token), FebeJsonContext.Default.FramesTokenDto);
+ });
+
+ endpoints.MapGet("/api/frames/download/{token}", async (string token, HttpContext context, IFebeStorage storage, FebeLibrary library, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock) =>
+ {
+ var plan = frames.Take(token) ?? throw new NotFoundException("Questo scaricamento non vale più: scegli di nuovo «Scarica».");
+ var ct = context.RequestAborted;
+ if (plan.Frames == 1)
+ {
+ var video = plan.Videos.First(v => v.Instants.Count > 0);
+ var one = await frames.FrameAsync(video.Path, null, video.Instants[0], plan.Format, null, ct).ConfigureAwait(false);
+ var name = FrameService.FileName(video.Stem, plan.Mode, one.Actual, 0, video.Instants.Count, plan.Format);
+ context.Response.Headers.CacheControl = "private, no-cache";
+ await Results.File(one.Data, one.ContentType, name).ExecuteAsync(context).ConfigureAwait(false);
+ return;
+ }
+
+ IDisposable? lease = null;
+ if (plan.Frames > FrameService.MaxAnyTime)
+ {
+ if (session.InSession)
+ {
+ throw new ApiStatusException(409, FrameService.SessionText);
+ }
+
+ if (!gate.TryEnter(LongWorkKind.FrameDownload, out lease, out var busy))
+ {
+ throw new ApiStatusException(409, LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy ?? LongWorkKind.FrameDownload));
+ }
+ }
+
+ try
+ {
+ var publication = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).SetFileTimeToPublication;
+ context.Response.ContentType = "application/zip";
+ context.Response.Headers.CacheControl = "private, no-cache";
+ context.Response.Headers.ContentDisposition = $"attachment; filename=\"febe-fotogrammi-{FrameService.Day(clock.Now, clock.LocalZone)}.zip\"";
+ await context.Response.StartAsync(ct).ConfigureAwait(false);
+ try
+ {
+ await frames.WriteZipAsync(context.Response.Body, plan, publication, ct).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is OperationCanceledException or IOException)
+ {
+ // The page went away, or stopped reading: the zip is left unfinished, so the browser says it failed.
+ context.Abort();
+ }
+ }
+ finally
+ {
+ lease?.Dispose();
+ }
+ });
+
+ endpoints.MapGet("/api/conversions/{id:long}/file", async (long id, string? download, HttpContext context, IFebeStorage storage, IConversionFileResolver files, CancellationToken ct) =>
+ {
+ var path = await ConversionPathAsync(storage, files, id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Il file convertito non è sul disco.");
+ if (!ContentTypes.TryGetContentType(path, out var type))
+ {
+ type = "application/octet-stream";
+ }
+
+ context.Response.Headers.CacheControl = "private, no-cache";
+ return download is "1" or "true"
+ ? Results.File(path, type, Path.GetFileName(path), enableRangeProcessing: true)
+ : Results.File(path, type, enableRangeProcessing: true);
+ });
+
+ endpoints.MapPost("/api/conversions/show-in-folder", async (HttpContext context, IFebeStorage storage, IConversionFileResolver files, INativeShell shell, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConversionActionRequest).ConfigureAwait(false);
+ var path = await ConversionPathAsync(storage, files, body.ConversionId, ct).ConfigureAwait(false)
+ ?? throw new NotFoundException("Il file convertito non è sul disco: forse è stato spostato o cancellato fuori da Febe.");
+ if (!await shell.ShowInFolderAsync(path, ct).ConfigureAwait(false))
+ {
+ throw new BadRequestException("Qui non si può aprire la cartella: usa «Scarica».");
+ }
+
+ return ApiHttp.Message("Cartella aperta.");
+ });
+ }
+
+ /// The rows of the converted files of one library file for the viewer (tappa E3, §16 domanda 30).
+ public static IReadOnlyList Conversions(IConversionFileResolver files, Account account, IEnumerable rows)
+ {
+ ArgumentNullException.ThrowIfNull(files);
+ ArgumentNullException.ThrowIfNull(account);
+ ArgumentNullException.ThrowIfNull(rows);
+ return [.. rows
+ .Where(r => r.State != MediaConversionState.Removed)
+ .Select(r =>
+ {
+ var path = files.Resolve(account, r);
+ return new MediaConversionDto(
+ r.Id,
+ ExportApi.FormatName(r.Format),
+ ExportApi.ConversionState(r),
+ r.Bytes,
+ LibraryConversionText.Note(r.LastError),
+ path is not null,
+ r.RelativePath is { } relative ? Path.GetFileName(LibraryLayout.ToPlatform(relative)) : null);
+ })];
+ }
+
+ // ---------------------------------------------------------------------------------------------- selection
+
+ /// What «Scarica» would give for a selection: the videos with their instants, and what is left out.
+ /// Videos of the selection (with frames or not).
+ /// Frames in all (from the lengths of the database when the videos were not opened).
+ private sealed record FramesSelection(ExportFramesRequest Request, List Videos, int VideoCount, int Photos, int NotAvailable, int OverCap, int Frames);
+
+ private static async Task 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.");
+ 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);
+
+ // The present videos of the selection, in media order; photos are counted and skipped.
+ var candidates = new List();
+ var photos = 0;
+ var missing = 0;
+ long after = 0;
+ while (true)
+ {
+ var page = await storage.Exports.ListCandidatesAsync(selection, after, 500, ct).ConfigureAwait(false);
+ if (page.Count == 0)
+ {
+ break;
+ }
+
+ after = page[^1].MediaId;
+ foreach (var c in page)
+ {
+ if (c.MediaKind != MediaKind.Video)
+ {
+ photos++;
+ }
+ else if (!EntryStateRules.IsPresent(c.State) || c.RelativePath is null || !accounts.ContainsKey(c.AccountId))
+ {
+ missing++;
+ }
+ else
+ {
+ candidates.Add(c);
+ }
+ }
+ }
+
+ // Few enough to download: each video is opened (from the cache when it was seen) for its length and whether
+ // frames can be taken; otherwise the lengths of the database are enough to say «scegli la cartella delle copie».
+ var probe = candidates.Count <= FrameService.MaxDownload;
+ var videos = new List();
+ var notAvailable = missing;
+ var overCap = 0;
+ var unprobedFrames = 0L;
+ foreach (var c in candidates)
+ {
+ var account = accounts[c.AccountId];
+ TimeSpan duration;
+ string? path = null;
+ if (probe)
+ {
+ var media = await storage.Media.GetAsync(c.MediaId, ct).ConfigureAwait(false);
+ path = media is null ? null : files.Resolve(account, media);
+ if (path is null)
+ {
+ notAvailable++;
+ continue;
+ }
+
+ var info = await frames.InfoAsync(path, c.Sha256, ct).ConfigureAwait(false);
+ if (!info.Available)
+ {
+ notAvailable++;
+ continue;
+ }
+
+ duration = info.Duration;
+ }
+ else
+ {
+ duration = c.Duration ?? TimeSpan.Zero;
+ }
+
+ var count = ExportFrames.FrameCount(duration, request);
+ if (count > ExportFrames.MaxPerVideo)
+ {
+ overCap++;
+ continue;
+ }
+
+ if (!probe)
+ {
+ unprobedFrames += count;
+ continue;
+ }
+
+ var entry = await storage.Entries.GetAsync(c.EntryId, ct).ConfigureAwait(false);
+ videos.Add(new FrameDownloadVideo(
+ account.Username,
+ path!,
+ Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(c.RelativePath!)),
+ ExportFrames.Instants(duration, request),
+ entry?.PublishedAt ?? clock.Now));
+ }
+
+ var total = probe ? videos.Sum(v => v.Instants.Count) : (int)Math.Min(unprobedFrames, int.MaxValue);
+ return new FramesSelection(request, videos, candidates.Count + missing, photos, notAvailable, overCap, total);
+ }
+
+ /// Why «Scarica» cannot run now; null when it can.
+ private static string? Problem(FramesSelection plan, LongWorkGate gate, IEngineSessionState session)
+ {
+ if (plan.Frames == 0)
+ {
+ return plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText;
+ }
+
+ if (plan.Frames > FrameService.MaxDownload)
+ {
+ return FrameService.TooManyText;
+ }
+
+ if (plan.Frames > FrameService.MaxAnyTime)
+ {
+ if (session.InSession)
+ {
+ return FrameService.SessionText;
+ }
+
+ if (gate.Busy is { } busy)
+ {
+ return LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy);
+ }
+ }
+
+ return null;
+ }
+
+ /// «12 fotogrammi da 4 video · le 3 foto si saltano · 3 video senza fotogrammi».
+ private static string Summary(FramesSelection plan)
+ {
+ var withFrames = plan.VideoCount - plan.NotAvailable - plan.OverCap;
+ var parts = new List
+ {
+ withFrames > 0
+ ? $"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(withFrames)} video"
+ : ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi"),
+ };
+ if (plan.Photos > 0)
+ {
+ parts.Add(ExportApi.PhotosSkippedText(plan.Photos));
+ }
+
+ if (plan.NotAvailable > 0)
+ {
+ parts.Add(plan.NotAvailable == 1 ? "1 video senza fotogrammi" : $"{ItalianText.Number(plan.NotAvailable)} video senza fotogrammi");
+ }
+
+ if (plan.OverCap > 0)
+ {
+ parts.Add(plan.OverCap == 1 ? "1 video oltre 1.000 fotogrammi" : $"{ItalianText.Number(plan.OverCap)} video oltre 1.000 fotogrammi");
+ }
+
+ return string.Join(" · ", parts);
+ }
+
+ // ---------------------------------------------------------------------------------------------- helpers
+
+ private sealed record VideoFile(Account Account, Media Media, string Path);
+
+ /// A present video of the library on disk; 404 otherwise.
+ private static async Task 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)
+ {
+ throw new BadRequestException("I fotogrammi si prendono solo dai video.");
+ }
+
+ var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
+ var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
+ var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco.");
+ return new VideoFile(account, media, path);
+ }
+
+ private static string Stem(Media media) =>
+ media.RelativePath is { } relative ? Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(relative)) : "video-" + media.Id.ToString(CultureInfo.InvariantCulture);
+
+ /// The file of a Converted or Superseded conversion of a present account, or null.
+ private static async Task ConversionPathAsync(IFebeStorage storage, IConversionFileResolver files, long id, CancellationToken ct)
+ {
+ var conversion = await storage.Conversions.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Conversione non trovata.");
+ if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded))
+ {
+ throw new NotFoundException("Questa conversione non ha un file.");
+ }
+
+ var media = await storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
+ var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
+ var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
+ return files.Resolve(account, conversion);
+ }
+}
diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs
index 1e2bee4..30afcda 100644
--- a/src/Febe.Web/Api/LibraryApi.cs
+++ b/src/Febe.Web/Api/LibraryApi.cs
@@ -5,6 +5,7 @@ using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Storage;
+using Febe.Web.Export;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
@@ -136,8 +137,8 @@ public static class LibraryApi
return ApiHttp.Message("Cartella aperta.");
});
- endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) =>
- ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
+ endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, FrameService frames, IConversionFileResolver conversions, CancellationToken ct) =>
+ ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct, frames, conversions).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) =>
{
@@ -165,12 +166,43 @@ public static class LibraryApi
var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false);
var deleted = results.Count(r => r.Found);
var removed = results.Sum(r => r.DeletedFiles.Count);
+ var converted = results.Sum(r => r.ConvertedFiles);
var problems = results.SelectMany(r => r.FailedFiles).ToList();
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria")
+ + (converted > 0 ? $", con {Core.Engine.ItalianText.Count(converted, "file convertito", "file convertiti")}" : string.Empty)
+ (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.")
+ (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty);
- return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message), FebeJsonContext.Default.DeleteResultDto);
+ return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message, converted), FebeJsonContext.Default.DeleteResultDto);
+ });
+
+ // What «Elimina dalla libreria» would remove (tappa E3): the confirmation also counts the converted files.
+ endpoints.MapPost("/api/entries/delete-preview", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.EntryIdsRequest).ConfigureAwait(false);
+ if (body.Ids.Count > 5000)
+ {
+ throw new BadRequestException("Troppi elementi in una richiesta.");
+ }
+
+ var entries = 0;
+ var files = 0;
+ var converted = 0;
+ foreach (var id in body.Ids.Distinct())
+ {
+ var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false);
+ if (stored is null)
+ {
+ continue;
+ }
+
+ entries++;
+ files += stored.Media.Count(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State));
+ converted += (await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false))
+ .Count(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null);
+ }
+
+ return ApiHttp.Json(new EntryDeletionPreviewDto(entries, files, converted), FebeJsonContext.Default.EntryDeletionPreviewDto);
});
endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) =>
@@ -220,7 +252,12 @@ public static class LibraryApi
tile.FilePosition);
}
- public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
+ ///
+ /// Everything the viewer shows of an entry. With , a video says whether frames can be taken
+ /// (from the cache by SHA-256, else probed within a short time: null when it takes longer); with
+ /// , each file lists its converted files of the library (tappa E3).
+ ///
+ public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct, FrameService? frames = null, IConversionFileResolver? conversions = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(files);
@@ -236,6 +273,7 @@ public static class LibraryApi
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
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);
var media = new List(stored.Media.Count);
foreach (var m in stored.Media)
{
@@ -263,7 +301,9 @@ public static class LibraryApi
path is not null,
ApiMapping.State(m.State),
damaged,
- copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false)));
+ 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))));
}
return new EntryDto(
@@ -311,9 +351,14 @@ public static class LibraryApi
var tile = tiles[i];
if (tile.FilePosition is not null)
{
- if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied)
+ if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark))
{
- list[i] = list[i] with { Copies = "copied" };
+ list[i] = mark switch
+ {
+ ExportMark.Copied => list[i] with { Copies = "copied" },
+ ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" },
+ _ => list[i],
+ };
}
}
else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies))
@@ -322,6 +367,7 @@ public static class LibraryApi
{
ExportMark.Copied => list[i] with { Copies = "copied" },
ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due },
+ ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" },
_ => list[i],
};
}
@@ -402,7 +448,7 @@ public static class LibraryApi
&& !destination.IsRetired
&& Enabled
&& Effective?.Id == destination.Id
- && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant);
+ && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && ExportApi.SameForm(c, copy));
shown.Add(new MediaCopyDto(
copy.Id,
ExportDestinations.Label(destination),
@@ -415,10 +461,12 @@ public static class LibraryApi
_ => "frame",
},
copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(),
- copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null,
+ copy.FrameAt is { } frame ? ExportFrames.ActualMs(frame) : null,
ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone),
own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null,
- canCopyAgain));
+ canCopyAgain,
+ copy.FrameAt is { } frameAt ? ExportFrames.Label(frameAt) : null,
+ copy.State == ExportCopyState.Failed ? copy.LastError : null));
if (shown.Count == MaxShown)
{
break;
@@ -436,6 +484,30 @@ public static class LibraryApi
/// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole.
/// The file is only read, never touched (rule 12).
///
+ private static readonly TimeSpan FramesProbeTime = TimeSpan.FromSeconds(3);
+
+ /// Whether «Fotogramma» works on a video on disk; null for a photo, a missing file or a slow probe.
+ private static async Task FramesAvailableAsync(FrameService? frames, Media media, string? path, CancellationToken ct)
+ {
+ if (frames is null || media.Kind != MediaKind.Video || path is null)
+ {
+ return null;
+ }
+
+ try
+ {
+ return (await frames.InfoAsync(path, media.Sha256, ct).WaitAsync(FramesProbeTime, ct).ConfigureAwait(false)).Available;
+ }
+ catch (TimeoutException)
+ {
+ return null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+
private static async Task IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs
index 87555f5..1bb9b53 100644
--- a/src/Febe.Web/Demo/DemoEngine.cs
+++ b/src/Febe.Web/Demo/DemoEngine.cs
@@ -390,12 +390,28 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
-/// Files of the demo: the shared sample pictures. Videos have only their cover.
+/// Files of the demo: the shared sample pictures, and one short video for every video (tappa E3).
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
{
public string? Resolve(Account account, Media media)
{
ArgumentNullException.ThrowIfNull(media);
- return media.Kind == MediaKind.Photo && media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null;
+ return media.Kind switch
+ {
+ MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null,
+ MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null,
+ _ => null,
+ };
+ }
+}
+
+/// The converted files of the demo's library: the rows seeded (tappa E3).
+public sealed class DemoConversionFileResolver(DemoWorld world) : IConversionFileResolver
+{
+ public string? Resolve(Account account, MediaConversion conversion)
+ {
+ ArgumentNullException.ThrowIfNull(conversion);
+ return conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded
+ && world.ConversionFiles.TryGetValue(conversion.Id, out var path) && File.Exists(path) ? path : null;
}
}
diff --git a/src/Febe.Web/Demo/DemoExport.cs b/src/Febe.Web/Demo/DemoExport.cs
index 215d677..6582ad2 100644
--- a/src/Febe.Web/Demo/DemoExport.cs
+++ b/src/Febe.Web/Demo/DemoExport.cs
@@ -1,4 +1,6 @@
+using System.Security.Cryptography;
using Febe.Core.Abstractions;
+using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
@@ -11,7 +13,8 @@ namespace Febe.Web.Demo;
/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder
/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its
/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore»,
-/// and a job left «interrotto» for the Dashboard. Everything lives in the demo's temporary folder, whose «esporta» is
+/// and a job left «interrotto» for the Dashboard; tappa E3 adds a copy converted to PNG, a frame of a video and two
+/// conversions of the library («Convertito», «Non si converte»). Everything lives in the demo's temporary folder, whose «esporta» is
/// the demo's /esporta: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
///
public static class DemoExport
@@ -117,6 +120,179 @@ public static class DemoExport
}
await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false);
+
+ // Tappa E3: a converted copy by the real engine (PNG, «Copia in…» → «Cambia»), a frame and two conversions.
+ if (rest.Skip(FormatsFrom).FirstOrDefault() is { } toConvert)
+ {
+ await service.StartAsync(
+ new ExportJobRequest(new ExportSelection.Media([toConvert.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)),
+ ct).ConfigureAwait(false);
+ await service.WaitAsync(ct).ConfigureAwait(false);
+ }
+
+ await FrameAsync(database, world, general, marta, clock, ct).ConfigureAwait(false);
+ await ConversionsAsync(root, database, world, [.. rest.Skip(FormatsFrom + 1).Take(2)], clock, ct).ConfigureAwait(false);
+ }
+
+ /// The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s).
+ public static readonly TimeSpan FrameAsked = TimeSpan.FromMilliseconds(1234);
+
+ // rest[0..2] are «Tolto», «Superato» and «Errore», rest[3..14] the interrupted job.
+ private const int FormatsFrom = 15;
+
+ ///
+ /// A frame of a video of @marta.demo in the general folder, as «Fotogrammi…» → «Nella cartella delle copie» writes it:
+ /// the demo shares one video file whose SHA-256 is not the one recorded, so the engine would refuse it (rule: the
+ /// frames are of the file recorded); the row and its PNG are written here.
+ ///
+ private static async Task FrameAsync(FebeDatabase database, DemoWorld world, ExportDestination general, Account marta, IClock clock, CancellationToken ct)
+ {
+ if (world.VideoFile is not { } videoFile || !File.Exists(videoFile)
+ || await VideoAsync(database, marta, ct).ConfigureAwait(false) is not { } video
+ || await database.Entries.GetAsync(video.EntryId, ct).ConfigureAwait(false) is not { } entry)
+ {
+ return;
+ }
+
+ byte[] png;
+ TimeSpan actual;
+ await using (var stream = File.OpenRead(videoFile))
+ {
+ using var reader = VideoFrameReader.Open(stream, out var info);
+ if (!info.Available)
+ {
+ return;
+ }
+
+ var target = reader.Locate([FrameAsked])[0];
+ using var frame = reader.Decode([target], ct).Single();
+ png = ImageConverter.Encode(frame.Image, ImageFormat.Png, null);
+ actual = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
+ }
+
+ var suffix = ExportFrames.Suffix(FrameMode.At, actual, 0, 1);
+ var segments = ExportPaths.Segments(general, LibraryNaming.Default, marta, entry, video, null, false, world.Zone, new ExportNameOptions(".png", suffix));
+ var relative = ExportPaths.RelativePathFor(general, segments, keepSuffix: suffix);
+ var framePath = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative));
+ Directory.CreateDirectory(Path.GetDirectoryName(framePath)!);
+ await using (var output = new FileStream(framePath, FileMode.CreateNew, FileAccess.Write))
+ {
+ await output.WriteAsync(png, ct).ConfigureAwait(false);
+ }
+
+ await database.Exports.AddCopyAsync(
+ new ExportCopy
+ {
+ DestinationId = general.Id,
+ AccountId = marta.Id,
+ MediaId = video.Id,
+ SourceSha256 = video.Sha256!,
+ Variant = ExportVariant.Frame,
+ Format = ExportFormat.Png,
+ FrameAt = actual,
+ State = ExportCopyState.Copied,
+ RelativePath = relative,
+ Bytes = png.Length,
+ CopySha256 = Convert.ToHexStringLower(SHA256.HashData(png)),
+ CopiedAt = clock.Now.AddDays(-1),
+ },
+ ct).ConfigureAwait(false);
+ }
+
+ ///
+ /// Two conversions of the library (spec §4.10): a PNG next to its original («Convertito», its file in the demo's
+ /// «convertiti» folder) and one that never converts («Non si converte»). The demo never runs the conversion.
+ ///
+ private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList photos, IClock clock, CancellationToken ct)
+ {
+ var now = clock.Now;
+ if (photos.Count > 0 && photos[0] is { Sha256: { } sha, RelativePath: { } original } converted
+ && world.Pictures.TryGetValue(sha, out var source) && File.Exists(source))
+ {
+ var result = await Task.Run(() => ImageConverter.Convert(File.ReadAllBytes(source), ImageFormat.Png), ct).ConfigureAwait(false);
+ var folder = Path.Combine(root, "convertiti");
+ Directory.CreateDirectory(folder);
+ var file = Path.Combine(folder, sha + ".png");
+ await File.WriteAllBytesAsync(file, result.Data, ct).ConfigureAwait(false);
+ var row = await database.Conversions.AddAsync(
+ new MediaConversion
+ {
+ MediaId = converted.Id,
+ Format = ExportFormat.Png,
+ State = MediaConversionState.Converted,
+ SourceSha256 = sha,
+ RelativePath = Path.ChangeExtension(original, ".png"),
+ Bytes = result.Data.Length,
+ Sha256 = Convert.ToHexStringLower(SHA256.HashData(result.Data)),
+ CreatedAt = now.AddDays(-4),
+ ConvertedAt = now.AddDays(-4),
+ StateChangedAt = now.AddDays(-4),
+ LastError = ExportText.JoinNotes([.. result.NotCarried, .. result.Losses]),
+ },
+ ct).ConfigureAwait(false);
+ world.ConversionFiles[row.Id] = file;
+ }
+
+ if (photos.Count > 1 && photos[1].Sha256 is { } asIsSha)
+ {
+ await database.Conversions.AddAsync(
+ new MediaConversion
+ {
+ MediaId = photos[1].Id,
+ Format = ExportFormat.Png,
+ State = MediaConversionState.Failed,
+ SourceSha256 = asIsSha,
+ CreatedAt = now.AddDays(-4),
+ StateChangedAt = now.AddDays(-4),
+ LastError = ImageConversionLosses.AsIsAnimated,
+ },
+ ct).ConfigureAwait(false);
+ }
+ }
+
+ ///
+ /// A present video of an account whose SHA-256 the fewest files share (the demo's videos take the SHA-256 of their
+ /// cover picture, and the marks of the copies go by SHA-256): the newest among those.
+ ///
+ private static async Task VideoAsync(FebeDatabase database, Account account, CancellationToken ct)
+ {
+ var files = new Dictionary(StringComparer.Ordinal);
+ var videos = new List();
+ LibraryCursor? cursor = null;
+ do
+ {
+ var page = await database.Entries.QueryLibraryAsync(
+ new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 },
+ ct).ConfigureAwait(false);
+ foreach (var tile in page.Tiles)
+ {
+ if (tile.CoverSha256 is { } sha)
+ {
+ files[sha] = files.GetValueOrDefault(sha) + 1;
+ }
+
+ if (tile.CoverKind == MediaKind.Video && tile.CoverMediaId is { } id)
+ {
+ videos.Add(id);
+ }
+ }
+
+ cursor = page.Older;
+ }
+ while (cursor is not null);
+
+ Media? best = null;
+ foreach (var id in videos)
+ {
+ if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha, RelativePath: not null } media
+ && EntryStateRules.IsPresent(media.State)
+ && (best is null || files.GetValueOrDefault(sha) < files.GetValueOrDefault(best.Sha256!)))
+ {
+ best = media;
+ }
+ }
+
+ return best;
}
/// One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».
diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs
index 0774c2c..16cafe7 100644
--- a/src/Febe.Web/Demo/DemoHost.cs
+++ b/src/Febe.Web/Demo/DemoHost.cs
@@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs
index 60b86f0..4615f41 100644
--- a/src/Febe.Web/Demo/DemoSeeder.cs
+++ b/src/Febe.Web/Demo/DemoSeeder.cs
@@ -1,6 +1,8 @@
+using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
using Febe.Core.Abstractions;
+using Febe.Core.Codecs.H264;
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
@@ -64,6 +66,15 @@ public sealed class DemoWorld
/// Sample pictures in the proportions of a story (the browser preview of the demo).
public IReadOnlyList StoryPictures { get; init; } = [];
+
+ ///
+ /// The demo's one video file (H.264, 2 s, tappa E3), served for every video of the demo so that «Fotogramma» works.
+ /// Its bytes are not those recorded for the videos (they share the SHA-256 of their cover picture).
+ ///
+ public string? VideoFile { get; init; }
+
+ /// The files of the seeded conversions of the library, by row id (written by ).
+ public ConcurrentDictionary ConversionFiles { get; } = new();
}
///
@@ -583,8 +594,11 @@ public static class DemoSeeder
var mine = accounts.First(a => a.Spec.Mine).Account;
var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false);
+ var videoFile = Path.Combine(pictures, "video-dimostrativo.mp4");
+ await File.WriteAllBytesAsync(videoFile, await Task.Run(H264PcmWriter.DemoVideo, ct).ConfigureAwait(false), ct).ConfigureAwait(false);
return new DemoWorld
{
+ VideoFile = videoFile,
SeededAt = now,
Zone = zone,
Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal),
diff --git a/src/Febe.Web/Export/FrameService.cs b/src/Febe.Web/Export/FrameService.cs
new file mode 100644
index 0000000..30b06e8
--- /dev/null
+++ b/src/Febe.Web/Export/FrameService.cs
@@ -0,0 +1,454 @@
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.IO.Compression;
+using System.Security.Cryptography;
+using Febe.Core.Abstractions;
+using Febe.Core.Codecs.Images;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Core.Library.Conversion;
+using Febe.Web.Api;
+
+namespace Febe.Web.Export;
+
+/// A frame encoded for the page: its bytes, media type, extension and the instant really shown.
+public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual);
+
+/// The frames of one video in a download: where it is, its account and name, and the instants asked.
+/// The account (first segment of the zip entries).
+/// The library file.
+/// The library file name without extension.
+/// The instants asked, in increasing order.
+/// When the entry was published (the time of the zip entries, D18).
+public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList Instants, DateTimeOffset PublishedAt);
+
+/// A «Scarica» of frames waiting for its address to be opened.
+public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList Videos)
+{
+ /// The frames in all.
+ public int Frames => Videos.Sum(v => v.Instants.Count);
+}
+
+///
+/// Frames of videos for the page (spec §4.10 «Fotogrammi», tappa E3, D14): what a video allows (kept for 64 files by
+/// SHA-256), a single frame for the previews and «Scarica», and the zip of several. Previews and single frames go one at
+/// a time (one decoder busy, never a queue of heavy work) within ; they are not long work and run at
+/// any time. A zip of up to frames runs at any time too; from 21 to
+/// it takes and never runs during an engine session. Nothing here writes a
+/// file: the frames go to the page only.
+///
+public sealed class FrameService(IClock clock)
+{
+ /// The longest side of a preview.
+ public const int MaxPreview = 480;
+
+ /// The most frames of a zip at any time.
+ public const int MaxAnyTime = 20;
+
+ /// The most frames of «Scarica».
+ public const int MaxDownload = 500;
+
+ /// Video infos kept.
+ public const int CacheSize = 64;
+
+ public const string TimeoutText = "Il fotogramma richiede troppo tempo: scegli la cartella delle copie";
+
+ public const string SessionText = "Il motore è in sessione: per più di 20 fotogrammi riprova fra poco";
+
+ public const string TooManyText = "Per più di 500 fotogrammi scegli la cartella delle copie";
+
+ public const string NothingText = "Nessun fotogramma da scaricare: scegli dei video con i fotogrammi disponibili.";
+
+ private static readonly TimeSpan TokenLife = TimeSpan.FromMinutes(5);
+
+ private readonly SemaphoreSlim _one = new(1, 1);
+ private readonly Lock _cacheGate = new();
+ private readonly Dictionary _cache = new(StringComparer.Ordinal);
+ private readonly ConcurrentDictionary _tokens = new(StringComparer.Ordinal);
+ private long _uses;
+
+ /// The time a preview or a single frame may take, waiting included.
+ public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
+
+ /// A write of the zip that makes no progress for this long aborts the download.
+ public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
+
+ /// What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).
+ public async Task InfoAsync(string path, string? sha256, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ if (sha256 is { Length: > 0 } && Cached(sha256) is { } cached)
+ {
+ return cached;
+ }
+
+ var info = await Task.Run(
+ () =>
+ {
+ using var stream = OpenRead(path);
+ using var reader = VideoFrameReader.Open(stream, out var found);
+ return found;
+ },
+ ct).ConfigureAwait(false);
+ if (sha256 is { Length: > 0 })
+ {
+ Remember(sha256, info);
+ }
+
+ return info;
+ }
+
+ ///
+ /// The instants of for the video at with the samples really shown;
+ /// empty when the video has no frames. over 1.000 frames.
+ ///
+ public Task<(VideoFrameInfo Info, IReadOnlyList Targets)> LocateAsync(string path, string? sha256, ExportFramesRequest request, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ ArgumentNullException.ThrowIfNull(request);
+ return Task.Run(
+ () =>
+ {
+ using var stream = OpenRead(path);
+ using var reader = VideoFrameReader.Open(stream, out var info);
+ if (sha256 is { Length: > 0 })
+ {
+ Remember(sha256, info);
+ }
+
+ if (!info.Available)
+ {
+ return (info, (IReadOnlyList)[]);
+ }
+
+ var instants = ExportFrames.Instants(info.Duration, request);
+ return (info, reader.Locate(instants));
+ },
+ ct);
+ }
+
+ ///
+ /// The frame shown at , encoded in ; with
+ /// scaled down to fit it (a preview). One at a time, within : past it
+ /// 503. when the video has no frames.
+ ///
+ public async Task FrameAsync(string path, string? sha256, TimeSpan at, ExportFormat format, int? maxSide, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+ var image = MediaConverter.ImageFormatOf(format) ?? throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.");
+ using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ budget.CancelAfter(Budget);
+ try
+ {
+ await _one.WaitAsync(budget.Token).ConfigureAwait(false);
+ try
+ {
+ return await Task.Run(() => Decode(path, sha256, at, image, maxSide, budget.Token), budget.Token).ConfigureAwait(false);
+ }
+ finally
+ {
+ _one.Release();
+ }
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ throw new ApiStatusException(503, TimeoutText);
+ }
+ }
+
+ /// Keeps a download for , for one use; returns its token.
+ public string Register(FrameDownloadPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ var now = clock.Now;
+ foreach (var (key, value) in _tokens)
+ {
+ if (value.Expires <= now)
+ {
+ _tokens.TryRemove(key, out _);
+ }
+ }
+
+ var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
+ _tokens[token] = (plan, now + TokenLife);
+ return token;
+ }
+
+ /// The download of , taken once; null when unknown, used or expired.
+ public FrameDownloadPlan? Take(string token)
+ {
+ if (string.IsNullOrEmpty(token) || !_tokens.TryRemove(token, out var found))
+ {
+ return null;
+ }
+
+ return found.Expires > clock.Now ? found.Plan : null;
+ }
+
+ /// The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension.
+ public static string FileName(string stem, FrameMode mode, TimeSpan actual, int index, int count, ExportFormat format) =>
+ WindowsFileNames.SanitizeSegment(stem + ExportFrames.Suffix(mode, actual, index, count) + MediaConverter.ExtensionOf(format));
+
+ ///
+ /// Writes the zip of into as it is made (not compressed: the
+ /// images are), entries account/name unique as the copies number them («x (2).png»), dated per
+ /// (the publication, else now), within the years a zip can hold.
+ ///
+ public async Task WriteZipAsync(Stream output, FrameDownloadPlan plan, bool publicationTime, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(output);
+ ArgumentNullException.ThrowIfNull(plan);
+ var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan));
+ var guarded = new StallGuardStream(output, WriteStall);
+ var names = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false);
+ await using (zip.ConfigureAwait(false))
+ {
+ foreach (var video in plan.Videos)
+ {
+ var folder = WindowsFileNames.SanitizeSegment(video.Username);
+ var time = EntryTime(publicationTime ? video.PublishedAt : clock.Now);
+ await foreach (var (index, frame) in FramesAsync(video, plan, image, ct).ConfigureAwait(false))
+ {
+ var name = FileName(video.Stem, plan.Mode, frame.Actual, index, video.Instants.Count, plan.Format);
+ var relative = folder + "/" + name;
+ var suffix = ExportFrames.Suffix(plan.Mode, frame.Actual, index, video.Instants.Count);
+ for (var attempt = 2; !names.Add(relative); attempt++)
+ {
+ relative = ExportPaths.NumberedName("febe", folder + "/" + name, attempt, keepSuffix: suffix);
+ }
+
+ var entry = zip.CreateEntry(relative, CompressionLevel.NoCompression);
+ entry.LastWriteTime = time;
+ var stream = await entry.OpenAsync(ct).ConfigureAwait(false);
+ await using (stream.ConfigureAwait(false))
+ {
+ await stream.WriteAsync(frame.Data, ct).ConfigureAwait(false);
+ }
+ }
+ }
+ }
+
+ await guarded.CompleteAsync(ct).ConfigureAwait(false);
+ }
+
+ /// The frames of one video of a download, encoded, in decoding order, with their index among its instants.
+ public async IAsyncEnumerable<(int Index, EncodedFrame Frame)> FramesAsync(FrameDownloadVideo video, FrameDownloadPlan plan, ImageFormat image, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(video);
+ ArgumentNullException.ThrowIfNull(plan);
+ Stream stream;
+ try
+ {
+ stream = OpenRead(video.Path);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ yield break; // the file went since the plan: its frames are left out
+ }
+
+ await using (stream.ConfigureAwait(false))
+ {
+ var (reader, info) = await Task.Run(() => (VideoFrameReader.Open(stream, out var found), found), ct).ConfigureAwait(false);
+ using (reader)
+ {
+ if (!info.Available)
+ {
+ yield break;
+ }
+
+ var targets = reader.Locate(video.Instants);
+ using var frames = reader.Decode(targets, ct).GetEnumerator();
+ var shown = new HashSet();
+ while (await Task.Run(() => frames.MoveNext(), ct).ConfigureAwait(false))
+ {
+ using var frame = frames.Current;
+ if (!shown.Add(frame.Actual.Ticks))
+ {
+ continue; // two instants on the same picture give it once, as the copies do
+ }
+
+ var data = await Task.Run(() => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false);
+ yield return (frame.Index, new EncodedFrame(data, ContentType(image), MediaConverter.ExtensionOf(plan.Format), frame.Actual));
+ }
+ }
+ }
+ }
+
+ /// The media type of an image format written by Febe.
+ public static string ContentType(ImageFormat format) => format switch
+ {
+ ImageFormat.Jpeg => "image/jpeg",
+ ImageFormat.Png => "image/png",
+ _ => "image/webp",
+ };
+
+ private EncodedFrame Decode(string path, string? sha256, TimeSpan at, ImageFormat image, int? maxSide, CancellationToken ct)
+ {
+ using var stream = OpenRead(path);
+ using var reader = VideoFrameReader.Open(stream, out var info);
+ if (sha256 is { Length: > 0 })
+ {
+ Remember(sha256, info);
+ }
+
+ if (!info.Available)
+ {
+ throw new NotFoundException(info.Unavailable ?? VideoFrameReader.NotAvailableMessage);
+ }
+
+ var targets = reader.Locate([at]);
+ using var frame = reader.Decode(targets, ct).FirstOrDefault() ?? throw new NotFoundException(VideoFrameReader.NotAvailableMessage);
+ ct.ThrowIfCancellationRequested();
+ var source = frame.Image;
+ if (maxSide is { } max && Math.Max(source.Width, source.Height) > max)
+ {
+ var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, max);
+ using var small = ImageResampler.Resize(source, width, height);
+ return new EncodedFrame(ImageConverter.Encode(small, image, null), ContentType(image), Extension(image), frame.Actual);
+ }
+
+ return new EncodedFrame(ImageConverter.Encode(source, image, null), ContentType(image), Extension(image), frame.Actual);
+ }
+
+ private static string Extension(ImageFormat image) => image switch
+ {
+ ImageFormat.Jpeg => ".jpg",
+ ImageFormat.Png => ".png",
+ _ => ".webp",
+ };
+
+ /// The time of a zip entry: within 1980-2107, the years a zip can hold.
+ private DateTimeOffset EntryTime(DateTimeOffset instant)
+ {
+ var local = TimeZoneInfo.ConvertTime(instant, clock.LocalZone);
+ var min = new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset);
+ var max = new DateTimeOffset(2107, 12, 31, 23, 59, 58, local.Offset);
+ return local < min ? min : local > max ? max : local;
+ }
+
+ private VideoFrameInfo? Cached(string sha256)
+ {
+ lock (_cacheGate)
+ {
+ if (_cache.TryGetValue(sha256, out var found))
+ {
+ _cache[sha256] = (found.Info, ++_uses);
+ return found.Info;
+ }
+
+ return null;
+ }
+ }
+
+ private void Remember(string sha256, VideoFrameInfo info)
+ {
+ lock (_cacheGate)
+ {
+ _cache[sha256] = (info, ++_uses);
+ if (_cache.Count > CacheSize)
+ {
+ var oldest = _cache.MinBy(p => p.Value.Used).Key;
+ _cache.Remove(oldest);
+ }
+ }
+ }
+
+ private static FileStream OpenRead(string path) =>
+ new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
+
+ internal static string Day(DateTimeOffset now, TimeZoneInfo zone) =>
+ LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
+
+ ///
+ /// A write-only stream that gives up a write making no progress for a while (the page stopped reading). The zip of
+ /// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those
+ /// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write.
+ ///
+ private sealed class StallGuardStream(Stream inner, TimeSpan stall) : Stream
+ {
+ // A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL.
+ private const int MaxPending = 64 * 1024;
+
+ private readonly MemoryStream _pending = new();
+ private long _position;
+
+ public override bool CanRead => false;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => _position;
+ set => throw new NotSupportedException();
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override async Task FlushAsync(CancellationToken cancellationToken)
+ {
+ await SendPendingAsync(cancellationToken).ConfigureAwait(false);
+ await inner.FlushAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
+
+ public override void Write(ReadOnlySpan buffer)
+ {
+ if (_pending.Length + buffer.Length > MaxPending)
+ {
+ throw new NotSupportedException("Lo zip dei fotogrammi si scrive solo in modo asincrono.");
+ }
+
+ _pending.Write(buffer);
+ _position += buffer.Length;
+ }
+
+ public override void WriteByte(byte value) => Write([value]);
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
+ WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
+
+ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ await SendPendingAsync(cancellationToken).ConfigureAwait(false);
+ await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false);
+ _position += buffer.Length;
+ }
+
+ /// Sends what was written synchronously and flushes: call it once the zip is complete.
+ public Task CompleteAsync(CancellationToken ct) => FlushAsync(ct);
+
+ private async Task SendPendingAsync(CancellationToken ct)
+ {
+ if (_pending.Length == 0)
+ {
+ return;
+ }
+
+ var bytes = _pending.ToArray();
+ _pending.SetLength(0);
+ await GuardedAsync(bytes, ct).ConfigureAwait(false);
+ }
+
+ private async Task GuardedAsync(ReadOnlyMemory buffer, CancellationToken ct)
+ {
+ using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ guard.CancelAfter(stall);
+ await inner.WriteAsync(buffer, guard.Token).ConfigureAwait(false);
+ }
+ }
+}
diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs
index 013624c..8b6a397 100644
--- a/src/Febe.Web/FebeWeb.cs
+++ b/src/Febe.Web/FebeWeb.cs
@@ -4,6 +4,7 @@ using Febe.Core.Alerts;
using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
+using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
using Febe.Web.Api;
using Febe.Web.Connection;
@@ -90,6 +91,20 @@ public static class FebeWeb
: ExportRootOptions.AnyFolder);
services.TryAddSingleton(sp => new SystemExportDisk(sp.GetRequiredService().Mounts));
services.TryAddSingleton();
+ // The conversion of the library (tappa E3): the composition registers the worker it starts; without one (the
+ // demo, the tests) the endpoints get one that never runs, over the same database and gate.
+ services.TryAddSingleton(sp => new LibraryConversionQueue(sp.GetRequiredService(), sp.GetRequiredService()));
+ services.TryAddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment
+ {
+ Storage = sp.GetRequiredService(),
+ Layout = () => sp.GetRequiredService().Layout,
+ Clock = sp.GetRequiredService(),
+ Gate = sp.GetRequiredService(),
+ Session = sp.GetRequiredService(),
+ }));
+ // Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip.
+ services.TryAddSingleton();
+ services.TryAddSingleton();
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
@@ -152,6 +167,7 @@ public static class FebeWeb
SettingsApi.Map(endpoints);
ImportApi.Map(endpoints);
ExportApi.Map(endpoints);
+ FramesApi.Map(endpoints);
DuplicatesApi.Map(endpoints);
SearchApi.Map(endpoints);
RemoteViewSocket.Map(endpoints);
diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md
index 0e764a5..18383b8 100644
--- a/src/Febe.Web/LEGGIMI.md
+++ b/src/Febe.Web/LEGGIMI.md
@@ -139,10 +139,14 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa |
| `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime |
| `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata |
-| `GET /api/export`, `PUT /api/export/settings` (`{ samePost: "onePerAccount"\|"oneOnly" }`) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria |
+| `GET /api/export`, `PUT /api/export/settings` (`{ samePost?, photoFormat?, videoFormat?, libraryPhotoFormat?, libraryVideoFormat?, convertExisting? }`, parziale) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria, formati (`original`, `jpg`, `png`, `webplossless`, `mp4`) e stato della conversione della libreria (`libraryConversion`). Il salvataggio risponde `{ message, overview, queued }` |
+| `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`; 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 }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo, avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato |
+| `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 |
+| `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/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, `/`). 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) |
| `POST /api/accounts/{id}/export-enabled` (`{ value }`) | «Esporta questo account»: spento, nessuna copia dell'account, neanche da «Copia in…». La scheda (`GET /api/accounts/{id}`) ha `export` con i conteggi dei file dovuti |
| `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (``) |
@@ -265,6 +269,12 @@ scrive mai nella libreria vera e non usa la rete.
propria di @studio.lumen.demo), `esporta/Chiavetta` (quella che dà la finestra di scelta); @il.porto.demo non si
esporta; di @marta.demo circa due terzi delle foto copiati dal motore vero (un lavoro concluso con resoconto), un file
tolto, uno superato, uno con errore e un lavoro interrotto da riprendere. In veste Docker la radice si chiama `/esporta`.
+- Formati e fotogrammi (tappa E3): ogni video della dimostrazione è lo stesso video H.264 di 2 secondi
+ (`campioni/video-dimostrativo.mp4`, scritto da `H264PcmWriter`), così «Fotogramma» e «Fotogrammi…» → «Scarica»
+ funzionano; di @marta.demo una foto copiata in PNG dal motore vero, un fotogramma a 1,234 s (cioè 0:01,125, il
+ fotogramma mostrato in quel momento) già nella cartella generale, una foto con il suo PNG in libreria e una che «non si
+ converte». La conversione della libreria non parte mai. «Nella cartella delle copie» dei fotogrammi di un video
+ finisce in errore («non corrisponde»): i video condividono l'impronta della loro copertina, non quella del file.
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino.
diff --git a/src/Febe.Web/Library/FebeLibrary.cs b/src/Febe.Web/Library/FebeLibrary.cs
index 000b0f9..7898b4d 100644
--- a/src/Febe.Web/Library/FebeLibrary.cs
+++ b/src/Febe.Web/Library/FebeLibrary.cs
@@ -82,6 +82,41 @@ public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolve
}
}
+///
+/// Where the file of a conversion of the library is on disk (tappa E3): only Converted and Superseded rows have one.
+/// The demo maps its seeded rows; the real one uses the layout.
+///
+public interface IConversionFileResolver
+{
+ /// Full path of an existing file, or null when the row has no file or it is not on disk.
+ string? Resolve(Account account, MediaConversion conversion);
+}
+
+/// Converted files next to their originals, under the account folders of the library (spec §4.10).
+public sealed class LibraryConversionFileResolver(FebeLibrary library) : IConversionFileResolver
+{
+ public string? Resolve(Account account, MediaConversion conversion)
+ {
+ ArgumentNullException.ThrowIfNull(account);
+ ArgumentNullException.ThrowIfNull(conversion);
+ if (conversion.RelativePath is null || conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded))
+ {
+ return null;
+ }
+
+ try
+ {
+ // FullPath refuses a path that leaves the account folder.
+ var path = library.Layout.FullPath(account, conversion.RelativePath);
+ return File.Exists(path) ? path : null;
+ }
+ catch (ArgumentException)
+ {
+ return null;
+ }
+ }
+}
+
/// Something changed in the library: the open pages reload what they show.
/// When.
/// The account concerned, when there is only one.
diff --git a/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs b/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs
new file mode 100644
index 0000000..1cba046
--- /dev/null
+++ b/tests/Febe.Tests/Media/H264/H264PcmWriterTests.cs
@@ -0,0 +1,78 @@
+using Febe.Core.Codecs.H264;
+using Febe.Core.Library;
+
+namespace Febe.Tests.Codecs.H264;
+
+///
+/// The small H.264 video the demo shows (tappa E3): PCM macroblocks only, so its frames decode to the samples written,
+/// through the same reader «Fotogramma» uses.
+///
+[TestClass]
+public sealed class H264PcmWriterTests
+{
+ [TestMethod]
+ public void TheDemoVideoIsTheSameEveryTime() =>
+ CollectionAssert.AreEqual(H264PcmWriter.DemoVideo(), H264PcmWriter.DemoVideo());
+
+ [TestMethod]
+ public void TheDemoVideoGivesItsFramesAtTheirInstants()
+ {
+ using var stream = new MemoryStream(H264PcmWriter.DemoVideo());
+ using var reader = VideoFrameReader.Open(stream, out var info);
+
+ Assert.IsTrue(info.Available, info.Unavailable);
+ Assert.AreEqual((H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight), (info.Width, info.Height));
+ Assert.AreEqual(H264PcmWriter.DemoPictures, info.SampleCount);
+ Assert.AreEqual(TimeSpan.FromSeconds(2), info.Duration);
+ Assert.IsFalse(info.HasAudio);
+
+ // 8 pictures per second: 1.234 s shows picture 9 (shown from 1.125 s).
+ var targets = reader.Locate([TimeSpan.FromMilliseconds(1234), TimeSpan.Zero]);
+ Assert.AreEqual(TimeSpan.FromMilliseconds(1125), targets[0].Actual);
+ Assert.AreEqual(9, targets[0].Sample);
+
+ var frames = reader.Decode(targets, CancellationToken.None).ToList();
+ try
+ {
+ Assert.HasCount(2, frames);
+ foreach (var frame in frames)
+ {
+ var expected = H264PcmWriter.DemoPicture(frame.Index == 0 ? 9 : 0);
+ var pixels = frame.Image.ToArray();
+ var width = H264PcmWriter.DemoWidth;
+ foreach (var (x, y) in new[] { (0, 0), (17, 33), (width - 1, H264PcmWriter.DemoHeight - 1), (120, 200) })
+ {
+ var (r, g, b) = Bt601(expected.Y[(y * width) + x], expected.Cb[((y / 2) * (width / 2)) + (x / 2)], expected.Cr[((y / 2) * (width / 2)) + (x / 2)]);
+ var at = ((y * width) + x) * 4;
+ Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at] - r), $"R at {x},{y}");
+ Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 1] - g), $"G at {x},{y}");
+ Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 2] - b), $"B at {x},{y}");
+ Assert.AreEqual((byte)255, pixels[at + 3]);
+ }
+ }
+ }
+ finally
+ {
+ frames.ForEach(f => f.Dispose());
+ }
+ }
+
+ [TestMethod]
+ public void TheSamplesNeverContainAStartCode()
+ {
+ var nal = H264PcmWriter.Idr(H264PcmWriter.DemoPicture(3), 1);
+ for (var i = 0; i + 2 < nal.Length; i++)
+ {
+ Assert.IsFalse(nal[i] == 0 && nal[i + 1] == 0 && nal[i + 2] <= 3 && nal[i + 2] != 3, $"Start code at {i}");
+ }
+ }
+
+ private static (int R, int G, int B) Bt601(byte y, byte cb, byte cr)
+ {
+ var c = 1.164 * (y - 16);
+ var d = cb - 128;
+ var e = cr - 128;
+ static int Clamp(double v) => (int)Math.Clamp(Math.Round(v), 0, 255);
+ return (Clamp(c + (1.596 * e)), Clamp(c - (0.392 * d) - (0.813 * e)), Clamp(c + (2.017 * d)));
+ }
+}
diff --git a/tests/Febe.Tests/Web/DemoExportTests.cs b/tests/Febe.Tests/Web/DemoExportTests.cs
index 7c60263..6575887 100644
--- a/tests/Febe.Tests/Web/DemoExportTests.cs
+++ b/tests/Febe.Tests/Web/DemoExportTests.cs
@@ -12,7 +12,8 @@ namespace Febe.Tests.Web;
///
/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account
/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real
-/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there.
+/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. Tappa E3:
+/// a copy converted to PNG, a frame of a video and two conversions of the library, which the demo never runs.
///
[TestClass]
public sealed class DemoExportTests
@@ -61,12 +62,18 @@ public sealed class DemoExportTests
var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct);
Assert.IsGreaterThanOrEqualTo(2, destinations.Count);
var states = new HashSet();
+ var forms = new List();
foreach (var destination in destinations)
{
Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath);
foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct))
{
states.Add(copy.State);
+ if (copy.State == ExportCopyState.Copied && copy.Variant != ExportVariant.Whole)
+ {
+ forms.Add(copy);
+ }
+
var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null;
switch (copy.State)
{
@@ -149,5 +156,59 @@ public sealed class DemoExportTests
}
Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy");
+
+ // Tappa E3: the converted copy (by the real engine) and the frame are real files with their SHA-256 (checked above).
+ var convertedCopy = forms.SingleOrDefault(c => c.Variant == ExportVariant.Converted);
+ Assert.IsNotNull(convertedCopy, "a copy converted to PNG");
+ Assert.AreEqual(ExportFormat.Png, convertedCopy.Format);
+ StringAssert.EndsWith(convertedCopy.RelativePath, ".png");
+ var frameCopy = forms.Single(c => c.Variant == ExportVariant.Frame);
+ Assert.AreEqual(TimeSpan.FromMilliseconds(1125), frameCopy.FrameAt, "1.234 s shows the picture shown from 1.125 s");
+ StringAssert.EndsWith(frameCopy.RelativePath, "_t0m01s125.png");
+
+ // The demo video gives frames: the preview of that instant is the frame copied.
+ var videoId = frameCopy.MediaId!.Value;
+ var info = await GetAsync($"/api/media/{videoId}/frames/info");
+ Assert.IsTrue(info.Bool("available"), info.ToString());
+ Assert.AreEqual(2000L, info.Long("durationMs"));
+ using (var frame = await client.GetAsync($"/api/media/{videoId}/frame?at=1234&format=png&download=1", ct))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
+ Assert.AreEqual("image/png", frame.Content.Headers.ContentType?.MediaType);
+ Assert.AreEqual(frameCopy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await frame.Content.ReadAsByteArrayAsync(ct))));
+ }
+
+ var video = await demo.Storage.Media.GetAsync(videoId, ct);
+ var viewer = (await GetAsync($"/api/entries/{video!.EntryId}")).Items("media").Single(m => m.Long("id") == videoId);
+ Assert.IsTrue(viewer.Bool("framesAvailable"));
+ var frameRow = viewer.Items("copies").Single(c => c.Str("variant") == "frame");
+ Assert.AreEqual(1125L, frameRow.Long("frameAtMs"));
+ Assert.AreEqual("0:01,125", frameRow.Str("frameLabel"));
+
+ // Two conversions of the library, which the demo never runs: nothing waits and nothing changes.
+ var conversion = await GetAsync("/api/export/library-conversion");
+ Assert.AreEqual(0, conversion.Int("pending"));
+ Assert.AreEqual(1, conversion.Int("converted"));
+ Assert.AreEqual(1, conversion.Int("asIs"));
+ Assert.AreEqual(0, conversion.Int("failed"));
+ var (rowId, file) = demo.World.ConversionFiles.Single();
+ var row = await demo.Storage.Conversions.GetAsync(rowId, ct);
+ Assert.AreEqual(MediaConversionState.Converted, row!.State);
+ using (var converted = await client.GetAsync($"/api/conversions/{rowId}/file", ct))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, converted.StatusCode);
+ Assert.AreEqual("image/png", converted.Content.Headers.ContentType?.MediaType);
+ Assert.AreEqual(row.Sha256, Convert.ToHexStringLower(SHA256.HashData(await converted.Content.ReadAsByteArrayAsync(ct))));
+ }
+
+ var photo = await demo.Storage.Media.GetAsync(row.MediaId, ct);
+ var shown = (await GetAsync($"/api/entries/{photo!.EntryId}")).Items("media").Single(m => m.Long("id") == row.MediaId);
+ var shownRow = shown.Items("conversions").Single();
+ Assert.AreEqual("converted", shownRow.Str("state"));
+ Assert.AreEqual("png", shownRow.Str("format"));
+ Assert.IsTrue(shownRow.Bool("available"));
+ await Task.Delay(TimeSpan.FromSeconds(1), ct);
+ Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(rowId, ct))!.State, "the demo never converts");
+ Assert.IsTrue(File.Exists(file));
}
}
diff --git a/tests/Febe.Tests/Web/DemoTests.cs b/tests/Febe.Tests/Web/DemoTests.cs
index 15e75ac..905bff3 100644
--- a/tests/Febe.Tests/Web/DemoTests.cs
+++ b/tests/Febe.Tests/Web/DemoTests.cs
@@ -219,8 +219,11 @@ public sealed class DemoTests
}
else
{
- // Videos have only their cover in the demo.
- Assert.AreEqual(HttpStatusCode.NotFound, file.StatusCode);
+ // Every video of the demo plays its one short H.264 video (tappa E3: «Fotogramma» works in the demo).
+ Assert.AreEqual(HttpStatusCode.OK, file.StatusCode);
+ Assert.AreEqual("video/mp4", file.Content.Headers.ContentType?.MediaType);
+ var bytes = await file.Content.ReadAsByteArrayAsync();
+ Assert.AreEqual("ftyp", System.Text.Encoding.ASCII.GetString(bytes, 4, 4), "a real MP4");
checkedVideos++;
}
}
diff --git a/tests/Febe.Tests/Web/ExportApiDemoTests.cs b/tests/Febe.Tests/Web/ExportApiDemoTests.cs
index 6248097..6d7979c 100644
--- a/tests/Febe.Tests/Web/ExportApiDemoTests.cs
+++ b/tests/Febe.Tests/Web/ExportApiDemoTests.cs
@@ -139,7 +139,8 @@ public sealed class ExportApiDemoTests
Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark");
var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList();
Assert.IsNotEmpty(notCopied);
- Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark");
+ // Tappa E3: a video with only a frame copied is still to copy, and says so («frameOnly»), never «copiato».
+ Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null || t.Str("copies") == "frameOnly"), "a file not copied has no mark of a copy");
Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status);
var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList();
diff --git a/tests/Febe.Tests/Web/ExportFormatsApiTests.cs b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs
new file mode 100644
index 0000000..47eeb19
--- /dev/null
+++ b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs
@@ -0,0 +1,197 @@
+using System.IO.Compression;
+using System.Net;
+using System.Text.Json;
+using Febe.Core.Codecs.H264;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Core.Library;
+using Febe.Tests.Export.Support;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Support;
+using Febe.Web;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Febe.Tests.Web;
+
+///
+/// Formats and frames over the API of a real web host (tappa E3): the formats of the settings and of a folder of the
+/// copies (wire names of D21), the conversion of the library (status, question, pause), and frames of a video built by
+/// the test (information, one frame, the instants of a mode, «Scarica» of one frame and of a zip).
+///
+[TestClass]
+public sealed class ExportFormatsApiTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task TheFormatsOfTheSettingsAreSavedByTheirWireNames()
+ {
+ await using var server = await StartAsync();
+ var overview = await server.GetJsonAsync("/api/export");
+ foreach (var name in new[] { "photoFormat", "videoFormat", "libraryPhotoFormat", "libraryVideoFormat" })
+ {
+ Assert.AreEqual("original", overview.Str(name), name);
+ }
+
+ var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "webplossless", videoFormat = "mp4" });
+ Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
+ Assert.IsNotEmpty(saved.Str("message"));
+ Assert.AreEqual("webplossless", saved.GetProperty("overview").Str("photoFormat"));
+ overview = await server.GetJsonAsync("/api/export");
+ Assert.AreEqual("webplossless", overview.Str("photoFormat"));
+ Assert.AreEqual("mp4", overview.Str("videoFormat"));
+ Assert.AreEqual("original", overview.Str("libraryPhotoFormat"), "a partial request keeps the rest");
+
+ foreach (var wrong in new object[] { new { }, new { photoFormat = "mp4" }, new { videoFormat = "png" }, new { libraryPhotoFormat = "tiff" } })
+ {
+ Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", wrong)).Status, JsonSerializer.Serialize(wrong));
+ }
+
+ Assert.AreEqual("webplossless", (await server.GetJsonAsync("/api/export")).Str("photoFormat"), "a refused request changes nothing");
+
+ // A command from another page is refused, like every other one.
+ using var foreign = server.Request(HttpMethod.Put, "/api/export/settings", new { photoFormat = "png" }, "http://altro.example");
+ using var refused = await server.Client.SendAsync(foreign, TestContext.CancellationToken);
+ Assert.AreEqual(HttpStatusCode.Forbidden, refused.StatusCode);
+ }
+
+ [TestMethod]
+ public async Task AFolderOfTheCopiesKeepsItsFormats()
+ {
+ await using var server = await StartAsync();
+ var root = server.Temp.Combine("usb");
+ Directory.CreateDirectory(root);
+ var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "png", videoFormat: "original"));
+ Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
+ var destination = saved.GetProperty("destination");
+ Assert.AreEqual("png", destination.Str("photoFormat"));
+ Assert.AreEqual("original", destination.Str("videoFormat"));
+ var stored = await server.Db.Exports.GetDestinationAsync(destination.Long("id"));
+ Assert.AreEqual(ExportFormat.Png, stored!.PhotoFormat);
+
+ Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(server.Temp.Combine("nas"), photoFormat: "mp4"))).Status);
+ }
+
+ [TestMethod]
+ public async Task TheConversionOfTheLibrarySaysWhatItWouldDo()
+ {
+ await using var server = await StartAsync();
+ var status = await server.GetJsonAsync("/api/export/library-conversion");
+ Assert.AreEqual(0, status.Int("pending"));
+ Assert.IsFalse(status.Bool("on"));
+ var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=png");
+ Assert.AreEqual(0, preview.Int("files"));
+ foreach (var action in new[] { "pause", "resume", "retry" })
+ {
+ var (code, answer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/library-conversion/{action}", new { });
+ Assert.AreEqual(HttpStatusCode.OK, code, $"{action}: {answer}");
+ Assert.IsNotEmpty(answer.Str("message"));
+ }
+ }
+
+ [TestMethod]
+ [Timeout(120_000, CooperativeCancellation = true)]
+ public async Task FramesOfAVideoArePreviewedAndDownloaded()
+ {
+ var ct = TestContext.CancellationToken;
+ await using var server = await StartAsync();
+ var video = await AddVideoAsync(server);
+
+ var info = await server.GetJsonAsync($"/api/media/{video.Id}/frames/info");
+ Assert.IsTrue(info.Bool("available"), info.ToString());
+ Assert.AreEqual(2000L, info.Long("durationMs"));
+ Assert.AreEqual(H264PcmWriter.DemoWidth, info.Int("width"));
+
+ // A preview fits the size asked; a download is full size, PNG by default, named by its actual instant.
+ using (var preview = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&max=120", ct))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode);
+ Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType);
+ }
+
+ using (var full = await server.Client.GetAsync($"/api/media/{video.Id}/frame?at=1234&download=1", ct))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, full.StatusCode);
+ Assert.AreEqual("image/png", full.Content.Headers.ContentType?.MediaType);
+ StringAssert.EndsWith(full.Content.Headers.ContentDisposition?.FileNameStar ?? full.Content.Headers.ContentDisposition?.FileName?.Trim('"'), "_t0m01s125.png");
+ }
+
+ var instants = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=numero&count=4");
+ Assert.AreEqual(4, instants.Int("total"));
+ var labels = instants.Items("instants").Select(i => i.Str("suffix")).ToList();
+ CollectionAssert.AreEqual(new[] { "_f001", "_f002", "_f003", "_f004" }, labels);
+ var over = await server.GetJsonAsync($"/api/media/{video.Id}/frames/instants?mode=ogni&every=100");
+ Assert.IsFalse(over.Bool("overCap"));
+ Assert.AreEqual(20, over.Int("total"));
+
+ // «Scarica» of 3 frames: a zip with one entry per frame under the account folder, each a PNG.
+ var selection = new { mediaIds = new[] { video.Id }, frames = new { mode = "numero", count = 3, format = "png" } };
+ var (planStatus, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection);
+ Assert.AreEqual(HttpStatusCode.OK, planStatus, plan.ToString());
+ Assert.AreEqual(1, plan.Int("videos"));
+ Assert.AreEqual(3, plan.Int("frames"));
+ Assert.IsFalse(plan.Bool("needsQuiet"));
+ var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
+ Assert.AreEqual(HttpStatusCode.OK, tokenStatus, token.ToString());
+ using (var zip = await server.Client.GetAsync(token.Str("url"), ct))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode);
+ Assert.AreEqual("application/zip", zip.Content.Headers.ContentType?.MediaType);
+ using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read);
+ Assert.HasCount(3, archive.Entries);
+ foreach (var entry in archive.Entries)
+ {
+ StringAssert.StartsWith(entry.FullName, "marta.demo/");
+ StringAssert.EndsWith(entry.FullName, ".png");
+ using var data = entry.Open();
+ var header = new byte[8];
+ data.ReadExactly(header);
+ CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A }, header);
+ }
+ }
+
+ // A token is used once.
+ using (var again = await server.Client.GetAsync(token.Str("url"), ct))
+ {
+ Assert.AreEqual(HttpStatusCode.NotFound, again.StatusCode);
+ }
+
+ // A photo has no frames.
+ var (photoStatus, _) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.PhotoId}/frames/info");
+ Assert.AreEqual(HttpStatusCode.BadRequest, photoStatus);
+ }
+
+ // ------------------------------------------------------------------------------------------------- support
+
+ private static Task StartAsync() =>
+ WebTestServer.StartAsync(
+ new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None },
+ s => s.AddSingleton(new FakeExportDisk(500_000_000_000)));
+
+ private static object Destination(string path, string? photoFormat = null, string? videoFormat = null) => new
+ {
+ scope = "general",
+ accountId = (long?)null,
+ path,
+ label = (string?)null,
+ types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" },
+ namingScheme = (string?)null,
+ highlightNamingScheme = (string?)null,
+ profileNamingScheme = (string?)null,
+ photoFormat,
+ videoFormat,
+ };
+
+ /// A post of @marta.demo with the demo's 2 s video and a photo, saved as the collection does.
+ private static async Task<(long Id, long PhotoId)> AddVideoAsync(WebTestServer server)
+ {
+ var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
+ var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex());
+ var added = await server.Db.Entries.AddAsync(Make.Entry(account.Id, "video-1", Make.T0.AddDays(-1)), [Make.Video(1), Make.Photo(2)]);
+ var media = added.Stored.Media;
+ await ingest.SaveMediaAsync(account, added.Stored.Entry, media[0], new MediaContent { Content = new MemoryStream(H264PcmWriter.DemoVideo()), Extension = ".mp4" });
+ await ingest.SaveMediaAsync(account, added.Stored.Entry, media[1], new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(3, 96, 120)), Extension = ".jpg" });
+ await ingest.AppendJournalAsync(added.Stored.Entry.Id);
+ return (media[0].Id, media[1].Id);
+ }
+}
diff --git a/tests/Febe.Tests/Web/FrameServiceTests.cs b/tests/Febe.Tests/Web/FrameServiceTests.cs
new file mode 100644
index 0000000..acd54b8
--- /dev/null
+++ b/tests/Febe.Tests/Web/FrameServiceTests.cs
@@ -0,0 +1,82 @@
+using System.IO.Compression;
+using Febe.Core.Codecs.H264;
+using Febe.Core.Domain;
+using Febe.Core.Export;
+using Febe.Tests.Support;
+using Febe.Web.Export;
+
+namespace Febe.Tests.Web;
+
+///
+/// The zip of «Scarica» of frames (tappa E3, D14): written while it is sent, through asynchronous writes only (a
+/// response body refuses synchronous ones), one entry per frame under the account folder, names made unique.
+///
+[TestClass]
+public sealed class FrameServiceTests
+{
+ public TestContext TestContext { get; set; } = null!;
+
+ [TestMethod]
+ public async Task TheZipIsWrittenThroughAsynchronousWritesOnly()
+ {
+ using var temp = new TempFolder("fotogrammi-zip");
+ var path = temp.Combine("video.mp4");
+ await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), TestContext.CancellationToken);
+ var clock = new ManualClock(Make.T0);
+ var service = new FrameService(clock);
+ var instants = new[] { TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1.5) };
+ var plan = new FrameDownloadPlan(FrameMode.Count, ExportFormat.Png, [
+ new FrameDownloadVideo("marta.demo", path, "post", instants, Make.T0.AddDays(-3)),
+ new FrameDownloadVideo("marta.demo", path, "post", instants[..1], Make.T0.AddDays(-3)),
+ ]);
+ using var sent = new MemoryStream();
+
+ await service.WriteZipAsync(new AsyncOnlyStream(sent), plan, publicationTime: true, TestContext.CancellationToken);
+
+ using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
+ CollectionAssert.AreEqual(
+ new[] { "marta.demo/post_f001.png", "marta.demo/post_f002.png", "marta.demo/post_f003.png", "marta.demo/post_f001 (2).png" },
+ archive.Entries.Select(e => e.FullName).ToArray());
+ var published = TimeZoneInfo.ConvertTime(Make.T0.AddDays(-3), clock.LocalZone).DateTime;
+ foreach (var entry in archive.Entries)
+ {
+ Assert.AreEqual(entry.Length, entry.CompressedLength, "frames are stored, not compressed");
+ // The zip keeps local date and time fields at 2 s steps: the time of publication where Febe runs (D18).
+ Assert.IsLessThanOrEqualTo(2.0, Math.Abs((entry.LastWriteTime.DateTime - published).TotalSeconds), $"{entry.LastWriteTime} vs {published}");
+ }
+ }
+
+ /// A response body: asynchronous writes only.
+ private sealed class AsyncOnlyStream(Stream inner) : Stream
+ {
+ public override bool CanRead => false;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override void Flush() => throw new InvalidOperationException("synchronous flush");
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write");
+
+ public override void Write(ReadOnlySpan buffer) => throw new InvalidOperationException("synchronous write");
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
+ inner.WriteAsync(buffer, offset, count, cancellationToken);
+
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
+ inner.WriteAsync(buffer, cancellationToken);
+ }
+}