Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

@@ -0,0 +1,165 @@
using System.Text;
using System.Text.Json;
namespace Febe.Core.Collection.Readers;
/// <summary>
/// Describes the key structure of a JSON response without any value (spec §6.4: «formato non riconosciuto» events
/// carry only the structure). Keys that look like identifiers become «#», so not even they leak.
/// </summary>
/// <remarks>Example: <c>{dati:{elenco:[{a,b,c:{d}}]},stato}</c>.</remarks>
public static class KeyStructure
{
public const int DefaultMaxLength = 600;
private const int MaxDepth = 6;
private const int MaxKeysPerObject = 24;
public static string Describe(JsonElement root, int maxLength = DefaultMaxLength)
{
var sb = new StringBuilder();
Append(sb, root, 0);
if (sb.Length > maxLength)
{
sb.Length = Math.Max(0, maxLength - 1);
sb.Append('…');
}
return sb.ToString();
}
/// <summary>
/// True for keys that look like identifiers rather than names: long digit runs, long hexadecimal or mixed
/// letter-digit tokens. Shared with the sample sanitizer (spec §14.5).
/// </summary>
public static bool LooksLikeIdentifier(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
var digits = 0;
var letters = 0;
var others = 0;
foreach (var c in key)
{
if (char.IsAsciiDigit(c))
{
digits++;
}
else if (char.IsAsciiLetter(c))
{
letters++;
}
else if (c is not ('_' or '-'))
{
others++;
}
}
if (digits >= 5 && letters == 0 && others == 0)
{
return true; // 17841400000, 1234567
}
if (others == 0 && key.Length >= 16 && digits >= 3 && letters >= 3)
{
return true; // tokens and hashes
}
return others > 0 && digits >= 5; // e.g. «id:123456»
}
private static void Append(StringBuilder sb, JsonElement element, int depth)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
if (depth >= MaxDepth)
{
sb.Append("{…}");
return;
}
sb.Append('{');
var count = 0;
var identifierKeys = 0;
JsonElement? identifierSample = null;
foreach (var property in element.EnumerateObject())
{
if (LooksLikeIdentifier(property.Name))
{
identifierKeys++;
identifierSample ??= property.Value;
continue;
}
if (count == MaxKeysPerObject)
{
sb.Append(",…");
count++;
continue;
}
if (count > MaxKeysPerObject)
{
continue;
}
if (count > 0)
{
sb.Append(',');
}
sb.Append(property.Name);
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
{
sb.Append(':');
Append(sb, property.Value, depth + 1);
}
count++;
}
if (identifierKeys > 0)
{
if (count > 0)
{
sb.Append(',');
}
sb.Append('#');
if (identifierSample is { ValueKind: JsonValueKind.Object or JsonValueKind.Array } sample)
{
sb.Append(':');
Append(sb, sample, depth + 1);
}
}
sb.Append('}');
return;
case JsonValueKind.Array:
if (depth >= MaxDepth)
{
sb.Append("[…]");
return;
}
sb.Append('[');
foreach (var item in element.EnumerateArray())
{
if (item.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
{
Append(sb, item, depth + 1);
}
break; // the first element stands for the others
}
sb.Append(']');
return;
default:
return;
}
}
}
@@ -0,0 +1,99 @@
using Febe.Core.Domain;
namespace Febe.Core.Collection.Readers;
/// <summary>Turns what the reader recognized into domain records (spec §6.4: Entry, Media, Account, Highlight).</summary>
public static class ReadMapping
{
/// <summary>The entry of a content item for an account.</summary>
/// <param name="item">The content.</param>
/// <param name="accountId">Local key of the account the entry belongs to (for tagged posts: the tagged account).</param>
/// <param name="kind">Post, story, highlight item or tagged post.</param>
/// <param name="now">Discovery time.</param>
public static Entry ToEntry(ContentItem item, long accountId, EntryKind kind, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(item);
var foreignAuthor = kind == EntryKind.Tagged;
return new Entry
{
AccountId = accountId,
Kind = kind,
InstagramId = item.Id,
Code = item.Code,
PublishedAt = item.TakenAt,
Caption = item.Caption,
AuthorUsername = foreignAuthor ? item.Owner?.Username : null,
AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null,
DiscoveredAt = now,
ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null,
};
}
/// <summary>The files of a content item, positions from 1, with the addresses of the chosen versions.</summary>
public static IReadOnlyList<Media> ToMedia(ContentItem item, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(item);
return [.. item.Files.Select((file, index) => ToMedia(file, index + 1, now))];
}
public static Media ToMedia(ContentFile file, int position, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(file);
return new Media
{
Position = position,
Kind = file.Kind,
InstagramId = file.InstagramId,
Width = file.Best.Width,
Height = file.Best.Height,
Duration = file.Duration,
SourceUrl = file.Best.Url,
CoverUrl = file.Cover?.Url,
SourceSeenAt = now,
};
}
/// <summary>A profile picture as an entry: its identity is the address path of the picture (it changes with the picture).</summary>
public static (Entry Entry, Media Media)? ToProfilePicture(ProfileInfo profile, long accountId, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(profile);
if (profile.Picture is not { } picture || !Uri.TryCreate(picture.Url, UriKind.Absolute, out var uri))
{
return null;
}
var identity = "ritratto-" + Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(uri.AbsolutePath)))[..16];
var entry = new Entry
{
AccountId = accountId,
Kind = EntryKind.ProfilePicture,
InstagramId = identity,
PublishedAt = now,
DiscoveredAt = now,
};
var media = new Media
{
Position = 1,
Kind = MediaKind.Photo,
Width = picture.Width,
Height = picture.Height,
SourceUrl = picture.Url,
SourceSeenAt = now,
};
return (entry, media);
}
public static Highlight ToHighlight(HighlightInfo info, long accountId, int position, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(info);
return new Highlight
{
AccountId = accountId,
InstagramId = info.Id,
Title = string.IsNullOrWhiteSpace(info.Title) ? "Senza titolo" : info.Title.Trim(),
Position = position,
DiscoveredAt = now,
LastCheckedAt = now,
};
}
}
@@ -0,0 +1,143 @@
using System.Text;
using Febe.Core.Domain;
namespace Febe.Core.Collection.Readers;
/// <summary>One version of a file as the page received it: an address with its size.</summary>
/// <param name="Url">Signed address: never logged (spec §13.2).</param>
/// <param name="Width">Width in pixels, when given.</param>
/// <param name="Height">Height in pixels, when given.</param>
/// <param name="HasAudio">For videos: whether the rendition carries audio; null when the response does not say.</param>
public sealed record FileVersion(string Url, int? Width, int? Height, bool? HasAudio)
{
public long Area => (long)(Width ?? 0) * (Height ?? 0);
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Width = {Width}, Height = {Height}, HasAudio = {HasAudio}");
return true;
}
}
/// <summary>One file of a content item, with the version chosen for download (spec §6.5 point 1).</summary>
/// <param name="Kind">Photo or video.</param>
/// <param name="InstagramId">Identifier of this file of a series, when the site gives one.</param>
/// <param name="Best">Largest image, or best video version complete with audio.</param>
/// <param name="Cover">For videos: the largest cover image.</param>
/// <param name="Duration">Video duration, when given.</param>
public sealed record ContentFile(MediaKind Kind, string? InstagramId, FileVersion Best, FileVersion? Cover, TimeSpan? Duration);
/// <summary>A profile as it appears in a response (author of content, profile page, list of followed profiles).</summary>
public sealed record ProfileInfo
{
public required string Id { get; init; }
public required string Username { get; init; }
public string? DisplayName { get; init; }
public bool? IsPrivate { get; init; }
public bool? IsFollowed { get; init; }
public int? PostCount { get; init; }
/// <summary>Largest version of the profile picture.</summary>
public FileVersion? Picture { get; init; }
/// <summary>Publication time of the latest active story (stories bar).</summary>
public DateTimeOffset? LatestStoryAt { get; init; }
/// <summary>True when the response presents this profile as the connected account (H10).</summary>
public bool IsViewer { get; init; }
}
/// <summary>A content node: a post, a story or an item of a highlight collection.</summary>
public sealed record ContentItem
{
public required string Id { get; init; }
public string? Code { get; init; }
public required DateTimeOffset TakenAt { get; init; }
/// <summary>Caption: never logged.</summary>
public string? Caption { get; init; }
public ProfileInfo? Owner { get; init; }
public bool Pinned { get; init; }
public DateTimeOffset? ExpiresAt { get; init; }
/// <summary>The files in order (one for a single photo or video, several for a series).</summary>
public required IReadOnlyList<ContentFile> Files { get; init; }
/// <summary>False when the series declares more files than the response carries: Post singolo completes it.</summary>
public bool IsComplete { get; init; } = true;
/// <summary>Identifier of the highlight collection the item was found in, if any.</summary>
public string? HighlightId { get; init; }
/// <summary>Order of appearance in the response, from 0.</summary>
public int Order { get; init; }
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}");
return true;
}
}
/// <summary>A highlight collection, with its contents when the response carries them.</summary>
public sealed record HighlightInfo
{
public required string Id { get; init; }
public required string Title { get; init; }
public ProfileInfo? Owner { get; init; }
public FileVersion? Cover { get; init; }
public IReadOnlyList<ContentItem> Items { get; init; } = [];
public int Order { get; init; }
}
/// <summary>Pagination information of a page of data.</summary>
public sealed record PageInfo(bool? HasMore, string? Cursor);
/// <summary>What the reader made of a response.</summary>
public enum ReadShape
{
/// <summary>At least one content, profile or highlight was recognized.</summary>
Recognized,
/// <summary>Nothing to read (empty lists, a bare status): not an error, but counts as an empty page.</summary>
Empty,
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
Unrecognized,
}
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
public sealed record ReadResult
{
public static ReadResult EmptyResult { get; } = new() { Shape = ReadShape.Empty };
public required ReadShape Shape { get; init; }
public IReadOnlyList<ContentItem> Contents { get; init; } = [];
public IReadOnlyList<ProfileInfo> Profiles { get; init; } = [];
public IReadOnlyList<HighlightInfo> Highlights { get; init; } = [];
public PageInfo? Page { get; init; }
public ProfileInfo? Viewer { get; init; }
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
public string? KeyStructure { get; init; }
}
@@ -0,0 +1,434 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Febe.Core.Collection.Readers;
/// <summary>
/// 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».
/// </summary>
public sealed record VocabularyKeys(IReadOnlyList<string> Paths)
{
public static VocabularyKeys None { get; } = new([]);
public bool IsSet => Paths.Count > 0;
/// <summary>Each path split into its segments.</summary>
internal IReadOnlyList<string[]> Segments { get; } = [.. Paths.Select(p => p.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))];
/// <summary>Looks the concept up in <paramref name="node"/>: the first path that exists wins.</summary>
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;
}
/// <summary>True when the first segment of one of the paths is a property of <paramref name="node"/>.</summary>
public bool Has(JsonElement node) => TryGet(node, out _);
public override string ToString() => Paths.Count == 0 ? "(non impostato)" : string.Join(" | ", Paths);
}
/// <summary>Keys of a content node: a post, a story, an item of a highlight collection, or a file of a series.</summary>
public sealed record ContentKeys
{
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
public VocabularyKeys Code { get; init; } = VocabularyKeys.None;
/// <summary>Publication time: a number (Unix seconds, or milliseconds when very large) or an ISO 8601 text.</summary>
public VocabularyKeys TakenAt { get; init; } = VocabularyKeys.None;
public VocabularyKeys Caption { get; init; } = VocabularyKeys.None;
/// <summary>The image versions: an array of version objects (or a single one).</summary>
public VocabularyKeys Images { get; init; } = VocabularyKeys.None;
/// <summary>The video versions: an array of version objects (or a single one).</summary>
public VocabularyKeys Videos { get; init; } = VocabularyKeys.None;
/// <summary>The files of a series, in order: each one is a content node without its own date.</summary>
public VocabularyKeys Children { get; init; } = VocabularyKeys.None;
/// <summary>How many files the series declares: when more than the children received, the data is incomplete.</summary>
public VocabularyKeys ChildCount { get; init; } = VocabularyKeys.None;
/// <summary>The author: a profile node.</summary>
public VocabularyKeys Owner { get; init; } = VocabularyKeys.None;
/// <summary>True for content pinned on top of a profile (not «already known» for the stop rule).</summary>
public VocabularyKeys Pinned { get; init; } = VocabularyKeys.None;
/// <summary>When a story stops being available (a date, as for <see cref="TakenAt"/>).</summary>
public VocabularyKeys ExpiresAt { get; init; } = VocabularyKeys.None;
/// <summary>Video duration in seconds (on the node or on the video version).</summary>
public VocabularyKeys Duration { get; init; } = VocabularyKeys.None;
}
/// <summary>Keys of one version of a file (one size of an image, one rendition of a video).</summary>
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;
/// <summary>For videos: true when the rendition carries audio and video together (spec §6.5 point 1).</summary>
public VocabularyKeys HasAudio { get; init; } = VocabularyKeys.None;
}
/// <summary>Keys of a profile node.</summary>
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;
/// <summary>True when Alberto follows the profile.</summary>
public VocabularyKeys IsFollowed { get; init; } = VocabularyKeys.None;
public VocabularyKeys PostCount { get; init; } = VocabularyKeys.None;
/// <summary>Profile picture: a version object, an array of versions or an address.</summary>
public VocabularyKeys Picture { get; init; } = VocabularyKeys.None;
/// <summary>When the latest active story was published (stories bar, H2).</summary>
public VocabularyKeys LatestStoryAt { get; init; } = VocabularyKeys.None;
}
/// <summary>Keys of a highlight collection node.</summary>
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;
/// <summary>The contents of the collection, when the response carries them.</summary>
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
}
/// <summary>Keys of the pagination information that comes with a page of data.</summary>
public sealed record PageKeys
{
public VocabularyKeys HasMore { get; init; } = VocabularyKeys.None;
/// <summary>Opaque resume point given by the site (the backfill stores it).</summary>
public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None;
}
/// <summary>Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10).</summary>
public enum VocabularyStatus
{
Confirmed,
/// <summary>Hints only, to be confirmed with the M0 samples: recipes refuse to use it.</summary>
Hypothesis,
}
/// <summary>
/// The key vocabulary of one site (<c>lettori.instagram.json</c>, <c>lettori.prova.json</c>): 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).
/// </summary>
public sealed record ReaderVocabulary
{
public required string Site { get; init; }
public VocabularyStatus Status { get; init; } = VocabularyStatus.Hypothesis;
public string? Note { get; init; }
/// <summary>Where it was loaded from, for messages.</summary>
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();
/// <summary>The key under which the response describes the connected account (H10).</summary>
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<string> MissingConcepts
{
get
{
var missing = new List<string>();
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");
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;
}
}
/// <summary>True when recipes may rely on this vocabulary.</summary>
public bool IsUsable => Status == VocabularyStatus.Confirmed && MissingConcepts.Count == 0;
/// <summary>Italian explanation of why the vocabulary cannot be used yet, or null.</summary>
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)}.";
/// <summary>The shipped Instagram vocabulary (embedded <c>lettori.instagram.json</c>): hints only.</summary>
public static ReaderVocabulary LoadInstagram() => LoadEmbedded("lettori.instagram.json");
/// <summary>The vocabulary of the local test site (embedded <c>lettori.prova.json</c>).</summary>
public static ReaderVocabulary LoadTestSite() => LoadEmbedded("lettori.prova.json");
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
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<string>? 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),
};
}
}
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<string>? Viewer { get; set; }
}
internal sealed class ContentDto
{
public string? Note { get; set; }
public List<string>? Id { get; set; }
public List<string>? Code { get; set; }
public List<string>? TakenAt { get; set; }
public List<string>? Caption { get; set; }
public List<string>? Images { get; set; }
public List<string>? Videos { get; set; }
public List<string>? Children { get; set; }
public List<string>? ChildCount { get; set; }
public List<string>? Owner { get; set; }
public List<string>? Pinned { get; set; }
public List<string>? ExpiresAt { get; set; }
public List<string>? Duration { get; set; }
}
internal sealed class VersionDto
{
public string? Note { get; set; }
public List<string>? Url { get; set; }
public List<string>? Width { get; set; }
public List<string>? Height { get; set; }
public List<string>? HasAudio { get; set; }
}
internal sealed class ProfileDto
{
public string? Note { get; set; }
public List<string>? Id { get; set; }
public List<string>? Username { get; set; }
public List<string>? DisplayName { get; set; }
public List<string>? IsPrivate { get; set; }
public List<string>? IsFollowed { get; set; }
public List<string>? PostCount { get; set; }
public List<string>? Picture { get; set; }
public List<string>? LatestStoryAt { get; set; }
}
internal sealed class HighlightDto
{
public string? Note { get; set; }
public List<string>? Id { get; set; }
public List<string>? Title { get; set; }
public List<string>? Owner { get; set; }
public List<string>? Items { get; set; }
}
internal sealed class PageDto
{
public string? Note { get; set; }
public List<string>? HasMore { get; set; }
public List<string>? Cursor { get; set; }
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
[JsonSerializable(typeof(VocabularyFile))]
internal sealed partial class VocabularyJsonContext : JsonSerializerContext;
@@ -0,0 +1,488 @@
using System.Globalization;
using System.Text.Json;
using Febe.Core.Domain;
namespace Febe.Core.Collection.Readers;
/// <summary>
/// The generic reader (spec §6.4): walks any JSON tree and recognizes, wherever they are, the nodes that look like a
/// content (identifier, date, image or video versions, possibly a series), a profile (identifier and user name), a
/// highlight collection (identifier and title) and the pagination of a page. Which keys mean what comes from the
/// site's <see cref="ReaderVocabulary"/>, never from fixed paths or addresses.
/// </summary>
/// <remarks>
/// Version choice (spec §6.5 point 1): the largest image; for videos the largest among the versions complete with
/// audio (versions that do not say are taken as complete), or the largest of all when none has audio.
/// Thread-safe: the reader keeps no state between calls.
/// </remarks>
public sealed class ShapeReader
{
private const int MaxDepth = 64;
private readonly ReaderVocabulary _v;
public ShapeReader(ReaderVocabulary vocabulary)
{
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
}
public ReaderVocabulary Vocabulary => _v;
/// <summary>Reads one response body. Never throws on unexpected shapes: they become <see cref="ReadShape.Unrecognized"/>.</summary>
public ReadResult Read(JsonElement root)
{
var walk = new Walk();
Visit(root, walk, owner: null, highlightId: null, depth: 0);
var profiles = walk.Profiles.Values.ToList();
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
{
return new ReadResult
{
Shape = ReadShape.Recognized,
Contents = walk.Contents,
Profiles = profiles,
Highlights = walk.Highlights,
Page = walk.Page,
Viewer = viewer,
};
}
if (IsEmptyShape(root, walk.Page is not null))
{
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
}
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
}
/// <summary>Reads a body given as text (tests, probe samples).</summary>
public ReadResult Read(string json)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 256 });
return Read(document.RootElement);
}
private void Visit(JsonElement node, Walk walk, ProfileInfo? owner, string? highlightId, int depth)
{
if (depth > MaxDepth)
{
return;
}
if (node.ValueKind == JsonValueKind.Array)
{
foreach (var item in node.EnumerateArray())
{
Visit(item, walk, owner, highlightId, depth + 1);
}
return;
}
if (node.ValueKind != JsonValueKind.Object)
{
return;
}
if (walk.Page is null && (_v.Page.HasMore.Has(node) || _v.Page.Cursor.Has(node)))
{
walk.Page = new PageInfo(
_v.Page.HasMore.TryGet(node, out var more) ? AsBool(more) : null,
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
}
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
{
walk.AddProfile(viewer with { IsViewer = true });
}
if (IsContent(node))
{
if (ReadContent(node, walk, owner, highlightId) is { } item)
{
walk.Contents.Add(item);
}
return;
}
if (IsHighlight(node))
{
var highlightOwner = _v.Highlight.Owner.TryGet(node, out var ho) ? ReadProfile(ho) ?? owner : owner;
if (highlightOwner is not null)
{
walk.AddProfile(highlightOwner);
}
var id = AsText(Get(_v.Highlight.Id, node))!;
var before = walk.Contents.Count;
if (_v.Highlight.Items.TryGet(node, out var items))
{
Visit(items, walk, highlightOwner, id, depth + 1);
}
walk.Highlights.Add(new HighlightInfo
{
Id = id,
Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty,
Owner = highlightOwner,
Items = walk.Contents.Skip(before).ToList(),
Order = walk.Highlights.Count,
});
return;
}
var inherited = owner;
if (ReadProfile(node) is { } profile)
{
walk.AddProfile(profile);
inherited = profile;
}
else if (_v.Content.Owner.TryGet(node, out var ownerNode) && ReadProfile(ownerNode) is { } declared)
{
// An object that declares an author for what it contains (e.g. the stories of one account).
walk.AddProfile(declared);
inherited = declared;
}
foreach (var property in node.EnumerateObject())
{
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
{
Visit(property.Value, walk, inherited, highlightId, depth + 1);
}
}
}
private bool IsContent(JsonElement node) =>
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
private bool IsHighlight(JsonElement node) =>
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
{
var id = AsText(Get(_v.Content.Id, node));
var takenAt = AsTime(Get(_v.Content.TakenAt, node));
if (id is null || takenAt is null)
{
return null;
}
var owner = _v.Content.Owner.TryGet(node, out var ownerNode) ? ReadProfile(ownerNode) ?? inheritedOwner : inheritedOwner;
if (owner is not null)
{
walk.AddProfile(owner);
}
var files = new List<ContentFile>();
var hasChildren = _v.Content.Children.TryGet(node, out var children) && children.ValueKind == JsonValueKind.Array && children.GetArrayLength() > 0;
var declaredChildren = 0;
if (hasChildren)
{
foreach (var child in children.EnumerateArray())
{
declaredChildren++;
if (child.ValueKind == JsonValueKind.Object && ReadFile(child) is { } file)
{
files.Add(file);
}
}
}
else if (ReadFile(node) is { } single)
{
files.Add(single);
}
var complete = files.Count > 0 && (!hasChildren || files.Count == declaredChildren);
if (_v.Content.ChildCount.TryGet(node, out var countNode) && AsInt(countNode) is { } declared && declared > files.Count)
{
complete = false;
}
return new ContentItem
{
Id = id,
Code = AsText(Get(_v.Content.Code, node)),
TakenAt = takenAt.Value,
Caption = AsText(Get(_v.Content.Caption, node)),
Owner = owner,
Pinned = _v.Content.Pinned.TryGet(node, out var pinned) && AsBool(pinned) == true,
ExpiresAt = AsTime(Get(_v.Content.ExpiresAt, node)),
Files = files,
IsComplete = complete,
HighlightId = highlightId,
Order = walk.Contents.Count,
};
}
private ContentFile? ReadFile(JsonElement node)
{
var videos = _v.Content.Videos.TryGet(node, out var v) ? ReadVersions(v) : [];
var images = _v.Content.Images.TryGet(node, out var i) ? ReadVersions(i) : [];
var id = AsText(Get(_v.Content.Id, node));
var largestImage = images.Count == 0 ? null : images.MaxBy(x => x.Version.Area);
if (videos.Count > 0)
{
var complete = videos.Where(x => x.Version.HasAudio != false).ToList();
var best = (complete.Count > 0 ? complete : videos).MaxBy(x => x.Version.Area)!;
var duration = AsSeconds(Get(_v.Content.Duration, node)) ?? AsSeconds(Get(_v.Content.Duration, best.Node));
return new ContentFile(MediaKind.Video, id, best.Version, largestImage?.Version, duration);
}
return largestImage is null ? null : new ContentFile(MediaKind.Photo, id, largestImage.Version, null, null);
}
private List<VersionNode> ReadVersions(JsonElement value)
{
var list = new List<VersionNode>();
switch (value.ValueKind)
{
case JsonValueKind.Array:
foreach (var item in value.EnumerateArray())
{
if (ReadVersion(item) is { } version)
{
list.Add(new VersionNode(version, item));
}
}
break;
case JsonValueKind.Object:
case JsonValueKind.String:
if (ReadVersion(value) is { } single)
{
list.Add(new VersionNode(single, value));
}
break;
}
return list;
}
private FileVersion? ReadVersion(JsonElement node)
{
if (node.ValueKind == JsonValueKind.String)
{
return IsAddress(node.GetString()) ? new FileVersion(node.GetString()!, null, null, null) : null;
}
if (node.ValueKind != JsonValueKind.Object)
{
return null;
}
var url = AsText(Get(_v.Version.Url, node));
if (!IsAddress(url))
{
return null;
}
return new FileVersion(
url!,
AsInt(Get(_v.Version.Width, node)),
AsInt(Get(_v.Version.Height, node)),
_v.Version.HasAudio.TryGet(node, out var audio) ? AsBool(audio) : null);
}
private ProfileInfo? ReadProfile(JsonElement node)
{
if (node.ValueKind != JsonValueKind.Object)
{
return null;
}
var id = AsText(Get(_v.Profile.Id, node));
var username = AsText(Get(_v.Profile.Username, node));
if (id is null || string.IsNullOrWhiteSpace(username))
{
return null;
}
FileVersion? picture = null;
if (_v.Profile.Picture.TryGet(node, out var pictureNode))
{
picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version;
}
return new ProfileInfo
{
Id = id,
Username = username.Trim(),
DisplayName = AsText(Get(_v.Profile.DisplayName, node)),
IsPrivate = _v.Profile.IsPrivate.TryGet(node, out var p) ? AsBool(p) : null,
IsFollowed = _v.Profile.IsFollowed.TryGet(node, out var f) ? AsBool(f) : null,
PostCount = AsInt(Get(_v.Profile.PostCount, node)),
Picture = picture,
LatestStoryAt = AsTime(Get(_v.Profile.LatestStoryAt, node)),
};
}
/// <summary>
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
/// </summary>
private static bool IsEmptyShape(JsonElement root, bool hasPage)
{
var nested = false;
var nonEmptyArray = false;
Scan(root, 0, ref nested, ref nonEmptyArray);
return !nonEmptyArray && (hasPage || !nested);
}
private static void Scan(JsonElement element, int depth, ref bool nested, ref bool nonEmptyArray)
{
if (depth > MaxDepth)
{
return;
}
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (property.Value.ValueKind == JsonValueKind.Object)
{
nested = true;
}
Scan(property.Value, depth + 1, ref nested, ref nonEmptyArray);
}
break;
case JsonValueKind.Array:
if (element.GetArrayLength() > 0)
{
nonEmptyArray = true;
}
break;
}
}
private static JsonElement Get(VocabularyKeys keys, JsonElement node) => keys.TryGet(node, out var value) ? value : default;
private static bool IsAddress(string? text) =>
!string.IsNullOrWhiteSpace(text)
&& Uri.TryCreate(text, UriKind.Absolute, out var uri)
&& uri.Scheme is "http" or "https";
internal static string? AsText(JsonElement value) => value.ValueKind switch
{
JsonValueKind.String => string.IsNullOrEmpty(value.GetString()) ? null : value.GetString(),
JsonValueKind.Number => value.GetRawText(),
_ => null,
};
internal static int? AsInt(JsonElement value)
{
switch (value.ValueKind)
{
case JsonValueKind.Number when value.TryGetInt32(out var i):
return i;
case JsonValueKind.Number when value.TryGetDouble(out var d) && d is >= int.MinValue and <= int.MaxValue:
return (int)Math.Round(d);
case JsonValueKind.String when int.TryParse(value.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s):
return s;
default:
return null;
}
}
internal static bool? AsBool(JsonElement value) => value.ValueKind switch
{
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Number => value.TryGetInt64(out var n) ? n != 0 : null,
JsonValueKind.String => value.GetString()?.Trim().ToLowerInvariant() switch
{
"true" or "1" or "sì" or "si" => true,
"false" or "0" or "no" => false,
_ => null,
},
_ => null,
};
internal static TimeSpan? AsSeconds(JsonElement value)
{
double? seconds = value.ValueKind switch
{
JsonValueKind.Number when value.TryGetDouble(out var d) => d,
JsonValueKind.String when double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var s) => s,
_ => null,
};
return seconds is { } x && x >= 0 && x < 1e7 ? TimeSpan.FromSeconds(x) : null;
}
/// <summary>A date: Unix seconds (milliseconds when larger than 10^11), or ISO 8601 text.</summary>
internal static DateTimeOffset? AsTime(JsonElement value)
{
switch (value.ValueKind)
{
case JsonValueKind.Number when value.TryGetDouble(out var n):
return FromUnix(n);
case JsonValueKind.String:
var text = value.GetString();
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var numeric))
{
return FromUnix(numeric);
}
return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
? parsed
: null;
default:
return null;
}
}
private static DateTimeOffset? FromUnix(double value)
{
if (value <= 0 || double.IsNaN(value))
{
return null;
}
var ms = value > 1e11 ? value : value * 1000;
return ms < 253402300799000 ? DateTimeOffset.FromUnixTimeMilliseconds((long)ms) : null;
}
private sealed record VersionNode(FileVersion Version, JsonElement Node);
private sealed class Walk
{
public List<ContentItem> Contents { get; } = [];
public List<HighlightInfo> Highlights { get; } = [];
public Dictionary<string, ProfileInfo> Profiles { get; } = new(StringComparer.Ordinal);
public PageInfo? Page { get; set; }
/// <summary>Merges what different parts of a response say about the same profile.</summary>
public void AddProfile(ProfileInfo profile)
{
if (!Profiles.TryGetValue(profile.Id, out var known))
{
Profiles[profile.Id] = profile;
return;
}
Profiles[profile.Id] = known with
{
DisplayName = known.DisplayName ?? profile.DisplayName,
IsPrivate = known.IsPrivate ?? profile.IsPrivate,
IsFollowed = known.IsFollowed ?? profile.IsFollowed,
PostCount = known.PostCount ?? profile.PostCount,
Picture = known.Picture ?? profile.Picture,
LatestStoryAt = known.LatestStoryAt ?? profile.LatestStoryAt,
IsViewer = known.IsViewer || profile.IsViewer,
};
}
}
}