Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
245 lines
9.9 KiB
C#
245 lines
9.9 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Febe.Browser.Targets;
|
|
|
|
/// <summary>
|
|
/// How to find one thing in the page (spec §6.3): element role, accessible name, link shape, optional index.
|
|
/// Never fixed coordinates, never generated class names.
|
|
/// </summary>
|
|
/// <param name="Id">Identifier used by recipes (e.g. «viewer-next»).</param>
|
|
/// <param name="Roles">Accepted ARIA roles, explicit or implicit («link», «button», ...). Empty: any.</param>
|
|
/// <param name="NamePattern">Regular expression (case-insensitive) on the accessible name; may contain {parameters}.</param>
|
|
/// <param name="HrefPattern">Link shape on the path, e.g. «/{username}/», «/stories/**»: {name} or * is one segment, ** the rest.</param>
|
|
/// <param name="Index">Which of the visible matches, in document order (0 = first, -1 = last).</param>
|
|
/// <param name="Hypothesis">Hypothesis of spec §6.6 the target depends on (e.g. «H11»), when not yet confirmed.</param>
|
|
public sealed record TargetSpec(string Id, IReadOnlyList<string> Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis)
|
|
{
|
|
/// <summary>
|
|
/// False for a placeholder of a skeleton map (role, name and href written but empty, e.g. the first
|
|
/// <c>bersagli.instagram.json</c>): looking it up gives <see cref="TargetStatus.NotConfigured"/> without touching the page.
|
|
/// </summary>
|
|
public bool IsConfigured => Roles.Count > 0 || NamePattern is not null || HrefPattern is not null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The target map of one site (<c>bersagli.instagram.json</c>, <c>bersagli.prova.json</c>), editable without
|
|
/// recompiling: it is the second thing to touch, after the readers, when the site changes.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Format:
|
|
/// <code>
|
|
/// {
|
|
/// "site": "prova",
|
|
/// "note": "testo libero",
|
|
/// "targets": {
|
|
/// "viewer-next": { "role": "button", "name": "^avanti$", "note": "..." },
|
|
/// "profile-stories": { "role": "link", "href": "/stories/{username}/", "index": 0, "hypothesis": "H11" }
|
|
/// }
|
|
/// }
|
|
/// </code>
|
|
/// «role» may list alternatives with «|» («button|link»). At least one of role, name and href is required.
|
|
/// Unknown keys are refused, so coordinates or class names cannot slip in.
|
|
/// </remarks>
|
|
public sealed partial class TargetMap
|
|
{
|
|
private readonly Dictionary<string, TargetSpec> _targets;
|
|
|
|
public TargetMap(string? site, IEnumerable<TargetSpec> targets, string? source = null)
|
|
{
|
|
Site = site;
|
|
Source = source;
|
|
_targets = targets.ToDictionary(t => t.Id, StringComparer.Ordinal);
|
|
}
|
|
|
|
public string? Site { get; }
|
|
|
|
public string? Source { get; }
|
|
|
|
public IReadOnlyDictionary<string, TargetSpec> Targets => _targets;
|
|
|
|
public bool Contains(string id) => _targets.ContainsKey(id);
|
|
|
|
public TargetSpec Get(string id) =>
|
|
_targets.TryGetValue(id, out var spec)
|
|
? spec
|
|
: throw new KeyNotFoundException($"Il bersaglio «{id}» non è nella mappa {Source ?? Site ?? string.Empty}.".TrimEnd());
|
|
|
|
public static TargetMap Load(string path) => Parse(File.ReadAllText(path), path);
|
|
|
|
/// <summary>A map shipped with Febe.Core (<c>bersagli.prova.json</c>, <c>bersagli.instagram.json</c>).</summary>
|
|
public static TargetMap LoadEmbedded(string fileName) =>
|
|
Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText(fileName), fileName);
|
|
|
|
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
|
|
public static TargetMap LoadOrEmbedded(string? path, string embeddedName) =>
|
|
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
|
|
|
|
public static TargetMap Parse(string json, string? source = null)
|
|
{
|
|
var name = source ?? "bersagli";
|
|
TargetMapFile? file;
|
|
try
|
|
{
|
|
file = JsonSerializer.Deserialize(json, TargetMapJsonContext.Default.TargetMapFile);
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
throw new InvalidDataException($"{name}: file non valido ({ex.Message.Split('.')[0]}).", ex);
|
|
}
|
|
|
|
if (file?.Targets is null || file.Targets.Count == 0)
|
|
{
|
|
throw new InvalidDataException($"{name}: manca l'elenco «targets».");
|
|
}
|
|
|
|
var specs = new List<TargetSpec>();
|
|
foreach (var (id, dto) in file.Targets)
|
|
{
|
|
var where = $"{name}, bersaglio «{id}»";
|
|
if (!IdShape().IsMatch(id))
|
|
{
|
|
throw new InvalidDataException($"{where}: l'identificativo usa solo lettere minuscole, cifre e trattini.");
|
|
}
|
|
|
|
var roles = (dto.Role ?? string.Empty).Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
|
.Select(r => r.ToLowerInvariant())
|
|
.ToArray();
|
|
// A skeleton entry writes the three keys empty on purpose (still to be filled from the M0 samples);
|
|
// an entry that names none of them is a mistake.
|
|
var placeholder = dto.Role is not null && dto.Name is not null && dto.Href is not null;
|
|
if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href) && !placeholder)
|
|
{
|
|
throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href» (vuoti tutti e tre per una voce ancora da compilare).");
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(dto.Name))
|
|
{
|
|
try
|
|
{
|
|
_ = new Regex(PlaceholderToken().Replace(dto.Name, "x"), RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(100));
|
|
}
|
|
catch (ArgumentException ex)
|
|
{
|
|
throw new InvalidDataException($"{where}: espressione «name» non valida.", ex);
|
|
}
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(dto.Href) && !dto.Href.StartsWith('/'))
|
|
{
|
|
throw new InvalidDataException($"{where}: «href» descrive un percorso e comincia con «/».");
|
|
}
|
|
|
|
specs.Add(new TargetSpec(id, roles, NullIfBlank(dto.Name), NullIfBlank(dto.Href), dto.Index ?? 0, NullIfBlank(dto.Hypothesis)));
|
|
}
|
|
|
|
return new TargetMap(file.Site, specs, source);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Turns a link shape into an anchored, case-insensitive-ready regular expression on the path.
|
|
/// {name} becomes the escaped parameter value when given, otherwise one segment; * is one segment; ** the rest.
|
|
/// </summary>
|
|
public static string HrefPatternToRegex(string pattern, IReadOnlyDictionary<string, string>? parameters = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(pattern);
|
|
var sb = new StringBuilder("^");
|
|
var i = 0;
|
|
while (i < pattern.Length)
|
|
{
|
|
if (pattern[i] == '{')
|
|
{
|
|
var end = pattern.IndexOf('}', i);
|
|
if (end < 0)
|
|
{
|
|
throw new FormatException($"Segnaposto non chiuso in «{pattern}».");
|
|
}
|
|
|
|
var key = pattern[(i + 1)..end];
|
|
sb.Append(parameters is not null && parameters.TryGetValue(key, out var value) ? EscapeForRegex(value) : "[^/]+");
|
|
i = end + 1;
|
|
}
|
|
else if (pattern[i] == '*')
|
|
{
|
|
var isDouble = i + 1 < pattern.Length && pattern[i + 1] == '*';
|
|
sb.Append(isDouble ? ".*" : "[^/]+");
|
|
i += isDouble ? 2 : 1;
|
|
}
|
|
else
|
|
{
|
|
sb.Append(EscapeForRegex(pattern[i].ToString()));
|
|
i++;
|
|
}
|
|
}
|
|
|
|
return sb.Append('$').ToString();
|
|
}
|
|
|
|
/// <summary>Replaces {parameters} in a name pattern with their escaped values.</summary>
|
|
public static string ExpandNamePattern(string pattern, IReadOnlyDictionary<string, string>? parameters) =>
|
|
PlaceholderToken().Replace(pattern, m =>
|
|
parameters is not null && parameters.TryGetValue(m.Groups[1].Value, out var value) ? EscapeForRegex(value) : ".+");
|
|
|
|
/// <summary>Escapes regular-expression metacharacters in a way valid both for .NET and JavaScript.</summary>
|
|
internal static string EscapeForRegex(string text)
|
|
{
|
|
var sb = new StringBuilder(text.Length);
|
|
foreach (var c in text)
|
|
{
|
|
if (@"\^$.|?*+()[]{}/".Contains(c, StringComparison.Ordinal))
|
|
{
|
|
sb.Append('\\');
|
|
}
|
|
|
|
sb.Append(c);
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
|
|
private static string? NullIfBlank(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim();
|
|
|
|
[GeneratedRegex("^[a-z0-9]+(-[a-z0-9]+)*$", RegexOptions.CultureInvariant)]
|
|
private static partial Regex IdShape();
|
|
|
|
[GeneratedRegex(@"\{([A-Za-z][A-Za-z0-9_]*)\}", RegexOptions.CultureInvariant)]
|
|
private static partial Regex PlaceholderToken();
|
|
}
|
|
|
|
internal sealed class TargetMapFile
|
|
{
|
|
public string? Site { get; set; }
|
|
|
|
public string? Note { get; set; }
|
|
|
|
/// <summary>Page addresses: read by <c>Febe.Core.Collection.SiteMap</c>, accepted and ignored here.</summary>
|
|
public Dictionary<string, JsonElement>? Pages { get; set; }
|
|
|
|
public Dictionary<string, TargetDto>? Targets { get; set; }
|
|
}
|
|
|
|
internal sealed class TargetDto
|
|
{
|
|
public string? Role { get; set; }
|
|
|
|
public string? Name { get; set; }
|
|
|
|
public string? Href { get; set; }
|
|
|
|
public int? Index { get; set; }
|
|
|
|
public string? Hypothesis { get; set; }
|
|
|
|
public string? Note { get; set; }
|
|
}
|
|
|
|
[JsonSourceGenerationOptions(
|
|
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
|
ReadCommentHandling = JsonCommentHandling.Skip,
|
|
AllowTrailingCommas = true,
|
|
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
|
|
[JsonSerializable(typeof(TargetMapFile))]
|
|
internal sealed partial class TargetMapJsonContext : JsonSerializerContext;
|