Files

382 lines
11 KiB
Go

// 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"
"io"
"net/http"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/tradarr/backend/internal/scraper"
"golang.org/x/net/html"
)
const maxHTMLBytes = 16 * 1024 * 1024
// A listing may use an article path without a filename/date pattern. Trust
// only the exact source origin, upgrade HTTP before network I/O, and preserve
// semantic query parameters. The original Article.URL is never rewritten.
func safeURL(source, value string) (string, bool) {
u, err := url.Parse(value)
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Opaque != "" || u.User != nil || u.Port() != "" || len(value) > 4096 || u.Path == "" || u.Path == "/" {
return "", false
}
host := strings.ToLower(u.Hostname())
switch source {
case "yahoo_finance":
if host != "finance.yahoo.com" {
return "", false
}
case "cnbc_business":
if host != "www.cnbc.com" {
return "", false
}
default:
return "", false
}
u.Scheme = "https"
u.Host = host
u.Fragment = ""
return u.String(), true
}
func articleIdentity(source, value string) (string, bool) {
value, ok := safeURL(source, value)
if !ok {
return "", false
}
u, _ := url.Parse(value)
q := u.Query()
for k := range q {
if strings.HasPrefix(strings.ToLower(k), "utm_") || k == "guccounter" || k == "guce_referrer" || k == "guce_referrer_sig" {
q.Del(k)
}
}
u.RawQuery = q.Encode()
return u.String(), true
}
func Enrich(ctx context.Context, client *http.Client, source string, articles []scraper.Article) ([]scraper.Article, error) {
scraper.EnableFetchMetrics(ctx)
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
out := append([]scraper.Article(nil), articles...)
bounded := *client
bounded.Timeout = 15 * time.Second
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}
// Only an observed, validated redirect chain may change the fetch
// identity. Metadata may identify the initial or observed final URL.
verifiedFinal := target
requestClient := bounded
requestClient.CheckRedirect = func(r *http.Request, via []*http.Request) error {
normalized, ok := safeURL(source, r.URL.String())
if !ok || len(via) >= 3 {
return http.ErrUseLastResponse
}
parsed, _ := url.Parse(normalized)
r.URL = parsed
verifiedFinal = normalized
return nil
}
observation := scraper.FetchObservation{State: scraper.ContentUnavailable, CandidateBodySupported: true}
var trace *scraper.FetchObservation
if scraper.FetchMetricsEnabled(ctx) {
trace = &observation
}
resp, err := requestClient.Do(req)
if err != nil {
observation.Network = true
}
if err == nil {
observation.HTTPStatus = resp.StatusCode
responseMatches := true
if resp.Request != nil && resp.Request.URL != nil {
actual, ok := articleIdentity(source, resp.Request.URL.String())
expected, _ := articleIdentity(source, verifiedFinal)
responseMatches = ok && actual == expected
}
if !responseMatches {
observation.Identity = scraper.IdentityMismatch
}
if resp.StatusCode == http.StatusOK && responseMatches {
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
if readErr == nil && len(raw) <= maxHTMLBytes {
var aliases []string
if source == "yahoo_finance" {
aliases = []string{target}
}
extracted = extractHTML(source, verifiedFinal, raw, trace, aliases...)
}
}
resp.Body.Close()
}
observation.State = extracted.ContentState
scraper.RecordFetch(ctx, observation)
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(strings.ToLower(attr(n, "class")+" "+attr(n, "data-component")), s) {
return true
}
}
return false
}
func knownRoot(source string, n *html.Node) bool {
if n.Type != html.ElementNode {
return false
}
switch source {
case "yahoo_finance":
if hasClass(n, "caas-body") {
return true
}
if hasClass(n, "body") {
hashed := false
for _, c := range strings.Fields(attr(n, "class")) {
if strings.HasPrefix(c, "yf-") {
hashed = true
}
}
if hashed {
for p := n.Parent; p != nil; p = p.Parent {
if p.Type == html.ElementNode && p.Data == "article" {
return true
}
}
}
}
case "cnbc_business":
return hasClass(n, "ArticleBody-articleBody") || attr(n, "data-module") == "ArticleBody"
}
return false
}
func missingMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
return strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") || attr(n, "data-content-truncated") == "true" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete"
}
// Challenges may replace or overlay editorial content, so their scope is global.
func challengeMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
return strings.Contains(marker, "captcha") || strings.Contains(marker, "challenge") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.Contains(attr(n, "src"), "challenge-platform")
}
func accessMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
return strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || strings.Contains(marker, "captcha") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.HasPrefix(attr(n, "id"), "challenge") || strings.Contains(attr(n, "src"), "challenge-platform") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true"
}
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
return extractHTML(source, articleURL, raw, nil)
}
func extractHTML(source, articleURL string, raw []byte, observation *scraper.FetchObservation, aliases ...string) 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
}
evidence := inspectEvidence(doc, source, articleURL, aliases...)
var roots []*html.Node
blocked := evidence.blocked
var walk func(*html.Node)
walk = func(n *html.Node) {
if knownRoot(source, n) {
valid := true
for p := n; p != nil; p = p.Parent {
if excluded(p) {
valid = false
break
}
}
if valid {
roots = append(roots, n)
}
}
if accessMarker(n) && (source != "cnbc_business" || challengeMarker(n) || missingMarker(n)) {
blocked = true
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
extractionEvaluated := false
if observation != nil {
// Read-only diagnostics: never influence association, dates or completeness.
defer func() {
observeGranular(doc, roots, source, articleURL, aliases, a.Content, extractionEvaluated, observation)
}()
}
if source == "cnbc_business" {
// Generic subscription chrome is unrelated; article wrappers and their
// descendants still carry access restrictions. Challenges remain global.
var scan func(*html.Node)
scan = func(n *html.Node) {
if accessMarker(n) || missingMarker(n) {
blocked = true
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
scan(c)
}
}
for _, root := range roots {
scan(root)
for p := root.Parent; p != nil; p = p.Parent {
if accessMarker(p) || missingMarker(p) {
blocked = true
}
if p.Type == html.ElementNode && p.Data == "article" {
scan(p)
break
}
}
}
}
if observation != nil {
if len(roots) == 1 {
observation.CandidateBodyLength = candidateBodyLength(roots[0])
}
observation.Root = scraper.ObservedNo
if len(roots) == 1 {
observation.Root = scraper.ObservedYes
}
observation.Identity = scraper.IdentityNo
if evidence.associated {
observation.Identity = scraper.IdentityYes
}
if evidence.mismatch {
observation.Identity = scraper.IdentityMismatch
}
observation.Blocking = scraper.ObservedNo
if blocked {
observation.Blocking = scraper.ObservedYes
}
}
if evidence.mismatch {
return a
}
if evidence.associated && !evidence.dateConflict {
a.PublishedAt = evidence.date
}
if len(roots) != 1 {
return a
}
paragraphs := []string{}
var chunk strings.Builder
flush := func() {
text := strings.Join(strings.Fields(chunk.String()), " ")
if text != "" {
paragraphs = append(paragraphs, text)
}
chunk.Reset()
}
var collect func(*html.Node)
collect = func(n *html.Node) {
if missingMarker(n) {
if observation != nil {
observation.Blocking = scraper.ObservedYes
}
blocked = true
}
if excluded(n) {
return
}
if n.Type == html.TextNode {
chunk.WriteString(n.Data)
return
}
block := false
switch n.Data {
case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th":
block = true
}
if block {
flush()
}
if n.Data == "br" {
chunk.WriteByte(' ')
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
collect(c)
}
if block {
flush()
}
}
collect(roots[0])
flush()
a.Content = strings.Join(paragraphs, "\n\n")
extractionEvaluated = true
if observation != nil {
observation.Length = utf8.RuneCountInString(a.Content)
}
if evidence.fullBody != nil && strings.Join(strings.Fields(*evidence.fullBody), " ") != strings.Join(strings.Fields(a.Content), " ") {
blocked = true
}
if a.Content != "" {
a.ContentState = scraper.ContentIncomplete
if evidence.associated && !blocked {
a.ContentState = scraper.ContentComplete
}
}
return a
}