using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// What the comparison decided for one file.
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
///
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
///
/// - same SHA-256 as a library file present in any account → «Già in libreria» (the destination account first);
/// a file Alberto deleted «ricordando la scelta» counts too, so a deletion is not undone by an import;
/// - same SHA-256 as an earlier file of the source → identical copy in the source;
/// - same Instagram identifier or code with a different file → «Doppione probabile» (destination account first, then
/// the rest of the library);
/// - perceptual hash within of a library photo → «Doppione
/// probabile» (destination account first);
/// - the same two checks against earlier files of the source;
/// - otherwise «Nuovo».
///
/// Videos have no perceptual hash: for them only SHA-256 and identifiers count. One pair at most per file, with its
/// best match. Pairs inside the source always point to the first file of the group.
///
internal sealed class ImportComparer
{
private readonly IFebeStorage _storage;
private readonly PerceptualHashIndex _library;
private readonly Func _now;
private readonly Dictionary> _entriesById = new(StringComparer.Ordinal);
private readonly Dictionary> _entriesByCode = new(StringComparer.Ordinal);
private readonly Dictionary> _mediaById = new(StringComparer.Ordinal);
private readonly Dictionary> _mediaOfEntry = [];
private readonly Dictionary _entries = [];
// The source: first file by SHA-256, by identity, and the perceptual hashes of the files that are «Nuovo».
private readonly Dictionary _sourceSha = new(StringComparer.Ordinal);
private readonly Dictionary _sourceIdentity = new(StringComparer.Ordinal);
private readonly PerceptualHashIndex _sourceHashes = new();
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func now)
{
_storage = storage;
_library = library;
_now = now;
}
/// Loads the library identifiers and, when resuming, the files of the source already analysed.
/// The database.
/// The library's perceptual hashes (loaded from the database when null).
/// The import.
/// The recognizers' hints of a file already analysed (positions are not stored).
/// Current time.
/// Cancellation.
public static async Task CreateAsync(
IFebeStorage storage,
PerceptualHashIndex? sharedIndex,
long runId,
Func hintsOf,
Func now,
CancellationToken ct)
{
var library = sharedIndex;
if (library is null)
{
library = new PerceptualHashIndex();
library.Load(await storage.Media.LoadPerceptualHashesAsync(ct).ConfigureAwait(false));
}
var comparer = new ImportComparer(storage, library, now);
var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false);
foreach (var entry in identifiers.Entries)
{
comparer._entries[entry.EntryId] = entry;
if (entry.InstagramId is { } id)
{
Add(comparer._entriesById, id, entry);
}
if (entry.Code is { } code)
{
Add(comparer._entriesByCode, code, entry);
}
}
foreach (var media in identifiers.Media)
{
Add(comparer._mediaById, media.InstagramId, media);
}
long after = 0;
while (true)
{
var page = await storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, AfterId = after, Limit = 5000 }, ct).ConfigureAwait(false);
if (page.Count == 0)
{
break;
}
foreach (var file in page.Where(f => f.Outcome != ImportOutcome.Pending))
{
var hints = hintsOf(file);
comparer.Remember(file, file.Outcome, IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position));
}
after = page[^1].Id;
}
return comparer;
}
///
/// Compares a file (its must be set) with the library and with the earlier files of the
/// source, then remembers it for the files that follow.
///
public async Task CompareAsync(ImportFile file, FileHints hints, long? targetAccountId, CancellationToken ct)
{
var comparison = await ClassifyAsync(file, hints, targetAccountId, ct).ConfigureAwait(false);
Remember(file, comparison.Outcome, IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position));
return comparison;
}
private async Task ClassifyAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
{
if (file.MediaKind is null || file.Sha256 is null)
{
return new Comparison(ImportOutcome.Unrecognized, null, null, ImportText.NoteNotRecognized);
}
// 1. Same bytes anywhere in the library.
var same = await _storage.Media.FindBySha256Async(file.Sha256, ct).ConfigureAwait(false);
var present = same.Where(s => EntryStateRules.IsPresent(s.Media.State)).OrderBy(s => s.Entry.AccountId == target ? 0 : 1).ThenBy(s => s.Media.Id).FirstOrDefault();
if (present is not null)
{
return new Comparison(ImportOutcome.AlreadyInLibrary, present.Media.Id, null, null);
}
if (same.FirstOrDefault(s => s.Media.State == MediaState.Deleted || s.Entry.State == EntryState.Deleted) is { } deleted)
{
return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto);
}
// 2. Same bytes earlier in the source.
if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id)
{
return new Comparison(ImportOutcome.IdenticalInSource, null, null, $"Uguale a «{twin.Path}» della stessa sorgente.");
}
// 3. Same identifier, different file, in the library.
if (await MatchIdentityAsync(file, hints, target, ct).ConfigureAwait(false) is { } byIdentity)
{
return byIdentity;
}
// 4. Visually similar to a library photo.
if (file.PerceptualHash is { } hash
&& _library.FindSimilar(hash, PerceptualHash.DuplicateThreshold, target, limit: 1) is [var similar, ..])
{
return Pair(file, DuplicateReason.VisuallySimilar, similar.MediaId, null, similar.Distance);
}
// 5. Same identity or similar image earlier in the source.
foreach (var key in IdentityKeys(hints.InstagramId, hints.Code, hints.MediaInstagramId, hints.Position))
{
if (_sourceIdentity.TryGetValue(key, out var first) && first != file.Id)
{
return Pair(file, DuplicateReason.SameInstagramId, null, first, null);
}
}
if (file.PerceptualHash is { } h && _sourceHashes.FindSimilar(h, PerceptualHash.DuplicateThreshold, excludeMediaId: file.Id, limit: 1) is [var near, ..])
{
return Pair(file, DuplicateReason.VisuallySimilar, null, near.MediaId, near.Distance);
}
return new Comparison(ImportOutcome.New, null, null, null);
}
private async Task MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
{
var candidates = new List<(EntryIdentity Entry, long? MediaId)>();
foreach (var id in new[] { hints.MediaInstagramId, hints.InstagramId }.OfType().Distinct(StringComparer.Ordinal))
{
foreach (var media in _mediaById.GetValueOrDefault(id) ?? [])
{
if (EntryOf(media.EntryId) is { } owner)
{
candidates.Add((owner, media.MediaId));
}
}
}
if (hints.InstagramId is { } entryId)
{
candidates.AddRange((_entriesById.GetValueOrDefault(entryId) ?? []).Select(e => (e, (long?)null)));
}
if (hints.Code is { } code)
{
candidates.AddRange((_entriesByCode.GetValueOrDefault(code) ?? []).Select(e => (e, (long?)null)));
}
foreach (var (entry, mediaId) in candidates.OrderBy(c => c.Entry.AccountId == target ? 0 : 1).ThenBy(c => c.MediaId is null ? 1 : 0))
{
if (entry.State == EntryState.Deleted)
{
return new Comparison(ImportOutcome.AlreadyInLibrary, null, null, ImportText.NoteDeletedByAlberto);
}
if (!_mediaOfEntry.TryGetValue(entry.EntryId, out var files))
{
files = await _storage.Media.ListByEntryAsync(entry.EntryId, ct).ConfigureAwait(false);
_mediaOfEntry[entry.EntryId] = files;
}
var chosen = mediaId is { } m ? files.FirstOrDefault(f => f.Id == m)
: hints.Position is { } p ? files.FirstOrDefault(f => f.Position == p)
: files.Count == 1 ? files[0] : null;
if (chosen is not null && EntryStateRules.IsPresent(chosen.State) && !string.Equals(chosen.Sha256, file.Sha256, StringComparison.Ordinal))
{
return Pair(file, DuplicateReason.SameInstagramId, chosen.Id, null, null);
}
}
return null;
}
private EntryIdentity? EntryOf(long entryId) => _entries.GetValueOrDefault(entryId);
private Comparison Pair(ImportFile file, DuplicateReason reason, long? existingMediaId, long? existingFileId, int? distance) => new(
ImportOutcome.ProbableDuplicate,
existingMediaId,
new DuplicatePair
{
Origin = DuplicateOrigin.Import,
Reason = reason,
ExistingMediaId = existingMediaId,
ExistingImportFileId = existingFileId,
CandidateImportFileId = file.Id,
Distance = distance,
CreatedAt = _now(),
},
null);
private void Remember(ImportFile file, ImportOutcome outcome, IEnumerable identityKeys)
{
if (file.Sha256 is { } sha && outcome != ImportOutcome.Unrecognized)
{
_sourceSha.TryAdd(sha, (file.Id, file.RelativePath));
}
if (outcome != ImportOutcome.New)
{
return; // pairs inside the source point to the first file of a group
}
foreach (var key in identityKeys)
{
_sourceIdentity.TryAdd(key, file.Id);
}
if (file.PerceptualHash is { } hash)
{
_sourceHashes.Add(file.Id, 0, hash);
}
}
/// Keys that identify the same Instagram file: the item's own id, or the entry id/code with the position.
private static IEnumerable IdentityKeys(string? instagramId, string? code, string? mediaInstagramId, int? position)
{
if (mediaInstagramId is not null)
{
yield return "m:" + mediaInstagramId;
}
var n = (position ?? 1).ToString(System.Globalization.CultureInfo.InvariantCulture);
if (instagramId is not null)
{
yield return "i:" + instagramId + "#" + n;
}
if (code is not null)
{
yield return "c:" + code + "#" + n;
}
}
private static void Add(Dictionary> map, string key, T value)
{
if (!map.TryGetValue(key, out var list))
{
list = [];
map[key] = list;
}
list.Add(value);
}
}