using System.Globalization; using Chronos.Core.Project; using Chronos.Data.Copies; namespace Chronos.Data.Sync; /// /// The photo-by-photo comparison of two copies of one time-lapse (owner review 6, #73; design §4.1): which photos both hold, /// which only one holds, which one side deleted, which differ and which a Union kept in two versions. Detection, the Compare /// dialog, Integrate and Merge all read this one comparison. Pure: no I/O, thread-safe, O(n log n). /// public static class CopyComparer { /// The unhashed key prefix: "u:<size>:<capture millisecond>". internal const string UnhashedPrefix = "u:"; /// /// Compares (this PC, or the kept sequence of a merge) with (the server, /// or the other local sequence). Each photo lands in exactly one class; unusable frames (Missing or Corrupt) hold nothing /// and mark the photo the other side brings as a repair. /// public static CopyComparisonResult Compare(CopySideInput here, CopySideInput there) { ArgumentNullException.ThrowIfNull(here); ArgumentNullException.ThrowIfNull(there); // 1. Tombstones of both sides; unusable frames left out of their side's holdings. var tombstones = SyncTombstones.FromDtos(here.Removed ?? [], there.Removed); var mine = Holdings(here.Photos, tombstones); var theirs = Holdings(there.Photos, tombstones); var brokenHere = Broken(here.Photos, tombstones); var brokenThere = Broken(there.Photos, tombstones); var theirsByKey = theirs.ToDictionary(h => h.Key, StringComparer.Ordinal); var done = new HashSet(ReferenceEqualityComparer.Instance); var photos = new List(mine.Count + theirs.Count); // 3. Same and Converted: one canonical key on both sides. foreach (var h in mine) { if (!h.Hashed || !theirsByKey.TryGetValue(h.Key, out var t)) continue; var (hereFrame, thereFrame, same) = Pick(h, t); photos.Add(new ComparedPhoto(same ? PhotoClass.Same : PhotoClass.Converted, h.Key, hereFrame, thereFrame, h.Occurrences, t.Occurrences, hereFrame.Size)); done.Add(h); done.Add(t); } // 4. SameUnhashed: one side not hashed, the same size and capture millisecond (FramePhoto.Matches), one to one. var bySizeAndTime = new Dictionary<(long Size, long Ms), List>(); foreach (var t in theirs) { if (done.Contains(t) || t.Ms is not { } ms) continue; if (!bySizeAndTime.TryGetValue((t.First.Size, ms), out var list)) bySizeAndTime[(t.First.Size, ms)] = list = []; list.Add(t); } foreach (var h in mine) { if (done.Contains(h) || h.Ms is not { } ms || !bySizeAndTime.TryGetValue((h.First.Size, ms), out var candidates)) continue; var t = candidates.FirstOrDefault(c => !done.Contains(c) && (!h.Hashed || !c.Hashed)); if (t is null) continue; var key = h.Hashed ? h.Key : t.Hashed ? t.Key : h.Key; photos.Add(new ComparedPhoto(PhotoClass.SameUnhashed, key, h.First, t.First, h.Occurrences, t.Occurrences, h.First.Size)); done.Add(h); done.Add(t); } // 5. Deleted there / deleted here: held by one side, tombstoned by the other, which does not hold it. foreach (var h in mine.Where(h => !done.Contains(h) && h.Hashed && tombstones.DeletedRemotely(h.Key))) { photos.Add(new ComparedPhoto(PhotoClass.DeletedThere, h.Key, h.First, null, h.Occurrences, 0, h.First.Size)); done.Add(h); } foreach (var t in theirs.Where(t => !done.Contains(t) && t.Hashed && tombstones.DeletedLocally(t.Key))) { photos.Add(Brought(PhotoClass.DeletedHere, t, brokenHere)); done.Add(t); } // 6. Differs, strictly: one hashed photo per side at one sub-second instant, with the same file name. var hereAt = HashedAt(mine.Where(h => !done.Contains(h))); var thereAt = HashedAt(theirs.Where(t => !done.Contains(t))); foreach (var (ms, onHere) in hereAt) { if (onHere.Count != 1 || !SubSecond(ms) || !thereAt.TryGetValue(ms, out var onThere) || onThere.Count != 1) continue; var (h, t) = (onHere[0], onThere[0]); if (!string.Equals(h.First.FileName, t.First.FileName, StringComparison.OrdinalIgnoreCase)) continue; photos.Add(new ComparedPhoto(PhotoClass.Differs, h.Key, h.First, t.First, h.Occurrences, t.Occurrences, h.First.Size)); done.Add(h); done.Add(t); } // 7. Versions: a sub-second instant holding exactly the same two shared photos on both sides (a Union keep-both). MarkVersions(photos, mine, theirs); // 8. The rest is on one side only (unhashed leftovers are not assumed to match). foreach (var h in mine.Where(h => !done.Contains(h))) photos.Add(new ComparedPhoto(PhotoClass.OnlyHere, h.Key, h.First, null, h.Occurrences, 0, h.First.Size, RepairsThere: Repairs(h, brokenThere))); foreach (var t in theirs.Where(t => !done.Contains(t))) photos.Add(Brought(PhotoClass.OnlyThere, t, brokenHere)); photos.Sort(Order); return new CopyComparisonResult(photos, Totals(photos), Score(photos, mine.Count, theirs.Count)); } /// /// For linked pairs at each reconcile: only the deletion counts, cheaply. Deleted there: distinct photos this side holds /// that the other side tombstoned and does not hold; deleted here the other way round (as /// leaves them out). /// public static (int DeletedHere, int DeletedThere) Deletions(IReadOnlyCollection here, IReadOnlyCollection there, SyncTombstones tombstones) { ArgumentNullException.ThrowIfNull(here); ArgumentNullException.ThrowIfNull(there); ArgumentNullException.ThrowIfNull(tombstones); if (tombstones.IsEmpty) return (0, 0); var mine = here.Select(tombstones.Canonical).ToList(); var theirs = there.Select(tombstones.Canonical).ToList(); var minePhotos = new FramePhotos(mine.Select((p, i) => (i, p))); var theirPhotos = new FramePhotos(theirs.Select((p, i) => (i, p))); return (Count(theirs, tombstones.DeletedLocally, minePhotos), Count(mine, tombstones.DeletedRemotely, theirPhotos)); static int Count(List side, Func deleted, FramePhotos other) => side.Where(p => p.IsHashed && deleted(p.Sha256) && other.IndexOf(p) is null).Select(p => p.Sha256!.ToLowerInvariant()).Distinct(StringComparer.Ordinal).Count(); } /// The key of an unhashed photo by its size and capture time; a photo without a time is keyed by its frame (it matches nothing). internal static string UnhashedKey(long size, DateTime? capturedAt, Guid frameId) => capturedAt is { } at ? string.Create(CultureInfo.InvariantCulture, $"{UnhashedPrefix}{size}:{Millisecond(at)}") : string.Create(CultureInfo.InvariantCulture, $"{UnhashedPrefix}{size}:{frameId:N}"); internal static long Millisecond(DateTime time) => time.Ticks / TimeSpan.TicksPerMillisecond; /// A capture millisecond with a sub-second part: the camera records real sub-second times. private static bool SubSecond(long ms) => ms % 1000 != 0; /// One photo of one side: its key and the frames holding it, in index order (the first stands for it). private sealed class Holding(string key, bool hashed, List frames) { public string Key { get; } = key; public bool Hashed { get; } = hashed; public List Frames { get; } = frames; public CopyPhotoInput First => Frames[0]; public int Occurrences => Frames.Count; public long? Ms => First.CapturedAt is { } at ? Millisecond(at) : null; } /// 2. A side's usable frames grouped by photo key (copies of one photo inside a side count once), in index order. private static List Holdings(IReadOnlyList photos, SyncTombstones tombstones) { ArgumentNullException.ThrowIfNull(photos); var result = new List(); var byKey = new Dictionary(StringComparer.Ordinal); foreach (var frame in photos.Where(p => p is { Unusable: false }).OrderBy(p => p.Index).ThenBy(p => p.FrameId)) { var hashed = !string.IsNullOrEmpty(frame.Sha256); var key = Key(frame, tombstones); if (byKey.TryGetValue(key, out var holding)) { holding.Frames.Add(frame); continue; } byKey[key] = holding = new Holding(key, hashed, [frame]); result.Add(holding); } return result; } private static string Key(CopyPhotoInput frame, SyncTombstones tombstones) => string.IsNullOrEmpty(frame.Sha256) ? UnhashedKey(frame.Size, frame.CapturedAt, frame.FrameId) : tombstones.Canonical(frame.Sha256)!; /// The keys of a side's unusable frames: canonical SHA-256 and size and capture time, so a photo either way marks a repair. private static HashSet Broken(IReadOnlyList photos, SyncTombstones tombstones) { var broken = new HashSet(StringComparer.Ordinal); foreach (var frame in photos.Where(p => p is { Unusable: true })) { broken.Add(Key(frame, tombstones)); if (frame.CapturedAt is not null) broken.Add(UnhashedKey(frame.Size, frame.CapturedAt, frame.FrameId)); } return broken; } private static bool Repairs(Holding brought, HashSet broken) => broken.Count > 0 && (broken.Contains(brought.Key) || (brought.First.CapturedAt is not null && broken.Contains(UnhashedKey(brought.First.Size, brought.First.CapturedAt, brought.First.FrameId)))); /// A photo only the other side holds (or holds and this side deleted). private static ComparedPhoto Brought(PhotoClass c, Holding t, HashSet brokenHere) => new(c, t.Key, null, t.First, 0, t.Occurrences, t.First.Size, RepairsHere: Repairs(t, brokenHere)); /// The frames standing for a photo both hold: one with the same raw SHA-256 on each side when there is one (Same), else the first (Converted). private static (CopyPhotoInput Here, CopyPhotoInput There, bool Same) Pick(Holding h, Holding t) { foreach (var mine in h.Frames) { var theirs = t.Frames.FirstOrDefault(f => string.Equals(f.Sha256, mine.Sha256, StringComparison.OrdinalIgnoreCase)); if (theirs is not null) return (mine, theirs, true); } return (h.First, t.First, false); } /// The hashed photos left at each capture millisecond. private static SortedDictionary> HashedAt(IEnumerable holdings) { var at = new SortedDictionary>(); foreach (var h in holdings) { if (!h.Hashed || h.Ms is not { } ms) continue; if (!at.TryGetValue(ms, out var list)) at[ms] = list = []; list.Add(h); } return at; } private static void MarkVersions(List photos, List mine, List theirs) { var hereAt = KeysAt(mine); var thereAt = KeysAt(theirs); var shared = photos.Where(p => p.Class is PhotoClass.Same or PhotoClass.Converted).Select(p => p.Key).ToHashSet(StringComparer.Ordinal); for (var i = 0; i < photos.Count; i++) { var p = photos[i]; if (p.Class is not (PhotoClass.Same or PhotoClass.Converted) || p.Here!.CapturedAt is not { } hereTime || p.There!.CapturedAt is not { } thereTime) continue; var ms = Millisecond(hereTime); if (ms != Millisecond(thereTime) || !SubSecond(ms)) continue; if (!hereAt.TryGetValue(ms, out var onHere) || !thereAt.TryGetValue(ms, out var onThere)) continue; if (onHere.Count == 2 && onThere.Count == 2 && onHere.SetEquals(onThere) && onHere.All(shared.Contains)) photos[i] = p with { Class = PhotoClass.Versions }; } static Dictionary> KeysAt(List side) { var at = new Dictionary>(); foreach (var h in side) { if (h.Ms is not { } ms) continue; if (!at.TryGetValue(ms, out var keys)) at[ms] = keys = new HashSet(StringComparer.Ordinal); keys.Add(h.Key); } return at; } } /// Capture order, then key and class: the same for any order of the inputs. private static int Order(ComparedPhoto a, ComparedPhoto b) { var byTime = ((a.Here ?? a.There)!.CapturedAt ?? DateTime.MaxValue).CompareTo((b.Here ?? b.There)!.CapturedAt ?? DateTime.MaxValue); if (byTime != 0) return byTime; var byKey = string.CompareOrdinal(a.Key, b.Key); return byKey != 0 ? byKey : a.Class.CompareTo(b.Class); } private static PhotoClassTotal[] Totals(List photos) => [ .. Enum.GetValues().Select(c => { var of = photos.Where(p => p.Class == c).ToList(); return new PhotoClassTotal(c, of.Count, of.Sum(p => p.Here?.Size ?? 0), of.Sum(p => p.There?.Size ?? 0)); }), ]; /// 10. The counts and ratios of design §3.2 (Versions counted in Shared). private static CopyScore Score(List photos, int localPhotos, int otherPhotos) { int Of(PhotoClass c) => photos.Count(p => p.Class == c); var versions = Of(PhotoClass.Versions); var shared = Of(PhotoClass.Same) + Of(PhotoClass.Converted) + versions; var unhashed = Of(PhotoClass.SameUnhashed); var (deletedHere, deletedThere) = (Of(PhotoClass.DeletedHere), Of(PhotoClass.DeletedThere)); var removed = deletedHere + deletedThere; var smaller = Math.Min(localPhotos, otherPhotos); var union = localPhotos + otherPhotos - (shared + unhashed); var containment = smaller == 0 ? 0 : (int)Math.Min(1000, 1000L * (shared + unhashed + removed) / smaller); var overlap = union <= 0 ? 0 : (int)Math.Min(1000, 1000L * (shared + unhashed) / union); return new CopyScore(shared, unhashed, removed, Of(PhotoClass.OnlyHere), Of(PhotoClass.OnlyThere), Of(PhotoClass.Differs), deletedHere, deletedThere, versions, localPhotos, otherPhotos, containment, overlap, 0); } }