using System.Text.Json; using System.Text.Json.Serialization; namespace Febe.Core.Collection.Readers; /// /// One concept of the vocabulary: the keys (or dotted paths, e.g. «image_versions2.candidates») under which a site /// puts a piece of data. Empty means «not known yet». /// public sealed record VocabularyKeys(IReadOnlyList Paths) { public static VocabularyKeys None { get; } = new([]); public bool IsSet => Paths.Count > 0; /// Each path split into its segments. internal IReadOnlyList Segments { get; } = [.. Paths.Select(p => p.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))]; /// Looks the concept up in : the first path that exists wins. public bool TryGet(JsonElement node, out JsonElement value) { if (node.ValueKind == JsonValueKind.Object) { foreach (var segments in Segments) { var current = node; var found = true; foreach (var segment in segments) { if (current.ValueKind != JsonValueKind.Object || !current.TryGetProperty(segment, out current)) { found = false; break; } } if (found && current.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) { value = current; return true; } } } value = default; return false; } /// True when the first segment of one of the paths is a property of . public bool Has(JsonElement node) => TryGet(node, out _); public override string ToString() => Paths.Count == 0 ? "(non impostato)" : string.Join(" | ", Paths); } /// Keys of a content node: a post, a story, an item of a highlight collection, or a file of a series. public sealed record ContentKeys { public VocabularyKeys Id { get; init; } = VocabularyKeys.None; public VocabularyKeys Code { get; init; } = VocabularyKeys.None; /// Publication time: a number (Unix seconds, or milliseconds when very large) or an ISO 8601 text. public VocabularyKeys TakenAt { get; init; } = VocabularyKeys.None; public VocabularyKeys Caption { get; init; } = VocabularyKeys.None; /// The image versions: an array of version objects (or a single one). public VocabularyKeys Images { get; init; } = VocabularyKeys.None; /// The video versions: an array of version objects (or a single one). public VocabularyKeys Videos { get; init; } = VocabularyKeys.None; /// The files of a series, in order: each one is a content node without its own date. public VocabularyKeys Children { get; init; } = VocabularyKeys.None; /// How many files the series declares: when more than the children received, the data is incomplete. public VocabularyKeys ChildCount { get; init; } = VocabularyKeys.None; /// The author: a profile node. public VocabularyKeys Owner { get; init; } = VocabularyKeys.None; /// True for content pinned on top of a profile (not «already known» for the stop rule). public VocabularyKeys Pinned { get; init; } = VocabularyKeys.None; /// When a story stops being available (a date, as for ). public VocabularyKeys ExpiresAt { get; init; } = VocabularyKeys.None; /// Video duration in seconds (on the node or on the video version). public VocabularyKeys Duration { get; init; } = VocabularyKeys.None; } /// Keys of one version of a file (one size of an image, one rendition of a video). public sealed record VersionKeys { public VocabularyKeys Url { get; init; } = VocabularyKeys.None; public VocabularyKeys Width { get; init; } = VocabularyKeys.None; public VocabularyKeys Height { get; init; } = VocabularyKeys.None; /// For videos: true when the rendition carries audio and video together (spec §6.5 point 1). public VocabularyKeys HasAudio { get; init; } = VocabularyKeys.None; } /// Keys of a profile node. public sealed record ProfileKeys { public VocabularyKeys Id { get; init; } = VocabularyKeys.None; public VocabularyKeys Username { get; init; } = VocabularyKeys.None; public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None; public VocabularyKeys IsPrivate { get; init; } = VocabularyKeys.None; /// True when Alberto follows the profile. public VocabularyKeys IsFollowed { get; init; } = VocabularyKeys.None; public VocabularyKeys PostCount { get; init; } = VocabularyKeys.None; /// Profile picture: a version object, an array of versions or an address. public VocabularyKeys Picture { get; init; } = VocabularyKeys.None; /// When the latest active story was published (stories bar, H2). public VocabularyKeys LatestStoryAt { get; init; } = VocabularyKeys.None; } /// Keys of a highlight collection node. public sealed record HighlightKeys { public VocabularyKeys Id { get; init; } = VocabularyKeys.None; public VocabularyKeys Title { get; init; } = VocabularyKeys.None; public VocabularyKeys Owner { get; init; } = VocabularyKeys.None; /// The contents of the collection, when the response carries them. public VocabularyKeys Items { get; init; } = VocabularyKeys.None; } /// Keys of the pagination information that comes with a page of data. public sealed record PageKeys { public VocabularyKeys HasMore { get; init; } = VocabularyKeys.None; /// Opaque resume point given by the site (the backfill stores it). public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None; } /// Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10). public enum VocabularyStatus { Confirmed, /// Hints only, to be confirmed with the M0 samples: recipes refuse to use it. Hypothesis, } /// /// The key vocabulary of one site (lettori.instagram.json, lettori.prova.json): which keys mean what. /// The reader finds data by shape, wherever it is in the response; the vocabulary only names the keys, so it can be /// updated without recompiling when the site changes (spec §6.4). /// public sealed record ReaderVocabulary { public required string Site { get; init; } public VocabularyStatus Status { get; init; } = VocabularyStatus.Hypothesis; public string? Note { get; init; } /// Where it was loaded from, for messages. public string? Source { get; init; } public ContentKeys Content { get; init; } = new(); public VersionKeys Version { get; init; } = new(); public ProfileKeys Profile { get; init; } = new(); public HighlightKeys Highlight { get; init; } = new(); public PageKeys Page { get; init; } = new(); /// The key under which the response describes the connected account (H10). public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None; /// /// Keys at least one of which, anywhere in a response, makes it «about contents or profiles». A response that has /// none of them is and ignored, instead of counting as an unknown shape: a real site /// sends many JSON answers that have nothing to do with contents (Instagram: promotions, logging, «seen» marks). /// Plain key names, not paths. Empty: every response counts (the test site, where any unknown answer is a format /// change). /// public IReadOnlyList Relevance { get; init; } = []; /// /// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is /// a hypothesis, recipes refuse to run on the site. /// public IReadOnlyList MissingConcepts { get { var missing = new List(); void Need(VocabularyKeys keys, string name) { if (!keys.IsSet) { missing.Add(name); } } Need(Content.Id, "content.id"); Need(Content.TakenAt, "content.takenAt"); Need(Content.Images, "content.images"); Need(Content.Videos, "content.videos"); // Without the author nothing tells whose a post is: the giro dei seguiti would save nothing and the profile // recipes would skip every post, silently. Need(Content.Owner, "content.owner"); Need(Version.Url, "version.url"); Need(Version.Width, "version.width"); Need(Version.Height, "version.height"); Need(Profile.Id, "profile.id"); Need(Profile.Username, "profile.username"); return missing; } } /// True when recipes may rely on this vocabulary. public bool IsUsable => Status == VocabularyStatus.Confirmed && MissingConcepts.Count == 0; /// Italian explanation of why the vocabulary cannot be used yet, or null. public string? UnusableReason => IsUsable ? null : Status == VocabularyStatus.Hypothesis ? $"Il vocabolario dei lettori per «{Site}» è ancora un'ipotesi, da confermare con i campioni di M0 (specifica §6.4, regola 10)." : $"Il vocabolario dei lettori per «{Site}» è incompleto: mancano {string.Join(", ", MissingConcepts)}."; /// The shipped Instagram vocabulary (embedded lettori.instagram.json): hints only. public static ReaderVocabulary LoadInstagram() => LoadEmbedded("lettori.instagram.json"); /// The vocabulary of the local test site (embedded lettori.prova.json). public static ReaderVocabulary LoadTestSite() => LoadEmbedded("lettori.prova.json"); /// Loads when it exists, otherwise the embedded file with the same name. public static ReaderVocabulary LoadOrEmbedded(string? path, string embeddedName) => !string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName); public static ReaderVocabulary Load(string path) => Parse(File.ReadAllText(path), path); public static ReaderVocabulary LoadEmbedded(string fileName) { var resource = $"Febe.Core.Config.{fileName}"; using var stream = typeof(ReaderVocabulary).Assembly.GetManifestResourceStream(resource) ?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}"); using var reader = new StreamReader(stream); return Parse(reader.ReadToEnd(), fileName); } public static ReaderVocabulary Parse(string json, string? source = null) { var name = source ?? "lettori"; VocabularyFile? file; try { file = JsonSerializer.Deserialize(json, VocabularyJsonContext.Default.VocabularyFile); } catch (JsonException ex) { throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}): {ex.Message.Split('.')[0]}.", ex); } if (file is null || string.IsNullOrWhiteSpace(file.Site)) { throw new InvalidDataException($"{name}: manca «site»."); } var status = file.Status?.Trim().ToLowerInvariant() switch { "confermato" or "confirmed" => VocabularyStatus.Confirmed, "ipotesi" or "hypothesis" or null or "" => VocabularyStatus.Hypothesis, _ => throw new InvalidDataException($"{name}: stato «{file.Status}» sconosciuto (ammessi: confermato, ipotesi)."), }; static VocabularyKeys K(List? paths) => paths is null ? VocabularyKeys.None : new VocabularyKeys([.. paths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim())]); var c = file.Content ?? new ContentDto(); var v = file.Version ?? new VersionDto(); var p = file.Profile ?? new ProfileDto(); var h = file.Highlight ?? new HighlightDto(); var g = file.Page ?? new PageDto(); return new ReaderVocabulary { Site = file.Site.Trim(), Status = status, Note = file.Note, Source = source, Content = new ContentKeys { Id = K(c.Id), Code = K(c.Code), TakenAt = K(c.TakenAt), Caption = K(c.Caption), Images = K(c.Images), Videos = K(c.Videos), Children = K(c.Children), ChildCount = K(c.ChildCount), Owner = K(c.Owner), Pinned = K(c.Pinned), ExpiresAt = K(c.ExpiresAt), Duration = K(c.Duration), }, Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) }, Profile = new ProfileKeys { Id = K(p.Id), Username = K(p.Username), DisplayName = K(p.DisplayName), IsPrivate = K(p.IsPrivate), IsFollowed = K(p.IsFollowed), PostCount = K(p.PostCount), Picture = K(p.Picture), LatestStoryAt = K(p.LatestStoryAt), }, Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) }, Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) }, Viewer = K(file.Viewer), Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)], }; } } internal sealed class VocabularyFile { public string? Site { get; set; } public string? Status { get; set; } public string? Note { get; set; } public ContentDto? Content { get; set; } public VersionDto? Version { get; set; } public ProfileDto? Profile { get; set; } public HighlightDto? Highlight { get; set; } public PageDto? Page { get; set; } public List? Viewer { get; set; } public RelevanceDto? Relevance { get; set; } } internal sealed class RelevanceDto { public string? Note { get; set; } public List? Keys { get; set; } } internal sealed class ContentDto { public string? Note { get; set; } public List? Id { get; set; } public List? Code { get; set; } public List? TakenAt { get; set; } public List? Caption { get; set; } public List? Images { get; set; } public List? Videos { get; set; } public List? Children { get; set; } public List? ChildCount { get; set; } public List? Owner { get; set; } public List? Pinned { get; set; } public List? ExpiresAt { get; set; } public List? Duration { get; set; } } internal sealed class VersionDto { public string? Note { get; set; } public List? Url { get; set; } public List? Width { get; set; } public List? Height { get; set; } public List? HasAudio { get; set; } } internal sealed class ProfileDto { public string? Note { get; set; } public List? Id { get; set; } public List? Username { get; set; } public List? DisplayName { get; set; } public List? IsPrivate { get; set; } public List? IsFollowed { get; set; } public List? PostCount { get; set; } public List? Picture { get; set; } public List? LatestStoryAt { get; set; } } internal sealed class HighlightDto { public string? Note { get; set; } public List? Id { get; set; } public List? Title { get; set; } public List? Owner { get; set; } public List? Items { get; set; } } internal sealed class PageDto { public string? Note { get; set; } public List? HasMore { get; set; } public List? Cursor { get; set; } } [JsonSourceGenerationOptions( PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)] [JsonSerializable(typeof(VocabularyFile))] internal sealed partial class VocabularyJsonContext : JsonSerializerContext;