Files
Febe/src/Febe.Web/Api/ExportApi.cs
T
Alby96andClaude Opus 5.5 2efb408957
verifica / controlli (push) Canceled after 0s
verifica / prove (push) Canceled after 0s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
E3: seconda revisione di rimuxaggio, spazio, impostazioni e zip
Le quattro osservazioni confermate della seconda revisione, ognuna con
la sua prova (ciascuna cade sul codice di prima):

- Rimuxaggio con fotogrammi B: l'MP4 misura la fine della presentazione
  in tempo di composizione, non con la somma delle durate di decodifica.
  Prima nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone) e
  durava altrettanto meno in elst, tkhd e mvhd. Per le tracce senza
  scarti di composizione i byte restano gli stessi.
- Conversione della libreria: il lavoro ricorda il file che l'ha messo
  in pausa per spazio e quanto serve al suo convertito. Finché il disco
  non ha posto anche per quello, non rilegge l'originale a ogni
  risveglio (anche quando lo spazio libero sta appena sopra la soglia).
- Impostazioni dell'esportazione: formati, chiavi «dal» e coda del
  formato sostituito si salvano in una transazione sola; «Anche i N»
  dopo il salvataggio non dipende più dalla richiesta. Il gancio della
  libreria legge formati e chiavi «dal» in una lettura. Una scheda
  chiusa o un arresto non lasciano più un formato senza la sua chiave
  né «Non riuscito» che «Riprova» non tocca.
- Zip dei fotogrammi: i tempi del blocco passano da un TimeProvider
  della BCL, e la prova del lettore lento non dipende più dal carico
  della macchina.

Decisioni in docs/decisioni.md (28/11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:29:00 +01:00

1135 lines
57 KiB
C#

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.WebUtilities;
using ItalianText = Febe.Core.Engine.ItalianText;
namespace Febe.Web.Api;
/// <summary>
/// The copies to external folders (spec §4.10, §10.3, tappa E2) over <see cref="ExportService"/>: destinations and
/// their folders, «Copia in…» (plan, then start), the progress for the Dashboard tab «Esportazione», jobs, reports and
/// «Copia di nuovo». Every command passes the Origin check of the security middleware like any other. Nothing here
/// touches a file of a destination except through the service (its probe, its copies): no file is ever deleted, moved
/// or overwritten.
/// </summary>
public static class ExportApi
{
/// <summary>Title of the native folder picker for a destination.</summary>
public const string PickTitle = "Scegli la cartella delle copie";
/// <summary>The most files a «Copia in…» can name one by one (a larger choice goes through the filter).</summary>
public const int MaxIds = 50_000;
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the
/// library conversion compares before and after, so two quick changes must not both start from the same before.
/// </summary>
private static readonly SemaphoreSlim SettingsGate = new(1, 1);
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) =>
ApiHttp.Json(await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportOverviewDto));
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 (before, after, queued) = await SaveSettingsAsync(body, storage, queue, ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
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,
};
// The question is about the kind being turned on or changed: the other one is not counted (it already had
// its answer). Without either, both formats set now.
var (photoAsked, videoAsked) = (!string.IsNullOrWhiteSpace(photo), !string.IsNullOrWhiteSpace(video));
var both = !photoAsked && !videoAsked;
var preview = settings.ConvertsLibrary
? await queue.PreviewExistingAsync(
both || photoAsked ? LibraryConversionRules.FormatFor(MediaKind.Photo, settings) : null,
both || videoAsked ? LibraryConversionRules.FormatFor(MediaKind.Video, settings) : null,
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) =>
{
await hub.GetAsync(ct).ConfigureAwait(false);
var root = hub.RootFor(context);
if (root.Root is not { } rootFolder)
{
throw new BadRequestException("Qui la cartella si sceglie con la finestra del sistema.");
}
if (ExportRoots.Evaluate(root) is { Active: false, Problem: { } problem })
{
throw new BadRequestException(problem);
}
var relative = string.IsNullOrWhiteSpace(path) ? string.Empty : path.Trim().Trim('/', '\\').Replace('\\', '/');
// Never on the request thread without a limit: a dead share below /esporta must not hang the picker.
var folders = await GuardAsync(() => ExportRoots.BrowseAsync(root, relative.Length == 0 ? null : relative, DiskTimeout, ct)).ConfigureAwait(false);
string? parent = relative.Length == 0 ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty;
var full = relative.Length == 0 ? rootFolder : Path.Combine(rootFolder, LibraryLayout.ToPlatform(relative));
return ApiHttp.Json(
new ExportFolderListDto(relative, parent, ExportRoots.DisplayPath(root, full), [.. folders.Select(f => new SourceFolderDto(f.Name, f.Path, f.HasSubfolders))]),
FebeJsonContext.Default.ExportFolderListDto);
});
endpoints.MapPost("/api/export/pick-folder", async (HttpContext context, ExportHub hub, IFebeStorage storage, INativeShell shell, CancellationToken ct) =>
{
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.ExportPickRequest, new ExportPickRequest(null)).ConfigureAwait(false);
if (!shell.CanPickFolder || hub.RootFor(context).Root is not null)
{
throw new BadRequestException("Qui la cartella delle copie si sceglie dall'elenco delle cartelle di /esporta.");
}
// The picker opens on the folder of the destination being changed (from the database, never from the page).
string? initial = null;
if (body.DestinationId is { } id && await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) is { } destination
&& await ExistsAsync(destination.RootPath, ct).ConfigureAwait(false))
{
initial = destination.RootPath;
}
var picked = await shell.PickFolderAsync(PickTitle, initial, ct).ConfigureAwait(false);
return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto);
});
endpoints.MapPost("/api/export/check-folder", async (HttpContext context, ExportHub hub, IExportDisk disk, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
EnsureActive(hub);
var verdict = await GuardAsync(() => service.Destinations.CheckFolderAsync(body.Path ?? string.Empty, ct)).ConfigureAwait(false);
long? free = null;
var fat = false;
if (verdict.Accepted)
{
free = await MeasureAsync(() => disk.FreeBytes(verdict.FullPath), ct).ConfigureAwait(false);
fat = await MeasureAsync(() => disk.MaxFileBytes(verdict.FullPath), ct).ConfigureAwait(false) is { } max && max <= ExportSpace.Fat32Limit;
}
return ApiHttp.Json(
new ExportFolderCheckDto(verdict.Accepted, verdict.FullPath, Display(hub.RootFor(context), verdict.FullPath), verdict.Problem?.Message, free, fat),
FebeJsonContext.Default.ExportFolderCheckDto);
});
endpoints.MapPost("/api/export/naming-preview", async (HttpContext context, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportNamingPreviewRequest).ConfigureAwait(false);
var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
var sample = await SettingsApi.SampleAccountAsync(storage, ct).ConfigureAwait(false);
var preview = ExportNamingPreview.Build(ParseScope(body.Scope), Clean(body.General), Clean(body.Highlight), Clean(body.Profile), naming, clock.LocalZone, sample);
return ApiHttp.Json(SettingsApi.Preview(preview), FebeJsonContext.Default.NamingPreviewDto);
});
endpoints.MapPost("/api/export/destinations", async (HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
EnsureActive(hub);
var saved = await GuardAsync(() => service.Destinations.CreateAsync(Spec(body), ct)).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export"));
return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto);
});
endpoints.MapPut("/api/export/destinations/{id:long}", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false);
var service = await hub.GetAsync(ct).ConfigureAwait(false);
EnsureActive(hub);
var saved = await GuardAsync(() => service.Destinations.UpdateAsync(id, Spec(body), ct)).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export"));
return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto);
});
endpoints.MapDelete("/api/export/destinations/{id:long}", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GuardAsync(async () =>
{
await service.Destinations.RetireAsync(id, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
return ApiHttp.Message(ExportDestinations.RetiredText);
});
endpoints.MapGet("/api/export/destinations/{id:long}/status", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var status = await GuardAsync(() => service.Destinations.StatusAsync(id, ct)).ConfigureAwait(false);
var names = await UsernamesAsync(storage, ct).ConfigureAwait(false);
return ApiHttp.Json(
Destination(status.Destination, names, status.Counts, hub.RootFor(context), clock, status.Reachable, status.FreeBytes, status.Problem),
FebeJsonContext.Default.ExportDestinationDto);
});
endpoints.MapPost("/api/export/destinations/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var retry = await GuardAsync(() => service.RetryDestinationAsync(id, ct)).ConfigureAwait(false);
if (retry.Problem is { } problem)
{
throw new BadRequestException(problem);
}
return ApiHttp.Message(retry.Resumed.Count > 0
? "La cartella risponde di nuovo: la copia riprende."
: "La cartella risponde di nuovo.");
});
endpoints.MapPost("/api/export/destinations/{id:long}/check", async (long id, ExportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GuardAsync(async () =>
{
await service.CheckCopiesAsync(id, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
return ApiHttp.Message("Controllo delle copie avviato: segui l'avanzamento nella Dashboard, scheda Esportazione. Nessun file viene toccato.");
});
endpoints.MapPost("/api/export/plan", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false);
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), request.Frames is not null), FebeJsonContext.Default.ExportPlanDto);
});
endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false);
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), 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) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyAgainRequest).ConfigureAwait(false);
var copy = await storage.Exports.GetCopyAsync(body.CopyId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa copia non è più registrata.");
if (copy.State is not (ExportCopyState.Removed or ExportCopyState.Superseded))
{
throw new BadRequestException("Si copia di nuovo solo un file tolto dalla destinazione o superato.");
}
if (copy.AccountId is not { } accountId)
{
throw new BadRequestException("L'account di questa copia è stato rimosso: non c'è niente da copiare di nuovo.");
}
// The file the library has now: the one that took the place of the copied one, else the copied one itself
// (it can be back in the library in another entry while the one that replaced it went).
string? sha = null;
List<MediaLocation> present = [];
foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType<string>().Distinct(StringComparer.Ordinal))
{
present = (await storage.Media.FindBySha256Async(candidate, ct).ConfigureAwait(false))
.Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State))
.ToList();
if (present.Count > 0)
{
sha = candidate;
break;
}
}
if (sha is null)
{
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 && 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 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 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);
});
endpoints.MapGet("/api/export/progress", async (ExportHub hub, IFebeStorage storage, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var progress = await service.GetProgressAsync(ct).ConfigureAwait(false);
var error = service.LastJobError;
if (error is null && progress.RunId is { } runId && await storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) is { } run)
{
error = run.LastError;
}
return ApiHttp.Json(
new ExportProgressDto(
progress.RunId,
Phase(progress.Phase),
progress.Fraction,
progress.FilesDone,
progress.FilesTotal,
progress.BytesDone,
progress.BytesTotal,
progress.CurrentFile,
progress.DestinationLabel,
ItemCounts(progress.ByState),
service.IsBusy,
error),
FebeJsonContext.Default.ExportProgressDto);
});
endpoints.MapGet("/api/export/runs", async (int? limit, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var runs = await storage.Exports.ListRecentRunsAsync(Math.Clamp(limit ?? 20, 1, 100), ct).ConfigureAwait(false);
var labels = await LabelsAsync(storage, ct).ConfigureAwait(false);
var active = service.ActiveRunIds;
var list = new List<ExportRunDto>(runs.Count);
foreach (var run in runs)
{
var summary = await storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false);
list.Add(Run(run, summary, labels, clock, active.Contains(run.Id)));
}
return ApiHttp.Json<IReadOnlyList<ExportRunDto>>(list, FebeJsonContext.Default.IReadOnlyListExportRunDto);
});
endpoints.MapPost("/api/export/interrupt", async (ExportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await service.InterruptAsync(ct).ConfigureAwait(false);
return ApiHttp.Message("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi.");
});
endpoints.MapPost("/api/export/runs/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GuardAsync(() => service.ResumeAsync([id], ct)).ConfigureAwait(false);
return ApiHttp.Message("Copia ripresa: segui l'avanzamento qui.");
});
endpoints.MapPost("/api/export/resume", async (ExportHub hub, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var resumed = await GuardAsync(() => service.ResumeAsync(null, ct)).ConfigureAwait(false);
return ApiHttp.Message(resumed.Count switch
{
0 => "Non c'è nessuna copia da riprendere.",
1 => "Copia ripresa: segui l'avanzamento qui.",
var n => $"{Core.Engine.ItalianText.Number(n)} copie riprese, una cartella alla volta: segui l'avanzamento qui.",
});
});
endpoints.MapPost("/api/export/runs/{id:long}/discard", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
await GuardAsync(async () =>
{
await service.DiscardAsync(id, ct).ConfigureAwait(false);
return true;
}).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
return ApiHttp.Message("Annullata. I file già copiati restano dove sono.");
});
endpoints.MapGet("/api/export/runs/{id:long}/report", async (long id, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var report = await GuardAsync(() => service.Reports.BuildAsync(id, ct)).ConfigureAwait(false);
var labels = await LabelsAsync(storage, ct).ConfigureAwait(false);
var summary = new ExportRunSummary(report.Total, report.ByState);
return ApiHttp.Json(
new ExportReportDto(
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, 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);
});
}
// ---------------------------------------------------------------------------------------------- mapping
public static string Scope(ExportScope scope) => scope == ExportScope.General ? "general" : "account";
public static string SamePost(SamePostCopies copies) => copies == SamePostCopies.OneOnly ? "oneOnly" : "onePerAccount";
/// <summary>The wire names of the content types of a destination, in the order of the dialog.</summary>
public static IReadOnlyList<string> TypeNames(ContentTypes types)
{
var names = new List<string>(6);
foreach (var (type, name) in TypeTable)
{
if ((types & type) != ContentTypes.None)
{
names.Add(name);
}
}
return names;
}
public static string CopyState(ExportCopyState state) => state switch
{
ExportCopyState.Copied => "copied",
ExportCopyState.Removed => "removed",
ExportCopyState.Superseded => "superseded",
_ => "failed",
};
public static string RunState(ExportRunState state) => state switch
{
ExportRunState.Running => "running",
ExportRunState.Interrupted => "interrupted",
ExportRunState.Paused => "paused",
ExportRunState.Completed => "completed",
_ => "cancelled",
};
public static string ItemState(ExportItemState state) => state switch
{
ExportItemState.Pending => "pending",
ExportItemState.Copied => "copied",
ExportItemState.Adopted => "adopted",
ExportItemState.AlreadyCopied => "alreadyCopied",
ExportItemState.Skipped => "skipped",
ExportItemState.Missing => "missing",
_ => "failed",
};
/// <summary>Copies per state with every state present.</summary>
public static IReadOnlyDictionary<string, int> CopyCounts(IReadOnlyDictionary<ExportCopyState, int> counts)
{
ArgumentNullException.ThrowIfNull(counts);
return Enum.GetValues<ExportCopyState>().ToDictionary(CopyState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal);
}
/// <summary>Files of a job per state with every state present.</summary>
public static IReadOnlyDictionary<string, int> ItemCounts(IReadOnlyDictionary<ExportItemState, int> counts)
{
ArgumentNullException.ThrowIfNull(counts);
return Enum.GetValues<ExportItemState>().ToDictionary(ItemState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal);
}
/// <summary>The path of a folder as shown to Alberto (relative to <c>/esporta</c> in Docker).</summary>
public static string Display(ExportRootOptions root, string fullPath)
{
ArgumentNullException.ThrowIfNull(root);
try
{
return string.IsNullOrWhiteSpace(fullPath) ? fullPath ?? string.Empty : ExportRoots.DisplayPath(root, fullPath);
}
catch (ArgumentException)
{
return fullPath;
}
}
public static ExportDestinationDto Destination(
ExportDestination destination,
IReadOnlyDictionary<long, string> usernames,
IReadOnlyDictionary<ExportCopyState, int> counts,
ExportRootOptions root,
IClock clock,
bool? reachable = null,
long? freeBytes = null,
string? problem = null)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(usernames);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
return new ExportDestinationDto(
destination.Id,
Scope(destination.Scope),
destination.AccountId,
destination.AccountId is { } a && usernames.TryGetValue(a, out var name) ? name : null,
ExportDestinations.Label(destination),
destination.RootPath,
Display(root, destination.RootPath),
TypeNames(destination.ContentTypes),
destination.NamingScheme,
destination.HighlightNamingScheme,
destination.ProfileNamingScheme,
destination.Automatic,
destination.PausedAt is { } paused ? ApiMapping.Local(paused, now, clock.LocalZone) : null,
problem ?? (destination.PausedAt is not null ? destination.LastError : null),
CopyCounts(counts),
reachable,
freeBytes,
destination.IsOrphan,
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>
public static async Task<ExportDestinationDto> DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(destination);
var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
var names = new Dictionary<long, string>();
if (destination.AccountId is { } accountId && await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is { } account)
{
names[accountId] = account.Username;
}
return Destination(destination, names, counts, root, clock);
}
/// <summary>«Copie esterne» of the account card (decisions D1-D3 of tappa E2).</summary>
public static async Task<ExportAccountDto> AccountAsync(IFebeStorage storage, Account account, ExportRootOptions root, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(account);
var exports = storage.Exports;
var own = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false);
var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false));
var counts = await exports.CountAccountFilesAsync(account.Id, ct).ConfigureAwait(false);
return new ExportAccountDto(
enabled,
own is not null,
destination is null ? null : await DestinationAsync(storage, destination, root, clock, ct).ConfigureAwait(false),
counts.Due,
counts.NotCopied,
counts.RemovedOrSuperseded,
counts.Failed);
}
public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root, bool frames = false)
{
ArgumentNullException.ThrowIfNull(plan);
return new ExportPlanDto(
plan.Files,
plan.Bytes,
plan.AlreadyCopied,
plan.RemovedOrSuperseded,
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.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>
/// PUT /api/export/settings under <see cref="SettingsGate"/>: loads the settings, applies the request, saves them
/// and tells the queue of the library conversion, all before the next change starts.
/// </summary>
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsAsync(
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
{
await SettingsGate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await SaveSettingsCoreAsync(body, storage, queue, ct).ConfigureAwait(false);
}
finally
{
SettingsGate.Release();
}
}
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsCoreAsync(
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
{
var queued = 0;
var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var after = before;
if (body.SamePost is { } samePostText)
{
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,
};
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.");
}
// The formats, their «dal» keys and the queue of a format replaced in one transaction; once it is stored, what
// follows no longer depends on the request (a closed tab must not leave half of it).
await queue.SaveSettingsAsync(before, after, ct).ConfigureAwait(false);
if (body.ConvertExisting == true)
{
// «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps
// what was answered for it («Solo i nuovi» included, Q29).
var photo = Changed(MediaKind.Photo, body.LibraryPhotoFormat, before, after);
var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after);
if (photo is not null || video is not null)
{
queued = await queue.EnqueueExistingAsync(photo, video, CancellationToken.None).ConfigureAwait(false);
}
}
return (before, after, queued);
}
/// <summary>
/// The library format of <paramref name="kind"/> when this request set it and it changed (the kind the question
/// «Convertire anche i N file già in libreria?» was asked about); null otherwise, or when it is «Originale».
/// </summary>
private static ExportFormat? Changed(MediaKind kind, string? requested, ExportSettings before, ExportSettings after)
{
var now = LibraryConversionRules.FormatFor(kind, after);
return requested is not null && now != LibraryConversionRules.FormatFor(kind, before) ? now : null;
}
/// <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>
public static ExportJobRequest Request(CopyJobRequestDto body, IClock clock)
{
ArgumentNullException.ThrowIfNull(body);
ArgumentNullException.ThrowIfNull(clock);
var chosen = (body.MediaIds is { Count: > 0 } ? 1 : 0) + (body.EntryIds is { Count: > 0 } ? 1 : 0) + (body.Query is not null ? 1 : 0) + (body.AccountId is not null ? 1 : 0);
if (chosen != 1)
{
throw new BadRequestException("Scegli che cosa copiare: dei file, degli elementi, i risultati del filtro o un account.");
}
ExportSelection selection;
if (body.MediaIds is { Count: > 0 } media)
{
selection = new ExportSelection.Media(Ids(media));
}
else if (body.EntryIds is { Count: > 0 } entries)
{
selection = new ExportSelection.Entries(Ids(entries));
}
else if (body.Query is { } query)
{
var parsed = new QueryCollection(QueryHelpers.ParseQuery(query));
var mode = ApiMapping.Mode(body.Mode ?? parsed["mode"].ToString());
selection = new ExportSelection.Filter(ApiMapping.Filter(parsed, clock.LocalZone), mode);
}
else
{
selection = new ExportSelection.Account(body.AccountId!.Value);
}
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
private static readonly (ContentTypes Type, string Name)[] TypeTable =
[
(ContentTypes.PostPhotos, "postFoto"),
(ContentTypes.PostVideos, "postVideo"),
(ContentTypes.Stories, "storie"),
(ContentTypes.Highlights, "evidenza"),
(ContentTypes.Tagged, "taggati"),
(ContentTypes.ProfilePicture, "profilo"),
];
private static ContentTypes ParseTypes(IReadOnlyList<string>? names)
{
var types = ContentTypes.None;
foreach (var name in names ?? [])
{
var match = TypeTable.FirstOrDefault(t => string.Equals(t.Name, name?.Trim(), StringComparison.OrdinalIgnoreCase));
if (match.Name is null)
{
throw new BadRequestException("Tipo di contenuto sconosciuto.");
}
types |= match.Type;
}
return types;
}
private static ExportScope ParseScope(string? text) => text?.Trim().ToLowerInvariant() switch
{
"general" or "generale" => ExportScope.General,
"account" => ExportScope.Account,
_ => throw new BadRequestException("Tipo di cartella sconosciuto: generale o di un account."),
};
private static DestinationSpec Spec(ExportDestinationRequest body) => new(
ParseScope(body.Scope),
body.AccountId,
body.Path ?? string.Empty,
Clean(body.Label),
ParseTypes(body.Types),
Clean(body.NamingScheme),
Clean(body.HighlightNamingScheme),
Clean(body.ProfileNamingScheme),
body.Automatic,
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();
private static List<long> Ids(IReadOnlyList<long> ids) =>
ids.Count > MaxIds ? throw new BadRequestException("Troppi file in una volta: copia con il filtro della libreria.") : [.. ids.Distinct()];
private static string Phase(ExportPhase phase) => phase switch
{
ExportPhase.Preparing => "preparing",
ExportPhase.Checking => "checking",
ExportPhase.WaitingForSession => "waitingForSession",
ExportPhase.Copying => "copying",
_ => "finished",
};
private static ExportJobDto Job(ExportStart start, ExportRootOptions root, bool frames = false) => new(
[.. start.Runs.Select(r => r.Id)],
Plan(start.Plan, root, frames),
start.Runs.Count == 0
? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria."
: "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione.");
private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary<long, string> labels, IClock clock, bool running)
{
var now = clock.Now;
return new ExportRunDto(
run.Id,
run.DestinationId,
labels.TryGetValue(run.DestinationId, out var label) ? label : "Cartella tolta",
run.Kind == ExportRunKind.Recognize ? "recognize" : "copy",
run.Origin == ExportRunOrigin.Automatic ? "automatic" : "manual",
RunState(run.State),
ApiMapping.Local(run.StartedAt, now, clock.LocalZone),
run.CompletedAt is { } done ? ApiMapping.Local(done, now, clock.LocalZone) : null,
run.LastError,
summary.Total,
summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending),
running);
}
private static async Task<ExportDestinationSavedDto> SavedAsync(IFebeStorage storage, DestinationSaveResult saved, ExportRootOptions root, IClock clock, CancellationToken ct) =>
new(await DestinationAsync(storage, saved.Destination, root, clock, ct).ConfigureAwait(false), saved.Warnings);
private static async Task<IReadOnlyDictionary<long, string>> UsernamesAsync(IFebeStorage storage, CancellationToken ct) =>
(await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
/// <summary>Names of every destination, retired ones included (old jobs keep their name).</summary>
private static async Task<IReadOnlyDictionary<long, string>> LabelsAsync(IFebeStorage storage, CancellationToken ct) =>
(await storage.Exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id, ExportDestinations.Label);
/// <summary>Docker with <c>/esporta</c> not declared or not mounted: nothing can be written (decision D14 of tappa E2).</summary>
private static void EnsureActive(ExportHub hub)
{
if (ExportRoots.Evaluate(hub.Root) is { Active: false, Problem: { } problem })
{
throw new BadRequestException(problem);
}
}
/// <summary>A measure of a disk that may not answer (a disconnected share): null after the timeout.</summary>
private static async Task<T?> MeasureAsync<T>(Func<T?> measure, CancellationToken ct)
where T : struct
{
try
{
return await Task.Run(measure, ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return null;
}
}
private static async Task<bool> ExistsAsync(string folder, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(folder), ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
// ---------------------------------------------------------------------------------------------- errors
/// <summary>The export's own exceptions become Italian answers: 400 for a refused request, 404 for something missing.</summary>
internal static T Guard<T>(Func<T> action)
{
try
{
return action();
}
catch (Exception ex) when (Translate(ex) is { } translated)
{
throw translated;
}
}
internal static async Task<T> GuardAsync<T>(Func<Task<T>> action)
{
try
{
return await action().ConfigureAwait(false);
}
catch (Exception ex) when (Translate(ex) is { } translated)
{
throw translated;
}
}
private static Exception? Translate(Exception ex) => ex switch
{
ExportFolderException => new BadRequestException(ex.Message, ex),
DuplicateRecordException => new BadRequestException(ex.Message, ex),
KeyNotFoundException => new NotFoundException(ex.Message, ex),
ArgumentException a => new BadRequestException(ApiErrorMiddleware.CleanMessage(a), ex),
InvalidOperationException => new BadRequestException(ex.Message, ex),
_ => null,
};
}