feat(sources): replace WatcherGuru with CNBC Business
Add the CNBC Business RSS source, switch supported-source wiring and reporting, and migrate existing WatcherGuru rows to disabled historical status without rewriting references. Refs #23 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
166
backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
Normal file
166
backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
Normal file
@ -0,0 +1,166 @@
|
||||
// Package cnbcbusiness reads only CNBC's configured Business RSS feed.
|
||||
// Article URLs are returned as metadata and are never fetched.
|
||||
package cnbcbusiness
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
const feedURL = "https://www.cnbc.com/id/10001147/device/rss/rss.html"
|
||||
const maxFeedBytes = 2 * 1024 * 1024
|
||||
|
||||
type CNBCBusiness struct{ client *http.Client }
|
||||
|
||||
func New() *CNBCBusiness {
|
||||
return &CNBCBusiness{client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
|
||||
}
|
||||
func (*CNBCBusiness) Name() string { return "cnbc_business" }
|
||||
|
||||
type rssItem struct {
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
PubDate string `xml:"pubDate"`
|
||||
}
|
||||
type rssChannel struct {
|
||||
Items []rssItem `xml:"item"`
|
||||
}
|
||||
type rssFeed struct {
|
||||
XMLName xml.Name `xml:"rss"`
|
||||
Channel *rssChannel `xml:"channel"`
|
||||
}
|
||||
|
||||
func (c *CNBCBusiness) Scrape(ctx context.Context, _ []string) (articles []scraper.Article, resultErr error) {
|
||||
status := 0
|
||||
cause := "none"
|
||||
defer func() {
|
||||
outcome := "ok"
|
||||
if resultErr != nil {
|
||||
outcome = "failed"
|
||||
}
|
||||
log.Printf("source=cnbc_business rss status=%d articles=%d outcome=%s cause=%s", status, len(articles), outcome, cause)
|
||||
}()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
|
||||
if err != nil {
|
||||
cause = "request"
|
||||
return nil, errors.New("cnbc_business: request failed")
|
||||
}
|
||||
req.Header.Set("User-Agent", "Tradarr/1.0")
|
||||
req.Header.Set("Accept", "application/rss+xml, application/xml, text/xml")
|
||||
response, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
cause = "transport"
|
||||
if ctx.Err() != nil {
|
||||
cause = "canceled_or_timeout"
|
||||
}
|
||||
return nil, errors.New("cnbc_business: transport or timeout failure")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
status = response.StatusCode
|
||||
if status != http.StatusOK {
|
||||
cause = "http_status"
|
||||
return nil, errors.New("cnbc_business: unexpected HTTP status")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxFeedBytes+1))
|
||||
if err != nil {
|
||||
cause = "read"
|
||||
return nil, errors.New("cnbc_business: feed read failed")
|
||||
}
|
||||
if len(body) > maxFeedBytes {
|
||||
cause = "too_large"
|
||||
return nil, errors.New("cnbc_business: feed exceeds size limit")
|
||||
}
|
||||
decoder := xml.NewDecoder(bytes.NewReader(body))
|
||||
var feed rssFeed
|
||||
if decoder.Decode(&feed) != nil || feed.Channel == nil {
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS feed")
|
||||
}
|
||||
// Allow trailing XML whitespace/comments, but never a second document or text.
|
||||
for {
|
||||
token, err := decoder.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS framing")
|
||||
}
|
||||
switch value := token.(type) {
|
||||
case xml.CharData:
|
||||
if strings.TrimSpace(string(value)) == "" {
|
||||
continue
|
||||
}
|
||||
case xml.Comment:
|
||||
continue
|
||||
}
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS framing")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
articles = make([]scraper.Article, 0, len(feed.Channel.Items))
|
||||
for _, item := range feed.Channel.Items {
|
||||
title := plainText(item.Title)
|
||||
link, err := url.Parse(strings.TrimSpace(item.Link))
|
||||
if title == "" || err != nil || link.Host == "" || link.User != nil || (link.Scheme != "https" && link.Scheme != "http") {
|
||||
continue
|
||||
}
|
||||
link.Fragment = ""
|
||||
canonical := link.String()
|
||||
if seen[canonical] {
|
||||
continue
|
||||
}
|
||||
seen[canonical] = true
|
||||
var published *time.Time
|
||||
for _, format := range []string{time.RFC1123Z, time.RFC1123, "Mon, 02 Jan 2006 15:04:05 -0700", time.RFC3339} {
|
||||
if parsed, err := time.Parse(format, strings.TrimSpace(item.PubDate)); err == nil {
|
||||
published = &parsed
|
||||
break
|
||||
}
|
||||
}
|
||||
articles = append(articles, scraper.Article{Title: title, URL: canonical, Content: plainText(item.Description), PublishedAt: published})
|
||||
}
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
// Parse description markup locally. Scripts/styles and comments are not evidence;
|
||||
// no missing description, date or article body is fabricated.
|
||||
func plainText(value string) string {
|
||||
document, err := html.Parse(strings.NewReader(value))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var text strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(node *html.Node) {
|
||||
if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {
|
||||
return
|
||||
}
|
||||
if node.Type == html.TextNode {
|
||||
text.WriteString(node.Data)
|
||||
}
|
||||
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "br" || node.Data == "li") {
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
walk(child)
|
||||
}
|
||||
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "li") {
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
walk(document)
|
||||
return strings.Join(strings.Fields(text.String()), " ")
|
||||
}
|
||||
105
backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
Normal file
105
backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
Normal file
@ -0,0 +1,105 @@
|
||||
package cnbcbusiness
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func TestCNBCBusinessRSSMapsMetadataWithoutArticleRequests(t *testing.T) {
|
||||
calls := 0
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.Method != "GET" || r.URL.String() != "https://www.cnbc.com/id/10001147/device/rss/rss.html" {
|
||||
t.Fatalf("unexpected request %s %s", r.Method, r.URL)
|
||||
}
|
||||
body := `<rss version="2.0"><channel><item><title> Business & markets </title><link>https://www.cnbc.com/fixture.html</link><description><![CDATA[<p>Available <b>RSS</b> evidence.</p><script>PRIVATE_SCRIPT</script>]]></description><pubDate>Mon, 02 Jan 2006 15:04:05 -0700</pubDate></item><item><title>Duplicate</title><link>https://www.cnbc.com/fixture.html</link></item><item><title>No description</title><link>https://www.cnbc.com/empty.html</link><pubDate>invalid</pubDate></item><item><title>Unsafe</title><link>javascript:alert(1)</link></item><item><title>Missing link</title></item></channel></rss>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), []string{"IGNORED"})
|
||||
if err != nil || len(got) != 2 || calls != 1 {
|
||||
t.Fatalf("articles=%+v calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
if feed.Name() != "cnbc_business" || got[0].Title != "Business & markets" || got[0].Content != "Available RSS evidence." || got[0].PublishedAt == nil || got[0].PublishedAt.Year() != 2006 {
|
||||
t.Fatalf("mapping=%+v", got[0])
|
||||
}
|
||||
if got[1].Content != "" || got[1].PublishedAt != nil {
|
||||
t.Fatalf("invented missing data=%+v", got[1])
|
||||
}
|
||||
}
|
||||
func TestCNBCBusinessFailsSafelyAndLogsOnlyDiagnostics(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"http", 503, "PRIVATE_RESPONSE https://secret.invalid/?key=PRIVATE_SECRET"},
|
||||
{"malformed", 200, "<rss><PRIVATE_ARTICLE"}, {"html", 200, "<html>PRIVATE_TITLE</html>"},
|
||||
{"trailing", 200, "<rss><channel/></rss>PRIVATE_PROMPT"}, {"oversize", 200, strings.Repeat("x", 2*1024*1024+1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
old := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(old)
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
if err == nil || len(got) != 0 {
|
||||
t.Fatalf("not fail-closed: %d %v", len(got), err)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "cnbc_business") || !strings.Contains(logs.String(), "status=") || !strings.Contains(logs.String(), "articles=0") {
|
||||
t.Fatalf("missing diagnostics: %q", logs.String())
|
||||
}
|
||||
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "PRIVATE_") || strings.Contains(err.Error(), "https://") {
|
||||
t.Fatal("sensitive response leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCBusinessDoesNotFollowRedirectOrLeakTransportError(t *testing.T) {
|
||||
for _, redirect := range []bool{false, true} {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
feed := New()
|
||||
calls := 0
|
||||
feed.client.Transport = fakeTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.String() != feedURL {
|
||||
t.Errorf("followed redirect to an article")
|
||||
}
|
||||
if !redirect {
|
||||
return nil, errors.New("PRIVATE_TRANSPORT https://private.invalid/article?key=secret")
|
||||
}
|
||||
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://private.invalid/article?key=secret"}}, Body: io.NopCloser(strings.NewReader("PRIVATE_RESPONSE"))}, nil
|
||||
})
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
log.SetOutput(previous)
|
||||
if err == nil || len(got) != 0 || calls != 1 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "https://") {
|
||||
t.Fatal("transport/redirect data leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCNBCBusinessEmptyRSSIsNoResults(t *testing.T) {
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("<rss><channel/></rss>"))}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("empty RSS: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user