Files
Anubis/src/Anubis/News/Feeds.cs
T
Alby96andClaude Opus 5.5 61878c2023 Keep broken model answers and articles from stopping the news (refs #58, refs #61)
The independent review of phase 7 found that an answer with half a Unicode
character, or of an unexpected shape, escaped the validation as an exception:
its cost was lost, it was paid again every two minutes past the daily cap, and
the diary of the news stopped. The same happened to the whole round with an
article cut in the middle of an emoji.

Such answers are now refused like any other, the cost is written before the
request leaves and settled with what the service used, never clamped to the
estimate, and neither the analyst nor one source can stop the others. The
estimate counts every byte as a token, so it is a true worst case. Summaries
with bare domains or invisible characters are refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:24:36 +01:00

239 lines
9.2 KiB
C#

using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
namespace Anubis.News;
/// <summary>One article as a feed gives it, before cleaning and grouping (SPEC 10.2, point 1).</summary>
public sealed record FeedItem(string Title, string Link)
{
public string? Summary { get; init; }
public DateTimeOffset? PublishedAt { get; init; }
/// <summary>The language of the feed (<c>en</c>, <c>it</c>), when it says.</summary>
public string? Language { get; init; }
/// <summary>Symbols the source attaches to the article (Alpaca News does; feeds do not).</summary>
public IReadOnlyList<string> Symbols { get; init; } = [];
}
/// <summary>
/// Reads RSS 2.0, RSS 1.0 and Atom with the framework's XML reader, without external components. A document type
/// declaration is ignored and nothing is ever downloaded from inside a feed: its text is untrusted data.
/// </summary>
public static partial class FeedParser
{
public const int MaxSummary = 600;
private static readonly XNamespace Atom = "http://www.w3.org/2005/Atom";
private static readonly XNamespace Rss1 = "http://purl.org/rss/1.0/";
private static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/";
/// <summary>The articles of a feed; a document that is not a feed gives a <see cref="FormatException"/>.</summary>
public static IReadOnlyList<FeedItem> Parse(Stream content)
{
ArgumentNullException.ThrowIfNull(content);
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Ignore,
XmlResolver = null,
MaxCharactersFromEntities = 1024,
MaxCharactersInDocument = 20_000_000,
IgnoreComments = true,
};
XDocument document;
try
{
using var reader = XmlReader.Create(content, settings);
document = XDocument.Load(reader);
}
catch (XmlException ex)
{
throw new FormatException("Il feed non è XML valido: " + ex.Message, ex);
}
var root = document.Root ?? throw new FormatException("Il feed è vuoto.");
var language = Language(root.Element("channel")?.Element("language")?.Value ?? root.Attribute(XNamespace.Xml + "lang")?.Value
?? root.Element(Rss1 + "channel")?.Element(Dc + "language")?.Value);
IEnumerable<FeedItem?> items = root.Name.LocalName switch
{
"rss" => root.Element("channel")?.Elements("item").Select(Rss) ?? [],
"RDF" => root.Elements(Rss1 + "item").Select(RdfItem),
"feed" when root.Name.Namespace == Atom => root.Elements(Atom + "entry").Select(AtomEntry),
_ => throw new FormatException("Formato di feed sconosciuto: " + root.Name.LocalName),
};
return items.OfType<FeedItem>().Select(i => i with { Language = i.Language ?? language }).ToList();
}
public static IReadOnlyList<FeedItem> Parse(byte[] content) => Parse(new MemoryStream(content ?? throw new ArgumentNullException(nameof(content))));
private static FeedItem? Rss(XElement item)
{
var link = item.Element("link")?.Value.Trim();
if (string.IsNullOrEmpty(link) && item.Element("guid") is { } guid && guid.Attribute("isPermaLink")?.Value != "false")
{
link = guid.Value.Trim();
}
return Make(item.Element("title")?.Value, link, item.Element("description")?.Value,
item.Element("pubDate")?.Value ?? item.Element(Dc + "date")?.Value, item.Element(Dc + "language")?.Value);
}
private static FeedItem? RdfItem(XElement item) =>
Make(item.Element(Rss1 + "title")?.Value, item.Element(Rss1 + "link")?.Value ?? item.Attribute(XName.Get("about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"))?.Value,
item.Element(Rss1 + "description")?.Value, item.Element(Dc + "date")?.Value, item.Element(Dc + "language")?.Value);
private static FeedItem? AtomEntry(XElement entry)
{
var links = entry.Elements(Atom + "link").ToList();
var link = links.FirstOrDefault(l => (l.Attribute("rel")?.Value ?? "alternate") == "alternate") ?? links.FirstOrDefault();
return Make(entry.Element(Atom + "title")?.Value, link?.Attribute("href")?.Value, entry.Element(Atom + "summary")?.Value ?? entry.Element(Atom + "content")?.Value,
entry.Element(Atom + "published")?.Value ?? entry.Element(Atom + "updated")?.Value, entry.Attribute(XNamespace.Xml + "lang")?.Value);
}
private static FeedItem? Make(string? title, string? link, string? summary, string? published, string? language)
{
var cleanTitle = Text(title, 300);
if (cleanTitle is null || string.IsNullOrWhiteSpace(link) || !Uri.TryCreate(link.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
{
return null;
}
return new FeedItem(cleanTitle, uri.AbsoluteUri)
{
Summary = Text(summary, MaxSummary),
PublishedAt = NewsDates.TryParse(published, out var at) ? at : null,
Language = Language(language),
};
}
/// <summary>Plain text from a feed field: tags out, entities decoded (twice, some feeds encode them twice), spaces collapsed.</summary>
public static string? Text(string? html, int max)
{
if (string.IsNullOrWhiteSpace(html))
{
return null;
}
var text = WebUtility.HtmlDecode(Tags().Replace(WebUtility.HtmlDecode(Tags().Replace(html, " ")), " "));
text = Spaces().Replace(Printable(text), " ").Trim();
if (text.Length == 0)
{
return null;
}
return Cut(text, max);
}
/// <summary>At most <paramref name="max"/> characters, never ending with half an emoji: half a character cannot be stored.</summary>
public static string Cut(string text, int max)
{
ArgumentNullException.ThrowIfNull(text);
if (text.Length <= max)
{
return text;
}
var end = max - 1;
return text[..(char.IsHighSurrogate(text[end - 1]) ? end - 1 : end)].TrimEnd() + "…";
}
// Control characters (PostgreSQL refuses the zero) and halves of characters become spaces.
private static string Printable(string text)
{
var clean = new StringBuilder(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
{
clean.Append(text[i]).Append(text[++i]);
}
else
{
clean.Append(char.IsSurrogate(text[i]) || char.IsControl(text[i]) ? ' ' : text[i]);
}
}
return clean.ToString();
}
private static string? Language(string? code) =>
string.IsNullOrWhiteSpace(code) ? null : code.Trim()[..Math.Min(2, code.Trim().Length)].ToLowerInvariant();
[GeneratedRegex("<[^>]*>")]
private static partial Regex Tags();
[GeneratedRegex(@"\s+")]
private static partial Regex Spaces();
}
/// <summary>The dates of the feeds: RFC 822 with any zone form (GMT, Z, +0100, EST), ISO 8601, or a bare time taken as UTC.</summary>
public static partial class NewsDates
{
private static readonly string[] Formats =
[
"ddd, d MMM yyyy HH:mm:ss zzz", "ddd, d MMM yyyy HH:mm zzz", "d MMM yyyy HH:mm:ss zzz", "d MMM yyyy HH:mm zzz",
"ddd, dd MMM yyyy HH:mm:ss zzz", "dddd, d MMMM yyyy HH:mm:ss zzz",
];
private static readonly Dictionary<string, string> Zones = new(StringComparer.OrdinalIgnoreCase)
{
["GMT"] = "+00:00",
["UT"] = "+00:00",
["UTC"] = "+00:00",
["Z"] = "+00:00",
["EST"] = "-05:00",
["EDT"] = "-04:00",
["CST"] = "-06:00",
["CDT"] = "-05:00",
["MST"] = "-07:00",
["MDT"] = "-06:00",
["PST"] = "-08:00",
["PDT"] = "-07:00",
["CET"] = "+01:00",
["CEST"] = "+02:00",
["BST"] = "+01:00",
};
public static bool TryParse(string? text, out DateTimeOffset moment)
{
moment = default;
if (string.IsNullOrWhiteSpace(text))
{
return false;
}
var value = Spaces().Replace(text.Trim(), " ");
var rfc = ZoneAtEnd().Match(value);
if (rfc.Success)
{
var zone = rfc.Groups["zone"].Value;
var offset = Zones.TryGetValue(zone, out var named) ? named
: zone.Length == 5 ? zone[..3] + ":" + zone[3..] : zone;
if (DateTimeOffset.TryParseExact(value[..rfc.Index] + " " + offset, Formats, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out moment))
{
moment = moment.ToUniversalTime();
return true;
}
}
if (DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out moment))
{
moment = moment.ToUniversalTime();
return true;
}
return false;
}
[GeneratedRegex(@"\s(?<zone>[+-]\d{2}:?\d{2}|[A-Za-z]{1,4})$")]
private static partial Regex ZoneAtEnd();
[GeneratedRegex(@"\s+")]
private static partial Regex Spaces();
}