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,106 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Febe.Core.Abstractions;
|
||||
|
||||
/// <summary>The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»).</summary>
|
||||
public enum LongWorkKind
|
||||
{
|
||||
/// <summary>An import job: analysis or copy (spec §9).</summary>
|
||||
Import,
|
||||
|
||||
/// <summary>A job of copies to external folders (spec §4.10).</summary>
|
||||
Export,
|
||||
|
||||
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
|
||||
Rebuild,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole
|
||||
/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing
|
||||
/// it twice releases nothing more.
|
||||
/// </summary>
|
||||
public sealed class LongWorkGate
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private Lease? _holder;
|
||||
|
||||
/// <summary>Who holds the gate, or null when it is free.</summary>
|
||||
public LongWorkKind? Busy
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _holder?.Kind;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
|
||||
/// kind, the same one included) holds it.
|
||||
/// </summary>
|
||||
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_holder is { } holder)
|
||||
{
|
||||
lease = null;
|
||||
busyWith = holder.Kind;
|
||||
return false;
|
||||
}
|
||||
|
||||
var taken = new Lease(this, kind);
|
||||
_holder = taken;
|
||||
lease = taken;
|
||||
busyWith = null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Italian answer when <paramref name="wanted"/> cannot start because <paramref name="busy"/> is running.</summary>
|
||||
public static string BusyMessage(LongWorkKind wanted, LongWorkKind busy) => (wanted, busy) switch
|
||||
{
|
||||
(LongWorkKind.Import, LongWorkKind.Import) => "C'è già un'importazione al lavoro: aspetta che finisca o interrompila.",
|
||||
(LongWorkKind.Export, LongWorkKind.Export) => "C'è già una copia al lavoro: aspetta che finisca o interrompila.",
|
||||
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
|
||||
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||
};
|
||||
|
||||
private static string Verb(LongWorkKind kind) => kind switch
|
||||
{
|
||||
LongWorkKind.Import => "importa",
|
||||
LongWorkKind.Export => "copia",
|
||||
_ => "ricostruisci",
|
||||
};
|
||||
|
||||
private void Release(Lease lease)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReferenceEquals(_holder, lease))
|
||||
{
|
||||
_holder = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public LongWorkKind Kind { get; } = kind;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
gate.Release(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>Whether the engine is in a session now: copies never run during one (spec §4.10, decision D11 of tappa E2).</summary>
|
||||
public interface IEngineSessionState
|
||||
{
|
||||
bool InSession { get; }
|
||||
}
|
||||
|
||||
/// <summary>No engine (tests, a start with problems): never in a session.</summary>
|
||||
public sealed class NoEngineSession : IEngineSessionState
|
||||
{
|
||||
public static readonly NoEngineSession Instance = new();
|
||||
|
||||
private NoEngineSession()
|
||||
{
|
||||
}
|
||||
|
||||
public bool InSession => false;
|
||||
}
|
||||
|
||||
/// <summary>The session of the running engine.</summary>
|
||||
public sealed class RuntimeSessionState(EngineRuntime runtime) : IEngineSessionState
|
||||
{
|
||||
private readonly EngineRuntime _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
|
||||
|
||||
public bool InSession => _runtime.CurrentSession is not null;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>«Esporta questo account» (spec §4.10).</summary>
|
||||
public static class ExportAccounts
|
||||
{
|
||||
/// <summary>On when Alberto never chose: decision of Alberto, 27 November 2026 (D1 of tappa E2).</summary>
|
||||
public const bool DefaultEnabled = true;
|
||||
|
||||
/// <summary>The switch of an account from its stored choice (null: none recorded).</summary>
|
||||
public static bool IsEnabled(bool? stored) => stored ?? DefaultEnabled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The effective destination of an account (D2): its own folder in use, otherwise the general folder in use, otherwise
|
||||
/// none; with the switch «Esporta questo account».
|
||||
/// </summary>
|
||||
public sealed record EffectiveDestination(long AccountId, ExportDestination? Destination, bool Enabled)
|
||||
{
|
||||
/// <summary>The account's own folder.</summary>
|
||||
public bool IsOwn => Destination?.Scope == ExportScope.Account;
|
||||
|
||||
public bool HasDestination => Destination is not null;
|
||||
|
||||
/// <summary>The switch is on and there is a destination: files of the account may be copied (D3).</summary>
|
||||
public bool Exports => Enabled && Destination is not null;
|
||||
|
||||
/// <summary>The account's files of this content type are copied (D3, D4).</summary>
|
||||
public bool Wants(ContentTypes type) => Exports && (Destination!.ContentTypes & type) != ContentTypes.None;
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// One export job towards one destination (spec §4.10 «Come si copia»; decisions D11, D12, D16, D17 of tappa E2):
|
||||
/// <list type="bullet">
|
||||
/// <item>before each group of files (at most <see cref="ExportEnvironment.GroupFiles"/> files, or until
|
||||
/// <see cref="ExportEnvironment.GroupBytes"/> bytes are reached) the destination is checked with a probe file; a failed
|
||||
/// check pauses the destination and the job, never the red strip;</item>
|
||||
/// <item>each file is written to a <c>.part</c> in its final folder, hashed while writing, read back from the disk and
|
||||
/// compared, compared with the library's SHA-256, then renamed to a free name: nothing is ever overwritten, and no
|
||||
/// other file of the destination is deleted or moved;</item>
|
||||
/// <item>a file already at the planned path with the same SHA-256 is adopted, not written again;</item>
|
||||
/// <item>«Tolto» and «Superato» are never copied again by themselves, only with «Copia di nuovo»;</item>
|
||||
/// <item>nothing is copied during an engine session: the job waits;</item>
|
||||
/// <item>resumable: every file has its state, and the target path is recorded before its <c>.part</c> exists.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class ExportCopier(ExportEnvironment env)
|
||||
{
|
||||
private const int PageSize = 500;
|
||||
private const int MaxSiblings = 1000;
|
||||
private const int MaxPath = WindowsFileNames.MaxPathLength;
|
||||
|
||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
|
||||
/// <summary>
|
||||
/// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation
|
||||
/// the job becomes «interrotto» and <see cref="OperationCanceledException"/> is thrown.
|
||||
/// </summary>
|
||||
/// <exception cref="KeyNotFoundException">No such job.</exception>
|
||||
/// <exception cref="InvalidOperationException">The job already ended.</exception>
|
||||
public async Task<ExportRun> CopyAsync(long runId, IProgress<ExportProgress>? progress = null, CancellationToken ct = default)
|
||||
{
|
||||
var store = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var run = await store.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
|
||||
if (run.State is not (ExportRunState.Running or ExportRunState.Interrupted or ExportRunState.Paused))
|
||||
{
|
||||
throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere.");
|
||||
}
|
||||
|
||||
var destination = await store.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false);
|
||||
if (destination is null || destination.IsRetired)
|
||||
{
|
||||
run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = ExportText.RetiredDestination };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
|
||||
return run;
|
||||
}
|
||||
|
||||
run = run with { State = ExportRunState.Running, LastError = null };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
var x = new RunContext(run, destination, progress);
|
||||
try
|
||||
{
|
||||
x.Report(_env, ExportPhase.Preparing, null);
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
var layout = _env.Layout();
|
||||
var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
x.Naming = library.Naming;
|
||||
x.SetFileTime = library.SetFileTimeToPublication;
|
||||
x.OneOnly = settings.SamePost == SamePostCopies.OneOnly;
|
||||
x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false);
|
||||
var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false);
|
||||
x.FilesTotal = summary.Total;
|
||||
x.FilesDone = summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending);
|
||||
x.ByState = new Dictionary<ExportItemState, int>(summary.ByState);
|
||||
x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false);
|
||||
|
||||
var groupFiles = 0;
|
||||
long groupBytes = 0;
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
foreach (var item in page)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
|
||||
{
|
||||
return await PauseAsync(x, problem).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false);
|
||||
var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false);
|
||||
if (result.Pause is { } pause)
|
||||
{
|
||||
return await PauseAsync(x, pause).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
x.FilesDone++;
|
||||
x.BytesDone += result.Bytes;
|
||||
x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1);
|
||||
x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1;
|
||||
groupFiles++;
|
||||
groupBytes += result.Bytes;
|
||||
if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes)
|
||||
{
|
||||
groupFiles = 0;
|
||||
groupBytes = 0;
|
||||
}
|
||||
|
||||
x.Report(_env, ExportPhase.Copying, result.Path);
|
||||
}
|
||||
}
|
||||
|
||||
var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false);
|
||||
run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = _env.Clock.Now,
|
||||
Code = "esportazione-completata",
|
||||
Message = ExportText.CompletionMessage(final, x.Destination),
|
||||
Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success,
|
||||
AccountId = x.Destination.AccountId,
|
||||
},
|
||||
none).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false);
|
||||
x.ByState = new Dictionary<ExportItemState, int>(final.ByState);
|
||||
x.Report(_env, ExportPhase.Finished, null);
|
||||
return run;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested;
|
||||
run = run with { State = ExportRunState.Interrupted, LastError = cancelled ? null : ExportText.ErrorText(ex) };
|
||||
await store.UpdateRunAsync(run, none).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks a destination before a group of copies: the mount rule in Docker, then the folder check with its probe
|
||||
/// file and the identity test (WP1.3). Returns why it cannot be written, or null; a success clears its pause.
|
||||
/// </summary>
|
||||
internal async Task<string?> CheckDestinationAsync(ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mount)
|
||||
{
|
||||
return mount;
|
||||
}
|
||||
|
||||
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
|
||||
var verdict = await _env.CreateFolderCheck().CheckAsync(destination.RootPath, context, ct).ConfigureAwait(false);
|
||||
return verdict.Problem switch
|
||||
{
|
||||
null => null,
|
||||
{ Kind: ExportFolderProblemKind.Missing or ExportFolderProblemKind.NotResponding } =>
|
||||
$"{ExportDestinations.Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati, poi riprendi.",
|
||||
{ } problem => problem.Message,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<string?> ProbeAsync(RunContext x, CancellationToken ct)
|
||||
{
|
||||
var problem = await CheckDestinationAsync(x.Destination, ct).ConfigureAwait(false);
|
||||
if (problem is null && (x.Destination.PausedAt is not null || x.Destination.LastError is not null))
|
||||
{
|
||||
x.Destination = await ExportPause.ClearAsync(_env, x.Destination).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return problem;
|
||||
}
|
||||
|
||||
private async Task<ExportRun> PauseAsync(RunContext x, string message)
|
||||
{
|
||||
x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false);
|
||||
var run = x.Run with { State = ExportRunState.Paused, LastError = message };
|
||||
await _env.Storage.Exports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false);
|
||||
x.Report(_env, ExportPhase.Finished, null);
|
||||
return run;
|
||||
}
|
||||
|
||||
private async Task WaitOutsideSessionAsync(RunContext x, CancellationToken ct)
|
||||
{
|
||||
while (_env.Session.InSession)
|
||||
{
|
||||
x.Report(_env, ExportPhase.WaitingForSession, null);
|
||||
await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<long> PendingBytesAsync(long runId, CancellationToken ct)
|
||||
{
|
||||
long total = 0;
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await _env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
return total;
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
foreach (var item in page)
|
||||
{
|
||||
if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes })
|
||||
{
|
||||
total += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ItemResult> ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct)
|
||||
{
|
||||
var storage = _env.Storage;
|
||||
var exports = storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var destination = x.Destination;
|
||||
var root = destination.RootPath;
|
||||
|
||||
// a. No longer in the library.
|
||||
if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null;
|
||||
var entry = media is null ? null : await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
|
||||
var source = media is { Sha256.Length: 64, RelativePath: not null } && EntryStateRules.IsPresent(media.State) && entry?.AccountId == accountId
|
||||
? _env.ResolveSourcePath(account, media)
|
||||
: null;
|
||||
if (source is null || media is null || entry is null)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The account may have been switched off, or got another folder, or the destination stopped taking this type
|
||||
// since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy.
|
||||
var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false);
|
||||
if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id
|
||||
|| !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight)))
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// b. The file may have changed since the job was planned.
|
||||
var sha = media.Sha256!;
|
||||
if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal))
|
||||
{
|
||||
item = item with { SourceSha256 = sha };
|
||||
}
|
||||
|
||||
var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0;
|
||||
var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null);
|
||||
var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight);
|
||||
|
||||
// c. Already copied, removed, superseded, copied for another account, or failed before.
|
||||
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
ExportCopy? failed = null;
|
||||
if (current is { State: ExportCopyState.Copied })
|
||||
{
|
||||
if (current.RelativePath is { } copied && Exists(root, copied))
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The file is not there: «Tolto», unless the whole destination went away meanwhile.
|
||||
if (!Directory.Exists(root) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone)
|
||||
{
|
||||
return ItemResult.Paused(gone);
|
||||
}
|
||||
|
||||
await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false);
|
||||
if (!x.CopyAgain)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (current is { State: ExportCopyState.Failed })
|
||||
{
|
||||
failed = current;
|
||||
}
|
||||
else if (!x.CopyAgain)
|
||||
{
|
||||
var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded })
|
||||
{
|
||||
var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded;
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (x.OneOnly
|
||||
&& await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { AccountId: { } other, RelativePath: { } elsewherePath } elsewhere
|
||||
&& other != accountId
|
||||
&& await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where
|
||||
&& Exists(where.RootPath, elsewherePath))
|
||||
{
|
||||
return await FinishAsync(
|
||||
item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null },
|
||||
bytes,
|
||||
null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>d. and e.: the path, the limits of the disk, adoption, the safe write and its record.</summary>
|
||||
private async Task<ItemResult> WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var destination = x.Destination;
|
||||
var root = destination.RootPath;
|
||||
|
||||
string planned;
|
||||
try
|
||||
{
|
||||
planned = ExportPaths.RelativePathFor(
|
||||
destination,
|
||||
ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone),
|
||||
MaxPath);
|
||||
}
|
||||
catch (PathTooLongException ex)
|
||||
{
|
||||
return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max)
|
||||
{
|
||||
return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin)
|
||||
{
|
||||
return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes));
|
||||
}
|
||||
|
||||
// Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …).
|
||||
foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath))
|
||||
{
|
||||
var full = LibraryLayout.FullPath(root, candidate);
|
||||
if (_env.FileSystem.FileLength(full) != file.Bytes
|
||||
|| !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false);
|
||||
if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal)))
|
||||
{
|
||||
return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (holder.Identity == file.Identity)
|
||||
{
|
||||
return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The same bytes, recorded for another copy: not ours to take.
|
||||
}
|
||||
|
||||
// A path recorded for another copy whose file is gone is free again («Tolto»).
|
||||
await ReleaseStalePathAsync(destination, planned, file.Identity, ct).ConfigureAwait(false);
|
||||
|
||||
// The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items).
|
||||
item = item with { RelativePath = planned };
|
||||
await exports.UpdateItemsAsync([item], none).ConfigureAwait(false);
|
||||
|
||||
SavedFile saved;
|
||||
try
|
||||
{
|
||||
var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty;
|
||||
await using var content = _env.FileSystem.OpenRead(file.Source);
|
||||
saved = (await new SafeFileWriter(MaxPath).SaveAsync(
|
||||
content,
|
||||
root,
|
||||
directory,
|
||||
(digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal)
|
||||
? ValueTask.FromResult<string?>(planned)
|
||||
: throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."),
|
||||
new SafeWriteOptions
|
||||
{
|
||||
RequireExistingRoot = true,
|
||||
VerifyFromDisk = true,
|
||||
LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null,
|
||||
},
|
||||
ct).ConfigureAwait(false))!;
|
||||
}
|
||||
catch (ContentChangedException ex)
|
||||
{
|
||||
return await FailAsync(item, file, failed, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (IsDiskFull(ex))
|
||||
{
|
||||
return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left
|
||||
? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes)
|
||||
: ExportText.DiskFull(destination));
|
||||
}
|
||||
|
||||
if ((ex is ExportRootMissingException or DirectoryNotFoundException || !Directory.Exists(root)) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem)
|
||||
{
|
||||
return ItemResult.Paused(problem); // the item stays pending
|
||||
}
|
||||
|
||||
return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
string? taken = null;
|
||||
if (!string.Equals(saved.RelativePath, planned, StringComparison.Ordinal))
|
||||
{
|
||||
taken = ExportText.Notes.NameTaken;
|
||||
await ReleaseStalePathAsync(destination, saved.RelativePath, file.Identity, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names.</summary>
|
||||
private IEnumerable<string> AdoptionCandidates(string root, string planned, string? previous)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (seen.Add(planned) && Exists(root, planned))
|
||||
{
|
||||
yield return planned;
|
||||
}
|
||||
|
||||
if (previous is null)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
for (var attempt = 1; attempt <= MaxSiblings; attempt++)
|
||||
{
|
||||
string name;
|
||||
try
|
||||
{
|
||||
name = ExportPaths.NumberedName(root, previous, attempt, MaxPath);
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!Exists(root, name))
|
||||
{
|
||||
yield break; // the writer takes the first free name: nothing of ours after it
|
||||
}
|
||||
|
||||
if (seen.Add(name))
|
||||
{
|
||||
yield return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Copied or Superseded row of another copy on this path whose file is not there becomes «Tolto».</summary>
|
||||
private async Task ReleaseStalePathAsync(ExportDestination destination, string path, ExportCopyIdentity identity, CancellationToken ct)
|
||||
{
|
||||
var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false);
|
||||
if (held is not null && held.Identity != identity && !Exists(destination.RootPath, path))
|
||||
{
|
||||
await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ItemResult> RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
var now = _env.Clock.Now;
|
||||
ExportCopy copy;
|
||||
try
|
||||
{
|
||||
if (failed is not null)
|
||||
{
|
||||
copy = failed with
|
||||
{
|
||||
State = ExportCopyState.Copied,
|
||||
Origin = origin,
|
||||
RelativePath = path,
|
||||
Bytes = bytes,
|
||||
CopySha256 = file.Sha256,
|
||||
CopiedAt = now,
|
||||
StateChangedAt = now,
|
||||
LastError = null,
|
||||
MediaId = file.Media.Id,
|
||||
};
|
||||
await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false);
|
||||
}
|
||||
else if (orphan is not null)
|
||||
{
|
||||
copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
copy = await exports.AddCopyAsync(
|
||||
new ExportCopy
|
||||
{
|
||||
DestinationId = file.Identity.DestinationId,
|
||||
AccountId = file.Identity.AccountId,
|
||||
MediaId = file.Media.Id,
|
||||
SourceSha256 = file.Sha256,
|
||||
Variant = ExportVariant.Whole,
|
||||
Format = ExportFormat.Original,
|
||||
State = ExportCopyState.Copied,
|
||||
Origin = origin,
|
||||
RelativePath = path,
|
||||
Bytes = bytes,
|
||||
CopySha256 = file.Sha256,
|
||||
CopiedAt = now,
|
||||
},
|
||||
none).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (DuplicateRecordException)
|
||||
{
|
||||
// Taken meanwhile by another record. The file written stays where it is: nothing is ever removed.
|
||||
return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied;
|
||||
return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on.</summary>
|
||||
private async Task<ItemResult> FailAsync(ExportItem item, FileContext file, ExportCopy? failed, string error, string? note)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var none = CancellationToken.None;
|
||||
long? copyId = failed?.Id;
|
||||
try
|
||||
{
|
||||
if (failed is not null)
|
||||
{
|
||||
await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
copyId = (await exports.AddCopyAsync(
|
||||
new ExportCopy
|
||||
{
|
||||
DestinationId = file.Identity.DestinationId,
|
||||
AccountId = file.Identity.AccountId,
|
||||
MediaId = file.Media.Id,
|
||||
SourceSha256 = file.Sha256,
|
||||
Variant = ExportVariant.Whole,
|
||||
Format = ExportFormat.Original,
|
||||
State = ExportCopyState.Failed,
|
||||
CopiedAt = _env.Clock.Now,
|
||||
LastError = error,
|
||||
},
|
||||
none).ConfigureAwait(false)).Id;
|
||||
}
|
||||
}
|
||||
catch (DuplicateRecordException)
|
||||
{
|
||||
// The identity got a current row meanwhile: that one tells the state.
|
||||
}
|
||||
|
||||
return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<ItemResult> FinishAsync(ExportItem item, long bytes, string? path)
|
||||
{
|
||||
await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false);
|
||||
return new ItemResult(item.State, bytes, path, null);
|
||||
}
|
||||
|
||||
private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct)
|
||||
{
|
||||
if (entry.Kind is not (EntryKind.Story or EntryKind.Highlight))
|
||||
{
|
||||
return (null, false);
|
||||
}
|
||||
|
||||
var collections = await _env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false);
|
||||
return (collections.FirstOrDefault()?.Title, collections.Count > 0);
|
||||
}
|
||||
|
||||
private bool Exists(string root, string relativePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>«Disco pieno»: ERROR_DISK_FULL or ERROR_HANDLE_DISK_FULL on Windows, ENOSPC elsewhere.</summary>
|
||||
internal static bool IsDiskFull(Exception ex) =>
|
||||
ex is IOException io
|
||||
&& (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28
|
||||
|| io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight);
|
||||
|
||||
/// <summary>What happened to an item; <see cref="Pause"/> stops the job with the destination paused.</summary>
|
||||
private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause)
|
||||
{
|
||||
public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message);
|
||||
}
|
||||
|
||||
private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress<ExportProgress>? progress)
|
||||
{
|
||||
private readonly Dictionary<long, ExportDestination?> _destinations = [];
|
||||
|
||||
public ExportRun Run { get; } = run;
|
||||
|
||||
public ExportDestination Destination { get; set; } = destination;
|
||||
|
||||
public LibraryNaming? Naming { get; set; }
|
||||
|
||||
public bool SetFileTime { get; set; } = true;
|
||||
|
||||
public bool OneOnly { get; set; }
|
||||
|
||||
public bool CopyAgain { get; set; }
|
||||
|
||||
public IReadOnlyDictionary<long, EffectiveDestination> Effective { get; set; } = new Dictionary<long, EffectiveDestination>();
|
||||
|
||||
public int FilesDone { get; set; }
|
||||
|
||||
public int FilesTotal { get; set; }
|
||||
|
||||
public long BytesDone { get; set; }
|
||||
|
||||
public long BytesTotal { get; set; }
|
||||
|
||||
public Dictionary<ExportItemState, int> ByState { get; set; } = [];
|
||||
|
||||
public async Task<ExportDestination?> DestinationAsync(IFebeStorage storage, long id, CancellationToken ct)
|
||||
{
|
||||
if (!_destinations.TryGetValue(id, out var row))
|
||||
{
|
||||
_destinations[id] = row = await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
public void Report(ExportEnvironment env, ExportPhase phase, string? current) =>
|
||||
progress?.Report(new ExportProgress(
|
||||
Run.Id,
|
||||
phase,
|
||||
FilesDone,
|
||||
FilesTotal,
|
||||
BytesDone,
|
||||
Math.Max(BytesTotal, BytesDone),
|
||||
current,
|
||||
ExportDestinations.Label(Destination),
|
||||
new Dictionary<ExportItemState, int>(ByState),
|
||||
env.Clock.Now));
|
||||
}
|
||||
}
|
||||
@@ -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.";
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Febe.Core.Alerts;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>Free space and the largest file a destination's disk accepts (a seam: tests give their own).</summary>
|
||||
public interface IExportDisk
|
||||
{
|
||||
/// <summary>Bytes free for Febe on the disk of <paramref name="root"/>; null when it cannot be measured.</summary>
|
||||
long? FreeBytes(string root);
|
||||
|
||||
/// <summary>The largest file the file system accepts (FAT32: 4 GB − 1); null when there is no known limit.</summary>
|
||||
long? MaxFileBytes(string root);
|
||||
}
|
||||
|
||||
/// <summary>Limits of the space check before each copy (spec §4.10 «Spazio»).</summary>
|
||||
public static class ExportSpace
|
||||
{
|
||||
/// <summary>The margin left free after the next file (decision of Alberto, question Q6 of tappa E2): 64 MiB.</summary>
|
||||
public const long Margin = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>The largest file on FAT32: 4 GiB − 1 byte.</summary>
|
||||
public const long Fat32Limit = (4L * 1024 * 1024 * 1024) - 1;
|
||||
|
||||
private static readonly HashSet<string> FatTypes = new(StringComparer.OrdinalIgnoreCase) { "FAT32", "FAT", "vfat", "msdos", "fat" };
|
||||
|
||||
/// <summary>True for the names Windows (<c>DriveFormat</c>) and Linux (mount type) give to FAT file systems.</summary>
|
||||
public static bool IsFat(string? fileSystem) => fileSystem is not null && FatTypes.Contains(fileSystem);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real disks: free space through <see cref="DriveFreeSpaceProbe"/> (a UNC share gives null: the Windows edition
|
||||
/// registers its own measure), the FAT32 limit from the drive format on Windows and from the mount type on Linux.
|
||||
/// </summary>
|
||||
public sealed class SystemExportDisk(IExportMounts mounts) : IExportDisk
|
||||
{
|
||||
private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts));
|
||||
|
||||
public long? FreeBytes(string root)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return new DriveFreeSpaceProbe().Measure(root)?.AvailableBytes;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public long? MaxFileBytes(string root)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(root))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string? type;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var drive = Path.GetPathRoot(Path.GetFullPath(root));
|
||||
type = string.IsNullOrEmpty(drive) || drive.StartsWith(@"\\", StringComparison.Ordinal) ? null : new DriveInfo(drive).DriveFormat;
|
||||
}
|
||||
else
|
||||
{
|
||||
type = _mounts.FindContaining(Path.GetFullPath(root))?.FileSystemType;
|
||||
}
|
||||
|
||||
return ExportSpace.IsFat(type) ? ExportSpace.Fat32Limit : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// What the export needs from the rest of Febe (spec §4.10). Built once by the composition (the web layer's export
|
||||
/// hub); the layout is a function because on Windows the library folder can change while Febe runs.
|
||||
/// </summary>
|
||||
public sealed record ExportEnvironment
|
||||
{
|
||||
public required IFebeStorage Storage { get; init; }
|
||||
|
||||
/// <summary>The library folder and account folders now.</summary>
|
||||
public required Func<LibraryLayout> Layout { get; init; }
|
||||
|
||||
/// <summary>The Data folder: a destination may not overlap it.</summary>
|
||||
public required string DataFolder { get; init; }
|
||||
|
||||
public required IClock Clock { get; init; }
|
||||
|
||||
/// <summary>Docker <c>/importa</c>: a destination may not overlap it. Null on Windows.</summary>
|
||||
public string? ImportRoot { get; init; }
|
||||
|
||||
/// <summary>Where destinations may be chosen (Docker: <c>/esporta</c>).</summary>
|
||||
public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder;
|
||||
|
||||
/// <summary>
|
||||
/// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's
|
||||
/// <c>LibraryFileResolver</c>). Use <see cref="ResolveSourcePath"/>.
|
||||
/// </summary>
|
||||
public Func<Account, Media, string?>? ResolveSource { get; init; }
|
||||
|
||||
/// <summary>Reading and hashing files (library files and files found in a destination).</summary>
|
||||
public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance;
|
||||
|
||||
/// <summary>Free space and the FAT32 limit of a destination.</summary>
|
||||
public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo());
|
||||
|
||||
/// <summary>Copies never run during an engine session.</summary>
|
||||
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
|
||||
|
||||
/// <summary>Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests).</summary>
|
||||
public LongWorkGate? Gate { get; init; }
|
||||
|
||||
/// <summary>Time allowed to a check of a destination folder (a disconnected share must not block).</summary>
|
||||
public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>How often a waiting job looks whether the engine session ended.</summary>
|
||||
public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>A group of copies, checked with a probe before it starts: at most this many files…</summary>
|
||||
public int GroupFiles { get; init; } = 100;
|
||||
|
||||
/// <summary>…or this many planned bytes, whichever comes first.</summary>
|
||||
public long GroupBytes { get; init; } = 1L << 30;
|
||||
|
||||
/// <summary>The checker of destination folders of this environment.</summary>
|
||||
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout);
|
||||
|
||||
/// <summary>The protected folders now (Data, library, account folders, <c>/importa</c>) and the extra ones.</summary>
|
||||
public Task<ExportFolderContext> FolderContextAsync(IReadOnlyList<ProtectedFolder>? extra, CancellationToken ct) =>
|
||||
ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct);
|
||||
|
||||
/// <summary>The full path of a library file present on disk, or null (<see cref="ResolveSource"/> or the layout).</summary>
|
||||
public string? ResolveSourcePath(Account account, Media media)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(media);
|
||||
if (ResolveSource is { } resolve)
|
||||
{
|
||||
return resolve(account, media);
|
||||
}
|
||||
|
||||
if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var path = Layout().FullPath(account, media.RelativePath);
|
||||
return FileSystem.FileExists(path) ? path : null;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>File operations of the export (a seam, like <c>IImportFileSystem</c>).</summary>
|
||||
public interface IExportFileSystem
|
||||
{
|
||||
/// <summary>Opens a file for reading only.</summary>
|
||||
Stream OpenRead(string path);
|
||||
|
||||
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
|
||||
Task<string> ComputeSha256Async(string path, CancellationToken ct);
|
||||
|
||||
bool FileExists(string path);
|
||||
|
||||
/// <summary>Size of a file, or null when it is not there.</summary>
|
||||
long? FileLength(string path);
|
||||
}
|
||||
|
||||
/// <summary>The real file system.</summary>
|
||||
public sealed class ExportFileSystem : IExportFileSystem
|
||||
{
|
||||
private const int BufferSize = 128 * 1024;
|
||||
|
||||
private ExportFileSystem()
|
||||
{
|
||||
}
|
||||
|
||||
public static ExportFileSystem Instance { get; } = new();
|
||||
|
||||
public Stream OpenRead(string path) =>
|
||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
|
||||
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||
{
|
||||
await using var stream = OpenRead(path);
|
||||
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public bool FileExists(string path) => File.Exists(path);
|
||||
|
||||
public long? FileLength(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
return info.Exists ? info.Length : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>Why a folder cannot be a destination (spec §4.10 «Cartelle rifiutate»).</summary>
|
||||
public enum ExportFolderProblemKind
|
||||
{
|
||||
Empty,
|
||||
NotFullyQualified,
|
||||
OutsideExportRoot,
|
||||
ExportRootItself,
|
||||
ParentSegment,
|
||||
NotMounted,
|
||||
ReadOnlyMount,
|
||||
Missing,
|
||||
NotAFolder,
|
||||
Link,
|
||||
RootOfDisk,
|
||||
PathTooLong,
|
||||
InsideProtected,
|
||||
ContainsProtected,
|
||||
SameAsProtected,
|
||||
ProbeFailed,
|
||||
NotResponding,
|
||||
}
|
||||
|
||||
/// <summary>A refused folder: the kind and the Italian message that says why and what to do.</summary>
|
||||
public sealed record ExportFolderProblem(ExportFolderProblemKind Kind, string Message)
|
||||
{
|
||||
/// <summary>The folder overlaps Data, Libreria, an account folder or <c>/importa</c> (the conflicts of a re-check).</summary>
|
||||
public bool IsOverlap => Kind is ExportFolderProblemKind.InsideProtected or ExportFolderProblemKind.ContainsProtected or ExportFolderProblemKind.SameAsProtected;
|
||||
}
|
||||
|
||||
/// <summary>The outcome of a folder check.</summary>
|
||||
/// <param name="FullPath">The full path of the candidate (as typed when it could not be resolved).</param>
|
||||
/// <param name="Problem">Null when the folder is accepted.</param>
|
||||
public sealed record ExportFolderVerdict(string FullPath, ExportFolderProblem? Problem)
|
||||
{
|
||||
public bool Accepted => Problem is null;
|
||||
}
|
||||
|
||||
/// <summary>What a protected folder is.</summary>
|
||||
public enum ProtectedFolderKind
|
||||
{
|
||||
/// <summary>The Data folder.</summary>
|
||||
Data,
|
||||
|
||||
/// <summary>The library folder.</summary>
|
||||
Library,
|
||||
|
||||
/// <summary>The folder of an account (inside the library or outside it).</summary>
|
||||
Account,
|
||||
|
||||
/// <summary>The root of the import sources (Docker <c>/importa</c>).</summary>
|
||||
Import,
|
||||
}
|
||||
|
||||
/// <summary>A folder a destination may neither be, sit inside nor contain.</summary>
|
||||
/// <param name="Path">Full path.</param>
|
||||
/// <param name="Kind">What it is (for the message).</param>
|
||||
/// <param name="Username">The account of an account folder, when known.</param>
|
||||
public sealed record ProtectedFolder(string Path, ProtectedFolderKind Kind, string? Username)
|
||||
{
|
||||
/// <summary>«la cartella dei dati di Febe», «la cartella dell'account @x»…</summary>
|
||||
public string Description => Kind switch
|
||||
{
|
||||
ProtectedFolderKind.Data => "la cartella dei dati di Febe",
|
||||
ProtectedFolderKind.Library => "la cartella della libreria",
|
||||
ProtectedFolderKind.Import => "la cartella delle importazioni",
|
||||
_ => Username is { Length: > 0 } name ? $"la cartella dell'account @{name}" : "la cartella di un account",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The folders a candidate is checked against, and where destinations may be chosen.</summary>
|
||||
public sealed record ExportFolderContext(IReadOnlyList<ProtectedFolder> Protected, ExportRootOptions Root);
|
||||
|
||||
/// <summary>A folder or path that cannot be used as a destination; the message (Italian) says why. The API answers 400.</summary>
|
||||
public sealed class ExportFolderException : IOException
|
||||
{
|
||||
public ExportFolderException()
|
||||
{
|
||||
}
|
||||
|
||||
public ExportFolderException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public ExportFolderException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public ExportFolderException(string message, ExportFolderProblemKind kind)
|
||||
: base(message) => Kind = kind;
|
||||
|
||||
/// <summary>The kind of refusal, when known.</summary>
|
||||
public ExportFolderProblemKind? Kind { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks a candidate destination folder (spec §4.10, decision D13 of tappa E2): textual checks first, then the
|
||||
/// identity test with a probe file written and removed <b>only in the candidate</b>, so that a drive letter and a UNC
|
||||
/// path to the same place are recognised. In Data, Libreria, the account folders and <c>/importa</c> the probe is only
|
||||
/// looked for, read-only. Everything that touches the disk runs in the background with a timeout (10 s by default): a
|
||||
/// disconnected share never blocks the caller.
|
||||
/// </summary>
|
||||
public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null)
|
||||
{
|
||||
/// <summary>Prefix of the probe file (a temporary file of <see cref="SafeFileWriter"/>: <c>.febe-prova-*.part</c>).</summary>
|
||||
public const string ProbePrefix = SafeFileWriter.TempPrefix + "prova-";
|
||||
|
||||
private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts));
|
||||
private readonly TimeSpan _timeout = timeout ?? TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>A new probe file name: <c>.febe-prova-<12 hex>.part</c>.</summary>
|
||||
public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix;
|
||||
|
||||
/// <summary>
|
||||
/// The protected folders: Data, the library, the folder of every account (outside the library too), the extra
|
||||
/// folders (an account folder or a library root about to be saved) and the import root.
|
||||
/// </summary>
|
||||
public static async Task<ExportFolderContext> ContextAsync(
|
||||
IFebeStorage storage,
|
||||
LibraryLayout layout,
|
||||
string dataFolder,
|
||||
string? importRoot,
|
||||
ExportRootOptions root,
|
||||
IReadOnlyList<ProtectedFolder>? extra = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(layout);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
|
||||
ArgumentNullException.ThrowIfNull(root);
|
||||
var folders = new List<ProtectedFolder>
|
||||
{
|
||||
new(Full(dataFolder), ProtectedFolderKind.Data, null),
|
||||
new(Full(layout.Root), ProtectedFolderKind.Library, null),
|
||||
};
|
||||
foreach (var account in await storage.Accounts.ListAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
string folder;
|
||||
try
|
||||
{
|
||||
folder = Full(layout.AccountFolder(account));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
continue; // an unusable stored folder protects nothing
|
||||
}
|
||||
|
||||
folders.Add(new ProtectedFolder(folder, ProtectedFolderKind.Account, account.Username));
|
||||
}
|
||||
|
||||
foreach (var folder in extra ?? [])
|
||||
{
|
||||
folders.Add(folder with { Path = Full(folder.Path) });
|
||||
}
|
||||
|
||||
if (importRoot is { Length: > 0 })
|
||||
{
|
||||
folders.Add(new ProtectedFolder(Full(importRoot), ProtectedFolderKind.Import, null));
|
||||
}
|
||||
|
||||
return new ExportFolderContext(folders, root);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks <paramref name="candidate"/>. Never throws for a refused folder (the verdict says why); only
|
||||
/// <paramref name="ct"/> cancels it.
|
||||
/// </summary>
|
||||
public async Task<ExportFolderVerdict> CheckAsync(string candidate, ExportFolderContext context, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
{
|
||||
return new ExportFolderVerdict(candidate ?? string.Empty, new ExportFolderProblem(ExportFolderProblemKind.Empty, "Scegli la cartella in cui copiare i file."));
|
||||
}
|
||||
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = ExportRoots.Resolve(context.Root, candidate);
|
||||
}
|
||||
catch (ExportFolderException ex)
|
||||
{
|
||||
return new ExportFolderVerdict(candidate, new ExportFolderProblem(ex.Kind ?? ExportFolderProblemKind.NotFullyQualified, ex.Message));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => CheckOnDisk(full, context, ct), ct).WaitAsync(_timeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return new ExportFolderVerdict(full, new ExportFolderProblem(
|
||||
ExportFolderProblemKind.NotResponding,
|
||||
$"La cartella non risponde entro {_timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova."));
|
||||
}
|
||||
}
|
||||
|
||||
private ExportFolderVerdict CheckOnDisk(string full, ExportFolderContext context, CancellationToken ct)
|
||||
{
|
||||
var o = context.Root;
|
||||
var shown = ExportRoots.DisplayPath(o, full);
|
||||
ExportFolderVerdict Refuse(ExportFolderProblemKind kind, string message) => new(full, new ExportFolderProblem(kind, message));
|
||||
|
||||
if (ExportRoots.MountCheck(o, full) is { } mountProblem)
|
||||
{
|
||||
return new ExportFolderVerdict(full, mountProblem);
|
||||
}
|
||||
|
||||
if (File.Exists(full))
|
||||
{
|
||||
return Refuse(ExportFolderProblemKind.NotAFolder, $"{shown} è un file: scegli una cartella.");
|
||||
}
|
||||
|
||||
if (!Directory.Exists(full))
|
||||
{
|
||||
return Refuse(
|
||||
ExportFolderProblemKind.Missing,
|
||||
$"La cartella {shown} non esiste. Febe non crea mai la cartella di una destinazione: creala tu, o collega il disco, poi sceglila di nuovo.");
|
||||
}
|
||||
|
||||
if (o.Root is not null && new DirectoryInfo(full).LinkTarget is not null)
|
||||
{
|
||||
return Refuse(ExportFolderProblemKind.Link, "La cartella scelta è un collegamento: scegli la cartella a cui punta.");
|
||||
}
|
||||
|
||||
if (IsRootOfDisk(full))
|
||||
{
|
||||
return Refuse(
|
||||
ExportFolderProblemKind.RootOfDisk,
|
||||
$"{shown} è la radice di un disco o di una condivisione: scegli una sua cartella, così i file di Febe non si mescolano al resto.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WindowsFileNames.FitPath(full, ["x"]);
|
||||
}
|
||||
catch (PathTooLongException)
|
||||
{
|
||||
return Refuse(
|
||||
ExportFolderProblemKind.PathTooLong,
|
||||
$"Il percorso di {shown} è troppo lungo: i nomi dei file non ci starebbero nei {WindowsFileNames.MaxPathLength} caratteri. Scegli una cartella con un percorso più corto.");
|
||||
}
|
||||
|
||||
// Textual overlap first: it needs no write.
|
||||
foreach (var folder in context.Protected)
|
||||
{
|
||||
if (Overlap(full, folder.Path, shown, folder) is { } problem)
|
||||
{
|
||||
return new ExportFolderVerdict(full, problem);
|
||||
}
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return ProbeIdentity(full, shown, context.Protected);
|
||||
}
|
||||
|
||||
private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder)
|
||||
{
|
||||
if (ExportPaths.Same(full, protectedPath))
|
||||
{
|
||||
return Same(shown, folder);
|
||||
}
|
||||
|
||||
if (ExportPaths.IsSameOrInside(full, protectedPath))
|
||||
{
|
||||
return Inside(shown, folder);
|
||||
}
|
||||
|
||||
return ExportPaths.IsSameOrInside(protectedPath, full) ? Contains(shown, folder) : null;
|
||||
}
|
||||
|
||||
private static ExportFolderProblem Same(string shown, ProtectedFolder folder) =>
|
||||
new(ExportFolderProblemKind.SameAsProtected, $"{shown} è {folder.Description}: scegli un'altra cartella.");
|
||||
|
||||
private static ExportFolderProblem Inside(string shown, ProtectedFolder folder) =>
|
||||
new(ExportFolderProblemKind.InsideProtected, $"{shown} è dentro {folder.Description}: scegli una cartella fuori.");
|
||||
|
||||
private static ExportFolderProblem Contains(string shown, ProtectedFolder folder) =>
|
||||
new(ExportFolderProblemKind.ContainsProtected, $"{shown} contiene {folder.Description}: scegli una cartella che non la contenga.");
|
||||
|
||||
/// <summary>
|
||||
/// The identity test of spec §4.10: a probe written in the candidate only, then looked for (never written) up the
|
||||
/// parents of each protected folder (the candidate contains it, or is it) and, for each parent of the candidate, at the
|
||||
/// same relative path under each protected folder (the candidate is inside it).
|
||||
/// </summary>
|
||||
private static ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList<ProtectedFolder> protectedFolders)
|
||||
{
|
||||
var name = NewProbeName();
|
||||
var probe = Path.Combine(full, name);
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None);
|
||||
stream.Write("Febe"u8);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
var reason = ex is UnauthorizedAccessException ? "accesso negato" : ex.Message;
|
||||
return new ExportFolderVerdict(full, new ExportFolderProblem(
|
||||
ExportFolderProblemKind.ProbeFailed,
|
||||
$"Febe non riesce a scrivere in {shown} ({reason}): controlla i permessi o che il disco non sia in sola lettura."));
|
||||
}
|
||||
|
||||
foreach (var folder in protectedFolders)
|
||||
{
|
||||
// (a) The candidate is the protected folder, or one of its parents, under another name.
|
||||
for (var ancestor = folder.Path; ancestor is not null; ancestor = Path.GetDirectoryName(ancestor))
|
||||
{
|
||||
if (Exists(Path.Combine(ancestor, name)))
|
||||
{
|
||||
var problem = ExportPaths.Same(ancestor, folder.Path) ? Same(shown, folder) : Contains(shown, folder);
|
||||
return new ExportFolderVerdict(full, problem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// (b) The candidate is inside a protected folder under another name: for each parent M of the candidate,
|
||||
// the probe would appear at F/<candidate relative to M> for the protected folder F that is M.
|
||||
for (var parent = Path.GetDirectoryName(full); parent is not null; parent = Path.GetDirectoryName(parent))
|
||||
{
|
||||
var relative = Path.GetRelativePath(parent, full);
|
||||
foreach (var folder in protectedFolders)
|
||||
{
|
||||
if (Exists(Path.Combine(folder.Path, relative, name)))
|
||||
{
|
||||
return new ExportFolderVerdict(full, Inside(shown, folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new ExportFolderVerdict(full, null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(probe);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Best effort: a probe left behind is a temporary file of Febe, harmless.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Exists(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decision D15: on Windows the path is its own root (<c>C:\</c>, <c>\\srv\share</c>); on Linux it is <c>/</c> or
|
||||
/// exactly a mount point that shows the root of its file system.
|
||||
/// </summary>
|
||||
private bool IsRootOfDisk(string full)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var root = Path.GetPathRoot(full);
|
||||
return !string.IsNullOrEmpty(root) && ExportPaths.Same(root, full);
|
||||
}
|
||||
|
||||
if (full == "/")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var mount = _mounts.FindContaining(full);
|
||||
return mount is not null && string.Equals(ExportPaths.Trim(mount.MountPoint), full, StringComparison.Ordinal) && mount.Root == "/";
|
||||
}
|
||||
|
||||
private static string Full(string path) => ExportPaths.Trim(Path.GetFullPath(path));
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The <c>.part</c> files a crash left in a destination (spec §4.10): removed only in the folders where the items of
|
||||
/// an unfinished job were to be written, never by a scan of the destination, never in a folder of no item. Only our
|
||||
/// own temporary names (<c>.febe-*.part</c>, the probes included) are touched.
|
||||
/// </summary>
|
||||
public static class ExportLeftovers
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
|
||||
/// <summary>Removes our temporary files in the folders of the items of <paramref name="run"/>. Returns how many.</summary>
|
||||
public static async Task<int> CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
ArgumentNullException.ThrowIfNull(run);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var folders = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = run.Id, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
foreach (var item in page)
|
||||
{
|
||||
if (item.RelativePath is { } relative && item.State is ExportItemState.Pending or ExportItemState.Failed)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Path.GetDirectoryName(LibraryLayout.FullPath(destination.RootPath, relative)) is { } folder)
|
||||
{
|
||||
folders.Add(folder);
|
||||
}
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
// A path that would leave the root: nothing of ours can be there.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var removed = 0;
|
||||
foreach (var folder in folders)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
removed += await Task.Run(() => SafeFileWriter.CleanupTemporaryFiles(folder, recursive: false), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return removed; // the disk stopped answering: the next resume tries again
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Best effort: a leftover .part takes some space, nothing more.
|
||||
}
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static async Task<bool> AnswersAsync(ExportEnvironment env, string root, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => Directory.Exists(root), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>What a «Copia in…» is asked for (spec §4.10 «Manuale sempre»).</summary>
|
||||
public abstract record ExportSelection
|
||||
{
|
||||
private ExportSelection()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Files by id: a selection of «Tutte le foto», a file of the viewer.</summary>
|
||||
public sealed record Media(IReadOnlyList<long> MediaIds) : ExportSelection;
|
||||
|
||||
/// <summary>Entries by id: a grouped selection, an entry of the viewer.</summary>
|
||||
public sealed record Entries(IReadOnlyList<long> EntryIds) : ExportSelection;
|
||||
|
||||
/// <summary>The current filter («Copia i file in…» of the CSV menu).</summary>
|
||||
public sealed record Filter(LibraryFilter LibraryFilter, MosaicMode Mode) : ExportSelection;
|
||||
|
||||
/// <summary>Every file of an account (the account card).</summary>
|
||||
public sealed record Account(long AccountId) : ExportSelection;
|
||||
}
|
||||
|
||||
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
|
||||
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
|
||||
|
||||
/// <summary>
|
||||
/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective
|
||||
/// destination of its account (D5).
|
||||
/// </summary>
|
||||
/// <param name="Files">Files to write.</param>
|
||||
/// <param name="Bytes">Their bytes.</param>
|
||||
/// <param name="AlreadyCopied">Already in their destination (or, with «Una copia sola», copied for another account).</param>
|
||||
/// <param name="RemovedOrSuperseded">
|
||||
/// «Tolti o superati»: never copied again by themselves. With <see cref="ExportJobRequest.CopyAgain"/> they are also
|
||||
/// counted in <paramref name="Files"/> and <paramref name="Bytes"/>, since they will be written.
|
||||
/// </param>
|
||||
/// <param name="NotExported">«Esporta questo account» off, no destination, or a content type the destination does not take.</param>
|
||||
/// <param name="Missing">«File non presente in libreria».</param>
|
||||
/// <param name="Destinations">Each destination that gets files, with whether it answers now.</param>
|
||||
public sealed record ExportPlan(
|
||||
int Files,
|
||||
long Bytes,
|
||||
int AlreadyCopied,
|
||||
int RemovedOrSuperseded,
|
||||
int NotExported,
|
||||
int Missing,
|
||||
IReadOnlyList<ExportPlanDestination> Destinations)
|
||||
{
|
||||
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
|
||||
}
|
||||
|
||||
/// <summary>A destination of a plan.</summary>
|
||||
/// <param name="Username">The account of an own folder; null for the general folder.</param>
|
||||
/// <param name="Files">Files to write there.</param>
|
||||
/// <param name="Paused">The destination is paused (its last check failed).</param>
|
||||
/// <param name="Problem">Why it cannot be written now (not reachable, not mounted, paused), in Italian; null when fine.</param>
|
||||
/// <param name="FreeBytes">Free space, when it can be measured.</param>
|
||||
public sealed record ExportPlanDestination(
|
||||
long DestinationId,
|
||||
string Label,
|
||||
string RootPath,
|
||||
ExportScope Scope,
|
||||
string? Username,
|
||||
int Files,
|
||||
long Bytes,
|
||||
bool Paused,
|
||||
string? Problem,
|
||||
long? FreeBytes);
|
||||
|
||||
/// <summary>What the export job is doing.</summary>
|
||||
public enum ExportPhase
|
||||
{
|
||||
Preparing,
|
||||
|
||||
/// <summary>«Controlla le copie».</summary>
|
||||
Checking,
|
||||
|
||||
/// <summary>An engine session is running: copies wait for it to end (decision D11).</summary>
|
||||
WaitingForSession,
|
||||
|
||||
Copying,
|
||||
|
||||
Finished,
|
||||
}
|
||||
|
||||
/// <summary>Progress of the export job, for the progress card (polled, D20).</summary>
|
||||
/// <param name="RunId">The job's run being worked on; null for «Controlla le copie» and when nothing ever ran.</param>
|
||||
/// <param name="BytesTotal">Bytes of the files still pending when the run (re)started, plus those done since; 0 when unknown.</param>
|
||||
public sealed record ExportProgress(
|
||||
long? RunId,
|
||||
ExportPhase Phase,
|
||||
int FilesDone,
|
||||
int FilesTotal,
|
||||
long BytesDone,
|
||||
long BytesTotal,
|
||||
string? CurrentFile,
|
||||
string? DestinationLabel,
|
||||
IReadOnlyDictionary<ExportItemState, int> ByState,
|
||||
DateTimeOffset UpdatedAt)
|
||||
{
|
||||
/// <summary>0..1: by bytes when known, otherwise by files.</summary>
|
||||
public double Fraction => BytesTotal > 0
|
||||
? Math.Clamp((double)BytesDone / BytesTotal, 0, 1)
|
||||
: FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0;
|
||||
}
|
||||
|
||||
/// <summary>What <c>ExportService.StartAsync</c> did: one run per destination (D6), and the plan it followed.</summary>
|
||||
public sealed record ExportStart(IReadOnlyList<ExportRun> Runs, ExportPlan Plan);
|
||||
|
||||
/// <summary>The export job ended (however it ended): the runs it worked on, and whether copies may have changed.</summary>
|
||||
public sealed record ExportJobFinished(IReadOnlyList<long> RunIds, bool CopiesChanged);
|
||||
@@ -0,0 +1,35 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The «Risultato» tree of a destination's naming (spec §4.10 «Nomi dei file»): the library preview rendered with the
|
||||
/// destination's schemes, «Come la libreria» (null) taking the library's. In the general folder each file sits under
|
||||
/// its account segment.
|
||||
/// </summary>
|
||||
public static class ExportNamingPreview
|
||||
{
|
||||
public static NamingPreview Build(
|
||||
ExportScope scope,
|
||||
string? general,
|
||||
string? highlight,
|
||||
string? profile,
|
||||
LibraryNaming library,
|
||||
TimeZoneInfo zone,
|
||||
string sampleAccount = "nome.utente")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(library);
|
||||
var preview = NamingPreview.Build(general ?? library.General.Text, highlight ?? library.Highlight.Text, profile ?? library.ProfilePicture.Text, zone, sampleAccount);
|
||||
if (scope != ExportScope.General)
|
||||
{
|
||||
return preview;
|
||||
}
|
||||
|
||||
var segment = WindowsFileNames.SanitizeSegment(sampleAccount);
|
||||
return preview with
|
||||
{
|
||||
Folders = preview.Folders.Select(f => f with { Path = [segment, .. f.Path] }).ToList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>Paths and content types of the export (spec §4.10).</summary>
|
||||
public static class ExportPaths
|
||||
{
|
||||
/// <summary>Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does.</summary>
|
||||
public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or inside it, as text (full paths).</summary>
|
||||
public static bool IsSameOrInside(string path, string folder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
ArgumentNullException.ThrowIfNull(folder);
|
||||
var p = Trim(path);
|
||||
var f = Trim(folder);
|
||||
return string.Equals(p, f, PathComparison)
|
||||
|| p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) || f.EndsWith(Path.AltDirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison);
|
||||
}
|
||||
|
||||
/// <summary>The same folder, as text.</summary>
|
||||
public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison);
|
||||
|
||||
/// <summary>A full path without its trailing separator (a root such as <c>C:\</c> or <c>/</c> keeps it).</summary>
|
||||
public static string Trim(string path)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(path);
|
||||
return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The content type of a file (decision D4 of tappa E2): a post photo or video, a story (also a highlight when the
|
||||
/// story is in a collection), a highlight, a tagged post, a profile picture. The «Copie» filter repeats it in SQL.
|
||||
/// </summary>
|
||||
public static ContentTypes TypeOf(EntryKind kind, MediaKind media, bool inHighlight) => kind switch
|
||||
{
|
||||
EntryKind.Post => media == MediaKind.Photo ? ContentTypes.PostPhotos : ContentTypes.PostVideos,
|
||||
EntryKind.Story => inHighlight ? ContentTypes.Stories | ContentTypes.Highlights : ContentTypes.Stories,
|
||||
EntryKind.Highlight => ContentTypes.Highlights,
|
||||
EntryKind.Tagged => ContentTypes.Tagged,
|
||||
EntryKind.ProfilePicture => ContentTypes.ProfilePicture,
|
||||
_ => ContentTypes.None,
|
||||
};
|
||||
|
||||
/// <summary>Folder of imported files without a known date or code (as the import names it).</summary>
|
||||
public const string ImportedFolder = "importati";
|
||||
|
||||
/// <summary>
|
||||
/// The path of a copy below the destination root, as sanitized segments, before <see cref="RelativePathFor"/>
|
||||
/// (decision D18 of tappa E2). «Come la libreria» (a null scheme) renders the library's current scheme again, except
|
||||
/// for a file the import left in <c>importati/</c>, which keeps its path. A story in a highlight collection takes the
|
||||
/// highlight scheme only when the destination takes highlights and not stories. In the general folder the account
|
||||
/// segment comes first.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Segments(
|
||||
ExportDestination d,
|
||||
LibraryNaming library,
|
||||
Account account,
|
||||
Entry entry,
|
||||
Media media,
|
||||
string? highlightTitle,
|
||||
bool inHighlight,
|
||||
TimeZoneInfo zone)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(d);
|
||||
ArgumentNullException.ThrowIfNull(library);
|
||||
ArgumentNullException.ThrowIfNull(account);
|
||||
ArgumentNullException.ThrowIfNull(entry);
|
||||
ArgumentNullException.ThrowIfNull(media);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var stored = media.RelativePath is { Length: > 0 } path
|
||||
? LibraryLayout.ToStored(path)
|
||||
: throw new ArgumentException("Il file non è nella libreria: non ha un percorso.", nameof(media));
|
||||
|
||||
var renderAs = entry.Kind == EntryKind.Story && inHighlight
|
||||
&& d.ContentTypes.HasFlag(ContentTypes.Highlights) && !d.ContentTypes.HasFlag(ContentTypes.Stories)
|
||||
? EntryKind.Highlight
|
||||
: entry.Kind;
|
||||
var use = UseOf(renderAs);
|
||||
var text = use switch
|
||||
{
|
||||
NamingSchemeUse.Highlight => d.HighlightNamingScheme,
|
||||
NamingSchemeUse.ProfilePicture => d.ProfileNamingScheme,
|
||||
_ => d.NamingScheme,
|
||||
};
|
||||
|
||||
IReadOnlyList<string> segments;
|
||||
if (text is null && stored.StartsWith(ImportedFolder + "/", StringComparison.Ordinal))
|
||||
{
|
||||
segments = stored.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(WindowsFileNames.SanitizeSegment).ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
var scheme = (text is null ? null : NamingScheme.Validate(text, use).Scheme) ?? library.For(renderAs);
|
||||
var extension = Path.GetExtension(stored).TrimStart('.').ToLowerInvariant();
|
||||
var values = NamingValues.For(
|
||||
account.Username,
|
||||
entry with { Kind = renderAs },
|
||||
media.Position,
|
||||
extension,
|
||||
renderAs == EntryKind.Highlight ? highlightTitle : null,
|
||||
media.Sha256);
|
||||
segments = scheme.Render(values, zone);
|
||||
}
|
||||
|
||||
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
|
||||
}
|
||||
|
||||
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
|
||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
|
||||
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(d);
|
||||
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
|
||||
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash.
|
||||
/// </summary>
|
||||
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (attempt <= 1)
|
||||
{
|
||||
return string.Join('/', segments);
|
||||
}
|
||||
|
||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
|
||||
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath));
|
||||
}
|
||||
|
||||
/// <summary>The scheme that names an entry kind.</summary>
|
||||
public static NamingSchemeUse UseOf(EntryKind kind) => kind switch
|
||||
{
|
||||
EntryKind.Highlight => NamingSchemeUse.Highlight,
|
||||
EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture,
|
||||
_ => NamingSchemeUse.General,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The pause of a destination (spec §4.10): its probe could not be written, it is not reachable, or the disk is full.
|
||||
/// The state shows in Impostazioni and in the Dashboard and the next check clears it. Never the red strip: the event
|
||||
/// <c>esportazione-in-pausa</c> is not an alert of the engine.
|
||||
/// </summary>
|
||||
public static class ExportPause
|
||||
{
|
||||
/// <summary>Code of the event written once when a destination goes into pause.</summary>
|
||||
public const string PausedEventCode = "esportazione-in-pausa";
|
||||
|
||||
/// <summary>
|
||||
/// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it
|
||||
/// is). The event is written only on the transition from running to paused. Returns the stored row.
|
||||
/// </summary>
|
||||
public static async Task<ExportDestination> PauseAsync(ExportEnvironment env, ExportDestination destination, string message)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(message);
|
||||
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
|
||||
if (stored.IsRetired)
|
||||
{
|
||||
return stored;
|
||||
}
|
||||
|
||||
var wasPaused = stored.PausedAt is not null;
|
||||
if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal))
|
||||
{
|
||||
return stored;
|
||||
}
|
||||
|
||||
var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message };
|
||||
await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false);
|
||||
if (!wasPaused)
|
||||
{
|
||||
await env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = env.Clock.Now,
|
||||
Code = PausedEventCode,
|
||||
Severity = EventSeverity.Warning,
|
||||
Message = $"{ExportDestinations.Label(paused)} in pausa: {message}",
|
||||
AccountId = paused.AccountId,
|
||||
},
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return paused;
|
||||
}
|
||||
|
||||
/// <summary>Clears the pause of a destination after a check succeeded. Returns the stored row.</summary>
|
||||
public static async Task<ExportDestination> ClearAsync(ExportEnvironment env, ExportDestination destination)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination;
|
||||
if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null))
|
||||
{
|
||||
return stored;
|
||||
}
|
||||
|
||||
var cleared = stored with { PausedAt = null, LastError = null };
|
||||
await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false);
|
||||
return cleared;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the
|
||||
/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are
|
||||
/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog.
|
||||
/// </summary>
|
||||
public sealed class ExportPlanner(ExportEnvironment env)
|
||||
{
|
||||
private const int PageSize = 2000;
|
||||
|
||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
|
||||
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
|
||||
public async Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var destinations = new ExportDestinations(_env);
|
||||
var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
var tally = new PlanTally();
|
||||
await foreach (var file in EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
||||
{
|
||||
tally.Add(file);
|
||||
}
|
||||
|
||||
return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an
|
||||
/// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with
|
||||
/// «Una copia sola» the same file counts once across accounts.
|
||||
/// </summary>
|
||||
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
|
||||
ExportJobRequest request,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
ExportSettings settings,
|
||||
[EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var oneOnly = settings.SamePost == SamePostCopies.OneOnly;
|
||||
var seen = new HashSet<(long Destination, long Account, string Sha256)>();
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
after = page[^1].MediaId;
|
||||
var keys = new Dictionary<long, HashSet<(long AccountId, string Sha256)>>();
|
||||
foreach (var c in page)
|
||||
{
|
||||
if (Due(c, effective) is { } destination)
|
||||
{
|
||||
if (!keys.TryGetValue(destination, out var set))
|
||||
{
|
||||
keys[destination] = set = [];
|
||||
}
|
||||
|
||||
set.Add((c.AccountId, c.Sha256!));
|
||||
}
|
||||
}
|
||||
|
||||
var states = new Dictionary<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
|
||||
foreach (var (destination, set) in keys)
|
||||
{
|
||||
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var c in page)
|
||||
{
|
||||
if (!IsPresent(c))
|
||||
{
|
||||
yield return new PlannedFile(c, null, PlannedCopy.Missing);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Due(c, effective) is not { } destination)
|
||||
{
|
||||
yield return new PlannedFile(c, null, PlannedCopy.NotExported);
|
||||
continue;
|
||||
}
|
||||
|
||||
var sha = c.Sha256!;
|
||||
var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha);
|
||||
var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null;
|
||||
PlannedFile planned;
|
||||
if (state == ExportCopyState.Copied)
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
||||
}
|
||||
else if (state is ExportCopyState.Removed or ExportCopyState.Superseded)
|
||||
{
|
||||
planned = request.CopyAgain
|
||||
? new PlannedFile(c, destination, PlannedCopy.Write, Again: true)
|
||||
: new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded);
|
||||
}
|
||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, ct).ConfigureAwait(false) is { } other
|
||||
&& other.AccountId != c.AccountId)
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
||||
}
|
||||
else
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.Write);
|
||||
}
|
||||
|
||||
if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key))
|
||||
{
|
||||
planned = planned with { Action = PlannedCopy.AlreadyCopied, Again = false };
|
||||
}
|
||||
|
||||
yield return planned;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
|
||||
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
|
||||
|
||||
/// <summary>The destination a present file goes to (D3), or null when it is not exported.</summary>
|
||||
private static long? Due(ExportCandidate c, IReadOnlyDictionary<long, EffectiveDestination> effective) =>
|
||||
IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight))
|
||||
? e.Destination!.Id
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>A candidate with what the plan does with it.</summary>
|
||||
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
|
||||
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
|
||||
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
|
||||
|
||||
internal enum PlannedCopy
|
||||
{
|
||||
Write,
|
||||
AlreadyCopied,
|
||||
RemovedOrSuperseded,
|
||||
NotExported,
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// <summary>Counts of a plan while its files go by.</summary>
|
||||
internal sealed class PlanTally
|
||||
{
|
||||
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
|
||||
|
||||
public int Files { get; private set; }
|
||||
|
||||
public long Bytes { get; private set; }
|
||||
|
||||
public int AlreadyCopied { get; private set; }
|
||||
|
||||
public int RemovedOrSuperseded { get; private set; }
|
||||
|
||||
public int NotExported { get; private set; }
|
||||
|
||||
public int Missing { get; private set; }
|
||||
|
||||
public void Add(PlannedFile file)
|
||||
{
|
||||
switch (file.Action)
|
||||
{
|
||||
case PlannedCopy.Missing:
|
||||
Missing++;
|
||||
return;
|
||||
case PlannedCopy.NotExported:
|
||||
NotExported++;
|
||||
return;
|
||||
case PlannedCopy.AlreadyCopied:
|
||||
AlreadyCopied++;
|
||||
break;
|
||||
case PlannedCopy.RemovedOrSuperseded:
|
||||
RemovedOrSuperseded++;
|
||||
break;
|
||||
case PlannedCopy.Write:
|
||||
var bytes = file.Candidate.Bytes ?? 0;
|
||||
Files++;
|
||||
Bytes += bytes;
|
||||
if (file.Again)
|
||||
{
|
||||
RemovedOrSuperseded++;
|
||||
}
|
||||
|
||||
var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value);
|
||||
_byDestination[file.DestinationId.Value] = (f + 1, b + bytes);
|
||||
return;
|
||||
}
|
||||
|
||||
_byDestination.TryAdd(file.DestinationId!.Value, (0, 0));
|
||||
}
|
||||
|
||||
/// <summary>The plan. With <paramref name="checkDestinations"/> each destination is asked whether it answers now.</summary>
|
||||
public async Task<ExportPlan> BuildAsync(
|
||||
ExportEnvironment env,
|
||||
ExportDestinations destinations,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
bool checkDestinations,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var rows = effective.Values.Where(e => e.Destination is not null).Select(e => e.Destination!).DistinctBy(d => d.Id).ToDictionary(d => d.Id);
|
||||
var accounts = (await env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
|
||||
var list = new List<ExportPlanDestination>();
|
||||
foreach (var (id, (files, bytes)) in _byDestination.OrderBy(d => rows.TryGetValue(d.Key, out var r) && r.Scope == ExportScope.General ? 0 : 1).ThenBy(d => d.Key))
|
||||
{
|
||||
var d = rows.TryGetValue(id, out var row) ? row : await env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false);
|
||||
if (d is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string? problem = null;
|
||||
long? free = null;
|
||||
if (checkDestinations)
|
||||
{
|
||||
var status = await destinations.StatusAsync(id, ct).ConfigureAwait(false);
|
||||
problem = status.Problem;
|
||||
free = status.FreeBytes;
|
||||
}
|
||||
|
||||
problem ??= d.PausedAt is not null ? d.LastError : null;
|
||||
var username = d.AccountId is { } a ? accounts.GetValueOrDefault(a) : null;
|
||||
list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free));
|
||||
}
|
||||
|
||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list);
|
||||
}
|
||||
|
||||
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
|
||||
public IReadOnlyCollection<long> Destinations => _byDestination.Keys;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>The report of an export job (spec §4.10): counts, per account, and the files that need a look.</summary>
|
||||
/// <param name="Problems">At most <see cref="ExportReports.MaxProblems"/> lines: failed, missing, and skipped files with a note.</param>
|
||||
public sealed record ExportReport(
|
||||
ExportRun Run,
|
||||
ExportDestination Destination,
|
||||
int Total,
|
||||
IReadOnlyDictionary<ExportItemState, int> ByState,
|
||||
long BytesCopied,
|
||||
IReadOnlyList<ExportReportAccount> Accounts,
|
||||
IReadOnlyList<ExportReportLine> Problems);
|
||||
|
||||
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
|
||||
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
|
||||
|
||||
/// <summary>A file of the report, with its reason in Italian.</summary>
|
||||
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
|
||||
|
||||
/// <summary>Builds the report of a job from the database (no CSV in E2: §4.10 leaves «Copiato in» in the CSV out of 0.3.0).</summary>
|
||||
public sealed class ExportReports(ExportEnvironment env)
|
||||
{
|
||||
public const int MaxProblems = 200;
|
||||
|
||||
private const int PageSize = 1000;
|
||||
|
||||
/// <summary>A name for files whose account was removed.</summary>
|
||||
public const string RemovedAccount = "account rimosso";
|
||||
|
||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
|
||||
/// <exception cref="KeyNotFoundException">No such job.</exception>
|
||||
public async Task<ExportReport> BuildAsync(long runId, CancellationToken ct = default)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var run = await exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
|
||||
var destination = await exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"Destinazione di esportazione {run.DestinationId} non trovata.");
|
||||
var summary = await exports.GetRunSummaryAsync(runId, ct).ConfigureAwait(false);
|
||||
var names = (await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
|
||||
string Name(long? id) => id is { } a && names.TryGetValue(a, out var n) ? n : RemovedAccount;
|
||||
|
||||
var accounts = new Dictionary<long, int[]>();
|
||||
var problems = new List<ExportReportLine>();
|
||||
long bytes = 0;
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await exports.ListItemsAsync(new ExportItemQuery { RunId = runId, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
foreach (var item in page)
|
||||
{
|
||||
var key = item.AccountId ?? 0;
|
||||
if (!accounts.TryGetValue(key, out var row))
|
||||
{
|
||||
accounts[key] = row = new int[4];
|
||||
}
|
||||
|
||||
switch (item.State)
|
||||
{
|
||||
case ExportItemState.Copied or ExportItemState.Adopted:
|
||||
row[0]++;
|
||||
if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b })
|
||||
{
|
||||
bytes += b;
|
||||
}
|
||||
|
||||
break;
|
||||
case ExportItemState.AlreadyCopied:
|
||||
row[1]++;
|
||||
break;
|
||||
case ExportItemState.Skipped or ExportItemState.Missing:
|
||||
row[2]++;
|
||||
break;
|
||||
case ExportItemState.Failed:
|
||||
row[3]++;
|
||||
break;
|
||||
}
|
||||
|
||||
var problem = item.State is ExportItemState.Failed or ExportItemState.Missing
|
||||
|| (item.State == ExportItemState.Skipped && item.Note is not null);
|
||||
if (problem && problems.Count < MaxProblems)
|
||||
{
|
||||
var text = item.State == ExportItemState.Failed
|
||||
? item.LastError ?? ExportText.Note(item.Note) ?? ExportText.State(item.State)
|
||||
: ExportText.Note(item.Note) ?? ExportText.State(item.State);
|
||||
problems.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, text));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var perAccount = accounts
|
||||
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]))
|
||||
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>A mounted file system, as the export needs it (spec §4.10 «Docker e Windows»).</summary>
|
||||
/// <param name="MountPoint">Where it is mounted.</param>
|
||||
/// <param name="Root">Folder of its file system shown there (<c>/</c>: the root of that file system).</param>
|
||||
/// <param name="FileSystemType">File system type (<c>vfat</c> for FAT32).</param>
|
||||
/// <param name="ReadOnly">Mounted read-only.</param>
|
||||
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly);
|
||||
|
||||
/// <summary>The mount table (a seam: tests give their own; Linux reads <c>/proc/self/mountinfo</c>).</summary>
|
||||
public interface IExportMounts
|
||||
{
|
||||
/// <summary>The mount that holds a full path, or null (always null on Windows).</summary>
|
||||
ExportMount? FindContaining(string fullPath);
|
||||
|
||||
/// <summary>Every mount (empty on Windows).</summary>
|
||||
IReadOnlyList<ExportMount> All();
|
||||
}
|
||||
|
||||
/// <summary>The mounts of this process from <c>/proc/self/mountinfo</c>, read at each call (it is small).</summary>
|
||||
public sealed class ProcMountInfo(Func<string?>? read = null) : IExportMounts
|
||||
{
|
||||
private readonly Func<string?> _read = read ?? MountInfoTable.ReadProcSelf;
|
||||
|
||||
public ExportMount? FindContaining(string fullPath)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fullPath);
|
||||
var mounts = Read();
|
||||
return mounts.Count == 0 ? null : Map(MountInfoTable.FindContaining(mounts, fullPath));
|
||||
}
|
||||
|
||||
public IReadOnlyList<ExportMount> All() => Read().Select(m => Map(m)!).ToList();
|
||||
|
||||
private IReadOnlyList<MountInfoEntry> Read()
|
||||
{
|
||||
try
|
||||
{
|
||||
return _read() is { } content ? MountInfoTable.Parse(content) : [];
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where destinations may be chosen. Docker: subfolders of <c>/esporta</c>, only when it is declared
|
||||
/// (<c>--esporta</c>, <c>FEBE_ESPORTA</c>) and the destination sits on a mount at <c>/esporta</c> or below it (decision of
|
||||
/// Alberto, question Q2 of tappa E2). Windows: any folder, through the native picker.
|
||||
/// </summary>
|
||||
public sealed record ExportRootOptions
|
||||
{
|
||||
/// <summary>Docker: the full path of <c>/esporta</c>. Null: any folder.</summary>
|
||||
public string? Root { get; init; }
|
||||
|
||||
/// <summary><c>--esporta</c> or <c>FEBE_ESPORTA</c> (always true without a root).</summary>
|
||||
public bool Declared { get; init; }
|
||||
|
||||
/// <summary>The mount table.</summary>
|
||||
public IExportMounts Mounts { get; init; } = new ProcMountInfo();
|
||||
|
||||
/// <summary>Windows (and development): any folder.</summary>
|
||||
public static ExportRootOptions AnyFolder { get; } = new() { Declared = true };
|
||||
|
||||
/// <summary>Docker: destinations under <paramref name="root"/>.</summary>
|
||||
public static ExportRootOptions Docker(string root, bool declared, IExportMounts? mounts = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(root);
|
||||
return new ExportRootOptions { Root = ExportPaths.Trim(Path.GetFullPath(root)), Declared = declared, Mounts = mounts ?? new ProcMountInfo() };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether copies to external folders can be written at all, and why not.</summary>
|
||||
/// <param name="Active">True: destinations may be created and written.</param>
|
||||
/// <param name="Root">Docker: the root (<c>/esporta</c>); null on Windows.</param>
|
||||
/// <param name="Problem">Italian text of the reason when not active.</param>
|
||||
public sealed record ExportRootState(bool Active, string? Root, string? Problem);
|
||||
|
||||
/// <summary>The rules of the export root (spec §4.10, §11): <c>/esporta</c> in Docker, any folder on Windows.</summary>
|
||||
public static class ExportRoots
|
||||
{
|
||||
/// <summary>Copies to external folders are switched off in Docker (not declared).</summary>
|
||||
public const string NotDeclaredText =
|
||||
"Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1 (o --esporta) e una cartella del server montata su /esporta.";
|
||||
|
||||
/// <summary>Whether the root is usable: always without a root; in Docker declared and with a mount at or below it.</summary>
|
||||
public static ExportRootState Evaluate(ExportRootOptions o)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
if (o.Root is not { } root)
|
||||
{
|
||||
return new ExportRootState(true, null, null);
|
||||
}
|
||||
|
||||
if (!o.Declared)
|
||||
{
|
||||
return new ExportRootState(false, root, NotDeclaredText);
|
||||
}
|
||||
|
||||
return o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root))
|
||||
? new ExportRootState(true, root, null)
|
||||
: new ExportRootState(false, root, NotMountedText(o));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when a destination may be written as far as the mounts are concerned (always on Windows); otherwise the
|
||||
/// Italian reason: not declared, not on a mount at or below the root, or a read-only mount.
|
||||
/// </summary>
|
||||
public static string? MountProblem(ExportRootOptions o, string destinationFullPath) => MountCheck(o, destinationFullPath)?.Message;
|
||||
|
||||
internal static ExportFolderProblem? MountCheck(ExportRootOptions o, string destinationFullPath)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(destinationFullPath);
|
||||
if (o.Root is not { } root)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!o.Declared)
|
||||
{
|
||||
return new ExportFolderProblem(ExportFolderProblemKind.NotMounted, NotDeclaredText);
|
||||
}
|
||||
|
||||
var full = ExportPaths.Trim(Path.GetFullPath(destinationFullPath));
|
||||
var mount = o.Mounts.FindContaining(full);
|
||||
if (mount is null || !ExportPaths.IsSameOrInside(ExportPaths.Trim(mount.MountPoint), root))
|
||||
{
|
||||
return new ExportFolderProblem(
|
||||
ExportFolderProblemKind.NotMounted,
|
||||
o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root))
|
||||
? $"{DisplayPath(o, full)} non è su una cartella montata in {DisplayPath(o, root)}: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di {DisplayPath(o, root)}."
|
||||
: NotMountedText(o));
|
||||
}
|
||||
|
||||
return mount.ReadOnly
|
||||
? new ExportFolderProblem(ExportFolderProblemKind.ReadOnlyMount, $"{DisplayPath(o, full)} è montata in sola lettura: Febe non può copiarci nulla.")
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subfolders offered by the picker in Docker: <paramref name="relative"/> is relative to the root, and so are the
|
||||
/// returned paths. Without a root it is an absolute folder. Links, hidden and system folders are skipped.
|
||||
/// </summary>
|
||||
/// <exception cref="ExportFolderException">The folder cannot be browsed.</exception>
|
||||
public static IReadOnlyList<SourceFolderChoice> Browse(ExportRootOptions o, string? relative)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
string folder;
|
||||
if (o.Root is { } root)
|
||||
{
|
||||
folder = string.IsNullOrWhiteSpace(relative) ? root : Resolve(o, relative, allowRoot: true);
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(relative) || !Path.IsPathFullyQualified(relative))
|
||||
{
|
||||
throw new ExportFolderException("Scegli la cartella da sfogliare con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified);
|
||||
}
|
||||
else
|
||||
{
|
||||
folder = ExportPaths.Trim(Path.GetFullPath(relative));
|
||||
}
|
||||
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false))
|
||||
.Order(StringComparer.Ordinal)
|
||||
.Select(d => new SourceFolderChoice(
|
||||
Path.GetFileName(d),
|
||||
o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d,
|
||||
Directory.EnumerateDirectories(d, "*", ImportSources.Enumeration(recursive: false)).Any()))
|
||||
.ToList();
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
throw new ExportFolderException($"Febe non riesce a leggere {DisplayPath(o, folder)}: controlla che il disco sia collegato.", ExportFolderProblemKind.Missing);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The full path of a chosen folder: in Docker the root plus a relative path (or a full path inside the root), never
|
||||
/// the root itself, never with «..»; without a root a fully qualified path.
|
||||
/// </summary>
|
||||
/// <exception cref="ExportFolderException">The path cannot be a destination; the message says why.</exception>
|
||||
public static string Resolve(ExportRootOptions o, string chosen) => Resolve(o, chosen, allowRoot: false);
|
||||
|
||||
/// <summary>The path shown to Alberto: in Docker «/esporta/usb»; elsewhere the full path.</summary>
|
||||
public static string DisplayPath(ExportRootOptions o, string full)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
ArgumentNullException.ThrowIfNull(full);
|
||||
if (o.Root is { } root && ExportPaths.IsSameOrInside(full, root))
|
||||
{
|
||||
var relative = Path.GetRelativePath(root, full);
|
||||
return relative == "." ? LibraryLayout.ToStored(root) : LibraryLayout.ToStored(root).TrimEnd('/') + "/" + LibraryLayout.ToStored(relative);
|
||||
}
|
||||
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string Resolve(ExportRootOptions o, string chosen, bool allowRoot)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(o);
|
||||
if (string.IsNullOrWhiteSpace(chosen))
|
||||
{
|
||||
throw new ExportFolderException("Scegli la cartella in cui copiare i file.", ExportFolderProblemKind.Empty);
|
||||
}
|
||||
|
||||
var display = o.Root is { } shown ? DisplayPath(o, shown) : null;
|
||||
|
||||
// Refused as text, before any normalisation: «..» never walks out of the list the picker shows.
|
||||
if (chosen.Split('/', '\\').Any(s => s == ".."))
|
||||
{
|
||||
throw new ExportFolderException(
|
||||
display is null ? "«..» non è ammesso: scegli la cartella con il suo percorso completo." : $"«..» non è ammesso: scegli una sottocartella di {display} dall'elenco.",
|
||||
ExportFolderProblemKind.ParentSegment);
|
||||
}
|
||||
|
||||
if (o.Root is not { } root)
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(chosen))
|
||||
{
|
||||
throw new ExportFolderException("Scegli la cartella con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified);
|
||||
}
|
||||
|
||||
return ExportPaths.Trim(FullPath(chosen));
|
||||
}
|
||||
|
||||
var full = ExportPaths.Trim(Path.IsPathFullyQualified(chosen) ? FullPath(chosen) : FullPath(Path.Combine(root, chosen.TrimStart('/', '\\'))));
|
||||
if (!ExportPaths.IsSameOrInside(full, root))
|
||||
{
|
||||
throw new ExportFolderException(
|
||||
$"In Docker le copie vanno solo in una sottocartella di {display}: monta lì una cartella del server e sceglila dall'elenco.",
|
||||
ExportFolderProblemKind.OutsideExportRoot);
|
||||
}
|
||||
|
||||
if (!allowRoot && ExportPaths.Same(full, root))
|
||||
{
|
||||
throw new ExportFolderException($"Scegli una sottocartella di {display}: {display} stessa non è una destinazione.", ExportFolderProblemKind.ExportRootItself);
|
||||
}
|
||||
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string FullPath(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Path.GetFullPath(path);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
throw new ExportFolderException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ExportFolderProblemKind.NotFullyQualified);
|
||||
}
|
||||
}
|
||||
|
||||
private static string NotMountedText(ExportRootOptions o) =>
|
||||
$"{DisplayPath(o, o.Root!)} è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su {DisplayPath(o, o.Root!)}.";
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Settings of one export job (like <c>ImportRunSettings</c>): a row of the <c>setting</c> table each, so the schema
|
||||
/// stays as E1 left it. Cleared when the job completes, is cancelled or deleted.
|
||||
/// </summary>
|
||||
internal static class ExportRunSettings
|
||||
{
|
||||
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
|
||||
|
||||
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
|
||||
public static async Task<bool> GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||
{
|
||||
var text = await store.GetAsync(CopyAgainKey(runId), ct).ConfigureAwait(false);
|
||||
return string.Equals(text?.Trim(), "1", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
|
||||
store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct);
|
||||
|
||||
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||
store.SetAsync(CopyAgainKey(runId), null, ct);
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The copies to external folders for the interface (spec §4.10): one background job at a time, never together with
|
||||
/// an import or a rebuild (<see cref="LongWorkGate"/>), never during an engine session. A «Copia in…» makes one job
|
||||
/// record per destination (decision D6 of tappa E2) and the job works on them in order. Every state lives in the
|
||||
/// database: after a restart call <see cref="RecoverAsync"/> once; «Riprendi» is always Alberto's.
|
||||
/// </summary>
|
||||
public sealed class ExportService : IAsyncDisposable
|
||||
{
|
||||
private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila.";
|
||||
private const int ItemBatch = 2000;
|
||||
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
||||
|
||||
private readonly ExportEnvironment _env;
|
||||
private readonly Lock _gate = new();
|
||||
private Job? _job;
|
||||
private ExportProgress? _current;
|
||||
private long _lastPublished;
|
||||
private Task _cleanup = Task.CompletedTask;
|
||||
private bool _starting;
|
||||
|
||||
public ExportService(ExportEnvironment env)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
_env = env;
|
||||
Destinations = new ExportDestinations(env);
|
||||
Planner = new ExportPlanner(env);
|
||||
Copier = new ExportCopier(env);
|
||||
Reports = new ExportReports(env);
|
||||
}
|
||||
|
||||
/// <summary>Progress of the running job, at most four times a second and at every change of phase (pool thread).</summary>
|
||||
public event EventHandler<ExportProgress>? ProgressChanged;
|
||||
|
||||
/// <summary>The job ended, however it ended (pool thread): the interface refreshes tiles and filter.</summary>
|
||||
public event EventHandler<ExportJobFinished>? JobFinished;
|
||||
|
||||
public ExportDestinations Destinations { get; }
|
||||
|
||||
public ExportPlanner Planner { get; }
|
||||
|
||||
public ExportCopier Copier { get; }
|
||||
|
||||
public ExportReports Reports { get; }
|
||||
|
||||
/// <summary>The runs of the running job; empty when idle (and for «Controlla le copie», which has none).</summary>
|
||||
public IReadOnlyList<long> ActiveRunIds
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _job is { Task.IsCompleted: false } job ? job.RunIds : [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job is running.</summary>
|
||||
public bool IsBusy
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _starting || _job is { Task.IsCompleted: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last error of a background job that could not be stored with its run (normally null).</summary>
|
||||
public string? LastJobError { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the
|
||||
/// <c>.part</c> files of unfinished jobs are removed in the background, only in their items' folders. Never resumes
|
||||
/// by itself. Returns how many jobs became interrupted.
|
||||
/// </summary>
|
||||
public async Task<int> RecoverAsync(CancellationToken ct = default)
|
||||
{
|
||||
var active = ActiveRunIds;
|
||||
var recovered = 0;
|
||||
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||
foreach (var run in unfinished)
|
||||
{
|
||||
if (run.State == ExportRunState.Running && !active.Contains(run.Id))
|
||||
{
|
||||
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false);
|
||||
recovered++;
|
||||
}
|
||||
}
|
||||
|
||||
var toClean = unfinished.Where(r => !active.Contains(r.Id)).ToList();
|
||||
lock (_gate)
|
||||
{
|
||||
_cleanup = Task.Run(() => CleanLeftoversAsync(toClean));
|
||||
}
|
||||
|
||||
return recovered;
|
||||
}
|
||||
|
||||
/// <summary>The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers).</summary>
|
||||
public Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct);
|
||||
|
||||
/// <summary>
|
||||
/// «Copia in…»: records one job per destination that gets files, with its items, and starts copying in the
|
||||
/// background. Files not exported or missing are only counted in the returned plan. When nothing is due, no job is
|
||||
/// recorded and nothing starts.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
|
||||
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
lock (_gate)
|
||||
{
|
||||
EnsureIdle();
|
||||
_starting = true; // a second «Copia in…» meanwhile records nothing
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await StartReservedAsync(request, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_starting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ExportStart> StartReservedAsync(ExportJobRequest request, CancellationToken ct)
|
||||
{
|
||||
var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
var tally = new PlanTally();
|
||||
var runs = new Dictionary<long, ExportRun>();
|
||||
var pending = new List<ExportItem>();
|
||||
var exports = _env.Storage.Exports;
|
||||
try
|
||||
{
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
||||
{
|
||||
tally.Add(file);
|
||||
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!runs.TryGetValue(destination, out var run))
|
||||
{
|
||||
run = await exports.CreateRunAsync(
|
||||
new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
runs[destination] = run;
|
||||
if (request.CopyAgain)
|
||||
{
|
||||
await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
pending.Add(new ExportItem
|
||||
{
|
||||
RunId = run.Id,
|
||||
MediaId = file.Candidate.MediaId,
|
||||
AccountId = file.Candidate.AccountId,
|
||||
SourceSha256 = file.Candidate.Sha256,
|
||||
Variant = ExportVariant.Whole,
|
||||
Format = ExportFormat.Original,
|
||||
State = ExportItemState.Pending,
|
||||
});
|
||||
if (pending.Count >= ItemBatch)
|
||||
{
|
||||
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
||||
pending.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
await StopRunsAsync(runs.Values).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
var plan = await tally.BuildAsync(_env, Destinations, effective, checkDestinations: false, CancellationToken.None).ConfigureAwait(false);
|
||||
var ordered = runs.Values.OrderBy(r => r.Id).ToList();
|
||||
if (ordered.Count == 0)
|
||||
{
|
||||
return new ExportStart([], plan);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_starting = false;
|
||||
StartCopyJob(ordered.Select(r => r.Id).ToList());
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
await StopRunsAsync(ordered).ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
return new ExportStart(ordered, plan);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a
|
||||
/// paused one checks its destination first and pauses again if it still does not answer).
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<ExportRun>> ResumeAsync(IReadOnlyList<long>? runIds = null, CancellationToken ct = default)
|
||||
{
|
||||
EnsureIdle();
|
||||
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
|
||||
List<ExportRun> chosen;
|
||||
if (runIds is null)
|
||||
{
|
||||
chosen = unfinished.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
chosen = [];
|
||||
foreach (var id in runIds.Distinct())
|
||||
{
|
||||
var run = unfinished.FirstOrDefault(r => r.Id == id);
|
||||
if (run is null)
|
||||
{
|
||||
_ = await _env.Storage.Exports.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {id} non trovato.");
|
||||
throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere.");
|
||||
}
|
||||
|
||||
chosen.Add(run);
|
||||
}
|
||||
}
|
||||
|
||||
chosen = chosen.OrderBy(r => r.Id).ToList();
|
||||
if (chosen.Count > 0)
|
||||
{
|
||||
StartCopyJob(chosen.Select(r => r.Id).ToList());
|
||||
}
|
||||
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/// <summary>«Interrompi»: stops the running job and waits until its states are saved.</summary>
|
||||
public async Task InterruptAsync(CancellationToken ct = default)
|
||||
{
|
||||
Job? job;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job is { Task.IsCompleted: false } j ? j : null;
|
||||
}
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
||||
await job.Task.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our
|
||||
/// <c>.part</c> files in its folders go; no other file is touched, and the copies made stay.
|
||||
/// </summary>
|
||||
public async Task DiscardAsync(long runId, CancellationToken ct = default)
|
||||
{
|
||||
if (ActiveRunIds.Contains(runId))
|
||||
{
|
||||
await InterruptAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato.");
|
||||
if (run.State is ExportRunState.Completed or ExportRunState.Cancelled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false);
|
||||
if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination)
|
||||
{
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Controlla le copie»: a job without a record (not resumable, idempotent) that looks for every Copied or
|
||||
/// Superseded copy of a destination and marks «Tolto» those whose file is gone. Never touches a file.
|
||||
/// </summary>
|
||||
public async Task CheckCopiesAsync(long destinationId, CancellationToken ct = default)
|
||||
{
|
||||
EnsureIdle();
|
||||
var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata.");
|
||||
if (destination.IsRetired)
|
||||
{
|
||||
throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da controllare.");
|
||||
}
|
||||
|
||||
StartJob([], (progress, token) => CheckJobAsync(destination, progress, token));
|
||||
}
|
||||
|
||||
/// <summary>The progress of the running job, or a snapshot of the newest job.</summary>
|
||||
public async Task<ExportProgress> GetProgressAsync(CancellationToken ct = default)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_job is { Task.IsCompleted: false } && _current is { } current)
|
||||
{
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
var newest = (await _env.Storage.Exports.ListRecentRunsAsync(1, ct).ConfigureAwait(false)).FirstOrDefault();
|
||||
return newest is null
|
||||
? new ExportProgress(null, ExportPhase.Finished, 0, 0, 0, 0, null, null, new Dictionary<ExportItemState, int>(), _env.Clock.Now)
|
||||
: await SnapshotAsync(newest, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits for the running job (if any) to end, however it ends.</summary>
|
||||
public async Task WaitAsync(CancellationToken ct = default)
|
||||
{
|
||||
Job? job;
|
||||
Task cleanup;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job;
|
||||
cleanup = _cleanup;
|
||||
}
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
await job.Task.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await cleanup.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Job? job;
|
||||
Task cleanup;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job;
|
||||
cleanup = _cleanup;
|
||||
}
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
||||
await job.Task.ConfigureAwait(false);
|
||||
job.Cancellation.Dispose();
|
||||
}
|
||||
|
||||
await cleanup.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<ExportProgress> SnapshotAsync(ExportRun run, CancellationToken ct)
|
||||
{
|
||||
var summary = await _env.Storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false);
|
||||
var destination = await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false);
|
||||
var phase = run.State == ExportRunState.Running && IsBusy ? ExportPhase.Copying : ExportPhase.Finished;
|
||||
return new ExportProgress(
|
||||
run.Id,
|
||||
phase,
|
||||
summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending),
|
||||
summary.Total,
|
||||
0,
|
||||
0,
|
||||
null,
|
||||
destination is null ? null : ExportDestinations.Label(destination),
|
||||
summary.ByState,
|
||||
_env.Clock.Now);
|
||||
}
|
||||
|
||||
private async Task CheckJobAsync(ExportDestination destination, IProgress<ExportProgress> progress, CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var label = ExportDestinations.Label(destination);
|
||||
var counts = await exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
|
||||
var total = counts.GetValueOrDefault(ExportCopyState.Copied) + counts.GetValueOrDefault(ExportCopyState.Superseded);
|
||||
void Report(ExportPhase phase, int done) =>
|
||||
progress.Report(new ExportProgress(null, phase, done, total, 0, 0, null, label, new Dictionary<ExportItemState, int>(), _env.Clock.Now));
|
||||
|
||||
Report(ExportPhase.Checking, 0);
|
||||
if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem)
|
||||
{
|
||||
await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false);
|
||||
Report(ExportPhase.Finished, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false);
|
||||
var done = 0;
|
||||
var removed = 0;
|
||||
foreach (var state in new[] { ExportCopyState.Copied, ExportCopyState.Superseded })
|
||||
{
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
while (_env.Session.InSession)
|
||||
{
|
||||
Report(ExportPhase.WaitingForSession, done);
|
||||
await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var page = await exports.ListCopiesAsync(destination.Id, state, after, 1000, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
after = page[^1].Id;
|
||||
if (!Directory.Exists(destination.RootPath))
|
||||
{
|
||||
// The disk went away during the check: nothing is «Tolto» because of that.
|
||||
var gone = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile.";
|
||||
await ExportPause.PauseAsync(_env, destination, gone).ConfigureAwait(false);
|
||||
Report(ExportPhase.Finished, done);
|
||||
return;
|
||||
}
|
||||
|
||||
var missing = new List<long>();
|
||||
foreach (var copy in page)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path))
|
||||
{
|
||||
missing.Add(copy.Id);
|
||||
}
|
||||
}
|
||||
|
||||
removed += await exports.MarkCopiesRemovedAsync(missing, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
done += page.Count;
|
||||
Report(ExportPhase.Checking, done);
|
||||
}
|
||||
}
|
||||
|
||||
await _env.Storage.Events.AppendAsync(
|
||||
new EventRecord
|
||||
{
|
||||
At = _env.Clock.Now,
|
||||
Code = "esportazione-controllo",
|
||||
Message = ExportText.CheckMessage(done, removed, destination),
|
||||
Severity = removed > 0 ? EventSeverity.Warning : EventSeverity.Success,
|
||||
AccountId = destination.AccountId,
|
||||
},
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
Report(ExportPhase.Finished, done);
|
||||
}
|
||||
|
||||
private bool FileExists(string root, string relativePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CleanLeftoversAsync(IReadOnlyList<ExportRun> runs)
|
||||
{
|
||||
foreach (var run in runs)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId).ConfigureAwait(false) is { } destination)
|
||||
{
|
||||
await ExportLeftovers.CleanAsync(_env, run, destination, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Best effort: the resume of that job cleans again.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopRunsAsync(IEnumerable<ExportRun> runs)
|
||||
{
|
||||
foreach (var run in runs)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The job never started: nothing was copied, there is nothing to resume.
|
||||
await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false);
|
||||
await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// RecoverAsync makes it «interrotto» at the next start.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureIdle()
|
||||
{
|
||||
if (IsBusy)
|
||||
{
|
||||
throw new InvalidOperationException(BusyText);
|
||||
}
|
||||
|
||||
if (_env.Gate?.Busy is { } busy)
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy));
|
||||
}
|
||||
}
|
||||
|
||||
private void StartCopyJob(IReadOnlyList<long> runIds) =>
|
||||
StartJob(runIds, async (progress, token) =>
|
||||
{
|
||||
foreach (var runId in runIds)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
await Copier.CopyAsync(runId, progress, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
// Stored with the run (Interrupted, with its error); the next destination still gets its files.
|
||||
LastJobError = ExportText.ErrorText(ex);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, CancellationToken, Task> work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_job is { Task.IsCompleted: false })
|
||||
{
|
||||
throw new InvalidOperationException(BusyText);
|
||||
}
|
||||
|
||||
IDisposable? lease = null;
|
||||
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy))
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value));
|
||||
}
|
||||
|
||||
_job?.Cancellation.Dispose();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
var reporter = new Reporter(this);
|
||||
LastJobError = null;
|
||||
_current = new ExportProgress(runIds.Count > 0 ? runIds[0] : null, runIds.Count > 0 ? ExportPhase.Preparing : ExportPhase.Checking, 0, 0, 0, 0, null, null, new Dictionary<ExportItemState, int>(), _env.Clock.Now);
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await work(reporter, cancellation.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
// Interrupted: the states were saved by the job.
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastJobError = ExportText.ErrorText(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
var last = _current is { } c ? c with { Phase = ExportPhase.Finished, UpdatedAt = _env.Clock.Now } : null;
|
||||
if (last is not null)
|
||||
{
|
||||
Publish(last, force: true);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
lease?.Dispose();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
JobFinished?.Invoke(this, new ExportJobFinished(runIds, CopiesChanged: true));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// A handler failed: the job is over all the same.
|
||||
}
|
||||
}
|
||||
});
|
||||
_job = new Job(runIds, cancellation, task);
|
||||
}
|
||||
}
|
||||
|
||||
private void Publish(ExportProgress progress, bool force)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_current = progress;
|
||||
}
|
||||
|
||||
var now = Stopwatch.GetTimestamp();
|
||||
var last = Interlocked.Read(ref _lastPublished);
|
||||
if (!force && Stopwatch.GetElapsedTime(last, now) < ProgressInterval)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Interlocked.Exchange(ref _lastPublished, now);
|
||||
ProgressChanged?.Invoke(this, progress);
|
||||
}
|
||||
|
||||
private sealed record Job(IReadOnlyList<long> RunIds, CancellationTokenSource Cancellation, Task Task);
|
||||
|
||||
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
|
||||
{
|
||||
private (ExportPhase, long?)? _phase;
|
||||
|
||||
public void Report(ExportProgress value)
|
||||
{
|
||||
var key = (value.Phase, value.RunId);
|
||||
var changed = _phase != key;
|
||||
_phase = key;
|
||||
owner.Publish(value, changed);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// «Superato» (spec §4.10): the library file of an account changed («Tieni il più grande», a slot filled again with
|
||||
/// other bytes, a rebuild that found other bytes on disk), so its copies are of a file the library no longer has. The
|
||||
/// copies stay where they are; they are only marked, and the new file is never copied by itself.
|
||||
/// </summary>
|
||||
public static class ExportSupersession
|
||||
{
|
||||
/// <summary>
|
||||
/// Marks the copies of the account's old file as superseded by the new one. A no-op when the old SHA-256 is null or
|
||||
/// equal to the new one, or when a present file of that account still has the old SHA-256. Writes are not
|
||||
/// cancellable: the library already changed.
|
||||
/// </summary>
|
||||
public static async Task<int> FileChangedAsync(IFebeStorage storage, long accountId, string? oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(newSha256);
|
||||
if (oldSha256 is not { Length: 64 } || newSha256.Length != 64 || string.Equals(oldSha256, newSha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var old = oldSha256.ToLowerInvariant();
|
||||
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
|
||||
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// Texts of the copies to external folders for Alberto (spec §4.10, §10.4): sentence case, dots for thousands, the same
|
||||
/// names everywhere. Notes are stored in <c>export_item.note</c> as English codes (<see cref="Notes"/>) and shown with
|
||||
/// <see cref="Note"/>.
|
||||
/// </summary>
|
||||
public static class ExportText
|
||||
{
|
||||
/// <summary>The codes of <c>export_item.note</c>.</summary>
|
||||
public static class Notes
|
||||
{
|
||||
public const string SourceMissing = "SourceMissing";
|
||||
public const string AccountRemoved = "AccountRemoved";
|
||||
public const string Removed = "Removed";
|
||||
public const string Superseded = "Superseded";
|
||||
public const string CopiedForAnotherAccount = "CopiedForAnotherAccount";
|
||||
public const string SourceChanged = "SourceChanged";
|
||||
public const string TooLargeForFileSystem = "TooLargeForFileSystem";
|
||||
public const string NameTaken = "NameTaken";
|
||||
public const string PathTaken = "PathTaken";
|
||||
public const string NotExported = "NotExported";
|
||||
}
|
||||
|
||||
/// <summary>Name of the state of a file of a job.</summary>
|
||||
public static string State(ExportItemState state) => state switch
|
||||
{
|
||||
ExportItemState.Pending => "In attesa",
|
||||
ExportItemState.Copied => "Copiato",
|
||||
ExportItemState.Adopted => "Adottato",
|
||||
ExportItemState.AlreadyCopied => "Già copiato",
|
||||
ExportItemState.Skipped => "Saltato",
|
||||
ExportItemState.Missing => "File non presente in libreria",
|
||||
ExportItemState.Failed => "Non riuscito",
|
||||
_ => state.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Name of the state of a copy.</summary>
|
||||
public static string CopyState(ExportCopyState state) => state switch
|
||||
{
|
||||
ExportCopyState.Copied => "Copiato",
|
||||
ExportCopyState.Removed => "Tolto",
|
||||
ExportCopyState.Superseded => "Superato",
|
||||
ExportCopyState.Failed => "Non riuscito",
|
||||
_ => state.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
|
||||
public static string? Note(string? code) => code switch
|
||||
{
|
||||
null or "" => null,
|
||||
Notes.SourceMissing => "File non presente in libreria",
|
||||
Notes.AccountRemoved => "L'account è stato rimosso",
|
||||
Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)",
|
||||
Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo",
|
||||
Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)",
|
||||
Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato",
|
||||
Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta",
|
||||
Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero",
|
||||
Notes.PathTaken => "Percorso preso nel frattempo: riprova",
|
||||
Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella",
|
||||
_ => code,
|
||||
};
|
||||
|
||||
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
|
||||
public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many;
|
||||
|
||||
/// <summary>The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.»</summary>
|
||||
public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
int Of(ExportItemState s) => summary.ByState.GetValueOrDefault(s);
|
||||
var parts = new List<string> { Count(Of(ExportItemState.Copied) + Of(ExportItemState.Adopted), "file copiato", "file copiati") };
|
||||
if (Of(ExportItemState.AlreadyCopied) > 0)
|
||||
{
|
||||
parts.Add(Count(Of(ExportItemState.AlreadyCopied), "già copiato", "già copiati"));
|
||||
}
|
||||
|
||||
if (Of(ExportItemState.Skipped) > 0)
|
||||
{
|
||||
parts.Add(Count(Of(ExportItemState.Skipped), "saltato", "saltati"));
|
||||
}
|
||||
|
||||
if (Of(ExportItemState.Missing) > 0)
|
||||
{
|
||||
parts.Add(Count(Of(ExportItemState.Missing), "non presente in libreria", "non presenti in libreria"));
|
||||
}
|
||||
|
||||
if (Of(ExportItemState.Failed) > 0)
|
||||
{
|
||||
parts.Add(Count(Of(ExportItemState.Failed), "non riuscito", "non riusciti"));
|
||||
}
|
||||
|
||||
return $"Copia in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}.";
|
||||
}
|
||||
|
||||
/// <summary>The event of «Controlla le copie».</summary>
|
||||
public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
var text = $"Controllate {ItalianText.Number(checkedCopies)} copie in {ExportDestinations.Label(destination)}: ";
|
||||
return text + (removed == 0 ? "ci sono tutte." : $"{Count(removed, "non c'è più (tolta)", "non ci sono più (tolte)")}.");
|
||||
}
|
||||
|
||||
/// <summary>The space is not enough for the next file (decision D16).</summary>
|
||||
public static string NoSpace(ExportDestination destination, long free, string file, long bytes) =>
|
||||
$"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per copiare {file} ({ItalianText.Bytes(bytes)}) serve più spazio, "
|
||||
+ $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi.";
|
||||
|
||||
/// <summary>The disk said it is full.</summary>
|
||||
public static string DiskFull(ExportDestination destination) =>
|
||||
$"Su {ExportDestinations.Label(destination)} non c'è più spazio: libera spazio, poi riprendi.";
|
||||
|
||||
/// <summary>A file over the FAT32 limit.</summary>
|
||||
public static string TooLarge(long bytes) =>
|
||||
$"Il file pesa {ItalianText.Bytes(bytes)}: su un disco FAT32 un file non può superare 4 GB.";
|
||||
|
||||
/// <summary>The destination was retired while a job used it.</summary>
|
||||
public const string RetiredDestination = "La cartella è stata tolta.";
|
||||
|
||||
/// <summary>An error for Alberto, without paths of secrets: the message of a file error, or a generic sentence.</summary>
|
||||
public static string ErrorText(Exception ex)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ex);
|
||||
return ex switch
|
||||
{
|
||||
ExportFolderException folder => folder.Message,
|
||||
IOException io => $"Errore di lettura o scrittura: {io.Message}",
|
||||
UnauthorizedAccessException => "Febe non ha il permesso di scrivere nella cartella: controlla i permessi.",
|
||||
_ => $"Errore inatteso ({ex.GetType().Name}): riprova; se si ripete, segnalalo.",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
@@ -545,6 +546,9 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
media.State,
|
||||
env.Clock.Now,
|
||||
none).ConfigureAwait(false);
|
||||
|
||||
// The copies of the old file in external folders are now «Superato» (spec §4.10): never copied again by themselves.
|
||||
await ExportSupersession.FileChangedAsync(env.Storage, account.Id, media.Sha256, saved.Sha256, env.Clock.Now, none).ConfigureAwait(false);
|
||||
await context.Ingest.TryAppendJournalAsync(entry.Id, none).ConfigureAwait(false);
|
||||
if (entry.InstagramId is null && string.IsNullOrWhiteSpace(entry.Code) && !string.Equals(oldRelative, saved.RelativePath, StringComparison.Ordinal))
|
||||
{
|
||||
|
||||
@@ -58,6 +58,12 @@ public sealed record ImportEnvironment
|
||||
/// <summary>Reading, hashing and deleting source files.</summary>
|
||||
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// The gate shared with the export and the rebuild (spec §4.10: they never run together). Null: no other long work
|
||||
/// to keep out (tests, the import alone).
|
||||
/// </summary>
|
||||
public LongWorkGate? Gate { get; init; }
|
||||
|
||||
/// <summary>Files analysed at the same time (hashing and decoding).</summary>
|
||||
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
@@ -283,6 +284,12 @@ public sealed class ImportService : IAsyncDisposable
|
||||
{
|
||||
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
||||
}
|
||||
|
||||
// Checked up front too, so a refused start records nothing; StartJob takes the gate for real.
|
||||
if (_env.Gate?.Busy is { } busy)
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy));
|
||||
}
|
||||
}
|
||||
|
||||
private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, CancellationToken, Task> work)
|
||||
@@ -294,6 +301,12 @@ public sealed class ImportService : IAsyncDisposable
|
||||
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
||||
}
|
||||
|
||||
IDisposable? lease = null;
|
||||
if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy))
|
||||
{
|
||||
throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value));
|
||||
}
|
||||
|
||||
_job?.Cancellation.Dispose();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
var reporter = new Reporter(this);
|
||||
@@ -322,6 +335,10 @@ public sealed class ImportService : IAsyncDisposable
|
||||
{
|
||||
// The database is closing: nothing to publish.
|
||||
}
|
||||
finally
|
||||
{
|
||||
lease?.Dispose();
|
||||
}
|
||||
}
|
||||
});
|
||||
_job = new Job(runId, phase, cancellation, task);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
@@ -174,6 +175,11 @@ public sealed class DownloadDuplicateReview(
|
||||
if (ok)
|
||||
{
|
||||
removed++;
|
||||
if (decision == DuplicateDecision.KeepLarger && loser == item.Existing && item.Candidate.Sha256 is { } larger)
|
||||
{
|
||||
// «Tieni il più grande» replaced the file already there: its copies in external folders are «Superato».
|
||||
await ExportSupersession.FileChangedAsync(storage, item.Existing.AccountId, item.Existing.Sha256, larger, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else if (problem is not null)
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
@@ -319,6 +320,10 @@ public sealed class LibraryIngest(
|
||||
throw new EntryDeletedException();
|
||||
}
|
||||
|
||||
// A slot that had other bytes (a rebuild left the journal's SHA-256 on a file to download again, an import
|
||||
// filled it): the copies of the old file in external folders are now «Superato» (spec §4.10).
|
||||
await ExportSupersession.FileChangedAsync(storage, account.Id, media.Sha256, saved.Sha256, now, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
var pairs = new List<DuplicatePair>();
|
||||
if (hash is { } h && hashIndex is not null)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
@@ -202,6 +203,14 @@ public sealed class LibraryRebuilder(
|
||||
}
|
||||
|
||||
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
|
||||
|
||||
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
|
||||
foreach (var (old, now) in report.Changed)
|
||||
{
|
||||
await ExportSupersession.FileChangedAsync(storage, account.Id, old, now, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
report.Changed.Clear();
|
||||
CountUntracked(folder, allItems, report);
|
||||
}
|
||||
|
||||
@@ -554,6 +563,7 @@ public sealed class LibraryRebuilder(
|
||||
report.FilesVerified++;
|
||||
if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
report.Changed.Add((media.Sha256, check.Sha256));
|
||||
report.HashMismatches++;
|
||||
report.Note($"Contenuto diverso da quello registrato: {file.Path}");
|
||||
}
|
||||
@@ -738,6 +748,9 @@ public sealed class LibraryRebuilder(
|
||||
|
||||
public int InvalidLines { get; set; }
|
||||
|
||||
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
|
||||
public List<(string Old, string New)> Changed { get; } = [];
|
||||
|
||||
public void Note(string note)
|
||||
{
|
||||
if (_notes.Count < MaxNotes)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>
|
||||
/// One line of <c>/proc/self/mountinfo</c> (proc(5)): unlike <c>/proc/self/mounts</c> it says which folder of its file
|
||||
/// system a mount shows (<see cref="Root"/>: <c>/</c> when the mount is the root of that file system) and gives the exact
|
||||
/// mount point, which the export needs for <c>/esporta</c> (spec §4.10, §11).
|
||||
/// </summary>
|
||||
/// <param name="Id">Mount id.</param>
|
||||
/// <param name="ParentId">Id of the parent mount.</param>
|
||||
/// <param name="Root">Folder of the file system shown at the mount point (<c>/</c>: its root).</param>
|
||||
/// <param name="MountPoint">Where it is mounted, unescaped.</param>
|
||||
/// <param name="Options">Per-mount options (<c>rw</c>, <c>ro</c>, <c>noatime</c>…).</param>
|
||||
/// <param name="FileSystemType">File system type (<c>ext4</c>, <c>vfat</c>, <c>cifs</c>…).</param>
|
||||
/// <param name="Source">Mount source (<c>/dev/sdb1</c>, <c>//server/share</c>…), unescaped.</param>
|
||||
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source)
|
||||
{
|
||||
/// <summary>The mount is read-only (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>).</summary>
|
||||
public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Reads <c>/proc/self/mountinfo</c>.</summary>
|
||||
public static class MountInfoTable
|
||||
{
|
||||
private const string MountInfoPath = "/proc/self/mountinfo";
|
||||
|
||||
/// <summary>
|
||||
/// Parses the content of <c>/proc/self/mountinfo</c>: fields 0-5, then optional fields up to the separator «-», then
|
||||
/// file system type and source. Malformed lines are skipped; nothing throws.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<MountInfoEntry> Parse(string content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var entries = new List<MountInfoEntry>();
|
||||
foreach (var raw in content.Split('\n'))
|
||||
{
|
||||
var fields = raw.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (fields.Length < 9
|
||||
|| !int.TryParse(fields[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id)
|
||||
|| !int.TryParse(fields[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parent))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var separator = Array.IndexOf(fields, "-", 6);
|
||||
if (separator < 0 || separator + 2 >= fields.Length)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var root = MountTable.Unescape(fields[3]);
|
||||
var point = MountTable.Unescape(fields[4]);
|
||||
if (!root.StartsWith('/') || !point.StartsWith('/'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
entries.Add(new MountInfoEntry(
|
||||
id,
|
||||
parent,
|
||||
root,
|
||||
point,
|
||||
fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries),
|
||||
fields[separator + 1],
|
||||
MountTable.Unescape(fields[separator + 2])));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mount that holds a path: the longest mount point that is the path itself or one of its parents (ordinal
|
||||
/// comparison; a later mount over the same point wins, as the kernel shows the last one). Null when none matches.
|
||||
/// </summary>
|
||||
public static MountInfoEntry? FindContaining(IReadOnlyList<MountInfoEntry> mounts, string fullPath)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mounts);
|
||||
ArgumentNullException.ThrowIfNull(fullPath);
|
||||
var path = fullPath.Length > 1 ? fullPath.TrimEnd('/') : fullPath;
|
||||
MountInfoEntry? best = null;
|
||||
var bestLength = -1;
|
||||
foreach (var mount in mounts)
|
||||
{
|
||||
var point = mount.MountPoint.Length > 1 ? mount.MountPoint.TrimEnd('/') : mount.MountPoint;
|
||||
var contains = point == "/"
|
||||
|| string.Equals(path, point, StringComparison.Ordinal)
|
||||
|| path.StartsWith(point + "/", StringComparison.Ordinal);
|
||||
if (contains && point.Length >= bestLength)
|
||||
{
|
||||
best = mount;
|
||||
bestLength = point.Length;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>The content of <c>/proc/self/mountinfo</c> on Linux; null elsewhere or when it cannot be read.</summary>
|
||||
public static string? ReadProcSelf()
|
||||
{
|
||||
if (!OperatingSystem.IsLinux())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return File.Exists(MountInfoPath) ? File.ReadAllText(MountInfoPath) : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,21 @@ public sealed record SafeWriteOptions
|
||||
|
||||
/// <summary>Bytes written so far.</summary>
|
||||
public IProgress<long>? Progress { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The root folder must already exist: <see cref="ExportRootMissingException"/> before anything is created (spec §4.10
|
||||
/// «La radice di una destinazione non si crea mai»: a missing disk or share must not become a local folder).
|
||||
/// Subfolders are still created. The root could vanish between the check and the creation of a subfolder: on Windows
|
||||
/// a missing drive or share throws anyway, and in Docker a mount cannot vanish inside a running container.
|
||||
/// </summary>
|
||||
public bool RequireExistingRoot { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// After the flush, read the temporary file back from the disk and compare its SHA-256 with the one computed while
|
||||
/// writing, before the final name is decided (copies to external disks, spec §4.10). On a mismatch the temporary file
|
||||
/// is removed and an <see cref="IOException"/> says so.
|
||||
/// </summary>
|
||||
public bool VerifyFromDisk { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
|
||||
@@ -47,6 +62,24 @@ public sealed class FileTooLargeException : IOException
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The root folder of a write with <see cref="SafeWriteOptions.RequireExistingRoot"/> does not exist; nothing was created.</summary>
|
||||
public sealed class ExportRootMissingException : DirectoryNotFoundException
|
||||
{
|
||||
public ExportRootMissingException()
|
||||
{
|
||||
}
|
||||
|
||||
public ExportRootMissingException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public ExportRootMissingException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes library files safely (spec §6.5 point 4, rule 12):
|
||||
/// <list type="number">
|
||||
@@ -136,6 +169,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
options ??= new SafeWriteOptions();
|
||||
var root = Path.GetFullPath(rootFolder);
|
||||
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
|
||||
if (options.RequireExistingRoot && !Directory.Exists(root))
|
||||
{
|
||||
throw new ExportRootMissingException($"La cartella {root} non c'è: Febe non la crea, perché un disco o una condivisione assente non deve diventare una cartella locale.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(tempFolder);
|
||||
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
|
||||
using var reservation = ReserveTemporaryFile(tempPath);
|
||||
@@ -144,6 +182,10 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
{
|
||||
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (options.VerifyFromDisk)
|
||||
{
|
||||
await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var desired = await decide(digest, ct).ConfigureAwait(false);
|
||||
if (desired is null)
|
||||
@@ -247,6 +289,22 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||
}
|
||||
|
||||
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
|
||||
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
|
||||
{
|
||||
string onDisk;
|
||||
await using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan))
|
||||
{
|
||||
onDisk = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
if (!string.Equals(onDisk, digest.Sha256, StringComparison.Ordinal))
|
||||
{
|
||||
TryDelete(tempPath); // our own temporary file: the caller's finally would remove it too
|
||||
throw new IOException("La copia scritta sul disco non corrisponde: il disco potrebbe avere problemi.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary>
|
||||
private static List<string> Segments(string relativePath)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
|
||||
namespace Febe.Core.Storage;
|
||||
|
||||
@@ -169,6 +170,90 @@ public interface IExportStore
|
||||
|
||||
/// <summary>Removes a job with its items. Only records: copies stay.</summary>
|
||||
Task DeleteRunAsync(long runId, CancellationToken ct = default);
|
||||
|
||||
// Tappa E2: the copies to external folders ----------------------------------------------------------------------
|
||||
|
||||
/// <summary>Every recorded «Esporta questo account», in one read: only accounts with a row (absent = the default).</summary>
|
||||
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> is
|
||||
/// this SHA-256: the library file that took the place of a copied one, never copied again by itself.
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Una copia sola»: the newest Copied row of this original, variant and format in a destination in use, any account.</summary>
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
|
||||
/// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row
|
||||
/// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256
|
||||
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
|
||||
long destinationId,
|
||||
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Controlla le copie»: Copied or Superseded rows become Removed («Tolto», state time <paramref name="at"/>) in one transaction. Returns the rows changed.</summary>
|
||||
Task<int> MarkCopiesRemovedAsync(IReadOnlyList<long> copyIds, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The library files of a «Copia in…», by media id, a page at a time (after <paramref name="afterMediaId"/>), present
|
||||
/// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter
|
||||
/// the files of its entries (with «Tutte le foto», only the files it shows).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Jobs for the Dashboard: newest first, at most <paramref name="limit"/>.</summary>
|
||||
Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The mark of each tile of a page (decision D3 of tappa E2): of the files of the entry that are due (present, of an
|
||||
/// account with «Esporta questo account» on, a destination and a content type it takes), how many are copied in
|
||||
/// the account's effective destination. Entries without due files are absent.
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
|
||||
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
|
||||
Task<ExportAccountCounts> CountAccountFilesAsync(long accountId, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>A library file a «Copia in…» may copy (one row per media, with what the plan needs of its entry).</summary>
|
||||
public sealed record ExportCandidate(
|
||||
long MediaId,
|
||||
long EntryId,
|
||||
long AccountId,
|
||||
EntryKind EntryKind,
|
||||
MediaKind MediaKind,
|
||||
MediaState State,
|
||||
string? Sha256,
|
||||
long? Bytes,
|
||||
string? RelativePath,
|
||||
int Position,
|
||||
bool InHighlight);
|
||||
|
||||
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
|
||||
public enum ExportMark
|
||||
{
|
||||
None,
|
||||
Partly,
|
||||
Copied,
|
||||
}
|
||||
|
||||
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
|
||||
/// <param name="Due">Files that go to the account's effective destination.</param>
|
||||
/// <param name="NotCopied">Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included).</param>
|
||||
/// <param name="RemovedOrSuperseded">Due files whose copy was removed from the destination or superseded: never copied again by themselves.</param>
|
||||
/// <param name="Failed">Due files whose last copy failed (also counted in <paramref name="NotCopied"/>).</param>
|
||||
public sealed record ExportAccountCounts(int Due, int NotCopied, int RemovedOrSuperseded, int Failed)
|
||||
{
|
||||
/// <summary>Due files copied.</summary>
|
||||
public int Copied => Due - NotCopied - RemovedOrSuperseded;
|
||||
}
|
||||
|
||||
/// <summary>A page of the items of an export job.</summary>
|
||||
|
||||
@@ -30,6 +30,22 @@ public enum LibraryKindFilter
|
||||
Posts,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The «Copie» filter (spec §4.6, §4.10), over the files that are due (decision D3 of tappa E2): «Non ancora copiati»,
|
||||
/// «Copiati», «Tolti o superati». Null: «Tutti».
|
||||
/// </summary>
|
||||
public enum LibraryCopiesFilter
|
||||
{
|
||||
/// <summary>«Non ancora copiati»: an entry with a due file that «Copia in…» would copy (a failed copy included).</summary>
|
||||
NotCopied,
|
||||
|
||||
/// <summary>«Copiati»: an entry whose due files are all copied in their effective destination.</summary>
|
||||
Copied,
|
||||
|
||||
/// <summary>«Tolti o superati»: an entry with a due file whose copy was removed or superseded (never copied again by itself).</summary>
|
||||
RemovedOrSuperseded,
|
||||
}
|
||||
|
||||
/// <summary>Filters of the library mosaic and of the account tabs (spec §4.6).</summary>
|
||||
public sealed record LibraryFilter
|
||||
{
|
||||
@@ -54,6 +70,9 @@ public sealed record LibraryFilter
|
||||
|
||||
/// <summary>Entry states shown. Null means <see cref="EntryStateRules.Visible"/> (entries with files).</summary>
|
||||
public IReadOnlyList<EntryState>? States { get; init; }
|
||||
|
||||
/// <summary>«Copie» (null: «Tutti»). With «Tutte le foto» it applies to each file.</summary>
|
||||
public LibraryCopiesFilter? Copies { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user