using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Titano.Core.Imaging;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Protocol;
namespace Titano.Data.Sync;
/// The fields both sides version together (BRIEF §14.5: settings and tags carry version counters).
public sealed record SyncPayload(string? Title, IReadOnlyList Tags, int Rating, string? Notes, string? SettingsJson)
{
public static SyncPayload Of(Sequence s) => new(s.Title, s.Tags, s.Rating, s.Notes, s.SettingsJson);
public static SyncPayload Of(SequenceDto s, string? settingsJson) => new(s.Title, s.Tags, s.Rating, s.Notes, settingsJson);
/// Title, tags, rating and notes match (blank equals absent, tags ignore case and order).
public bool SameMetadata(SyncPayload other) =>
SyncRules.Blank(Title) == SyncRules.Blank(other.Title)
&& SyncRules.Blank(Notes) == SyncRules.Blank(other.Notes)
&& Rating == other.Rating
&& Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(other.Tags);
public bool SameAs(SyncPayload other) => SameMetadata(other) && SyncRules.SameSettings(SettingsJson, other.SettingsJson);
///
/// The PATCH that makes the server's copy equal to this one; settings are sent in their normalised form, with the
/// server frames version their frame positions name when they were translated to the server's frames.
///
public UpdateSequenceRequest ToRequest(int? expectedSettingsVersion, int? expectedFramesVersion = null) =>
new(Title ?? string.Empty, Tags, Rating, Notes ?? string.Empty, SyncRules.NormalizeSettings(SettingsJson), expectedSettingsVersion,
ExpectedFramesVersion: expectedFramesVersion);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(SyncPayload))]
internal sealed partial class SyncPayloadJson : JsonSerializerContext;
///
/// One field that differs: its dotted path ("exposure.deflickerWindow.manual", or "sequence.tags" for the metadata)
/// and the value on each side (JSON for settings, plain text for metadata; null when absent).
///
public sealed record SettingsDifference(string Path, string? Mine, string? Theirs);
/// Decisions of the sync engine that need no I/O: the status of a row, settings equality and differences, merges.
public static class SyncRules
{
/// Path prefix of the title, tags, rating and notes in .
public const string MetadataPath = "sequence.";
///
/// Where a linked pair stands. Settings changed on both sides since they last agreed are a conflict (the engine
/// settles equal content before a row is shown); missing originals count before settings changed on one side only.
///
public static SyncStatus Status(Sequence? local, SyncLink? link)
{
if (link is null) return SyncStatus.LocalOnly;
if (local is null) return link.ProxiesCached > 0 ? SyncStatus.ProxiesOnly : SyncStatus.RemoteOnly;
var localChanged = link.BaseLocalSettings != local.SettingsVersion;
var remoteChanged = link.BaseRemoteSettings != link.RemoteSettingsVersion;
if (localChanged && remoteChanged) return SyncStatus.Conflict;
if (link.MissingRemote > 0 || localChanged) return SyncStatus.LocalAhead;
if (link.MissingLocal > 0 || remoteChanged) return SyncStatus.ServerAhead;
return SyncStatus.InSync;
}
/// The state stored on the local sequence for the Library; null for rows without a local copy or in transfer.
public static SyncState? ToSequenceState(SyncStatus status) => status switch
{
SyncStatus.InSync => SyncState.InSync,
SyncStatus.LocalOnly => SyncState.LocalOnly,
SyncStatus.LocalAhead => SyncState.LocalAhead,
SyncStatus.ServerAhead => SyncState.ServerAhead,
SyncStatus.Conflict => SyncState.Conflict,
_ => null,
};
///
/// Settings JSON in the form both sides store: a project read and written again (missing members take their
/// defaults, so "no settings" equals the default project). Text that is not a project of this build is kept as is.
///
public static string NormalizeSettings(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings().ToJson();
try
{
return ProjectSettings.FromJson(json).ToJson();
}
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
return json.Trim();
}
}
public static bool SameSettings(string? a, string? b) => Differences(a, b, 1).Count == 0;
/// Up to settings that differ, in document order.
public static IReadOnlyList Differences(string? mine, string? theirs, int max = 3)
{
var differences = new List();
Collect(Parse(NormalizeSettings(mine)), Parse(NormalizeSettings(theirs)), string.Empty, differences, max);
return differences;
}
///
/// Up to differences between two payloads: title, tags, rating and notes first (paths
/// sequence.title, sequence.tags, …, tags as one comma-separated value), then the settings.
///
public static IReadOnlyList Differences(SyncPayload mine, SyncPayload theirs, int max = 3)
{
var differences = new List();
if (Blank(mine.Title) != Blank(theirs.Title)) differences.Add(new(MetadataPath + "title", Blank(mine.Title), Blank(theirs.Title)));
if (!mine.Tags.ToHashSet(StringComparer.OrdinalIgnoreCase).SetEquals(theirs.Tags))
differences.Add(new(MetadataPath + "tags", string.Join(", ", mine.Tags), string.Join(", ", theirs.Tags)));
if (mine.Rating != theirs.Rating)
differences.Add(new(MetadataPath + "rating", mine.Rating.ToString(CultureInfo.InvariantCulture), theirs.Rating.ToString(CultureInfo.InvariantCulture)));
if (Blank(mine.Notes) != Blank(theirs.Notes)) differences.Add(new(MetadataPath + "notes", Blank(mine.Notes), Blank(theirs.Notes)));
if (differences.Count < max) differences.AddRange(Differences(mine.SettingsJson, theirs.SettingsJson, max - differences.Count));
return differences.Count > max ? differences.GetRange(0, max) : differences;
}
///
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict), from their SHA-256 alone (an
/// empty or null one: not hashed yet). See .
///
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection localHashes, IReadOnlyCollection remoteHashes) =>
CompareOriginals([.. localHashes.Select(h => new FramePhoto(h, 0, null))], [.. remoteHashes.Select(h => new FramePhoto(h, 0, null))]);
///
/// Originals missing on each side by content (BRIEF §14.5: originals never conflict): the same SHA-256 where both
/// sides hashed them, else the same size and capture time (; a folder adopted on
/// either side and not verified yet). Local frames not hashed yet that nothing matched are assumed to match server
/// frames that nothing matched.
///
public static (int MissingRemote, int MissingLocal) CompareOriginals(IReadOnlyCollection local, IReadOnlyCollection remote)
{
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(remote);
var remoteHashes = remote.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
var localHashes = local.Where(p => p.IsHashed).Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
// What no hash matched: each content once, each frame not hashed on its own.
var localLeft = Unmatched(local, remoteHashes);
var remoteLeft = Unmatched(remote, localHashes);
var byTime = new Dictionary<(long Size, long Time), List>();
for (var i = 0; i < remoteLeft.Count; i++)
{
if (remoteLeft[i].CapturedAt is not { } time) continue;
var key = (remoteLeft[i].Size, time.Ticks / TimeSpan.TicksPerMillisecond);
if (!byTime.TryGetValue(key, out var list)) byTime[key] = list = [];
list.Add(i);
}
var paired = new bool[remoteLeft.Count];
int localHashedLeft = 0, localUnhashedLeft = 0, remoteMatched = 0;
foreach (var photo in localLeft)
{
var match = -1;
if (photo.CapturedAt is { } time && byTime.TryGetValue((photo.Size, time.Ticks / TimeSpan.TicksPerMillisecond), out var candidates))
{
var at = candidates.FindIndex(i => !paired[i] && remoteLeft[i].Matches(photo));
if (at >= 0) match = candidates[at];
}
if (match >= 0)
{
paired[match] = true;
remoteMatched++;
}
else if (photo.IsHashed)
{
localHashedLeft++;
}
else
{
localUnhashedLeft++;
}
}
var remoteUnmatched = remoteLeft.Count - remoteMatched;
return (localHashedLeft + Math.Max(0, localUnhashedLeft - remoteUnmatched), Math.Max(0, remoteUnmatched - localUnhashedLeft));
static List Unmatched(IEnumerable side, HashSet other) =>
[
.. side.Where(p => p.IsHashed && !other.Contains(p.Sha256!.ToLowerInvariant())).DistinctBy(p => p.Sha256!.ToLowerInvariant()),
.. side.Where(p => !p.IsHashed),
];
}
///
/// Frames whose proxy the server asks for (it cannot decode their originals, BRIEF §2.3) that this PC holds and its
/// reads: an upload makes and sends them. A local original not hashed yet (a folder adopted
/// and not verified) stands for a wanted frame of its size that no hash matched (by size, not name: the server names
/// its copy by its own template); the upload hashes it before making the proxy. A wanted frame the server has not
/// hashed is the local original of its size and capture time (, by server frame id), as
/// finds it for the upload.
///
public static int ProxiesToSend(SequenceManifest manifest, IReadOnlyCollection local, ImageDecoder decoder,
IReadOnlyDictionary? captured = null)
{
ArgumentNullException.ThrowIfNull(manifest);
IReadOnlyList frames = [.. local];
var photos = Photos(frames);
var count = 0;
// The originals of frames the server has not hashed first: they are no longer free to stand for others by size.
var taken = new HashSet();
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length == 0))
{
if (ProxyOriginal(frame, captured?.GetValueOrDefault(frame.Id), frames, photos) is { } original && taken.Add(original.Id) && Readable(original)) count++;
}
var hashed = frames.Where(f => !string.IsNullOrEmpty(f.Sha256)).ToLookup(f => f.Sha256!.ToLowerInvariant(), StringComparer.Ordinal);
var unhashed = frames.Where(f => string.IsNullOrEmpty(f.Sha256) && Readable(f) && !taken.Contains(f.Id)).GroupBy(f => f.Size)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var frame in manifest.Frames.Where(f => f.WantsProxy && f.Sha256.Length > 0))
{
var sha = frame.Sha256.ToLowerInvariant();
if (hashed.Contains(sha))
{
if (hashed[sha].Any(Readable)) count++;
}
else if (unhashed.TryGetValue(frame.Size, out var left) && left > 0)
{
unhashed[frame.Size] = left - 1;
count++;
}
}
return count;
bool Readable(Frame frame) => !ArchiveImages.NeedsProxy(decoder, frame.Format);
}
///
/// The local original of a wanted frame the server has not hashed yet (adopted there, not verified): the one of its
/// size and capture time (, from the server's frame row); null when none is, or the time
/// is unknown. are of .
///
public static Frame? ProxyOriginal(ManifestFrame wanted, DateTime? capturedAt, IReadOnlyList local, FramePhotos photos)
{
ArgumentNullException.ThrowIfNull(wanted);
ArgumentNullException.ThrowIfNull(local);
ArgumentNullException.ThrowIfNull(photos);
return capturedAt is not null && photos.IndexOf(new FramePhoto(null, wanted.Size, capturedAt)) is { } at ? local[at] : null;
}
/// The photos of 's frames, by their place in the list.
public static FramePhotos Photos(IReadOnlyList local) => new(local.Select((f, i) => (i, new FramePhoto(f.Sha256, f.Size, f.CapturedAt))));
///
/// Whether holds originals a server cannot decode (it asks for their proxies, BRIEF §2.3,
/// §4.2: managed decoders only) that this PC's reads, so it can make those proxies.
///
public static bool MakesProxiesFor(IEnumerable local, ImageDecoder decoder) =>
local.Select(f => f.Format).Distinct().Any(format => ArchiveImages.ServerNeedsProxy(format) && !ArchiveImages.NeedsProxy(decoder, format));
internal static string Blank(string? text) => text?.Trim() ?? string.Empty;
private static JsonNode? Parse(string json)
{
try
{
return JsonNode.Parse(json);
}
catch (JsonException)
{
return JsonValue.Create(json);
}
}
private static void Collect(JsonNode? a, JsonNode? b, string path, List differences, int max)
{
if (differences.Count >= max) return;
if (a is JsonObject left && b is JsonObject right)
{
foreach (var name in left.Select(p => p.Key).Concat(right.Select(p => p.Key)).Distinct(StringComparer.Ordinal))
{
left.TryGetPropertyValue(name, out var x);
right.TryGetPropertyValue(name, out var y);
Collect(x, y, path.Length == 0 ? name : path + "." + name, differences, max);
if (differences.Count >= max) return;
}
return;
}
if (!JsonNode.DeepEquals(a, b)) differences.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, a?.ToJsonString(), b?.ToJsonString()));
}
}