E5: API e interfaccia delle copie automatiche e di «Riconosci»
L'interfaccia di programmazione e le pagine mostrano e usano ciò che i
pacchetti precedenti hanno costruito nel nucleo.
- API: le modifiche delle destinazioni passano da ChangeDestinationAsync
(spegnere «Automatica» ferma subito la sua copia automatica, risposta
52); nuova /api/export/automatic-preview (switchOn, widen, removeOwn,
account) per la domanda «Solo i nuovi / Copia anche gli N» e i file in
più (risposta 55); /destinations/{id}/recognize; /automatic/resume
(«Riprendi ora»); «Interrompi» su una copia automatica dice fino a che
ora le copie automatiche restano ferme (risposta 53); runs?unfinished;
avanzamento con tipo e origine; destinazioni con «dal» e i file che
aspettano una cartella in pausa; stato delle copie automatiche nella
panoramica (null senza il lavoratore, quindi nella dimostrazione);
«da riprendere» conta solo i lavori di Alberto.
- Interfaccia: l'interruttore «Automatica» nella finestra della
destinazione con la domanda all'accensione, i file in più e l'avviso
allo spegnimento; stato della cartella condiviso da Impostazioni e
scheda account (pausa «dal …», file che aspettano, «Riprova»,
«Controlla le copie», «Riconosci le copie già presenti»); Dashboard con
i nomi dei lavori automatici e di riconoscimento, la riga delle copie
automatiche con «Riprendi ora», «Da riprendere» con ogni lavoro non
finito e la copia manuale pronta a ripartire (risposta 48).
- Prove API in ExportApiTests.Automatic.cs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e66e322d35
commit
f8491529ca
12 files changed
+1247
-113
No files matched your search
+317
-25
@@ -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
|
||||
/// <summary>The most files a «Copia in…» can name one by one (a larger choice goes through the filter).</summary>
|
||||
public const int MaxIds = 50_000;
|
||||
|
||||
/// <summary>The answer of «Riconosci le copie già presenti» (tappa E5).</summary>
|
||||
public const string RecognizeStartedText = "Riconoscimento avviato: segui l'avanzamento nella Dashboard, scheda Esportazione. Nessun file viene toccato.";
|
||||
|
||||
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>How long the count of the files waiting for an automatic destination in pause is kept (<see cref="WaitingAsync"/>).</summary>
|
||||
private static readonly TimeSpan WaitingKept = TimeSpan.FromMinutes(1);
|
||||
|
||||
private static readonly ConditionalWeakTable<IFebeStorage, ConcurrentDictionary<ExportBacklogQuery, (DateTimeOffset At, int Files)>> WaitingCache = new();
|
||||
|
||||
/// <summary>
|
||||
/// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the
|
||||
/// library conversion compares before and after, so two quick changes must not both start from the same before.
|
||||
@@ -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<ExportRunDto>(runs.Count);
|
||||
@@ -359,11 +418,14 @@ public static class ExportApi
|
||||
return ApiHttp.Json<IReadOnlyList<ExportRunDto>>(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);
|
||||
}
|
||||
|
||||
/// <summary>A destination with its counts, read from the database.</summary>
|
||||
/// <summary>A destination with its counts (and, in pause, the files that wait for it), read from the database.</summary>
|
||||
public static async Task<ExportDestinationDto> DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
|
||||
var names = new Dictionary<long, string>();
|
||||
if (destination.AccountId is { } accountId && await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is { } account)
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files that wait for a destination in pause (tappa E5, D14): for an automatic one, what it would copy by itself
|
||||
/// (at least what its unfinished jobs still have to copy); for one without «Automatica», what its unfinished jobs
|
||||
/// still have to copy. Null when it is not paused. The count of an automatic destination is kept a minute per
|
||||
/// database: a disk that stays unplugged must not make every reading of the Dashboard count the library again.
|
||||
/// </summary>
|
||||
public static async Task<int?> WaitingAsync(IFebeStorage storage, ExportDestination destination, IReadOnlyList<ExportRun> unfinished, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
ArgumentNullException.ThrowIfNull(unfinished);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
if (destination.PausedAt is null || destination.IsRetired)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var pending = 0;
|
||||
foreach (var run in unfinished.Where(r => r.DestinationId == destination.Id && r.Kind == ExportRunKind.Copy))
|
||||
{
|
||||
pending += (await storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false)).ByState.GetValueOrDefault(ExportItemState.Pending);
|
||||
}
|
||||
|
||||
if (!destination.Automatic || destination.IsOrphan)
|
||||
{
|
||||
return pending;
|
||||
}
|
||||
|
||||
var query = new ExportBacklogQuery(destination.Scope, destination.AccountId, destination.ContentTypes, destination.Id, destination.AutomaticSince);
|
||||
var cache = WaitingCache.GetValue(storage, _ => new ConcurrentDictionary<ExportBacklogQuery, (DateTimeOffset At, int Files)>());
|
||||
var now = clock.Now;
|
||||
if (!cache.TryGetValue(query, out var kept) || now - kept.At > WaitingKept || now < kept.At)
|
||||
{
|
||||
kept = (now, (await storage.Exports.CountAutomaticBacklogAsync(query, ct).ConfigureAwait(false)).Files);
|
||||
cache[query] = kept;
|
||||
}
|
||||
|
||||
return Math.Max(pending, kept.Files);
|
||||
}
|
||||
|
||||
/// <summary>«Copie esterne» of the account card (decisions D1-D3 of tappa E2).</summary>
|
||||
@@ -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<ExportDestinationDto>(destinations.Count);
|
||||
foreach (var destination in destinations)
|
||||
{
|
||||
var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
|
||||
mapped.Add(Destination(destination, names, counts, root, clock));
|
||||
var 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);
|
||||
}
|
||||
|
||||
/// <summary>The automatic copies as the Dashboard shows them (tappa E5); the hold is the service's own.</summary>
|
||||
public static async Task<ExportAutomaticStatusDto> AutomaticStatusAsync(AutoExportWorker worker, ExportService service, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(worker);
|
||||
ArgumentNullException.ThrowIfNull(service);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var status = await worker.StatusAsync(ct).ConfigureAwait(false);
|
||||
var now = clock.Now;
|
||||
LocalTimeDto? Local(DateTimeOffset? at) => at is { } value ? ApiMapping.Local(value, now, clock.LocalZone) : null;
|
||||
return new ExportAutomaticStatusDto(
|
||||
status.AnyAutomatic,
|
||||
status.Waiting,
|
||||
Local(status.LastRound),
|
||||
Local(status.NextRound),
|
||||
Local(service.AutomaticHeldUntil ?? status.HeldUntil));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>POST /api/export/automatic-preview</c> (tappa E5): what an automatic destination would copy by itself, from the
|
||||
/// store's count (the same terms as the automatic copies: due, not copied, «Tolto» and «Superato» left out, each file
|
||||
/// once as the plan counts it).
|
||||
/// </summary>
|
||||
public static async Task<ExportAutomaticPreviewDto> AutomaticPreviewAsync(ExportAutomaticPreviewRequest body, ExportRootOptions root, IFebeStorage storage, IExportDisk disk, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(body);
|
||||
ArgumentNullException.ThrowIfNull(root);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(disk);
|
||||
var exports = storage.Exports;
|
||||
switch (body.Mode?.Trim().ToLowerInvariant())
|
||||
{
|
||||
case "switchon":
|
||||
{
|
||||
// «Solo i nuovi / Copia anche gli N»: the destination as the dialog has it now, its copies only while the
|
||||
// folder stays the same (a new folder is a new destination, with no copies, r.575).
|
||||
var scope = ParseScope(body.Scope);
|
||||
var accountId = scope == ExportScope.Account ? await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false) : (long?)null;
|
||||
var stored = body.DestinationId is { } id ? await StoredAsync(exports, id, ct).ConfigureAwait(false) : null;
|
||||
if (stored is not null && (stored.Scope != scope || stored.AccountId != accountId))
|
||||
{
|
||||
throw new BadRequestException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.");
|
||||
}
|
||||
|
||||
var same = stored is not null && !stored.IsOrphan && SameFolder(root, body.Path, stored.RootPath);
|
||||
var types = ParseTypes(body.Types);
|
||||
var backlog = types == ContentTypes.None
|
||||
? new ExportBacklog(0, 0)
|
||||
: await exports.CountAutomaticBacklogAsync(new ExportBacklogQuery(scope, accountId, types, same ? stored!.Id : null, null), ct).ConfigureAwait(false);
|
||||
var free = same ? await MeasureAsync(() => disk.FreeBytes(stored!.RootPath), ct).ConfigureAwait(false) : null;
|
||||
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, SwitchOnText(backlog), free);
|
||||
}
|
||||
|
||||
case "widen":
|
||||
{
|
||||
// Answer 55: no new question; the files of the added types saved since the same «dal» go by themselves.
|
||||
var stored = await StoredAsync(exports, body.DestinationId ?? throw new BadRequestException("Manca la cartella delle copie."), ct).ConfigureAwait(false);
|
||||
var added = ParseTypes(body.Types) & ~stored.ContentTypes;
|
||||
if (!stored.Automatic || stored.IsOrphan || added == ContentTypes.None)
|
||||
{
|
||||
return new ExportAutomaticPreviewDto(0, 0, WidenText(0));
|
||||
}
|
||||
|
||||
var before = await exports.CountAutomaticBacklogAsync(
|
||||
new ExportBacklogQuery(stored.Scope, stored.AccountId, stored.ContentTypes, stored.Id, stored.AutomaticSince), ct).ConfigureAwait(false);
|
||||
var after = await exports.CountAutomaticBacklogAsync(
|
||||
new ExportBacklogQuery(stored.Scope, stored.AccountId, stored.ContentTypes | added, stored.Id, stored.AutomaticSince), ct).ConfigureAwait(false);
|
||||
var files = Math.Max(0, after.Files - before.Files);
|
||||
return new ExportAutomaticPreviewDto(files, Math.Max(0, after.Bytes - before.Bytes), WidenText(files));
|
||||
}
|
||||
|
||||
case "removeown":
|
||||
{
|
||||
// «Usa la cartella generale» while the general folder is automatic: the account's files go there by themselves.
|
||||
var accountId = await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false);
|
||||
var username = (await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false))!.Username;
|
||||
var general = await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
|
||||
var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false);
|
||||
if (general is not { Automatic: true } || own is null)
|
||||
{
|
||||
return new ExportAutomaticPreviewDto(0, 0, string.Empty);
|
||||
}
|
||||
|
||||
var backlog = await exports.CountAutomaticBacklogAsync(
|
||||
new ExportBacklogQuery(ExportScope.General, accountId, general.ContentTypes, general.Id, general.AutomaticSince, accountId), ct).ConfigureAwait(false);
|
||||
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, backlog.Files == 0 ? string.Empty : RemoveOwnText(backlog.Files, username));
|
||||
}
|
||||
|
||||
case "account":
|
||||
{
|
||||
// «Esporta questo account» on again: what its automatic destination now copies of it by itself.
|
||||
var accountId = await AccountOfAsync(storage, body.AccountId, ct).ConfigureAwait(false);
|
||||
var destination = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false)
|
||||
?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
|
||||
if (destination is not { Automatic: true })
|
||||
{
|
||||
return new ExportAutomaticPreviewDto(0, 0, string.Empty);
|
||||
}
|
||||
|
||||
var backlog = await exports.CountAutomaticBacklogAsync(
|
||||
new ExportBacklogQuery(destination.Scope, accountId, destination.ContentTypes, destination.Id, destination.AutomaticSince), ct).ConfigureAwait(false);
|
||||
return new ExportAutomaticPreviewDto(backlog.Files, backlog.Bytes, backlog.Files == 0 ? string.Empty : AccountText(backlog.Files, ExportDestinations.Label(destination)));
|
||||
}
|
||||
|
||||
default:
|
||||
throw new BadRequestException("Domanda sconosciuta: switchOn, widen, removeOwn o account.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>«Copia anche i 12 già in libreria: circa 3,1 GB.», or that there is none.</summary>
|
||||
public static string SwitchOnText(ExportBacklog backlog)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(backlog);
|
||||
return backlog.Files switch
|
||||
{
|
||||
0 => "Nessun file già in libreria da copiare qui.",
|
||||
1 => $"Copia anche quello già in libreria: circa {ItalianText.Bytes(backlog.Bytes)}.",
|
||||
var n => $"Copia anche i {ItalianText.Number(n)} già in libreria: circa {ItalianText.Bytes(backlog.Bytes)}.",
|
||||
};
|
||||
}
|
||||
|
||||
private static string WidenText(int files) => files switch
|
||||
{
|
||||
0 => "Nessun file in più da copiare da solo.",
|
||||
1 => "1 file in più si copierà da solo.",
|
||||
var n => $"{ItalianText.Number(n)} file in più si copieranno da soli.",
|
||||
};
|
||||
|
||||
private static string RemoveOwnText(int files, string username) =>
|
||||
$"{ItalianText.Count(files, "file", "file")} di {ItalianText.Handle(username)} {(files == 1 ? "andrà da solo" : "andranno da soli")} nella cartella generale.";
|
||||
|
||||
private static string AccountText(int files, string label) =>
|
||||
$"{ItalianText.Count(files, "file", "file")} {(files == 1 ? "si copierà da solo" : "si copieranno da soli")} in {label}.";
|
||||
|
||||
private static async Task<long> AccountOfAsync(IFebeStorage storage, long? accountId, CancellationToken ct)
|
||||
{
|
||||
if (accountId is not { } id)
|
||||
{
|
||||
throw new BadRequestException("Manca l'account della cartella.");
|
||||
}
|
||||
|
||||
return await storage.Accounts.GetAsync(id, ct).ConfigureAwait(false) is null
|
||||
? throw new BadRequestException("Account sconosciuto.")
|
||||
: id;
|
||||
}
|
||||
|
||||
private static async Task<ExportDestination> StoredAsync(IExportStore exports, long id, CancellationToken ct)
|
||||
{
|
||||
var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa cartella delle copie non c'è più.");
|
||||
return stored.IsRetired ? throw new BadRequestException("Questa cartella è stata tolta.") : stored;
|
||||
}
|
||||
|
||||
/// <summary>The folder chosen in the dialog is the stored one (as <see cref="ExportDestinations.UpdateAsync"/> decides).</summary>
|
||||
private static bool SameFolder(ExportRootOptions root, string? path, string stored)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return ExportPaths.Same(ExportRoots.Resolve(root, path.Trim()), stored);
|
||||
}
|
||||
catch (ExportFolderException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string RunKind(ExportRunKind kind) => kind == ExportRunKind.Recognize ? "recognize" : "copy";
|
||||
|
||||
private static string RunOrigin(ExportRunOrigin origin) => origin == ExportRunOrigin.Automatic ? "automatic" : "manual";
|
||||
|
||||
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
|
||||
public static ExportJobRequest Request(CopyJobRequestDto body, IClock clock)
|
||||
{
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user