«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
436 lines
19 KiB
C#
436 lines
19 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Core.Collection.Privacy;
|
|
|
|
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 when the address carries it.</summary>
|
|
public const string StoryViewer = "storyViewer";
|
|
|
|
/// <summary>
|
|
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
|
|
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
|
|
/// </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";
|
|
|
|
/// <summary>The command that opens the site's search panel («Cerca» in the side column; issue #37).</summary>
|
|
public const string SearchOpen = "search-open";
|
|
|
|
/// <summary>The search box of that panel, where the profile search types (issue #37).</summary>
|
|
public const string SearchBox = "search-box";
|
|
|
|
public static IReadOnlyList<string> All { get; } =
|
|
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose, SearchOpen, SearchBox];
|
|
}
|
|
|
|
/// <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;
|
|
private readonly IReadOnlyList<(string Name, Regex Shape)> _classifier;
|
|
private readonly HashSet<string> _literals;
|
|
|
|
/// <summary>The fixed words and the placeholder names of the shipped maps (the only ones a report may show).</summary>
|
|
private static readonly Lazy<(HashSet<string> Words, HashSet<string> Placeholders)> Shipped = new(LoadShippedWords);
|
|
|
|
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);
|
|
|
|
// More literal segments first (the highlight viewer before the story viewer, whose {username} would take
|
|
// «highlights»), shapes without a query before the same shape with one, then the order of SitePages.All: a page
|
|
// made only of placeholders (the profile, «/{username}/») comes after every page with a word of its own.
|
|
_classifier = [.. _pages
|
|
.Select(p => (Name: p.Key, Pattern: p.Value, Shape: p.Value.Split('?')[0]))
|
|
.OrderByDescending(p => LiteralSegments(p.Shape))
|
|
.ThenBy(p => p.Pattern.Contains('?', StringComparison.Ordinal) ? 1 : 0)
|
|
.ThenBy(p => IndexOfPage(p.Name))
|
|
.ThenBy(p => p.Name, StringComparer.Ordinal)
|
|
.Select(p => (p.Name, new Regex(ShapeRegex(p.Shape, out _), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100))))];
|
|
_literals = new HashSet<string>(
|
|
_pages.Values.SelectMany(v => v.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries)).Where(segment => !Placeholder().IsMatch(segment)),
|
|
StringComparer.OrdinalIgnoreCase);
|
|
}
|
|
|
|
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 regex = ShapeRegex(pattern.Split('?')[0], out var names);
|
|
var match = Regex.Match(path, regex, 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>
|
|
/// Which page of the map an address path has the shape of, or null when none (data endpoints, pages the map does not
|
|
/// know). Pages with more words of their own are tried first, so «/stories/highlights/1/» is the highlight viewer
|
|
/// and not the story viewer of someone called «highlights»; the profile, made only of a placeholder, comes last.
|
|
/// A placeholder never takes a fixed word of the site (<see cref="PathPatterns.IsKnownSegment"/>) or of a map:
|
|
/// «/challenge/», «/explore/», «/reels/» are not profiles. Only the page NAME comes out: never the values (issue #39).
|
|
/// </summary>
|
|
public string? Classify(string? path)
|
|
{
|
|
if (string.IsNullOrEmpty(path))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
foreach (var (name, shape) in _classifier)
|
|
{
|
|
try
|
|
{
|
|
var match = shape.Match(path);
|
|
if (match.Success && !TakesAWord(match))
|
|
{
|
|
return name;
|
|
}
|
|
}
|
|
catch (RegexMatchTimeoutException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The shape of the address of page <paramref name="name"/> for a report: without its query, with its
|
|
/// {placeholders} and no value (e.g. «/{username}/»); null when the page is not set. A map may come from Alberto's
|
|
/// data folder, so the shape is reduced like any path: only the fixed words of the site and of the shipped maps
|
|
/// and their placeholders stay, any other segment becomes {numero} or {testo} («/alberto.rossi/following/» written
|
|
/// in place of «/{username}/following/» gives «/{testo}/following/»).
|
|
/// </summary>
|
|
public string? PatternOf(string name) =>
|
|
_pages.TryGetValue(name, out var pattern) ? ReportShape(pattern.Split('?')[0]) : null;
|
|
|
|
/// <summary>A page shape reduced for a report (<see cref="PatternOf"/>).</summary>
|
|
public static string ReportShape(string shape)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(shape);
|
|
var (words, placeholders) = Shipped.Value;
|
|
var segments = shape.Split('/');
|
|
for (var i = 0; i < segments.Length; i++)
|
|
{
|
|
var segment = segments[i];
|
|
if (segment.Length == 0 || PathPatterns.IsKnownSegment(segment) || words.Contains(segment))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var whole = Placeholder().Match(segment);
|
|
if (whole.Success && whole.Length == segment.Length && placeholders.Contains(whole.Groups[1].Value))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
segments[i] = PathPatterns.Of("/" + segment)[1..];
|
|
}
|
|
|
|
return string.Join('/', segments);
|
|
}
|
|
|
|
/// <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 map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets 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 string ShapeRegex(string shape, out List<string> names)
|
|
{
|
|
names = [];
|
|
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('$');
|
|
return regex.ToString();
|
|
}
|
|
|
|
/// <summary>True when a placeholder of the match took a fixed word of the site or of a map (not a value, so not this page).</summary>
|
|
private bool TakesAWord(Match match)
|
|
{
|
|
var shippedWords = Shipped.Value.Words;
|
|
for (var i = 1; i < match.Groups.Count; i++)
|
|
{
|
|
var value = match.Groups[i].Value;
|
|
if (PathPatterns.IsKnownSegment(value) || PathPatterns.IsKnownSegment(value.ToLowerInvariant())
|
|
|| _literals.Contains(value) || shippedWords.Contains(value))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static (HashSet<string> Words, HashSet<string> Placeholders) LoadShippedWords()
|
|
{
|
|
var words = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
var placeholders = new HashSet<string>(StringComparer.Ordinal);
|
|
foreach (var file in new[] { "bersagli.instagram.json", "bersagli.prova.json" })
|
|
{
|
|
foreach (var pattern in LoadEmbedded(file)._pages.Values)
|
|
{
|
|
// The names of the values the recipes fill in, in the path or in the query («{cursor}»).
|
|
placeholders.UnionWith(Placeholder().Matches(pattern).Select(m => m.Groups[1].Value));
|
|
foreach (var segment in pattern.Split('?')[0].Split('/', StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
if (!Placeholder().IsMatch(segment))
|
|
{
|
|
words.Add(segment);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return (words, placeholders);
|
|
}
|
|
|
|
private static int LiteralSegments(string shape) =>
|
|
shape.Split('/', StringSplitOptions.RemoveEmptyEntries).Count(segment => !Placeholder().IsMatch(segment));
|
|
|
|
private static int IndexOfPage(string name)
|
|
{
|
|
for (var i = 0; i < SitePages.All.Count; i++)
|
|
{
|
|
if (SitePages.All[i] == name)
|
|
{
|
|
return i;
|
|
}
|
|
}
|
|
|
|
return int.MaxValue;
|
|
}
|
|
|
|
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();
|
|
}
|