using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»).
/// General folder or own folder of an account.
/// The account of an own folder; null for the general folder.
/// The folder as chosen (Docker: relative to /esporta, or a full path inside it).
/// Name shown; null: the last segment of the folder.
/// At least one type.
/// General scheme; null: «Come la libreria».
/// Scheme of highlight collections; null: «Come la libreria».
/// Scheme of profile pictures; null: «Come la libreria».
/// «Automatica»: stored only in tappa E2 (tappa E5 acts on it).
/// «Solo i nuovi» when «Automatica» is turned on.
/// Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).
/// Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».
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);
/// A saved destination and the warnings of its naming schemes (shown, they do not block).
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList Warnings);
/// A destination in use that now overlaps a protected folder (WP1.10 of tappa E2).
public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem);
/// What Impostazioni and the Dashboard show of a destination.
/// The stored row (paused or not).
/// The folder answered now (and, in Docker, sits on a usable mount).
/// Why it is not reachable, or the error of its pause; null when fine.
/// Copies per state, every state present.
/// Free space when reachable and measurable.
public sealed record ExportDestinationStatus(
ExportDestination Destination,
bool Reachable,
string? Problem,
IReadOnlyDictionary Counts,
long? FreeBytes);
///
/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched
/// here except through (its probe, only in the candidate folder).
///
public sealed class ExportDestinations(ExportEnvironment env)
{
/// The answer to «Togli la cartella».
public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono.";
/// A destination with an unfinished job cannot be retired nor moved.
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));
/// The name shown for a destination: its label, or the last segment of its folder.
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;
}
/// The effective destination of an account (D2) with its switch (D1).
public async Task 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);
}
/// The effective destination of every account, with one read of each table.
public async Task> 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)));
}
///
/// Adds a destination after checking folder (WP1.3), content types and naming schemes.
///
/// The folder cannot be a destination.
/// Types, schemes, scope or account are not valid (Italian message).
public async Task 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));
}
}
///
/// 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.
///
/// No such destination.
/// The new folder cannot be a destination.
/// Types, schemes, scope or account are not valid.
/// An unfinished job uses the old folder.
public async Task 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);
}
/// «Togli la cartella»: only the configuration goes; copies and files stay ().
/// No such destination.
/// An unfinished job uses it.
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);
}
/// «Esporta questo account».
/// No such account.
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);
}
/// Checks a folder for the dialog, before saving (WP1.3).
public async Task CheckFolderAsync(string candidate, CancellationToken ct)
{
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false);
}
///
/// Checks again every destination in use against the protected folders, with
/// (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.
///
public Task> RecheckAsync(IReadOnlyList? extraAccountFolders, CancellationToken ct) =>
RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct);
/// As , with folders of any kind (a new library root is ).
public async Task> RecheckAgainstAsync(IReadOnlyList? 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();
}
///
/// 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.
///
public async Task> 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;
}
/// Whether a destination answers now, its pause, its copies and its free space.
/// No such destination.
public async Task 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 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));
}
/// Content types and naming schemes; returns the warnings of the schemes.
private static List 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();
var warnings = new List();
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 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.";
}