Files
Febe/src/Febe.Web/Api/ExportApi.cs
T
Alby96andClaude Opus 5.5 f8491529ca E5: API e interfaccia delle copie automatiche e di «Riconosci»
L'interfaccia di programmazione e le pagine mostrano e usano ciò che i
pacchetti precedenti hanno costruito nel nucleo.

- API: le modifiche delle destinazioni passano da ChangeDestinationAsync
  (spegnere «Automatica» ferma subito la sua copia automatica, risposta
  52); nuova /api/export/automatic-preview (switchOn, widen, removeOwn,
  account) per la domanda «Solo i nuovi / Copia anche gli N» e i file in
  più (risposta 55); /destinations/{id}/recognize; /automatic/resume
  («Riprendi ora»); «Interrompi» su una copia automatica dice fino a che
  ora le copie automatiche restano ferme (risposta 53); runs?unfinished;
  avanzamento con tipo e origine; destinazioni con «dal» e i file che
  aspettano una cartella in pausa; stato delle copie automatiche nella
  panoramica (null senza il lavoratore, quindi nella dimostrazione);
  «da riprendere» conta solo i lavori di Alberto.
- Interfaccia: l'interruttore «Automatica» nella finestra della
  destinazione con la domanda all'accensione, i file in più e l'avviso
  allo spegnimento; stato della cartella condiviso da Impostazioni e
  scheda account (pausa «dal …», file che aspettano, «Riprova»,
  «Controlla le copie», «Riconosci le copie già presenti»); Dashboard con
  i nomi dei lavori automatici e di riconoscimento, la riga delle copie
  automatiche con «Riprendi ora», «Da riprendere» con ogni lavoro non
  finito e la copia manuale pronta a ripartire (risposta 48).
- Prove API in ExportApiTests.Automatic.cs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 16:30:25 +01:00

1444 lines
75 KiB
C#

using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Storage;
using Febe.Web.Export;
using Febe.Web.Library;
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;
/// <summary>The answer of «Riconosci le copie già presenti» (tappa E5).</summary>
public const string RecognizeStartedText = "Riconoscimento avviato: segui l'avanzamento nella Dashboard, scheda Esportazione. Nessun file viene toccato.";
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
/// <summary>How long the count of the files waiting for an automatic destination in pause is kept (<see cref="WaitingAsync"/>).</summary>
private static readonly TimeSpan WaitingKept = TimeSpan.FromMinutes(1);
private static readonly ConditionalWeakTable<IFebeStorage, ConcurrentDictionary<ExportBacklogQuery, (DateTimeOffset At, int Files)>> WaitingCache = new();
/// <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 spec = Spec(body);
// Through the service (tappa E5, D7.4): no automatic copy starts while a destination changes.
var saved = await GuardAsync(() => service.ChangeDestinationAsync(null, c => service.Destinations.CreateAsync(spec, c), 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 spec = Spec(body);
// Turning «Automatica» off stops the automatic copy of this folder at once (answer 52); the copies made stay.
var saved = await GuardAsync(() => service.ChangeDestinationAsync(id, c => service.Destinations.UpdateAsync(id, spec, c), 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(() => service.ChangeDestinationAsync(
id,
async c =>
{
await service.Destinations.RetireAsync(id, c).ConfigureAwait(false);
return true;
},
ct)).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/destinations/{id:long}/recognize", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
var run = await GuardAsync(() => service.RecognizeAsync(id, ct)).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, null, "export"));
return ApiHttp.Json(new ExportRecognizeStartedDto(RecognizeStartedText, run.Id), FebeJsonContext.Default.ExportRecognizeStartedDto);
});
endpoints.MapPost("/api/export/automatic-preview", async (HttpContext context, ExportHub hub, IFebeStorage storage, IExportDisk disk, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportAutomaticPreviewRequest).ConfigureAwait(false);
await hub.GetAsync(ct).ConfigureAwait(false);
var preview = await GuardAsync(() => AutomaticPreviewAsync(body, hub.Root, storage, disk, ct)).ConfigureAwait(false);
return ApiHttp.Json(preview, FebeJsonContext.Default.ExportAutomaticPreviewDto);
});
endpoints.MapPost("/api/export/automatic/resume", async (ExportHub hub, IServiceProvider services, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
if (services.GetService(typeof(AutoExportWorker)) is AutoExportWorker worker)
{
await worker.ResumeNowAsync(ct).ConfigureAwait(false);
}
else
{
service.ReleaseAutomaticHold();
AutoExportSignal.Default.Signal(urgent: true);
}
return ApiHttp.Message("Copie automatiche di nuovo attive.");
});
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 still = copy.Variant == ExportVariant.Frame && sha == copy.SourceSha256 && ExportFrames.IsSingleName(copy.RelativePath);
var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt, still);
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;
var (kind, origin) = (progress.Kind, progress.Origin);
if (progress.RunId is { } runId && await storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) is { } run)
{
error ??= run.LastError;
// A job being prepared reports no kind yet: its run has it («Controlla le copie» has no run).
kind ??= run.Kind;
origin ??= run.Origin;
}
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,
kind is { } k ? RunKind(k) : null,
origin is { } o ? RunOrigin(o) : null),
FebeJsonContext.Default.ExportProgressDto);
});
endpoints.MapGet("/api/export/runs", async (int? limit, bool? unfinished, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
// «Da riprendere» (tappa E5): every unfinished job, oldest first, not only those among the newest.
var runs = unfinished == true
? await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)
: 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, IClock clock, CancellationToken ct) =>
{
var service = await hub.GetAsync(ct).ConfigureAwait(false);
// An automatic copy stops the automatic copies until the next recovery round, at least an hour (answer 53).
var heldUntil = await service.InterruptAsync(ct).ConfigureAwait(false);
return ApiHttp.Message(heldUntil is { } until
? ExportText.AutomaticInterrupted(until, clock.LocalZone)
: "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))],
report.NotFound,
report.Different),
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,
int? waiting = null)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(usernames);
ArgumentNullException.ThrowIfNull(clock);
var now = clock.Now;
var since = destination.Automatic ? destination.AutomaticSince : null;
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,
since is { } from ? ApiMapping.Local(from, now, clock.LocalZone) : null,
waiting);
}
/// <summary>A destination with its counts (and, in pause, the files that wait for it), 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);
ArgumentNullException.ThrowIfNull(clock);
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;
}
var unfinished = destination.PausedAt is null ? [] : await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
var waiting = await WaitingAsync(storage, destination, unfinished, clock, ct).ConfigureAwait(false);
return Destination(destination, names, counts, root, clock, waiting: waiting);
}
/// <summary>
/// The files that wait for a destination in pause (tappa E5, D14): for an automatic one, what it would copy by itself
/// (at least what its unfinished jobs still have to copy); for one without «Automatica», what its unfinished jobs
/// still have to copy. Null when it is not paused. The count of an automatic destination is kept a minute per
/// database: a disk that stays unplugged must not make every reading of the Dashboard count the library again.
/// </summary>
public static async Task<int?> WaitingAsync(IFebeStorage storage, ExportDestination destination, IReadOnlyList<ExportRun> unfinished, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(destination);
ArgumentNullException.ThrowIfNull(unfinished);
ArgumentNullException.ThrowIfNull(clock);
if (destination.PausedAt is null || destination.IsRetired)
{
return null;
}
var pending = 0;
foreach (var run in unfinished.Where(r => r.DestinationId == destination.Id && r.Kind == ExportRunKind.Copy))
{
pending += (await storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false)).ByState.GetValueOrDefault(ExportItemState.Pending);
}
if (!destination.Automatic || destination.IsOrphan)
{
return pending;
}
var query = new ExportBacklogQuery(destination.Scope, destination.AccountId, destination.ContentTypes, destination.Id, destination.AutomaticSince);
var cache = WaitingCache.GetValue(storage, _ => new ConcurrentDictionary<ExportBacklogQuery, (DateTimeOffset At, int Files)>());
var now = clock.Now;
if (!cache.TryGetValue(query, out var kept) || now - kept.At > WaitingKept || now < kept.At)
{
kept = (now, (await storage.Exports.CountAutomaticBacklogAsync(query, ct).ConfigureAwait(false)).Files);
cache[query] = kept;
}
return Math.Max(pending, kept.Files);
}
/// <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),
plan.NotStill);
}
/// <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);
}
if (plan.NotStill > 0)
{
parts.Add(StillVideoText.NotStill);
}
}
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,
"fermo" or "still" => FrameMode.Still,
_ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."),
};
if (mode == FrameMode.Still && (body.AtMs is not null || body.EveryMs is not null || body.Count is not null))
{
// The instant is the analysis' own (tappa E4): one asked by the page would be another frame.
throw new BadRequestException("«Salva il fotogramma» prende il fotogramma scelto dall'analisi: niente istante, intervallo o numero.");
}
return new ExportFramesRequest(
mode,
mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null,
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 runs = await storage.Exports.ListUnfinishedRunsAsync(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);
var waiting = await WaitingAsync(storage, destination, runs, clock, ct).ConfigureAwait(false);
mapped.Add(Destination(destination, names, counts, root, clock, waiting: waiting));
}
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
var active = service.ActiveRunIds;
// Alberto's jobs only: the automatic ones resume by themselves (tappa E5), and the Dashboard lists them apart.
var unfinished = runs.Count(r => !active.Contains(r.Id) && r.Origin == ExportRunOrigin.Manual);
var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
var worker = services.GetService(typeof(LibraryConversionWorker)) as LibraryConversionWorker;
var automatic = services.GetService(typeof(AutoExportWorker)) is AutoExportWorker { Running: true } auto
? await AutomaticStatusAsync(auto, service, clock, ct).ConfigureAwait(false)
: null;
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),
automatic);
}
/// <summary>The automatic copies as the Dashboard shows them (tappa E5); the hold is the service's own.</summary>
public static async Task<ExportAutomaticStatusDto> AutomaticStatusAsync(AutoExportWorker worker, ExportService service, IClock clock, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(worker);
ArgumentNullException.ThrowIfNull(service);
ArgumentNullException.ThrowIfNull(clock);
var status = await worker.StatusAsync(ct).ConfigureAwait(false);
var now = clock.Now;
LocalTimeDto? Local(DateTimeOffset? at) => at is { } value ? ApiMapping.Local(value, now, clock.LocalZone) : null;
return new ExportAutomaticStatusDto(
status.AnyAutomatic,
status.Waiting,
Local(status.LastRound),
Local(status.NextRound),
Local(service.AutomaticHeldUntil ?? status.HeldUntil));
}
/// <summary>
/// <c>POST /api/export/automatic-preview</c> (tappa E5): what an automatic destination would copy by itself, from the
/// store's count (the same terms as the automatic copies: due, not copied, «Tolto» and «Superato» left out, each file
/// once as the plan counts it).
/// </summary>
public static async Task<ExportAutomaticPreviewDto> AutomaticPreviewAsync(ExportAutomaticPreviewRequest body, ExportRootOptions root, IFebeStorage storage, IExportDisk disk, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(body);
ArgumentNullException.ThrowIfNull(root);
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(disk);
var exports = storage.Exports;
switch (body.Mode?.Trim().ToLowerInvariant())
{
case "switchon":
{
// «Solo i nuovi / Copia anche gli N»: the destination as the dialog has it now, its copies only while the
// folder stays the same (a new folder is a new destination, with no copies, r.575).
var scope = ParseScope(body.Scope);
var accountId = scope == ExportScope.Account ? await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false) : (long?)null;
var stored = body.DestinationId is { } id ? await StoredAsync(exports, id, ct).ConfigureAwait(false) : null;
if (stored is not null && (stored.Scope != scope || stored.AccountId != accountId))
{
throw new BadRequestException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.");
}
var same = stored is not null && !stored.IsOrphan && SameFolder(root, body.Path, stored.RootPath);
var types = ParseTypes(body.Types);
var backlog = types == ContentTypes.None
? new ExportBacklog(0, 0)
: await exports.CountAutomaticBacklogAsync(new ExportBacklogQuery(scope, accountId, types, same ? stored!.Id : null, null), ct).ConfigureAwait(false);
var free = same ? await MeasureAsync(() => disk.FreeBytes(stored!.RootPath), ct).ConfigureAwait(false) : null;
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, SwitchOnText(backlog), free);
}
case "widen":
{
// Answer 55: no new question; the files of the added types saved since the same «dal» go by themselves.
var stored = await StoredAsync(exports, body.DestinationId ?? throw new BadRequestException("Manca la cartella delle copie."), ct).ConfigureAwait(false);
var added = ParseTypes(body.Types) & ~stored.ContentTypes;
if (!stored.Automatic || stored.IsOrphan || added == ContentTypes.None)
{
return new ExportAutomaticPreviewDto(0, 0, WidenText(0));
}
var before = await exports.CountAutomaticBacklogAsync(
new ExportBacklogQuery(stored.Scope, stored.AccountId, stored.ContentTypes, stored.Id, stored.AutomaticSince), ct).ConfigureAwait(false);
var after = await exports.CountAutomaticBacklogAsync(
new ExportBacklogQuery(stored.Scope, stored.AccountId, stored.ContentTypes | added, stored.Id, stored.AutomaticSince), ct).ConfigureAwait(false);
var files = Math.Max(0, after.Files - before.Files);
return new ExportAutomaticPreviewDto(files, Math.Max(0, after.Bytes - before.Bytes), WidenText(files));
}
case "removeown":
{
// «Usa la cartella generale» while the general folder is automatic: the account's files go there by themselves.
var accountId = await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false);
var username = (await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false))!.Username;
var general = await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false);
if (general is not { Automatic: true } || own is null)
{
return new ExportAutomaticPreviewDto(0, 0, string.Empty);
}
var backlog = await exports.CountAutomaticBacklogAsync(
new ExportBacklogQuery(ExportScope.General, accountId, general.ContentTypes, general.Id, general.AutomaticSince, accountId), ct).ConfigureAwait(false);
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, backlog.Files == 0 ? string.Empty : RemoveOwnText(backlog.Files, username));
}
case "account":
{
// «Esporta questo account» on again: what its automatic destination now copies of it by itself.
var accountId = await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false);
var destination = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false)
?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
if (destination is not { Automatic: true })
{
return new ExportAutomaticPreviewDto(0, 0, string.Empty);
}
var backlog = await exports.CountAutomaticBacklogAsync(
new ExportBacklogQuery(destination.Scope, accountId, destination.ContentTypes, destination.Id, destination.AutomaticSince), ct).ConfigureAwait(false);
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, backlog.Files == 0 ? string.Empty : AccountText(backlog.Files, ExportDestinations.Label(destination)));
}
default:
throw new BadRequestException("Domanda sconosciuta: switchOn, widen, removeOwn o account.");
}
}
/// <summary>«Copia anche i 12 già in libreria: circa 3,1 GB.», or that there is none.</summary>
public static string SwitchOnText(ExportBacklog backlog)
{
ArgumentNullException.ThrowIfNull(backlog);
return backlog.Files switch
{
0 => "Nessun file già in libreria da copiare qui.",
1 => $"Copia anche quello già in libreria: circa {ItalianText.Bytes(backlog.Bytes)}.",
var n => $"Copia anche i {ItalianText.Number(n)} già in libreria: circa {ItalianText.Bytes(backlog.Bytes)}.",
};
}
private static string WidenText(int files) => files switch
{
0 => "Nessun file in più da copiare da solo.",
1 => "1 file in più si copierà da solo.",
var n => $"{ItalianText.Number(n)} file in più si copieranno da soli.",
};
private static string RemoveOwnText(int files, string username) =>
$"{ItalianText.Count(files, "file", "file")} di {ItalianText.Handle(username)} {(files == 1 ? "andrà da solo" : "andranno da soli")} nella cartella generale.";
private static string AccountText(int files, string label) =>
$"{ItalianText.Count(files, "file", "file")} {(files == 1 ? "si copierà da solo" : "si copieranno da soli")} in {label}.";
private static async Task<long> AccountOfAsync(IFebeStorage storage, long? accountId, CancellationToken ct)
{
if (accountId is not { } id)
{
throw new BadRequestException("Manca l'account della cartella.");
}
return await storage.Accounts.GetAsync(id, ct).ConfigureAwait(false) is null
? throw new BadRequestException("Account sconosciuto.")
: id;
}
private static async Task<ExportDestination> StoredAsync(IExportStore exports, long id, CancellationToken ct)
{
var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa cartella delle copie non c'è più.");
return stored.IsRetired ? throw new BadRequestException("Questa cartella è stata tolta.") : stored;
}
/// <summary>The folder chosen in the dialog is the stored one (as <see cref="ExportDestinations.UpdateAsync"/> decides).</summary>
private static bool SameFolder(ExportRootOptions root, string? path, string stored)
{
if (string.IsNullOrWhiteSpace(path))
{
return false;
}
try
{
return ExportPaths.Same(ExportRoots.Resolve(root, path.Trim()), stored);
}
catch (ExportFolderException)
{
return false;
}
}
private static string RunKind(ExportRunKind kind) => kind == ExportRunKind.Recognize ? "recognize" : "copy";
private static string RunOrigin(ExportRunOrigin origin) => origin == ExportRunOrigin.Automatic ? "automatic" : "manual";
/// <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
? start.Plan.NotStill > 0 && start.Plan.Files == 0
? StillVideoText.NotStill + ": niente da copiare."
: "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria."
: "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione.");
private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary<long, string> labels, IClock clock, bool running)
{
var now = clock.Now;
return new ExportRunDto(
run.Id,
run.DestinationId,
labels.TryGetValue(run.DestinationId, out var label) ? label : "Cartella tolta",
RunKind(run.Kind),
RunOrigin(run.Origin),
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,
};
}