Files
Febe/src/Febe.Core/Library/LibraryDeletion.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

232 lines
9.9 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Library;
/// <summary>The two choices of the deletion dialog (spec §4.6).</summary>
public enum DeletionMode
{
/// <summary>
/// Default, «ricorda la scelta»: the entry stays in the database without files, in the state «eliminato», so it is
/// never downloaded again.
/// </summary>
Remember,
/// <summary>«Eliminalo e lascia che torni»: the record is removed too; a later check may download it again.</summary>
AllowReturn,
}
/// <summary>What a deletion did.</summary>
/// <param name="EntryId">The entry.</param>
/// <param name="Found">False when the entry did not exist (nothing done).</param>
/// <param name="DeletedFiles">Files removed from disk (relative paths).</param>
/// <param name="MissingFiles">Files that were already missing.</param>
/// <param name="FailedFiles">Files that could not be removed (e.g. open in another program), with the reason.</param>
public sealed record DeletionResult(
long EntryId,
bool Found,
IReadOnlyList<string> DeletedFiles,
IReadOnlyList<string> MissingFiles,
IReadOnlyList<string> FailedFiles)
{
public bool Complete => Found && FailedFiles.Count == 0;
/// <summary>Converted files of the library (tappa E3) deleted with the originals; they are in <see cref="DeletedFiles"/> too.</summary>
public int ConvertedFiles { get; init; }
}
/// <summary>
/// «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).
/// <para>
/// Order: the deletion line goes to <c>_febe.jsonl</c> first (so a rebuild honours it even if Febe stops halfway),
/// then the database, then the files and their thumbnails.
/// </para>
/// </summary>
public sealed class LibraryDeletion(
IFebeStorage storage,
LibraryLayout layout,
AccountJournal journal,
IClock clock,
ThumbnailStore? thumbnails = null,
PerceptualHashIndex? hashIndex = null)
{
public async Task<DeletionResult> 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<MediaConversion> withFiles = removed.Where(HasFile).ToList();
foreach (var media in stored.Media)
{
hashIndex?.Remove(media.Id);
}
var deleted = new List<string>();
var missing = new List<string>();
var failed = new List<string>();
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<string>().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 };
}
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
internal static bool HasFile(MediaConversion c) =>
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
/// <summary>
/// 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.
/// </summary>
internal static async Task<int> DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList<MediaConversion> conversions,
List<string> deleted, List<string> missing, List<string> 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<bool> 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));
}
/// <summary>Multiple selection: deletes each entry in turn.</summary>
public async Task<IReadOnlyList<DeletionResult>> DeleteManyAsync(IEnumerable<long> entryIds, DeletionMode mode = DeletionMode.Remember, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
var results = new List<DeletionResult>();
foreach (var id in entryIds.Distinct())
{
ct.ThrowIfCancellationRequested();
results.Add(await DeleteAsync(id, mode, ct).ConfigureAwait(false));
}
return results;
}
}