268 lines
7.4 KiB
Go
268 lines
7.4 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"
|
|
|
|
"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 && sameResponseArticle(source, target, resp) {
|
|
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(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"
|
|
}
|
|
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 {
|
|
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)
|
|
if evidence.mismatch {
|
|
return a
|
|
}
|
|
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) {
|
|
blocked = true
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
walk(c)
|
|
}
|
|
}
|
|
walk(doc)
|
|
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) {
|
|
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")
|
|
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
|
|
}
|
|
|
|
func sameResponseArticle(source, target string, resp *http.Response) bool {
|
|
if resp.Request == nil || resp.Request.URL == nil {
|
|
return true
|
|
}
|
|
actual, ok := safeURL(source, resp.Request.URL.String())
|
|
return ok && actual == target
|
|
}
|