merge: integrate managed RSS feeds (#41)
This commit is contained in:
@ -8,13 +8,12 @@ import (
|
|||||||
"github.com/tradarr/backend/internal/ai"
|
"github.com/tradarr/backend/internal/ai"
|
||||||
"github.com/tradarr/backend/internal/companycatalog"
|
"github.com/tradarr/backend/internal/companycatalog"
|
||||||
"github.com/tradarr/backend/internal/config"
|
"github.com/tradarr/backend/internal/config"
|
||||||
"github.com/tradarr/backend/internal/crypto"
|
|
||||||
"github.com/tradarr/backend/internal/database"
|
"github.com/tradarr/backend/internal/database"
|
||||||
"github.com/tradarr/backend/internal/indices/openfigi"
|
"github.com/tradarr/backend/internal/indices/openfigi"
|
||||||
"github.com/tradarr/backend/internal/models"
|
"github.com/tradarr/backend/internal/models"
|
||||||
"github.com/tradarr/backend/internal/scraper"
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
|
||||||
"github.com/tradarr/backend/internal/scraper/cnbcbusiness"
|
"github.com/tradarr/backend/internal/scraper/cnbcbusiness"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/quanwenrss"
|
||||||
"github.com/tradarr/backend/internal/scraper/yahoofinance"
|
"github.com/tradarr/backend/internal/scraper/yahoofinance"
|
||||||
"github.com/tradarr/backend/internal/server"
|
"github.com/tradarr/backend/internal/server"
|
||||||
)
|
)
|
||||||
@ -48,14 +47,14 @@ func main() {
|
|||||||
if err := repo.RecoverGenerationJobs(context.Background()); err != nil {
|
if err := repo.RecoverGenerationJobs(context.Background()); err != nil {
|
||||||
log.Fatal("generation jobs: recovery failed")
|
log.Fatal("generation jobs: recovery failed")
|
||||||
}
|
}
|
||||||
enc := crypto.New(cfg.EncryptionKey)
|
|
||||||
|
|
||||||
if err := ensureAdmin(repo, cfg); err != nil {
|
if err := ensureAdmin(repo, cfg); err != nil {
|
||||||
log.Printf("ensure admin: %v", err)
|
log.Printf("ensure admin: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds := map[string]scraper.Scraper{
|
feeds := map[string]scraper.Scraper{
|
||||||
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
|
models.SourceBloomberg: quanwenrss.New(models.SourceBloomberg, repo, nil),
|
||||||
|
models.SourceInvesting: quanwenrss.New(models.SourceInvesting, repo, nil),
|
||||||
models.SourceYahooFinance: yahoofinance.New(),
|
models.SourceYahooFinance: yahoofinance.New(),
|
||||||
models.SourceCNBCBusiness: cnbcbusiness.New(),
|
models.SourceCNBCBusiness: cnbcbusiness.New(),
|
||||||
}
|
}
|
||||||
|
|||||||
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
@ -0,0 +1,146 @@
|
|||||||
|
package ai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/generation"
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/quanwenrss"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
)
|
||||||
|
|
||||||
|
type rss41Repo struct {
|
||||||
|
input generation.UserInput
|
||||||
|
saved generation.GenerationRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *rss41Repo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||||
|
return r.input, nil
|
||||||
|
}
|
||||||
|
func (r *rss41Repo) SaveGeneration(_ context.Context, _ string, record generation.GenerationRecord) error {
|
||||||
|
r.saved = record
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type rss41Loader struct{}
|
||||||
|
|
||||||
|
func (rss41Loader) SourceFeedURLs(_ context.Context, key string) ([]string, error) {
|
||||||
|
return sourcefeeds.Defaults(key), nil
|
||||||
|
}
|
||||||
|
func TestTicket41RSSMergeThreePassSelectionAndFullSummaryPrompt(t *testing.T) {
|
||||||
|
item := func(title, id, host, body string, full, dated bool) string {
|
||||||
|
date := ""
|
||||||
|
if dated {
|
||||||
|
date = "<pubDate>Fri, 02 Jan 2026 03:04:05 GMT</pubDate>"
|
||||||
|
}
|
||||||
|
field := "description"
|
||||||
|
if full {
|
||||||
|
field = "content:encoded"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(`<item><title>%s</title><link>https://%s/news/%s</link><guid>%s</guid>%s<%s><![CDATA[<article><p>%s</p></article>]]></%s></item>`, title, host, id, id, date, field, body, field)
|
||||||
|
}
|
||||||
|
literal := item("Watched Company literal", "literal", "www.bloomberg.com", "Synthetic full literal body.", true, true)
|
||||||
|
direct := item("Synthetic direct", "direct", "www.bloomberg.com", "Synthetic full direct body.", true, true)
|
||||||
|
indirect := item("Synthetic indirect", "indirect", "www.bloomberg.com", "Synthetic full indirect body.", true, true)
|
||||||
|
partial := item("Synthetic partial", "partial", "www.bloomberg.com", "Synthetic teaser excluded from Laya.", false, true)
|
||||||
|
investment := item("Synthetic investment", "investment", "www.investing.com", "Synthetic complete investment body.", true, false)
|
||||||
|
urls := sourcefeeds.Defaults(sourcefeeds.Bloomberg)
|
||||||
|
bodies := map[string]string{urls[0]: literal, urls[1]: literal + direct, urls[2]: indirect, urls[3]: partial, sourcefeeds.Defaults(sourcefeeds.Investing)[0]: investment}
|
||||||
|
fetches := 0
|
||||||
|
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
fetches++
|
||||||
|
if r.URL.Host != sourcefeeds.Host {
|
||||||
|
t.Fatal("article host was fetched")
|
||||||
|
}
|
||||||
|
status := 200
|
||||||
|
content, ok := bodies[r.URL.String()]
|
||||||
|
if !ok {
|
||||||
|
status = 503
|
||||||
|
}
|
||||||
|
body := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + content + `</channel></rss>`
|
||||||
|
return &http.Response{StatusCode: status, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})}
|
||||||
|
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||||
|
passes := []string{}
|
||||||
|
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
var payload struct {
|
||||||
|
States []struct{ Title, Content string }
|
||||||
|
Questions map[string]any
|
||||||
|
}
|
||||||
|
if json.NewDecoder(r.Body).Decode(&payload) != nil {
|
||||||
|
t.Fatal("invalid Laya request")
|
||||||
|
}
|
||||||
|
pass := ""
|
||||||
|
for key := range payload.Questions {
|
||||||
|
pass = key
|
||||||
|
}
|
||||||
|
passes = append(passes, pass)
|
||||||
|
results := []any{}
|
||||||
|
for _, state := range payload.States {
|
||||||
|
if strings.Contains(state.Title, "partial") || state.Title == "Watched Company literal" || state.Content == "" {
|
||||||
|
t.Fatal("partial article or literal first-pass selection leaked into Laya")
|
||||||
|
}
|
||||||
|
yes := state.Title == "Synthetic direct" || state.Title == "Synthetic investment"
|
||||||
|
if pass == "indirect_mention" {
|
||||||
|
yes = state.Title == "Synthetic indirect"
|
||||||
|
}
|
||||||
|
probability := 0.1
|
||||||
|
if yes {
|
||||||
|
probability = 0.9
|
||||||
|
}
|
||||||
|
results = append(results, map[string]any{"answers": map[string]any{pass: map[string]any{"type": "noul", "noul": probability, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1}})
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
|
||||||
|
})}
|
||||||
|
bloom, invest := models.SourceBloomberg, models.SourceInvesting
|
||||||
|
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic personalized context", SummaryPromptTokenBudget: 250000, GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Watched Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &bloom, Enabled: true, ArticleLimit: 4}, {ID: "i", Type: "investing_com", SourceKey: &invest, Enabled: true, ArticleLimit: 1}}}}
|
||||||
|
provider := &incident37Provider{}
|
||||||
|
summarizer := fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}
|
||||||
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: summarizer, Scrapers: map[string]scraper.Scraper{bloom: quanwenrss.New(bloom, rss41Loader{}, client), invest: quanwenrss.New(invest, rss41Loader{}, client)}})
|
||||||
|
result, err := uc.Generate(context.Background(), "fixture-user")
|
||||||
|
if err != nil || result.Summary == nil || provider.calls != 1 || fetches != 6 || len(passes) != 2 || passes[0] != "direct_mention" || passes[1] != "indirect_mention" || result.Outcome.Selected != 4 || result.Outcome.ContentIncomplete != 1 || result.Outcome.Status != "partial" {
|
||||||
|
t.Fatal("RSS source/three-pass/synthesis integration contract failed")
|
||||||
|
}
|
||||||
|
if result.Outcome.SourceStats[0].Candidates != 4 || result.Outcome.SourceStats[0].Feeds == nil || result.Outcome.SourceStats[0].Feeds.Failed != 1 {
|
||||||
|
t.Fatal("dedup/source limit/feed diagnostics are wrong")
|
||||||
|
}
|
||||||
|
var prompt struct {
|
||||||
|
Articles []struct {
|
||||||
|
Title, Content, Source string
|
||||||
|
PublishedAt *time.Time `json:"published_at"`
|
||||||
|
}
|
||||||
|
Indices []map[string]string
|
||||||
|
Context struct{ Instructions string }
|
||||||
|
}
|
||||||
|
at := strings.Index(provider.prompt, "\n")
|
||||||
|
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil || len(prompt.Articles) != 4 || prompt.Context.Instructions != repo.input.SummaryContext || len(prompt.Indices) != 1 || prompt.Indices[0]["name"] != "Watched Company" {
|
||||||
|
t.Fatal("summary lost full articles/watchlist/context")
|
||||||
|
}
|
||||||
|
nullable := false
|
||||||
|
for _, article := range prompt.Articles {
|
||||||
|
if article.Content == "" || strings.Contains(article.Title, "partial") {
|
||||||
|
t.Fatal("summary received incomplete content")
|
||||||
|
}
|
||||||
|
if article.Source == invest {
|
||||||
|
nullable = article.PublishedAt == nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !nullable {
|
||||||
|
t.Fatal("missing RSS date was invented")
|
||||||
|
}
|
||||||
|
saved, _ := json.Marshal(repo.saved.Outcome)
|
||||||
|
for _, private := range []string{"http://", "https://", "Synthetic full", "Synthetic complete", "Watched Company", "personalized context"} {
|
||||||
|
if strings.Contains(string(saved), private) {
|
||||||
|
t.Fatal("sensitive article data persisted in outcome")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
package ai
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/generation"
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/quanwenrss"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket41RSSSourceLimitKeepsNewestUniqueArticlesThroughLayaAndSummary(t *testing.T) {
|
||||||
|
const limit = 3
|
||||||
|
item := func(id int, dated bool) string {
|
||||||
|
date := ""
|
||||||
|
if dated {
|
||||||
|
date = fmt.Sprintf("<pubDate>Fri, 02 Jan 2026 %02d:00:00 GMT</pubDate>", id)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(`<item><title>Synthetic candidate %d</title><link>https://www.bloomberg.com/news/articles/2026-01-02/fixture-%d</link><guid>fixture-%d</guid>%s<content:encoded><![CDATA[<p>Synthetic complete body %d.</p>]]></content:encoded></item>`, id, id, id, date, id)
|
||||||
|
}
|
||||||
|
// Eight unique articles across all five feeds, including one undated item.
|
||||||
|
// The first feed itself exceeds N, with its newest item after position N.
|
||||||
|
// Other newest items arrive in later feeds; duplicates must not consume N.
|
||||||
|
urls := sourcefeeds.Defaults(models.SourceBloomberg)
|
||||||
|
bodies := map[string]string{
|
||||||
|
urls[0]: item(1, true) + item(2, true) + item(3, true) + item(7, true),
|
||||||
|
urls[1]: item(1, true) + item(6, true),
|
||||||
|
urls[2]: item(4, true) + item(6, true),
|
||||||
|
urls[3]: item(5, true) + item(2, true),
|
||||||
|
urls[4]: item(8, false),
|
||||||
|
}
|
||||||
|
fetches := 0
|
||||||
|
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
body, ok := bodies[r.URL.String()]
|
||||||
|
if !ok || r.URL.Host != sourcefeeds.Host {
|
||||||
|
t.Fatal("request escaped fixture feed routes")
|
||||||
|
}
|
||||||
|
fetches++
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(`<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + body + `</channel></rss>`))}, nil
|
||||||
|
})}
|
||||||
|
expected := []string{"Synthetic candidate 7", "Synthetic candidate 6", "Synthetic candidate 5"}
|
||||||
|
layaCalls := 0
|
||||||
|
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
layaCalls++
|
||||||
|
var payload struct {
|
||||||
|
States []struct{ Title, Content string }
|
||||||
|
Questions map[string]any
|
||||||
|
}
|
||||||
|
if json.NewDecoder(r.Body).Decode(&payload) != nil {
|
||||||
|
t.Fatal("invalid fixture ranking request")
|
||||||
|
}
|
||||||
|
titles := []string{}
|
||||||
|
results := []any{}
|
||||||
|
for _, state := range payload.States {
|
||||||
|
titles = append(titles, state.Title)
|
||||||
|
results = append(results, map[string]any{"answers": map[string]any{"direct_mention": map[string]any{"type": "noul", "noul": 0.9, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(titles, expected) {
|
||||||
|
t.Fatalf("ranking did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
|
||||||
|
}
|
||||||
|
for i, state := range payload.States {
|
||||||
|
if state.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) {
|
||||||
|
t.Fatal("ranking received the wrong full body")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(payload.Questions) != 1 || payload.Questions["direct_mention"] == nil {
|
||||||
|
t.Fatal("unexpected selection pass")
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1}})
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
|
||||||
|
})}
|
||||||
|
key := models.SourceBloomberg
|
||||||
|
feed := quanwenrss.New(key, rss41Loader{}, client)
|
||||||
|
pool, err := feed.Scrape(context.Background(), nil)
|
||||||
|
if err != nil || len(pool) != 8 || len(pool) <= limit {
|
||||||
|
t.Fatal("fixture does not establish more than N unique articles after multi-feed merge")
|
||||||
|
}
|
||||||
|
fetches = 0
|
||||||
|
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic source limit context", SummaryPromptTokenBudget: 250000, GlobalLimit: 10, Assets: []models.UserAsset{{Name: "Followed Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &key, Enabled: true, ArticleLimit: limit}}}}
|
||||||
|
provider := &incident37Provider{}
|
||||||
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}, Scrapers: map[string]scraper.Scraper{key: feed}})
|
||||||
|
result, err := uc.Generate(context.Background(), "fixture-user")
|
||||||
|
if err != nil || result.Summary == nil || fetches != 5 || layaCalls != 1 || provider.calls != 1 {
|
||||||
|
t.Fatal("multi-feed source limit integration did not reach ranking and synthesis")
|
||||||
|
}
|
||||||
|
if result.Outcome.TotalCandidates != limit || result.Outcome.Selected != limit || result.Outcome.ContentComplete != limit || len(result.Outcome.SourceStats) != 1 || result.Outcome.SourceStats[0].Candidates != limit {
|
||||||
|
t.Fatal("source limit was not applied before ranking")
|
||||||
|
}
|
||||||
|
counts := result.Outcome.SourceStats[0].Feeds
|
||||||
|
if counts == nil || counts.Attempted != 5 || counts.Succeeded != 5 || counts.Failed != 0 {
|
||||||
|
t.Fatal("not all configured feeds were merged")
|
||||||
|
}
|
||||||
|
var prompt struct {
|
||||||
|
Articles []struct {
|
||||||
|
Title, Content, Source string
|
||||||
|
PublishedAt *time.Time `json:"published_at"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at := strings.Index(provider.prompt, "\n")
|
||||||
|
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil {
|
||||||
|
t.Fatal("invalid summary prompt")
|
||||||
|
}
|
||||||
|
titles := []string{}
|
||||||
|
for i, a := range prompt.Articles {
|
||||||
|
titles = append(titles, a.Title)
|
||||||
|
expectedDate := time.Date(2026, 1, 2, 7-i, 0, 0, 0, time.UTC)
|
||||||
|
if a.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) || a.Source != key || a.PublishedAt == nil || !a.PublishedAt.Equal(expectedDate) {
|
||||||
|
t.Fatal("summary lost the newest article's full body/source/observed date")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(titles, expected) {
|
||||||
|
t.Fatalf("summary did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -3,9 +3,12 @@ package handlers
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/tradarr/backend/internal/auth"
|
"github.com/tradarr/backend/internal/auth"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
@ -234,7 +237,7 @@ func (h *Handler) ListAIModels(c *gin.Context) {
|
|||||||
func (h *Handler) ListSources(c *gin.Context) {
|
func (h *Handler) ListSources(c *gin.Context) {
|
||||||
sources, err := h.repo.ListSources()
|
sources, err := h.repo.ListSources()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
httputil.InternalError(c, err)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
type sourceResponse struct {
|
type sourceResponse struct {
|
||||||
@ -244,23 +247,51 @@ func (h *Handler) ListSources(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
result := make([]sourceResponse, 0, len(sources))
|
result := make([]sourceResponse, 0, len(sources))
|
||||||
for _, source := range sources {
|
for _, source := range sources {
|
||||||
|
if source.SourceKey != nil && sourcefeeds.Supported(*source.SourceKey) {
|
||||||
|
source.FeedURLs, err = h.repo.SourceFeedURLs(c.Request.Context(), *source.SourceKey)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
|
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
|
||||||
}
|
}
|
||||||
httputil.OK(c, result)
|
httputil.OK(c, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
type updateSourceRequest struct {
|
type updateSourceRequest struct {
|
||||||
Enabled bool `json:"enabled"`
|
FeedURLs json.RawMessage `json:"feed_urls"`
|
||||||
ArticleLimit *int `json:"article_limit" binding:"omitempty,min=1,max=200"`
|
Enabled bool `json:"enabled"`
|
||||||
|
ArticleLimit *int `json:"article_limit" binding:"omitempty,min=1,max=200"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) UpdateSource(c *gin.Context) {
|
func (h *Handler) UpdateSource(c *gin.Context) {
|
||||||
var req updateSourceRequest
|
var req *updateSourceRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 8192)
|
||||||
httputil.BadRequest(c, err)
|
decoder := json.NewDecoder(c.Request.Body)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
if err := decoder.Decode(&req); err != nil || req == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "source_configuration_invalid"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
|
if err := decoder.Decode(&struct{}{}); err != io.EOF || (req.ArticleLimit != nil && (*req.ArticleLimit < 1 || *req.ArticleLimit > 200)) {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "source_configuration_invalid"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var feeds *[]string
|
||||||
|
if len(req.FeedURLs) > 0 {
|
||||||
|
var values []string
|
||||||
|
if err := json.Unmarshal(req.FeedURLs, &values); err != nil || values == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "source_feeds_invalid"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
feeds = &values
|
||||||
|
}
|
||||||
|
if err := h.repo.UpdateSourceConfig(c.Param("id"), req.Enabled, req.ArticleLimit, feeds); err != nil {
|
||||||
|
if errors.Is(err, sourcefeeds.ErrInvalid) || errors.Is(err, sourcefeeds.ErrUnsupported) {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
if errors.Is(err, models.ErrSourceNotSupported) {
|
if errors.Is(err, models.ErrSourceNotSupported) {
|
||||||
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
|
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
|
||||||
return
|
return
|
||||||
@ -269,7 +300,7 @@ func (h *Handler) UpdateSource(c *gin.Context) {
|
|||||||
httputil.NotFound(c)
|
httputil.NotFound(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
httputil.InternalError(c, err)
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "source_configuration_unavailable"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
httputil.OK(c, gin.H{"ok": true})
|
httputil.OK(c, gin.H{"ok": true})
|
||||||
|
|||||||
164
backend/internal/api/source_feeds_ticket41_postgres_test.go
Normal file
164
backend/internal/api/source_feeds_ticket41_postgres_test.go
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
package api_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"github.com/lib/pq"
|
||||||
|
"github.com/tradarr/backend/internal/api"
|
||||||
|
"github.com/tradarr/backend/internal/api/handlers"
|
||||||
|
"github.com/tradarr/backend/internal/auth"
|
||||||
|
"github.com/tradarr/backend/internal/config"
|
||||||
|
"github.com/tradarr/backend/internal/models"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket41MigrationAdminFeedConfigurationIsAtomicAndPrivatePostgres(t *testing.T) {
|
||||||
|
db, err := sql.Open("postgres", postgresTestURL(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
db.SetMaxOpenConns(1)
|
||||||
|
schema := fmt.Sprintf("rss41_%d", time.Now().UnixNano())
|
||||||
|
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||||
|
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, q := range []string{
|
||||||
|
`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||||
|
`INSERT INTO users(id,email,role,password_hash) VALUES('admin','admin@example.test','admin','hash'),('user','user@example.test','user','hash')`,
|
||||||
|
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','cnbc_business','watcherguru','reuters')),source_key TEXT UNIQUE CONSTRAINT sources_source_key_check CHECK(source_key IN ('bloomberg','yahoo_finance','cnbc_business','watcher_guru')),enabled BOOLEAN,article_limit INTEGER,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||||
|
`INSERT INTO sources(id,name,type,source_key,enabled,article_limit) VALUES('00000000-0000-0000-0000-000000004101','Bloomberg','bloomberg','bloomberg',false,77),('00000000-0000-0000-0000-000000004102','Yahoo Finance','stocktwits','yahoo_finance',true,83),('00000000-0000-0000-0000-000000004103','CNBC Business','cnbc_business','cnbc_business',true,31)`,
|
||||||
|
`CREATE TABLE articles(id TEXT PRIMARY KEY,source_id UUID REFERENCES sources(id),title TEXT)`,
|
||||||
|
`INSERT INTO articles VALUES('history','00000000-0000-0000-0000-000000004101','Synthetic history')`,
|
||||||
|
} {
|
||||||
|
if _, err = db.Exec(q); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile("../database/migrations/000021_quanwen_rss.up.sql")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(`ALTER TABLE sources ADD CONSTRAINT refuse_investing_fixture CHECK(name <> 'Investing.com')`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(string(raw)); err == nil {
|
||||||
|
t.Fatal("migration fixture did not fail")
|
||||||
|
}
|
||||||
|
var noChild bool
|
||||||
|
if err = db.QueryRow(`SELECT to_regclass('source_feeds') IS NULL`).Scan(&noChild); err != nil || !noChild {
|
||||||
|
t.Fatal("failed migration leaked child table")
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(`ALTER TABLE sources DROP CONSTRAINT refuse_investing_fixture`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(string(raw)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var count int
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 6 {
|
||||||
|
t.Fatal("default feed migration failed")
|
||||||
|
}
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM sources WHERE (source_key='bloomberg' AND article_limit=77 AND NOT enabled) OR (source_key='yahoo_finance' AND article_limit=83 AND enabled) OR (source_key='cnbc_business' AND article_limit=31 AND enabled)`).Scan(&count); err != nil || count != 3 {
|
||||||
|
t.Fatal("migration changed existing source switches/caps")
|
||||||
|
}
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("history changed")
|
||||||
|
}
|
||||||
|
const secret = "ticket41-fixture"
|
||||||
|
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
|
||||||
|
token, _ := auth.GenerateToken("admin", "admin@example.test", "admin", secret)
|
||||||
|
user, _ := auth.GenerateToken("user", "user@example.test", "user", secret)
|
||||||
|
request := func(method, path, body, token string) *httptest.ResponseRecorder {
|
||||||
|
r := httptest.NewRequest(method, path, bytes.NewBufferString(body))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
if token != "" {
|
||||||
|
r.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(w, r)
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
path := "/api/admin/sources/00000000-0000-0000-0000-000000004101"
|
||||||
|
approved := sourcefeeds.Defaults(sourcefeeds.Bloomberg)[2]
|
||||||
|
good, _ := json.Marshal(map[string]any{"enabled": true, "article_limit": 12, "feed_urls": []string{approved}})
|
||||||
|
for _, token := range []string{"", user} {
|
||||||
|
if w := request(http.MethodPut, path, string(good), token); w.Code != 401 && w.Code != 403 {
|
||||||
|
t.Fatal("non-admin mutated feeds")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, body := range []string{
|
||||||
|
`null`, `{"enabled":true,"feed_urls":null}`, `{"enabled":true,"feed_urls":[]}`,
|
||||||
|
`{"enabled":true,"article_limit":0}`, `{"enabled":true,"feed_urls":[""]}`,
|
||||||
|
`{"enabled":true,"feed_urls":["https://127.0.0.1/PRIVATE_CANARY"]}`,
|
||||||
|
`{"enabled":true,"feed_urls":["https://feed.quanwenrss.com/feed/investing-news.xml"]}`,
|
||||||
|
fmt.Sprintf(`{"enabled":true,"feed_urls":[%q,%q]}`, approved, approved),
|
||||||
|
`{"enabled":true,"PRIVATE_CANARY":"ignored"}`, strings.Repeat(" ", 8193) + `{}`,
|
||||||
|
} {
|
||||||
|
w := request(http.MethodPut, path, body, token)
|
||||||
|
if w.Code != 400 || strings.Contains(w.Body.String(), "PRIVATE_CANARY") || strings.Contains(w.Body.String(), "http") {
|
||||||
|
t.Error("invalid admin configuration accepted or response exposed raw values")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var enabled bool
|
||||||
|
var cap int
|
||||||
|
if err = db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE source_key='bloomberg'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
|
||||||
|
t.Fatal("rejected update was not atomic")
|
||||||
|
}
|
||||||
|
if w := request(http.MethodPut, path, string(good), token); w.Code != 200 {
|
||||||
|
t.Fatal("valid source configuration rejected")
|
||||||
|
}
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds WHERE source_id='00000000-0000-0000-0000-000000004101'`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("configuration was not replaced")
|
||||||
|
}
|
||||||
|
w := request(http.MethodGet, "/api/admin/sources", "", token)
|
||||||
|
var result struct {
|
||||||
|
Data []models.Source `json:"data"`
|
||||||
|
}
|
||||||
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||||
|
t.Fatal("admin cannot read saved feed configuration")
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, s := range result.Data {
|
||||||
|
if s.SourceKey != nil && *s.SourceKey == models.SourceBloomberg {
|
||||||
|
found = s.Enabled && s.ArticleLimit == 12 && len(s.FeedURLs) == 1 && s.FeedURLs[0] == approved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("saved feed configuration does not round-trip")
|
||||||
|
}
|
||||||
|
if w := request(http.MethodPut, path, `{"enabled":false}`, token); w.Code != 200 {
|
||||||
|
t.Fatal("omitted feed configuration rejected")
|
||||||
|
}
|
||||||
|
values, err := models.NewRepository(db).SourceFeedURLs(context.Background(), models.SourceBloomberg)
|
||||||
|
if err != nil || len(values) != 1 || values[0] != approved {
|
||||||
|
t.Fatal("omitting feeds erased saved configuration")
|
||||||
|
}
|
||||||
|
down, err := os.ReadFile("../database/migrations/000021_quanwen_rss.down.sql")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err = db.Exec(string(down)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM source_feeds`).Scan(&count); err != nil || count != 2 {
|
||||||
|
t.Fatal("downgrade removed configuration")
|
||||||
|
}
|
||||||
|
if err = db.QueryRow(`SELECT count(*) FROM articles WHERE id='history'`).Scan(&count); err != nil || count != 1 {
|
||||||
|
t.Fatal("downgrade removed history")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
30
backend/internal/api/source_feeds_ticket41_test.go
Normal file
30
backend/internal/api/source_feeds_ticket41_test.go
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
package api_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"github.com/tradarr/backend/internal/api/handlers"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/config"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTicket41RejectsNullConfigurationsBeforeDatabase(t *testing.T) {
|
||||||
|
const secret = "ticket41-null-fixture"
|
||||||
|
router := gin.New()
|
||||||
|
router.Use(gin.Recovery())
|
||||||
|
handler := handlers.New(nil, &config.Config{JWTSecret: secret}, nil, nil, nil, nil)
|
||||||
|
router.PUT("/api/admin/sources/:id", handler.UpdateSource)
|
||||||
|
for _, body := range []string{`null`, `{"enabled":true,"feed_urls":null}`} {
|
||||||
|
r := httptest.NewRequest(http.MethodPut, "/api/admin/sources/fixture", bytes.NewBufferString(body))
|
||||||
|
r.Header.Set("Content-Type", "application/json")
|
||||||
|
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
router.ServeHTTP(w, r)
|
||||||
|
if w.Code != http.StatusBadRequest {
|
||||||
|
t.Error("null source configuration reached repository")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,2 @@
|
|||||||
|
-- Keep source identity, RSS configuration and historical references on downgrade.
|
||||||
|
UPDATE sources SET enabled=false WHERE source_key='investing_com';
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
-- Configuration only: preserve source IDs, settings, credentials and history.
|
||||||
|
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','investing_com'));
|
||||||
|
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','investing_com'));
|
||||||
|
INSERT INTO sources(id,name,type,enabled,article_limit,source_key)
|
||||||
|
VALUES(gen_random_uuid(),'Investing.com','investing_com',true,20,'investing_com');
|
||||||
|
CREATE TABLE source_feeds (
|
||||||
|
source_id UUID NOT NULL REFERENCES sources(id),
|
||||||
|
position INTEGER NOT NULL CHECK(position >= 0 AND position < 5),
|
||||||
|
url TEXT NOT NULL CHECK(url IN (
|
||||||
|
'https://feed.quanwenrss.com/feed/bloomberg-latest.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/bloomberg-economics.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/bloomberg-technology.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/bloomberg-politics.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/bloomberg-technology-ai.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/investing-news.xml')),
|
||||||
|
PRIMARY KEY(source_id,position), UNIQUE(source_id,url)
|
||||||
|
);
|
||||||
|
INSERT INTO source_feeds(source_id,position,url)
|
||||||
|
SELECT s.id,f.position,f.url FROM sources s CROSS JOIN (VALUES
|
||||||
|
(0,'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'),
|
||||||
|
(1,'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'),
|
||||||
|
(2,'https://feed.quanwenrss.com/feed/bloomberg-technology.xml'),
|
||||||
|
(3,'https://feed.quanwenrss.com/feed/bloomberg-politics.xml'),
|
||||||
|
(4,'https://feed.quanwenrss.com/feed/bloomberg-technology-ai.xml')
|
||||||
|
) AS f(position,url) WHERE s.source_key='bloomberg';
|
||||||
|
INSERT INTO source_feeds(source_id,position,url)
|
||||||
|
SELECT id,0,'https://feed.quanwenrss.com/feed/investing-news.xml' FROM sources WHERE source_key='investing_com';
|
||||||
|
END
|
||||||
|
$migration$;
|
||||||
@ -29,20 +29,21 @@ type Candidate struct {
|
|||||||
orderFrozen bool
|
orderFrozen bool
|
||||||
}
|
}
|
||||||
type SourceStat struct {
|
type SourceStat struct {
|
||||||
SourceKey string `json:"source_key"`
|
Feeds *scraper.FeedCounts `json:"feeds,omitempty"`
|
||||||
ContentComplete int `json:"content_complete"`
|
SourceKey string `json:"source_key"`
|
||||||
ContentIncomplete int `json:"content_incomplete"`
|
ContentComplete int `json:"content_complete"`
|
||||||
ContentUnavailable int `json:"content_unavailable"`
|
ContentIncomplete int `json:"content_incomplete"`
|
||||||
DatesAvailable int `json:"dates_available"`
|
ContentUnavailable int `json:"content_unavailable"`
|
||||||
SourceID string `json:"source_id"`
|
DatesAvailable int `json:"dates_available"`
|
||||||
SourceType string `json:"source_type"`
|
SourceID string `json:"source_id"`
|
||||||
Status string `json:"status"`
|
SourceType string `json:"source_type"`
|
||||||
Candidates int `json:"candidates"`
|
Status string `json:"status"`
|
||||||
LayaSelected int `json:"laya_selected"`
|
Candidates int `json:"candidates"`
|
||||||
Selected int `json:"selected"`
|
LayaSelected int `json:"laya_selected"`
|
||||||
ArticleLimit int `json:"article_limit"`
|
Selected int `json:"selected"`
|
||||||
ContentFallbacks int `json:"content_fallbacks"`
|
ArticleLimit int `json:"article_limit"`
|
||||||
FailureCode string `json:"failure_code,omitempty"`
|
ContentFallbacks int `json:"content_fallbacks"`
|
||||||
|
FailureCode string `json:"failure_code,omitempty"`
|
||||||
}
|
}
|
||||||
type GenerationOutcome struct {
|
type GenerationOutcome struct {
|
||||||
ContentComplete int `json:"content_complete"`
|
ContentComplete int `json:"content_complete"`
|
||||||
@ -220,7 +221,17 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
|||||||
if *source.SourceKey == models.SourceYahooFinance {
|
if *source.SourceKey == models.SourceYahooFinance {
|
||||||
sourceSymbols = yahooSymbols(input.Assets)
|
sourceSymbols = yahooSymbols(input.Assets)
|
||||||
}
|
}
|
||||||
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
if reported, ok := feed.(scraper.ReportedScraper); ok {
|
||||||
|
var counts scraper.FeedCounts
|
||||||
|
articles, counts, err = reported.ScrapeWithDiagnostics(ctx, append([]string(nil), sourceSymbols...))
|
||||||
|
stat.Feeds = &counts
|
||||||
|
if counts.Failed > 0 && counts.Succeeded > 0 {
|
||||||
|
stat.Status = "partial"
|
||||||
|
partial = true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
stat.Status = "failed"
|
stat.Status = "failed"
|
||||||
|
|||||||
@ -36,6 +36,7 @@ type UserAsset struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Source struct {
|
type Source struct {
|
||||||
|
FeedURLs []string `json:"feed_urls,omitempty"`
|
||||||
SourceKey *string `json:"source_key"`
|
SourceKey *string `json:"source_key"`
|
||||||
ArticleLimit int `json:"article_limit"`
|
ArticleLimit int `json:"article_limit"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
|
|||||||
@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
|
|||||||
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||||
s := &Source{}
|
s := &Source{}
|
||||||
err := r.db.QueryRow(`
|
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','cnbc_business')`, 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','investing_com')`, sourceType,
|
||||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
|
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
@ -160,22 +160,7 @@ func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
|||||||
var ErrSourceNotSupported = errors.New("source_not_supported")
|
var ErrSourceNotSupported = errors.New("source_not_supported")
|
||||||
|
|
||||||
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
|
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
|
||||||
tx, err := r.db.Begin()
|
return r.UpdateSourceConfig(id, enabled, articleLimit, nil)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback()
|
|
||||||
var key *string
|
|
||||||
if err = tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if key == nil || !SupportedSourceKey(*key) {
|
|
||||||
return ErrSourceNotSupported
|
|
||||||
}
|
|
||||||
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return tx.Commit()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Scrape Credentials ─────────────────────────────────────────────────────
|
// ── Scrape Credentials ─────────────────────────────────────────────────────
|
||||||
|
|||||||
70
backend/internal/models/source_feeds.go
Normal file
70
backend/internal/models/source_feeds.go
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r *Repository) SourceFeedURLs(ctx context.Context, key string) ([]string, error) {
|
||||||
|
if !sourcefeeds.Supported(key) {
|
||||||
|
return nil, sourcefeeds.ErrUnsupported
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx, `SELECT f.url FROM source_feeds f JOIN sources s ON s.id=f.source_id WHERE s.source_key=$1 ORDER BY f.position LIMIT 6`, key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
values := []string{}
|
||||||
|
for rows.Next() {
|
||||||
|
var value string
|
||||||
|
if err := rows.Scan(&value); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
values = append(values, value)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return sourcefeeds.Validate(key, values)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSourceConfig replaces configuration and switches in one transaction.
|
||||||
|
// Omitted feeds preserve the saved configuration; an empty replacement is invalid.
|
||||||
|
func (r *Repository) UpdateSourceConfig(id string, enabled bool, limit *int, feeds *[]string) error {
|
||||||
|
if limit != nil && (*limit < 1 || *limit > 200) {
|
||||||
|
return sourcefeeds.ErrInvalid
|
||||||
|
}
|
||||||
|
tx, err := r.db.Begin()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
var key *string
|
||||||
|
if err := tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if key == nil || !SupportedSourceKey(*key) {
|
||||||
|
return ErrSourceNotSupported
|
||||||
|
}
|
||||||
|
var normalized []string
|
||||||
|
if feeds != nil {
|
||||||
|
normalized, err = sourcefeeds.Validate(*key, *feeds)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, limit, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if feeds != nil {
|
||||||
|
if _, err = tx.Exec(`DELETE FROM source_feeds WHERE source_id=$1`, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for position, value := range normalized {
|
||||||
|
if _, err = tx.Exec(`INSERT INTO source_feeds(source_id,position,url) VALUES($1,$2,$3)`, id, position, value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
@ -3,13 +3,14 @@ package models
|
|||||||
const (
|
const (
|
||||||
SourceYahooFinance = "yahoo_finance"
|
SourceYahooFinance = "yahoo_finance"
|
||||||
SourceBloomberg = "bloomberg"
|
SourceBloomberg = "bloomberg"
|
||||||
|
SourceInvesting = "investing_com"
|
||||||
SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
|
SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
|
||||||
SourceCNBCBusiness = "cnbc_business"
|
SourceCNBCBusiness = "cnbc_business"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SupportedSourceKey(key string) bool {
|
func SupportedSourceKey(key string) bool {
|
||||||
switch key {
|
switch key {
|
||||||
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness:
|
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness, SourceInvesting:
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
|
|||||||
34
backend/internal/scraper/quanwenrss/access.go
Normal file
34
backend/internal/scraper/quanwenrss/access.go
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package quanwenrss
|
||||||
|
|
||||||
|
import (
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Restriction evidence is inspected before presentation chrome is removed.
|
||||||
|
func bodyRestricted(raw string) bool {
|
||||||
|
t := html.NewTokenizer(strings.NewReader(raw))
|
||||||
|
for {
|
||||||
|
kind := t.Next()
|
||||||
|
if kind == html.ErrorToken {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if kind != html.StartTagToken && kind != html.SelfClosingTagToken {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
token := t.Token()
|
||||||
|
for _, a := range token.Attr {
|
||||||
|
value := strings.ToLower(a.Val)
|
||||||
|
if (a.Key == "data-content-state" && (value == "partial" || value == "incomplete")) || (a.Key == "data-content-truncated" && value == "true") || (a.Key == "data-accessible" && value == "false") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if a.Key == "class" || a.Key == "id" || a.Key == "data-component" || a.Key == "data-testid" || a.Key == "data-test" || a.Key == "src" {
|
||||||
|
for _, marker := range []string{"paywall", "giftarticle", "captcha", "challenge", "cf-chl", "placeholder", "skeleton", "truncated", "partial"} {
|
||||||
|
if strings.Contains(value, marker) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
119
backend/internal/scraper/quanwenrss/collector.go
Normal file
119
backend/internal/scraper/quanwenrss/collector.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
package quanwenrss
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"github.com/tradarr/backend/internal/scraper/sourcehttp"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
)
|
||||||
|
|
||||||
|
const MaxSourceBytes = 12 * 1024 * 1024
|
||||||
|
|
||||||
|
var errUnavailable = errors.New("rss_source_unavailable")
|
||||||
|
|
||||||
|
type FeedLoader interface {
|
||||||
|
SourceFeedURLs(context.Context, string) ([]string, error)
|
||||||
|
}
|
||||||
|
type Collector struct {
|
||||||
|
source string
|
||||||
|
loader FeedLoader
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(source string, loader FeedLoader, client *http.Client) *Collector {
|
||||||
|
if client == nil {
|
||||||
|
client = &http.Client{Transport: sourcehttp.NewTransport(nil, nil)}
|
||||||
|
}
|
||||||
|
bounded := *client
|
||||||
|
bounded.Timeout = 10 * time.Second
|
||||||
|
// Redirects are revalidated against the exact source/path allowlist; article
|
||||||
|
// hosts and cross-source paths are never delegated to the transport.
|
||||||
|
bounded.CheckRedirect = func(r *http.Request, via []*http.Request) error {
|
||||||
|
if len(via) >= 3 {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
}
|
||||||
|
normalized, err := sourcefeeds.Validate(source, []string{r.URL.String()})
|
||||||
|
if err != nil {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
}
|
||||||
|
r.URL, _ = url.Parse(normalized[0])
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &Collector{source: source, loader: loader, client: &bounded}
|
||||||
|
}
|
||||||
|
func (c *Collector) Name() string { return c.source }
|
||||||
|
func (c *Collector) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||||
|
articles, _, err := c.ScrapeWithDiagnostics(ctx, symbols)
|
||||||
|
return articles, err
|
||||||
|
}
|
||||||
|
func (c *Collector) ScrapeWithDiagnostics(ctx context.Context, _ []string) ([]scraper.Article, scraper.FeedCounts, error) {
|
||||||
|
counts := scraper.FeedCounts{}
|
||||||
|
if c.loader == nil {
|
||||||
|
return nil, counts, errUnavailable
|
||||||
|
}
|
||||||
|
values, err := c.loader.SourceFeedURLs(ctx, c.source)
|
||||||
|
if err != nil {
|
||||||
|
return nil, counts, errUnavailable
|
||||||
|
}
|
||||||
|
values, err = sourcefeeds.Validate(c.source, values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, counts, errUnavailable
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
pools := [][]scraper.Article{}
|
||||||
|
consumed := 0
|
||||||
|
for _, value := range values {
|
||||||
|
counts.Attempted++
|
||||||
|
articles, n, err := c.fetch(ctx, value, MaxSourceBytes-consumed)
|
||||||
|
consumed += n
|
||||||
|
if err != nil {
|
||||||
|
counts.Failed++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
counts.Succeeded++
|
||||||
|
pools = append(pools, articles)
|
||||||
|
}
|
||||||
|
if counts.Succeeded == 0 {
|
||||||
|
return nil, counts, errUnavailable
|
||||||
|
}
|
||||||
|
return Merge(pools), counts, nil
|
||||||
|
}
|
||||||
|
func (c *Collector) fetch(ctx context.Context, value string, remaining int) ([]scraper.Article, int, error) {
|
||||||
|
if remaining <= 0 || ctx.Err() != nil {
|
||||||
|
return nil, 0, errUnavailable
|
||||||
|
}
|
||||||
|
// Defense in depth: never trust a stored configuration without validation.
|
||||||
|
if _, err := sourcefeeds.Validate(c.source, []string{value}); err != nil {
|
||||||
|
return nil, 0, errUnavailable
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, value, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, errUnavailable
|
||||||
|
}
|
||||||
|
req.Header.Set("Accept", "application/rss+xml, application/xml")
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, errUnavailable
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, 0, errUnavailable
|
||||||
|
}
|
||||||
|
limit := min(remaining, MaxFeedBytes)
|
||||||
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, int64(limit)+1))
|
||||||
|
if err != nil || len(raw) > limit {
|
||||||
|
return nil, len(raw), errUnavailable
|
||||||
|
}
|
||||||
|
articles, err := Parse(raw, c.source)
|
||||||
|
if err != nil {
|
||||||
|
return nil, len(raw), errUnavailable
|
||||||
|
}
|
||||||
|
return articles, len(raw), nil
|
||||||
|
}
|
||||||
126
backend/internal/scraper/quanwenrss/collector_test.go
Normal file
126
backend/internal/scraper/quanwenrss/collector_test.go
Normal file
@ -0,0 +1,126 @@
|
|||||||
|
package quanwenrss
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"github.com/tradarr/backend/internal/sourcefeeds"
|
||||||
|
)
|
||||||
|
|
||||||
|
type loaderFunc func(context.Context, string) ([]string, error)
|
||||||
|
|
||||||
|
func (f loaderFunc) SourceFeedURLs(ctx context.Context, key string) ([]string, error) {
|
||||||
|
return f(ctx, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
type fixtureTransport func(*http.Request) (*http.Response, error)
|
||||||
|
|
||||||
|
func (f fixtureTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||||
|
func fixtureRSS(id, date, body string) string {
|
||||||
|
return `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><item><title>Synthetic ` + id + `</title><link>https://www.bloomberg.com/news/articles/2026-01-02/` + id + `</link><guid>` + id + `</guid><pubDate>` + date + `</pubDate><content:encoded><![CDATA[<article><p>` + body + `</p></article>]]></content:encoded></item></channel></rss>`
|
||||||
|
}
|
||||||
|
func TestCollectorMergesAllConfiguredFeedsWithoutArticleRequestsAndPreservesPartialSuccess(t *testing.T) {
|
||||||
|
urls := sourcefeeds.Defaults(Bloomberg)
|
||||||
|
calls := 0
|
||||||
|
client := &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
if r.URL.Host != sourcefeeds.Host {
|
||||||
|
t.Fatal("article URL or external host was fetched")
|
||||||
|
}
|
||||||
|
status := 200
|
||||||
|
body := fixtureRSS("shared", "Fri, 02 Jan 2026 03:04:05 GMT", "Synthetic complete shared body.")
|
||||||
|
if r.URL.String() == urls[1] {
|
||||||
|
status = 503
|
||||||
|
body = "PRIVATE raw upstream response"
|
||||||
|
}
|
||||||
|
if r.URL.String() == urls[2] {
|
||||||
|
body = fixtureRSS("newer", "Fri, 02 Jan 2026 04:04:05 GMT", "Synthetic complete newer body.")
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: status, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})}
|
||||||
|
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), client)
|
||||||
|
got, stats, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||||
|
if err != nil || calls != 5 || stats != (scraper.FeedCounts{Attempted: 5, Succeeded: 4, Failed: 1}) || len(got) != 2 || got[0].Title != "Synthetic newer" || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||||
|
t.Fatal("multi-feed merge/partial outcome failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestStoredFeedPolicyIsRevalidatedBeforeAnyTransport(t *testing.T) {
|
||||||
|
for _, urls := range [][]string{nil, {"https://127.0.0.1/private"}, {sourcefeeds.Defaults(Investing)[0]}, {"https://feed.quanwenrss.com/feed/unknown.xml"}} {
|
||||||
|
calls := 0
|
||||||
|
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), &http.Client{Transport: fixtureTransport(func(*http.Request) (*http.Response, error) { calls++; return nil, errors.New("PRIVATE") })})
|
||||||
|
if _, _, err := c.ScrapeWithDiagnostics(context.Background(), nil); err == nil || calls != 0 {
|
||||||
|
t.Fatal("invalid saved configuration reached transport")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestFeedRedirectsAndFailuresCannotLeakOrFetchArticleHosts(t *testing.T) {
|
||||||
|
allowed := sourcefeeds.Defaults(Bloomberg)[0]
|
||||||
|
for _, destination := range []string{"https://127.0.0.1/private", "https://www.bloomberg.com/news/articles/private", sourcefeeds.Defaults(Investing)[0], "https://feed.quanwenrss.com/feed/unknown.xml"} {
|
||||||
|
calls := 0
|
||||||
|
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return []string{allowed}, nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{destination}}, Request: r, Body: io.NopCloser(strings.NewReader("PRIVATE"))}, nil
|
||||||
|
})})
|
||||||
|
_, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||||
|
if err == nil || calls != 1 || s.Failed != 1 || err.Error() != "rss_source_unavailable" {
|
||||||
|
t.Fatal("unsafe redirect or raw upstream error escaped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestGUIDMergeBridgesAliasesAndSourceSortingKeepsNullDatesLast(t *testing.T) {
|
||||||
|
pools := [][]scraper.Article{}
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
raw := fixtureRSS(fmt.Sprintf("fixture-%d", i), "Fri, 02 Jan 2026 03:04:05 GMT", "Synthetic body.")
|
||||||
|
raw = strings.Replace(raw, fmt.Sprintf("<guid>fixture-%d</guid>", i), "<guid>shared</guid>", 1)
|
||||||
|
got, err := Parse([]byte(raw), Bloomberg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pools = append(pools, got)
|
||||||
|
}
|
||||||
|
got := Merge(pools)
|
||||||
|
if len(got) != 1 || got[0].Title != "Synthetic fixture-0" {
|
||||||
|
t.Fatal("stable GUID did not deduplicate aliases")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSourceBudgetAndAllFailedFeedsAreExplicitWithoutSilentTruncation(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
urls := sourcefeeds.Defaults(Bloomberg)
|
||||||
|
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls, nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", MaxFeedBytes+1)))}, nil
|
||||||
|
})})
|
||||||
|
got, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||||
|
if err == nil || got != nil || s.Succeeded != 0 || s.Failed != 5 || calls != 3 {
|
||||||
|
t.Fatal("source byte budget did not stop body reads/requests or return explicit unavailable")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestApprovedSameHostRedirectRemainsBoundedToFeedPaths(t *testing.T) {
|
||||||
|
urls := sourcefeeds.Defaults(Bloomberg)
|
||||||
|
calls := 0
|
||||||
|
c := New(Bloomberg, loaderFunc(func(context.Context, string) ([]string, error) { return urls[:1], nil }), &http.Client{Transport: fixtureTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
calls++
|
||||||
|
header := make(http.Header)
|
||||||
|
status := 200
|
||||||
|
body := fixtureRSS("fixture", "", "Synthetic complete body.")
|
||||||
|
if calls == 1 {
|
||||||
|
status = 302
|
||||||
|
header.Set("Location", urls[1])
|
||||||
|
}
|
||||||
|
if calls > 2 || r.URL.Host != sourcefeeds.Host {
|
||||||
|
t.Fatal("unbounded/external redirect")
|
||||||
|
}
|
||||||
|
return &http.Response{StatusCode: status, Header: header, Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||||
|
})})
|
||||||
|
got, s, err := c.ScrapeWithDiagnostics(context.Background(), nil)
|
||||||
|
if err != nil || calls != 2 || s.Succeeded != 1 || len(got) != 1 || got[0].PublishedAt != nil {
|
||||||
|
t.Fatal("approved redirect or nullable RSS date failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
420
backend/internal/scraper/quanwenrss/rss.go
Normal file
420
backend/internal/scraper/quanwenrss/rss.go
Normal file
@ -0,0 +1,420 @@
|
|||||||
|
// Package quanwenrss parses transient RSS data without following article links.
|
||||||
|
package quanwenrss
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
Investing = "investing_com"
|
||||||
|
Bloomberg = "bloomberg"
|
||||||
|
MaxFeedBytes = 4 * 1024 * 1024
|
||||||
|
MaxDepth = 32
|
||||||
|
MaxItems = 200
|
||||||
|
MaxFieldBytes = 256 * 1024
|
||||||
|
contentNamespace = "http://purl.org/rss/1.0/modules/content/"
|
||||||
|
dcNamespace = "http://purl.org/dc/elements/1.1/"
|
||||||
|
)
|
||||||
|
|
||||||
|
var errInvalid = errors.New("rss_feed_invalid")
|
||||||
|
|
||||||
|
// Parse is entirely offline. The approved QuanwenRSS contract identifies the
|
||||||
|
// namespaced content:encoded field as full text, subject to identity/access limits.
|
||||||
|
func Parse(raw []byte, source string) ([]scraper.Article, error) {
|
||||||
|
if (source != Investing && source != Bloomberg) || len(raw) > MaxFeedBytes {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
dec := xml.NewDecoder(bytes.NewReader(raw))
|
||||||
|
depth, channelDepth, itemDepth, fieldDepth, items, channels := 0, 0, 0, 0, 0, 0
|
||||||
|
rootSeen, rootClosed := false, false
|
||||||
|
var fields map[string]string
|
||||||
|
field := ""
|
||||||
|
var text strings.Builder
|
||||||
|
out := []scraper.Article{}
|
||||||
|
for {
|
||||||
|
token, err := dec.Token()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
switch t := token.(type) {
|
||||||
|
case xml.Directive:
|
||||||
|
return nil, errInvalid
|
||||||
|
case xml.ProcInst:
|
||||||
|
if t.Target != "xml" || rootSeen {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
case xml.StartElement:
|
||||||
|
depth++
|
||||||
|
if depth > MaxDepth || rootClosed {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
if depth == 1 {
|
||||||
|
if rootSeen || t.Name.Local != "rss" || t.Name.Space != "" {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
rootSeen = true
|
||||||
|
}
|
||||||
|
if depth == 2 && t.Name.Local == "channel" && t.Name.Space == "" {
|
||||||
|
channels++
|
||||||
|
channelDepth = depth
|
||||||
|
if channels != 1 {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if channelDepth != 0 && depth == channelDepth+1 && t.Name.Local == "item" && t.Name.Space == "" {
|
||||||
|
items++
|
||||||
|
if items > MaxItems {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
itemDepth = depth
|
||||||
|
fields = map[string]string{}
|
||||||
|
}
|
||||||
|
if itemDepth != 0 && depth == itemDepth+1 {
|
||||||
|
field = ""
|
||||||
|
if t.Name.Space == "" {
|
||||||
|
switch t.Name.Local {
|
||||||
|
case "title", "link", "description", "pubDate", "guid":
|
||||||
|
field = t.Name.Local
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if t.Name.Local == "encoded" && t.Name.Space == contentNamespace {
|
||||||
|
field = "encoded"
|
||||||
|
}
|
||||||
|
if t.Name.Local == "date" && t.Name.Space == dcNamespace {
|
||||||
|
field = "date"
|
||||||
|
}
|
||||||
|
if field != "" {
|
||||||
|
if _, seen := fields[field]; seen {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
fieldDepth = depth
|
||||||
|
text.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if field == "encoded" && fieldDepth > 0 && depth > fieldDepth {
|
||||||
|
fields["encoded_nested"] = "true"
|
||||||
|
}
|
||||||
|
case xml.CharData:
|
||||||
|
if depth == 0 && strings.TrimSpace(string(t)) != "" {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
if field != "" && fieldDepth != 0 {
|
||||||
|
if text.Len()+len(t) > MaxFieldBytes {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
text.Write(t)
|
||||||
|
}
|
||||||
|
case xml.EndElement:
|
||||||
|
if fieldDepth == depth && field != "" {
|
||||||
|
fields[field] = text.String()
|
||||||
|
field = ""
|
||||||
|
fieldDepth = 0
|
||||||
|
text.Reset()
|
||||||
|
}
|
||||||
|
if itemDepth == depth {
|
||||||
|
a, keep, err := article(fields, source)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
if keep {
|
||||||
|
out = append(out, a)
|
||||||
|
}
|
||||||
|
itemDepth = 0
|
||||||
|
fields = nil
|
||||||
|
}
|
||||||
|
if channelDepth == depth {
|
||||||
|
channelDepth = 0
|
||||||
|
}
|
||||||
|
depth--
|
||||||
|
if depth == 0 {
|
||||||
|
rootClosed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !rootSeen || !rootClosed || depth != 0 || channels != 1 {
|
||||||
|
return nil, errInvalid
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func article(fields map[string]string, source string) (scraper.Article, bool, error) {
|
||||||
|
a := scraper.Article{Source: source, ContentState: scraper.ContentUnavailable}
|
||||||
|
value := strings.TrimSpace(fields["link"])
|
||||||
|
u, err := url.Parse(value)
|
||||||
|
host := "www.bloomberg.com"
|
||||||
|
if source == Investing {
|
||||||
|
host = "www.investing.com"
|
||||||
|
}
|
||||||
|
if len(fields["guid"]) > 4096 {
|
||||||
|
return a, false, errInvalid
|
||||||
|
}
|
||||||
|
a.FeedGUID = strings.TrimSpace(fields["guid"])
|
||||||
|
if (value == "" && a.FeedGUID == "") || (value != "" && (err != nil || len(value) > 4096 || u.Scheme != "https" || u.User != nil || u.Opaque != "" || !strings.EqualFold(u.Host, host) || u.Path == "" || u.Path == "/")) {
|
||||||
|
return a, false, nil
|
||||||
|
}
|
||||||
|
if len(fields["title"]) > 4096 {
|
||||||
|
return a, false, errInvalid
|
||||||
|
}
|
||||||
|
a.Title, err = cleanText(fields["title"])
|
||||||
|
if err != nil {
|
||||||
|
return a, false, err
|
||||||
|
}
|
||||||
|
if a.Title == "" {
|
||||||
|
return a, false, nil
|
||||||
|
}
|
||||||
|
a.URL = value
|
||||||
|
body := fields["encoded"]
|
||||||
|
if strings.TrimSpace(body) == "" {
|
||||||
|
body = fields["description"]
|
||||||
|
}
|
||||||
|
a.Content, err = cleanText(body)
|
||||||
|
if err != nil {
|
||||||
|
return a, false, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(a.Content) != "" && a.Content != a.Title {
|
||||||
|
a.ContentState = scraper.ContentIncomplete
|
||||||
|
if strings.TrimSpace(fields["encoded"]) != "" && fields["encoded_nested"] != "true" && !bodyRestricted(fields["encoded"]) {
|
||||||
|
a.ContentState = scraper.ContentComplete
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a.Content = ""
|
||||||
|
}
|
||||||
|
first, second := rssDate(fields["pubDate"]), rssDate(fields["date"])
|
||||||
|
a.PublishedAt = first
|
||||||
|
if first == nil {
|
||||||
|
a.PublishedAt = second
|
||||||
|
} else if second != nil && !first.Equal(*second) {
|
||||||
|
a.PublishedAt = nil
|
||||||
|
}
|
||||||
|
return a, true, nil
|
||||||
|
}
|
||||||
|
func rssDate(value string) *time.Time {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
layouts := []string{time.RFC3339Nano, time.RFC1123Z, time.RFC822Z}
|
||||||
|
if strings.HasSuffix(value, " GMT") || strings.HasSuffix(value, " UTC") {
|
||||||
|
layouts = append(layouts, time.RFC1123, time.RFC822)
|
||||||
|
}
|
||||||
|
for _, layout := range layouts {
|
||||||
|
if t, err := time.Parse(layout, value); err == nil {
|
||||||
|
t = t.UTC()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func cleanText(value string) (string, error) {
|
||||||
|
// Bound nesting before invoking the HTML tree builder (also for malformed
|
||||||
|
// fragments with many unclosed tags); no DOM/network side effects are used.
|
||||||
|
tokenizer := html.NewTokenizer(strings.NewReader(value))
|
||||||
|
tokenizer.SetMaxBuf(MaxFieldBytes)
|
||||||
|
nesting, tokens := 0, 0
|
||||||
|
for {
|
||||||
|
kind := tokenizer.Next()
|
||||||
|
if kind == html.ErrorToken {
|
||||||
|
if tokenizer.Err() != io.EOF {
|
||||||
|
return "", errInvalid
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
tokens++
|
||||||
|
if tokens > 20000 {
|
||||||
|
return "", errInvalid
|
||||||
|
}
|
||||||
|
if kind == html.StartTagToken {
|
||||||
|
name, _ := tokenizer.TagName()
|
||||||
|
switch string(name) {
|
||||||
|
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||||
|
default:
|
||||||
|
nesting++
|
||||||
|
}
|
||||||
|
if nesting > 64 {
|
||||||
|
return "", errInvalid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if kind == html.EndTagToken && nesting > 0 {
|
||||||
|
nesting--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc, err := html.Parse(strings.NewReader(value))
|
||||||
|
if err != nil {
|
||||||
|
return "", errInvalid
|
||||||
|
}
|
||||||
|
var text strings.Builder
|
||||||
|
nodes := 0
|
||||||
|
var walk func(*html.Node, int) error
|
||||||
|
walk = func(n *html.Node, depth int) error {
|
||||||
|
nodes++
|
||||||
|
if depth > 64 || nodes > 20000 {
|
||||||
|
return errInvalid
|
||||||
|
}
|
||||||
|
if n.Type == html.ElementNode {
|
||||||
|
switch n.Data {
|
||||||
|
case "script", "style", "noscript", "iframe", "object", "embed", "form", "nav", "aside", "footer", "header", "svg":
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, a := range n.Attr {
|
||||||
|
if a.Key == "hidden" || a.Key == "aria-hidden" && a.Val == "true" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if a.Key == "class" || a.Key == "data-component" {
|
||||||
|
v := strings.ToLower(a.Val)
|
||||||
|
for _, marker := range []string{"advertisement", "related-stories", "placeholder", "skeleton", "promo"} {
|
||||||
|
if strings.Contains(v, marker) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
block := false
|
||||||
|
switch n.Data {
|
||||||
|
case "p", "div", "section", "article", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "tr", "br":
|
||||||
|
block = true
|
||||||
|
}
|
||||||
|
if block {
|
||||||
|
text.WriteByte('\n')
|
||||||
|
}
|
||||||
|
if n.Type == html.TextNode {
|
||||||
|
text.WriteString(n.Data)
|
||||||
|
}
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||||
|
if err := walk(c, depth+1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if block {
|
||||||
|
text.WriteByte('\n')
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := walk(doc, 0); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
lines := []string{}
|
||||||
|
for _, line := range strings.Split(text.String(), "\n") {
|
||||||
|
if line = strings.Join(strings.Fields(line), " "); line != "" {
|
||||||
|
lines = append(lines, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n\n"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge preserves the first listing's identity. It does not impose a per-feed
|
||||||
|
// cap: the generation use case applies its source limit after this merged pool.
|
||||||
|
func Merge(feeds [][]scraper.Article) []scraper.Article {
|
||||||
|
|
||||||
|
flat := []scraper.Article{}
|
||||||
|
for _, pool := range feeds {
|
||||||
|
flat = append(flat, pool...)
|
||||||
|
}
|
||||||
|
parents := make([]int, len(flat))
|
||||||
|
for i := range parents {
|
||||||
|
parents[i] = i
|
||||||
|
}
|
||||||
|
var find func(int) int
|
||||||
|
find = func(i int) int {
|
||||||
|
if parents[i] != i {
|
||||||
|
parents[i] = find(parents[i])
|
||||||
|
}
|
||||||
|
return parents[i]
|
||||||
|
}
|
||||||
|
identities := map[string]int{}
|
||||||
|
for i, a := range flat {
|
||||||
|
keys := []string{}
|
||||||
|
if a.URL != "" {
|
||||||
|
keys = append(keys, "url:"+dedupKey(a.URL))
|
||||||
|
}
|
||||||
|
if a.FeedGUID != "" {
|
||||||
|
keys = append(keys, "guid:"+a.Source+":"+a.FeedGUID)
|
||||||
|
}
|
||||||
|
for _, key := range keys {
|
||||||
|
if j, ok := identities[key]; ok {
|
||||||
|
x, y := find(i), find(j)
|
||||||
|
if x < y {
|
||||||
|
parents[y] = x
|
||||||
|
} else {
|
||||||
|
parents[x] = y
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
identities[key] = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := []scraper.Article{}
|
||||||
|
groups := map[int]int{}
|
||||||
|
conflicts := map[int]bool{}
|
||||||
|
rank := func(a scraper.Article) int {
|
||||||
|
switch scraper.ContentStatus(a) {
|
||||||
|
case scraper.ContentComplete:
|
||||||
|
return 3
|
||||||
|
case scraper.ContentIncomplete:
|
||||||
|
return 2
|
||||||
|
default:
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, a := range flat {
|
||||||
|
group := find(i)
|
||||||
|
index, exists := groups[group]
|
||||||
|
if !exists {
|
||||||
|
groups[group] = len(out)
|
||||||
|
out = append(out, a)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
first := &out[index]
|
||||||
|
if !conflicts[group] {
|
||||||
|
if first.PublishedAt == nil {
|
||||||
|
first.PublishedAt = a.PublishedAt
|
||||||
|
} else if a.PublishedAt != nil && !first.PublishedAt.Equal(*a.PublishedAt) {
|
||||||
|
first.PublishedAt = nil
|
||||||
|
conflicts[group] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rank(a) > rank(*first) || rank(a) == rank(*first) && len(a.Content) > len(first.Content) {
|
||||||
|
first.Content = a.Content
|
||||||
|
first.ContentState = a.ContentState
|
||||||
|
first.ContentTruncated = a.ContentTruncated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sort.SliceStable(out, func(i, j int) bool {
|
||||||
|
a, b := out[i].PublishedAt, out[j].PublishedAt
|
||||||
|
if a == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if b == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return a.After(*b)
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func dedupKey(value string) string {
|
||||||
|
u, err := url.Parse(value)
|
||||||
|
if err != nil {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
u.Fragment = ""
|
||||||
|
u.Host = strings.ToLower(u.Host)
|
||||||
|
q := u.Query()
|
||||||
|
for key := range q {
|
||||||
|
if strings.HasPrefix(strings.ToLower(key), "utm_") {
|
||||||
|
q.Del(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
return u.String()
|
||||||
|
}
|
||||||
147
backend/internal/scraper/quanwenrss/rss_test.go
Normal file
147
backend/internal/scraper/quanwenrss/rss_test.go
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
package quanwenrss
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tradarr/backend/internal/scraper"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestContractualRSSPreservesCleanFullBodyAndDate(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("testdata/investing.xml")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := Parse(raw, Investing)
|
||||||
|
if err != nil || len(got) != 2 {
|
||||||
|
t.Fatal("synthetic RSS articles were not parsed")
|
||||||
|
}
|
||||||
|
expected := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||||
|
if got[0].PublishedAt == nil || !got[0].PublishedAt.Equal(expected) || got[1].PublishedAt != nil {
|
||||||
|
t.Fatal("RSS dates were invented or lost")
|
||||||
|
}
|
||||||
|
if !strings.Contains(got[0].Content, "Final synthetic paragraph.") || strings.Contains(got[0].Content, "EXCLUDED") || strings.Contains(got[0].Content, "<") {
|
||||||
|
t.Fatal("RSS editorial body was not cleaned")
|
||||||
|
}
|
||||||
|
if scraper.ContentStatus(got[0]) != scraper.ContentComplete || scraper.ContentStatus(got[1]) != scraper.ContentIncomplete {
|
||||||
|
t.Fatal("contractual encoded body or description completeness is wrong")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestMergeDeduplicatesBeforeApplyingSourceLimitAndKeepsStableListing(t *testing.T) {
|
||||||
|
date := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
listed := "https://www.bloomberg.com/news/articles/2026-01-02/synthetic"
|
||||||
|
first := []scraper.Article{{Title: "Synthetic initial", URL: listed, Content: "Synthetic teaser", ContentState: scraper.ContentIncomplete}, {Title: "Synthetic second", URL: listed + "-second"}}
|
||||||
|
second := []scraper.Article{{Title: "Synthetic duplicate", URL: listed + "?utm_source=fixture", Content: "Synthetic longer but unproven body", ContentState: scraper.ContentIncomplete, PublishedAt: &date}, {Title: "Synthetic third", URL: listed + "-third"}}
|
||||||
|
got := Merge([][]scraper.Article{first, second})
|
||||||
|
if len(got) != 3 || got[0].URL != listed || got[0].Title != "Synthetic initial" || got[0].PublishedAt == nil {
|
||||||
|
t.Fatal("source merge lost stable association or consumed source capacity with duplicate")
|
||||||
|
}
|
||||||
|
if scraper.ContentStatus(got[0]) == scraper.ContentComplete {
|
||||||
|
t.Fatal("merge invented completeness")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestRSSRejectsUnsafeOrOversizedDocumentsWithoutRawErrors(t *testing.T) {
|
||||||
|
for _, raw := range []string{
|
||||||
|
`<!DOCTYPE rss [<!ENTITY p "PRIVATE_CANARY">]><rss><channel/></rss>`,
|
||||||
|
`<rss><channel><item>`, strings.Repeat("x", MaxFeedBytes+1),
|
||||||
|
`<rss><channel>` + strings.Repeat("<x>", MaxDepth+1) + strings.Repeat("</x>", MaxDepth+1) + `</channel></rss>`,
|
||||||
|
} {
|
||||||
|
_, err := Parse([]byte(raw), Investing)
|
||||||
|
if err == nil || strings.Contains(err.Error(), "PRIVATE") || strings.Contains(err.Error(), "http") {
|
||||||
|
t.Fatal("RSS bound or sanitized error contract failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestRSSArticleReferencesAreNotTransportTargets(t *testing.T) {
|
||||||
|
raw := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>`
|
||||||
|
for _, u := range []string{"https://127.0.0.1/private", "http://www.investing.com/news/fixture", "https://www.investing.com.evil.invalid/news/fixture", "https://private:secret@www.investing.com/news/fixture", "https://www.bloomberg.com/news/articles/fixture"} {
|
||||||
|
raw += `<item><title>Synthetic</title><link>` + u + `</link></item>`
|
||||||
|
}
|
||||||
|
raw += `</channel></rss>`
|
||||||
|
got, err := Parse([]byte(raw), Investing)
|
||||||
|
if err != nil || len(got) != 0 {
|
||||||
|
t.Fatal("unsafe RSS association was accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBloombergSyntheticFixtureAndNamespacedContent(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("testdata/bloomberg.xml")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := Parse(raw, Bloomberg)
|
||||||
|
if err != nil || len(got) != 1 || got[0].PublishedAt == nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
|
||||||
|
t.Fatal("Bloomberg RSS content/date contract failed")
|
||||||
|
}
|
||||||
|
// A lookalike extension cannot assert or replace trusted content:encoded.
|
||||||
|
fake := `<rss xmlns:fake="urn:fixture"><channel><item><title>Synthetic headline</title><link>https://www.investing.com/news/synthetic-fixture</link><description>Synthetic teaser.</description><fake:encoded>Untrusted extension payload</fake:encoded></item></channel></rss>`
|
||||||
|
got, err = Parse([]byte(fake), Investing)
|
||||||
|
if err != nil || len(got) != 1 || got[0].Content != "Synthetic teaser." {
|
||||||
|
t.Fatal("untrusted encoded namespace was accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestRSSItemFieldAndHTMLLimitsFailWithoutTruncation(t *testing.T) {
|
||||||
|
item := `<item><title>Synthetic headline</title><link>https://www.investing.com/news/synthetic-fixture</link></item>`
|
||||||
|
for _, raw := range []string{
|
||||||
|
`<rss><channel>` + strings.Repeat(item, MaxItems+1) + `</channel></rss>`,
|
||||||
|
`<rss><channel><item><title>` + strings.Repeat("x", MaxFieldBytes+1) + `</title></item></channel></rss>`,
|
||||||
|
`<rss><channel><item><description><![CDATA[` + strings.Repeat("<div>", 1000) + `]]></description><title>Synthetic</title><link>https://www.investing.com/news/synthetic-fixture</link></item></channel></rss>`,
|
||||||
|
`<rss><channel><item><title>A</title><title>B</title></item></channel></rss>`,
|
||||||
|
`<rss><channel/><channel/></rss>`,
|
||||||
|
} {
|
||||||
|
if _, err := Parse([]byte(raw), Investing); err == nil || err.Error() != "rss_feed_invalid" {
|
||||||
|
t.Fatal("RSS resource limit/ambiguity was ignored or raw error escaped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestMergeKeepsSemanticLinksDistinctAndRemovesConflictingDates(t *testing.T) {
|
||||||
|
first := time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)
|
||||||
|
second := first.Add(time.Hour)
|
||||||
|
link := "https://www.investing.com/news/fixture?story=1"
|
||||||
|
got := Merge([][]scraper.Article{{{URL: link, PublishedAt: &first}}, {{URL: link + "&utm_source=fixture", PublishedAt: &second}}, {{URL: link, PublishedAt: &first}, {URL: "https://www.investing.com/news/fixture?story=2"}}})
|
||||||
|
if len(got) != 2 || got[0].PublishedAt != nil {
|
||||||
|
t.Fatal("semantic identities were conflated or conflicting date reinstated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTicket41ContractualEncodedBodyCanBeCompleteButMarkersCannot(t *testing.T) {
|
||||||
|
for _, source := range []string{Bloomberg, Investing} {
|
||||||
|
file := "testdata/bloomberg.xml"
|
||||||
|
if source == Investing {
|
||||||
|
file = "testdata/investing.xml"
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(file)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
full, err := Parse(raw, source)
|
||||||
|
if err != nil || len(full) == 0 || scraper.ContentStatus(full[0]) != scraper.ContentComplete {
|
||||||
|
t.Fatal("contractual full-body field was not recognized")
|
||||||
|
}
|
||||||
|
for _, marker := range []string{`<div class="paywall"></div>`, `<div id="challengeGate"></div>`, `<div data-content-state="partial"></div>`, `<div data-content-truncated="true"></div>`, `<div class="placeholder"></div>`} {
|
||||||
|
blocked := strings.Replace(string(raw), "</article>", marker+"</article>", 1)
|
||||||
|
got, err := Parse([]byte(blocked), source)
|
||||||
|
if err != nil || len(got) == 0 || scraper.ContentStatus(got[0]) == scraper.ContentComplete {
|
||||||
|
t.Fatal("restriction/partial marker was promoted to complete")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStableGUIDOnlyItemsDoNotInventLinksOrCollapseUnrelatedItems(t *testing.T) {
|
||||||
|
raw := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>`
|
||||||
|
for _, id := range []string{"opaque-one", "opaque-two", "opaque-one"} {
|
||||||
|
raw += `<item><guid>` + id + `</guid><title>Synthetic headline</title><content:encoded><![CDATA[<p>Synthetic complete body.</p>]]></content:encoded></item>`
|
||||||
|
}
|
||||||
|
raw += `</channel></rss>`
|
||||||
|
got, err := Parse([]byte(raw), Investing)
|
||||||
|
if err != nil || len(got) != 3 {
|
||||||
|
t.Fatal("stable GUID-only items lost")
|
||||||
|
}
|
||||||
|
merged := Merge([][]scraper.Article{got})
|
||||||
|
if len(merged) != 2 || merged[0].URL != "" || scraper.ContentStatus(merged[0]) != scraper.ContentComplete {
|
||||||
|
t.Fatal("opaque identity invented URL or collapsed distinct GUIDs")
|
||||||
|
}
|
||||||
|
}
|
||||||
5
backend/internal/scraper/quanwenrss/testdata/bloomberg.xml
vendored
Normal file
5
backend/internal/scraper/quanwenrss/testdata/bloomberg.xml
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<!-- Synthetic fixture only. Representative approved content:encoded full-text contract. -->
|
||||||
|
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
<channel><item><title>Synthetic Bloomberg headline</title><link>https://www.bloomberg.com/news/articles/2026-01-02/synthetic-fixture</link><dc:date>2026-01-02T03:04:05Z</dc:date><content:encoded><![CDATA[<article><p>Synthetic first paragraph.</p><p>Final synthetic paragraph.</p></article>]]></content:encoded></item></channel>
|
||||||
|
</rss>
|
||||||
7
backend/internal/scraper/quanwenrss/testdata/investing.xml
vendored
Normal file
7
backend/internal/scraper/quanwenrss/testdata/investing.xml
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<!-- Synthetic fixture only; no publisher HTML or article text. -->
|
||||||
|
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||||
|
<channel>
|
||||||
|
<item><title>Synthetic editorial headline</title><link>https://www.investing.com/news/stock-market-news/synthetic-fixture</link><pubDate>Fri, 02 Jan 2026 03:04:05 GMT</pubDate><description>Synthetic teaser.</description><content:encoded><![CDATA[<article><h2>Synthetic heading.</h2><p>Synthetic first paragraph.</p><script>EXCLUDED script</script><nav>EXCLUDED navigation</nav><aside>EXCLUDED sidebar</aside><div class="advertisement">EXCLUDED ad</div><p>Final synthetic paragraph.</p></article>]]></content:encoded></item>
|
||||||
|
<item><title>Synthetic second headline</title><link>https://www.investing.com/news/economy-news/synthetic-second</link><pubDate>unreliable fixture date</pubDate><description><![CDATA[<p>Synthetic teaser only.</p>]]></description></item>
|
||||||
|
</channel></rss>
|
||||||
@ -26,6 +26,7 @@ func ContentStatus(a Article) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Article struct {
|
type Article struct {
|
||||||
|
FeedGUID string
|
||||||
ContentState string
|
ContentState string
|
||||||
Source string
|
Source string
|
||||||
Title string
|
Title string
|
||||||
@ -41,6 +42,16 @@ type Scraper interface {
|
|||||||
Scrape(ctx context.Context, symbols []string) ([]Article, error)
|
Scrape(ctx context.Context, symbols []string) ([]Article, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FeedCounts contains only aggregate fetch outcomes, never feed/article values.
|
||||||
|
type FeedCounts struct {
|
||||||
|
Attempted int `json:"attempted"`
|
||||||
|
Succeeded int `json:"succeeded"`
|
||||||
|
Failed int `json:"failed"`
|
||||||
|
}
|
||||||
|
type ReportedScraper interface {
|
||||||
|
ScrapeWithDiagnostics(context.Context, []string) ([]Article, FeedCounts, error)
|
||||||
|
}
|
||||||
|
|
||||||
// ArticleEnricher is an optional, transient enrichment port. Generation calls
|
// ArticleEnricher is an optional, transient enrichment port. Generation calls
|
||||||
// it only after source limits, never for the full collected list.
|
// it only after source limits, never for the full collected list.
|
||||||
type ArticleEnricher interface {
|
type ArticleEnricher interface {
|
||||||
|
|||||||
@ -70,7 +70,7 @@ func NewTransport(resolver Resolver, dial DialFunc) *http.Transport {
|
|||||||
return nil, errUnavailable
|
return nil, errUnavailable
|
||||||
}
|
}
|
||||||
switch strings.ToLower(host) {
|
switch strings.ToLower(host) {
|
||||||
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com":
|
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com":
|
||||||
default:
|
default:
|
||||||
return nil, errUnavailable
|
return nil, errUnavailable
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,7 +24,7 @@ func (f resolverFunc) LookupNetIP(c context.Context, n, h string) ([]netip.Addr,
|
|||||||
return f(c, n, h)
|
return f(c, n, h)
|
||||||
}
|
}
|
||||||
func TestForbiddenDNSAnswersNeverDial(t *testing.T) {
|
func TestForbiddenDNSAnswersNeverDial(t *testing.T) {
|
||||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||||
for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} {
|
for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} {
|
||||||
t.Run(host+"/"+value, func(t *testing.T) {
|
t.Run(host+"/"+value, func(t *testing.T) {
|
||||||
dials := 0
|
dials := 0
|
||||||
@ -67,7 +67,7 @@ func TestDNSFailsClosedAndNumericPinning(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
|
func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
|
||||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||||
t.Run(host, func(t *testing.T) {
|
t.Run(host, func(t *testing.T) {
|
||||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
|
template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
|
||||||
@ -116,7 +116,7 @@ func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestEveryNewConnectionRevalidatesDNS(t *testing.T) {
|
func TestEveryNewConnectionRevalidatesDNS(t *testing.T) {
|
||||||
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
|
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com", "feed.quanwenrss.com"} {
|
||||||
lookups, dials := 0, 0
|
lookups, dials := 0, 0
|
||||||
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
|
||||||
lookups++
|
lookups++
|
||||||
|
|||||||
65
backend/internal/sourcefeeds/config.go
Normal file
65
backend/internal/sourcefeeds/config.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
// Package sourcefeeds defines the closed, shared admin/runtime RSS allowlist.
|
||||||
|
package sourcefeeds
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const Bloomberg = "bloomberg"
|
||||||
|
const Investing = "investing_com"
|
||||||
|
const Host = "feed.quanwenrss.com"
|
||||||
|
const MaxFeeds = 5
|
||||||
|
|
||||||
|
var ErrInvalid = errors.New("source_feeds_invalid")
|
||||||
|
var ErrUnsupported = errors.New("source_feeds_not_supported")
|
||||||
|
|
||||||
|
func Supported(source string) bool { return source == Bloomberg || source == Investing }
|
||||||
|
func Defaults(source string) []string {
|
||||||
|
var paths []string
|
||||||
|
switch source {
|
||||||
|
case Bloomberg:
|
||||||
|
paths = []string{"bloomberg-latest.xml", "bloomberg-economics.xml", "bloomberg-technology.xml", "bloomberg-politics.xml", "bloomberg-technology-ai.xml"}
|
||||||
|
case Investing:
|
||||||
|
paths = []string{"investing-news.xml"}
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(paths))
|
||||||
|
for _, path := range paths {
|
||||||
|
out = append(out, "https://"+Host+"/feed/"+path)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func Validate(source string, values []string) ([]string, error) {
|
||||||
|
if !Supported(source) {
|
||||||
|
return nil, ErrUnsupported
|
||||||
|
}
|
||||||
|
allowed := Defaults(source)
|
||||||
|
if len(values) == 0 || len(values) > len(allowed) {
|
||||||
|
return nil, ErrInvalid
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
out := make([]string, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
if len(value) > 256 || value != strings.TrimSpace(value) || strings.Contains(value, "#") {
|
||||||
|
return nil, ErrInvalid
|
||||||
|
}
|
||||||
|
u, err := url.Parse(value)
|
||||||
|
if err != nil || u.Scheme != "https" || (!strings.EqualFold(u.Host, Host) && !strings.EqualFold(u.Host, Host+":443")) || u.User != nil || u.Opaque != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.RawPath != "" || (u.Port() != "" && u.Port() != "443") {
|
||||||
|
return nil, ErrInvalid
|
||||||
|
}
|
||||||
|
normalized := "https://" + Host + u.Path
|
||||||
|
matched := false
|
||||||
|
for _, known := range allowed {
|
||||||
|
if normalized == known {
|
||||||
|
matched = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !matched || seen[normalized] {
|
||||||
|
return nil, ErrInvalid
|
||||||
|
}
|
||||||
|
seen[normalized] = true
|
||||||
|
out = append(out, normalized)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
28
backend/internal/sourcefeeds/config_test.go
Normal file
28
backend/internal/sourcefeeds/config_test.go
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package sourcefeeds
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestAdminAndRuntimeUseClosedSourceSpecificFeedAllowlist(t *testing.T) {
|
||||||
|
for _, source := range []string{Bloomberg, Investing} {
|
||||||
|
defaults := Defaults(source)
|
||||||
|
if _, err := Validate(source, defaults); err != nil {
|
||||||
|
t.Fatal("approved defaults rejected")
|
||||||
|
}
|
||||||
|
for _, bad := range [][]string{nil, {""}, {"http://" + Host + "/feed/investing-news.xml"}, {"https://127.0.0.1/feed/investing-news.xml"}, {"https://" + Host + ".evil.invalid/feed/investing-news.xml"}, {"https://user:secret@" + Host + "/feed/investing-news.xml"}, {"https://" + Host + ":444/feed/investing-news.xml"}, {"https://" + Host + "/feed/unknown.xml"}, {defaults[0] + "?key=secret"}, {defaults[0] + "#"}, {defaults[0], defaults[0]}, {"https://" + Host + "/feed/%69nvesting-news.xml"}} {
|
||||||
|
if _, err := Validate(source, bad); err != ErrInvalid {
|
||||||
|
t.Fatal("invalid source feed configuration accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := Validate(Bloomberg, Defaults(Investing)); err != ErrInvalid {
|
||||||
|
t.Fatal("cross-source feed accepted")
|
||||||
|
}
|
||||||
|
if _, err := Validate("yahoo_finance", Defaults(Investing)); err != ErrUnsupported {
|
||||||
|
t.Fatal("non-RSS source accepted feed mutation")
|
||||||
|
}
|
||||||
|
original := Defaults(Bloomberg)
|
||||||
|
original[0] = "private"
|
||||||
|
if Defaults(Bloomberg)[0] == "private" {
|
||||||
|
t.Fatal("mutable allowlist")
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -47,3 +47,78 @@ Le frontend protège ses pages, mais l’autorisation reste côté API. La PWA u
|
|||||||
`LayaRanker` est un port séparé. La composition production injecte `NewLayaHTTPRanker`, adapter du protocole HTTP officiel Laya v0.5.2, checkpoint `multilingual` explicite. Il associe les résultats par position, valide score/confiance/abstention/troncature et trie de façon stable sur tous les lots de 64 maximum. Tout échec annule le résultat complet, sans retry ni fallback vers le rôle filter ou le provider de synthèse. Les articles restent en mémoire ; aucune archive n’est ajoutée. L’E2E conserve son fake explicitement identifié et n’instancie pas cet adapter réel.
|
`LayaRanker` est un port séparé. La composition production injecte `NewLayaHTTPRanker`, adapter du protocole HTTP officiel Laya v0.5.2, checkpoint `multilingual` explicite. Il associe les résultats par position, valide score/confiance/abstention/troncature et trie de façon stable sur tous les lots de 64 maximum. Tout échec annule le résultat complet, sans retry ni fallback vers le rôle filter ou le provider de synthèse. Les articles restent en mémoire ; aucune archive n’est ajoutée. L’E2E conserve son fake explicitement identifié et n’instancie pas cet adapter réel.
|
||||||
|
|
||||||
Les snapshots `summary_model_id`, `provider_name`, `model_name` des nouvelles synthèses décrivent la paire résolue au début de génération ; les noms sont persistés indépendamment du catalogue. La sélection par compte et les références FK protègent la suppression des modèles sélectionnés. La migration 000016 est un bloc SQL atomique et conserve les données/settings/providers historiques. Les champs snapshot des anciennes synthèses restent NULL.
|
Les snapshots `summary_model_id`, `provider_name`, `model_name` des nouvelles synthèses décrivent la paire résolue au début de génération ; les noms sont persistés indépendamment du catalogue. La sélection par compte et les références FK protègent la suppression des modèles sélectionnés. La migration 000016 est un bloc SQL atomique et conserve les données/settings/providers historiques. Les champs snapshot des anciennes synthèses restent NULL.
|
||||||
|
|
||||||
|
## Sources RSS QuanwenRSS — ticket #41
|
||||||
|
|
||||||
|
La composition applicative utilise désormais `quanwenrss.Collector` pour Bloomberg
|
||||||
|
(`bloomberg`) et Investing.com (`investing_com`). Yahoo Finance et CNBC Business
|
||||||
|
restent enregistrés et inchangés. Les anciennes lignes, credentials et références
|
||||||
|
historiques Bloomberg restent conservés ; le parcours RSS n'utilise pas leurs
|
||||||
|
credentials et ne suit aucun lien d'article.
|
||||||
|
|
||||||
|
La migration 000021 ajoute `source_feeds(source_id, position, url)` et une source
|
||||||
|
Investing.com distincte (activée, plafond 20). Bloomberg conserve son ID, son état
|
||||||
|
et son plafond ; ses cinq flux initiaux sont latest, economics, technology,
|
||||||
|
politics et technology-ai. Investing.com reçoit investing-news. Tous utilisent
|
||||||
|
HTTPS et l'hôte exact `feed.quanwenrss.com`, sous les six chemins explicitement
|
||||||
|
approuvés `/feed/<nom>.xml`. Le downgrade désactive seulement Investing.com ; il
|
||||||
|
ne supprime ni configuration ni historique.
|
||||||
|
|
||||||
|
Contrat admin, compatible avec les commandes d'activation/plafond existantes :
|
||||||
|
|
||||||
|
- `GET /api/admin/sources` ajoute `feed_urls: string[]` pour les deux sources RSS.
|
||||||
|
Ces URLs sont des données de configuration administrateur, pas des diagnostics.
|
||||||
|
- `PUT /api/admin/sources/:id` reçoit `enabled: boolean`, `article_limit?: number`
|
||||||
|
(1–200) et `feed_urls?: string[]`. Le champ omis conserve les feeds ; une liste
|
||||||
|
fournie remplace l'ensemble et son ordre en transaction avec les autres réglages.
|
||||||
|
Envoyer l'état `enabled` courant lors d'une modification des feeds.
|
||||||
|
- Une liste RSS doit contenir 1–5 URLs Bloomberg ou l'unique URL Investing.com,
|
||||||
|
sans doublon et exclusivement des chemins autorisés pour cet éditeur. Hôte
|
||||||
|
insensible à la casse et port 443 explicite sont normalisés avant sauvegarde.
|
||||||
|
Query, fragment, userinfo, encodage alternatif du chemin et autres ports sont
|
||||||
|
refusés. Les sources non RSS refusent `feed_urls`. Le JSON est borné à 8192 octets,
|
||||||
|
sans champs inconnus ni valeur `null` pour le document ou les feeds.
|
||||||
|
- Succès 200 `{data:{ok:true}}`. Erreur 400 `source_feeds_invalid`,
|
||||||
|
`source_feeds_not_supported` ou `source_configuration_invalid` ; source historique
|
||||||
|
non opérationnelle 409 `source_not_supported`, inconnue 404, erreur locale 500
|
||||||
|
`source_configuration_unavailable`. Aucun message brut ou URL dans les erreurs.
|
||||||
|
Le contrôle admin relit le rôle courant. L'enregistrement ne lance aucun fetch.
|
||||||
|
|
||||||
|
Chaque génération recharge et revalide la configuration persistée. Le transport
|
||||||
|
partagé épingle une IP publique vérifiée, conserve Host/SNI, ignore les proxies
|
||||||
|
d'environnement et revalide les redirections même hôte/chemin approuvé, avec un
|
||||||
|
maximum de deux redirections suivies. Les liens des items ne sont que des
|
||||||
|
identifiants transitoires : aucun fetch, y compris lorsqu'ils contiennent un GUID
|
||||||
|
opaque sans lien (dans ce cas l'URL reste absente, elle n'est jamais inventée).
|
||||||
|
|
||||||
|
Limites : cinq feeds maximum, 45 s par source, 10 s par requête, 4 Mio XML
|
||||||
|
décompressé par réponse, 12 Mio cumulés par source, 200 items/feed, 256 Kio/champ,
|
||||||
|
profondeur XML 32 et HTML 64. Une limite dépassée provoque un échec explicite du
|
||||||
|
feed, pas un texte tronqué. Les autres feeds valides sont conservés ; aucun feed
|
||||||
|
valide donne une source indisponible. Les compteurs `source_stats[].feeds` sont
|
||||||
|
`{attempted,succeeded,failed}` : feeds configurés examinés, validés et échoués,
|
||||||
|
y compris les échecs de budget avant transport. `status: partial` signale un
|
||||||
|
échec partiel. Ces compteurs n'exposent ni URL, titre, contenu ni erreur brute.
|
||||||
|
|
||||||
|
La fixture contractuelle identifie le champ namespacé `content:encoded` comme
|
||||||
|
corps intégral de ces endpoints QuanwenRSS. Seul ce champ peut être `complete` :
|
||||||
|
corps nettoyé non vide et différent du titre, identité stable URL/GUID, tailles
|
||||||
|
respectées, absence de marqueur paywall/challenge/placeholder/partial/truncated.
|
||||||
|
Une description seule est `incomplete` ; un corps vide est `unavailable`.
|
||||||
|
Un champ absent ou une extension homonyme dans un autre namespace ne devient
|
||||||
|
jamais complet par supposition. Les fixtures sont synthétiques et représentatives,
|
||||||
|
sans HTML éditeur capturé ; aucun contenu live n'a été vérifié dans ce lot.
|
||||||
|
|
||||||
|
La fusion utilise l'URL normalisée (sans paramètres utm/fragments) ou le GUID par
|
||||||
|
source, y compris les alias reliés par l'un des deux. Elle conserve l'identité du
|
||||||
|
premier listing, le corps de meilleure qualité disponible sans rehausser son état,
|
||||||
|
et neutralise les dates contradictoires. Tri stable par date observée décroissante,
|
||||||
|
dates absentes à la fin, puis plafond source dans le use case existant. `pubDate`
|
||||||
|
et `dc:date` valides sont observés ; aucune date actuelle n'est ajoutée.
|
||||||
|
|
||||||
|
Les trois passes existantes sont conservées : sélection littérale, Laya direct,
|
||||||
|
Laya indirect. En `title_content`, seuls les articles complets entrent dans la
|
||||||
|
sélection. Le contrat #39 demeure : titre, date nullable, source et corps intégral,
|
||||||
|
watchlist, contexte personnalisé, langue et budget de prompt avant synthèse.
|
||||||
|
Les candidats/GUID/corps restent en mémoire ; seules synthèse et statistiques
|
||||||
|
agrégées sont persistées.
|
||||||
|
|||||||
@ -374,3 +374,23 @@ Il réutilise les collectors/enrichers de production, borne l'enrichissement à
|
|||||||
1–3 articles/source et n'exécute ni Laya, ni synthèse, ni DB. L'image offline
|
1–3 articles/source et n'exécute ni Laya, ni synthèse, ni DB. L'image offline
|
||||||
s'exécute sans réseau ; les diagnostics ne contiennent que des agrégats. Un lien
|
s'exécute sans réseau ; les diagnostics ne contiennent que des agrégats. Un lien
|
||||||
réassocié n'est jamais, à lui seul, une preuve de corps complet.
|
réassocié n'est jamais, à lui seul, une preuve de corps complet.
|
||||||
|
|
||||||
|
### Configuration RSS des sources (ticket #41)
|
||||||
|
|
||||||
|
Après migration 000021, Bloomberg utilise cinq flux QuanwenRSS et Investing.com
|
||||||
|
un flux dédié. L'administration `Sources et plafonds` permet d'enregistrer les
|
||||||
|
feeds, états et plafonds ; aucun accès réseau n'est déclenché par cet enregistrement.
|
||||||
|
Le contrat détaillé et les limites figurent dans `docs/architecture.md`, section
|
||||||
|
« Sources RSS QuanwenRSS — ticket #41 ». Yahoo et CNBC restent disponibles.
|
||||||
|
|
||||||
|
Le backend a uniquement besoin d'accéder aux chemins RSS approuvés sur
|
||||||
|
`feed.quanwenrss.com:443` pour ces deux sources. Il ne visite pas les articles et
|
||||||
|
n'a besoin d'aucun login Bloomberg pour ce parcours. Les anciens credentials et
|
||||||
|
outils de diagnostic Puppeteer restent conservés ; le bench d'ingestion historique
|
||||||
|
ne représente pas le nouveau parcours RSS de la génération applicative.
|
||||||
|
|
||||||
|
Ne pas interpréter une réponse RSS accessible comme la preuve que tous les items
|
||||||
|
ont un corps complet : consulter les compteurs de feeds et de complétude du bilan.
|
||||||
|
En cas de changement du format réel, un `content:encoded` absent ne devient pas
|
||||||
|
complet par fallback sur `description`. Les tests et fixtures de ce lot n'effectuent
|
||||||
|
aucun contrôle live des feeds.
|
||||||
|
|||||||
@ -22,10 +22,10 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
|
|||||||
await expect(page.getByRole('heading', { name: 'Sources et plafonds' })).toBeVisible()
|
await expect(page.getByRole('heading', { name: 'Sources et plafonds' })).toBeVisible()
|
||||||
|
|
||||||
const activationControls = page.locator('button[aria-label^="Activer "], button[aria-label^="Désactiver "]')
|
const activationControls = page.locator('button[aria-label^="Activer "], button[aria-label^="Désactiver "]')
|
||||||
await expect(activationControls).toHaveCount(3)
|
await expect(activationControls).toHaveCount(4)
|
||||||
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
|
const activationNames = (await activationControls.evaluateAll(nodes => nodes.map(node => node.getAttribute('aria-label').replace(/^(Activer|Désactiver) /, '')).sort()))
|
||||||
expect(activationNames).toEqual(['Bloomberg', 'CNBC Business', 'Yahoo Finance'])
|
expect(activationNames).toEqual(['Bloomberg', 'CNBC Business', 'Investing.com', 'Yahoo Finance'])
|
||||||
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(3)
|
await expect(page.locator('form[aria-label^="Réglages de "]')).toHaveCount(4)
|
||||||
|
|
||||||
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
|
const historical = page.getByRole('region', { name: 'Anciennes sources exclues' })
|
||||||
await expect(historical).toBeVisible()
|
await expect(historical).toBeVisible()
|
||||||
@ -43,7 +43,7 @@ test('admin source controls stay accessible and fit at 320, 375 and 390 px', asy
|
|||||||
expect(dimensions.document, `horizontal overflow at ${width}px: ${JSON.stringify(dimensions)}`).toBeLessThanOrEqual(dimensions.viewport)
|
expect(dimensions.document, `horizontal overflow at ${width}px: ${JSON.stringify(dimensions)}`).toBeLessThanOrEqual(dimensions.viewport)
|
||||||
|
|
||||||
await expect(page.getByRole('spinbutton', { name: 'Articles max par résumé' })).toBeVisible()
|
await expect(page.getByRole('spinbutton', { name: 'Articles max par résumé' })).toBeVisible()
|
||||||
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business']) {
|
for (const name of ['Yahoo Finance', 'Bloomberg', 'CNBC Business', 'Investing.com']) {
|
||||||
const toggle = page.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) })
|
const toggle = page.getByRole('button', { name: new RegExp(`^(?:Activer|Désactiver) ${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) })
|
||||||
const cap = page.getByRole('spinbutton', { name: `Plafond ${name}` })
|
const cap = page.getByRole('spinbutton', { name: `Plafond ${name}` })
|
||||||
await expect(toggle).toBeVisible()
|
await expect(toggle).toBeVisible()
|
||||||
|
|||||||
@ -13,6 +13,7 @@ export interface OllamaModelInfo {
|
|||||||
}
|
}
|
||||||
export interface Source {
|
export interface Source {
|
||||||
id: string; name: string; type: string; enabled: boolean; article_limit: number
|
id: string; name: string; type: string; enabled: boolean; article_limit: number
|
||||||
|
feed_urls?: string[]
|
||||||
source_key: string | null; supported: boolean; operational: boolean
|
source_key: string | null; supported: boolean; operational: boolean
|
||||||
}
|
}
|
||||||
export interface Setting { key: string; value: string }
|
export interface Setting { key: string; value: string }
|
||||||
@ -55,6 +56,9 @@ export const adminApi = {
|
|||||||
updateSource: (id: string, enabled: boolean, article_limit?: number) =>
|
updateSource: (id: string, enabled: boolean, article_limit?: number) =>
|
||||||
api.put<void>(`/admin/sources/${id}`, { enabled, ...(article_limit === undefined ? {} : { article_limit }) }),
|
api.put<void>(`/admin/sources/${id}`, { enabled, ...(article_limit === undefined ? {} : { article_limit }) }),
|
||||||
|
|
||||||
|
updateSourceFeeds: (id: string, enabled: boolean, feed_urls: string[]) =>
|
||||||
|
api.put<void>(`/admin/sources/${encodeURIComponent(id)}`, { enabled, feed_urls }),
|
||||||
|
|
||||||
// Settings
|
// Settings
|
||||||
listSettings: () => api.get<Setting[]>('/admin/settings'),
|
listSettings: () => api.get<Setting[]>('/admin/settings'),
|
||||||
updateSettings: (settings: Setting[]) => api.put<void>('/admin/settings', { settings }),
|
updateSettings: (settings: Setting[]) => api.put<void>('/admin/settings', { settings }),
|
||||||
|
|||||||
@ -26,6 +26,7 @@ export interface PromptBudgetUsage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface SourceGenerationStat extends ContentCompleteness {
|
export interface SourceGenerationStat extends ContentCompleteness {
|
||||||
|
feeds?: { attempted: number; succeeded: number; failed: number } | null
|
||||||
source_id: string
|
source_id: string
|
||||||
source_key?: string | null
|
source_key?: string | null
|
||||||
source_type: string
|
source_type: string
|
||||||
|
|||||||
@ -4,6 +4,7 @@ function sourceLabel(key?: string | null) {
|
|||||||
switch (key) {
|
switch (key) {
|
||||||
case 'yahoo_finance': return 'Yahoo Finance'
|
case 'yahoo_finance': return 'Yahoo Finance'
|
||||||
case 'bloomberg': return 'Bloomberg'
|
case 'bloomberg': return 'Bloomberg'
|
||||||
|
case 'investing_com': return 'Investing.com'
|
||||||
case 'cnbc_business': return 'CNBC Business'
|
case 'cnbc_business': return 'CNBC Business'
|
||||||
default: return 'Source non identifiée'
|
default: return 'Source non identifiée'
|
||||||
}
|
}
|
||||||
@ -11,20 +12,23 @@ function sourceLabel(key?: string | null) {
|
|||||||
|
|
||||||
function sourceState(source: SourceGenerationStat, mode: GenerationOutcome['ranking_mode']) {
|
function sourceState(source: SourceGenerationStat, mode: GenerationOutcome['ranking_mode']) {
|
||||||
if (source.status === 'failed') return 'Récupération impossible'
|
if (source.status === 'failed') return 'Récupération impossible'
|
||||||
if (source.status !== 'ok') return 'État de collecte non renseigné'
|
if (source.status !== 'ok' && source.status !== 'partial') return 'État de collecte non renseigné'
|
||||||
if (mode === 'title') return 'Source joignable · contenu non évalué'
|
const collection = source.status === 'partial' ? 'Récupération partielle' : 'Source joignable'
|
||||||
|
if (mode === 'title') return `${collection} · contenu non évalué`
|
||||||
const counts = [source.content_complete, source.content_incomplete, source.content_unavailable]
|
const counts = [source.content_complete, source.content_incomplete, source.content_unavailable]
|
||||||
if (counts.some(count => count === undefined)) return 'Source joignable · complétude non renseignée'
|
if (counts.some(count => count === undefined)) return `${collection} · complétude non renseignée`
|
||||||
if (source.candidates === 0) return 'Source joignable · aucun article examiné'
|
if (source.candidates === 0) return `${collection} · aucun article examiné`
|
||||||
if (counts.filter(count => (count ?? 0) > 0).length > 1) return 'Source joignable · contenus de complétude variable'
|
if (counts.filter(count => (count ?? 0) > 0).length > 1) return `${collection} · contenus de complétude variable`
|
||||||
if ((source.content_complete ?? 0) > 0) return 'Source joignable · contenus complets'
|
if ((source.content_complete ?? 0) > 0) return `${collection} · contenus complets`
|
||||||
if ((source.content_incomplete ?? 0) > 0) return 'Source joignable · contenu partiel'
|
if ((source.content_incomplete ?? 0) > 0) return `${collection} · contenu partiel`
|
||||||
if ((source.content_unavailable ?? 0) > 0) return 'Source joignable · contenu absent'
|
if ((source.content_unavailable ?? 0) > 0) return `${collection} · contenu absent`
|
||||||
return 'Source joignable · complétude non renseignée'
|
return `${collection} · complétude non renseignée`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
||||||
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_key))
|
const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_key))
|
||||||
|
const partialFeeds = outcome.source_stats.filter(source => source.status === 'partial').map(source => sourceLabel(source.source_key))
|
||||||
|
const hasFeedCounts = outcome.source_stats.some(source => source.feeds != null)
|
||||||
const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined
|
const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined
|
||||||
const usage = outcome.prompt_budget
|
const usage = outcome.prompt_budget
|
||||||
const number = (value: number) => value.toLocaleString('fr-FR')
|
const number = (value: number) => value.toLocaleString('fr-FR')
|
||||||
@ -36,6 +40,7 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
|||||||
{unavailable.length > 0 && <p>Cette synthèse a été générée sans {unavailable.join(', ')}, indisponible lors du traitement.</p>}
|
{unavailable.length > 0 && <p>Cette synthèse a été générée sans {unavailable.join(', ')}, indisponible lors du traitement.</p>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{partialFeeds.length > 0 && <p>Certains flux RSS de {partialFeeds.join(', ')} n’ont pas pu être récupérés. Les articles des autres flux restent pris en compte.</p>}
|
||||||
<p>{outcome.total_candidates} articles examinés · {outcome.laya_selected} sélectionnés par Laya · {outcome.selected} retenus après plafonds</p>
|
<p>{outcome.total_candidates} articles examinés · {outcome.laya_selected} sélectionnés par Laya · {outcome.selected} retenus après plafonds</p>
|
||||||
<div className="space-y-1" aria-label="Complétude des articles">
|
<div className="space-y-1" aria-label="Complétude des articles">
|
||||||
<p>Les compteurs portent sur les articles examinés après plafonds par source, avant sélection et plafond global.</p>
|
<p>Les compteurs portent sur les articles examinés après plafonds par source, avant sélection et plafond global.</p>
|
||||||
@ -66,12 +71,13 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {
|
|||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full text-sm text-left">
|
<table className="w-full text-sm text-left">
|
||||||
<caption className="text-left font-medium">Bilan par source</caption>
|
<caption className="text-left font-medium">Bilan par source</caption>
|
||||||
<thead><tr><th scope="col">Source</th><th scope="col">Collecte et complétude</th><th scope="col">Articles examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
|
<thead><tr><th scope="col">Source</th><th scope="col">Collecte et complétude</th><th scope="col">Articles examinés</th><th scope="col">Sélectionnés par Laya</th><th scope="col">Retenus</th><th scope="col">Plafond</th><th scope="col">Dates disponibles</th>{hasFeedCounts && <th scope="col">Récupération des flux RSS</th>}{outcome.ranking_mode === 'title_content' && <><th scope="col">Contenus complets</th><th scope="col">Contenus partiels</th><th scope="col">Contenus absents</th></>}</tr></thead>
|
||||||
<tbody>{outcome.source_stats.map(source => (
|
<tbody>{outcome.source_stats.map(source => (
|
||||||
<tr key={source.source_id}>
|
<tr key={source.source_id}>
|
||||||
<th scope="row">{sourceLabel(source.source_key)}</th>
|
<th scope="row">{sourceLabel(source.source_key)}</th>
|
||||||
<td>{sourceState(source, outcome.ranking_mode)}</td>
|
<td>{sourceState(source, outcome.ranking_mode)}</td>
|
||||||
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td><td>{source.dates_available ?? 'Non renseigné'}</td>
|
<td>{source.candidates}</td><td>{source.laya_selected}</td><td>{source.selected}</td><td>{source.article_limit}</td><td>{source.dates_available ?? 'Non renseigné'}</td>
|
||||||
|
{hasFeedCounts && <td>{source.feeds ? `Tentés : ${source.feeds.attempted} · récupérés : ${source.feeds.succeeded} · en échec : ${source.feeds.failed}` : 'Non renseigné'}</td>}
|
||||||
{outcome.ranking_mode === 'title_content' && <><td>{source.content_complete ?? 'Non renseigné'}</td><td>{source.content_incomplete ?? 'Non renseigné'}</td><td>{source.content_unavailable ?? 'Non renseigné'}</td></>}
|
{outcome.ranking_mode === 'title_content' && <><td>{source.content_complete ?? 'Non renseigné'}</td><td>{source.content_incomplete ?? 'Non renseigné'}</td><td>{source.content_unavailable ?? 'Non renseigné'}</td></>}
|
||||||
</tr>
|
</tr>
|
||||||
))}</tbody>
|
))}</tbody>
|
||||||
|
|||||||
112
frontend/src/components/SourceFeedsEditor.tsx
Normal file
112
frontend/src/components/SourceFeedsEditor.tsx
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
import { useRef, useState, type FormEvent } from 'react'
|
||||||
|
import { ApiError } from '@/api/client'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
interface SourceFeedsEditorProps {
|
||||||
|
sourceId: string
|
||||||
|
sourceKey: string
|
||||||
|
sourceName: string
|
||||||
|
urls: string[]
|
||||||
|
disabled?: boolean
|
||||||
|
onSave: (urls: string[]) => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const FEED_PATHS: Record<string, readonly string[]> = {
|
||||||
|
bloomberg: ['bloomberg-latest', 'bloomberg-economics', 'bloomberg-technology', 'bloomberg-politics', 'bloomberg-technology-ai'],
|
||||||
|
investing_com: ['investing-news'],
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateUrl(value: string, sourceKey: string): string | null {
|
||||||
|
try {
|
||||||
|
if (value !== value.trim() || value.length > 256) return null
|
||||||
|
const path = /^https:\/\/[^/?#]+(\/[^?#]*)$/.exec(value)?.[1]
|
||||||
|
const url = new URL(value)
|
||||||
|
if (url.protocol !== 'https:' || url.hostname !== 'feed.quanwenrss.com' || url.port ||
|
||||||
|
url.username || url.password || value.includes('#') || value.includes('?') ||
|
||||||
|
!Object.prototype.hasOwnProperty.call(FEED_PATHS, sourceKey) || !FEED_PATHS[sourceKey].some(name => path === `/feed/${name}.xml` && url.pathname === path)) return null
|
||||||
|
return url.href
|
||||||
|
} catch { return null }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SourceFeedsEditor({ sourceId, sourceKey, sourceName, urls, onSave, disabled = false }: SourceFeedsEditorProps) {
|
||||||
|
const [rows, setRows] = useState(() => urls.map((url, id) => ({ id, url })))
|
||||||
|
const [errors, setErrors] = useState<Record<number, string>>({})
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [saving, setSaving] = useState(false)
|
||||||
|
const [saved, setSaved] = useState(false)
|
||||||
|
const nextId = useRef(urls.length)
|
||||||
|
const fields = useRef(new Map<number, HTMLInputElement>())
|
||||||
|
const addButton = useRef<HTMLButtonElement>(null)
|
||||||
|
|
||||||
|
function clearMessages() { setErrors({}); setError(''); setSaved(false) }
|
||||||
|
function focusRow(id?: number) {
|
||||||
|
setTimeout(() => {
|
||||||
|
const field = id === undefined ? undefined : fields.current.get(id)
|
||||||
|
if (field) field.focus()
|
||||||
|
else addButton.current?.focus()
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
|
function add() {
|
||||||
|
const id = nextId.current++
|
||||||
|
setRows(current => [...current, { id, url: '' }]); clearMessages(); focusRow(id)
|
||||||
|
}
|
||||||
|
function remove(id: number, index: number) {
|
||||||
|
const remaining = rows.filter(row => row.id !== id)
|
||||||
|
setRows(remaining); clearMessages(); focusRow(remaining[Math.min(index, remaining.length - 1)]?.id)
|
||||||
|
}
|
||||||
|
async function save(event: FormEvent) {
|
||||||
|
event.preventDefault()
|
||||||
|
if (saving || disabled) return
|
||||||
|
clearMessages()
|
||||||
|
if (!rows.length) { setError('Ajoutez au moins un flux RSS pour enregistrer.'); return }
|
||||||
|
const invalid: Record<number, string> = {}
|
||||||
|
const normalized: string[] = []
|
||||||
|
for (const row of rows) {
|
||||||
|
const url = validateUrl(row.url, sourceKey)
|
||||||
|
if (!row.url.trim()) invalid[row.id] = 'Saisissez une URL de flux RSS.'
|
||||||
|
else if (!url) invalid[row.id] = 'Utilisez une URL RSS HTTPS autorisée pour cette source, sans identifiants, paramètres ni fragment.'
|
||||||
|
else if (normalized.includes(url)) invalid[row.id] = 'Ce flux RSS est déjà présent. Retirez le doublon ou modifiez son URL.'
|
||||||
|
if (url) normalized.push(url)
|
||||||
|
}
|
||||||
|
if (Object.keys(invalid).length) {
|
||||||
|
setErrors(invalid); focusRow(rows.find(row => invalid[row.id])?.id); return
|
||||||
|
}
|
||||||
|
setSaving(true)
|
||||||
|
try { await onSave(normalized); setSaved(true) }
|
||||||
|
catch (error) {
|
||||||
|
if (error instanceof ApiError && error.status === 400 && ['source_feeds_invalid', 'source_feeds_not_supported', 'source_configuration_invalid'].includes(error.message)) {
|
||||||
|
setError('Les flux RSS ont été refusés. Vérifiez les adresses autorisées et les doublons. Votre saisie est conservée.')
|
||||||
|
} else { setError('Impossible d’enregistrer les flux RSS. Votre saisie est conservée. Réessayez.') }
|
||||||
|
}
|
||||||
|
finally { setSaving(false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={save} noValidate aria-label={`Flux RSS ${sourceName}`} aria-busy={saving} className="space-y-3 min-w-0">
|
||||||
|
<p id={`feeds-help-${sourceId}`} className="text-sm text-muted-foreground">Une URL par ligne. Seuls les flux QuanwenRSS autorisés pour cette source sont acceptés. Les modifications s’appliquent aux prochaines synthèses, sans récupération ni génération immédiate. Un flux accessible ne garantit pas un contenu complet.</p>
|
||||||
|
{Object.keys(errors).length > 1 && <p role="alert" className="text-sm text-destructive">Plusieurs flux RSS sont invalides. Corrigez les champs signalés ci-dessous.</p>}
|
||||||
|
{rows.map((row, index) => (
|
||||||
|
<div key={row.id} className="space-y-2 min-w-0">
|
||||||
|
<Label htmlFor={`feed-${sourceId}-${row.id}`}>URL du flux RSS {sourceName} {index + 1}</Label>
|
||||||
|
<div className="flex flex-wrap gap-2 min-w-0">
|
||||||
|
<Input id={`feed-${sourceId}-${row.id}`} type="url" required maxLength={256} autoComplete="off" spellCheck={false}
|
||||||
|
ref={element => { if (element) fields.current.set(row.id, element); else fields.current.delete(row.id) }}
|
||||||
|
className="min-w-0 flex-1 basis-48" disabled={saving || disabled} value={row.url}
|
||||||
|
aria-invalid={!!errors[row.id]} aria-describedby={`feeds-help-${sourceId}${errors[row.id] ? ` feed-error-${sourceId}-${row.id}` : ''}`}
|
||||||
|
onChange={event => { const url = event.target.value; setRows(current => current.map(item => item.id === row.id ? { ...item, url } : item)); clearMessages() }} />
|
||||||
|
<Button type="button" variant="outline" disabled={saving} aria-label={`Retirer le flux RSS ${sourceName} ${index + 1}`} onClick={() => remove(row.id, index)}>Retirer</Button>
|
||||||
|
</div>
|
||||||
|
{errors[row.id] && <p id={`feed-error-${sourceId}-${row.id}`} role="alert" className="text-sm text-destructive">{errors[row.id]}</p>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button ref={addButton} type="button" variant="outline" disabled={saving} aria-label={`Ajouter un flux RSS ${sourceName}`} onClick={add}>Ajouter un flux RSS</Button>
|
||||||
|
<Button type="submit" disabled={saving} aria-label={`Enregistrer les flux RSS ${sourceName}`}>{saving ? 'Enregistrement…' : 'Enregistrer les flux RSS'}</Button>
|
||||||
|
</div>
|
||||||
|
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||||
|
{(saving || saved) && <p role="status">{saving ? 'Enregistrement des flux RSS…' : 'Flux RSS enregistrés pour les prochaines synthèses. Aucune récupération ni génération n’a été lancée.'}</p>}
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,11 +1,12 @@
|
|||||||
import { useState, useEffect, type FormEvent } from 'react'
|
import { useState, useEffect, type FormEvent } from 'react'
|
||||||
import { adminApi, type Source } from '@/api/admin'
|
import { adminApi, type Source } from '@/api/admin'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { SourceFeedsEditor } from '@/components/SourceFeedsEditor'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business'])
|
const SOURCE_KEYS = new Set(['yahoo_finance', 'bloomberg', 'cnbc_business', 'investing_com'])
|
||||||
|
|
||||||
function isSupported(source: Source) {
|
function isSupported(source: Source) {
|
||||||
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
|
return source.supported === true && source.source_key !== null && SOURCE_KEYS.has(source.source_key)
|
||||||
@ -24,6 +25,12 @@ function SourceLimit({ source }: { source: Source }) {
|
|||||||
const [saved, setSaved] = useState('')
|
const [saved, setSaved] = useState('')
|
||||||
const valid = validLimit(limit, 200)
|
const valid = validLimit(limit, 200)
|
||||||
|
|
||||||
|
async function saveFeeds(urls: string[]) {
|
||||||
|
setSaving(true); setSaved(''); setError('')
|
||||||
|
try { await adminApi.updateSourceFeeds(source.id, enabled, urls) }
|
||||||
|
finally { setSaving(false) }
|
||||||
|
}
|
||||||
|
|
||||||
async function toggle() {
|
async function toggle() {
|
||||||
if (saving) return
|
if (saving) return
|
||||||
setSaving(true); setError(''); setSaved('')
|
setSaving(true); setError(''); setSaved('')
|
||||||
@ -61,6 +68,9 @@ function SourceLimit({ source }: { source: Source }) {
|
|||||||
<p id={`limit-help-${source.id}`} className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 200 articles par génération. Le plafond est conservé quand la source est désactivée.' : 'Saisissez un nombre entier de 1 à 200. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
<p id={`limit-help-${source.id}`} className={`text-sm ${valid ? 'text-muted-foreground' : 'text-destructive'}`}>{valid ? 'De 1 à 200 articles par génération. Le plafond est conservé quand la source est désactivée.' : 'Saisissez un nombre entier de 1 à 200. La valeur actuelle est conservée tant que vous ne la modifiez pas.'}</p>
|
||||||
<Button type="submit" disabled={!valid || !enabled || saving} aria-label={`Enregistrer le plafond ${source.name}`}>{saving ? 'Enregistrement…' : 'Enregistrer le plafond'}</Button>
|
<Button type="submit" disabled={!valid || !enabled || saving} aria-label={`Enregistrer le plafond ${source.name}`}>{saving ? 'Enregistrement…' : 'Enregistrer le plafond'}</Button>
|
||||||
</form>
|
</form>
|
||||||
|
{(source.source_key === 'bloomberg' || source.source_key === 'investing_com') && (Array.isArray(source.feed_urls)
|
||||||
|
? <SourceFeedsEditor sourceId={source.id} sourceKey={source.source_key} sourceName={source.name} urls={source.feed_urls} onSave={saveFeeds} disabled={saving} />
|
||||||
|
: <p>Configuration des flux RSS indisponible. Rechargez la page ou contactez votre administrateur.</p>)}
|
||||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||||
{saved && <p role="status">{saved}</p>}
|
{saved && <p role="status">{saved}</p>}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -105,7 +115,7 @@ export function Sources() {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
|
<h1 className="text-2xl font-bold">Sources et plafonds</h1>
|
||||||
<p className="text-sm text-muted-foreground">Seules Yahoo Finance, Bloomberg et CNBC Business peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
|
<p className="text-sm text-muted-foreground">Yahoo Finance, Bloomberg, CNBC Business et Investing.com peuvent participer aux synthèses manuelles et planifiées. Seules les sources activées sont utilisées, dans la limite de leurs plafonds. Modifier ces réglages ne lance aucune récupération d’articles ni génération immédiate.</p>
|
||||||
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? (
|
{loading ? <p role="status">Chargement des sources et plafonds…</p> : loadError ? (
|
||||||
<div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
|
<div className="space-y-3"><p role="alert">{loadError}</p><Button onClick={() => void load()}>Réessayer</Button></div>
|
||||||
) : <>
|
) : <>
|
||||||
@ -124,7 +134,7 @@ export function Sources() {
|
|||||||
</Card>
|
</Card>
|
||||||
{sources.length === 0 && <p>Aucune source disponible.</p>}
|
{sources.length === 0 && <p>Aucune source disponible.</p>}
|
||||||
<div className="grid min-w-0 gap-4 lg:grid-cols-3">
|
<div className="grid min-w-0 gap-4 lg:grid-cols-3">
|
||||||
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source.source_key === 'cnbc_business' ? { ...source, name: 'CNBC Business' } : source} />)}
|
{supported.map(source => <SourceLimit key={source.id} source={source.source_key === 'yahoo_finance' ? { ...source, name: 'Yahoo Finance' } : source.source_key === 'cnbc_business' ? { ...source, name: 'CNBC Business' } : source.source_key === 'investing_com' ? { ...source, name: 'Investing.com' } : source.source_key === 'bloomberg' ? { ...source, name: 'Bloomberg' } : source} />)}
|
||||||
</div>
|
</div>
|
||||||
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3">
|
{historical.length > 0 && <section aria-labelledby="historical-sources-title" className="space-y-3">
|
||||||
<h2 id="historical-sources-title" className="text-lg font-semibold">Anciennes sources exclues</h2>
|
<h2 id="historical-sources-title" className="text-lg font-semibold">Anciennes sources exclues</h2>
|
||||||
|
|||||||
@ -38,3 +38,11 @@ it('envoie les plafonds via les endpoints admin et préserve le plafond lors du
|
|||||||
method: 'PUT', body: JSON.stringify({ enabled: false }),
|
method: 'PUT', body: JSON.stringify({ enabled: false }),
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('remplace les flux RSS par PUT sans modifier le plafond et sans appeler les feeds', async () => {
|
||||||
|
const urls = ['https://feed.quanwenrss.com/feed/bloomberg-latest.xml']
|
||||||
|
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ok: true } }), { status: 200 }))
|
||||||
|
vi.stubGlobal('fetch', fetchMock)
|
||||||
|
await adminApi.updateSourceFeeds('source-b', false, urls)
|
||||||
|
expect(fetchMock).toHaveBeenCalledExactlyOnceWith('/api/admin/sources/source-b', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: false, feed_urls: urls }) }))
|
||||||
|
})
|
||||||
|
|||||||
@ -244,7 +244,27 @@ describe('plafonds d’articles administrateur', () => {
|
|||||||
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('cnbc-new', true, 42))
|
await waitFor(() => expect(updateSource).toHaveBeenCalledWith('cnbc-new', true, 42))
|
||||||
expect(updateSource).toHaveBeenCalledTimes(1)
|
expect(updateSource).toHaveBeenCalledTimes(1)
|
||||||
expect(await screen.findByRole('status')).toHaveTextContent('Plafond CNBC Business enregistré pour les prochaines synthèses.')
|
expect(await screen.findByRole('status')).toHaveTextContent('Plafond CNBC Business enregistré pour les prochaines synthèses.')
|
||||||
expect(screen.getByText(/Seules Yahoo Finance, Bloomberg et CNBC Business/)).toBeInTheDocument()
|
expect(screen.getByText(/Yahoo Finance, Bloomberg, CNBC Business et Investing.com/)).toBeInTheDocument()
|
||||||
})
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('ticket #41 — sources additives', () => {
|
||||||
|
afterEach(cleanup)
|
||||||
|
it('affiche Investing.com depuis la clé canonique backend et conserve Yahoo Finance et CNBC Business', async () => {
|
||||||
|
listSettings.mockResolvedValue([])
|
||||||
|
listSources.mockResolvedValue([
|
||||||
|
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20 },
|
||||||
|
{ id: 'i', source_key: 'investing_com', name: 'Legacy RSS label', type: 'rss', supported: true, operational: false, enabled: false, article_limit: 40 },
|
||||||
|
{ id: 'y', source_key: 'yahoo_finance', name: 'legacy', type: 'stocktwits', supported: true, operational: true, enabled: true, article_limit: 20 },
|
||||||
|
{ id: 'c', source_key: 'cnbc_business', name: 'legacy', type: 'rss', supported: true, operational: true, enabled: true, article_limit: 20 },
|
||||||
|
])
|
||||||
|
render(<Sources />)
|
||||||
|
expect(await screen.findByRole('heading', { name: 'Investing.com' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(40)
|
||||||
|
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
|
||||||
|
expect(screen.getByRole('button', { name: 'Désactiver Yahoo Finance' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByRole('button', { name: 'Désactiver CNBC Business' })).toBeInTheDocument()
|
||||||
|
expect(screen.queryByRole('heading', { name: 'Legacy RSS label' })).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
72
frontend/tests/admin-source-feeds-ticket41.test.tsx
Normal file
72
frontend/tests/admin-source-feeds-ticket41.test.tsx
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
import { cleanup, render, screen, within } from '@testing-library/react'
|
||||||
|
import userEvent from '@testing-library/user-event'
|
||||||
|
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||||
|
import { Sources } from '../src/pages/admin/Sources'
|
||||||
|
|
||||||
|
const latest = 'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'
|
||||||
|
const economics = 'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'
|
||||||
|
const investing = 'https://feed.quanwenrss.com/feed/investing-news.xml'
|
||||||
|
const fetchMock = vi.fn()
|
||||||
|
let sources: object[]
|
||||||
|
beforeEach(() => {
|
||||||
|
sources = [
|
||||||
|
{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', supported: true, operational: true, enabled: true, article_limit: 20, feed_urls: [latest] },
|
||||||
|
{ id: 'i', source_key: 'investing_com', name: 'Investing.com', supported: true, operational: false, enabled: false, article_limit: 40, feed_urls: [investing] },
|
||||||
|
]
|
||||||
|
vi.stubGlobal('fetch', fetchMock)
|
||||||
|
fetchMock.mockReset().mockImplementation((url: string) => Promise.resolve(new Response(JSON.stringify({ data: url === '/api/admin/sources' ? sources : [] }), { status: 200 })))
|
||||||
|
})
|
||||||
|
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||||
|
|
||||||
|
it('charge et sauvegarde plusieurs flux Bloomberg sans déclencher de récupération ni génération', async () => {
|
||||||
|
render(<Sources />)
|
||||||
|
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
|
||||||
|
await userEvent.click(within(form).getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' }))
|
||||||
|
await userEvent.type(within(form).getByLabelText('URL du flux RSS Bloomberg 2'), economics)
|
||||||
|
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/sources/b', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: true, feed_urls: [latest, economics] }) }))
|
||||||
|
expect(within(form).getByRole('status')).toHaveTextContent('Aucune récupération ni génération n’a été lancée.')
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('enregistre les flux d’une source désactivée sans l’activer et sans modifier son plafond', async () => {
|
||||||
|
render(<Sources />)
|
||||||
|
const form = await screen.findByRole('form', { name: 'Flux RSS Investing.com' })
|
||||||
|
expect(within(form).getByLabelText('URL du flux RSS Investing.com 1')).toHaveValue(investing)
|
||||||
|
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Investing.com' }))
|
||||||
|
expect(fetchMock).toHaveBeenLastCalledWith('/api/admin/sources/i', expect.objectContaining({ method: 'PUT', body: JSON.stringify({ enabled: false, feed_urls: [investing] }) }))
|
||||||
|
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
|
||||||
|
expect(screen.getByLabelText('Plafond Investing.com')).toHaveValue(40)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ne propose pas de configuration supposée quand le DTO ne fournit pas de feeds', async () => {
|
||||||
|
sources = [{ id: 'b', source_key: 'bloomberg', name: 'Bloomberg', supported: true, operational: true, enabled: true, article_limit: 20 }]
|
||||||
|
render(<Sources />)
|
||||||
|
await screen.findByRole('heading', { name: 'Bloomberg' })
|
||||||
|
expect(screen.queryByRole('form', { name: 'Flux RSS Bloomberg' })).not.toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/Configuration des flux RSS indisponible/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('relie les rejets de validation serveur à un message assaini et conserve les saisies', async () => {
|
||||||
|
render(<Sources />)
|
||||||
|
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
|
||||||
|
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'source_feeds_invalid', url: 'PRIVATE_URL', content: 'PRIVATE_CONTENT' }), { status: 400 }))
|
||||||
|
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(within(form).getByRole('alert')).toHaveTextContent('Les flux RSS ont été refusés.')
|
||||||
|
expect(within(form).getByRole('alert')).not.toHaveTextContent(/PRIVATE_/)
|
||||||
|
expect(within(form).getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(latest)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('verrouille activation et plafond pendant la sauvegarde des flux de la même source', async () => {
|
||||||
|
render(<Sources />)
|
||||||
|
const form = await screen.findByRole('form', { name: 'Flux RSS Bloomberg' })
|
||||||
|
let complete!: (value: Response) => void
|
||||||
|
fetchMock.mockImplementationOnce(() => new Promise<Response>(resolve => { complete = resolve }))
|
||||||
|
await userEvent.click(within(form).getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getByRole('button', { name: 'Désactiver Bloomberg' })).toBeDisabled()
|
||||||
|
expect(screen.getByRole('button', { name: 'Enregistrer le plafond Bloomberg' })).toBeDisabled()
|
||||||
|
expect(screen.getByRole('button', { name: 'Activer Investing.com' })).toBeEnabled()
|
||||||
|
complete(new Response(JSON.stringify({ data: { ok: true } }), { status: 200 }))
|
||||||
|
expect(await within(form).findByText(/Flux RSS enregistrés pour les prochaines synthèses/)).toBeInTheDocument()
|
||||||
|
expect(screen.getByRole('button', { name: 'Désactiver Bloomberg' })).toBeEnabled()
|
||||||
|
})
|
||||||
38
frontend/tests/source-feed-outcome-ticket41.test.tsx
Normal file
38
frontend/tests/source-feed-outcome-ticket41.test.tsx
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||||
|
import { afterEach, expect, it } from 'vitest'
|
||||||
|
import { GenerationDetails } from '../src/components/GenerationDetails'
|
||||||
|
import type { GenerationOutcome } from '../src/api/summaries'
|
||||||
|
|
||||||
|
afterEach(cleanup)
|
||||||
|
const outcome = (status: string, sourceKey = 'bloomberg'): GenerationOutcome => ({
|
||||||
|
id: 'g', status: 'partial', language: 'fr', ranking_mode: 'title_content', failure_code: 'content_incomplete',
|
||||||
|
total_candidates: 6, laya_selected: 2, selected: 2, global_limit: 50, content_fallbacks: 1,
|
||||||
|
content_complete: 3, content_incomplete: 2, content_unavailable: 1,
|
||||||
|
source_stats: [{ source_id: 'b', source_key: sourceKey, source_type: 'stocktwits', status, candidates: 6, laya_selected: 2, selected: 2, article_limit: 20, content_fallbacks: 1,
|
||||||
|
content_complete: 3, content_incomplete: 2, content_unavailable: 1,
|
||||||
|
feeds: { attempted: 5, succeeded: status === 'failed' ? 0 : 4, failed: status === 'failed' ? 5 : 1 },
|
||||||
|
}],
|
||||||
|
})
|
||||||
|
function show(value: GenerationOutcome) {
|
||||||
|
const result = render(<GenerationDetails outcome={value} />)
|
||||||
|
fireEvent.click(screen.getByText('Détails de la génération'))
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
it('annonce une récupération partielle de feeds distincte de la complétude, sans perdre les agrégats', () => {
|
||||||
|
show(outcome('partial'))
|
||||||
|
expect(screen.getByText(/Certains flux RSS de Bloomberg n’ont pas pu être récupérés/)).toBeInTheDocument()
|
||||||
|
const row = screen.getByRole('row', { name: /Bloomberg/ })
|
||||||
|
expect(within(row).getByRole('cell', { name: 'Récupération partielle · contenus de complétude variable' })).toBeInTheDocument()
|
||||||
|
expect(within(row).getByText('Tentés : 5 · récupérés : 4 · en échec : 1')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('Contenus complets : 3')).toBeInTheDocument()
|
||||||
|
expect(screen.getByText(/Seuls les contenus complets sont éligibles/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('nomme Investing.com et rend une indisponibilité complète des feeds sans diagnostic brut', () => {
|
||||||
|
const { container } = show(outcome('failed', 'investing_com'))
|
||||||
|
expect(screen.getByRole('rowheader', { name: 'Investing.com' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByRole('cell', { name: 'Récupération impossible' })).toBeInTheDocument()
|
||||||
|
expect(screen.getByText('Tentés : 5 · récupérés : 0 · en échec : 5')).toBeInTheDocument()
|
||||||
|
expect(container.innerHTML).not.toMatch(/stocktwits|https?:|abonnement|authentification|challenge/i)
|
||||||
|
})
|
||||||
105
frontend/tests/source-feeds-editor-ticket41.test.tsx
Normal file
105
frontend/tests/source-feeds-editor-ticket41.test.tsx
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
import { cleanup, render, screen } from '@testing-library/react'
|
||||||
|
import userEvent from '@testing-library/user-event'
|
||||||
|
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||||
|
import { SourceFeedsEditor } from '../src/components/SourceFeedsEditor'
|
||||||
|
|
||||||
|
const latest = 'https://feed.quanwenrss.com/feed/bloomberg-latest.xml'
|
||||||
|
const economics = 'https://feed.quanwenrss.com/feed/bloomberg-economics.xml'
|
||||||
|
const save = vi.fn()
|
||||||
|
const fetchMock = vi.fn()
|
||||||
|
function show(urls = [latest]) {
|
||||||
|
return render(<SourceFeedsEditor sourceId="b" sourceKey="bloomberg" sourceName="Bloomberg" urls={urls} onSave={save} />)
|
||||||
|
}
|
||||||
|
beforeEach(() => { save.mockReset().mockResolvedValue(undefined); vi.stubGlobal('fetch', fetchMock.mockReset()) })
|
||||||
|
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||||
|
|
||||||
|
it('ajoute et retire des lignes identifiées puis sauvegarde toutes les URLs sans récupération', async () => {
|
||||||
|
show()
|
||||||
|
expect(screen.getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(latest)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' }))
|
||||||
|
await userEvent.type(screen.getByLabelText('URL du flux RSS Bloomberg 2'), economics)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(save).toHaveBeenLastCalledWith([latest, economics])
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Flux RSS enregistrés pour les prochaines synthèses. Aucune récupération ni génération n’a été lancée.')
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 1' }))
|
||||||
|
expect(screen.getByLabelText('URL du flux RSS Bloomberg 1')).toHaveValue(economics)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(save).toHaveBeenLastCalledWith([economics])
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
'', 'bad-url', 'http://feed.quanwenrss.com/feed/bloomberg-latest.xml',
|
||||||
|
'https://feed.quanwenrss.com.evil.invalid/feed/bloomberg-latest.xml',
|
||||||
|
'https://127.0.0.1/feed/bloomberg-latest.xml',
|
||||||
|
'https://feed.quanwenrss.com:8443/feed/bloomberg-latest.xml',
|
||||||
|
'https://user:PRIVATE_SECRET@feed.quanwenrss.com/feed/bloomberg-latest.xml',
|
||||||
|
`${latest}#fragment`, `${latest}?secret=PRIVATE_SECRET`,
|
||||||
|
'https://feed.quanwenrss.com/feed/investing-news.xml',
|
||||||
|
'https://feed.quanwenrss.com/feed/unknown.xml',
|
||||||
|
])('refuse une URL non autorisée sans requête (%s)', async url => {
|
||||||
|
show([url])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
const input = screen.getByLabelText('URL du flux RSS Bloomberg 1')
|
||||||
|
expect(input).toHaveAttribute('aria-invalid', 'true')
|
||||||
|
expect(input).toHaveAccessibleDescription(/URL|adresse/i)
|
||||||
|
const alert = screen.getByRole('alert')
|
||||||
|
expect(alert).not.toHaveTextContent(/PRIVATE_SECRET|127\.0\.0\.1|https?:/)
|
||||||
|
expect(save).not.toHaveBeenCalled()
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuse les doublons et une liste vidée puis permet de corriger', async () => {
|
||||||
|
show([latest, latest])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getAllByRole('alert')[0]).toHaveTextContent(/déjà présent/)
|
||||||
|
await userEvent.clear(screen.getByLabelText('URL du flux RSS Bloomberg 2'))
|
||||||
|
await userEvent.type(screen.getByLabelText('URL du flux RSS Bloomberg 2'), economics)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(save).toHaveBeenCalledWith([latest, economics])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 2' }))
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Retirer le flux RSS Bloomberg 1' }))
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getByRole('alert')).toHaveTextContent(/Ajoutez au moins un flux RSS/)
|
||||||
|
expect(save).toHaveBeenCalledTimes(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('garde les saisies après une erreur de sauvegarde, sans exposer le détail brut, et permet de réessayer', async () => {
|
||||||
|
save.mockRejectedValueOnce(new Error('PRIVATE_SECRET https://private.invalid'))
|
||||||
|
show([latest, economics])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getByRole('alert')).toHaveTextContent('Impossible d’enregistrer les flux RSS. Votre saisie est conservée. Réessayez.')
|
||||||
|
expect(screen.getByRole('alert')).not.toHaveTextContent(/PRIVATE_SECRET|private.invalid/)
|
||||||
|
expect(screen.getByLabelText('URL du flux RSS Bloomberg 2')).toHaveValue(economics)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(save).toHaveBeenCalledTimes(2)
|
||||||
|
expect(screen.getByRole('status')).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annonce l’enregistrement en cours et empêche les soumissions concurrentes', async () => {
|
||||||
|
let complete!: () => void
|
||||||
|
save.mockImplementationOnce(() => new Promise<void>(resolve => { complete = resolve }))
|
||||||
|
show()
|
||||||
|
const button = screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' })
|
||||||
|
await userEvent.click(button)
|
||||||
|
expect(screen.getByRole('form', { name: 'Flux RSS Bloomberg' })).toHaveAttribute('aria-busy', 'true')
|
||||||
|
expect(button).toBeDisabled()
|
||||||
|
expect(screen.getByRole('button', { name: 'Ajouter un flux RSS Bloomberg' })).toBeDisabled()
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent('Enregistrement des flux RSS…')
|
||||||
|
complete()
|
||||||
|
expect(await screen.findByText(/Flux RSS enregistrés pour les prochaines synthèses/)).toBeInTheDocument()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each([` ${latest}`, `${latest} `, 'https://feed.quanwenrss.com/feed/../feed/bloomberg-latest.xml'])('refuse une normalisation qui masquerait une URL non conforme au serveur (%s)', async url => {
|
||||||
|
show([url])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getByRole('alert')).toBeInTheDocument()
|
||||||
|
expect(save).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('normalise le port HTTPS standard et refuse les doublons normalisés', async () => {
|
||||||
|
show([latest, 'https://FEED.QUANWENRSS.COM:443/feed/bloomberg-latest.xml'])
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: 'Enregistrer les flux RSS Bloomberg' }))
|
||||||
|
expect(screen.getByRole('alert')).toHaveTextContent('déjà présent')
|
||||||
|
expect(save).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user