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:
74 files changed
+12689
-13
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user