259 lines
7.0 KiB
Go
259 lines
7.0 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"
|
|
"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()
|
|
}
|