From 64a7124889e00dd2dcb1c30cccfa1819ef8d0e72 Mon Sep 17 00:00:00 2001
From: Blomios
Date: Sun, 22 Nov 2026 17:17:15 +0100
Subject: [PATCH] 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
---
README.md | 2 +-
backend/cmd/server/main.go | 4 +-
.../migrations/000018_cnbc_business.down.sql | 3 +
.../migrations/000018_cnbc_business.up.sql | 16 ++
.../database/migrations/cnbc_business_test.go | 104 +++++++++++
.../generation/company_symbols_test.go | 8 +-
.../source_allowlist_ticket13_test.go | 7 +-
backend/internal/models/repository.go | 2 +-
backend/internal/models/source_support.go | 5 +-
.../internal/models/source_support_test.go | 15 ++
.../source_allowlist_ticket13_test.go | 9 +-
.../scraper/cnbcbusiness/cnbcbusiness.go | 166 ++++++++++++++++++
.../scraper/cnbcbusiness/cnbcbusiness_test.go | 105 +++++++++++
docs/operations.md | 9 +
frontend/src/components/GenerationDetails.tsx | 8 +-
frontend/src/pages/admin/Sources.tsx | 6 +-
frontend/tests/admin-article-limits.test.tsx | 35 +++-
.../source-diagnostics-ticket23.test.tsx | 33 ++++
18 files changed, 511 insertions(+), 26 deletions(-)
create mode 100644 backend/internal/database/migrations/000018_cnbc_business.down.sql
create mode 100644 backend/internal/database/migrations/000018_cnbc_business.up.sql
create mode 100644 backend/internal/database/migrations/cnbc_business_test.go
create mode 100644 backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
create mode 100644 backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
create mode 100644 frontend/tests/source-diagnostics-ticket23.test.tsx
diff --git a/README.md b/README.md
index 0c6edc2..58c146a 100644
--- a/README.md
+++ b/README.md
@@ -75,7 +75,7 @@ Laya est le moteur de classement dédié : adapter HTTP pour [Laya v0.5.2](https
Le modèle de synthèse est choisi par compte dans le catalogue admin `ai_provider_models`, indépendamment des anciens réglages globaux qui restent stockés mais inertes pour la génération. Sans sélection ou avec modèle désactivé/invalide, la génération échoue avec `summary_model_unavailable` avant source/Laya. Les nouvelles synthèses gardent un snapshot du provider et du modèle effectivement résolus ; les anciennes restent inconnues sur ces champs. Supprimer un modèle sélectionné renvoie 409.
-Tous les candidats des sources autorisées sont traités en mémoire ; sélection/ordre Laya puis plafonds source/global. Aucune nouvelle archive article. Le mode `title_content` reste enregistrable : si le contenu est absent ou égal au titre, le classement utilise explicitement le titre seul et compte ce fallback. Les synthèses et bilans agrégés sont persistés ; les anciennes archives restent intactes.
+Les sources exécutables sont Yahoo Finance, Bloomberg et CNBC Business ; WatcherGuru reste conservé mais désactivé et non supporté depuis la migration 000018. Tous les candidats des sources autorisées sont traités en mémoire ; sélection/ordre Laya puis plafonds source/global. Aucune nouvelle archive article. Le mode `title_content` reste enregistrable : si le contenu est absent ou égal au titre, le classement utilise explicitement le titre seul et compte ce fallback. Les synthèses et bilans agrégés sont persistés ; les anciennes archives restent intactes.
La PWA précharge les assets statiques, sans cache runtime des API privées. Son activation supprime l’ancien CacheStorage `api-cache`. Les données privées ne deviennent pas disponibles hors ligne. L’installation PWA exige un contexte sécurisé (HTTPS ou localhost).
diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go
index b3be5e2..515ea1d 100644
--- a/backend/cmd/server/main.go
+++ b/backend/cmd/server/main.go
@@ -13,7 +13,7 @@ import (
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/bloomberg"
- "github.com/tradarr/backend/internal/scraper/watcherguru"
+ "github.com/tradarr/backend/internal/scraper/cnbcbusiness"
"github.com/tradarr/backend/internal/scraper/yahoofinance"
"github.com/tradarr/backend/internal/server"
)
@@ -52,7 +52,7 @@ func main() {
feeds := map[string]scraper.Scraper{
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
models.SourceYahooFinance: yahoofinance.New(),
- models.SourceWatcherGuru: watcherguru.New(),
+ models.SourceCNBCBusiness: cnbcbusiness.New(),
}
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
diff --git a/backend/internal/database/migrations/000018_cnbc_business.down.sql b/backend/internal/database/migrations/000018_cnbc_business.down.sql
new file mode 100644
index 0000000..3c288c5
--- /dev/null
+++ b/backend/internal/database/migrations/000018_cnbc_business.down.sql
@@ -0,0 +1,3 @@
+-- Non-destructive retirement on downgrade: retain CNBC identity/history and
+-- permissive historical constraint values. Never auto-reactivate WatcherGuru.
+UPDATE sources SET enabled=false WHERE source_key='cnbc_business';
diff --git a/backend/internal/database/migrations/000018_cnbc_business.up.sql b/backend/internal/database/migrations/000018_cnbc_business.up.sql
new file mode 100644
index 0000000..bbbcff9
--- /dev/null
+++ b/backend/internal/database/migrations/000018_cnbc_business.up.sql
@@ -0,0 +1,16 @@
+-- Atomic even when executed as a standalone statement. Preserve retired source
+-- IDs, source keys, caps and all referencing history; never repurpose a row.
+DO $migration$
+BEGIN
+ LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
+ ALTER TABLE sources DROP CONSTRAINT sources_type_check;
+ ALTER TABLE sources ADD CONSTRAINT sources_type_check
+ CHECK (type IN ('bloomberg','stocktwits','reuters','watcherguru','cnbc_business'));
+ ALTER TABLE sources DROP CONSTRAINT sources_source_key_check;
+ ALTER TABLE sources ADD CONSTRAINT sources_source_key_check
+ CHECK (source_key IN ('yahoo_finance','bloomberg','watcher_guru','cnbc_business'));
+ UPDATE sources SET enabled=false WHERE source_key='watcher_guru';
+ INSERT INTO sources(id,name,type,enabled,article_limit,source_key)
+ VALUES(gen_random_uuid(),'CNBC Business','cnbc_business',true,20,'cnbc_business');
+END
+$migration$;
diff --git a/backend/internal/database/migrations/cnbc_business_test.go b/backend/internal/database/migrations/cnbc_business_test.go
new file mode 100644
index 0000000..d74ddfd
--- /dev/null
+++ b/backend/internal/database/migrations/cnbc_business_test.go
@@ -0,0 +1,104 @@
+package migrations
+
+import (
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestCNBCMigrationRetainsWatcherIdentityAndHistoricalReferencesPostgres(t *testing.T) {
+ db, cleanup := ticket13Database(t)
+ defer cleanup()
+ for _, q := range []string{
+ `ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
+ `INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
+ `INSERT INTO articles(id,source_id,title,url) VALUES('old-article','w','historic','https://fixture.invalid/history')`,
+ } {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ applyTicket13(t, db)
+ migration, err := os.ReadFile("000018_cnbc_business.up.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(string(migration)); err != nil {
+ t.Fatal(err)
+ }
+ var name, typ, key string
+ var enabled bool
+ var cap int
+ if err = db.QueryRow(`SELECT name,type,source_key,enabled,article_limit FROM sources WHERE id='w'`).Scan(&name, &typ, &key, &enabled, &cap); err != nil {
+ t.Fatal(err)
+ }
+ if name != "Watcher.Guru" || typ != "watcherguru" || key != "watcher_guru" || enabled || cap != 64 {
+ t.Fatal("Watcher identity/cap changed or still enabled")
+ }
+ var cnbcID string
+ if err = db.QueryRow(`SELECT id,enabled,article_limit FROM sources WHERE source_key='cnbc_business'`).Scan(&cnbcID, &enabled, &cap); err != nil {
+ t.Fatal(err)
+ }
+ if cnbcID == "w" || !regexp.MustCompile(`^[0-9a-f-]{36}$`).MatchString(cnbcID) || !enabled || cap != 20 {
+ t.Fatalf("new identity=%s enabled=%v cap=%d", cnbcID, enabled, cap)
+ }
+ var source string
+ if err = db.QueryRow(`SELECT source_id FROM articles WHERE id='old-article'`).Scan(&source); err != nil || source != "w" {
+ t.Fatalf("historical reference=%s err=%v", source, err)
+ }
+ if _, err = db.Exec(`UPDATE sources SET source_key='watcher_guru' WHERE id='w'`); err != nil {
+ t.Fatalf("legacy key no longer permitted by constraint: %v", err)
+ }
+ if _, err = db.Exec(`UPDATE sources SET source_key='unsupported' WHERE id='w'`); err == nil {
+ t.Fatal("unknown key accepted")
+ }
+ if _, err = db.Exec(`UPDATE sources SET type='unsupported' WHERE id='w'`); err == nil {
+ t.Fatal("unknown type accepted")
+ }
+ var count int
+ if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 4 {
+ t.Fatalf("unexpected source count=%d %v", count, err)
+ }
+ var yahooCap, bloombergCap int
+ if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='y'`).Scan(&yahooCap); err != nil {
+ t.Fatal(err)
+ }
+ if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='b'`).Scan(&bloombergCap); err != nil || yahooCap != 83 || bloombergCap != 77 {
+ t.Fatal("other caps changed")
+ }
+}
+
+func TestCNBCMigrationFailureRollsBackWatcherAndConstraintChangesPostgres(t *testing.T) {
+ db, cleanup := ticket13Database(t)
+ defer cleanup()
+ for _, q := range []string{
+ `ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
+ `INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
+ `ALTER TABLE sources ADD CONSTRAINT fixture_refuse_cnbc CHECK(name <> 'CNBC Business')`,
+ } {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ applyTicket13(t, db)
+ migration, err := os.ReadFile("000018_cnbc_business.up.sql")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = db.Exec(string(migration)); err == nil {
+ t.Fatal("expected insert failure")
+ }
+ var enabled bool
+ var count int
+ var constraint string
+ if err = db.QueryRow(`SELECT enabled FROM sources WHERE id='w'`).Scan(&enabled); err != nil || !enabled {
+ t.Fatal("failed migration disabled WatcherGuru")
+ }
+ if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 3 {
+ t.Fatal("failed migration changed source rows")
+ }
+ if err = db.QueryRow(`SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass AND conname='sources_source_key_check'`).Scan(&constraint); err != nil || strings.Contains(constraint, "cnbc_business") {
+ t.Fatal("failed migration changed source key constraint")
+ }
+}
diff --git a/backend/internal/generation/company_symbols_test.go b/backend/internal/generation/company_symbols_test.go
index 1c63452..b451514 100644
--- a/backend/internal/generation/company_symbols_test.go
+++ b/backend/internal/generation/company_symbols_test.go
@@ -29,18 +29,18 @@ func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, e
}
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
- yahoo, bloomberg, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
+ yahoo, bloomberg, cnbc, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
input := UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 20, Assets: []models.UserAsset{{CompanyID: pointer("isin:company"), Name: "Company", Symbol: "HISTORIC INDEX", YahooSymbol: pointer("9888.HK")}}}
- for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceWatcherGuru} {
+ for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness, models.SourceWatcherGuru} {
key := key
input.Sources = append(input.Sources, models.Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 20})
}
repo := &contractRepository{inputs: map[string]UserInput{"owner": input}, saved: map[string][]GenerationRecord{}}
- uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceWatcherGuru: watcher}})
+ uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceCNBCBusiness: cnbc, models.SourceWatcherGuru: watcher}})
if _, err := uc.Generate(context.Background(), "owner"); err != nil {
t.Fatal(err)
}
- if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(watcher.symbols, bloomberg.symbols) {
+ if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(cnbc.symbols, bloomberg.symbols) || watcher.symbols != nil {
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
}
}
diff --git a/backend/internal/generation/source_allowlist_ticket13_test.go b/backend/internal/generation/source_allowlist_ticket13_test.go
index e07e10b..bf66dad 100644
--- a/backend/internal/generation/source_allowlist_ticket13_test.go
+++ b/backend/internal/generation/source_allowlist_ticket13_test.go
@@ -14,6 +14,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
if err := json.Unmarshal([]byte(`[
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":20},
+ {"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
{"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20},
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20}
@@ -22,7 +23,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
}
repo := &contractRepository{inputs: map[string]UserInput{"user": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, saved: map[string][]GenerationRecord{}}
feeds := map[string]*contractScraper{}
- for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
+ for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
}
scrapers := map[string]scraper.Scraper{}
@@ -33,12 +34,12 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
if err != nil || result.Summary == nil {
t.Fatalf("generation result=%+v err=%v", result, err)
}
- for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
+ for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
if len(feeds[key].calls) != 1 {
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
}
}
- for _, key := range []string{"stocktwits", "reuters"} {
+ for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
if len(feeds[key].calls) != 0 {
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
}
diff --git a/backend/internal/models/repository.go b/backend/internal/models/repository.go
index 163319c..3840a34 100644
--- a/backend/internal/models/repository.go
+++ b/backend/internal/models/repository.go
@@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
s := &Source{}
err := r.db.QueryRow(`
- SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','watcher_guru')`, sourceType,
+ SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','cnbc_business')`, sourceType,
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
if err == sql.ErrNoRows {
return nil, nil
diff --git a/backend/internal/models/source_support.go b/backend/internal/models/source_support.go
index 7fe9d69..913faa6 100644
--- a/backend/internal/models/source_support.go
+++ b/backend/internal/models/source_support.go
@@ -3,12 +3,13 @@ package models
const (
SourceYahooFinance = "yahoo_finance"
SourceBloomberg = "bloomberg"
- SourceWatcherGuru = "watcher_guru"
+ SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
+ SourceCNBCBusiness = "cnbc_business"
)
func SupportedSourceKey(key string) bool {
switch key {
- case SourceYahooFinance, SourceBloomberg, SourceWatcherGuru:
+ case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness:
return true
}
return false
diff --git a/backend/internal/models/source_support_test.go b/backend/internal/models/source_support_test.go
index 58fc672..e1c33e4 100644
--- a/backend/internal/models/source_support_test.go
+++ b/backend/internal/models/source_support_test.go
@@ -22,3 +22,18 @@ func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
t.Fatal("disabled target support/operational mismatch")
}
}
+
+func TestCNBCReplacesWatcherGuruWithoutAliasingHistoricalIdentity(t *testing.T) {
+ cnbc, watcher := SourceCNBCBusiness, SourceWatcherGuru
+ sources := []Source{{ID: "new-cnbc", SourceKey: &cnbc, Enabled: true, ArticleLimit: 37}, {ID: "old-watcher", SourceKey: &watcher, Enabled: true, ArticleLimit: 64}}
+ if !sources[0].Supported() || sources[1].Supported() || sources[1].Operational() {
+ t.Fatal("retired WatcherGuru remains executable or CNBC unsupported")
+ }
+ operational := OperationalSources(sources)
+ if len(operational) != 1 || operational[0].ID != "new-cnbc" || operational[0].ArticleLimit != 37 {
+ t.Fatalf("operational=%+v", operational)
+ }
+ if *sources[1].SourceKey != "watcher_guru" || sources[1].ArticleLimit != 64 {
+ t.Fatal("historical identity or cap mutated")
+ }
+}
diff --git a/backend/internal/scheduler/source_allowlist_ticket13_test.go b/backend/internal/scheduler/source_allowlist_ticket13_test.go
index f98a0d5..2c465cd 100644
--- a/backend/internal/scheduler/source_allowlist_ticket13_test.go
+++ b/backend/internal/scheduler/source_allowlist_ticket13_test.go
@@ -46,14 +46,15 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
if err := json.Unmarshal([]byte(`[
{"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10},
{"id":"b","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":10},
- {"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
+ {"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
+ {"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":10},
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":10}]`), &sources); err != nil {
t.Fatal(err)
}
feeds := map[string]*ticket13Feed{}
scrapers := map[string]scraper.Scraper{}
- for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
+ for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
f := &ticket13Feed{}
feeds[key] = f
scrapers[key] = f
@@ -61,12 +62,12 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
uc := generation.NewUseCase(generation.Dependencies{Repository: ticket13Repository{generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, Scrapers: scrapers, Ranker: ticket13Ranker{}, Summarizer: ticket13Summary{}})
s := &Scheduler{users: ticket13Users{}, generationUseCase: uc}
s.run()
- for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
+ for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
if feeds[key].calls != 1 {
t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls)
}
}
- for _, key := range []string{"stocktwits", "reuters"} {
+ for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
if feeds[key].calls != 0 {
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
}
diff --git a/backend/internal/scraper/cnbcbusiness/cnbcbusiness.go b/backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
new file mode 100644
index 0000000..817ecee
--- /dev/null
+++ b/backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
@@ -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()), " ")
+}
diff --git a/backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go b/backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
new file mode 100644
index 0000000..a9b6f9c
--- /dev/null
+++ b/backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
@@ -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 := `- Business & markets https://www.cnbc.com/fixture.htmlAvailable RSS evidence.
]]>Mon, 02 Jan 2006 15:04:05 -0700- Duplicatehttps://www.cnbc.com/fixture.html
- No descriptionhttps://www.cnbc.com/empty.htmlinvalid
- Unsafejavascript:alert(1)
- Missing link
`
+ 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, "PRIVATE_TITLE