E3: API di formati e fotogrammi, conversione della libreria e demo

Porta le funzioni della tappa E3 fino all'interfaccia web, così che WP4
possa costruire le schermate su indirizzi veri.

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 01:02:37 +01:00
1 parent 724c5bda6f
commit ab0d717424
25 files changed
+2559 -95

No files matched your search

+5 -2
View File
@@ -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
+1
View File
@@ -39,6 +39,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMid
JsonException => (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."),
};
+27
View File
@@ -298,3 +298,30 @@ public sealed class NotFoundException : Exception
{
}
}
/// <summary>An answer with another status and an Italian message: 409 (busy, in session), 503 (too slow).</summary>
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;
}
/// <summary>The HTTP status (409 when not given).</summary>
public int Status { get; } = 409;
}
+6 -3
View File
@@ -92,7 +92,9 @@ public sealed record MediaDto(
bool Available,
string State,
bool Damaged = false,
IReadOnlyList<MediaCopyDto>? Copies = null);
IReadOnlyList<MediaCopyDto>? Copies = null,
bool? FramesAvailable = null,
IReadOnlyList<MediaConversionDto>? Conversions = null);
/// <summary>Everything the viewer shows of an entry.</summary>
public sealed record EntryDto(
@@ -117,7 +119,8 @@ public sealed record EntryDto(
public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode);
public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList<string> Problems, string Message);
/// <summary>What «Elimina dalla libreria» did; <paramref name="ConvertedFiles"/>: converted files of the library deleted too (tappa E3).</summary>
public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList<string> Problems, string Message, int ConvertedFiles = 0);
/// <summary>Export by keys, or by the current filter when no keys are given.</summary>
public sealed record ExportRequest(IReadOnlyList<long>? 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);
+374 -54
View File
@@ -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<ExportDestinationDto>(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);
}
/// <summary>A destination with its counts, read from the database.</summary>
@@ -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));
}
/// <summary>
/// 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».
/// </summary>
public static string PlanSummary(ExportPlan plan, bool frames)
{
ArgumentNullException.ThrowIfNull(plan);
var parts = new List<string>();
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);
}
/// <summary>«Le 4 foto si saltano» (frames are taken from videos only).</summary>
public static string PhotosSkippedText(int photos) =>
photos == 1 ? "la foto si salta" : $"le {ItalianText.Number(photos)} foto si saltano";
/// <summary>The wire name of a format (D21): <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>.</summary>
public static string FormatName(ExportFormat format) => format.ToString().ToLowerInvariant();
/// <summary>
/// A format of <paramref name="kind"/> from its wire name; null for null or empty (nothing chosen). 400 for a name
/// that is not a format of that kind.
/// </summary>
public static ExportFormat? ParseFormat(string? text, MediaKind kind)
{
if (string.IsNullOrWhiteSpace(text))
{
return null;
}
var name = text.Trim();
var format = Enum.GetValues<ExportFormat>().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;
}
/// <summary>A frame format from its wire name: JPG, PNG or WEBP senza perdita; PNG when none is given (§16, domanda 35).</summary>
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.");
}
/// <summary>Which frames, from the page's request.</summary>
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));
}
/// <summary>Two copy rows of the same form: variant, format and frame instant (the full identity of §4.10 without the file).</summary>
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;
}
/// <summary>The wire name of a state of a conversion of the library; a failure that never converts is <c>asIs</c>.</summary>
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",
};
}
/// <summary>The state of the conversion of the library, for the settings and the Dashboard.</summary>
public static async Task<LibraryConversionDto> 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<string>();
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<string>();
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) + ".";
}
/// <summary>Impostazioni → Esportazione: root, destinations, settings, formats and the conversion of the library.</summary>
public static async Task<ExportOverviewDto> 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<ExportDestinationDto>(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));
}
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
@@ -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));
/// <summary>A destination's format: null, empty or <c>general</c> is «Come le impostazioni generali».</summary>
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.");
+153 -16
View File
@@ -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);
/// <summary>
/// <c>GET /api/export</c>: Impostazioni → Esportazione and the notice of the Dashboard. <paramref name="SamePost"/>:
/// <c>onePerAccount</c> or <c>oneOnly</c>. <paramref name="UnfinishedRuns"/>: interrupted or paused jobs («Riprendi»).
/// Formats (tappa E3) on the wire: <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>; the
/// library ones are <c>original</c> while the conversion of the library is off. <paramref name="LibraryConversion"/>:
/// the state of that conversion.
/// </summary>
public sealed record ExportOverviewDto(
ExportRootDto Root,
@@ -56,10 +61,44 @@ public sealed record ExportOverviewDto(
IReadOnlyList<ExportDestinationDto> Own,
IReadOnlyList<long> ActiveRunIds,
int UnfinishedRuns,
ExportSchemesDto Library);
ExportSchemesDto Library,
string PhotoFormat = "original",
string VideoFormat = "original",
string LibraryPhotoFormat = "original",
string LibraryVideoFormat = "original",
LibraryConversionDto? LibraryConversion = null);
/// <summary><c>PUT /api/export/settings</c>: «Lo stesso post in due account», <c>onePerAccount</c> or <c>oneOnly</c>.</summary>
public sealed record ExportSettingsRequest(string SamePost);
/// <summary>
/// The conversion of the library (tappa E3, spec §4.10): files in the queue, converted, failed («Riprova»), that never
/// convert (<paramref name="AsIs"/>: «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. <paramref name="Text"/>: the status line
/// («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»). <paramref name="On"/>: a library format is
/// chosen.
/// </summary>
public sealed record LibraryConversionDto(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, string Text, bool On);
/// <summary>
/// <c>PUT /api/export/settings</c>, every field optional (null keeps it): «Lo stesso post in due account»
/// (<c>onePerAccount</c> or <c>oneOnly</c>), the formats of the copies and of the library (wire names).
/// <paramref name="ConvertExisting"/>: the answer «Anche i N già in libreria» when a library format is turned on.
/// </summary>
public sealed record ExportSettingsRequest(
string? SamePost = null,
string? PhotoFormat = null,
string? VideoFormat = null,
string? LibraryPhotoFormat = null,
string? LibraryVideoFormat = null,
bool? ConvertExisting = null);
/// <summary>What <c>PUT /api/export/settings</c> did: a message, the overview after the change, the files queued.</summary>
public sealed record ExportSettingsSavedDto(string Message, ExportOverviewDto Overview, int Queued = 0);
/// <summary>
/// «Converti anche i N file già in libreria?»: <paramref name="Files"/> 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ù»).
/// </summary>
public sealed record LibraryConversionPreviewDto(int Files, long Bytes, string Text);
/// <summary>Docker: the subfolders of a folder of <c>/esporta</c>. <paramref name="Relative"/> is "" for the root.</summary>
public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList<SourceFolderDto> 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);
/// <summary>A saved destination (a change of folder gives a new id) and the warnings of its schemes.</summary>
public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList<string> Warnings);
@@ -97,7 +138,10 @@ public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination,
/// What a «Copia in…» copies: exactly one of <paramref name="MediaIds"/> (files of «Tutte le foto» or the viewer),
/// <paramref name="EntryIds"/> (a grouped selection), <paramref name="Query"/> (the filter of the Libreria, as its query
/// string, with <paramref name="Mode"/> <c>grouped</c> or <c>files</c>) or <paramref name="AccountId"/> (every file of
/// the account). <paramref name="CopyAgain"/>: «Copia di nuovo anche i tolti o superati».
/// the account). <paramref name="CopyAgain"/>: «Copia di nuovo anche i tolti o superati». Tappa E3:
/// <paramref name="PhotoFormat"/>/<paramref name="VideoFormat"/> override the destination's for this request only
/// (null: as the destination); <paramref name="Frames"/> makes it a frames job («Fotogrammi…» → «Nella cartella delle
/// copie»), without formats.
/// </summary>
public sealed record CopyJobRequestDto(
IReadOnlyList<long>? 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);
/// <summary>
/// Which frames (spec §4.10 «Fotogrammi»): <paramref name="Mode"/> <c>istante</c> (at <paramref name="AtMs"/>),
/// <c>ogni</c> (every <paramref name="EveryMs"/>, at least 100) or <c>numero</c> (<paramref name="Count"/> in all, 1 to
/// 1.000); <paramref name="Format"/> <c>jpg</c>, <c>png</c> (the default) or <c>webplossless</c>.
/// </summary>
public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null);
/// <summary>Files of a plan copied as they are, of one kind («3 HEIC copiati come sono»).</summary>
public sealed record ExportPlanAsIsDto(string Label, int Files);
/// <summary>A destination of a plan. <paramref name="Problem"/>: why it cannot be written now (paused, not reachable).</summary>
public sealed record ExportPlanDestinationDto(
@@ -123,7 +180,12 @@ public sealed record ExportPlanDestinationDto(
/// <summary>
/// The summary of «Copia in…» (spec §10.3). <paramref name="Files"/>/<paramref name="Bytes"/>: what will be written
/// (with «Copia di nuovo» the tolti/superati too). <paramref name="NotExported"/>: of accounts that are not exported
/// (switch off, no destination, type not taken). <paramref name="Missing"/>: not in the library.
/// (switch off, no destination, type not taken). <paramref name="Missing"/>: not in the library. Tappa E3:
/// <paramref name="AsIs"/> files predicted copied as they are («circa»), <paramref name="Converted"/> predicted
/// converted, <paramref name="Lossy"/> «con perdita»; a frames job: <paramref name="Videos"/>,
/// <paramref name="PhotosSkipped"/>, <paramref name="Frames"/> and <paramref name="OverCap"/> (videos over 1.000
/// frames: the job is refused). <paramref name="Summary"/>: the line of the dialog («312 file · 41 già copiati, saltati ·
/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»).
/// </summary>
public sealed record ExportPlanDto(
int Files,
@@ -133,7 +195,15 @@ public sealed record ExportPlanDto(
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestinationDto> Destinations,
bool HasDestination = true);
bool HasDestination = true,
IReadOnlyList<ExportPlanAsIsDto>? AsIs = null,
int Converted = 0,
bool Lossy = false,
int Videos = 0,
int PhotosSkipped = 0,
int Frames = 0,
int OverCap = 0,
string? Summary = null);
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
@@ -174,24 +244,33 @@ public sealed record ExportRunDto(
int Done,
bool Running = false);
/// <summary>The files of one account in a job (<paramref name="Copied"/> counts written and adopted files).</summary>
public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
/// <summary>
/// The files of one account in a job (<paramref name="Copied"/> counts written and adopted files).
/// <paramref name="AsIs"/>: files copied as they are, by kind («HEIC» → 3).
/// </summary>
public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed, IReadOnlyDictionary<string, int>? AsIs = null);
/// <summary>A file of the report that needs a look, with its reason in Italian.</summary>
public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text);
/// <summary>The report of a job (at most 200 problems).</summary>
/// <summary>
/// The report of a job (at most 200 problems). <paramref name="Notes"/> (tappa E3): files copied or adopted with a note
/// (what a conversion could not keep, a file copied as it is), at most 200.
/// </summary>
public sealed record ExportReportDto(
ExportRunDto Run,
IReadOnlyDictionary<string, int> ByState,
long BytesCopied,
IReadOnlyList<ExportReportAccountDto> Accounts,
IReadOnlyList<ExportReportLineDto> Problems);
IReadOnlyList<ExportReportLineDto> Problems,
IReadOnlyList<ExportReportLineDto>? Notes = null);
/// <summary>
/// A copy of a file of the viewer (spec §4.6, §4.10). <paramref name="State"/>: copied, removed, superseded, failed;
/// <paramref name="Variant"/>: whole (tappa E2 copies originals only). <paramref name="ForAccount"/>: with «Una copia
/// sola», the account it was copied for when it is another one. <paramref name="CanCopyAgain"/>: «Copia di nuovo».
/// <paramref name="Variant"/>: whole, converted or frame; <paramref name="Format"/>: the wire name of a converted copy or
/// of a frame (null for a whole one); <paramref name="FrameAtMs"/> and <paramref name="FrameLabel"/> («0:01,25») for a
/// frame. <paramref name="ForAccount"/>: with «Una copia sola», the account it was copied for when it is another one.
/// <paramref name="CanCopyAgain"/>: «Copia di nuovo» of that same form. <paramref name="Notes"/>: why it failed.
/// </summary>
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);
/// <summary>
/// A converted file of the library next to its original (tappa E3, spec §4.10): <paramref name="Format"/> (wire name),
/// <paramref name="State"/> <c>pending</c>, <c>converted</c>, <c>failed</c>, <c>asIs</c> («non si converte»),
/// <c>superseded</c> or <c>removed</c>, its size, and <paramref name="Notes"/>: what was not kept, or why it failed or
/// does not convert. <paramref name="Available"/>: the file is on disk («Scarica», «Mostra nella cartella»).
/// </summary>
public sealed record MediaConversionDto(long Id, string Format, string State, long? Bytes, string? Notes, bool Available, string? FileName);
/// <summary>
/// «Copie esterne» of the account card. <paramref name="Destination"/>: 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)
/// <summary>
/// <c>GET /api/media/{id}/frames/info</c>: whether frames can be taken from the video (<paramref name="Unavailable"/>:
/// «Fotogramma non disponibile per questo video»), its length and its size as shown (rotation applied).
/// </summary>
public sealed record FrameInfoDto(bool Available, string? Unavailable, long DurationMs, int Width, int Height, bool HasAudio);
/// <summary>
/// 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 (<c>_t0m01s250</c>, <c>_f001</c>).
/// </summary>
public sealed record FrameInstantDto(int Index, long RequestedMs, long ActualMs, string Label, string Suffix);
/// <summary>
/// <c>GET /api/media/{id}/frames/instants</c>: the instants of a mode for one video (at most 1.000). <paramref name="Total"/>:
/// how many it asks; <paramref name="Problem"/>: why none is given (over 1.000, not available).
/// </summary>
public sealed record FrameInstantsDto(long DurationMs, int Total, bool OverCap, string? Problem, IReadOnlyList<FrameInstantDto> Instants);
/// <summary>
/// The frames of a selection («Fotogrammi…» from the selection bars): exactly one of <paramref name="MediaIds"/>,
/// <paramref name="EntryIds"/> (every video of those entries) or <paramref name="Query"/> with <paramref name="Mode"/>,
/// and which frames.
/// </summary>
public sealed record FramesSelectionRequest(IReadOnlyList<long>? MediaIds, IReadOnlyList<long>? EntryIds, string? Query, string? Mode, FramesRequestDto? Frames);
/// <summary>
/// <c>POST /api/frames/plan</c>: what «Scarica» would give. <paramref name="NotAvailable"/>: videos without frames (or
/// not on disk); <paramref name="OverCap"/>: videos over 1.000 frames; <paramref name="TooManyToDownload"/>: more than
/// 500 frames («Nella cartella delle copie»); <paramref name="NeedsQuiet"/>: more than 20 (only outside engine sessions
/// and other long work). <paramref name="Problem"/>: why «Scarica» cannot run now; <paramref name="Summary"/>: the line
/// of the dialog («12 fotogrammi da 4 video · le 3 foto si saltano»).
/// </summary>
public sealed record FramesPlanDto(int Videos, int PhotosSkipped, int NotAvailable, int Frames, int OverCap, bool TooManyToDownload, bool NeedsQuiet, string? Problem, string Summary);
/// <summary>A download of frames ready: open <paramref name="Url"/> once within 5 minutes.</summary>
public sealed record FramesTokenDto(string Token, int Frames, string Url);
/// <summary>A converted file of the library («Mostra nella cartella»).</summary>
public sealed record ConversionActionRequest(long ConversionId);
/// <summary>
/// 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»).
/// </summary>
public sealed record EntryDeletionPreviewDto(int Entries, int Files, int ConvertedFiles);
+10
View File
@@ -105,4 +105,14 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(IReadOnlyList<ExportRunDto>))]
[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;
+424
View File
@@ -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;
/// <summary>
/// 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
/// <c>/api/export/plan</c> and <c>/start</c> with <c>frames</c>. Nothing here writes a file.
/// </summary>
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.");
});
}
/// <summary>The rows of the converted files of one library file for the viewer (tappa E3, §16 domanda 30).</summary>
public static IReadOnlyList<MediaConversionDto> Conversions(IConversionFileResolver files, Account account, IEnumerable<MediaConversion> 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
/// <summary>What «Scarica» would give for a selection: the videos with their instants, and what is left out.</summary>
/// <param name="VideoCount">Videos of the selection (with frames or not).</param>
/// <param name="Frames">Frames in all (from the lengths of the database when the videos were not opened).</param>
private sealed record FramesSelection(ExportFramesRequest Request, List<FrameDownloadVideo> Videos, int VideoCount, int Photos, int NotAvailable, int OverCap, int Frames);
private static async Task<FramesSelection> SelectionAsync(FramesSelectionRequest body, IFebeStorage storage, IMediaFileResolver files, FrameService frames, IClock clock, CancellationToken ct)
{
var request = body.Frames is { } f ? ExportApi.Frames(f) : throw new BadRequestException("Scegli quali fotogrammi.");
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<ExportCandidate>();
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<FrameDownloadVideo>();
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);
}
/// <summary>Why «Scarica» cannot run now; null when it can.</summary>
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;
}
/// <summary>«12 fotogrammi da 4 video · le 3 foto si saltano · 3 video senza fotogrammi».</summary>
private static string Summary(FramesSelection plan)
{
var withFrames = plan.VideoCount - plan.NotAvailable - plan.OverCap;
var parts = new List<string>
{
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);
/// <summary>A present video of the library on disk; 404 otherwise.</summary>
private static async Task<VideoFile> VideoAsync(IFebeStorage storage, IMediaFileResolver files, long mediaId, CancellationToken ct)
{
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);
/// <summary>The file of a Converted or Superseded conversion of a present account, or null.</summary>
private static async Task<string?> 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);
}
}
+82 -10
View File
@@ -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<EntryDto> EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
/// <summary>
/// Everything the viewer shows of an entry. With <paramref name="frames"/>, 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
/// <paramref name="conversions"/>, each file lists its converted files of the library (tappa E3).
/// </summary>
public static async Task<EntryDto> 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<MediaDto>(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).
/// </summary>
private static readonly TimeSpan FramesProbeTime = TimeSpan.FromSeconds(3);
/// <summary>Whether «Fotogramma» works on a video on disk; null for a photo, a missing file or a slow probe.</summary>
private static async Task<bool?> 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<bool> IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
+18 -2
View File
@@ -390,12 +390,28 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Files of the demo: the shared sample pictures. Videos have only their cover.</summary>
/// <summary>Files of the demo: the shared sample pictures, and one short video for every video (tappa E3).</summary>
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,
};
}
}
/// <summary>The converted files of the demo's library: the rows <see cref="DemoExport"/> seeded (tappa E3).</summary>
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;
}
}
+177 -1
View File
@@ -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 <c>/esporta</c>: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
/// </summary>
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);
}
/// <summary>The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s).</summary>
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;
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList<Media> 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);
}
}
/// <summary>
/// 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.
/// </summary>
private static async Task<Media?> VideoAsync(FebeDatabase database, Account account, CancellationToken ct)
{
var files = new Dictionary<string, int>(StringComparer.Ordinal);
var videos = new List<long>();
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;
}
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>
+1
View File
@@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
services.AddSingleton<IMediaFileResolver, DemoFileResolver>();
services.AddSingleton<IConversionFileResolver, DemoConversionFileResolver>();
services.AddSingleton<IConfigurationProblems, DemoConfigurationProblems>();
services.AddSingleton<IConnectionService, DemoConnectionService>();
services.AddSingleton<IBrowserPreview, DemoBrowserPreview>();
+14
View File
@@ -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
/// <summary>Sample pictures in the proportions of a story (the browser preview of the demo).</summary>
public IReadOnlyList<string> StoryPictures { get; init; } = [];
/// <summary>
/// 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).
/// </summary>
public string? VideoFile { get; init; }
/// <summary>The files of the seeded conversions of the library, by row id (written by <see cref="DemoExport"/>).</summary>
public ConcurrentDictionary<long, string> ConversionFiles { get; } = new();
}
/// <summary>
@@ -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),
+454
View File
@@ -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;
/// <summary>A frame encoded for the page: its bytes, media type, extension and the instant really shown.</summary>
public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual);
/// <summary>The frames of one video in a download: where it is, its account and name, and the instants asked.</summary>
/// <param name="Username">The account (first segment of the zip entries).</param>
/// <param name="Path">The library file.</param>
/// <param name="Stem">The library file name without extension.</param>
/// <param name="Instants">The instants asked, in increasing order.</param>
/// <param name="PublishedAt">When the entry was published (the time of the zip entries, D18).</param>
public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList<TimeSpan> Instants, DateTimeOffset PublishedAt);
/// <summary>A «Scarica» of frames waiting for its address to be opened.</summary>
public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList<FrameDownloadVideo> Videos)
{
/// <summary>The frames in all.</summary>
public int Frames => Videos.Sum(v => v.Instants.Count);
}
/// <summary>
/// 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 <see cref="Budget"/>; they are not long work and run at
/// any time. A zip of up to <see cref="MaxAnyTime"/> frames runs at any time too; from 21 to <see cref="MaxDownload"/>
/// it takes <see cref="LongWorkKind.FrameDownload"/> and never runs during an engine session. Nothing here writes a
/// file: the frames go to the page only.
/// </summary>
public sealed class FrameService(IClock clock)
{
/// <summary>The longest side of a preview.</summary>
public const int MaxPreview = 480;
/// <summary>The most frames of a zip at any time.</summary>
public const int MaxAnyTime = 20;
/// <summary>The most frames of «Scarica».</summary>
public const int MaxDownload = 500;
/// <summary>Video infos kept.</summary>
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<string, (VideoFrameInfo Info, long Used)> _cache = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, (FrameDownloadPlan Plan, DateTimeOffset Expires)> _tokens = new(StringComparer.Ordinal);
private long _uses;
/// <summary>The time a preview or a single frame may take, waiting included.</summary>
public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A write of the zip that makes no progress for this long aborts the download.</summary>
public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
public async Task<VideoFrameInfo> 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;
}
/// <summary>
/// The instants of <paramref name="request"/> for the video at <paramref name="path"/> with the samples really shown;
/// empty when the video has no frames. <see cref="ArgumentException"/> over 1.000 frames.
/// </summary>
public Task<(VideoFrameInfo Info, IReadOnlyList<VideoFrameTarget> 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<VideoFrameTarget>)[]);
}
var instants = ExportFrames.Instants(info.Duration, request);
return (info, reader.Locate(instants));
},
ct);
}
/// <summary>
/// The frame shown at <paramref name="at"/>, encoded in <paramref name="format"/>; with <paramref name="maxSide"/>
/// scaled down to fit it (a preview). One at a time, within <see cref="Budget"/>: past it
/// <see cref="ApiStatusException"/> 503. <see cref="NotFoundException"/> when the video has no frames.
/// </summary>
public async Task<EncodedFrame> 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);
}
}
/// <summary>Keeps a download for <see cref="TokenLife"/>, for one use; returns its token.</summary>
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;
}
/// <summary>The download of <paramref name="token"/>, taken once; null when unknown, used or expired.</summary>
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;
}
/// <summary>The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension.</summary>
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));
/// <summary>
/// Writes the zip of <paramref name="plan"/> into <paramref name="output"/> as it is made (not compressed: the
/// images are), entries <c>account/name</c> unique as the copies number them («x (2).png»), dated per
/// <paramref name="publicationTime"/> (the publication, else now), within the years a zip can hold.
/// </summary>
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<string>(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);
}
/// <summary>The frames of one video of a download, encoded, in decoding order, with their index among its instants.</summary>
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<long>();
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));
}
}
}
}
/// <summary>The media type of an image format written by Febe.</summary>
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",
};
/// <summary>The time of a zip entry: within 1980-2107, the years a zip can hold.</summary>
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);
/// <summary>
/// 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.
/// </summary>
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<byte> 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<byte> buffer, CancellationToken cancellationToken = default)
{
await SendPendingAsync(cancellationToken).ConfigureAwait(false);
await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false);
_position += buffer.Length;
}
/// <summary>Sends what was written synchronously and flushes: call it once the zip is complete.</summary>
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<byte> buffer, CancellationToken ct)
{
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct);
guard.CancelAfter(stall);
await inner.WriteAsync(buffer, guard.Token).ConfigureAwait(false);
}
}
}
+16
View File
@@ -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<IExportDisk>(sp => new SystemExportDisk(sp.GetRequiredService<ExportRootOptions>().Mounts));
services.TryAddSingleton<ExportHub>();
// 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<IFebeStorage>(), sp.GetRequiredService<IClock>()));
services.TryAddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment
{
Storage = sp.GetRequiredService<IFebeStorage>(),
Layout = () => sp.GetRequiredService<FebeLibrary>().Layout,
Clock = sp.GetRequiredService<IClock>(),
Gate = sp.GetRequiredService<LongWorkGate>(),
Session = sp.GetRequiredService<IEngineSessionState>(),
}));
// Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip.
services.TryAddSingleton<IConversionFileResolver, LibraryConversionFileResolver>();
services.TryAddSingleton<FrameService>();
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);
+13 -3
View File
@@ -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, `<account>/<nome>`). Oltre 20 serve il motore fermo e nessun altro lavoro lungo (409 altrimenti) |
| `GET /api/conversions/{id}/file[?download=1]`, `POST /api/conversions/show-in-folder` (`{ conversionId }`), `POST /api/entries/delete-preview` (`{ ids }`) | File convertiti della libreria (`conversions` di ogni file del visualizzatore, con `framesAvailable` per i video e `frameAtMs`, `frameLabel`, `notes` nelle copie); quanti file e file convertiti toglierebbe «Elimina dalla libreria» |
| `GET /api/export/progress`, `GET /api/export/runs?limit=`, `POST /api/export/interrupt`, `/resume`, `/runs/{id}/resume`, `/runs/{id}/discard`, `GET /runs/{id}/report` | Scheda Esportazione della Dashboard: avanzamento, lavori, interruzione, ripresa, annullamento (i file copiati restano), resoconto (al più 200 problemi) |
| `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 (`<symbol id="i-nome">`) |
@@ -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.
+35
View File
@@ -82,6 +82,41 @@ public sealed class LibraryFileResolver(FebeLibrary library) : IMediaFileResolve
}
}
/// <summary>
/// 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.
/// </summary>
public interface IConversionFileResolver
{
/// <summary>Full path of an existing file, or null when the row has no file or it is not on disk.</summary>
string? Resolve(Account account, MediaConversion conversion);
}
/// <summary>Converted files next to their originals, under the account folders of the library (spec §4.10).</summary>
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;
}
}
}
/// <summary>Something changed in the library: the open pages reload what they show.</summary>
/// <param name="At">When.</param>
/// <param name="AccountId">The account concerned, when there is only one.</param>