using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Core.Collection.Privacy;
namespace Febe.Core.Collection;
/// Names of the pages of a site map (the «pages» section of bersagli.*.json).
public static class SitePages
{
/// Home: stories bar and recent posts of followed profiles.
public const string Home = "home";
/// Profile page, with {username}.
public const string Profile = "profile";
/// Profile page starting after a resume point, with {username} and {cursor} (optional: backfill resume).
public const string ProfileFrom = "profileFrom";
/// Reels tab of a profile resuming after {cursor} (optional).
public const string ReelsFrom = "reelsFrom";
/// Tagged tab of a profile resuming after {cursor} (optional).
public const string TaggedFrom = "taggedFrom";
/// Single post page, with {code}.
public const string Post = "post";
/// List of the profiles Alberto follows, with {username} (Alberto's).
public const string Following = "following";
/// The same list resuming after {cursor} (optional).
public const string FollowingFrom = "followingFrom";
/// Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.
public const string StoryViewer = "storyViewer";
///
/// 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).
///
public const string HighlightViewer = "highlightViewer";
public static IReadOnlyList All { get; } =
[Home, Profile, ProfileFrom, ReelsFrom, TaggedFrom, Post, Following, FollowingFrom, StoryViewer, HighlightViewer];
}
/// Identifiers of the targets the recipes look for (the «targets» section of bersagli.*.json).
public static class SiteTargets
{
/// An account in the stories bar of the home, with {username}.
public const string HomeStory = "home-story";
/// The profile picture with the stories ring, on a profile page, with {username}.
public const string ProfileStoryRing = "profile-story-ring";
/// Read-only marker of a profile that does not exist.
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";
/// A highlight collection on a profile page, with {id}.
public const string ProfileHighlight = "profile-highlight";
/// The zone or command that advances the viewer to the next story.
public const string ViewerNext = "viewer-next";
/// The command that closes the viewer.
public const string ViewerClose = "viewer-close";
/// The command that opens the site's search panel («Cerca» in the side column; issue #37).
public const string SearchOpen = "search-open";
/// The search box of that panel, where the profile search types (issue #37).
public const string SearchBox = "search-box";
public static IReadOnlyList All { get; } =
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose, SearchOpen, SearchBox];
}
///
/// 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
/// (Febe.Browser.Targets.TargetMap, same file).
///
public sealed partial class SiteMap
{
private readonly Dictionary _pages;
private readonly HashSet _configuredTargets;
private readonly HashSet _knownTargets;
private readonly IReadOnlyList<(string Name, Regex Shape)> _classifier;
private readonly HashSet _literals;
/// The fixed words and the placeholder names of the shipped maps (the only ones a report may show).
private static readonly Lazy<(HashSet Words, HashSet Placeholders)> Shipped = new(LoadShippedWords);
public SiteMap(string site, IReadOnlyDictionary pages, IEnumerable configuredTargets, IEnumerable 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(configuredTargets, StringComparer.Ordinal);
_knownTargets = new HashSet(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(
_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);
/// Pages and targets among the given ones that are still unset (Italian names for messages).
public IReadOnlyList Missing(IEnumerable pages, IEnumerable targets)
{
var missing = new List();
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;
}
/// The path of page with its {placeholders} filled (values escaped for an address).
/// The page is not configured.
public string BuildPath(string name, IReadOnlyDictionary? 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);
});
}
///
/// Reads an address path against the shape of page (e.g. the story viewer):
/// returns the {placeholder} values, or null when the path does not have that shape.
///
public IReadOnlyDictionary? 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(StringComparer.Ordinal);
for (var i = 0; i < names.Count; i++)
{
result[names[i]] = Uri.UnescapeDataString(match.Groups[i + 1].Value);
}
return result;
}
///
/// 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 () or of a map:
/// «/challenge/», «/explore/», «/reels/» are not profiles. Only the page NAME comes out: never the values (issue #39).
///
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;
}
///
/// The shape of the address of page 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/»).
///
public string? PatternOf(string name) =>
_pages.TryGetValue(name, out var pattern) ? ReportShape(pattern.Split('?')[0]) : null;
/// A page shape reduced for a report ().
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);
}
/// The target map of the local test site (embedded bersagli.prova.json).
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
/// The Instagram map (embedded bersagli.instagram.json): the pages seen in real traffic, targets still unset (H11).
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);
/// Text of an embedded configuration file (also used by the browser layer to parse the targets).
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(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();
var known = new List();
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 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();
}
/// 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).
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 Words, HashSet Placeholders) LoadShippedWords()
{
var words = new HashSet(StringComparer.OrdinalIgnoreCase);
var placeholders = new HashSet(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();
}