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

+276
View File
@@ -0,0 +1,276 @@
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Febe.Core.Collection;
/// <summary>Names of the pages of a site map (the «pages» section of <c>bersagli.*.json</c>).</summary>
public static class SitePages
{
/// <summary>Home: stories bar and recent posts of followed profiles.</summary>
public const string Home = "home";
/// <summary>Profile page, with {username}.</summary>
public const string Profile = "profile";
/// <summary>Profile page starting after a resume point, with {username} and {cursor} (optional: backfill resume).</summary>
public const string ProfileFrom = "profileFrom";
/// <summary>Reels tab of a profile resuming after {cursor} (optional).</summary>
public const string ReelsFrom = "reelsFrom";
/// <summary>Tagged tab of a profile resuming after {cursor} (optional).</summary>
public const string TaggedFrom = "taggedFrom";
/// <summary>Single post page, with {code}.</summary>
public const string Post = "post";
/// <summary>List of the profiles Alberto follows, with {username} (Alberto's).</summary>
public const string Following = "following";
/// <summary>The same list resuming after {cursor} (optional).</summary>
public const string FollowingFrom = "followingFrom";
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
public const string StoryViewer = "storyViewer";
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
public const string HighlightViewer = "highlightViewer";
public static IReadOnlyList<string> All { get; } =
[Home, Profile, ProfileFrom, ReelsFrom, TaggedFrom, Post, Following, FollowingFrom, StoryViewer, HighlightViewer];
}
/// <summary>Identifiers of the targets the recipes look for (the «targets» section of <c>bersagli.*.json</c>).</summary>
public static class SiteTargets
{
/// <summary>An account in the stories bar of the home, with {username}.</summary>
public const string HomeStory = "home-story";
/// <summary>The profile picture with the stories ring, on a profile page, with {username}.</summary>
public const string ProfileStoryRing = "profile-story-ring";
/// <summary>Read-only marker of a profile that does not exist.</summary>
public const string ProfileNotFound = "profile-not-found";
public const string ProfileTabPosts = "profile-tab-posts";
public const string ProfileTabReels = "profile-tab-reels";
public const string ProfileTabTagged = "profile-tab-tagged";
/// <summary>A highlight collection on a profile page, with {id}.</summary>
public const string ProfileHighlight = "profile-highlight";
/// <summary>The zone or command that advances the viewer to the next story.</summary>
public const string ViewerNext = "viewer-next";
/// <summary>The command that closes the viewer.</summary>
public const string ViewerClose = "viewer-close";
public static IReadOnlyList<string> All { get; } =
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose];
}
/// <summary>
/// The site-specific part of a target map file that the recipes need in Core: page addresses and which targets are
/// configured. How a target is found (role, accessible name, link shape) is the browser layer's business
/// (<c>Febe.Browser.Targets.TargetMap</c>, same file).
/// </summary>
public sealed partial class SiteMap
{
private readonly Dictionary<string, string> _pages;
private readonly HashSet<string> _configuredTargets;
private readonly HashSet<string> _knownTargets;
public SiteMap(string site, IReadOnlyDictionary<string, string?> pages, IEnumerable<string> configuredTargets, IEnumerable<string> knownTargets, string? source = null)
{
Site = site;
Source = source;
_pages = pages.Where(p => !string.IsNullOrWhiteSpace(p.Value)).ToDictionary(p => p.Key, p => p.Value!.Trim(), StringComparer.Ordinal);
_configuredTargets = new HashSet<string>(configuredTargets, StringComparer.Ordinal);
_knownTargets = new HashSet<string>(knownTargets, StringComparer.Ordinal);
}
public string Site { get; }
public string? Source { get; }
public bool HasPage(string name) => _pages.ContainsKey(name);
public bool IsTargetConfigured(string id) => _configuredTargets.Contains(id);
/// <summary>Pages and targets among the given ones that are still unset (Italian names for messages).</summary>
public IReadOnlyList<string> Missing(IEnumerable<string> pages, IEnumerable<string> targets)
{
var missing = new List<string>();
missing.AddRange(pages.Where(p => !HasPage(p)).Select(p => $"pagina «{p}»"));
missing.AddRange(targets.Where(t => !IsTargetConfigured(t)).Select(t => _knownTargets.Contains(t) ? $"bersaglio «{t}» (vuoto)" : $"bersaglio «{t}» (assente)"));
return missing;
}
/// <summary>The path of page <paramref name="name"/> with its {placeholders} filled (values escaped for an address).</summary>
/// <exception cref="InvalidOperationException">The page is not configured.</exception>
public string BuildPath(string name, IReadOnlyDictionary<string, string>? values = null)
{
if (!_pages.TryGetValue(name, out var pattern))
{
throw new InvalidOperationException($"La pagina «{name}» non è impostata nella mappa {Source ?? Site}.");
}
return Placeholder().Replace(pattern, m =>
{
var key = m.Groups[1].Value;
if (values is null || !values.TryGetValue(key, out var value))
{
throw new InvalidOperationException($"Manca il valore di «{{{key}}}» per la pagina «{name}».");
}
return Uri.EscapeDataString(value);
});
}
/// <summary>
/// Reads an address path against the shape of page <paramref name="name"/> (e.g. the story viewer):
/// returns the {placeholder} values, or null when the path does not have that shape.
/// </summary>
public IReadOnlyDictionary<string, string>? Match(string name, string path)
{
if (!_pages.TryGetValue(name, out var pattern) || string.IsNullOrEmpty(path))
{
return null;
}
var shape = pattern.Split('?')[0];
var names = new List<string>();
var regex = new StringBuilder("^");
var last = 0;
foreach (Match m in Placeholder().Matches(shape))
{
regex.Append(Regex.Escape(shape[last..m.Index]));
regex.Append("([^/]+)");
names.Add(m.Groups[1].Value);
last = m.Index + m.Length;
}
regex.Append(Regex.Escape(shape[last..]));
if (!shape.EndsWith('/'))
{
regex.Append("/?");
}
regex.Append('$');
var match = Regex.Match(path, regex.ToString(), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100));
if (!match.Success)
{
return null;
}
var result = new Dictionary<string, string>(StringComparer.Ordinal);
for (var i = 0; i < names.Count; i++)
{
result[names[i]] = Uri.UnescapeDataString(match.Groups[i + 1].Value);
}
return result;
}
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
public static SiteMap Load(string path) => Parse(File.ReadAllText(path), path);
/// <summary>Text of an embedded configuration file (also used by the browser layer to parse the targets).</summary>
public static string ReadEmbeddedText(string fileName)
{
var resource = $"Febe.Core.Config.{fileName}";
using var stream = typeof(SiteMap).Assembly.GetManifestResourceStream(resource)
?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
public static SiteMap LoadEmbedded(string fileName) => Parse(ReadEmbeddedText(fileName), fileName);
public static SiteMap Parse(string json, string? source = null)
{
var name = source ?? "bersagli";
JsonDocument document;
try
{
document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch (JsonException ex)
{
throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}).", ex);
}
using (document)
{
var root = document.RootElement;
var site = root.TryGetProperty("site", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString()! : "sito";
var pages = new Dictionary<string, string?>(StringComparer.Ordinal);
if (root.TryGetProperty("pages", out var p) && p.ValueKind == JsonValueKind.Object)
{
foreach (var page in p.EnumerateObject())
{
if (!SitePages.All.Contains(page.Name, StringComparer.Ordinal))
{
throw new InvalidDataException($"{name}: pagina «{page.Name}» sconosciuta (ammesse: {string.Join(", ", SitePages.All)}).");
}
var value = page.Value.ValueKind switch
{
JsonValueKind.String => page.Value.GetString(),
JsonValueKind.Object when page.Value.TryGetProperty("path", out var path) && path.ValueKind == JsonValueKind.String => path.GetString(),
_ => null,
};
if (!string.IsNullOrWhiteSpace(value) && !value.StartsWith('/'))
{
throw new InvalidDataException($"{name}: la pagina «{page.Name}» è un percorso e comincia con «/».");
}
pages[page.Name] = value;
}
}
var configured = new List<string>();
var known = new List<string>();
if (root.TryGetProperty("targets", out var t) && t.ValueKind == JsonValueKind.Object)
{
foreach (var target in t.EnumerateObject())
{
known.Add(target.Name);
if (target.Value.ValueKind == JsonValueKind.Object && IsConfigured(target.Value))
{
configured.Add(target.Name);
}
}
}
return new SiteMap(site, pages, configured, known, source);
}
}
private static bool IsConfigured(JsonElement target)
{
foreach (var key in new[] { "role", "name", "href" })
{
if (target.TryGetProperty(key, out var value) && value.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(value.GetString()))
{
return true;
}
}
return false;
}
[GeneratedRegex(@"\{([A-Za-z][A-Za-z0-9_]*)\}", RegexOptions.CultureInvariant)]
private static partial Regex Placeholder();
}