Importazione e dati: «Tieni il più grande» per gruppi, righe di _febe.jsonl mai perse, ricostruzione robusta (import-1, import-2, library-1, journal-1, rebuild-1, rebuild-2, rebuild-3, backup-1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
13 files changed
+1145
-95
No files matched your search
@@ -67,6 +67,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
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);
|
||||
@@ -99,6 +100,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
progress?.Report(new ImportProgress(runId, ImportPhase.Copying, done, total, bytesDone, bytesTotal, file.RelativePath, new Dictionary<ImportOutcome, int>(), 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(
|
||||
@@ -226,15 +228,22 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
catch (ContentChangedException)
|
||||
{
|
||||
tally.Failed++;
|
||||
return await SaveAsync(file with { State = ImportFileState.Failed, LastError = ImportText.NoteChanged }).ConfigureAwait(false);
|
||||
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(file with { State = ImportFileState.Failed, LastError = ImportAnalyzer.ErrorText(ex) }).ConfigureAwait(false);
|
||||
return await SaveAsync(await CurrentAsync(file).ConfigureAwait(false) with { State = ImportFileState.Failed, LastError = ImportAnalyzer.ErrorText(ex) }).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
private async Task<ImportFile> CurrentAsync(ImportFile file) =>
|
||||
await env.Storage.Imports.GetFileAsync(file.Id, CancellationToken.None).ConfigureAwait(false) ?? file;
|
||||
|
||||
/// <summary>Copies one file into its destination account as an imported entry (or into an entry it completes).</summary>
|
||||
private async Task<ImportFile> ImportAsync(CopyContext context, ImportFile file, Tally tally, CancellationToken ct)
|
||||
{
|
||||
@@ -267,7 +276,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
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.AppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
await context.Ingest.TryAppendJournalAsync(entry.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return await FinishAsync(context, file, account, entry.Id, already, null, tally).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -329,7 +338,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
await env.Storage.Highlights.AddItemAsync(collection.Id, entry.Id, none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await context.Ingest.AppendJournalAsync(entry.Id, CancellationToken.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);
|
||||
}
|
||||
|
||||
@@ -444,6 +453,14 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
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);
|
||||
@@ -473,9 +490,19 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
ct).ConfigureAwait(false))!;
|
||||
}
|
||||
|
||||
// From here the replacement goes to the end: a half-done replacement is worse than a late one.
|
||||
// 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;
|
||||
var onDisk = await env.FileSystem.ComputeSha256Async(saved.FullPath, none).ConfigureAwait(false);
|
||||
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
|
||||
@@ -488,14 +515,19 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
var thumbnail = false;
|
||||
if (file.MediaKind == MediaKind.Photo)
|
||||
{
|
||||
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
|
||||
await using (var stream = File.OpenRead(saved.FullPath))
|
||||
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));
|
||||
}
|
||||
@@ -513,7 +545,21 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
media.State,
|
||||
env.Clock.Now,
|
||||
none).ConfigureAwait(false);
|
||||
await context.Ingest.AppendJournalAsync(entry.Id, 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);
|
||||
@@ -538,7 +584,7 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
{
|
||||
thumbnails.Delete(oldSha);
|
||||
}
|
||||
catch (IOException)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A thumbnail left behind costs a few kilobytes.
|
||||
}
|
||||
|
||||
@@ -41,8 +41,10 @@ internal sealed record PlannedFile(ImportFile File, PlannedAction Action, string
|
||||
/// source;</item>
|
||||
/// <item>«Tieni quello in libreria»: the source file is skipped. «Tienili entrambi»: it is imported. «Tieni il più grande»:
|
||||
/// if the library file is larger the source file is skipped, otherwise it replaces the library file (more pixels win,
|
||||
/// then more bytes; a tie keeps the library file). Inside the source, among files joined by «tieni il più grande» only
|
||||
/// the largest is imported;</item>
|
||||
/// then more bytes; a tie keeps the library file). Several source files paired with the same library file form one
|
||||
/// group: only the largest of them can replace it, the others are skipped, so a replacement never removes the copy
|
||||
/// another replacement has just put in the library. Inside the source, among files joined by «tieni il più grande»
|
||||
/// only the largest is imported;</item>
|
||||
/// <item>files of a folder without account stay out.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
@@ -88,6 +90,7 @@ internal sealed class ImportPlanner
|
||||
}
|
||||
|
||||
var groups = new UnionFind();
|
||||
var rivals = new Dictionary<long, List<long>>(); // library file → source files that may replace it
|
||||
foreach (var pair in pairs.Where(p => p.Decision != DuplicateDecision.Pending && p.CandidateImportFileId is not null))
|
||||
{
|
||||
var candidate = pair.CandidateImportFileId!.Value;
|
||||
@@ -99,17 +102,13 @@ internal sealed class ImportPlanner
|
||||
planner.Lose(candidate, ImportText.NoteKeptExisting);
|
||||
break;
|
||||
case DuplicateDecision.KeepLarger:
|
||||
var library = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
|
||||
if (library is not null && files.TryGetValue(candidate, out var file)
|
||||
&& IsLarger(file.Width, file.Height, file.Bytes, library.Width, library.Height, library.Bytes))
|
||||
if (!rivals.TryGetValue(mediaId, out var list))
|
||||
{
|
||||
planner._replacements[candidate] = mediaId;
|
||||
}
|
||||
else
|
||||
{
|
||||
planner.Lose(candidate, ImportText.NoteLibraryLarger);
|
||||
list = [];
|
||||
rivals[mediaId] = list;
|
||||
}
|
||||
|
||||
list.Add(candidate);
|
||||
break;
|
||||
default:
|
||||
break; // KeepBoth: imported
|
||||
@@ -134,20 +133,54 @@ internal sealed class ImportPlanner
|
||||
foreach (var group in groups.Groups())
|
||||
{
|
||||
var members = group.Where(files.ContainsKey).Select(id => files[id]).ToList();
|
||||
var winner = members
|
||||
.OrderByDescending(f => (long)(f.Width ?? 0) * (f.Height ?? 0))
|
||||
.ThenByDescending(f => f.Bytes)
|
||||
.ThenBy(f => f.Id)
|
||||
.FirstOrDefault();
|
||||
var winner = Largest(members);
|
||||
foreach (var member in members.Where(m => m.Id != winner?.Id))
|
||||
{
|
||||
planner.Lose(member.Id, ImportText.NoteKeptOtherInSource);
|
||||
}
|
||||
}
|
||||
|
||||
// «Tieni il più grande» against a library file: the library file and every source file paired with it are one
|
||||
// group, and only the largest of the group stays. Deciding pair by pair would let a second, smaller source
|
||||
// file replace the copy the first one has just put in the library (and, with «Sposta», lose the larger one).
|
||||
foreach (var (mediaId, candidates) in rivals)
|
||||
{
|
||||
var library = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
|
||||
// A file already skipped never entered the library: it does not compete.
|
||||
var members = candidates.Distinct()
|
||||
.Where(id => files.TryGetValue(id, out var f) && f.State != ImportFileState.Skipped && !planner._decided.ContainsKey(id))
|
||||
.Select(id => files[id])
|
||||
.ToList();
|
||||
var winner = Largest(members);
|
||||
var replaces = winner is not null && library is not null
|
||||
&& (IsLarger(winner.Width, winner.Height, winner.Bytes, library.Width, library.Height, library.Bytes)
|
||||
// The library already holds this very file: a replacement interrupted before its state was saved,
|
||||
// which the copy finishes.
|
||||
|| string.Equals(winner.Sha256, library.Sha256, StringComparison.Ordinal));
|
||||
foreach (var member in members)
|
||||
{
|
||||
if (replaces && member.Id == winner!.Id)
|
||||
{
|
||||
planner._replacements[member.Id] = mediaId;
|
||||
}
|
||||
else
|
||||
{
|
||||
planner.Lose(member.Id, replaces ? ImportText.NoteLargerInSource : ImportText.NoteLibraryLarger);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return planner;
|
||||
}
|
||||
|
||||
/// <summary>The largest file: more pixels, then more bytes; on a tie the first one analysed.</summary>
|
||||
private static ImportFile? Largest(IEnumerable<ImportFile> files) =>
|
||||
files
|
||||
.OrderByDescending(f => (long)(f.Width ?? 0) * (f.Height ?? 0))
|
||||
.ThenByDescending(f => f.Bytes)
|
||||
.ThenBy(f => f.Id)
|
||||
.FirstOrDefault();
|
||||
|
||||
/// <summary>True when the folder of the file has (or will have) an account.</summary>
|
||||
public bool HasTarget(ImportFile file) => file.TargetAccountId is not null || _newAccounts.ContainsKey(file.Folder);
|
||||
|
||||
|
||||
@@ -136,6 +136,7 @@ public static class ImportText
|
||||
internal const string NoteKeptExisting = "Hai scelto di tenere il file già in libreria.";
|
||||
internal const string NoteLibraryLarger = "Hai scelto di tenere il più grande: è quello già in libreria.";
|
||||
internal const string NoteKeptOtherInSource = "Hai scelto di tenere l'altro file della sorgente.";
|
||||
internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria.";
|
||||
internal const string NoteNotRecognized = "Né foto né video: ignorato.";
|
||||
internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato.";
|
||||
internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto.";
|
||||
|
||||
@@ -25,6 +25,9 @@ public static class Mp4Reader
|
||||
|
||||
private const int MaxTopLevelBoxes = 10_000;
|
||||
|
||||
/// <summary>The most child boxes read inside one box (real files have a few dozen).</summary>
|
||||
private const int MaxChildBoxes = 10_000;
|
||||
|
||||
/// <summary>Reads a file (read-only). Null when no <c>moov</c> box is found.</summary>
|
||||
/// <param name="path">The file.</param>
|
||||
/// <param name="now">Current time: creation times after it (by more than a day) are ignored.</param>
|
||||
@@ -72,7 +75,8 @@ public static class Mp4Reader
|
||||
size = length - position; // to the end of the file
|
||||
}
|
||||
|
||||
if (size < headerSize || position + size > length + 8)
|
||||
// Compared without adding to the position: a 64-bit size close to 2^63 would overflow the sum and pass.
|
||||
if (size < headerSize || size > length - position + 8)
|
||||
{
|
||||
return null; // damaged
|
||||
}
|
||||
@@ -193,7 +197,7 @@ public static class Mp4Reader
|
||||
{
|
||||
var list = new List<(string, int, int)>();
|
||||
var offset = 0;
|
||||
while (offset + 8 <= data.Length)
|
||||
while (offset + 8 <= data.Length && list.Count < MaxChildBoxes)
|
||||
{
|
||||
long size = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(offset, 4));
|
||||
var type = System.Text.Encoding.Latin1.GetString(data.Slice(offset + 4, 4));
|
||||
@@ -208,7 +212,9 @@ public static class Mp4Reader
|
||||
size = data.Length - offset;
|
||||
}
|
||||
|
||||
if (size < headerSize || offset + size > data.Length)
|
||||
// «size > remaining» cannot overflow (unlike «offset + size»), and with «size >= headerSize» it keeps the
|
||||
// offset moving forward: a damaged 64-bit size can neither loop back nor run past the end.
|
||||
if (size < headerSize || size > data.Length - offset)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user