Collect news from the SPEC 4.4 feeds, group retold stories and link them to instruments (refs #56)

News is the first input of Phase 7. Every two minutes the "notizie" job asks each
enabled feed conditionally and backs off a failing one up to an hour.

- Parsing: RSS 2.0, RSS 1.0 and Atom are read without DTDs or entity expansion, so a
  hostile feed reads nothing from disk.
- Deduplication: articles are deduplicated by canonical URL.
- Grouping: retold titles join one story by word similarity within 48 hours, and
  independent publishers are counted by registrable domain.
- Linking: stories are linked to instruments by source symbols, cashtags, exchange
  tickers, coin tickers and capitalised company names; to the crypto or equity class
  or to the market by theme; to the source topic as a fallback.

ADR 0014 records the thresholds. The tests read a synthetic archive in each source's
real format and run on both engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-14 18:57:49 +01:00
1 parent 25e71b679f
commit f1ba452aba
21 files changed
+1549

No files matched your search

+5
View File
@@ -82,6 +82,7 @@ public sealed partial class MarketDataService : IDisposable
_universes = new UniverseStore(db, clock);
_builder = new UniverseBuilder(db, clock);
_states = new SourceStateStore(db, clock);
News = new News.NewsCollector(_http, db, clock, _logger);
}
public OkxClient Okx { get; }
@@ -92,6 +93,9 @@ public sealed partial class MarketDataService : IDisposable
public StoredMarketCalendar UsCalendar { get; }
/// <summary>The news sources of SPEC 4.4, read every 2 minutes on the same connection pool (issue #56).</summary>
public News.NewsCollector News { get; }
/// <summary>True while the live crypto feed is connected.</summary>
public bool LiveConnected => _okxCollector.Connected;
@@ -121,6 +125,7 @@ public sealed partial class MarketDataService : IDisposable
RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync)
{ MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) },
News.Job(),
];
/// <summary>
+73
View File
@@ -0,0 +1,73 @@
-- News (SPEC 10.2, issue #56): where they come from, each article, the groups of articles telling the same story,
-- and what each story is about.
-- A feed or an API. trusted is the "affidabile" label of 10.2, editable from the settings. topic is what the whole
-- source is about when an article names nothing: 'market' for the central banks, 'crypto' for the crypto press.
-- etag and last_modified make the next request conditional; failures counts the requests in a row that went wrong.
CREATE TABLE news_sources (
id {uuid} PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
kind TEXT NOT NULL,
trusted {bool} NOT NULL,
enabled {bool} NOT NULL,
topic TEXT,
etag TEXT,
last_modified TEXT,
last_checked_at {timestamp},
last_ok_at {timestamp},
failures INTEGER NOT NULL,
last_error TEXT,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
-- One story, told by one or more articles. sources counts the independent publishers (two feeds of the same
-- newspaper count once); trusted says whether at least one article came from a trusted source.
CREATE TABLE news_stories (
id {uuid} PRIMARY KEY,
title TEXT NOT NULL,
title_key TEXT NOT NULL,
published_at {timestamp} NOT NULL,
first_seen_at {timestamp} NOT NULL,
last_seen_at {timestamp} NOT NULL,
sources INTEGER NOT NULL,
trusted {bool} NOT NULL,
created_at {timestamp} NOT NULL,
updated_at {timestamp} NOT NULL
){strict};
CREATE INDEX news_stories_published ON news_stories (published_at);
-- One article. url_key is the address without tracking parameters, fragments and the other differences that do
-- not change the article: the same article is never stored twice.
CREATE TABLE news_items (
id {uuid} PRIMARY KEY,
story_id {uuid} NOT NULL REFERENCES news_stories (id),
source_id {uuid} NOT NULL REFERENCES news_sources (id),
url TEXT NOT NULL,
url_key TEXT NOT NULL UNIQUE,
publisher TEXT NOT NULL,
title TEXT NOT NULL,
summary TEXT,
language TEXT NOT NULL,
published_at {timestamp} NOT NULL,
created_at {timestamp} NOT NULL
){strict};
CREATE INDEX news_items_story ON news_items (story_id);
-- What a story is about: an instrument ('venue:symbol'), a class of instruments ('crypto', 'equity') or the market
-- in general ('market'). via says how the link was found: the symbols given by the source, a ticker in the text,
-- a name of the dictionary, a theme, or the topic of the source.
CREATE TABLE news_links (
id {uuid} PRIMARY KEY,
story_id {uuid} NOT NULL REFERENCES news_stories (id),
scope TEXT NOT NULL,
target TEXT NOT NULL,
via TEXT NOT NULL,
created_at {timestamp} NOT NULL,
UNIQUE (story_id, scope, target)
){strict};
CREATE INDEX news_links_target ON news_links (scope, target);
+205
View File
@@ -0,0 +1,205 @@
using System.Globalization;
using System.Net;
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(text, " ").Trim();
if (text.Length == 0)
{
return null;
}
return text.Length <= max ? text : text[..(max - 1)].TrimEnd() + "…";
}
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();
}
+317
View File
@@ -0,0 +1,317 @@
using System.Text.RegularExpressions;
using Anubis.Data;
namespace Anubis.News;
public static class LinkScopes
{
/// <summary>One instrument, as <c>venue:symbol</c>.</summary>
public const string Instrument = "instrument";
/// <summary>A class of instruments: <see cref="AssetClasses.Crypto"/> or <see cref="AssetClasses.Equity"/>.</summary>
public const string Class = "class";
/// <summary>The market in general: central banks, inflation, rates.</summary>
public const string Market = "market";
}
public static class LinkVia
{
public const string Source = "source";
public const string Ticker = "ticker";
public const string Name = "name";
public const string Theme = "theme";
public const string Topic = "topic";
}
/// <summary>What a story is about (SPEC 10.2, point 3).</summary>
public sealed record NewsLink(string Scope, string Target, string Via);
/// <summary>
/// The dictionary of 10.2, point 3: tickers and names of the instruments in the catalogue, names of the coins, and the
/// themes that concern a whole class or the market. A name is matched only where the text writes it with a capital
/// letter, and a name that is also a common word (Target, Block, Gap) needs its ticker: a wrong link would block an
/// instrument for nothing.
/// </summary>
public sealed partial class NewsLinker
{
private static readonly Dictionary<string, string> CoinNames = new(StringComparer.OrdinalIgnoreCase)
{
["Bitcoin"] = "BTC",
["Ether"] = "ETH",
["Ethereum"] = "ETH",
["Solana"] = "SOL",
["XRP"] = "XRP",
["Ripple"] = "XRP",
["Cardano"] = "ADA",
["Dogecoin"] = "DOGE",
["Polkadot"] = "DOT",
["Chainlink"] = "LINK",
["Litecoin"] = "LTC",
["Avalanche"] = "AVAX",
["Tron"] = "TRX",
["Toncoin"] = "TON",
["Stellar"] = "XLM",
["Uniswap"] = "UNI",
["Polygon"] = "POL",
["Aave"] = "AAVE",
["Tether"] = "USDT",
["USDC"] = "USDC",
["Shiba Inu"] = "SHIB",
["Sui"] = "SUI",
["Hedera"] = "HBAR",
["Near Protocol"] = "NEAR",
["Cosmos"] = "ATOM",
["Arbitrum"] = "ARB",
};
// Words of a theme, lower case: one of them in a title or summary links the story to the class or to the market.
private static readonly (string Scope, string Target, string[] Words)[] Themes =
[
(LinkScopes.Market, LinkScopes.Market,
[
"federal reserve", "fed", "fomc", "powell", "ecb", "bce", "banca centrale europea", "lagarde", "inflation", "inflazione", "cpi", "pce",
"payrolls", "nonfarm", "jobs report", "interest rate", "interest rates", "rate cut", "rate hike", "tassi", "recession", "recessione", "tariffs",
"tariff", "dazi", "treasury yields", "bond yields", "gdp", "pil",
]),
(LinkScopes.Class, AssetClasses.Crypto,
[
"crypto", "cryptocurrency", "cryptocurrencies", "criptovalute", "criptovaluta", "stablecoin", "stablecoins", "defi", "blockchain", "altcoin", "altcoins",
]),
(LinkScopes.Class, AssetClasses.Equity, ["wall street", "s&p 500", "nasdaq", "dow jones", "stock market", "borsa di new york", "russell 2000"]),
];
// Names that are also ordinary words: without a ticker they say nothing.
private static readonly HashSet<string> Ambiguous = new(StringComparer.OrdinalIgnoreCase)
{
"Target", "Block", "Gap", "Match", "Shift", "Live", "Snap", "Square", "Sea", "Box", "Zoom", "Open", "Best", "General", "First", "United",
"American", "National", "International", "Global", "Digital", "Energy", "Public", "Real", "Apple Hospitality", "Visa", "Ford", "Delta",
"Southern", "Dominion", "Progressive", "Equity", "Union", "Pioneer", "Alliance", "Carrier", "Discovery", "Hub", "Fox", "Coach", "Ball", "Cars",
"Opendoor", "Strategy", "Bank", "Group", "Holdings", "Trust", "Capital", "Partners", "Fund", "Index", "Arm", "Unity", "Nu", "Rent", "Lumen",
};
private static readonly string[] NameEndings =
[
" Common Stock", " Class A", " Class B", " Class C", " Ordinary Shares", " American Depositary", " Depositary", " ADS", " ADR", " Units", " Warrant",
];
private static readonly string[] Suffixes =
[
", Inc.", " Inc.", " Inc", ", Inc", " Incorporated", " Corporation", " Corp.", " Corp", " Company", " Co.", " Holdings", " Holding", " Group",
" Ltd.", " Ltd", " Limited", " plc", " PLC", " N.V.", " S.A.", " SE", " AG", " L.P.", " LP", " & Co", ",", ".com",
];
private readonly Dictionary<string, string> _equityTickers = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<string>> _coins = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<(string[] Words, string Target)>> _names = new(StringComparer.OrdinalIgnoreCase);
private NewsLinker()
{
}
public int Names => _names.Sum(n => n.Value.Count);
/// <summary>The dictionary of the instruments the bot knows: stocks of Alpaca and coins of OKX.</summary>
public static NewsLinker Build(IEnumerable<InstrumentSpec> instruments)
{
ArgumentNullException.ThrowIfNull(instruments);
var dictionary = new NewsLinker();
foreach (var spec in instruments)
{
var target = spec.Venue + ":" + spec.Symbol;
if (spec.AssetClass == AssetClasses.Crypto)
{
var coin = (spec.BaseCurrency ?? spec.Symbol.Split('-', '/')[0]).ToUpperInvariant();
if (!dictionary._coins.TryGetValue(coin, out var list))
{
dictionary._coins[coin] = list = [];
}
list.Add(target);
}
else if (spec.AssetClass == AssetClasses.Equity && spec.IsFund != true)
{
dictionary._equityTickers.TryAdd(spec.Symbol.ToUpperInvariant(), target);
if (CompanyName(spec.Name) is { } name)
{
dictionary.AddName(name, target);
if (name.EndsWith(".com", StringComparison.OrdinalIgnoreCase))
{
dictionary.AddName(name[..^4], target);
}
}
}
}
foreach (var (name, coin) in CoinNames)
{
if (dictionary._coins.TryGetValue(coin, out var targets))
{
foreach (var target in targets)
{
dictionary.AddName(name, target);
}
}
}
return dictionary;
}
/// <summary>"Apple Inc. Common Stock" → "Apple"; null when what remains is too short or an ordinary word.</summary>
public static string? CompanyName(string? name)
{
if (string.IsNullOrWhiteSpace(name))
{
return null;
}
var clean = name.Trim();
foreach (var ending in NameEndings)
{
var at = clean.IndexOf(ending, StringComparison.OrdinalIgnoreCase);
if (at > 0)
{
clean = clean[..at];
}
}
for (var changed = true; changed;)
{
changed = false;
foreach (var suffix in Suffixes)
{
if (suffix != ".com" && clean.EndsWith(suffix, StringComparison.Ordinal) && clean.Length > suffix.Length + 1)
{
clean = clean[..^suffix.Length].TrimEnd();
changed = true;
}
}
}
return clean.Length < 3 || Ambiguous.Contains(clean) ? null : clean;
}
/// <summary>
/// The links of one article. Without any link to an instrument, a class or the market, the topic of the source
/// (if it has one) stands for the article.
/// </summary>
public IReadOnlyList<NewsLink> Link(string title, string? summary, IEnumerable<string>? sourceSymbols = null, string? topic = null)
{
ArgumentNullException.ThrowIfNull(title);
var links = new List<NewsLink>();
void Add(string scope, string target, string via)
{
if (!links.Any(l => l.Scope == scope && l.Target == target))
{
links.Add(new NewsLink(scope, target, via));
}
}
foreach (var symbol in sourceSymbols ?? [])
{
var upper = symbol.Trim().ToUpperInvariant();
if (_equityTickers.TryGetValue(upper, out var stock))
{
Add(LinkScopes.Instrument, stock, LinkVia.Source);
}
else if (_coins.TryGetValue(upper.Split('-', '/')[0].Replace("USD", "", StringComparison.Ordinal), out var coins))
{
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Source));
}
}
var text = title + " " + (summary ?? "");
foreach (Match match in Cashtag().Matches(text).Concat(ExchangeTicker().Matches(text)))
{
var ticker = match.Groups["t"].Value;
if (_equityTickers.TryGetValue(ticker, out var stock))
{
Add(LinkScopes.Instrument, stock, LinkVia.Ticker);
}
else if (_coins.TryGetValue(ticker, out var coins))
{
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
}
}
var words = Words().Matches(text).Select(m => Possessive().Replace(m.Value, "").TrimEnd('.')).Where(w => w.Length > 0).ToList();
for (var i = 0; i < words.Count; i++)
{
// A coin's ticker in capitals (BTC, ETH, SOL) is a link: news write them that way.
if (words[i].Length >= 3 && words[i].All(char.IsUpper) && _coins.TryGetValue(words[i], out var coins))
{
coins.ForEach(c => Add(LinkScopes.Instrument, c, LinkVia.Ticker));
}
if (!char.IsUpper(words[i][0]) || !_names.TryGetValue(words[i], out var candidates))
{
continue;
}
foreach (var (nameWords, target) in candidates.OrderByDescending(c => c.Words.Length))
{
if (i + nameWords.Length <= words.Count
&& nameWords.Select((w, k) => string.Equals(w, words[i + k], StringComparison.OrdinalIgnoreCase)).All(x => x))
{
Add(LinkScopes.Instrument, target, LinkVia.Name);
break;
}
}
}
// "(NASDAQ: AAPL)" names the listing of one company, not the stock market as a whole.
var themed = ExchangeTicker().Replace(text, " ");
var lower = " " + Spaces().Replace(NonWord().Replace(themed.ToLowerInvariant(), " "), " ") + " ";
foreach (var (scope, target, themeWords) in Themes)
{
if (themeWords.Any(w => lower.Contains(" " + w + " ", StringComparison.Ordinal)))
{
Add(scope, target, LinkVia.Theme);
}
}
if (links.Count == 0 && topic is { Length: > 0 })
{
links.Add(topic == LinkScopes.Market ? new NewsLink(LinkScopes.Market, LinkScopes.Market, LinkVia.Topic) : new NewsLink(LinkScopes.Class, topic, LinkVia.Topic));
}
return links;
}
private void AddName(string name, string target)
{
var words = Words().Matches(name).Select(m => m.Value.TrimEnd('.')).Where(w => w.Length > 0).ToArray();
if (words.Length == 0 || (words.Length == 1 && (words[0].Length < 3 || Ambiguous.Contains(words[0]))))
{
return;
}
if (!_names.TryGetValue(words[0], out var list))
{
_names[words[0]] = list = [];
}
if (!list.Any(l => l.Target == target && l.Words.SequenceEqual(words, StringComparer.OrdinalIgnoreCase)))
{
list.Add((words, target));
}
}
[GeneratedRegex(@"\$(?<t>[A-Z]{1,6})\b")]
private static partial Regex Cashtag();
[GeneratedRegex(@"\((?:NASDAQ|Nasdaq|NYSE|NYSE American|NYSE Arca|AMEX|Cboe|OTC)\s*:\s*(?<t>[A-Z][A-Z.]{0,5})\)")]
private static partial Regex ExchangeTicker();
[GeneratedRegex(@"[\p{L}\p{N}][\p{L}\p{N}&'.\-]*")]
private static partial Regex Words();
[GeneratedRegex(@"['’]s$")]
private static partial Regex Possessive();
[GeneratedRegex(@"[^\p{L}\p{N}&]+")]
private static partial Regex NonWord();
[GeneratedRegex(@"\s+")]
private static partial Regex Spaces();
}
+153
View File
@@ -0,0 +1,153 @@
using System.Globalization;
using System.Text;
namespace Anubis.News;
/// <summary>
/// The cleaning and grouping of 10.2, point 2: the same article is recognised by its address, the same story told by
/// two newspapers by the words of the titles, and two feeds of the same newspaper are one publisher, not two.
/// </summary>
public static class NewsMatching
{
/// <summary>Two titles share at least this part of their words (Jaccard): the same story.</summary>
public const double SameStory = 0.5;
/// <summary>Or the shorter title is almost all inside the longer one.</summary>
public const double Contained = 0.8;
/// <summary>Retellings of a story arrive within two days of the first article; later ones are a new story.</summary>
public static readonly TimeSpan StoryWindow = TimeSpan.FromHours(48);
// Parameters that only say where the reader came from: they never change the article.
private static readonly string[] TrackingPrefixes = ["utm_", "mc_", "at_", "pk_", "ga_"];
private static readonly HashSet<string> TrackingNames = new(StringComparer.OrdinalIgnoreCase)
{
"ref", "src", "source", "cmpid", "mod", "fbclid", "gclid", "dclid", "msclkid", "ito", "taid", "mbid", "trk", "partnerid", "yptr", "guccounter",
"rss", "feed", "output", "cid",
};
// Short words of English and Italian that say nothing about which story it is.
private static readonly HashSet<string> StopWords = new(StringComparer.Ordinal)
{
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "have", "in", "into", "is", "it", "its", "of", "on", "or", "over",
"says", "say", "said", "the", "to", "up", "was", "were", "will", "with", "after", "amid", "new", "this", "that", "what", "why", "how",
"il", "lo", "la", "i", "gli", "le", "un", "uno", "una", "di", "del", "della", "dei", "delle", "da", "dal", "dalla", "in", "nel", "nella", "su",
"sul", "sulla", "per", "con", "tra", "fra", "e", "ed", "o", "che", "non", "si", "al", "alla", "ai", "alle", "come", "piu", "anche", "ma",
};
private static readonly HashSet<string> SecondLevel = new(StringComparer.Ordinal) { "co", "com", "org", "net", "gov", "ac", "edu" };
/// <summary>
/// The address without what does not change the article: scheme, <c>www.</c>, fragment, double slashes, a final
/// slash and the tracking parameters. The remaining parameters are sorted.
/// </summary>
public static string UrlKey(string url)
{
ArgumentNullException.ThrowIfNull(url);
if (!Uri.TryCreate(url.Trim(), UriKind.Absolute, out var uri))
{
return url.Trim().ToLowerInvariant();
}
var host = Host(uri);
var path = uri.AbsolutePath;
while (path.Contains("//", StringComparison.Ordinal))
{
path = path.Replace("//", "/", StringComparison.Ordinal);
}
if (path.Length > 1)
{
path = path.TrimEnd('/');
}
var query = uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)
.Where(p => p.Split('=', 2)[0] is var name && !TrackingNames.Contains(name) && !TrackingPrefixes.Any(t => name.StartsWith(t, StringComparison.OrdinalIgnoreCase)))
.Order(StringComparer.Ordinal)
.ToList();
return host + path + (query.Count == 0 ? "" : "?" + string.Join('&', query));
}
/// <summary>
/// Who published the article, from its address: the registrable domain, so <c>feeds.content.dowjones.io</c> giving
/// an article of <c>www.marketwatch.com</c> is MarketWatch, and <c>news.example.co.uk</c> is <c>example.co.uk</c>.
/// </summary>
public static string Publisher(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
return "?";
}
var labels = Host(uri).Split('.');
var take = labels.Length >= 3 && labels[^1].Length == 2 && SecondLevel.Contains(labels[^2]) ? 3 : 2;
return string.Join('.', labels.TakeLast(Math.Min(take, labels.Length)));
}
/// <summary>The words that tell the story: lower case, without accents and punctuation, without short common words.</summary>
public static IReadOnlySet<string> Words(string title)
{
ArgumentNullException.ThrowIfNull(title);
var plain = new StringBuilder(title.Length);
foreach (var c in title.Normalize(NormalizationForm.FormD))
{
var category = CharUnicodeInfo.GetUnicodeCategory(c);
if (category == UnicodeCategory.NonSpacingMark)
{
continue;
}
plain.Append(char.IsLetterOrDigit(c) ? char.ToLowerInvariant(c) : ' ');
}
return plain.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(w => w.Length > 3 && w.EndsWith('s') && !w.EndsWith("ss", StringComparison.Ordinal) ? w[..^1] : w)
.Where(w => !StopWords.Contains(w) && (w.Length >= 2 || char.IsDigit(w[0])))
.ToHashSet(StringComparer.Ordinal);
}
/// <summary>The words of a title as stored: sorted and joined, so a story can be compared without the original title.</summary>
public static string TitleKey(string title) => string.Join(' ', Words(title).Order(StringComparer.Ordinal));
public static IReadOnlySet<string> KeyWords(string titleKey) =>
(titleKey ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).ToHashSet(StringComparer.Ordinal);
/// <summary>
/// Whether two titles tell the same story. Titles of fewer than three words must be equal: too few words make
/// any two titles look alike.
/// </summary>
public static bool Similar(IReadOnlySet<string> a, IReadOnlySet<string> b)
{
ArgumentNullException.ThrowIfNull(a);
ArgumentNullException.ThrowIfNull(b);
if (a.Count == 0 || b.Count == 0)
{
return false;
}
var common = a.Count(b.Contains);
if (Math.Min(a.Count, b.Count) < 3)
{
return common == a.Count && common == b.Count;
}
var jaccard = (double)common / (a.Count + b.Count - common);
var contained = (double)common / Math.Min(a.Count, b.Count);
return jaccard >= SameStory || (Math.Min(a.Count, b.Count) >= 4 && contained >= Contained);
}
public static double Score(IReadOnlySet<string> a, IReadOnlySet<string> b)
{
ArgumentNullException.ThrowIfNull(a);
ArgumentNullException.ThrowIfNull(b);
var common = a.Count(b.Contains);
return a.Count + b.Count - common == 0 ? 0 : (double)common / (a.Count + b.Count - common);
}
private static string Host(Uri uri)
{
var host = uri.Host.ToLowerInvariant();
return host.StartsWith("www.", StringComparison.Ordinal) ? host[4..] : host;
}
}
+167
View File
@@ -0,0 +1,167 @@
using System.Net;
using System.Net.Http.Headers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Anubis.News;
/// <summary>
/// Reads the news sources every 2 minutes (SPEC 4.4, 10.2 point 1): one request at a time with a pause between two,
/// conditional on what the source said the last time (ETag, Last-Modified), and spaced out more and more for a source
/// that keeps failing. The text it reads is untrusted data: it is parsed, never followed.
/// </summary>
public sealed partial class NewsCollector(HttpClient http, Database db, IClock clock, ILogger? logger = null)
{
public const string JobName = "notizie";
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(2);
/// <summary>A failing source is tried again after 2, 4, 8… minutes, at most every hour.</summary>
public static readonly TimeSpan MaxBackoff = TimeSpan.FromHours(1);
/// <summary>The longest answer read from a source.</summary>
public const int MaxBytes = 5 * 1024 * 1024;
private readonly ILogger _logger = logger ?? NullLogger.Instance;
private readonly NewsStore _store = new(db, clock);
private readonly InstrumentCatalog _catalog = new(db, clock);
private (DateTimeOffset At, NewsLinker Dictionary)? _dictionary;
/// <summary>The pause between two requests: politeness towards the sources, zero in the tests.</summary>
public TimeSpan Pause { get; init; } = TimeSpan.FromSeconds(1);
public NewsStore Store => _store;
public ScheduledJob Job() => new(JobName, "Lettura delle notizie", Schedule.Every(Interval), RunOnceAsync) { MaxLateness = Interval };
/// <summary>One round over the sources that are due.</summary>
public async Task RunOnceAsync(CancellationToken cancellationToken)
{
await _store.EnsureDefaultsAsync(cancellationToken).ConfigureAwait(false);
var dictionary = await DictionaryAsync(cancellationToken).ConfigureAwait(false);
var first = true;
foreach (var source in await _store.ListSourcesAsync(cancellationToken).ConfigureAwait(false))
{
if (!source.Enabled || source.Kind != NewsSourceKinds.Rss || !Due(source, clock.UtcNow))
{
continue;
}
if (!first && Pause > TimeSpan.Zero)
{
await clock.WaitUntilAsync(clock.UtcNow + Pause, cancellationToken).ConfigureAwait(false);
}
first = false;
await ReadAsync(source, dictionary, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Whether a source is due: always while it answers, later and later while it fails.</summary>
public static bool Due(NewsSource source, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(source);
if (source.Failures == 0 || source.LastCheckedAt is not { } last)
{
return true;
}
var wait = TimeSpan.FromTicks(Math.Min(MaxBackoff.Ticks, Interval.Ticks << Math.Min(source.Failures - 1, 10)));
return now - last >= wait - TimeSpan.FromSeconds(5);
}
public async Task<IngestResult?> ReadAsync(NewsSource source, NewsLinker dictionary, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(source);
using var request = new HttpRequestMessage(HttpMethod.Get, source.Url);
request.Headers.Accept.ParseAdd("application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.8, */*;q=0.1");
if (source.ETag is { } etag && EntityTagHeaderValue.TryParse(etag, out var tag))
{
request.Headers.IfNoneMatch.Add(tag);
}
if (source.LastModified is { } modified && DateTimeOffset.TryParse(modified, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out var since))
{
request.Headers.IfModifiedSince = since;
}
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.NotModified)
{
await _store.RecordCheckAsync(source, ok: true, source.ETag, source.LastModified, null, cancellationToken).ConfigureAwait(false);
return new IngestResult(0, 0, 0, 0);
}
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"La fonte ha risposto {(int)response.StatusCode}.");
}
var content = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
var items = FeedParser.Parse(content);
var result = await _store.IngestAsync(source, items, dictionary, cancellationToken).ConfigureAwait(false);
await _store.RecordCheckAsync(source, ok: true, response.Headers.ETag?.ToString(), response.Content.Headers.LastModified?.ToString("R"), null, cancellationToken)
.ConfigureAwait(false);
if (result.Added > 0)
{
LogRead(_logger, source.Name, result.Added, result.Stories);
}
return result;
}
catch (Exception ex) when (ex is HttpRequestException or FormatException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
LogFailed(_logger, source.Name, ex.Message);
await _store.RecordCheckAsync(source, ok: false, null, null, ex is OperationCanceledException ? "Nessuna risposta in 30 secondi." : ex.Message, cancellationToken)
.ConfigureAwait(false);
return null;
}
}
/// <summary>The dictionary of names, built from the catalogue once an hour: the catalogue changes once a day.</summary>
public async Task<NewsLinker> DictionaryAsync(CancellationToken cancellationToken)
{
if (_dictionary is { } cached && clock.UtcNow - cached.At < TimeSpan.FromHours(1))
{
return cached.Dictionary;
}
var instruments = await _catalog.ListAsync(null, cancellationToken).ConfigureAwait(false);
var dictionary = NewsLinker.Build(instruments.Where(i => i.Venue is Venues.Okx or Venues.Alpaca && i.IsLive).Select(i => i.Spec));
_dictionary = (clock.UtcNow, dictionary);
return dictionary;
}
private static async Task<byte[]> ReadLimitedAsync(HttpContent content, CancellationToken cancellationToken)
{
await using var stream = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var buffer = new MemoryStream();
var chunk = new byte[81920];
int read;
while ((read = await stream.ReadAsync(chunk, cancellationToken).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > MaxBytes)
{
throw new FormatException("La risposta supera 5 MB.");
}
buffer.Write(chunk, 0, read);
}
return buffer.ToArray();
}
[LoggerMessage(Level = LogLevel.Information, Message = "News from {Source}: {Added} new articles in {Stories} stories")]
private static partial void LogRead(ILogger logger, string source, int added, int stories);
[LoggerMessage(Level = LogLevel.Warning, Message = "News source {Source} failed: {Error}")]
private static partial void LogFailed(ILogger logger, string source, string error);
}
+224
View File
@@ -0,0 +1,224 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.News;
public static class NewsSourceKinds
{
public const string Rss = "rss";
public const string Alpaca = "alpaca";
public const string Sec = "sec";
}
/// <summary>A source of news as stored; <see cref="Trusted"/> is the "affidabile" label of 10.2.</summary>
public sealed record NewsSource(Guid Id, string Url, string Name, string Kind, bool Trusted, bool Enabled, string? Topic)
{
public string? ETag { get; init; }
public string? LastModified { get; init; }
public DateTimeOffset? LastCheckedAt { get; init; }
public DateTimeOffset? LastOkAt { get; init; }
public int Failures { get; init; }
public string? LastError { get; init; }
}
/// <summary>What one round of ingestion did.</summary>
public sealed record IngestResult(int Added, int Duplicates, int Stories, int Old);
/// <summary>
/// The news of SPEC 10.2, points 1–3, in the database: the sources with their state, and each article grouped with
/// the other articles of the same story and linked to what it is about.
/// </summary>
public sealed class NewsStore(Database db, IClock clock)
{
/// <summary>Articles older than this when they first arrive are history, not news: they are not stored.</summary>
public static readonly TimeSpan MaxAge = TimeSpan.FromDays(3);
/// <summary>The feeds of SPEC 4.4 that answered on 9 October 2026, trusted as 10.2 says.</summary>
public static IReadOnlyList<NewsSource> Defaults { get; } =
[
Rss("https://www.federalreserve.gov/feeds/press_all.xml", "Federal Reserve", trusted: true, LinkScopes.Market),
Rss("https://www.ecb.europa.eu/rss/press.html", "BCE", trusted: true, LinkScopes.Market),
Rss("https://www.sec.gov/news/pressreleases.rss", "SEC", trusted: true, null),
Rss("https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "CNBC", trusted: true, null),
Rss("https://feeds.content.dowjones.io/public/rss/mw_topstories", "MarketWatch", trusted: true, null),
Rss("https://www.investing.com/rss/news.rss", "Investing.com", trusted: false, null),
Rss("https://xml.fxstreet.com/news/forex-news/index.xml", "FXStreet", trusted: false, null),
Rss("https://investinglive.com/feed/news", "investingLive", trusted: false, null),
Rss("https://www.coindesk.com/arc/outboundfeeds/rss/", "CoinDesk", trusted: true, Data.AssetClasses.Crypto),
Rss("https://cointelegraph.com/rss", "Cointelegraph", trusted: false, Data.AssetClasses.Crypto),
Rss("https://www.theblock.co/rss.xml", "The Block", trusted: false, Data.AssetClasses.Crypto),
Rss("https://decrypt.co/feed", "Decrypt", trusted: false, Data.AssetClasses.Crypto),
Rss("https://www.ilsole24ore.com/rss/finanza.xml", "Il Sole 24 Ore", trusted: true, null),
Rss("https://www.ansa.it/sito/notizie/economia/economia_rss.xml", "ANSA", trusted: true, null),
];
private const string SourceColumns = "id, url, name, kind, trusted, enabled, topic, etag, last_modified, last_checked_at, last_ok_at, failures, last_error";
/// <summary>The first time: the default sources. Later the list is the user's, and a removed default stays removed.</summary>
public async Task EnsureDefaultsAsync(CancellationToken cancellationToken)
{
await db.WriteAsync(async s =>
{
if (await s.CountAsync("SELECT COUNT(*) FROM news_sources").ConfigureAwait(false) > 0)
{
return;
}
foreach (var source in Defaults)
{
await AddAsync(s, source, cancellationToken).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
}
public async Task<NewsSource> AddSourceAsync(string url, string name, string kind, bool trusted, string? topic, CancellationToken cancellationToken)
{
var source = new NewsSource(Guid.Empty, url, name, kind, trusted, Enabled: true, topic);
var id = await db.WriteAsync(s => AddAsync(s, source, cancellationToken), cancellationToken).ConfigureAwait(false);
return source with { Id = id };
}
public async Task<IReadOnlyList<NewsSource>> ListSourcesAsync(CancellationToken cancellationToken) =>
await db.ReadAsync(s => s.QueryAsync($"SELECT {SourceColumns} FROM news_sources ORDER BY name", ReadSource), cancellationToken).ConfigureAwait(false);
/// <summary>How the last request to a source went: on success the validators for the next conditional request.</summary>
public Task RecordCheckAsync(NewsSource source, bool ok, string? etag, string? lastModified, string? error, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(source);
var now = clock.UtcNow;
return db.WriteAsync(s => ok
? s.ExecuteAsync("UPDATE news_sources SET etag = @e, last_modified = @m, last_checked_at = @t, last_ok_at = @t, failures = 0, last_error = NULL, updated_at = @t WHERE id = @id",
cancellationToken, ("e", etag), ("m", lastModified), ("t", now), ("id", source.Id))
: s.ExecuteAsync("UPDATE news_sources SET last_checked_at = @t, failures = failures + 1, last_error = @err, updated_at = @t WHERE id = @id",
cancellationToken, ("t", now), ("err", error is null ? null : Redactor.Redact(error)[..Math.Min(300, Redactor.Redact(error).Length)]), ("id", source.Id)),
cancellationToken);
}
/// <summary>
/// Stores the new articles of a source. An article already stored (same address) is skipped; a new one joins the
/// story whose title it retells, within two days, or starts a new one. The story counts again its independent
/// publishers and whether a trusted source told it.
/// </summary>
public async Task<IngestResult> IngestAsync(NewsSource source, IReadOnlyList<FeedItem> items, NewsLinker dictionary, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(items);
ArgumentNullException.ThrowIfNull(dictionary);
var now = clock.UtcNow;
return await db.WriteAsync(async s =>
{
int added = 0, duplicates = 0, old = 0;
var touched = new HashSet<Guid>();
var stories = await s.QueryAsync("SELECT id, title_key, published_at FROM news_stories WHERE published_at >= @t",
r => (Id: r.Id("id"), Words: NewsMatching.KeyWords(r.Text("title_key")), Published: r.Moment("published_at")),
("t", now - MaxAge - NewsMatching.StoryWindow)).ConfigureAwait(false);
foreach (var item in items.OrderBy(i => i.PublishedAt ?? now))
{
var published = item.PublishedAt is { } p && p <= now ? p : now;
if (now - published > MaxAge)
{
old++;
continue;
}
var key = NewsMatching.UrlKey(item.Link);
if (await s.CountAsync("SELECT COUNT(*) FROM news_items WHERE url_key = @k", ("k", key)).ConfigureAwait(false) > 0)
{
duplicates++;
continue;
}
var words = NewsMatching.Words(item.Title);
var story = stories.Where(st => (published - st.Published).Duration() <= NewsMatching.StoryWindow && NewsMatching.Similar(words, st.Words))
.OrderByDescending(st => NewsMatching.Score(words, st.Words)).Select(st => (Guid?)st.Id).FirstOrDefault();
if (story is null)
{
story = Ids.NewId(clock);
await s.ExecuteAsync(
"INSERT INTO news_stories (id, title, title_key, published_at, first_seen_at, last_seen_at, sources, trusted, created_at, updated_at) " +
"VALUES (@id, @title, @key, @p, @now, @now, 1, @trusted, @now, @now)", cancellationToken,
("id", story), ("title", item.Title), ("key", NewsMatching.TitleKey(item.Title)), ("p", published), ("now", now), ("trusted", source.Trusted))
.ConfigureAwait(false);
stories.Add((story.Value, words, published));
}
await s.ExecuteAsync(
"INSERT INTO news_items (id, story_id, source_id, url, url_key, publisher, title, summary, language, published_at, created_at) " +
"VALUES (@id, @story, @source, @url, @key, @pub, @title, @summary, @lang, @p, @now)", cancellationToken,
("id", Ids.NewId(clock)), ("story", story), ("source", source.Id), ("url", item.Link), ("key", key), ("pub", NewsMatching.Publisher(item.Link)),
("title", item.Title), ("summary", item.Summary), ("lang", item.Language ?? Languages.Guess(item.Title + " " + item.Summary)), ("p", published),
("now", now)).ConfigureAwait(false);
foreach (var link in dictionary.Link(item.Title, item.Summary, item.Symbols, source.Topic))
{
await s.ExecuteAsync(
"INSERT INTO news_links (id, story_id, scope, target, via, created_at) VALUES (@id, @story, @scope, @target, @via, @now) " +
"ON CONFLICT (story_id, scope, target) DO NOTHING", cancellationToken,
("id", Ids.NewId(clock)), ("story", story), ("scope", link.Scope), ("target", link.Target), ("via", link.Via), ("now", now)).ConfigureAwait(false);
}
touched.Add(story.Value);
added++;
}
foreach (var id in touched)
{
await s.ExecuteAsync(
"UPDATE news_stories SET last_seen_at = @now, updated_at = @now, " +
"sources = (SELECT COUNT(DISTINCT publisher) FROM news_items WHERE story_id = @id), " +
"trusted = (SELECT COUNT(*) FROM news_items i JOIN news_sources so ON so.id = i.source_id WHERE i.story_id = @id AND so.trusted = @yes) > 0 " +
"WHERE id = @id", cancellationToken, ("now", now), ("id", id), ("yes", true)).ConfigureAwait(false);
}
return new IngestResult(added, duplicates, touched.Count, old);
}, cancellationToken).ConfigureAwait(false);
}
private static NewsSource Rss(string url, string name, bool trusted, string? topic) =>
new(Guid.Empty, url, name, NewsSourceKinds.Rss, trusted, Enabled: true, topic);
private async Task<Guid> AddAsync(DbSession s, NewsSource source, CancellationToken cancellationToken)
{
var id = Ids.NewId(clock);
var now = clock.UtcNow;
await s.ExecuteAsync(
"INSERT INTO news_sources (id, url, name, kind, trusted, enabled, topic, failures, created_at, updated_at) VALUES (@id, @url, @name, @kind, @trusted, @enabled, @topic, 0, @now, @now)",
cancellationToken, ("id", id), ("url", source.Url), ("name", source.Name), ("kind", source.Kind), ("trusted", source.Trusted), ("enabled", source.Enabled),
("topic", source.Topic), ("now", now)).ConfigureAwait(false);
return id;
}
private static NewsSource ReadSource(DbRow r) => new(r.Id("id"), r.Text("url"), r.Text("name"), r.Text("kind"), r.Bool("trusted"), r.Bool("enabled"), r.TextOrNull("topic"))
{
ETag = r.TextOrNull("etag"),
LastModified = r.TextOrNull("last_modified"),
LastCheckedAt = r.MomentOrNull("last_checked_at"),
LastOkAt = r.MomentOrNull("last_ok_at"),
Failures = (int)r.Number("failures"),
LastError = r.TextOrNull("last_error"),
};
}
/// <summary>Italian or English, for a text whose feed does not say: the classifier of 10.2 reads only English.</summary>
public static class Languages
{
private static readonly HashSet<string> Italian = new(StringComparer.Ordinal)
{
"il", "lo", "gli", "della", "delle", "dei", "degli", "nel", "nella", "sul", "sulla", "per", "con", "che", "non", "una", "alla", "anche", "sono", "più", "dopo",
};
private static readonly HashSet<string> English = new(StringComparer.Ordinal)
{
"the", "of", "and", "to", "in", "for", "with", "on", "is", "are", "as", "after", "from", "by", "its", "will", "has", "says",
};
public static string Guess(string text)
{
var words = (text ?? "").ToLowerInvariant().Split((char[])[' ', ',', '.', ':', ';', '\'', '"', '(', ')'], StringSplitOptions.RemoveEmptyEntries);
return words.Count(Italian.Contains) > words.Count(English.Contains) ? "it" : "en";
}
}