using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; namespace Febe.Core.Library; /// The two choices of the deletion dialog (spec §4.6). public enum DeletionMode { /// /// Default, «ricorda la scelta»: the entry stays in the database without files, in the state «eliminato», so it is /// never downloaded again. /// Remember, /// «Eliminalo e lascia che torni»: the record is removed too; a later check may download it again. AllowReturn, } /// What a deletion did. /// The entry. /// False when the entry did not exist (nothing done). /// Files removed from disk (relative paths). /// Files that were already missing. /// Files that could not be removed (e.g. open in another program), with the reason. public sealed record DeletionResult( long EntryId, bool Found, IReadOnlyList DeletedFiles, IReadOnlyList MissingFiles, IReadOnlyList FailedFiles) { public bool Complete => Found && FailedFiles.Count == 0; /// Converted files of the library (tappa E3) deleted with the originals; they are in too. public int ConvertedFiles { get; init; } } /// /// «Elimina dalla libreria» (spec §4.6). The confirmation is the interface's job; this class runs only on an explicit /// choice of Alberto (rule 12: the library never deletes or replaces files on its own). /// /// Order: the deletion line goes to _febe.jsonl first (so a rebuild honours it even if Febe stops halfway), /// then the database, then the files and their thumbnails. /// /// public sealed class LibraryDeletion( IFebeStorage storage, LibraryLayout layout, AccountJournal journal, IClock clock, ThumbnailStore? thumbnails = null, PerceptualHashIndex? hashIndex = null) { public async Task DeleteAsync(long entryId, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default) { var stored = await storage.Entries.GetWithMediaAsync(entryId, ct).ConfigureAwait(false); if (stored is null) { return new DeletionResult(entryId, false, [], [], []); } var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false) ?? throw new InvalidOperationException($"L'account dell'elemento {entryId} non esiste."); var folder = layout.AccountFolder(account); var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList(); ct.ThrowIfCancellationRequested(); // From here the deletion goes to the end: a half-done deletion is worse than a late one. var none = CancellationToken.None; await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none) .ConfigureAwait(false); // The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them. // Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them. var removed = mode == DeletionMode.Remember ? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false) : await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false); IReadOnlyList withFiles = removed.Where(HasFile).ToList(); foreach (var media in stored.Media) { hashIndex?.Remove(media.Id); } var deleted = new List(); var missing = new List(); var failed = new List(); foreach (var media in present) { var relative = media.RelativePath!; try { var path = LibraryLayout.FullPath(folder, relative); if (File.Exists(path)) { File.Delete(path); deleted.Add(relative); } else { missing.Add(relative); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { failed.Add($"{relative}: {ex.Message}"); } } var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false); if (thumbnails is not null) { foreach (var sha in stored.Media.Select(m => m.Sha256).OfType().Distinct(StringComparer.Ordinal)) { var users = await storage.Media.FindBySha256Async(sha, none).ConfigureAwait(false); if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State))) { try { thumbnails.Delete(sha); } catch (IOException) { // A thumbnail left behind costs a few kilobytes; it is regenerated or ignored. } } } } return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted }; } /// A conversion whose file is (or was last known to be) on disk. internal static bool HasFile(MediaConversion c) => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null; /// /// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no /// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and /// is listed among the failures with its reason. Returns how many were deleted. /// internal static async Task DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList conversions, List deleted, List missing, List failed, CancellationToken ct) { var count = 0; foreach (var conversion in conversions) { var relative = conversion.RelativePath!; try { var path = LibraryLayout.FullPath(folder, relative); if (!File.Exists(path)) { missing.Add(relative); continue; } if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false)) { continue; // another file of the library has that name now: it is not this conversion's to delete } if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase)) { failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è."); continue; } File.Delete(path); deleted.Add(relative); count++; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { failed.Add($"{relative}: {ex.Message}"); } } return count; } private static async Task IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct) { var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; var sha = conversion.Sha256!; foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) { if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison)) { return true; } } foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false)) { if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded && string.Equals(other.RelativePath, conversion.RelativePath, comparison) && await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner && (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId) { return true; } } return false; } private static string HashFile(string path) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan); return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream)); } /// Multiple selection: deletes each entry in turn. public async Task> DeleteManyAsync(IEnumerable entryIds, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(entryIds); var results = new List(); foreach (var id in entryIds.Distinct()) { ct.ThrowIfCancellationRequested(); results.Add(await DeleteAsync(id, mode, ct).ConfigureAwait(false)); } return results; } }