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

+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.");