M7 Importazione: sorgenti con sola lettura riconosciuta, analisi in sola lettura interrompibile e ripristinabile (tipo dal contenuto, SHA-256, impronta, date da nome, EXIF scritto a mano, mvhd e ffprobe facoltativo), riconoscitori Febe, generico e 4K Stogram come ipotesi spenta, confronto con la libreria e dentro la sorgente, associazione cartelle-account, decisioni sui doppioni, copia o spostamento verificati con sostituzione sicura, resoconto e CSV; prove
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
32 files changed
+7707
-3
No files matched your search
@@ -0,0 +1,362 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Import;
|
||||
|
||||
/// <summary>
|
||||
/// The import for the interface (spec §9, mockup 09): one object with the four steps. Analysis and copy run in the
|
||||
/// background, one job at a time; the interface follows them with <see cref="ProgressChanged"/> or
|
||||
/// <see cref="GetProgressAsync"/> and stops them with <see cref="InterruptAsync"/>. Every state lives in the database:
|
||||
/// after a restart call <see cref="RecoverAsync"/> once, then <see cref="ResumeAsync"/> continues where it stopped.
|
||||
/// See <c>src/Febe.Core/Import/LEGGIMI.md</c>.
|
||||
/// </summary>
|
||||
public sealed class ImportService : IAsyncDisposable
|
||||
{
|
||||
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
||||
|
||||
private readonly ImportEnvironment _env;
|
||||
private readonly Lock _gate = new();
|
||||
private Job? _job;
|
||||
private ImportProgress? _current;
|
||||
private long _lastPublished;
|
||||
|
||||
public ImportService(ImportEnvironment env)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(env);
|
||||
_env = env;
|
||||
Sources = env.CreateSources();
|
||||
Analyzer = new ImportAnalyzer(env);
|
||||
Copier = new ImportCopier(env);
|
||||
Review = new ImportReview(env);
|
||||
Reports = new ImportReports(env);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Progress of the running job, at most four times a second and at every change of phase. Raised on a pool thread:
|
||||
/// handlers must be quick and thread-safe.
|
||||
/// </summary>
|
||||
public event EventHandler<ImportProgress>? ProgressChanged;
|
||||
|
||||
/// <summary>Step 1: checking sources.</summary>
|
||||
public ImportSources Sources { get; }
|
||||
|
||||
public ImportAnalyzer Analyzer { get; }
|
||||
|
||||
public ImportCopier Copier { get; }
|
||||
|
||||
public ImportReview Review { get; }
|
||||
|
||||
public ImportReports Reports { get; }
|
||||
|
||||
/// <summary>The import whose job is running, if any.</summary>
|
||||
public long? ActiveRunId
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _job is { Task.IsCompleted: false } job ? job.RunId : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The last error of a background job that could not be stored with the import (normally null).</summary>
|
||||
public string? LastJobError { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// After a restart: an analysis or a copy that was running when Febe stopped becomes «interrotta», ready to resume.
|
||||
/// Call once at start-up, before anything else.
|
||||
/// </summary>
|
||||
public async Task<int> RecoverAsync(CancellationToken ct = default)
|
||||
{
|
||||
var active = ActiveRunId;
|
||||
var recovered = 0;
|
||||
foreach (var run in await _env.Storage.Imports.ListRunsAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
if (run.Id == active)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var state = run.State switch
|
||||
{
|
||||
ImportRunState.Analyzing => ImportRunState.AnalysisInterrupted,
|
||||
ImportRunState.Copying => ImportRunState.CopyInterrupted,
|
||||
_ => run.State,
|
||||
};
|
||||
if (state != run.State)
|
||||
{
|
||||
await _env.Storage.Imports.UpdateRunAsync(run with { State = state }, ct).ConfigureAwait(false);
|
||||
recovered++;
|
||||
}
|
||||
}
|
||||
|
||||
return recovered;
|
||||
}
|
||||
|
||||
/// <summary>Imports, newest first (to offer «Riprendi» on an unfinished one).</summary>
|
||||
public Task<IReadOnlyList<ImportRun>> ListRunsAsync(CancellationToken ct = default) => _env.Storage.Imports.ListRunsAsync(ct);
|
||||
|
||||
public Task<ImportRun?> GetRunAsync(long runId, CancellationToken ct = default) => _env.Storage.Imports.GetRunAsync(runId, ct);
|
||||
|
||||
/// <summary>Step 1: checks a folder. Throws <see cref="ImportSourceException"/> with the reason in Italian.</summary>
|
||||
public ImportSourceInfo InspectSource(string path) => Sources.Inspect(path);
|
||||
|
||||
/// <summary>Step 1 in Docker: the subfolders of <c>/importa</c> (or of one of its subfolders).</summary>
|
||||
public IReadOnlyList<SourceFolderChoice> BrowseSources(string? path = null) => Sources.Browse(path);
|
||||
|
||||
/// <summary>Step 1 → 2: records the import and starts the analysis in the background.</summary>
|
||||
/// <exception cref="ImportSourceException">The folder cannot be used.</exception>
|
||||
/// <exception cref="InvalidOperationException">Another import job is running.</exception>
|
||||
public async Task<ImportRun> StartAsync(string sourcePath, ImportAnalysisOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
EnsureIdle();
|
||||
var source = Sources.Inspect(sourcePath);
|
||||
var run = await Analyzer.CreateRunAsync(source, options, ct).ConfigureAwait(false);
|
||||
StartJob(run.Id, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(run.Id, progress, token));
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>Continues an interrupted analysis or copy in the background.</summary>
|
||||
public async Task<ImportRun> ResumeAsync(long runId, CancellationToken ct = default)
|
||||
{
|
||||
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
||||
switch (run.State)
|
||||
{
|
||||
case ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted:
|
||||
StartJob(runId, ImportPhase.Analyzing, (progress, token) => Analyzer.AnalyzeAsync(runId, progress, token));
|
||||
break;
|
||||
case ImportRunState.Copying or ImportRunState.CopyInterrupted:
|
||||
StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token));
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException("Questa importazione non è interrotta: non c'è niente da riprendere.");
|
||||
}
|
||||
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Step 3 → 4: starts the copy in the background (also «importa i rimasti» on a completed import, after a change of
|
||||
/// associations or decisions). With <paramref name="mode"/> the mode is set first.
|
||||
/// </summary>
|
||||
public async Task<ImportRun> StartCopyAsync(long runId, ImportMode? mode = null, CancellationToken ct = default)
|
||||
{
|
||||
EnsureIdle();
|
||||
var run = mode is { } m
|
||||
? await Review.SetModeAsync(runId, m, ct).ConfigureAwait(false)
|
||||
: await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
||||
if (run.State is not (ImportRunState.Reviewing or ImportRunState.CopyInterrupted or ImportRunState.Completed))
|
||||
{
|
||||
throw new InvalidOperationException("L'analisi non è finita: riprendila prima di importare.");
|
||||
}
|
||||
|
||||
StartJob(runId, ImportPhase.Copying, (progress, token) => Copier.CopyAsync(runId, progress, token));
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>«Interrompi»: stops the running job of this import and waits until its state is saved.</summary>
|
||||
public async Task InterruptAsync(long runId)
|
||||
{
|
||||
Job? job;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job is { RunId: var id } j && id == runId ? j : null;
|
||||
}
|
||||
|
||||
if (job is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
||||
await job.Task.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits for the running job of this import (if any) to end, however it ends; returns the import.</summary>
|
||||
public async Task<ImportRun?> WaitAsync(long runId, CancellationToken ct = default)
|
||||
{
|
||||
Job? job;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job is { RunId: var id } j && id == runId ? j : null;
|
||||
}
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
await job.Task.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The progress of an import: live while its job runs, otherwise from the database.</summary>
|
||||
public async Task<ImportProgress> GetProgressAsync(long runId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_job is { RunId: var id, Task.IsCompleted: false } && id == runId && _current is { } current && current.RunId == runId)
|
||||
{
|
||||
return current;
|
||||
}
|
||||
}
|
||||
|
||||
var run = await _env.Storage.Imports.GetRunAsync(runId).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"Importazione {runId} non trovata.");
|
||||
var phase = run.State switch
|
||||
{
|
||||
ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted => ImportPhase.Analyzing,
|
||||
ImportRunState.Copying or ImportRunState.CopyInterrupted => ImportPhase.Copying,
|
||||
_ => ImportPhase.Finished,
|
||||
};
|
||||
return await Analyzer.SnapshotAsync(runId, phase, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Step 3, delegated to the review (see ImportReview).
|
||||
public Task<ImportReviewSummary> GetReviewAsync(long runId, CancellationToken ct = default) => Review.GetSummaryAsync(runId, ct);
|
||||
|
||||
public Task SetFolderTargetAsync(long runId, string folder, FolderTarget target, CancellationToken ct = default) => Review.SetFolderTargetAsync(runId, folder, target, ct);
|
||||
|
||||
public Task<ImportRun> SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) => Review.SetModeAsync(runId, mode, ct);
|
||||
|
||||
public Task<IReadOnlyList<DuplicateCase>> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) =>
|
||||
Review.ListDuplicatesAsync(runId, pendingOnly, afterPairId, limit, ct);
|
||||
|
||||
public Task<int> DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) =>
|
||||
Review.DecideAsync(runId, pairId, decision, scope, ct);
|
||||
|
||||
public Task<ImportPlan> GetPlanAsync(long runId, CancellationToken ct = default) => Review.GetPlanAsync(runId, ct);
|
||||
|
||||
// Step 4.
|
||||
public Task<ImportReport> GetReportAsync(long runId, CancellationToken ct = default) => Reports.GetReportAsync(runId, ct);
|
||||
|
||||
public Task WriteCsvAsync(long runId, Stream destination, CancellationToken ct = default) => Reports.WriteCsvAsync(runId, destination, ct);
|
||||
|
||||
/// <summary>
|
||||
/// «Annulla l'importazione»: stops its job; if nothing was copied yet the import disappears with its records,
|
||||
/// otherwise it becomes «annullata» and its pending duplicates are withdrawn. Files are never touched.
|
||||
/// </summary>
|
||||
public async Task DiscardAsync(long runId, CancellationToken ct = default)
|
||||
{
|
||||
await InterruptAsync(runId).ConfigureAwait(false);
|
||||
var run = await _env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false);
|
||||
if (run is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var summary = await _env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false);
|
||||
if (summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved] == 0)
|
||||
{
|
||||
await _env.Storage.Imports.DeleteRunAsync(runId, ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _env.Storage.Imports.RemovePendingPairsAsync(runId, ct).ConfigureAwait(false);
|
||||
await _env.Storage.Imports.UpdateRunAsync(run with { State = ImportRunState.Cancelled, CompletedAt = _env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await ImportRunSettings.ClearAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Job? job;
|
||||
lock (_gate)
|
||||
{
|
||||
job = _job;
|
||||
}
|
||||
|
||||
if (job is not null)
|
||||
{
|
||||
await job.Cancellation.CancelAsync().ConfigureAwait(false);
|
||||
await job.Task.ConfigureAwait(false);
|
||||
job.Cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureIdle()
|
||||
{
|
||||
if (ActiveRunId is not null)
|
||||
{
|
||||
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
||||
}
|
||||
}
|
||||
|
||||
private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, CancellationToken, Task> work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_job is { Task.IsCompleted: false })
|
||||
{
|
||||
throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila.");
|
||||
}
|
||||
|
||||
_job?.Cancellation.Dispose();
|
||||
var cancellation = new CancellationTokenSource();
|
||||
var reporter = new Reporter(this);
|
||||
_current = new ImportProgress(runId, phase, 0, 0, 0, 0, null, new Dictionary<ImportOutcome, int>(), 0, _env.Clock.Now);
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await work(reporter, cancellation.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
||||
{
|
||||
// Interrupted: the state was saved by the analysis or the copy.
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastJobError = ImportAnalyzer.ErrorText(ex); // also stored with the import when possible
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
Publish(await Analyzer.SnapshotAsync(runId, ImportPhase.Finished, null).ConfigureAwait(false), force: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The database is closing: nothing to publish.
|
||||
}
|
||||
}
|
||||
});
|
||||
_job = new Job(runId, phase, cancellation, task);
|
||||
}
|
||||
}
|
||||
|
||||
private void Publish(ImportProgress 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(long RunId, ImportPhase Phase, CancellationTokenSource Cancellation, Task Task);
|
||||
|
||||
private sealed class Reporter(ImportService owner) : IProgress<ImportProgress>
|
||||
{
|
||||
private ImportPhase? _phase;
|
||||
|
||||
public void Report(ImportProgress value)
|
||||
{
|
||||
var phaseChanged = _phase != value.Phase;
|
||||
_phase = value.Phase;
|
||||
owner.Publish(value, phaseChanged);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user