E2: motore delle copie esterne (porta, destinazioni, piano, copia)
Prima metà della tappa E2 «Copie esterne» (#58), parte Core e Data: - porta del lavoro lungo: importazione, copia e ricostruzione mai insieme; - radice /esporta in Docker con mountinfo, controllo delle cartelle con il file di prova, destinazioni con «Esporta questo account» acceso se Alberto non ha mai scelto (decisione del 27/11/2026); - filtro «Copie», segni delle tessere e conteggi dell'account sui soli file dovuti (D3); - percorsi «Come la libreria», segmento dell'account nella cartella generale, 240 caratteri, storia in evidenza; - piano di «Copia in…», un lavoro per destinazione, copia in .part con SHA-256 riletto dal disco, nome libero, mai sovrascrivere, adozione per percorso, pausa della destinazione su prova, spazio e FAT32, attesa fuori dalle sessioni del motore, ripresa e recupero; - .part rimossi solo nelle cartelle degli elementi di lavori non finiti; - «Tolto» e «Superato» (agganci in importazione, scaricamenti, doppioni e ricostruzione), mai ricopiati da soli; - rapporti e testi in italiano, prove del lavoro di copia. Interfaccia, API e composizione restano alla parte successiva. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
213b89a618
commit
a112c92893
41 files changed
+5370
-27
No files matched your search
@@ -0,0 +1,387 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»).</summary>
|
||||
/// <param name="Scope">General folder or own folder of an account.</param>
|
||||
/// <param name="AccountId">The account of an own folder; null for the general folder.</param>
|
||||
/// <param name="Path">The folder as chosen (Docker: relative to <c>/esporta</c>, or a full path inside it).</param>
|
||||
/// <param name="Label">Name shown; null: the last segment of the folder.</param>
|
||||
/// <param name="ContentTypes">At least one type.</param>
|
||||
/// <param name="NamingScheme">General scheme; null: «Come la libreria».</param>
|
||||
/// <param name="HighlightNamingScheme">Scheme of highlight collections; null: «Come la libreria».</param>
|
||||
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
|
||||
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
|
||||
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
|
||||
public sealed record DestinationSpec(
|
||||
ExportScope Scope,
|
||||
long? AccountId,
|
||||
string Path,
|
||||
string? Label,
|
||||
ContentTypes ContentTypes,
|
||||
string? NamingScheme,
|
||||
string? HighlightNamingScheme,
|
||||
string? ProfileNamingScheme,
|
||||
bool Automatic = false,
|
||||
bool OnlyNew = true);
|
||||
|
||||
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
|
||||
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>A destination in use that now overlaps a protected folder (WP1.10 of tappa E2).</summary>
|
||||
public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem);
|
||||
|
||||
/// <summary>What Impostazioni and the Dashboard show of a destination.</summary>
|
||||
/// <param name="Destination">The stored row (paused or not).</param>
|
||||
/// <param name="Reachable">The folder answered now (and, in Docker, sits on a usable mount).</param>
|
||||
/// <param name="Problem">Why it is not reachable, or the error of its pause; null when fine.</param>
|
||||
/// <param name="Counts">Copies per state, every state present.</param>
|
||||
/// <param name="FreeBytes">Free space when reachable and measurable.</param>
|
||||
public sealed record ExportDestinationStatus(
|
||||
ExportDestination Destination,
|
||||
bool Reachable,
|
||||
string? Problem,
|
||||
IReadOnlyDictionary<ExportCopyState, int> Counts,
|
||||
long? FreeBytes);
|
||||
|
||||
/// <summary>
|
||||
/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched
|
||||
/// here except through <see cref="ExportFolderCheck"/> (its probe, only in the candidate folder).
|
||||
/// </summary>
|
||||
public sealed class ExportDestinations(ExportEnvironment env)
|
||||
{
|
||||
/// <summary>The answer to «Togli la cartella».</summary>
|
||||
public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono.";
|
||||
|
||||
/// <summary>A destination with an unfinished job cannot be retired nor moved.</summary>
|
||||
public const string UnfinishedRunText = "C'è un lavoro di copia non finito verso questa cartella: finiscilo o annullalo, poi cambia cartella.";
|
||||
|
||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
|
||||
/// <summary>The name shown for a destination: its label, or the last segment of its folder.</summary>
|
||||
public static string Label(ExportDestination destination)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
if (!string.IsNullOrWhiteSpace(destination.Label))
|
||||
{
|
||||
return destination.Label.Trim();
|
||||
}
|
||||
|
||||
var trimmed = ExportPaths.Trim(destination.RootPath);
|
||||
var name = System.IO.Path.GetFileName(trimmed);
|
||||
return string.IsNullOrEmpty(name) ? trimmed : name;
|
||||
}
|
||||
|
||||
/// <summary>The effective destination of an account (D2) with its switch (D1).</summary>
|
||||
public async Task<EffectiveDestination> ResolveAsync(long accountId, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false);
|
||||
var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false);
|
||||
var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(accountId, ct).ConfigureAwait(false));
|
||||
return new EffectiveDestination(accountId, destination, enabled);
|
||||
}
|
||||
|
||||
/// <summary>The effective destination of every account, with one read of each table.</summary>
|
||||
public async Task<IReadOnlyDictionary<long, EffectiveDestination>> ResolveAllAsync(CancellationToken ct)
|
||||
{
|
||||
var accounts = await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false);
|
||||
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||
var switches = await _env.Storage.Exports.ListAccountExportSwitchesAsync(ct).ConfigureAwait(false);
|
||||
var general = destinations.FirstOrDefault(d => d.Scope == ExportScope.General);
|
||||
var own = destinations.Where(d => d.Scope == ExportScope.Account && d.AccountId is not null).ToDictionary(d => d.AccountId!.Value);
|
||||
return accounts.ToDictionary(
|
||||
a => a.Id,
|
||||
a => new EffectiveDestination(
|
||||
a.Id,
|
||||
own.GetValueOrDefault(a.Id) ?? general,
|
||||
ExportAccounts.IsEnabled(switches.TryGetValue(a.Id, out var on) ? on : null)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a destination after checking folder (WP1.3), content types and naming schemes.
|
||||
/// </summary>
|
||||
/// <exception cref="ExportFolderException">The folder cannot be a destination.</exception>
|
||||
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid (Italian message).</exception>
|
||||
public async Task<DestinationSaveResult> CreateAsync(DestinationSpec spec, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var account = await CheckScopeAsync(spec, ct).ConfigureAwait(false);
|
||||
var warnings = ValidateSettings(spec);
|
||||
if (spec.Scope == ExportScope.General && await _env.Storage.Exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
throw new ArgumentException("C'è già una cartella generale: cambiala invece di aggiungerne un'altra.", nameof(spec));
|
||||
}
|
||||
|
||||
if (account is not null && await _env.Storage.Exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
throw new ArgumentException(OwnFolderInUse(account), nameof(spec));
|
||||
}
|
||||
|
||||
var full = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false);
|
||||
var now = _env.Clock.Now;
|
||||
var row = Build(spec, full, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
|
||||
try
|
||||
{
|
||||
return new DestinationSaveResult(await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false), warnings);
|
||||
}
|
||||
catch (DuplicateRecordException)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
account is null ? "C'è già una cartella generale: cambiala invece di aggiungerne un'altra." : OwnFolderInUse(account),
|
||||
nameof(spec));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Changes a destination. The same folder updates the row; another folder retires it and adds a new row (the copies
|
||||
/// stay with the retired one), refused while an unfinished job writes to it.
|
||||
/// </summary>
|
||||
/// <exception cref="KeyNotFoundException">No such destination.</exception>
|
||||
/// <exception cref="ExportFolderException">The new folder cannot be a destination.</exception>
|
||||
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid.</exception>
|
||||
/// <exception cref="InvalidOperationException">An unfinished job uses the old folder.</exception>
|
||||
public async Task<DestinationSaveResult> UpdateAsync(long id, DestinationSpec spec, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var exports = _env.Storage.Exports;
|
||||
var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
|
||||
if (stored.IsRetired)
|
||||
{
|
||||
throw new ArgumentException("Questa cartella è stata tolta: non si modifica più.", nameof(id));
|
||||
}
|
||||
|
||||
if (stored.Scope != spec.Scope || stored.AccountId != spec.AccountId)
|
||||
{
|
||||
throw new ArgumentException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.", nameof(spec));
|
||||
}
|
||||
|
||||
var warnings = ValidateSettings(spec);
|
||||
var now = _env.Clock.Now;
|
||||
string? full = null;
|
||||
try
|
||||
{
|
||||
full = ExportRoots.Resolve(_env.Root, spec.Path);
|
||||
}
|
||||
catch (ExportFolderException)
|
||||
{
|
||||
// Not the same folder: the full check below gives the reason.
|
||||
}
|
||||
|
||||
if (full is not null && ExportPaths.Same(full, stored.RootPath))
|
||||
{
|
||||
var since = !spec.Automatic ? null
|
||||
: stored.Automatic ? stored.AutomaticSince
|
||||
: spec.OnlyNew ? now : (DateTimeOffset?)null;
|
||||
var updated = Build(spec, stored.RootPath, stored.CreatedAt) with
|
||||
{
|
||||
Id = stored.Id,
|
||||
AutomaticSince = since,
|
||||
PausedAt = stored.PausedAt,
|
||||
LastError = stored.LastError,
|
||||
};
|
||||
await exports.UpdateDestinationAsync(updated, ct).ConfigureAwait(false);
|
||||
return new DestinationSaveResult(updated, warnings);
|
||||
}
|
||||
|
||||
if (stored.IsOrphan)
|
||||
{
|
||||
throw new ArgumentException("La cartella di un account rimosso non si cambia: toglila, oppure ridalla all'account quando torna.", nameof(spec));
|
||||
}
|
||||
|
||||
await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false);
|
||||
var newFolder = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false);
|
||||
|
||||
// Two transactions, as the store wants: the old folder is retired with its copies, then the new one is added.
|
||||
await exports.RetireDestinationAsync(id, now, CancellationToken.None).ConfigureAwait(false);
|
||||
var row = Build(spec, newFolder, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null };
|
||||
return new DestinationSaveResult(await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false), warnings);
|
||||
}
|
||||
|
||||
/// <summary>«Togli la cartella»: only the configuration goes; copies and files stay (<see cref="RetiredText"/>).</summary>
|
||||
/// <exception cref="KeyNotFoundException">No such destination.</exception>
|
||||
/// <exception cref="InvalidOperationException">An unfinished job uses it.</exception>
|
||||
public async Task RetireAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var stored = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
|
||||
if (stored.IsRetired)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false);
|
||||
await _env.Storage.Exports.RetireDestinationAsync(id, _env.Clock.Now, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>«Esporta questo account».</summary>
|
||||
/// <exception cref="KeyNotFoundException">No such account.</exception>
|
||||
public async Task SetAccountEnabledAsync(long accountId, bool enabled, CancellationToken ct)
|
||||
{
|
||||
_ = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Account {accountId} non trovato.");
|
||||
await _env.Storage.Exports.SetAccountExportEnabledAsync(accountId, enabled, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Checks a folder for the dialog, before saving (WP1.3).</summary>
|
||||
public async Task<ExportFolderVerdict> CheckFolderAsync(string candidate, CancellationToken ct)
|
||||
{
|
||||
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
|
||||
return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks again every destination in use against the protected folders, with <paramref name="extraAccountFolders"/>
|
||||
/// (an account folder about to be saved). Only overlaps are conflicts: an unreachable folder is checked anyway at the
|
||||
/// start of its next group of copies.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<ExportFolderConflict>> RecheckAsync(IReadOnlyList<string>? extraAccountFolders, CancellationToken ct) =>
|
||||
RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct);
|
||||
|
||||
/// <summary>As <see cref="RecheckAsync"/>, with folders of any kind (a new library root is <see cref="ProtectedFolderKind.Library"/>).</summary>
|
||||
public async Task<IReadOnlyList<ExportFolderConflict>> RecheckAgainstAsync(IReadOnlyList<ProtectedFolder>? extra, CancellationToken ct)
|
||||
{
|
||||
var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||
if (destinations.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var context = await _env.FolderContextAsync(extra, ct).ConfigureAwait(false);
|
||||
var check = _env.CreateFolderCheck();
|
||||
var verdicts = await Task.WhenAll(destinations.Select(async d => (Destination: d, Verdict: await check.CheckAsync(d.RootPath, context, ct).ConfigureAwait(false))))
|
||||
.ConfigureAwait(false);
|
||||
return verdicts
|
||||
.Where(v => v.Verdict.Problem is { IsOverlap: true })
|
||||
.Select(v => new ExportFolderConflict(v.Destination, v.Verdict.Problem!))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>Whether a destination answers now, its pause, its copies and its free space.</summary>
|
||||
/// <exception cref="KeyNotFoundException">No such destination.</exception>
|
||||
public async Task<ExportDestinationStatus> StatusAsync(long id, CancellationToken ct)
|
||||
{
|
||||
var destination = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata.");
|
||||
var counts = await _env.Storage.Exports.CountCopiesAsync(id, ct).ConfigureAwait(false);
|
||||
if (destination.IsRetired)
|
||||
{
|
||||
return new ExportDestinationStatus(destination, false, "Questa cartella è stata tolta.", counts, null);
|
||||
}
|
||||
|
||||
if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mountProblem)
|
||||
{
|
||||
return new ExportDestinationStatus(destination, false, mountProblem, counts, null);
|
||||
}
|
||||
|
||||
bool reachable;
|
||||
try
|
||||
{
|
||||
reachable = await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
reachable = false;
|
||||
}
|
||||
|
||||
if (!reachable)
|
||||
{
|
||||
return new ExportDestinationStatus(
|
||||
destination,
|
||||
false,
|
||||
$"{Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati.",
|
||||
counts,
|
||||
null);
|
||||
}
|
||||
|
||||
long? free;
|
||||
try
|
||||
{
|
||||
free = await Task.Run(() => _env.Disk.FreeBytes(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
free = null;
|
||||
}
|
||||
|
||||
return new ExportDestinationStatus(destination, true, destination.PausedAt is not null ? destination.LastError : null, counts, free);
|
||||
}
|
||||
|
||||
private async Task<Account?> CheckScopeAsync(DestinationSpec spec, CancellationToken ct)
|
||||
{
|
||||
if (spec.Scope == ExportScope.General)
|
||||
{
|
||||
return spec.AccountId is null
|
||||
? null
|
||||
: throw new ArgumentException("La cartella generale non è di un account.", nameof(spec));
|
||||
}
|
||||
|
||||
if (spec.AccountId is not { } accountId)
|
||||
{
|
||||
throw new ArgumentException("Scegli l'account di questa cartella.", nameof(spec));
|
||||
}
|
||||
|
||||
return await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false)
|
||||
?? throw new ArgumentException("Questo account non c'è più.", nameof(spec));
|
||||
}
|
||||
|
||||
/// <summary>Content types and naming schemes; returns the warnings of the schemes.</summary>
|
||||
private static List<string> ValidateSettings(DestinationSpec spec)
|
||||
{
|
||||
if (spec.ContentTypes == ContentTypes.None || (spec.ContentTypes & ~ContentTypes.All) != ContentTypes.None)
|
||||
{
|
||||
throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec));
|
||||
}
|
||||
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
void Check(string? text, NamingSchemeUse use)
|
||||
{
|
||||
if (Clean(text) is not { } scheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var validation = NamingScheme.Validate(scheme, use);
|
||||
errors.AddRange(validation.Errors.Select(e => NamingPreview.Prefix(use) + e));
|
||||
warnings.AddRange(validation.Warnings.Select(w => NamingPreview.Prefix(use) + w));
|
||||
}
|
||||
|
||||
Check(spec.NamingScheme, NamingSchemeUse.General);
|
||||
Check(spec.HighlightNamingScheme, NamingSchemeUse.Highlight);
|
||||
Check(spec.ProfileNamingScheme, NamingSchemeUse.ProfilePicture);
|
||||
return errors.Count > 0 ? throw new ArgumentException(string.Join(" ", errors), nameof(spec)) : warnings;
|
||||
}
|
||||
|
||||
private async Task<string> CheckedFolderAsync(string path, CancellationToken ct)
|
||||
{
|
||||
var verdict = await CheckFolderAsync(path, ct).ConfigureAwait(false);
|
||||
return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath;
|
||||
}
|
||||
|
||||
private async Task EnsureNoUnfinishedRunAsync(long destinationId, CancellationToken ct)
|
||||
{
|
||||
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||
if (unfinished.Any(r => r.DestinationId == destinationId))
|
||||
{
|
||||
throw new InvalidOperationException(UnfinishedRunText);
|
||||
}
|
||||
}
|
||||
|
||||
private static ExportDestination Build(DestinationSpec spec, string root, DateTimeOffset createdAt) => new()
|
||||
{
|
||||
Scope = spec.Scope,
|
||||
AccountId = spec.AccountId,
|
||||
Label = Clean(spec.Label),
|
||||
RootPath = root,
|
||||
ContentTypes = spec.ContentTypes,
|
||||
NamingScheme = Clean(spec.NamingScheme),
|
||||
HighlightNamingScheme = Clean(spec.HighlightNamingScheme),
|
||||
ProfileNamingScheme = Clean(spec.ProfileNamingScheme),
|
||||
Automatic = spec.Automatic,
|
||||
CreatedAt = createdAt,
|
||||
};
|
||||
|
||||
private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
||||
|
||||
private static string OwnFolderInUse(Account account) => $"@{account.Username} ha già una cartella sua: cambiala invece di aggiungerne un'altra.";
|
||||
}
|
||||
Reference in new issue
Block a user