diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs index ae3047b..7ba4b2d 100644 --- a/src/Febe.Web/Api/ExportApi.cs +++ b/src/Febe.Web/Api/ExportApi.cs @@ -1,3 +1,5 @@ +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Export; @@ -31,8 +33,16 @@ public static class ExportApi /// The most files a «Copia in…» can name one by one (a larger choice goes through the filter). public const int MaxIds = 50_000; + /// The answer of «Riconosci le copie già presenti» (tappa E5). + 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); + /// How long the count of the files waiting for an automatic destination in pause is kept (). + private static readonly TimeSpan WaitingKept = TimeSpan.FromMinutes(1); + + private static readonly ConditionalWeakTable> WaitingCache = new(); + /// /// 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. @@ -178,7 +188,9 @@ public static class ExportApi 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); + 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); }); @@ -188,7 +200,9 @@ public static class ExportApi 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); + 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); }); @@ -196,11 +210,14 @@ public static class ExportApi 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); + 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); }); @@ -240,6 +257,38 @@ public static class ExportApi 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); @@ -321,9 +370,14 @@ public static class ExportApi 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) + 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; + 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( @@ -339,14 +393,19 @@ public static class ExportApi progress.DestinationLabel, ItemCounts(progress.ByState), service.IsBusy, - error), + error, + kind is { } k ? RunKind(k) : null, + origin is { } o ? RunOrigin(o) : null), FebeJsonContext.Default.ExportProgressDto); }); - endpoints.MapGet("/api/export/runs", async (int? limit, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + 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); - var runs = await storage.Exports.ListRecentRunsAsync(Math.Clamp(limit ?? 20, 1, 100), 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(runs.Count); @@ -359,11 +418,14 @@ public static class ExportApi return ApiHttp.Json>(list, FebeJsonContext.Default.IReadOnlyListExportRunDto); }); - endpoints.MapPost("/api/export/interrupt", async (ExportHub hub, CancellationToken ct) => + endpoints.MapPost("/api/export/interrupt", async (ExportHub hub, IClock clock, 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."); + // 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) => @@ -410,7 +472,9 @@ public static class ExportApi 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.Notes.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))], + report.NotFound, + report.Different), FebeJsonContext.Default.ExportReportDto); }); } @@ -500,12 +564,14 @@ public static class ExportApi IClock clock, bool? reachable = null, long? freeBytes = null, - string? problem = 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), @@ -527,14 +593,17 @@ public static class ExportApi destination.IsOrphan, destination.RemovedAccountUsername, destination.PhotoFormat is { } photo ? FormatName(photo) : null, - destination.VideoFormat is { } video ? FormatName(video) : null); + destination.VideoFormat is { } video ? FormatName(video) : null, + since is { } from ? ApiMapping.Local(from, now, clock.LocalZone) : null, + waiting); } - /// A destination with its counts, read from the database. + /// A destination with its counts (and, in pause, the files that wait for it), 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); + ArgumentNullException.ThrowIfNull(clock); 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) @@ -542,7 +611,49 @@ public static class ExportApi names[accountId] = account.Username; } - return Destination(destination, names, counts, root, clock); + 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); + } + + /// + /// 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. + /// + public static async Task WaitingAsync(IFebeStorage storage, ExportDestination destination, IReadOnlyList 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()); + 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); } /// «Copie esterne» of the account card (decisions D1-D3 of tappa E2). @@ -902,18 +1013,25 @@ public static class ExportApi 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(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 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; - var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); + + // 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), @@ -926,9 +1044,183 @@ public static class ExportApi FormatName(settings.VideoFormat), FormatName(settings.LibraryPhotoFormat), FormatName(settings.LibraryVideoFormat), - worker is null ? null : await ConversionAsync(storage, worker, ct).ConfigureAwait(false)); + worker is null ? null : await ConversionAsync(storage, worker, ct).ConfigureAwait(false), + automatic); } + /// The automatic copies as the Dashboard shows them (tappa E5); the hold is the service's own. + public static async Task 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)); + } + + /// + /// POST /api/export/automatic-preview (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). + /// + public static async Task 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."); + } + } + + /// «Copia anche i 12 già in libreria: circa 3,1 GB.», or that there is none. + 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 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 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; + } + + /// The folder chosen in the dialog is the stored one (as decides). + 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"; + /// The request of a «Copia in…»: exactly one selection. public static ExportJobRequest Request(CopyJobRequestDto body, IClock clock) { @@ -1056,8 +1348,8 @@ public static class ExportApi 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", + 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, diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs index 6571d9e..0e1ad95 100644 --- a/src/Febe.Web/Api/ExportDtos.cs +++ b/src/Febe.Web/Api/ExportDtos.cs @@ -22,7 +22,10 @@ public sealed record ExportSchemesDto(string General, string Highlight, string P /// of its pause (or, with /status, why it does not answer now). : copies per state /// (copied, removed, superseded, failed). and /// only from /status. : an own folder whose account was -/// removed («era di @»). +/// removed («era di @»). Tappa E5: is «Automatica», +/// its «Solo i nuovi» instant («Automatica dal …»; null with «Copia anche quelli già +/// in libreria» or when it is off); , only for a destination in pause, the files that wait for +/// it: what it would copy by itself when it is automatic, else what its unfinished jobs still have to copy. /// public sealed record ExportDestinationDto( long Id, @@ -45,14 +48,18 @@ public sealed record ExportDestinationDto( bool Orphan = false, string? FormerUsername = null, string? PhotoFormat = null, - string? VideoFormat = null); + string? VideoFormat = null, + LocalTimeDto? AutomaticSince = null, + int? Waiting = null); /// /// GET /api/export: Impostazioni → Esportazione and the notice of the Dashboard. : -/// onePerAccount or oneOnly. : interrupted or paused jobs («Riprendi»). +/// onePerAccount or oneOnly. : interrupted or paused jobs of Alberto +/// («Riprendi»); the automatic ones resume by themselves and are not counted (tappa E5). /// Formats (tappa E3) on the wire: original, jpg, png, webplossless, mp4; the /// library ones are original while the conversion of the library is off. : -/// the state of that conversion. +/// the state of that conversion. : the automatic copies (tappa E5), null when they do not +/// run (the demonstration, a start with problems). /// public sealed record ExportOverviewDto( ExportRootDto Root, @@ -66,7 +73,46 @@ public sealed record ExportOverviewDto( string VideoFormat = "original", string LibraryPhotoFormat = "original", string LibraryVideoFormat = "original", - LibraryConversionDto? LibraryConversion = null); + LibraryConversionDto? LibraryConversion = null, + ExportAutomaticStatusDto? Automatic = null); + +/// +/// The automatic copies now (tappa E5, spec §4.10): a destination in use has «Automatica» +/// on; why they wait (an engine session, an import, a copy of Alberto's…), or null; +/// and of the recovery round («giro di recupero», at start-up and +/// every hour); : «Interrompi» stopped them until then («Riprendi ora»). +/// +public sealed record ExportAutomaticStatusDto(bool AnyAutomatic, string? Waiting, LocalTimeDto? LastRound, LocalTimeDto? NextRound, LocalTimeDto? HeldUntil); + +/// +/// POST /api/export/automatic-preview (tappa E5): how many files an automatic destination would copy by itself. +/// : +/// switchOn, the question «Solo i nuovi / Copia anche gli N già in libreria» when «Automatica» is turned on (the +/// destination as the dialog has it: , , , +/// ; the copies of count only while the folder stays the same); +/// widen, the files in more when add types to the automatic destination +/// ; +/// removeOwn, the files of that go by themselves to the automatic general folder +/// once its own folder is taken away; +/// account, the files of that its automatic destination copies by itself +/// («Esporta questo account» turned on again). +/// +public sealed record ExportAutomaticPreviewRequest( + string Mode, + long? DestinationId = null, + string? Scope = null, + long? AccountId = null, + string? Path = null, + IReadOnlyList? Types = null); + +/// +/// What POST /api/export/automatic-preview counted: , the bytes of their originals +/// («circa»), the line to show and, for a stored folder, its free space (null when unknown). +/// +public sealed record ExportAutomaticPreviewDto(int Files, long Bytes, string Text, long? FreeBytes = null); + +/// «Riconosci le copie già presenti» started (tappa E5): the message and the job. +public sealed record ExportRecognizeStartedDto(string Message, long RunId); /// /// The conversion of the library (tappa E3, spec §4.10): files in the queue, converted, failed («Riprova»), that never @@ -116,7 +162,8 @@ public sealed record ExportNamingPreviewRequest(string Scope, string? General, s /// /// A destination to add or change. : in Docker the folder relative to /esporta (as listed), /// elsewhere the full path. : wire names, at least one. Null or empty schemes: «Come la -/// libreria». «Automatica» is stored only (tappa E5 acts on it). +/// libreria». : «Automatica» (tappa E5); is the answer when it is +/// turned on («Solo i nuovi»; false: «Copia anche quelli già in libreria»), kept while it stays on. /// public sealed record ExportDestinationRequest( string Scope, @@ -217,7 +264,9 @@ public sealed record CopyAgainRequest(long CopyId); /// /// GET /api/export/progress, polled by the Dashboard tab. : preparing, checking, -/// waitingForSession, copying, finished. : files of the job per state. +/// waitingForSession, copying, finished. : files of the job per state. Tappa E5, from the job +/// being worked on: copy or recognize (null for «Controlla le copie»), +/// manual or automatic. /// public sealed record ExportProgressDto( long? RunId, @@ -231,7 +280,9 @@ public sealed record ExportProgressDto( string? Destination, IReadOnlyDictionary ByState, bool Running, - string? Error); + string? Error, + string? Kind = null, + string? Origin = null); /// An export job. : copy or recognize; : manual or automatic. public sealed record ExportRunDto( @@ -259,7 +310,9 @@ public sealed record ExportReportLineDto(long ItemId, string Username, string? P /// /// The report of a job (at most 200 problems). (tappa E3): files copied or adopted with a note -/// (what a conversion could not keep, a file copied as it is), at most 200. +/// (what a conversion could not keep, a file copied as it is), at most 200. Tappa E5, for «Riconosci le copie già +/// presenti»: of the skipped files, are not in the folder and +/// have another file where the copy would be (those are problems; the ones not found are not). /// public sealed record ExportReportDto( ExportRunDto Run, @@ -267,7 +320,9 @@ public sealed record ExportReportDto( long BytesCopied, IReadOnlyList Accounts, IReadOnlyList Problems, - IReadOnlyList? Notes = null); + IReadOnlyList? Notes = null, + int NotFound = 0, + int Different = 0); /// /// A copy of a file of the viewer (spec §4.6, §4.10). : copied, removed, superseded, failed; diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 6ee50f6..329d53e 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -108,6 +108,9 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(ExportSettingsSavedDto))] [JsonSerializable(typeof(LibraryConversionDto))] [JsonSerializable(typeof(LibraryConversionPreviewDto))] +[JsonSerializable(typeof(ExportAutomaticPreviewRequest))] +[JsonSerializable(typeof(ExportAutomaticPreviewDto))] +[JsonSerializable(typeof(ExportRecognizeStartedDto))] [JsonSerializable(typeof(FrameInfoDto))] [JsonSerializable(typeof(FrameInstantsDto))] [JsonSerializable(typeof(FramesSelectionRequest))] diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index cddfaba..0e76c66 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -1202,6 +1202,25 @@ p.aiuto.descrizione-copie{margin-top:8px} .copie-esterne .conteggio-copie{margin-top:12px} .copie-esterne .etichetta-copie{margin:14px 0 6px} .etichetta-copie + .cartella{margin-top:0} +/* tappa E5: «Automatica», «Riconosci le copie già presenti», le copie automatiche nella Dashboard */ +.azioni-copie{display:flex;gap:8px;flex-wrap:wrap} +.azioni-cartella .riga-conteggi > span{min-width:180px} +.azioni-cartella .pausa-copie{margin-top:10px} +.azioni-cartella .pausa-copie .aspettano{font-weight:600} +.azioni-cartella .pausa-giro{margin:6px 0 0} +.azioni-cartella.compatte{display:flex;flex-direction:column;align-items:flex-start;gap:4px} +.azioni-cartella.compatte .azioni-copie{gap:0;margin-left:-11px} +.azioni-cartella.compatte p{margin:0} +.riga-pausa{display:flex;align-items:center;gap:6px} +.riga-etichetta{display:flex;align-items:center;gap:8px} +.riga-etichetta .etichetta{margin:0} +.blocco-riga{display:block;margin-top:2px;font-size:12.5px;color:var(--testo-2)} +.parte-automatica .leva-automatica{margin:10px 0 4px} +.automatica-scelta .domanda-automatica{margin:12px 0 0;font-size:13.5px} +.automatica-scelta > p{margin:8px 0 0} +.dialogo .scelte small.avviso-testo{color:var(--ambra)} +.stato-automatiche{margin-top:8px} +.togli-automatica{margin-top:8px} .vis .scheda dd.riga-copia{display:flex;align-items:center;gap:4px 8px;flex-wrap:wrap} .vis .scheda dd.riga-copia .btn{height:26px;padding:0 8px;margin-left:-8px} .tess .segno .copia.parte{font-variant-numeric:tabular-nums} diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 0a477ee..ce168d8 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -19,7 +19,7 @@ import { confirmDelete, selectionBar } from './library.js'; import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js'; import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { openViewer } from './viewer.js'; -import { copiesApi, copiesLabel, copiesMenu, copyDialog, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js'; +import { automaticLabel, copiesApi, copiesLabel, copiesMenu, copyDialog, destinationActions, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js'; import { framesDialog } from './frames.js'; import { stillVideosDialog } from './still-videos.js'; @@ -595,6 +595,8 @@ function settingsTab(page, detail) { /** * «Copie esterne» (spec §4.10, mockup 05): «Esporta questo account», which acts at once and is not part of the form * (decision D1: on unless switched off), where the copies go, how many files are still to copy and «Copia in…». + * Tappa E5: «Automatica» on the folder where the copies go; for a folder of its own, its state with «Riprova», + * «Controlla le copie» and «Riconosci le copie già presenti»; turned on again, how many files go there by themselves. */ function copiesBlock(page, detail) { const account = detail.account; @@ -610,6 +612,7 @@ function copiesBlock(page, detail) { const result = await api(`/api/accounts/${account.id}/export-enabled`, { method: 'POST', body: { value } }); toast(result.message); await reload(); + if (value && data.destination && data.destination.automatic) announceAutomatic(); } catch (error) { input.checked = !value; showError(error); @@ -619,6 +622,16 @@ function copiesBlock(page, detail) { }, }); + /** On again with an automatic folder (answer 55): how many of its files now go there by themselves. */ + async function announceAutomatic() { + try { + const preview = await api('/api/export/automatic-preview', { method: 'POST', body: { mode: 'account', accountId: account.id } }); + if (preview.files) toast(preview.text); + } catch (error) { + // Only a notice: the switch is already on. + } + } + async function reload() { try { const fresh = await api(`/api/accounts/${account.id}`, { signal: page.signal }); @@ -631,7 +644,7 @@ function copiesBlock(page, detail) { } async function chooseOwn() { - const saved = await destinationDialog({ scope: 'account', accountId: account.id, username: account.username, destination: data.hasOwnFolder ? data.destination : null }); + const saved = await destinationDialog({ scope: 'account', accountId: account.id, username: account.username, destination: data.hasOwnFolder ? data.destination : null, accountEnabled: data.enabled }); if (saved) await reload(); } @@ -647,9 +660,21 @@ function copiesBlock(page, detail) { return; } const fallback = Boolean(overview.general); + // The general folder automatic (answer 55): the files of the account that will go there by themselves. + let extra = null; + if (fallback && overview.general.automatic && data.enabled) { + try { + const preview = await api('/api/export/automatic-preview', { method: 'POST', body: { mode: 'removeOwn', accountId: account.id } }); + if (preview.files) extra = h('p.aiuto.togli-automatica', icon('refresh-cw', 'xs'), ' ', t('esportazione.automatica.togliPropria', { n: preview.files, nome: account.username })); + } catch (error) { + showError(error); + return; + } + } const ok = await confirmDialog({ title: t(fallback ? 'esportazione.account.usaGeneraleTitolo' : 'esportazione.account.togliTitolo', { nome: account.username }), text: t(fallback ? 'esportazione.account.usaGeneraleTesto' : 'esportazione.account.togliTesto'), + extra, buttons: [ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true }, { label: t(fallback ? 'esportazione.account.usaGenerale' : 'esportazione.togliSi'), value: true, kind: fallback ? 'primo' : 'pericolo' }, @@ -671,14 +696,18 @@ function copiesBlock(page, detail) { if (d) { const where = data.hasOwnFolder ? d.display : `${d.display}${separator(d.display)}${account.username}`; // The kind of folder goes above the field, like the labels of mockup 08: the path keeps the whole width. - rows.push(h('span.etichetta.etichetta-copie', t(data.hasOwnFolder ? 'esportazione.account.sua' : 'esportazione.account.generale'))); + rows.push(h('div.etichetta-copie.riga-etichetta', + h('span.etichetta', t(data.hasOwnFolder ? 'esportazione.account.sua' : 'esportazione.account.generale')), + d.automatic ? automaticLabel(d) : null)); rows.push(h('div.cartella', h('div.campo.sola', { title: where }, icon('hard-drive', 's'), h('span.val.dati', where)), data.hasOwnFolder ? [h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.modifica')), h('button.btn.nudo', { type: 'button', onclick: useGeneral }, t('esportazione.account.usaGenerale'))] : h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.account.scegliSua')))); - if (d.pausedAt || d.problem) { + if (data.hasOwnFolder) { + rows.push(destinationActions(d, { onChange: reload })); + } else if (d.pausedAt || d.problem) { rows.push(h('div.avviso.ambra', { style: { marginTop: '10px' } }, icon('pause', 's'), h('span', t('esportazione.pausa', { problema: d.problem || '' })))); } } else { diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js index ec212bd..73ce4a1 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js @@ -6,6 +6,11 @@ // copied as they are per account and the «Note» (what a conversion could not keep, a file copied as it is). // Tappa E4: the card «Video fermi» while «Cerca i video fermi» works (progress, why it waits, «Interrompi») and, until // Febe closes, what the last one found. +// Tappa E5: the automatic copies. Under «Nessuna copia al lavoro» one line says why they wait, until when «Interrompi» +// stopped them («Riprendi ora»), or when the next recovery round runs (never in the demonstration, which runs none); +// the job at work is named «Copia automatica in …», «Riconoscimento delle copie in …» or «Controllo delle copie»; +// «Da riprendere» lists every unfinished job, the automatic ones with their label and when they resume by themselves, +// and a copy of Alberto's in pause whose folder answers again says so (it waits for «Riprendi», answer 48). import { api, withCarried } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; @@ -35,7 +40,9 @@ export async function mountExport(page) { let overview = null; let runs = []; + let unfinished = []; let progress = null; + let drawnCurrent = ''; let stillJob = null; let drawnStills = ''; let wasRunning = null; @@ -52,10 +59,12 @@ export async function mountExport(page) { async function loadSide() { try { - [overview, runs] = await Promise.all([ + [overview, runs, unfinished] = await Promise.all([ api('/api/export', { signal: page.signal }), api('/api/export/runs?limit=20', { signal: page.signal }), + api('/api/export/runs?unfinished=true', { signal: page.signal }), ]); + drawCurrent(); drawPending(); drawConversion(); drawRecent(); @@ -123,17 +132,27 @@ export async function mountExport(page) { const p = progress; const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.inCorso'))); if (!p || !p.running) { - fill(current, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.nessunaInCorso'))); + // Drawn again only when it changes: «Riprendi ora» keeps the focus of the keyboard between readings. + const auto = overview && overview.automatic && overview.automatic.anyAutomatic ? overview.automatic : null; + const drawn = JSON.stringify({ idle: true, auto }); + if (drawn === drawnCurrent) return; + drawnCurrent = drawn; + const focused = current.contains(document.activeElement); + fill(current, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.nessunaInCorso')), auto ? automaticLine(auto) : null); + const button = focused && current.querySelector('button:not([disabled])'); + if (button) button.focus(); return; } + drawnCurrent = ''; const percent = Math.round((p.fraction || 0) * 100); - const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(percent), 'aria-label': t('esportazione.dashboard.copio', { cartella: p.destination || '' }) }, + const title = currentName(p); + const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(percent), 'aria-label': title }, h('i', { style: { width: `${percent}%` } })); const phase = p.phase && p.phase !== 'copying' && p.phase !== 'finished' ? t(`esportazione.dashboard.fasi.${p.phase}`) : ''; const count = [t('esportazione.dashboard.fatti', { fatti: number(p.filesDone), totale: number(p.filesTotal) })]; if (p.bytesTotal) count.push(t('esportazione.dashboard.byte', { fatti: bytes(p.bytesDone), totale: bytes(p.bytesTotal) })); fill(current, head, h('div.pannello.avanzamento-import.avanzamento-copia', - h('h2.sez', t('esportazione.dashboard.copio', { cartella: p.destination || '' })), + h('h2.sez', title, p.origin === 'automatic' ? [' ', label(t('esportazione.automatica.etichetta'), 'accento', 'refresh-cw')] : null), bar, h('p.conteggio.dati', count.join(' · ')), phase ? h('p.avviso.ambra.fase-copia', icon(p.phase === 'waitingForSession' ? 'hourglass' : 'info', 's'), h('span', phase)) : null, @@ -141,6 +160,39 @@ export async function mountExport(page) { h('div.riga-azione', h('button.btn', { type: 'button', onclick: interrupt }, icon('pause', 's'), t('esportazione.dashboard.interrompi'))))); } + /** «Copia automatica in …», «Riconoscimento delle copie in …», «Controllo delle copie in …» or «Copio in …». */ + function currentName(p) { + const cartella = p.destination || ''; + if (!p.kind) return t(p.runId == null ? 'esportazione.dashboard.lavoroControllo' : 'esportazione.dashboard.copio', { cartella }); + if (p.kind === 'recognize') return t('esportazione.dashboard.lavoroRiconosci', { cartella }); + if (p.origin === 'automatic') return t('esportazione.dashboard.lavoroAutomatico', { cartella }); + return t('esportazione.dashboard.copio', { cartella }); + } + + /** The line of the automatic copies: why they wait, until when they are stopped («Riprendi ora»), the next round. */ + function automaticLine(auto) { + if (auto.heldUntil) { + return h('div.riga-conteggi.stato-automatiche', + h('span.muto', icon('pause', 'xs'), ' ', t('esportazione.dashboard.automatica.ferme', { quando: at(auto.heldUntil) })), + h('button.btn.piccolo', { type: 'button', onclick: resumeAutomatic }, icon('play', 's'), t('esportazione.dashboard.automatica.riprendiOra'))); + } + if (auto.waiting) return h('p.aiuto.stato-automatiche', icon('hourglass', 'xs'), ' ', auto.waiting); + return auto.nextRound + ? h('p.aiuto.stato-automatiche', icon('refresh-cw', 'xs'), ' ', t('esportazione.dashboard.automatica.prossimoGiro', { quando: at(auto.nextRound) })) + : null; + } + + async function resumeAutomatic(e) { + e.currentTarget.disabled = true; + try { + const result = await api('/api/export/automatic/resume', { method: 'POST' }); + toast(result.message); + } catch (error) { + showError(error); + } + again(); + } + async function interrupt(e) { e.currentTarget.disabled = true; try { @@ -154,8 +206,10 @@ export async function mountExport(page) { // ------------------------------------------------------------------------------------------- da riprendere function drawPending() { - const waiting = runs.filter((r) => !r.running && (r.state === 'interrupted' || r.state === 'paused')); + const waiting = unfinished.filter((r) => !r.running && (r.state === 'interrupted' || r.state === 'paused')); const folders = overview ? [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem)) : []; + const pausedIds = new Set(folders.map((d) => d.id)); + const auto = overview && overview.automatic; pending.hidden = !waiting.length && !folders.length; if (pending.hidden) { pending.replaceChildren(); @@ -166,16 +220,31 @@ export async function mountExport(page) { h('div.testa-blocco', h('h2', t('esportazione.dashboard.daRiprendere')), waiting.length > 1 ? h('div.destra', h('button.btn.piccolo', { type: 'button', disabled: busy, onclick: resumeAll }, icon('play', 's'), t('esportazione.dashboard.riprendiTutte'))) : null), folders.map((d) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), - h('span', t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') })), + h('span', t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') }), + auto ? h('small.blocco-riga', t('esportazione.pausaGiro')) : null), h('button.btn.piccolo', { type: 'button', onclick: (e) => retry(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.riprova')))), waiting.map((r) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), - h('span', r.state === 'paused' - ? t('esportazione.dashboard.ferma', { cartella: r.destination, problema: r.error || t('esportazione.inPausa') }) - : t('esportazione.dashboard.interrotta', { cartella: r.destination, fatti: number(r.done), totale: number(r.total) })), + h('span', r.origin === 'automatic' ? [label(t('esportazione.automatica.etichetta'), 'accento', 'refresh-cw'), ' '] : null, + pendingText(r, pausedIds), + r.origin === 'automatic' && auto ? h('small.blocco-riga', resumesText(r, auto)) : null), h('button.btn.primo.piccolo', { type: 'button', disabled: busy, onclick: (e) => resume(r, e.currentTarget) }, icon('play', 's'), t('esportazione.dashboard.riprendi')), h('button.btn.nudo.piccolo', { type: 'button', onclick: () => discard(r) }, t('esportazione.dashboard.annulla'))))); } + function pendingText(r, pausedIds) { + if (r.state !== 'paused') return t('esportazione.dashboard.interrotta', { cartella: r.destination, fatti: number(r.done), totale: number(r.total) }); + // A copy of Alberto's stays his when the folder answers again (answer 48): it says so, and waits for «Riprendi». + if (r.origin !== 'automatic' && !pausedIds.has(r.destinationId)) return t('esportazione.dashboard.fermaPronta', { cartella: r.destination }); + return t('esportazione.dashboard.ferma', { cartella: r.destination, problema: r.error || t('esportazione.inPausa') }); + } + + /** When an automatic job resumes by itself: after the hold, at the next round (in pause or stopped by an error), or soon. */ + function resumesText(r, auto) { + if (auto.heldUntil) return t('esportazione.automatica.riprendeDaSola', { quando: at(auto.heldUntil) }); + if ((r.state === 'paused' || r.error) && auto.nextRound) return t('esportazione.automatica.riprendeDaSola', { quando: at(auto.nextRound) }); + return t('esportazione.automatica.riprendeFraPoco'); + } + async function resume(run, button) { button.disabled = true; try { @@ -321,7 +390,7 @@ export async function mountExport(page) { return h('li', h('span.quando.dati', capitalize(at(r.startedAt))), h('div.chi-cosa', - h('b', jobName(r)), + h('b', jobName(r), r.origin === 'automatic' ? [' ', label(t('esportazione.automatica.etichetta'), 'accento', 'refresh-cw')] : null), h('span', [t('esportazione.dashboard.fatti', { fatti: number(r.done), totale: number(r.total) }), r.error].filter(Boolean).join(' · '))), label(t(`esportazione.dashboard.stati.${state}`), kind, look), h('button.btn.piccolo', { type: 'button', onclick: () => openReport(r) }, t('esportazione.dashboard.resoconto'))); @@ -337,7 +406,10 @@ export async function mountExport(page) { } function jobName(run) { - return t(run.kind === 'recognize' ? 'esportazione.dashboard.lavoroControllo' : 'esportazione.dashboard.lavoroCopia', { cartella: run.destination }); + let key = 'esportazione.dashboard.lavoroCopia'; + if (run.kind === 'recognize') key = 'esportazione.dashboard.lavoroRiconosci'; + else if (run.origin === 'automatic') key = 'esportazione.dashboard.lavoroAutomatico'; + return t(key, { cartella: run.destination }); } /** The resoconto of a job: files per state, per account, and the files that need a look (at most 200). */ @@ -353,6 +425,9 @@ async function openReport(run) { const when = [t('esportazione.dashboard.iniziata', { quando: at(r.startedAt) })]; if (r.completedAt) when.push(t('esportazione.dashboard.finita', { quando: at(r.completedAt) })); const states = FILE_STATES.filter((s) => report.byState[s]).map((s) => t(`esportazione.dashboard.statiFile.${s}`, { n: report.byState[s] })); + // Tappa E5, «Riconosci le copie già presenti»: of the skipped files, those not in the folder and those different there. + if (report.notFound) states.push(t('esportazione.dashboard.statiFile.notFound', { n: report.notFound })); + if (report.different) states.push(t('esportazione.dashboard.statiFile.different', { n: report.different })); if (report.bytesCopied) states.push(t('esportazione.dashboard.copiatiByte', { spazio: bytes(report.bytesCopied) })); // Tappa E3: the files copied as they are, per kind («3 HEIC»), in a column only when some job file was. const asIsText = (a) => Object.entries(a.asIs || {}).filter(([, n]) => n).map(([kind, n]) => `${number(n)} ${kind}`).join(', '); diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js index 0be5ec6..f3c93ef 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js @@ -695,7 +695,9 @@ function drawExportNotice(box, overview) { box.replaceChildren(); return; } - const paused = [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem)); + // A folder in pause only while something waits for it (tappa E5): a stick that is usually unplugged does not keep the + // notice on for nothing. + const paused = [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem) && d.waiting !== 0); const items = paused.map((d) => t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') })); if (!paused.length && overview.unfinishedRuns) items.push(t('esportazione.dashboard.avvisoDaRiprendere', { n: overview.unfinishedRuns })); fill(box, items.map((text) => h('div.avviso.ambra.avviso-azione', { style: { marginBottom: '10px' } }, icon('pause', 's'), diff --git a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js index 494ec72..b99a752 100644 --- a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js +++ b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js @@ -4,12 +4,16 @@ // destination, «Copia di nuovo anche i N tolti o superati» unchecked), the menu of the CSV icon and the «Copie» filter. // Tappa E3: the formats (the destination's «Formati» with «Come le impostazioni generali» first; the row «Formato: come // la destinazione · Cambia» of «Copia in…», whose summary says what is copied as it is and «con perdita»). -// «Automatica» is not shown: tappa E5 acts on it (decision D8 of E2). +// Tappa E5: «Automatica» in the destination dialog (turned on, or on with a new folder, it asks «Solo i nuovi» or +// «Copia anche i N già in libreria»; with more types it says how many files more go by themselves; turned off while it +// copies it says that the copy stops), and the state of a folder shared by Impostazioni and the account card: the +// pause «dal …» with the files that wait and «Riprova», the counts, «Controlla le copie» and «Riconosci le copie già +// presenti». import { api } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; -import { t, bytes } from '../core/text.js'; -import { checkbox, dialog, menu, radio, segmented, showError, toast } from '../core/ui.js'; +import { t, bytes, shortDay } from '../core/text.js'; +import { checkbox, dialog, label, menu, radio, segmented, showError, toast, toggle } from '../core/ui.js'; import { formatLabel } from './frames.js'; /** The formats of the copies by kind (wire names, decision D21), «Originale» first. */ @@ -116,13 +120,105 @@ export function countsText(counts) { return parts.join(' · '); } -/** «Tipi: post foto, storie · nomi come la libreria». */ +/** «Tipi: post foto, storie · nomi come la libreria», and « · Automatica dal 4 dicembre» (tappa E5). */ export function describe(destination) { const types = destination.types.length === TYPES.length ? t('esportazione.tuttiITipi') : destination.types.map((k) => t(`esportazione.tipi.${k}`).toLowerCase()).join(', '); const own = destination.namingScheme || destination.highlightNamingScheme || destination.profileNamingScheme; - return `${t('esportazione.tipiScelti', { elenco: types })} · ${t(own ? 'esportazione.nomiSuoi' : 'esportazione.nomiLibreria')}`; + const parts = [t('esportazione.tipiScelti', { elenco: types }), t(own ? 'esportazione.nomiSuoi' : 'esportazione.nomiLibreria')]; + if (destination.automatic) parts.push(automaticText(destination)); + return parts.join(' · '); +} + +/** «Automatica dal 4 dicembre», or «Automatica» when it copies every due file. */ +export function automaticText(destination) { + return destination.automaticSince + ? t('esportazione.automatica.descrizione', { data: shortDay(destination.automaticSince.day) }) + : t('esportazione.automatica.etichetta'); +} + +/** The «Automatica» label of a folder (tappa E5). */ +export function automaticLabel(destination) { + return label(automaticText(destination), 'accento', 'refresh-cw'); +} + +/** «In pausa dal 3 dicembre: …» («da oggi», «da ieri»). */ +function pausedText(d) { + const problem = d.problem || ''; + const since = d.pausedAt; + if (!since) return t('esportazione.pausa', { problema: problem }); + if (since.dayDelta === 0) return t('esportazione.pausaDa', { giorno: t('tempo.oggi'), problema: problem }); + if (since.dayDelta === -1) return t('esportazione.pausaDa', { giorno: t('tempo.ieri'), problema: problem }); + return t('esportazione.pausaDal', { giorno: shortDay(since.day), problema: problem }); +} + +/** + * The state of a folder and what can be done with it (tappa E5, shared by Impostazioni → Esportazione and the account + * card): in pause, since when and why, how many files wait for it, «Riprova» and, when the automatic copies run, that + * Febe tries again by itself; then the counts of the copies with «Controlla le copie» and «Riconosci le copie già + * presenti». compact: the cell of a table (small buttons, the pause as a label). onChange: after «Riprova». + */ +export function destinationActions(d, { automatic = null, compact = false, onChange = null } = {}) { + const paused = Boolean(d.pausedAt || d.problem); + const retryButton = h(`button.btn.piccolo${compact ? '.nudo' : ''}`, { type: 'button', onclick: (e) => retryDestination(d, e.currentTarget, onChange) }, icon('rotate-cw', 's'), t('esportazione.riprova')); + const buttons = [ + h(`button.btn.piccolo${compact ? '.nudo' : ''}`, { type: 'button', title: t('esportazione.controllaAiuto'), onclick: (e) => checkCopies(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.controlla')), + d.orphan ? null : h(`button.btn.piccolo${compact ? '.nudo' : ''}`, { type: 'button', title: t('esportazione.riconosciAiuto'), onclick: (e) => recognizeCopies(d, e.currentTarget) }, icon('search', 's'), t('esportazione.riconosci')), + ]; + const waiting = d.waiting ? t('esportazione.aspettano', { n: d.waiting }) : ''; + if (compact) { + return h('div.azioni-cartella.compatte', + paused ? h('div.riga-pausa', label(t('esportazione.inPausa'), 'ambra', 'pause'), retryButton) : null, + paused ? h('p.piccolo.muto', { title: d.problem || '' }, [pausedText(d), waiting].filter(Boolean).join(' ')) : null, + h('span.muto.piccolo', countsText(d.counts)), + h('div.azioni-copie', buttons)); + } + return h('div.azioni-cartella', + paused ? h('div.avviso.ambra.avviso-azione.pausa-copie', icon('pause', 's'), + h('span', pausedText(d), waiting ? h('span.aspettano', ` ${waiting}`) : null), + retryButton) : null, + paused && automatic ? h('p.aiuto.piccolo.pausa-giro', t('esportazione.pausaGiro')) : null, + h('div.stato-copie.riga-conteggi', + h('span.muto', countsText(d.counts)), + h('div.azioni-copie', buttons))); +} + +async function retryDestination(d, button, onChange) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/resume`, { method: 'POST' }); + toast(result.message); + if (onChange) await onChange(); + } catch (error) { + button.disabled = false; + showError(error); + } +} + +async function checkCopies(d, button) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/check`, { method: 'POST' }); + toast(result.message, '', { label: t('esportazione.apriEsportazione'), href: '/dashboard/esportazione' }); + } catch (error) { + showError(error); + } finally { + button.disabled = false; + } +} + +/** «Riconosci le copie già presenti» (tappa E5): a job of its own, followed in the Dashboard. */ +async function recognizeCopies(d, button) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/recognize`, { method: 'POST' }); + toast(result.message, '', { label: t('esportazione.apriEsportazione'), href: '/dashboard/esportazione' }); + } catch (error) { + showError(error); + } finally { + button.disabled = false; + } } /** The separator of the folders of a path as shown («/» in Docker, «\» on Windows). */ @@ -134,10 +230,10 @@ export function separator(display) { /** * The dialog of a destination: the general folder, or the own folder of an account. overview: GET /api/export (asked - * when missing). destination: the one being changed, or null for a new one. Resolves with the saved destination, or - * undefined when closed. + * when missing). destination: the one being changed, or null for a new one. accountEnabled: «Esporta questo account» + * of the account of an own folder. Resolves with the saved destination, or undefined when closed. */ -export async function destinationDialog({ scope, accountId = null, username = '', destination = null, overview = null }) { +export async function destinationDialog({ scope, accountId = null, username = '', destination = null, overview = null, accountEnabled = true }) { let info = overview; if (!info) { try { @@ -164,7 +260,15 @@ export async function destinationDialog({ scope, accountId = null, username = '' saving: false, photoFormat: (destination && destination.photoFormat) || 'general', videoFormat: (destination && destination.videoFormat) || 'general', + // Tappa E5: «Automatica», the answer to «Solo i nuovi / Copia anche gli N» ('new' or 'all') and what was counted. + automatic: Boolean(destination && destination.automatic), + choice: 'new', + preview: null, + previewKey: '', + widen: null, + autoWork: false, }; + const wasAutomatic = Boolean(destination && destination.automatic); return dialog({ title: general ? t('esportazione.dialogo.titoloGenerale') : t('esportazione.dialogo.titoloAccount', { nome: username }), @@ -269,6 +373,7 @@ export async function destinationDialog({ scope, accountId = null, username = '' changedNote.hidden = !destination || !state.path || samePath(state.path, original); drawSave(); refresh(); + drawAuto(); } // ------------------------------------------------------------------------------- types @@ -282,6 +387,7 @@ export async function destinationDialog({ scope, accountId = null, username = '' else state.types.delete(x.key); typesNote.hidden = state.types.size > 0; drawSave(); + drawAuto(); }, }); box.classList.add('tipo'); @@ -374,6 +480,8 @@ export async function destinationDialog({ scope, accountId = null, username = '' if (!ready()) return; state.saving = true; drawSave(); + const asked = asks(); + const all = asked && state.choice === 'all' && state.preview && state.preview.files > 0; const body = { scope, accountId: general ? null : accountId, @@ -383,16 +491,21 @@ export async function destinationDialog({ scope, accountId = null, username = '' namingScheme: state.own ? state.naming : null, highlightNamingScheme: state.own ? state.highlight : null, profileNamingScheme: state.own ? state.profile : null, - // «Automatica» is kept as stored: tappa E5 acts on it (decision D8). - automatic: destination ? destination.automatic : false, - onlyNew: true, + // Tappa E5: «Solo i nuovi» unless «Copia anche gli N» was chosen; while it stays on the answer is kept. + automatic: state.automatic, + onlyNew: !all, // Tappa E3: «general» is «Come le impostazioni generali». photoFormat: state.photoFormat, videoFormat: state.videoFormat, }; try { const saved = await api(destination ? `/api/export/destinations/${destination.id}` : '/api/export/destinations', { method: destination ? 'PUT' : 'POST', body }); - toast(t('esportazione.salvata')); + if (asked) { + toast(all ? t('esportazione.automatica.accesaTutti', { n: state.preview.files }) : t('esportazione.automatica.accesaNuovi')); + if (state.check && state.check.accepted === false) toast(t('esportazione.automatica.nonRisponde')); + } else { + toast(t('esportazione.salvata')); + } for (const w of saved.warnings || []) toast(w); done(saved.destination); } catch (error) { @@ -408,6 +521,139 @@ export async function destinationDialog({ scope, accountId = null, username = '' formatChoice({ kind: 'photo', value: state.photoFormat, first: asGeneral, onchange: (v) => { state.photoFormat = v; } }), formatChoice({ kind: 'video', value: state.videoFormat, first: asGeneral, onchange: (v) => { state.videoFormat = v; } })); + // ------------------------------------------------------------------------------- automatic (tappa E5) + // Hidden for the folder of a removed account (it never copies by itself); with no folder that can be written + // (Docker without /esporta) it cannot be turned on. + const orphan = Boolean(destination && destination.orphan); + const autoToggle = toggle({ + checked: state.automatic, + label: t('esportazione.automatica.leva'), + disabled: !root.active, + onchange: (v) => { + state.automatic = v; + if (!v && wasAutomatic) findAutomaticWork(); + drawAuto(); + }, + }); + const autoBox = h('div.automatica-scelta', { 'aria-live': 'polite' }); + const autoNotes = []; + if (!general && !accountEnabled) autoNotes.push(h('p.avviso-testo', icon('info', 'xs'), ' ', t('esportazione.automatica.accountSpento', { nome: username }))); + if (!general && !destination && info.general && info.general.automatic) autoNotes.push(h('p.aiuto', icon('info', 'xs'), ' ', t('esportazione.automatica.generaleAccesa', { nome: username }))); + const autoPart = orphan ? null : h('section.parte-dialogo.parte-automatica', + h('h3', t('esportazione.automatica.titolo')), + h('p.aiuto', t('esportazione.automatica.aiuto')), + autoNotes, + h('div.leva-automatica', autoToggle), + autoBox); + + /** The folder of a destination being changed is another one now. */ + function folderChanged() { + return Boolean(destination && state.path && !samePath(state.path, original)); + } + + /** The question «Solo i nuovi» is asked: turned on, or on with another folder (a new destination, r.575). */ + function asks() { + return state.automatic && (!wasAutomatic || folderChanged()); + } + + function typeList() { + return TYPES.map((x) => x.key).filter((k) => state.types.has(k)); + } + + // The count is asked again only when what it depends on changes (types, the folder), never at each key. + let autoToken = 0; + const fetchAuto = later(async (mine, key, request) => { + try { + const result = await api('/api/export/automatic-preview', { method: 'POST', body: request }); + if (mine !== autoToken) return; + if (request.mode === 'widen') state.widen = { key, ...result }; + else state.preview = { key, ...result }; + drawAuto(); + } catch (error) { + if (mine !== autoToken) return; + fill(autoBox, h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', error.message)); + } + }, 300); + + function want(request) { + const key = JSON.stringify(request); + const kept = request.mode === 'widen' ? state.widen : state.preview; + if (kept && kept.key === key) return kept; + if (state.previewKey !== key) { + state.previewKey = key; + fetchAuto(++autoToken, key, request); + } + return null; + } + + async function findAutomaticWork() { + try { + const runs = await api('/api/export/runs?unfinished=true'); + state.autoWork = runs.some((r) => r.origin === 'automatic' && r.destinationId === destination.id); + drawAuto(); + } catch (error) { + // Without the list the note is not shown: turning off still stops the copy. + state.autoWork = false; + } + } + + function drawAuto() { + if (!autoPart) return; + if (state.types.size === 0) { + autoBox.replaceChildren(); + return; + } + if (asks()) { + const preview = want({ + mode: 'switchOn', + destinationId: destination ? destination.id : null, + scope, + accountId: general ? null : accountId, + // The copies of the folder count only while it stays the same; another folder has none, whatever its name. + path: destination && !folderChanged() ? original : '', + types: typeList(), + }); + if (!preview) { + fill(autoBox, h('p.aiuto', t('esportazione.automatica.conto'))); + return; + } + if (!preview.files) { + state.choice = 'new'; + fill(autoBox, h('p.aiuto', icon('info', 'xs'), ' ', t('esportazione.automatica.nessuno'))); + return; + } + const free = preview.freeBytes != null ? preview.freeBytes : (state.check && state.check.accepted ? state.check.freeBytes : null); + const choose = (value) => { state.choice = value; }; + fill(autoBox, + h('p.domanda-automatica', h('b', t('esportazione.automatica.domanda'))), + h('div.scelte', { role: 'radiogroup', 'aria-label': t('esportazione.automatica.domanda') }, + radio({ name: 'automatica-esistenti', value: 'new', checked: state.choice !== 'all', onchange: choose, labelNode: h('span', h('b', t('esportazione.automatica.soloNuovi')), h('small', t('esportazione.automatica.soloNuoviAiuto'))) }), + radio({ + name: 'automatica-esistenti', + value: 'all', + checked: state.choice === 'all', + onchange: choose, + labelNode: h('span', h('b', t('esportazione.automatica.anche', { n: preview.files })), + h('small', t('esportazione.automatica.spazio', { spazio: bytes(preview.bytes) })), + free != null && preview.bytes > free ? h('small.avviso-testo', t('esportazione.automatica.pocoSpazio', { liberi: bytes(free) })) : null), + }))); + return; + } + if (state.automatic) { + // On already, with the same folder: what it copies, and the files in more when it takes more types (answer 55). + const since = destination.automaticSince; + const added = typeList().some((k) => !destination.types.includes(k)); + const widen = added ? want({ mode: 'widen', destinationId: destination.id, types: typeList() }) : null; + fill(autoBox, + h('p.aiuto', icon('refresh-cw', 'xs'), ' ', since ? t('esportazione.automatica.dal', { data: shortDay(since.day) }) : t('esportazione.automatica.tutto')), + widen && widen.files ? h('p.avviso-testo.in-piu', icon('info', 'xs'), ' ', t('esportazione.automatica.inPiu', { n: widen.files })) : null); + return; + } + fill(autoBox, wasAutomatic && state.autoWork + ? h('p.avviso-testo.spegnere', icon('triangle-alert', 'xs'), ' ', t('esportazione.automatica.spegnere')) + : null); + } + const body = h('div.contenuto', h('section.parte-dialogo', h('h3', t('esportazione.dialogo.cartella')), @@ -426,13 +672,14 @@ export async function destinationDialog({ scope, accountId = null, username = '' general ? h('p.aiuto', t('esportazione.dialogo.notaAccount')) : null, h('div.nomi-file', h('div.colonna-nomi', namingChoice, fields, problems), - h('div.colonna-albero', h('span.etichetta', t('esportazione.dialogo.risultato')), tree)))); + h('div.colonna-albero', h('span.etichetta', t('esportazione.dialogo.risultato')), tree))), + autoPart); const footer = h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), save)); if (state.path) checkFolder(state.path); else drawCheck(); - return { body, footer, onClose: () => { previewToken++; fetchPreview.cancel(); } }; + return { body, footer, onClose: () => { previewToken++; fetchPreview.cancel(); autoToken++; fetchAuto.cancel(); } }; }, }); } diff --git a/src/Febe.Web/wwwroot/js/pages/settings-export.js b/src/Febe.Web/wwwroot/js/pages/settings-export.js index 23202ec..31c70f6 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-export.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-export.js @@ -4,14 +4,16 @@ // save bar. Tappa E3: «Formati delle copie» (Foto and Video, JPG says «con perdita: qualità 92», MP4 «solo // rimuxaggio, mai ricodifica») and «Conversione della libreria» (the same two controls; turning one on asks «Convertire // anche i N file già in libreria?» with «Solo i nuovi» first; the status line with «Interrompi», «Riprendi» and -// «Riprova i non riusciti»). «Automatica» comes with tappa E5 (decision D8 of E2). +// «Riprova i non riusciti»). Tappa E5: «Automatica» is set in the dialog of each folder; the general folder and each +// folder of an account say it («Automatica dal …») and have their state: the pause «dal …» with the files that wait +// and «Riprova», the counts, «Controlla le copie» and «Riconosci le copie già presenti». import { api, withCarried } from '../core/api.js'; import { h, icon, fill, later } from '../core/dom.js'; import { t, bytes } from '../core/text.js'; -import { confirmDialog, label, segmented, showError, toast } from '../core/ui.js'; +import { confirmDialog, segmented, showError, toast } from '../core/ui.js'; import { heading } from './settings.js'; -import { countsText, describe, destinationDialog, formatChoice } from './export-dialogs.js'; +import { describe, destinationActions, destinationDialog, formatChoice } from './export-dialogs.js'; export default async function exportSettings(page, box) { let overview = await api('/api/export', { signal: page.signal }); @@ -47,19 +49,7 @@ export default async function exportSettings(page, box) { g ? h('span.val.dati', g.display) : h('span.val.tenue', t('esportazione.nessunaCartella'))), buttons), g ? h('p.aiuto.descrizione-copie', describe(g)) : null, - g ? stateLine(g) : null)); - } - - /** «In pausa: …» with «Riprova», or the counts of the copies with «Controlla le copie». */ - function stateLine(d) { - if (d.pausedAt || d.problem) { - return h('div.avviso.ambra.avviso-azione.stato-copie', icon('pause', 's'), - h('span', t('esportazione.pausa', { problema: d.problem || '' })), - h('button.btn.piccolo', { type: 'button', onclick: (e) => retry(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.riprova'))); - } - return h('div.stato-copie.riga-conteggi', - h('span.muto', countsText(d.counts)), - h('button.btn.piccolo', { type: 'button', title: t('esportazione.controllaAiuto'), onclick: (e) => check(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.controlla'))); + g ? destinationActions(g, { automatic: overview.automatic, onChange: reload }) : null)); } async function edit(destination) { @@ -86,30 +76,6 @@ export default async function exportSettings(page, box) { } } - async function retry(d, button) { - button.disabled = true; - try { - const result = await api(`/api/export/destinations/${d.id}/resume`, { method: 'POST' }); - toast(result.message); - await reload(); - } catch (error) { - button.disabled = false; - showError(error); - } - } - - async function check(d, button) { - button.disabled = true; - try { - const result = await api(`/api/export/destinations/${d.id}/check`, { method: 'POST' }); - toast(result.message, '', { label: t('esportazione.apriEsportazione'), href: '/dashboard/esportazione' }); - } catch (error) { - showError(error); - } finally { - button.disabled = false; - } - } - // ------------------------------------------------------------------------------------------- same post const samePost = segmented({ label: t('esportazione.stessoPost'), @@ -252,9 +218,7 @@ export default async function exportSettings(page, box) { ? h('a', { href: withCarried(`/account/${d.accountId}/impostazioni`) }, `@${d.username}`) : h('span.muto', t('esportazione.eraDi', { nome: d.formerUsername || '?' }))), h('td', h('span.dati', { title: d.display }, d.display), h('div.piccolo.muto', describe(d))), - h('td', d.pausedAt || d.problem - ? label(t('esportazione.inPausa'), 'ambra', 'pause') - : h('span.muto.piccolo', countsText(d.counts))))))))); + h('td', destinationActions(d, { automatic: overview.automatic, compact: true, onChange: reload })))))))); } // ------------------------------------------------------------------------------------------- notes diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index 4c71a84..3231bcb 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -1101,6 +1101,39 @@ "riprova": "Riprova", "controlla": "Controlla le copie", "controllaAiuto": "Guarda se i file copiati sono ancora nella cartella. Nessun file viene toccato.", + "riconosci": "Riconosci le copie già presenti", + "riconosciAiuto": "Cerca nella cartella i file che sono proprio le copie di quelli in libreria e li segna come «Copiato». Nessun file viene toccato.", + "pausaDal": "In pausa dal {giorno}: {problema}", + "pausaDa": "In pausa da {giorno}: {problema}", + "aspettano": "1 file aspetta questa cartella.|{n} file aspettano questa cartella.", + "pausaGiro": "Febe riprova da sola all'avvio e a ogni giro di recupero, ogni ora.", + "automatica": { + "titolo": "Automatica", + "leva": "Copie automatiche in questa cartella", + "aiuto": "Poco dopo ogni salvataggio in libreria, e comunque all'avvio e a ogni giro di recupero (ogni ora), Febe copia qui da sola i file dovuti: quelli salvati dopo l'accensione, o anche quelli di prima se l'hai scelto. Mai durante una sessione del motore; i tuoi lavori hanno la precedenza. «Tolto» e «Superato» non si ricopiano mai da soli.", + "domanda": "Che cosa fare dei file già in libreria?", + "conto": "Conto i file già in libreria…", + "soloNuovi": "Solo i nuovi", + "soloNuoviAiuto": "Da adesso in poi: i file salvati in libreria dopo questo momento, scaricati o importati.", + "anche": "Copia anche quello già in libreria|Copia anche i {n} già in libreria", + "spazio": "Circa {spazio}. La copia parte da sola fuori dalle sessioni del motore e lascia il passo ai tuoi lavori.", + "pocoSpazio": "Nella cartella ci sono {liberi} liberi: quando lo spazio finisce la copia va in pausa.", + "nessuno": "Nessun file già in libreria da copiare qui: da adesso si copiano da soli i file nuovi.", + "dal": "Automatica dal {data}: copia i file salvati in libreria da allora.", + "tutto": "Automatica: copia tutti i file dovuti.", + "spegnere": "Spegnendo, la copia automatica di questa cartella si ferma e i file che restavano non si copiano da soli; quelli già copiati restano.", + "inPiu": "1 file in più si copierà da solo.|{n} file in più si copieranno da soli.", + "accountSpento": "Per @{nome} «Esporta questo account» è spento: non si copia nulla, nemmeno da sola.", + "generaleAccesa": "Con una cartella sua, i file nuovi di @{nome} non vanno più da soli nella cartella generale: qui «Automatica» è spenta finché non la accendi.", + "togliPropria": "1 file di @{nome} andrà da solo nella cartella generale.|{n} file di @{nome} andranno da soli nella cartella generale.", + "etichetta": "Automatica", + "descrizione": "Automatica dal {data}", + "accesaNuovi": "Automatica accesa: da adesso si copiano da soli i file nuovi.", + "accesaTutti": "Automatica accesa: 1 file da copiare; la copia parte fra poco, mai durante una sessione del motore.|Automatica accesa: {n} file da copiare; la copia parte fra poco, mai durante una sessione del motore.", + "nonRisponde": "La cartella ora non risponde: le copie partono quando torna.", + "riprendeDaSola": "riprende da sola {quando}", + "riprendeFraPoco": "riprende da sola fra poco" + }, "conteggi": { "copiati": "1 copiato|{n} copiati", "tolti": "1 tolto|{n} tolti", @@ -1268,7 +1301,7 @@ }, "account": { "titolo": "Copie esterne", - "aiuto": "Copie dei file di questo account in una cartella fuori da Febe, con «Copia in…». I file già copiati si saltano.", + "aiuto": "Copie dei file di questo account in una cartella fuori da Febe, con «Copia in…», oppure da sola se la cartella ha «Automatica» accesa. I file già copiati si saltano.", "interruttore": "Esporta questo account", "spento": "Questo account non si esporta: «Copia in…» lo salta. Le copie già fatte restano dove sono.", "generale": "Nella cartella generale", @@ -1418,9 +1451,17 @@ "annullaTesto": "I file già copiati restano dove sono; quelli che mancano non si copiano.", "annullaSi": "Annulla la copia", "ultimi": "Ultimi lavori", - "vuoto": "Nessuna copia ancora. Le copie partono da «Copia in…» nella Libreria, nel visualizzatore o nella scheda di un account.", + "vuoto": "Nessuna copia ancora. Le copie partono da «Copia in…» nella Libreria, nel visualizzatore o nella scheda di un account; nelle cartelle con «Automatica» accesa le copie partono anche da sole.", "lavoroCopia": "Copia in {cartella}", "lavoroControllo": "Controllo delle copie in {cartella}", + "lavoroRiconosci": "Riconoscimento delle copie in {cartella}", + "lavoroAutomatico": "Copia automatica in {cartella}", + "fermaPronta": "Copia in {cartella} ferma: la cartella risponde di nuovo, riprendi quando vuoi.", + "automatica": { + "prossimoGiro": "Copie automatiche: prossimo giro di recupero {quando}.", + "ferme": "Copie automatiche ferme fino {quando}.", + "riprendiOra": "Riprendi ora" + }, "stati": { "running": "In corso", "interrupted": "Interrotta", @@ -1440,7 +1481,9 @@ "alreadyCopied": "1 già copiato|{n} già copiati", "skipped": "1 saltato|{n} saltati", "missing": "1 non presente in libreria|{n} non presenti in libreria", - "failed": "1 non riuscito|{n} non riusciti" + "failed": "1 non riuscito|{n} non riusciti", + "notFound": "1 non trovato|{n} non trovati", + "different": "1 diverso|{n} diversi" }, "perAccount": "Per account", "colonne": { diff --git a/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs b/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs new file mode 100644 index 0000000..b8fce46 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiTests.Automatic.cs @@ -0,0 +1,403 @@ +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Export; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// The automatic copies over the API (tappa E5, §3.1 of its design): the question «Solo i nuovi / Copia anche gli N» +/// and the files in more, «Riconosci le copie già presenti», «Automatica» turned off, «Automatica dal …» and the files +/// that wait for a folder in pause, the status of the automatic copies, «Da riprendere», «Interrompi» and «Riprendi ora». +/// +public sealed partial class ExportApiTests +{ + private static readonly string[] AllTypes = ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"]; + + [TestMethod] + public async Task AutomaticPreviewCountsTheBacklog() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var luca = await AddPhotosAsync(server, "luca.demo", 2); + var (generalId, usb) = await GeneralAsync(server); + var nas = server.Temp.Combine("nas"); + Directory.CreateDirectory(nas); + + // «Automatica» turned on for the general folder: the files of both accounts, none copied yet, as «Copia in…» counts them. + var on = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = AllTypes }); + Assert.AreEqual(5, on.Int("files"), on.ToString()); + Assert.AreEqual(await PlanFilesAsync(server, marta.Account.Id) + await PlanFilesAsync(server, luca.Account.Id), on.Int("files")); + Assert.IsGreaterThan(0L, on.Long("bytes")); + StringAssert.StartsWith(on.Str("text"), "Copia anche i 5 già in libreria: circa "); + Assert.AreEqual(Free, on.Long("freeBytes"), "the space of the stored folder"); + + // A file copied by hand is no longer counted; in another folder (a new destination) nothing is copied yet. + await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id } }); + Assert.AreEqual(4, (await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = AllTypes })).Int("files")); + var moved = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = nas, types = AllTypes }); + Assert.AreEqual(5, moved.Int("files"), "a new folder has no copies"); + Assert.AreEqual(JsonValueKind.Null, moved.GetProperty("freeBytes").ValueKind); + var none = await PreviewAsync(server, new { mode = "switchOn", destinationId = generalId, scope = "general", path = usb, types = new[] { "storie" } }); + Assert.AreEqual(0, none.Int("files")); + Assert.AreEqual("Nessun file già in libreria da copiare qui.", none.Str("text")); + + // A new own folder of luca: his two files, none copied there. + var own = await PreviewAsync(server, new { mode = "switchOn", scope = "account", accountId = luca.Account.Id, path = nas, types = AllTypes }); + Assert.AreEqual(2, own.Int("files")); + + // «Widen»: the general folder automatic with videos only, «Copia anche quelli già in libreria»; adding the photos + // adds the four photos not copied (answer 55: no new question). + var (put, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"], automatic: true, onlyNew: false)); + Assert.AreEqual(HttpStatusCode.OK, put, saved.ToString()); + var widen = await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = new[] { "postVideo", "postFoto" } }); + Assert.AreEqual(4, widen.Int("files"), widen.ToString()); + Assert.AreEqual("4 file in più si copieranno da soli.", widen.Str("text")); + Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = new[] { "postVideo" } })).Int("files"), "no type added"); + + // «Solo i nuovi» keeps the files saved before the switch out of what is added. + server.Clock.Now += TimeSpan.FromMinutes(5); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"]))).Status); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, types: ["postVideo"], automatic: true))).Status); + Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = AllTypes })).Int("files"), "every photo was saved before"); + server.Clock.Now += TimeSpan.FromMinutes(1); + await AddPostAsync(server, luca.Account, "luca.demo-nuovo", 40); + Assert.AreEqual(1, (await PreviewAsync(server, new { mode = "widen", destinationId = generalId, types = AllTypes })).Int("files"), "the photo saved after"); + + // An own folder taken away while the general folder is automatic (since null): luca's files go there by themselves. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb))).Status); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{generalId}", Destination(usb, automatic: true, onlyNew: false))).Status); + var (ownStatus, ownSaved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas, scope: "account", accountId: luca.Account.Id)); + Assert.AreEqual(HttpStatusCode.OK, ownStatus, ownSaved.ToString()); + var remove = await PreviewAsync(server, new { mode = "removeOwn", accountId = luca.Account.Id }); + Assert.AreEqual(3, remove.Int("files"), remove.ToString()); + Assert.AreEqual("3 file di @luca.demo andranno da soli nella cartella generale.", remove.Str("text")); + Assert.AreEqual(0, (await PreviewAsync(server, new { mode = "account", accountId = luca.Account.Id })).Int("files"), "his own folder is not automatic"); + var martaAccount = await PreviewAsync(server, new { mode = "account", accountId = marta.Account.Id }); + Assert.AreEqual(2, martaAccount.Int("files"), "marta's files not copied, in the automatic general folder"); + + // Once the own folder is gone, the plan of «Copia in…» agrees with what was announced. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{ownSaved.GetProperty("destination").Long("id")}")).Status); + Assert.AreEqual(3, await PlanFilesAsync(server, luca.Account.Id)); + + // Requests that make no sense are refused in Italian. + foreach (var bad in new object[] + { + new { mode = "boh" }, + new { mode = "switchOn", scope = "general", path = usb, types = new[] { "nessuno" } }, + new { mode = "switchOn", scope = "account", path = nas, types = AllTypes }, + new { mode = "switchOn", scope = "account", accountId = 999_999L, path = nas, types = AllTypes }, + new { mode = "removeOwn" }, + }) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", bad); + Assert.AreEqual(HttpStatusCode.BadRequest, status, answer.ToString()); + Assert.IsNotEmpty(answer.Str("message")); + } + + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", new { mode = "widen", destinationId = 999_999L, types = AllTypes })).Status); + } + + [TestMethod] + public async Task RecognizeStartsARun() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var (oldId, usb) = await GeneralAsync(server); + await StartAndWaitAsync(server, new { accountId = marta.Account.Id }); + + // The copies in another folder, as Alberto could have made them himself: one the same, one missing, one different. + var nas = server.Temp.Combine("nas"); + foreach (var file in Directory.GetFiles(usb, "*", SearchOption.AllDirectories)) + { + var target = Path.Combine(nas, Path.GetRelativePath(usb, file)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(file, target); + } + + var copies = Directory.GetFiles(nas, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).ToList(); + Assert.HasCount(3, copies); + File.Delete(copies[1]); + await File.WriteAllTextAsync(copies[2], "un altro file"); + var (put, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{oldId}", Destination(nas)); + Assert.AreEqual(HttpStatusCode.OK, put, saved.ToString()); + var nasId = saved.GetProperty("destination").Long("id"); + Assert.AreNotEqual(oldId, nasId, "a new folder is a new destination"); + var before = Directory.GetFiles(nas, "*", SearchOption.AllDirectories).ToDictionary(f => f, File.ReadAllBytes); + + var (status, started) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{nasId}/recognize"); + Assert.AreEqual(HttpStatusCode.OK, status, started.ToString()); + Assert.AreEqual(Febe.Web.Api.ExportApi.RecognizeStartedText, started.Str("message")); + var runId = started.Long("runId"); + await WaitIdleAsync(server); + + var progress = await server.GetJsonAsync("/api/export/progress"); + Assert.AreEqual(runId, progress.Long("runId")); + Assert.AreEqual("recognize", progress.Str("kind")); + Assert.AreEqual("manual", progress.Str("origin")); + var run = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().First(); + Assert.AreEqual(runId, run.Long("id")); + Assert.AreEqual("recognize", run.Str("kind")); + Assert.AreEqual("completed", run.Str("state")); + var report = await server.GetJsonAsync($"/api/export/runs/{runId}/report"); + Assert.AreEqual(1, report.GetProperty("byState").Int("adopted"), report.ToString()); + Assert.AreEqual(1, report.Int("notFound"), report.ToString()); + Assert.AreEqual(1, report.Int("different"), report.ToString()); + Assert.HasCount(1, report.Items("problems").ToList(), "only the different file needs a look"); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/export")).GetProperty("general").GetProperty("counts").Int("copied")); + + // Nothing was written, moved or removed in the folder. + CollectionAssert.AreEquivalent(before.Keys.ToList(), Directory.GetFiles(nas, "*", SearchOption.AllDirectories)); + Assert.IsTrue(before.All(f => f.Value.AsSpan().SequenceEqual(File.ReadAllBytes(f.Key)))); + + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations/999999/recognize")).Status); + var (retired, answer) = await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{oldId}/recognize"); + Assert.AreEqual(HttpStatusCode.BadRequest, retired, answer.ToString()); + Assert.IsNotEmpty(answer.Str("message")); + } + + [TestMethod] + public async Task TurningAutomaticOffCancelsItsAutomaticRuns() + { + await using var server = await StartAsync(); + await AddPhotosAsync(server, "marta.demo", 1); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true, onlyNew: false)); + Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString()); + var id = saved.GetProperty("destination").Long("id"); + Assert.IsTrue(saved.GetProperty("destination").Bool("automatic")); + var exports = server.Db.Exports; + var automatic = await exports.CreateRunAsync(new ExportRun { DestinationId = id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now }); + var manual = await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now }); + + // Turned off (answer 52): the automatic copy of the folder stops for good, the copies made by hand stay Alberto's. + var (put, off) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb)); + Assert.AreEqual(HttpStatusCode.OK, put, off.ToString()); + Assert.IsFalse(off.GetProperty("destination").Bool("automatic")); + var stopped = (await exports.GetRunAsync(automatic.Id))!; + Assert.AreEqual(ExportRunState.Cancelled, stopped.State); + Assert.AreEqual(ExportText.AutomaticTurnedOff, stopped.LastError); + Assert.AreEqual(ExportRunState.Interrupted, (await exports.GetRunAsync(manual.Id))!.State); + } + + [TestMethod] + public async Task DestinationDtoExposesAutomaticSinceAndTheFilesThatWait() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var luca = await AddPhotosAsync(server, "luca.demo", 2); + var usb = server.Temp.Combine("usb"); + var nas = server.Temp.Combine("nas"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(nas); + server.Clock.Now += TimeSpan.FromMinutes(1); + var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true)); + Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString()); + var general = saved.GetProperty("destination"); + var id = general.Long("id"); + Assert.AreEqual(server.Clock.Now.ToUnixTimeMilliseconds(), general.GetProperty("automaticSince").Long("ms"), "«Solo i nuovi»: from now"); + Assert.AreEqual(JsonValueKind.Null, general.GetProperty("waiting").ValueKind, "not paused"); + + // Off, then on with «Copia anche quelli già in libreria»: no «dal». + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb))).Status); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").GetProperty("automaticSince").ValueKind, "off"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(usb, automatic: true, onlyNew: false))).Status); + var all = (await server.GetJsonAsync("/api/export")).GetProperty("general"); + Assert.IsTrue(all.Bool("automatic")); + Assert.AreEqual(JsonValueKind.Null, all.GetProperty("automaticSince").ValueKind, "everything due"); + + // In pause: the five files of the two accounts wait for it (one of luca's goes to his own folder once it has one). + await server.Db.Exports.SetDestinationPausedAsync(id, server.Clock.Now, "La cartella non risponde."); + var paused = (await server.GetJsonAsync("/api/export")).GetProperty("general"); + Assert.AreEqual(5, paused.Int("waiting"), paused.ToString()); + Assert.AreEqual("La cartella non risponde.", paused.Str("problem")); + + // The account card shows the same folder, automatic, with what waits. + var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").GetProperty("destination"); + Assert.IsTrue(card.Bool("automatic")); + Assert.AreEqual(5, card.Int("waiting")); + + // A folder without «Automatica», in pause: what its unfinished jobs still have to copy. + var (ownStatus, ownSaved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas, scope: "account", accountId: luca.Account.Id)); + Assert.AreEqual(HttpStatusCode.OK, ownStatus, ownSaved.ToString()); + var ownId = ownSaved.GetProperty("destination").Long("id"); + var run = await server.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = ownId, State = ExportRunState.Paused, StartedAt = server.Clock.Now }); + await server.Db.Exports.AddItemsAsync([.. luca.Entries.Select(e => e.Media[0]).Select(m => new ExportItem { RunId = run.Id, MediaId = m.Id, AccountId = luca.Account.Id, SourceSha256 = m.Sha256 })]); + await server.Db.Exports.SetDestinationPausedAsync(ownId, server.Clock.Now, "La chiavetta non c'è."); + + // The count of an automatic folder in pause is kept a minute (a disk left unplugged is not counted at each reading). + server.Clock.Now += TimeSpan.FromMinutes(2); + var overview = await server.GetJsonAsync("/api/export"); + var ownDto = overview.GetProperty("own").EnumerateArray().Single(); + Assert.AreEqual(2, ownDto.Int("waiting"), ownDto.ToString()); + Assert.AreEqual(JsonValueKind.Null, ownDto.GetProperty("automaticSince").ValueKind); + Assert.AreEqual(3, overview.GetProperty("general").Int("waiting"), "luca's files now go to his own folder"); + } + + [TestMethod] + public async Task UnfinishedRunsCountsManualOnly_RunsListHasEveryUnfinished() + { + await using var server = await StartAsync(); + var (id, _) = await GeneralAsync(server); + var exports = server.Db.Exports; + var manual = await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Interrupted, StartedAt = server.Clock.Now }); + var automatic = await exports.CreateRunAsync(new ExportRun { DestinationId = id, Origin = ExportRunOrigin.Automatic, State = ExportRunState.Paused, StartedAt = server.Clock.Now }); + for (var i = 0; i < 25; i++) + { + server.Clock.Now += TimeSpan.FromMinutes(1); + await exports.CreateRunAsync(new ExportRun { DestinationId = id, State = ExportRunState.Completed, StartedAt = server.Clock.Now, CompletedAt = server.Clock.Now }); + } + + Assert.AreEqual(1, (await server.GetJsonAsync("/api/export")).Int("unfinishedRuns"), "only Alberto's job: the automatic one resumes by itself"); + var recent = (await server.GetJsonAsync("/api/export/runs?limit=20")).EnumerateArray().Select(r => r.Long("id")).ToList(); + Assert.HasCount(20, recent); + Assert.IsFalse(recent.Contains(manual.Id) || recent.Contains(automatic.Id), "older than the twenty newest"); + var unfinished = (await server.GetJsonAsync("/api/export/runs?unfinished=true")).EnumerateArray().ToList(); + CollectionAssert.AreEqual(new[] { manual.Id, automatic.Id }, unfinished.Select(r => r.Long("id")).ToArray(), "every unfinished job, oldest first"); + CollectionAssert.AreEqual(new[] { "manual", "automatic" }, unfinished.Select(r => r.Str("origin")).ToArray()); + } + + [TestMethod] + public async Task InterruptOfAnAutomaticJobHoldsTheAutomaticCopiesAndSaysWhen() + { + var session = new FakeSessionState(); + var clock = new GatedClock(new ManualClock(Make.T0)); + await using var server = await StartAsync(session: session, clock: clock); + await AddPhotosAsync(server, "marta.demo", 2); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true, onlyNew: false)); + Assert.AreEqual(HttpStatusCode.OK, created, saved.ToString()); + var id = saved.GetProperty("destination").Long("id"); + + // An automatic job that waits for the end of an engine session (the session starts right after it is planned). + var service = await server.App.Services.GetRequiredService().GetAsync(); + service.AutomaticRunRecorded = _ => + { + session.InSession = true; + return Task.CompletedTask; + }; + var start = await service.TryStartAutomaticAsync(new ExportSelection.Automatic([new ExportSelection.AutomaticScope(id, null)], [], Round: true)); + Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome); + var progress = (await WaitForAsync(async () => + { + var p = await server.GetJsonAsync("/api/export/progress"); + return p.Bool("running") && p.Str("phase") == "waitingForSession" ? (JsonElement?)p : null; + })).GetValueOrDefault(); + Assert.AreEqual("automatic", progress.Str("origin")); + Assert.AreEqual("copy", progress.Str("kind")); + + // «Interrompi» (answer 53): the automatic copies stop until the next round, at least an hour, and the answer says when. + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt"); + Assert.AreEqual(HttpStatusCode.OK, status, answer.ToString()); + var until = clock.Now + service.AutomaticHoldTime; + Assert.AreEqual(until, service.AutomaticHeldUntil); + Assert.AreEqual(ExportText.AutomaticInterrupted(until, clock.LocalZone), answer.Str("message")); + StringAssert.Contains(answer.Str("message"), "riprende da sola alle"); + Assert.AreEqual(ExportRunState.Interrupted, (await server.Db.Exports.GetRunAsync(start.Runs[0].Id))!.State); + + // «Riprendi ora»: no longer held. + var (resumed, resumeAnswer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic/resume"); + Assert.AreEqual(HttpStatusCode.OK, resumed, resumeAnswer.ToString()); + Assert.AreEqual("Copie automatiche di nuovo attive.", resumeAnswer.Str("message")); + Assert.IsNull(service.AutomaticHeldUntil); + + // A manual job keeps the message of before. + session.InSession = false; + Assert.AreEqual("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi.", (await server.SendJsonAsync(HttpMethod.Post, "/api/export/interrupt")).Body.Str("message")); + Assert.IsNull(service.AutomaticHeldUntil); + } + + [TestMethod] + public async Task OverviewCarriesTheAutomaticStatus() + { + // Without the worker (the demonstration, a start with problems): no status. + await using (var plain = await StartAsync()) + { + Assert.AreEqual(JsonValueKind.Null, (await plain.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind); + } + + var clock = new GatedClock(new ManualClock(Make.T0)); + var signal = new AutoExportSignal(); + await using var server = await WebTestServer.StartAsync( + new Febe.Web.FebeWebOptions { Edition = Febe.Web.FebeEdition.Desktop, Access = Febe.Web.AccessMode.None }, + s => + { + s.AddSingleton(new FakeExportDisk(Free)); + s.AddSingleton(clock); + s.AddSingleton(sp => new AutoExportWorker(new AutoExportEnvironment + { + Storage = sp.GetRequiredService(), + Clock = clock, + Service = ct => sp.GetRequiredService().GetAsync(ct), + Signal = signal, + Gate = sp.GetRequiredService(), + })); + }); + var worker = server.App.Services.GetRequiredService(); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind, "not started yet"); + + using var stop = new CancellationTokenSource(); + var loop = Task.Run(() => worker.RunAsync(stop.Token)); + try + { + // The start-up round has run: when the next one is due. + var status = (await WaitForAsync(async () => + { + var a = (await server.GetJsonAsync("/api/export")).GetProperty("automatic"); + return a.ValueKind == JsonValueKind.Object && a.GetProperty("lastRound").ValueKind == JsonValueKind.Object ? (JsonElement?)a : null; + })).GetValueOrDefault(); + Assert.IsFalse(status.Bool("anyAutomatic")); + Assert.AreEqual((Make.T0 + TimeSpan.FromHours(1)).ToUnixTimeMilliseconds(), status.GetProperty("nextRound").Long("ms")); + Assert.AreEqual(Make.T0.ToUnixTimeMilliseconds(), status.GetProperty("lastRound").Long("ms")); + Assert.AreEqual(JsonValueKind.Null, status.GetProperty("heldUntil").ValueKind); + + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, automatic: true))).Status); + Assert.IsTrue((await server.GetJsonAsync("/api/export")).GetProperty("automatic").Bool("anyAutomatic")); + + // Held by «Interrompi» until a time, then «Riprendi ora». + var service = await server.App.Services.GetRequiredService().GetAsync(); + var until = service.HoldAutomatic(clock.Now + TimeSpan.FromHours(1)); + Assert.AreEqual(until.ToUnixTimeMilliseconds(), (await server.GetJsonAsync("/api/export")).GetProperty("automatic").GetProperty("heldUntil").Long("ms")); + var count = signal.Count; + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic/resume")).Status); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").GetProperty("heldUntil").ValueKind); + Assert.IsGreaterThan(count, signal.Count, "a pass is asked at once"); + } + finally + { + await stop.CancelAsync(); + await worker.StopAsync(); + await loop; + } + + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("automatic").ValueKind, "stopped"); + } + + // ------------------------------------------------------------------------------------------------- support + + private static async Task PreviewAsync(WebTestServer server, object request) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/automatic-preview", request); + Assert.AreEqual(HttpStatusCode.OK, status, answer.ToString()); + return answer; + } + + /// The files «Copia in…» would write for an account now. + private static async Task PlanFilesAsync(WebTestServer server, long accountId) + { + var (status, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId }); + Assert.AreEqual(HttpStatusCode.OK, status, plan.ToString()); + return plan.Int("files"); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiTests.cs b/tests/Febe.Tests/Web/ExportApiTests.cs index 5061063..aea4ee4 100644 --- a/tests/Febe.Tests/Web/ExportApiTests.cs +++ b/tests/Febe.Tests/Web/ExportApiTests.cs @@ -21,7 +21,7 @@ namespace Febe.Tests.Web; /// real (saved through ), destinations are folders of the temporary folder of the test. /// [TestClass] -public sealed class ExportApiTests +public sealed partial class ExportApiTests { public TestContext TestContext { get; set; } = null!; @@ -455,7 +455,7 @@ public sealed class ExportApiTests } }); - private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new + private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null, bool automatic = false, bool onlyNew = true) => new { scope, accountId, @@ -465,6 +465,8 @@ public sealed class ExportApiTests namingScheme = (string?)null, highlightNamingScheme = (string?)null, profileNamingScheme = (string?)null, + automatic, + onlyNew, }; /// The general folder «usb» in the temporary folder of the host.