// 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() }