using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Library; using Febe.Core.Storage; namespace Febe.Core.Import; /// /// Step 4 of the import (spec §9.4): copy or move with verification, then the report. /// /// Files enter the library through , like downloads: safe write with SHA-256, thumbnails, /// perceptual hashes, _febe.jsonl line, provenance «importato». Nothing is ever overwritten. /// Files with a known date and code take the name of the library scheme; the others go to /// importati/ with their original name. /// «Sposta» deletes an original only after the copy on disk has been hashed again and matches; never when the /// source is read-only. If the copy does not match, the original stays. /// «Tieni il più grande», when the source file is larger, replaces the library file: only on Alberto's explicit /// choice (rule 12). The new file is written and verified first, then the record and the journal are updated, and only /// then is the old file removed. /// Resumable: every file has its state; an interrupted copy continues where it stopped (an entry created just before /// an interruption is reused, not duplicated). /// /// public sealed class ImportCopier(ImportEnvironment env) { private const string ImportedFolder = "importati"; /// /// Runs (or resumes) the copy of an import. Files that stay out (folder without account, undecided duplicates) keep /// their state: after a change in the review the copy can run again on the same import and takes them. /// On cancellation the import becomes «copia interrotta» and is thrown. /// public async Task CopyAsync(long runId, IProgress? progress = null, CancellationToken ct = default) { var run = 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.Copying or ImportRunState.CopyInterrupted or ImportRunState.Completed)) { throw new InvalidOperationException(run.State is ImportRunState.Analyzing or ImportRunState.AnalysisInterrupted ? "L'analisi non è finita: riprendila prima di importare." : "Questa importazione è stata annullata."); } if (run.Mode == ImportMode.Move && run.SourceReadOnly) { throw new InvalidOperationException("La sorgente è in sola lettura: si può solo copiare."); } run = run with { State = ImportRunState.Copying, LastError = null }; await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); var tally = new Tally(); try { if (!Directory.Exists(run.SourcePath)) { throw new ImportSourceException($"La cartella {run.SourcePath} non si trova più: ricollega il disco e riprendi l'importazione."); } await CreateNewAccountsAsync(run, ct).ConfigureAwait(false); var layout = SourceLayout.Inspect(run.SourcePath); var recognizers = ImportRecognizers.Create( env.Clock.LocalZone, () => env.Clock.Now, await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false)); await recognizers.PrepareAsync(layout, ct).ConfigureAwait(false); var files = await LoadFilesAsync(runId, ct).ConfigureAwait(false); var planner = await ImportPlanner.LoadAsync(env.Storage, runId, files, ct).ConfigureAwait(false); var ingest = new LibraryIngest(env.Storage, env.Layout, env.Naming, env.Journal, env.Clock, env.Thumbnails, hashIndex: null, env.SetFileTimeToPublication); await ingest.AppendPendingJournalAsync(ct).ConfigureAwait(false); // lines a busy _febe.jsonl refused earlier var context = new CopyContext(run, layout, recognizers, ingest); var total = files.Count; var bytesTotal = files.Values.Sum(f => f.Bytes); var done = 0; long bytesDone = 0; var copied = files.Values.Count(f => f.State is ImportFileState.Copied or ImportFileState.Moved); foreach (var file in files.Values.OrderBy(f => f.Id)) { ct.ThrowIfCancellationRequested(); var current = file; if (run.Mode == ImportMode.Move && file.State == ImportFileState.Copied && file.EntryId is not null && file.LastError is { } pending && (pending.EndsWith(ImportText.NoteMovePending, StringComparison.Ordinal) || pending.EndsWith(ImportText.NoteOriginalKept, StringComparison.Ordinal))) { // A move interrupted between the copy and the deletion of the original (or a deletion that failed). // Files copied earlier under «Copia» carry no such note: their originals are never deleted. current = await FinishMoveAsync(context, file, tally).ConfigureAwait(false); } else { var planned = planner.Classify(file); current = await ApplyAsync(context, planned, tally, ct).ConfigureAwait(false); if (current.State is ImportFileState.Copied or ImportFileState.Moved && file.State is not (ImportFileState.Copied or ImportFileState.Moved)) { copied++; } } done++; bytesDone += file.Bytes; progress?.Report(new ImportProgress(runId, ImportPhase.Copying, done, total, bytesDone, bytesTotal, file.RelativePath, new Dictionary(), copied, env.Clock.Now)); } await ingest.AppendPendingJournalAsync(CancellationToken.None).ConfigureAwait(false); run = run with { State = ImportRunState.Completed, CompletedAt = env.Clock.Now, LastError = null }; await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); await env.Storage.Events.AppendAsync( new EventRecord { At = env.Clock.Now, Code = "importazione-completata", Message = CompletionMessage(layout.RootName, tally), Severity = tally.Failed > 0 ? EventSeverity.Warning : EventSeverity.Success, }, CancellationToken.None).ConfigureAwait(false); progress?.Report(new ImportProgress(runId, ImportPhase.Finished, done, total, bytesDone, bytesDone, null, new Dictionary(), copied, env.Clock.Now)); return run; } catch (Exception ex) { var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested; run = run with { State = ImportRunState.CopyInterrupted, LastError = cancelled ? null : ImportAnalyzer.ErrorText(ex) }; await env.Storage.Imports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); throw; } } private static string CompletionMessage(string source, Tally tally) { var text = $"Importazione dalla cartella «{source}» finita: {ImportText.Count(tally.Copied, "file importato", "file importati")}"; if (tally.Replaced > 0) { text += $" ({ImportText.Count(tally.Replaced, "al posto di un file più piccolo", "al posto di file più piccoli")})"; } if (tally.LeftOut > 0) { text += ", " + ImportText.Count(tally.LeftOut, "file resta fuori", "file restano fuori"); } if (tally.Failed > 0) { text += ", " + ImportText.Count(tally.Failed, "file non riuscito", "file non riusciti"); } return text + "."; } private async Task> LoadFilesAsync(long runId, CancellationToken ct) { 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; } return files; } /// Creates the «Solo archivio» accounts chosen in the review and associates their folders. private async Task CreateNewAccountsAsync(ImportRun run, CancellationToken ct) { var intents = await ImportRunSettings.GetNewAccountsAsync(env.Storage.Settings, run.Id, ct).ConfigureAwait(false); if (intents.Count == 0) { return; } foreach (var (folder, username) in intents) { var account = await env.Storage.Accounts.FindByUsernameAsync(username, ct).ConfigureAwait(false); if (account is null) { var now = env.Clock.Now; account = await env.Storage.Accounts.AddAsync( Account.Create(username, StartingPoint.EverythingAndKeepUpdated, now, env.Clock.LocalZone) with { State = AccountState.ArchiveOnly, KeepUpdated = false, StateChangedAt = now, }, CancellationToken.None).ConfigureAwait(false); await env.Storage.Events.AppendAsync( new EventRecord { At = now, Code = "account-solo-archivio", Message = $"Account {account.Username} creato dall'importazione, «Solo archivio».", AccountId = account.Id }, CancellationToken.None).ConfigureAwait(false); } await env.Storage.Imports.SetFolderTargetAsync(run.Id, folder, account.Id, CancellationToken.None).ConfigureAwait(false); } await ImportRunSettings.SetNewAccountsAsync(env.Storage.Settings, run.Id, new Dictionary(), CancellationToken.None).ConfigureAwait(false); } private async Task ApplyAsync(CopyContext context, PlannedFile planned, Tally tally, CancellationToken ct) { var file = planned.File; switch (planned.Action) { case PlannedAction.Done or PlannedAction.NotAnalyzed: return file; case PlannedAction.Skip: tally.Skipped++; return await SaveAsync(file with { State = ImportFileState.Skipped, LastError = planned.Note }).ConfigureAwait(false); case PlannedAction.WaitNoAccount or PlannedAction.WaitDecision: tally.LeftOut++; return file.LastError == planned.Note ? file : await SaveAsync(file with { LastError = planned.Note }).ConfigureAwait(false); default: break; } try { return planned.Action == PlannedAction.Replace ? await ReplaceAsync(context, file, planned.ReplaceMediaId!.Value, tally, ct).ConfigureAwait(false) : await ImportAsync(context, file, tally, ct).ConfigureAwait(false); } catch (ContentChangedException) { tally.Failed++; return await SaveAsync(await CurrentAsync(file).ConfigureAwait(false) with { State = ImportFileState.Failed, LastError = ImportText.NoteChanged }).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { tally.Failed++; return await SaveAsync(await CurrentAsync(file).ConfigureAwait(false) with { State = ImportFileState.Failed, LastError = ImportAnalyzer.ErrorText(ex) }).ConfigureAwait(false); } } /// /// The file's record as saved during the attempt (the entry it was given, so a resumed copy reuses it instead of /// taking the file for one already in the library). /// private async Task CurrentAsync(ImportFile file) => await env.Storage.Imports.GetFileAsync(file.Id, CancellationToken.None).ConfigureAwait(false) ?? file; /// Copies one file into its destination account as an imported entry (or into an entry it completes). private async Task ImportAsync(CopyContext context, ImportFile file, Tally tally, CancellationToken ct) { var source = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); // The library may have received the same bytes since the analysis (an identical copy met earlier in the source). var same = await env.Storage.Media.FindBySha256Async(file.Sha256!, ct).ConfigureAwait(false); if (same.FirstOrDefault(s => EntryStateRules.IsPresent(s.Media.State)) is { } twin && file.EntryId is null) { tally.Skipped++; return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); } var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella."); var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath)); var target = await ResolveTargetAsync(account, file, hints, ct).ConfigureAwait(false); if (target.Deleted) { tally.Skipped++; return await SaveAsync(file with { State = ImportFileState.Skipped, LastError = ImportText.NoteDeletedByAlberto }).ConfigureAwait(false); } var (entry, media) = (target.Entry!, target.Media!); if (file.EntryId != entry.Id) { file = await SaveAsync(file with { EntryId = entry.Id }).ConfigureAwait(false); // a resumed copy reuses this entry } if (EntryStateRules.IsPresent(media.State) && string.Equals(media.Sha256, file.Sha256, StringComparison.Ordinal) && media.RelativePath is { } already) { // Stored before an interruption: only the journal line and the state are missing. await context.Ingest.TryAppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false); return await FinishAsync(context, file, account, entry.Id, already, null, tally).ConfigureAwait(false); } var byScheme = target.ByScheme && file.DateSource is ImportDateSource.FileName or ImportDateSource.Journal or ImportDateSource.Metadata; MediaSaveResult result; try { await using var content = env.FileSystem.OpenRead(source); using var cover = file.MediaKind == MediaKind.Video ? await FrameAsync(source, ct).ConfigureAwait(false) : null; result = await context.Ingest.SaveMediaAsync( account, entry, media, new MediaContent { Content = content, Extension = Extension(file, source), Cover = cover, FixedRelativePath = byScheme ? null : ImportedFolder + "/" + Path.GetFileName(source), ExpectedSha256 = file.Sha256, }, file.HighlightTitle, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or OperationCanceledException) { // Nothing was written under a final name. A record made for this file alone goes too, so that the library // does not show an empty entry; a resumed copy would make it again. if (target.OwnedByThisFile) { await RemoveIfEmptyAsync(entry.Id).ConfigureAwait(false); await SaveAsync(file with { EntryId = null }).ConfigureAwait(false); } throw; } if (result.Outcome == MediaSaveOutcome.IdenticalInAccount) { if (target.OwnedByThisFile) { await RemoveIfEmptyAsync(entry.Id).ConfigureAwait(false); } tally.Skipped++; return await SaveAsync(file with { State = ImportFileState.Skipped, EntryId = null, MatchedMediaId = result.Identical?.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false); } if (result.File!.PerceptualHash is { } hash) { env.HashIndex?.Add(media.Id, account.Id, hash); } if (entry.Kind == EntryKind.Highlight && file.HighlightTitle is { } title) { var none = CancellationToken.None; var collection = await env.Storage.Highlights.FindByTitleAsync(account.Id, title, none).ConfigureAwait(false) ?? await env.Storage.Highlights.UpsertAsync(new Highlight { AccountId = account.Id, Title = title, DiscoveredAt = env.Clock.Now }, none).ConfigureAwait(false); await env.Storage.Highlights.AddItemAsync(collection.Id, entry.Id, none).ConfigureAwait(false); } await context.Ingest.TryAppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false); return await FinishAsync(context, file, account, entry.Id, result.File.RelativePath, null, tally).ConfigureAwait(false); } /// The entry that receives the file. /// The file record to fill. /// The entry has an identity: the file may take the scheme name. /// The entry was deleted by Alberto «ricordando la scelta»: the file is not imported. /// The entry exists only for this file (created by this import for it). private sealed record Target(Entry? Entry, Media? Media, bool ByScheme, bool Deleted, bool OwnedByThisFile = false); /// /// The entry and file record that receive a source file: the one created by an interrupted attempt; an entry of the /// destination account with the same identifier or code (a file it lacks is added or filled, as when an import /// completes a series); or a new imported entry. When the position is already taken by another file (Alberto chose /// «Tienili entrambi»), the file gets an entry of its own without identifier, in importati/. /// private async Task ResolveTargetAsync(Account account, ImportFile file, FileHints hints, CancellationToken ct) { var kind = file.ProbableKind ?? EntryKind.Post; var position = hints.Position is >= 1 ? hints.Position.Value : 1; if (file.EntryId is { } previous && await env.Storage.Entries.GetWithMediaAsync(previous, ct).ConfigureAwait(false) is { } resumed) { var known = resumed.Entry.InstagramId is not null || resumed.Entry.Code is not null; var existing = resumed.Media.FirstOrDefault(m => m.Position == (known ? position : 1)); var usable = existing is not null && (!EntryStateRules.IsPresent(existing.State) || string.Equals(existing.Sha256, file.Sha256, StringComparison.Ordinal)); if (usable) { var owned = resumed.Entry.Provenance == Provenance.Imported && resumed.Media.Count == 1; return new Target(resumed.Entry, existing, known, false, owned); } } if (file.InstagramId is not null || file.Code is not null) { var same = file.InstagramId is { } id ? await env.Storage.Entries.FindAsync(account.Id, kind, id, ct).ConfigureAwait(false) : await env.Storage.Imports.FindEntryByCodeAsync(account.Id, kind, file.Code!, ct).ConfigureAwait(false); if (same is not null) { if (same.State == EntryState.Deleted) { return new Target(null, null, false, true); } var files = await env.Storage.Media.ListByEntryAsync(same.Id, ct).ConfigureAwait(false); var slot = files.FirstOrDefault(m => m.Position == position); if (slot is null) { var added = await env.Storage.Media.AddToEntryAsync(same.Id, [NewMedia(file, hints, position)], ct).ConfigureAwait(false); return new Target(same, added.First(m => m.Position == position), true, false); } if (!EntryStateRules.IsPresent(slot.State) && slot.State != MediaState.Deleted) { return new Target(same, slot, true, false); // a file still to download: the import fills it } } else { var created = await env.Storage.Entries.AddAsync(NewEntry(account, file, hints, kind, withIdentity: true), [NewMedia(file, hints, position)], ct).ConfigureAwait(false); if (created.Created) { return new Target(created.Stored.Entry, created.Stored.Media[0], true, false, true); } } } var plain = await env.Storage.Entries.AddAsync(NewEntry(account, file, hints, kind, withIdentity: false), [NewMedia(file, hints, 1) with { InstagramId = null }], ct).ConfigureAwait(false); return new Target(plain.Stored.Entry, plain.Stored.Media[0], false, false, true); } private Entry NewEntry(Account account, ImportFile file, FileHints hints, EntryKind kind, bool withIdentity) => new() { AccountId = account.Id, Kind = kind, InstagramId = withIdentity ? file.InstagramId : null, Code = withIdentity ? file.Code : null, PublishedAt = file.TakenAt ?? file.ModifiedAt ?? env.Clock.Now, Caption = withIdentity ? hints.Caption : null, AuthorUsername = withIdentity ? hints.AuthorUsername : null, AuthorInstagramId = withIdentity ? hints.AuthorInstagramId : null, Provenance = Provenance.Imported, State = EntryState.ToDownload, DiscoveredAt = env.Clock.Now, }; private static Media NewMedia(ImportFile file, FileHints hints, int position) => new() { Position = position, Kind = file.MediaKind ?? MediaKind.Photo, InstagramId = hints.MediaInstagramId, Width = file.Width, Height = file.Height, Duration = file.Duration, State = MediaState.ToDownload, }; /// /// «Tieni il più grande» with the source file larger: writes the new file next to the old one, verifies it, points /// the library record and the journal at it, then removes the old file (rule 12: only on Alberto's choice). /// private async Task ReplaceAsync(CopyContext context, ImportFile file, long mediaId, Tally tally, CancellationToken ct) { var media = await env.Storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false); if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null) { return await ImportAsync(context, file, tally, ct).ConfigureAwait(false); // the library file is gone meanwhile } if (string.Equals(media.Sha256, file.Sha256, StringComparison.Ordinal)) { return await FinishAsync(context, file, (await AccountOfEntryAsync(media.EntryId, ct).ConfigureAwait(false)).Account, media.EntryId, media.RelativePath, ImportText.NoteReplaced, tally).ConfigureAwait(false); } // Alberto chose «keep the larger»: the file in the library now is what counts, not the one seen when the copy // was planned. A smaller or equal file never takes the place of a larger one. if (!ImportPlanner.IsLarger(file.Width, file.Height, file.Bytes, media.Width, media.Height, media.Bytes)) { tally.Skipped++; return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = media.Id, LastError = ImportText.NoteLibraryLarger }).ConfigureAwait(false); } var (account, entry) = await AccountOfEntryAsync(media.EntryId, ct).ConfigureAwait(false); var folder = env.Layout.AccountFolder(account); var source = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); var oldRelative = media.RelativePath; var oldFull = LibraryLayout.FullPath(folder, oldRelative); var highlights = await env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false); var newRelative = oldRelative.StartsWith(ImportedFolder + "/", StringComparison.Ordinal) ? ImportedFolder + "/" + Path.GetFileName(source) : env.Layout.RelativePathFor( folder, env.Naming.For(entry.Kind), NamingValues.For(account.Username, entry, media.Position, Extension(file, source), highlights.FirstOrDefault()?.Title, file.Sha256), env.Clock.LocalZone); var directory = newRelative.Contains('/', StringComparison.Ordinal) ? newRelative[..newRelative.LastIndexOf('/')] : string.Empty; SavedFile saved; await using (var content = env.FileSystem.OpenRead(source)) { saved = (await new SafeFileWriter(env.Layout.MaxPathLength).SaveAsync( content, folder, directory, (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) ? ValueTask.FromResult(newRelative) : throw new ContentChangedException("Il file è cambiato dopo l'analisi."), new SafeWriteOptions { LastWriteTime = env.SetFileTimeToPublication ? entry.PublishedAt : null }, ct).ConfigureAwait(false))!; } // From here the replacement goes to the end: a half-done replacement is worse than a late one. The new file is // either registered or removed again: never left in the library with nothing pointing to it. var none = CancellationToken.None; string? onDisk = null; try { onDisk = await env.FileSystem.ComputeSha256Async(saved.FullPath, none).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Not readable: not verified. } if (!string.Equals(onDisk, file.Sha256, StringComparison.Ordinal)) { TryDelete(saved.FullPath); // the new file was never registered: nothing in the library points to it tally.Failed++; return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteNotVerified }).ConfigureAwait(false); } ulong? hash = null; int? width = file.Width, height = file.Height; var thumbnail = false; if (file.MediaKind == MediaKind.Photo) { try { hash = PerceptualHash.ComputeFromFile(saved.FullPath); await using var stream = File.OpenRead(saved.FullPath); if (ImageDecoding.ReadSize(stream) is { } size) { (width, height) = size; } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Verified a moment ago: recorded without perceptual hash, with the size measured by the analysis. } thumbnail = TryThumbnail(saved.Sha256, () => File.OpenRead(saved.FullPath)); } else if (await FrameAsync(source, none).ConfigureAwait(false) is { } frame) { using (frame) { thumbnail = TryThumbnail(saved.Sha256, () => frame); } } await env.Storage.Media.MarkStoredAsync( media.Id, new StoredFile(saved.RelativePath, saved.Bytes, saved.Sha256, hash, width, height, file.Duration ?? media.Duration, thumbnail), media.State, 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)) { // An entry without identifier or code is known in the journal by its file: the line of the old file is // closed («delete», not remembered), so a rebuild does not bring back an entry whose file is gone. try { await env.Journal.AppendDeletedAsync(folder, account, entry, [oldRelative], remember: false, none).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Without this line a rebuild reports the old file as missing and does not restore it: nothing is lost. } } if (hash is { } h) { env.HashIndex?.Add(media.Id, account.Id, h); } else { env.HashIndex?.Remove(media.Id); } var note = ImportText.NoteReplaced; if (!TryDelete(oldFull)) { note += " " + ImportText.NoteOldNotDeleted; } if (media.Sha256 is { } oldSha && env.Thumbnails is { } thumbnails) { var users = await env.Storage.Media.FindBySha256Async(oldSha, none).ConfigureAwait(false); if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State))) { try { thumbnails.Delete(oldSha); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // A thumbnail left behind costs a few kilobytes. } } } tally.Replaced++; return await FinishAsync(context, file with { MatchedMediaId = media.Id }, account, entry.Id, saved.RelativePath, note, tally).ConfigureAwait(false); } /// Records a stored file; with «Sposta» verifies the copy on disk and only then deletes the original. private async Task FinishAsync(CopyContext context, ImportFile file, Account account, long entryId, string relativePath, string? note, Tally tally) { tally.Copied++; var copied = file with { State = ImportFileState.Copied, EntryId = entryId, DestinationPath = relativePath, TargetAccountId = file.TargetAccountId ?? account.Id, LastError = note, }; if (context.Run.Mode != ImportMode.Move || context.Run.SourceReadOnly) { return await SaveAsync(copied).ConfigureAwait(false); } // Recorded first, so that a move interrupted here is finished (verification included) by the next run. copied = await SaveAsync(copied with { LastError = Join(note, ImportText.NoteMovePending) }).ConfigureAwait(false); return await MoveOriginalAsync(context, copied, LibraryLayout.FullPath(env.Layout.AccountFolder(account), relativePath), tally).ConfigureAwait(false); } private async Task FinishMoveAsync(CopyContext context, ImportFile file, Tally tally) { var stored = await env.Storage.Entries.GetWithMediaAsync(file.EntryId!.Value, CancellationToken.None).ConfigureAwait(false); var account = stored is null ? null : await env.Storage.Accounts.GetAsync(stored.Entry.AccountId, CancellationToken.None).ConfigureAwait(false); if (account is null || file.DestinationPath is null) { return file; } return await MoveOriginalAsync(context, file, LibraryLayout.FullPath(env.Layout.AccountFolder(account), file.DestinationPath), tally).ConfigureAwait(false); } /// The safety rule of «Sposta»: hash the copy as it is on disk now; delete the original only on a match. private async Task MoveOriginalAsync(CopyContext context, ImportFile file, string copyPath, Tally tally) { if (context.Run.SourceReadOnly) { return file; } var original = LibraryLayout.FullPath(context.Layout.Root, file.RelativePath); string? onDisk = null; try { onDisk = await env.FileSystem.ComputeSha256Async(copyPath, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // Unreadable copy: not verified. } if (!string.Equals(onDisk, file.Sha256, StringComparison.Ordinal)) { tally.Copied--; tally.Failed++; return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteNotVerified }).ConfigureAwait(false); } var note = WithoutMoveNotes(file.LastError); try { if (File.Exists(original)) { env.FileSystem.DeleteOriginal(original); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return await SaveAsync(file with { LastError = Join(note, ImportText.NoteOriginalKept) }).ConfigureAwait(false); } tally.Moved++; return await SaveAsync(file with { State = ImportFileState.Moved, LastError = note }).ConfigureAwait(false); } private async Task<(Account Account, Entry Entry)> AccountOfEntryAsync(long entryId, CancellationToken ct) { var entry = await env.Storage.Entries.GetAsync(entryId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("L'elemento della libreria non esiste più."); var account = await env.Storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException("L'account dell'elemento non esiste più."); return (account, entry); } private async Task FrameAsync(string videoPath, CancellationToken ct) { if (env.Frames is null || env.Thumbnails is null) { return null; } var frame = await env.Frames.ExtractImageAsync(videoPath, ct).ConfigureAwait(false); return frame is null ? null : new MemoryStream(frame, writable: false); } private bool TryThumbnail(string key, Func open) { if (env.Thumbnails is null) { return false; } try { using var stream = open(); return env.Thumbnails.Create(key, stream); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) { return false; } } /// Removes an entry this import created when it ended up without any file (identical content found). private async Task RemoveIfEmptyAsync(long entryId) { var stored = await env.Storage.Entries.GetWithMediaAsync(entryId, CancellationToken.None).ConfigureAwait(false); if (stored is { Entry.Provenance: Provenance.Imported } && stored.Media.All(m => !EntryStateRules.IsPresent(m.State))) { await env.Storage.Entries.RemoveAsync(entryId, CancellationToken.None).ConfigureAwait(false); } } /// The library extension: the detected format's (".jpeg" becomes ".jpg"), or the file's own for unknown ones. private static string Extension(ImportFile file, string source) { var detected = file.ContentType is { } type ? MediaSnifferExtension(type) : null; return detected ?? Path.GetExtension(source); } private static string? MediaSnifferExtension(string contentType) => contentType switch { "image/jpeg" => ".jpg", "image/png" => ".png", "image/gif" => ".gif", "image/webp" => ".webp", "image/heic" => ".heic", "image/heif" => ".heif", "image/avif" => ".avif", "image/bmp" => ".bmp", "video/mp4" => ".mp4", "video/quicktime" => ".mov", "video/webm" => ".webm", "video/x-matroska" => ".mkv", "video/3gpp" => ".3gp", "video/x-msvideo" => ".avi", _ => null, // TIFF family and rarer formats keep their own extension }; private Task SaveAsync(ImportFile file) => SaveCoreAsync(file); private async Task SaveCoreAsync(ImportFile file) { await env.Storage.Imports.UpdateFileAsync(file, CancellationToken.None).ConfigureAwait(false); return file; } private static string Join(string? first, string second) => string.IsNullOrEmpty(first) ? second : first + " " + second; private static string? WithoutMoveNotes(string? note) { if (note is null) { return null; } var cleaned = note.Replace(ImportText.NoteMovePending, string.Empty, StringComparison.Ordinal) .Replace(ImportText.NoteOriginalKept, string.Empty, StringComparison.Ordinal) .Trim(); return cleaned.Length == 0 ? null : cleaned; } private static bool TryDelete(string path) { try { if (File.Exists(path)) { File.Delete(path); } return true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; } } private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest); private sealed class Tally { public int Copied { get; set; } public int Moved { get; set; } public int Replaced { get; set; } public int Skipped { get; set; } public int LeftOut { get; set; } public int Failed { get; set; } } }