feat(summary): send complete articles within user budget (#39)

This commit is contained in:
2026-11-24 17:39:26 +01:00
parent d0c7cb7cae
commit 79953ce49f
73 changed files with 1688 additions and 288 deletions

View File

@ -0,0 +1,258 @@
// Package articlecontent enriches bounded runtime pools using source-specific
// editorial roots. It never treats RSS summaries or generic page text as bodies.
package articlecontent
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/tradarr/backend/internal/scraper"
"golang.org/x/net/html"
)
const maxHTMLBytes = 16 * 1024 * 1024
func safeURL(source, value string) (string, bool) {
u, err := url.Parse(value)
if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || len(value) > 4096 {
return "", false
}
switch source {
case "yahoo_finance":
if u.Hostname() != "finance.yahoo.com" || !strings.HasPrefix(u.Path, "/news/") || !strings.HasSuffix(u.Path, ".html") {
return "", false
}
case "cnbc_business":
if u.Hostname() != "www.cnbc.com" || !strings.HasSuffix(u.Path, ".html") || len(u.Path) < 12 || u.Path[5] != '/' || u.Path[8] != '/' || u.Path[11] != '/' {
return "", false
}
default:
return "", false
}
u.RawQuery = ""
u.Fragment = ""
return u.String(), true
}
func Enrich(ctx context.Context, client *http.Client, source string, articles []scraper.Article) ([]scraper.Article, error) {
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
out := append([]scraper.Article(nil), articles...)
bounded := *client
bounded.Timeout = 15 * time.Second
bounded.CheckRedirect = func(r *http.Request, via []*http.Request) error {
if _, ok := safeURL(source, r.URL.String()); !ok || len(via) >= 3 {
return http.ErrUseLastResponse
}
return nil
}
cache := map[string]scraper.Article{}
for i, a := range out {
out[i].Content = ""
out[i].ContentTruncated = false
out[i].ContentState = scraper.ContentUnavailable
target, ok := safeURL(source, a.URL)
if !ok || ctx.Err() != nil {
continue
}
extracted, exists := cache[target]
if !exists {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
continue
}
req.Header.Set("User-Agent", "Tradarr/1.0")
req.Header.Set("Accept", "text/html")
extracted = scraper.Article{ContentState: scraper.ContentUnavailable}
resp, err := bounded.Do(req)
if err == nil {
if resp.StatusCode == http.StatusOK {
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
if readErr == nil && len(raw) <= maxHTMLBytes {
extracted = ExtractHTML(source, target, raw)
}
}
resp.Body.Close()
}
cache[target] = extracted
}
out[i].Content = extracted.Content
out[i].ContentState = extracted.ContentState
if extracted.PublishedAt != nil {
out[i].PublishedAt = extracted.PublishedAt
}
}
return out, nil
}
func attr(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
func hasClass(n *html.Node, want string) bool {
for _, v := range strings.Fields(attr(n, "class")) {
if v == want {
return true
}
}
return false
}
func excluded(n *html.Node) bool {
if n.Type != html.ElementNode {
return false
}
switch n.Data {
case "script", "style", "noscript", "nav", "aside", "footer", "header", "button", "form", "svg":
return true
}
for _, a := range n.Attr {
if a.Key == "hidden" || a.Key == "aria-hidden" && a.Val == "true" {
return true
}
}
for _, s := range []string{"related-stories", "advertisement", "disclaimer", "placeholder", "promo"} {
if strings.Contains(attr(n, "class")+" "+attr(n, "data-component"), s) {
return true
}
}
return false
}
func nodeText(n *html.Node) string {
if excluded(n) {
return ""
}
if n.Type == html.TextNode {
return n.Data
}
var b strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
b.WriteString(nodeText(c))
if c.Data == "br" {
b.WriteByte(' ')
}
}
return b.String()
}
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
a := scraper.Article{ContentState: scraper.ContentUnavailable}
if len(raw) > maxHTMLBytes {
return a
}
doc, err := html.Parse(bytes.NewReader(raw))
if err != nil {
return a
}
rootClass := ""
switch source {
case "yahoo_finance":
rootClass = "caas-body"
case "cnbc_business":
rootClass = "ArticleBody-articleBody"
default:
return a
}
var roots []*html.Node
blocked := false
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
if hasClass(n, rootClass) {
roots = append(roots, n)
}
if strings.Contains(strings.ToLower(attr(n, "class")), "paywall") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true" {
blocked = true
}
if n.Data == "meta" && attr(n, "property") == "article:published_time" {
if date, err := time.Parse(time.RFC3339Nano, attr(n, "content")); err == nil {
a.PublishedAt = &date
}
}
if n.Data == "script" && attr(n, "type") == "application/ld+json" {
// JSON-LD is used only for matching publication metadata/access flags.
// It never substitutes an unverified articleBody for the editorial root.
var values any
if json.Unmarshal([]byte(nText(n)), &values) == nil {
var inspect func(any)
inspect = func(v any) {
switch x := v.(type) {
case []any:
for _, v := range x {
inspect(v)
}
case map[string]any:
if graph, ok := x["@graph"]; ok {
inspect(graph)
}
typ, _ := x["@type"].(string)
u, _ := x["url"].(string)
if u == "" {
u, _ = x["@id"].(string)
}
if (typ == "NewsArticle" || typ == "Article") && u == articleURL {
if x["isAccessibleForFree"] == false || x["isAccessibleForFree"] == "False" {
blocked = true
}
if s, ok := x["datePublished"].(string); ok {
if date, err := time.Parse(time.RFC3339Nano, s); err == nil {
a.PublishedAt = &date
}
}
}
}
}
inspect(values)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
if len(roots) != 1 {
return a
}
paragraphs := []string{}
var collect func(*html.Node)
collect = func(n *html.Node) {
if excluded(n) {
return
}
if n.Type == html.ElementNode && (n.Data == "p" || n.Data == "h1" || n.Data == "h2" || n.Data == "h3" || n.Data == "h4" || n.Data == "h5" || n.Data == "h6" || n.Data == "li" || n.Data == "blockquote" || n.Data == "pre" || n.Data == "figcaption" || n.Data == "tr") {
text := strings.Join(strings.Fields(nodeText(n)), " ")
if text != "" {
paragraphs = append(paragraphs, text)
}
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
collect(c)
}
}
collect(roots[0])
a.Content = strings.Join(paragraphs, "\n\n")
if a.Content != "" {
a.ContentState = scraper.ContentComplete
if blocked {
a.ContentState = scraper.ContentIncomplete
}
}
return a
}
func nText(n *html.Node) string {
var b strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.TextNode {
b.WriteString(c.Data)
}
}
return b.String()
}

View File

@ -0,0 +1,75 @@
package articlecontent
import (
"context"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"os"
"strings"
"testing"
)
type roundTrip func(*http.Request) (*http.Response, error)
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestTicket39SourceFixtures(t *testing.T) {
for _, source := range []string{"yahoo_finance", "cnbc_business"} {
t.Run(source, func(t *testing.T) {
raw, err := os.ReadFile("testdata/" + source + ".html")
if err != nil {
t.Fatal(err)
}
a := ExtractHTML(source, "https://fixture.invalid/article", raw)
if a.ContentState != scraper.ContentComplete || !strings.Contains(a.Content, "Final editorial paragraph.") || strings.Contains(a.Content, "excluded") || a.PublishedAt == nil {
t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt)
}
a = ExtractHTML(source, "https://fixture.invalid/article", append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
if a.ContentState != scraper.ContentIncomplete {
t.Fatal("paywall claimed complete")
}
})
}
}
func TestTicket39FetchRestrictionsAndFullBody(t *testing.T) {
calls := 0
body := "<div class=caas-body><p>" + strings.Repeat("Full editorial paragraph. ", 2000) + "</p></div>"
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
})}
in := []scraper.Article{{Title: "original", URL: "https://finance.yahoo.com/news/fixture.html"}, {Title: "blocked", URL: "http://127.0.0.1/secret"}}
got, err := Enrich(context.Background(), client, "yahoo_finance", in)
if err != nil || calls != 1 || got[0].ContentState != scraper.ContentComplete || len(got[0].Content) < 30000 || got[0].Title != "original" || got[1].ContentState != scraper.ContentUnavailable {
t.Fatal("full extraction/restriction failed")
}
}
func TestTicket39UnrecognizedAndForeignMetadataDoNotInventContentOrDate(t *testing.T) {
for _, source := range []string{"yahoo_finance", "cnbc_business"} {
a := ExtractHTML(source, "https://fixture.invalid/current", []byte(`<html><body><main><p>Generic consent or navigation text.</p></main><script type="application/ld+json">{"@type":"NewsArticle","url":"https://fixture.invalid/other","articleBody":"not this article","datePublished":"2026-01-02T03:04:05Z"}</script></body></html>`))
if a.Content != "" || a.ContentState != scraper.ContentUnavailable || a.PublishedAt != nil {
t.Fatal("unverified content/date accepted")
}
}
}
func TestTicket39RedirectCannotLeaveSource(t *testing.T) {
calls := 0
client := &http.Client{Transport: roundTrip(func(*http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: 302, Body: io.NopCloser(strings.NewReader("PRIVATE_BODY")), Header: http.Header{"Location": []string{"http://127.0.0.1/private"}}}, nil
})}
got, err := Enrich(context.Background(), client, "yahoo_finance", []scraper.Article{{Title: "Fixture", URL: "https://finance.yahoo.com/news/fixture.html"}})
if err != nil || calls != 1 || got[0].ContentState != scraper.ContentUnavailable || got[0].Content != "" {
t.Fatal("redirect followed or private data returned")
}
}
func TestTicket39EditorialHeadingsListsAndQuotesAreNotDropped(t *testing.T) {
for _, tc := range []struct{ source, root string }{{"yahoo_finance", "caas-body"}, {"cnbc_business", "ArticleBody-articleBody"}} {
a := ExtractHTML(tc.source, "https://fixture.invalid/current", []byte(`<div class="`+tc.root+`"><h2>Editorial heading</h2><p>First paragraph.</p><ul><li>Editorial list item</li></ul><blockquote>Editorial quotation</blockquote></div>`))
for _, text := range []string{"Editorial heading", "First paragraph.", "Editorial list item", "Editorial quotation"} {
if !strings.Contains(a.Content, text) {
t.Fatal("editorial text omitted")
}
}
}
}

View File

@ -0,0 +1 @@
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><header>excluded navigation</header><div class="ArticleBody-articleBody"><div class="group"><p>Synthetic first editorial paragraph.</p><div data-component="related-stories"><p>excluded recommendation</p></div><p>Final editorial paragraph.</p></div></div></body></html>

View File

@ -0,0 +1 @@
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><nav>excluded navigation</nav><div class="caas-body"><p>Synthetic first editorial paragraph.</p><aside><p>excluded recommendation</p></aside><p>Final editorial paragraph.</p></div></body></html>