Files
Febe/src/Febe.Core/Export/ExportDestinations.cs
T
Alby96andClaude Opus 5.5 b746aff45d E3: formati e fotogrammi nella copia verso le cartelle esterne
La richiesta di copia porta i formati («Copia in…» per foto e video, poi
la destinazione, poi le impostazioni), i fotogrammi dei video e la «Copia
di nuovo» di una sola copia. Il piano prevede convertiti, copiati com'è e
fotogrammi; il lavoro si ricorda di fotogrammi ed identità esatta per la
ripresa.

La copia converte prima dei controlli di spazio e di FAT32, adotta un file
già presente solo se lunghezza e SHA-256 della conversione coincidono, e
prende i fotogrammi di un video in un solo passaggio, ognuno con il suo
istante esatto come identità. Un file copiato in qualunque forma che non
sia un fotogramma è «già copiato»; un fotogramma non rende mai copiato il
file (nuovo segno FrameOnly). Le note sono un elenco di codici, con i testi
italiani nuovi e il rapporto che mostra i file copiati con una nota.

Le prove dell'archivio e dei piani delle query seguono le nuove ricerche;
due prove nuove coprono una foto convertita e un fotogramma.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:08:38 +01:00

420 lines
21 KiB
C#

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>
/// <param name="PhotoFormat">Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).</param>
/// <param name="VideoFormat">Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».</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,
ExportFormat? PhotoFormat = null,
ExportFormat? VideoFormat = null);
/// <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>
/// After a rebuild of the database (WP1.10 of tappa E2): every destination in use that now overlaps a protected
/// folder is paused with the reason. Nothing is interactive there. Returns the conflicts.
/// </summary>
public async Task<IReadOnlyList<ExportFolderConflict>> RecheckAndPauseAsync(CancellationToken ct)
{
var conflicts = await RecheckAsync(null, ct).ConfigureAwait(false);
foreach (var conflict in conflicts)
{
await ExportPause.PauseAsync(_env, conflict.Destination, conflict.Problem.Message).ConfigureAwait(false);
}
return conflicts;
}
/// <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));
}
// A change of format is not a new folder: the copies already made stay «già copiato» (D3 of tappa E3).
if (spec.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo))
{
throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(spec));
}
if (spec.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video))
{
throw new ArgumentException("Per i video si sceglie Originale o MP4.", 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),
PhotoFormat = spec.PhotoFormat,
VideoFormat = spec.VideoFormat,
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.";
}