using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Export; using Febe.Web.Library; using Febe.Web.Native; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.WebUtilities; namespace Febe.Web.Api; /// /// The copies to external folders (spec §4.10, §10.3, tappa E2) over : 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. /// public static class ExportApi { /// Title of the native folder picker for a destination. public const string PickTitle = "Scegli la cartella delle copie"; /// The most files a «Copia in…» can name one by one (a larger choice goes through the filter). public const int MaxIds = 50_000; private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10); 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) => { var service = await hub.GetAsync(ct).ConfigureAwait(false); var root = hub.RootFor(context); var d = SettingsApi.Deps.From(services); var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock); var state = ExportRoots.Evaluate(root); var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); var mapped = new List(destinations.Count); foreach (var destination in destinations) { var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); mapped.Add(Destination(destination, names, counts, root, clock)); } var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); var active = service.ActiveRunIds; var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; return ApiHttp.Json( new ExportOverviewDto( new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder), SamePost(settings.SamePost), mapped.FirstOrDefault(x => x.Scope == "general"), [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)], active, unfinished, new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)), FebeJsonContext.Default.ExportOverviewDto); }); endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false); var samePost = body.SamePost?.Trim().ToLowerInvariant() switch { "oneperaccount" => SamePostCopies.OnePerAccount, "oneonly" => SamePostCopies.OneOnly, _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."), }; var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, null, "export")); return ApiHttp.Message(samePost == SamePostCopies.OneOnly ? "Fatto: lo stesso post in due account si copia una volta sola." : "Fatto: lo stesso post in due account si copia una volta per ciascun account."); }); 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)), 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)), 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 present = []; foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType().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."); } if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant)) { 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»). var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0]; var service = await hub.GetAsync(ct).ConfigureAwait(false); var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false); 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(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>(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))], [.. report.Problems.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"; /// The wire names of the content types of a destination, in the order of the dialog. public static IReadOnlyList TypeNames(ContentTypes types) { var names = new List(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", }; /// Copies per state with every state present. public static IReadOnlyDictionary CopyCounts(IReadOnlyDictionary counts) { ArgumentNullException.ThrowIfNull(counts); return Enum.GetValues().ToDictionary(CopyState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); } /// Files of a job per state with every state present. public static IReadOnlyDictionary ItemCounts(IReadOnlyDictionary counts) { ArgumentNullException.ThrowIfNull(counts); return Enum.GetValues().ToDictionary(ItemState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); } /// The path of a folder as shown to Alberto (relative to /esporta in Docker). 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 usernames, IReadOnlyDictionary 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); } /// A destination with its counts, read from the database. public static async Task 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(); 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); } /// «Copie esterne» of the account card (decisions D1-D3 of tappa E2). public static async Task 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) { 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); } /// The request of a «Copia in…»: exactly one selection. 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); } return new ExportJobRequest(selection, body.CopyAgain); } // ---------------------------------------------------------------------------------------------- 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? 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); private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); private static List Ids(IReadOnlyList 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) => new( [.. start.Runs.Select(r => r.Id)], Plan(start.Plan, root), 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 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 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> UsernamesAsync(IFebeStorage storage, CancellationToken ct) => (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); /// Names of every destination, retired ones included (old jobs keep their name). private static async Task> LabelsAsync(IFebeStorage storage, CancellationToken ct) => (await storage.Exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id, ExportDestinations.Label); /// Docker with /esporta not declared or not mounted: nothing can be written (decision D14 of tappa E2). private static void EnsureActive(ExportHub hub) { if (ExportRoots.Evaluate(hub.Root) is { Active: false, Problem: { } problem }) { throw new BadRequestException(problem); } } /// A measure of a disk that may not answer (a disconnected share): null after the timeout. private static async Task MeasureAsync(Func 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 ExistsAsync(string folder, CancellationToken ct) { try { return await Task.Run(() => Directory.Exists(folder), ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false); } catch (TimeoutException) { return false; } } // ---------------------------------------------------------------------------------------------- errors /// The export's own exceptions become Italian answers: 400 for a refused request, 404 for something missing. internal static T Guard(Func action) { try { return action(); } catch (Exception ex) when (Translate(ex) is { } translated) { throw translated; } } internal static async Task GuardAsync(Func> 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, }; }