using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Storage; namespace Febe.Core.Import; /// /// Step 3 of the import (spec §9.3, §9.4, mockup 09): the summary, the association of folders with accounts, the probable /// duplicates and Alberto's decisions, the mode and the plan of the final button. Nothing here touches a file. /// public sealed class ImportReview(ImportEnvironment env) { private readonly SemaphoreSlim _settingsGate = new(1, 1); /// The summary of an analysed import. public async Task GetSummaryAsync(long runId, CancellationToken ct = default) { var run = await GetRunAsync(runId, ct).ConfigureAwait(false); var summary = await env.Storage.Imports.GetSummaryAsync(runId, ct).ConfigureAwait(false); var folders = await ListFoldersAsync(run, ct).ConfigureAwait(false); var pending = await env.Storage.Imports.CountPairsAsync(runId, pendingOnly: true, ct).ConfigureAwait(false); var stogram = await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); return new ImportReviewSummary( run, env.CreateSources().DisplayPath(run.SourcePath), summary.Total, summary.Bytes, summary.ByOutcome, folders.Sum(f => f.Recognized), pending, folders, run.AnalyzedAt is { } analyzed ? analyzed - run.StartedAt : null, stogram, summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved], damaged.Count); } /// The rows of «Cartelle e account». public async Task> ListFoldersAsync(long runId, CancellationToken ct = default) => await ListFoldersAsync(await GetRunAsync(runId, ct).ConfigureAwait(false), ct).ConfigureAwait(false); private async Task> ListFoldersAsync(ImportRun run, CancellationToken ct) { var counts = await env.Storage.Imports.ListFolderCountsAsync(run.Id, ct).ConfigureAwait(false); var newAccounts = await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, run.Id, ct).ConfigureAwait(false); var layout = Directory.Exists(run.SourcePath) ? SourceLayout.Inspect(run.SourcePath) : null; var rows = new List(); foreach (var folder in counts) { FolderTarget target; if (folder.TargetAccountId is { } accountId) { var account = await env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); target = new FolderTarget(FolderTargetKind.Existing, accountId, account?.Username); } else if (newAccounts.TryGetValue(folder.Folder, out var username)) { target = FolderTarget.NewArchiveAccount(username); } else { target = FolderTarget.None; } rows.Add(new ImportFolderReview( folder.Folder, layout?.DisplayName(folder.Folder) ?? (folder.Folder.Length == 0 ? Path.GetFileName(run.SourcePath) : folder.Folder), folder.ProbableAccount, folder.Files, folder.Bytes, folder.ByOutcome[ImportOutcome.New], folder.ByOutcome[ImportOutcome.AlreadyInLibrary] + folder.ByOutcome[ImportOutcome.IdenticalInSource], folder.ByOutcome[ImportOutcome.ProbableDuplicate], folder.ByOutcome[ImportOutcome.Unrecognized], folder.Recognized, target)); } return rows; } /// /// Associates a source folder («Va in»): an existing account, a new «Solo archivio» account (created when the copy /// starts; an existing account with that name is used instead), or none (its files stay out). /// /// The account does not exist or the name cannot be an Instagram user name. public async Task SetFolderTargetAsync(long runId, string folder, FolderTarget target, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(folder); ArgumentNullException.ThrowIfNull(target); var run = await GetRunAsync(runId, ct).ConfigureAwait(false); EnsureEditable(run); if (!(await env.Storage.Imports.ListFolderCountsAsync(runId, ct).ConfigureAwait(false)).Any(f => f.Folder == folder)) { throw new ArgumentException("Questa cartella non fa parte dell'importazione.", nameof(folder)); } long? accountId = null; string? newUsername = null; switch (target.Kind) { case FolderTargetKind.Existing: var account = target.AccountId is { } id ? await env.Storage.Accounts.GetAsync(id, ct).ConfigureAwait(false) : null; accountId = account?.Id ?? throw new ArgumentException("L'account scelto non esiste più: scegline un altro.", nameof(target)); break; case FolderTargetKind.NewArchiveAccount: var username = SourceLayout.UsernameFrom(target.Username) ?? throw new ArgumentException("Il nome dell'account può contenere solo lettere, numeri, punti e trattini bassi, fino a 30 caratteri.", nameof(target)); if (await env.Storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false) is { } existing) { accountId = existing.Id; } else { newUsername = username; } break; default: break; } await _settingsGate.WaitAsync(ct).ConfigureAwait(false); try { var intents = new Dictionary(await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false), StringComparer.Ordinal); var changed = newUsername is null ? intents.Remove(folder) : !intents.TryGetValue(folder, out var old) || old != newUsername; if (newUsername is not null) { intents[folder] = newUsername; } await env.Storage.Imports.SetFolderTargetAsync(runId, folder, accountId, ct).ConfigureAwait(false); if (changed) { await ImportRunSettings.SetNewAccountsAsync(env.Storage.Settings, runId, intents, ct).ConfigureAwait(false); } } finally { _settingsGate.Release(); } } /// «Copia» or «Sposta». /// «Sposta» on a read-only source. public async Task SetModeAsync(long runId, ImportMode mode, CancellationToken ct = default) { var run = await GetRunAsync(runId, ct).ConfigureAwait(false); EnsureEditable(run); if (mode == ImportMode.Move && run.SourceReadOnly) { throw new InvalidOperationException("La sorgente è in sola lettura: si può solo copiare."); } run = run with { Mode = mode }; await env.Storage.Imports.UpdateRunAsync(run, ct).ConfigureAwait(false); return run; } /// /// The probable duplicates of an import, both sides described, in creation order. /// gives the ones still to decide. /// public async Task> ListDuplicatesAsync(long runId, bool pendingOnly = true, long afterPairId = 0, int limit = 50, CancellationToken ct = default) { var pairs = await env.Storage.Imports.ListPairsAsync(runId, pendingOnly, afterPairId, limit, ct).ConfigureAwait(false); var cases = new List(pairs.Count); foreach (var pair in pairs) { cases.Add(await DescribeAsync(pair, ct).ConfigureAwait(false)); } return cases; } /// One probable duplicate, both sides described. public async Task GetDuplicateAsync(long pairId, CancellationToken ct = default) => await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false) is { Origin: DuplicateOrigin.Import } pair ? await DescribeAsync(pair, ct).ConfigureAwait(false) : null; /// /// Records Alberto's decision on a probable duplicate and, with , on the other pairs of the /// same import still waiting («Fai lo stesso per gli altri»). Nothing is copied or replaced here: the copy applies /// the decisions. Returns how many pairs were decided. /// /// The decision is «Pending», or the pair is not of this import. public async Task DecideAsync(long runId, long pairId, DuplicateDecision decision, DecisionScope scope = DecisionScope.ThisPair, CancellationToken ct = default) { if (decision == DuplicateDecision.Pending) { throw new ArgumentException("Scegli una delle tre possibilità.", nameof(decision)); } var run = await GetRunAsync(runId, ct).ConfigureAwait(false); EnsureEditable(run); var pair = await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false); var candidate = pair?.CandidateImportFileId is { } fileId ? await env.Storage.Imports.GetFileAsync(fileId, ct).ConfigureAwait(false) : null; if (pair is null || candidate?.RunId != runId) { throw new ArgumentException("Questa coppia non appartiene all'importazione.", nameof(pairId)); } var targets = new List { pair }; if (scope != DecisionScope.ThisPair) { long after = 0; while (true) { var page = await env.Storage.Imports.ListPairsAsync(runId, pendingOnly: true, after, 1000, ct).ConfigureAwait(false); if (page.Count == 0) { break; } targets.AddRange(page.Where(p => p.Id != pair.Id && (scope == DecisionScope.AllPending || p.Reason == pair.Reason))); after = page[^1].Id; } } var now = env.Clock.Now; var fileDecision = decision switch { DuplicateDecision.KeepLarger => ImportDecision.KeepLarger, DuplicateDecision.KeepExisting => ImportDecision.KeepExisting, _ => ImportDecision.KeepBoth, }; foreach (var target in targets) { await env.Storage.Duplicates.DecideAsync(target.Id, decision, now, ct).ConfigureAwait(false); if (target.CandidateImportFileId is { } id && await env.Storage.Imports.GetFileAsync(id, ct).ConfigureAwait(false) is { } file) { await env.Storage.Imports.UpdateFileAsync(file with { Decision = fileDecision }, ct).ConfigureAwait(false); } } return targets.Count; } /// Takes back a decision: the pair waits again (no choice made). public async Task UndecideAsync(long runId, long pairId, CancellationToken ct = default) { var run = await GetRunAsync(runId, ct).ConfigureAwait(false); EnsureEditable(run); var pair = await env.Storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false) ?? throw new ArgumentException("Coppia non trovata.", nameof(pairId)); await env.Storage.Duplicates.DecideAsync(pair.Id, DuplicateDecision.Pending, env.Clock.Now, ct).ConfigureAwait(false); if (pair.CandidateImportFileId is { } id && await env.Storage.Imports.GetFileAsync(id, ct).ConfigureAwait(false) is { RunId: var r } file && r == runId) { await env.Storage.Imports.UpdateFileAsync(file with { Decision = ImportDecision.None }, ct).ConfigureAwait(false); } } /// What «Importa» would do now: files to import, to replace, skipped, left out and why. public async Task GetPlanAsync(long runId, CancellationToken ct = default) { var run = await GetRunAsync(runId, ct).ConfigureAwait(false); var files = new Dictionary(); long after = 0; while (true) { var page = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, AfterId = after, Limit = 10_000 }, ct).ConfigureAwait(false); if (page.Count == 0) { break; } foreach (var file in page) { files[file.Id] = file; } after = page[^1].Id; } var planner = await ImportPlanner.LoadAsync(env.Storage, runId, files, ct).ConfigureAwait(false); int import = 0, replace = 0, skipped = 0, noAccount = 0, undecided = 0, done = 0; long bytes = 0; var blockedFolders = new HashSet(StringComparer.Ordinal); foreach (var file in files.Values) { var planned = planner.Classify(file); switch (planned.Action) { case PlannedAction.Import: import++; bytes += file.Bytes; break; case PlannedAction.Replace: import++; replace++; bytes += file.Bytes; break; case PlannedAction.Skip: skipped++; break; case PlannedAction.WaitNoAccount: noAccount++; blockedFolders.Add(file.Folder); break; case PlannedAction.WaitDecision: undecided++; break; case PlannedAction.Done: if (file.State is ImportFileState.Copied or ImportFileState.Moved) { done++; } else { skipped++; } break; default: break; } } return new ImportPlan(import, replace, skipped, noAccount, blockedFolders.Count, undecided, done, bytes, run.Mode); } /// Opens a file of the source for reading (the comparison panel shows it). public async Task OpenSourceFileAsync(long fileId, CancellationToken ct = default) { var (run, file) = await GetFileWithRunAsync(fileId, ct).ConfigureAwait(false); return env.FileSystem.OpenRead(LibraryLayout.FullPath(run.SourcePath, file.RelativePath)); } /// /// A JPEG preview of a photo of the source, at most pixels (not stored: the source file /// may never enter the library). Null for videos and formats that cannot be decoded. /// public async Task RenderPreviewAsync(long fileId, int longSide = ThumbnailStore.LongSide, CancellationToken ct = default) { var (run, file) = await GetFileWithRunAsync(fileId, ct).ConfigureAwait(false); if (file.MediaKind != MediaKind.Photo) { return null; } await using var stream = env.FileSystem.OpenRead(LibraryLayout.FullPath(run.SourcePath, file.RelativePath)); return ImportPreview.RenderJpeg(stream, Math.Clamp(longSide, 64, 2048)); } private async Task<(ImportRun Run, ImportFile File)> GetFileWithRunAsync(long fileId, CancellationToken ct) { var file = await env.Storage.Imports.GetFileAsync(fileId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"File di importazione {fileId} non trovato."); return (await GetRunAsync(file.RunId, ct).ConfigureAwait(false), file); } private async Task DescribeAsync(DuplicatePair pair, CancellationToken ct) { var existing = await SideAsync(pair.ExistingMediaId, pair.ExistingImportFileId, ct).ConfigureAwait(false); var candidate = await SideAsync(pair.CandidateMediaId, pair.CandidateImportFileId, ct).ConfigureAwait(false); var larger = ImportPlanner.IsLarger(candidate.Width, candidate.Height, candidate.Bytes, existing.Width, existing.Height, existing.Bytes); return new DuplicateCase(pair, existing, candidate, larger); } private async Task SideAsync(long? mediaId, long? fileId, CancellationToken ct) { if (mediaId is { } m && await env.Storage.Media.GetAsync(m, ct).ConfigureAwait(false) is { } media) { var entry = await env.Storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); var account = entry is null ? null : await env.Storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false); return new DuplicateSide(true, media.Id, null, account?.Username, media.RelativePath, media.Kind, media.Width, media.Height, media.Bytes, entry?.PublishedAt, media.Sha256, media.HasThumbnail); } if (fileId is { } f && await env.Storage.Imports.GetFileAsync(f, ct).ConfigureAwait(false) is { } file) { var account = file.TargetAccountId is { } a ? await env.Storage.Accounts.GetAsync(a, ct).ConfigureAwait(false) : null; return new DuplicateSide(false, null, file.Id, account?.Username ?? file.ProbableAccount, file.RelativePath, file.MediaKind, file.Width, file.Height, file.Bytes, file.TakenAt, file.Sha256, false); } return new DuplicateSide(mediaId is not null, mediaId, fileId, null, null, null, null, null, null, null, null, false); } private async Task GetRunAsync(long runId, CancellationToken ct) => await env.Storage.Imports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Importazione {runId} non trovata."); private static void EnsureEditable(ImportRun run) { if (run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted) { throw new InvalidOperationException("L'analisi non è finita: le scelte si fanno dopo."); } if (run.State is ImportRunState.Copying) { throw new InvalidOperationException("La copia è in corso: interrompila prima di cambiare le scelte."); } if (run.State is ImportRunState.Cancelled) { throw new InvalidOperationException("Questa importazione è stata annullata."); } } }