// Package rss reads RSS 2.0 and Atom feeds into content items. package rss import ( "context" "crypto/sha256" "encoding/hex" "encoding/xml" "fmt" "html" "io" "net/http" "regexp" "strings" "time" "supermarket/internal/models" ) // maxFeedBytes caps how much of a feed is read. const maxFeedBytes = 5 << 20 // maxBody caps an item's text: enough for the model to understand it. const maxBody = 1500 // Client fetches feeds. type Client struct { http *http.Client userAgent string } // New returns a client that identifies itself as userAgent. func New(userAgent string) *Client { return &Client{http: &http.Client{Timeout: 20 * time.Second}, userAgent: userAgent} } // Fetch returns the feed's items published after since. func (c *Client) Fetch(ctx context.Context, feedURL string, since time.Time, entryName string) ([]models.ContentItem, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", c.userAgent) req.Header.Set("Accept", "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.8") res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("HTTP %d", res.StatusCode) } data, err := io.ReadAll(io.LimitReader(res.Body, maxFeedBytes)) if err != nil { return nil, err } items, err := Parse(data, entryName) if err != nil { return nil, err } out := items[:0] for _, it := range items { // Items without a date are kept: some feeds leave it out. if it.PublishedAt.IsZero() || it.PublishedAt.After(since) { if it.PublishedAt.IsZero() { it.PublishedAt = time.Now().UTC() } out = append(out, it) } } return out, nil } type rssDoc struct { XMLName xml.Name Channel struct { Title string `xml:"title"` Items []rssItem `xml:"item"` } `xml:"channel"` // Atom Title string `xml:"title"` Entries []atomEntry `xml:"entry"` } type rssItem struct { Title string `xml:"title"` Link string `xml:"link"` GUID string `xml:"guid"` PubDate string `xml:"pubDate"` Date string `xml:"http://purl.org/dc/elements/1.1/ date"` Description string `xml:"description"` Content string `xml:"http://purl.org/rss/1.0/modules/content/ encoded"` Author string `xml:"author"` Creator string `xml:"http://purl.org/dc/elements/1.1/ creator"` } type atomEntry struct { Title string `xml:"title"` ID string `xml:"id"` Links []struct { Href string `xml:"href,attr"` Rel string `xml:"rel,attr"` } `xml:"link"` Published string `xml:"published"` Updated string `xml:"updated"` Summary string `xml:"summary"` Content string `xml:"content"` Author struct { Name string `xml:"name"` } `xml:"author"` } // Parse reads an RSS 2.0 or Atom document. func Parse(data []byte, entryName string) ([]models.ContentItem, error) { var doc rssDoc dec := xml.NewDecoder(strings.NewReader(string(data))) dec.Strict = false dec.CharsetReader = func(_ string, r io.Reader) (io.Reader, error) { return r, nil } if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("not an RSS or Atom feed: %w", err) } var items []models.ContentItem switch strings.ToLower(doc.XMLName.Local) { case "rss", "rdf": for _, it := range doc.Channel.Items { key := firstNonEmpty(it.GUID, it.Link, it.Title) if key == "" { continue } items = append(items, models.ContentItem{ ID: itemID(key), Source: models.SourceRSS, Author: clean(firstNonEmpty(it.Creator, it.Author, doc.Channel.Title), 200), Title: clean(it.Title, 300), Body: clean(firstNonEmpty(it.Content, it.Description), maxBody), URL: strings.TrimSpace(it.Link), PublishedAt: parseDate(firstNonEmpty(it.PubDate, it.Date)), AppName: entryName, }) } case "feed": for _, e := range doc.Entries { link := "" for _, l := range e.Links { if l.Rel == "" || l.Rel == "alternate" { link = l.Href break } } key := firstNonEmpty(e.ID, link, e.Title) if key == "" { continue } items = append(items, models.ContentItem{ ID: itemID(key), Source: models.SourceRSS, Author: clean(firstNonEmpty(e.Author.Name, doc.Title), 200), Title: clean(e.Title, 300), Body: clean(firstNonEmpty(e.Summary, e.Content), maxBody), URL: strings.TrimSpace(link), PublishedAt: parseDate(firstNonEmpty(e.Published, e.Updated)), AppName: entryName, }) } default: return nil, fmt.Errorf("not an RSS or Atom feed (root element <%s>)", doc.XMLName.Local) } return items, nil } func itemID(key string) string { h := sha256.Sum256([]byte(strings.TrimSpace(key))) return "rss:" + hex.EncodeToString(h[:12]) } var ( tags = regexp.MustCompile(`(?s)<[^>]*>`) spaces = regexp.MustCompile(`\s+`) ) // clean turns feed HTML into plain text of at most n characters. func clean(s string, n int) string { s = tags.ReplaceAllString(s, " ") s = html.UnescapeString(s) s = strings.TrimSpace(spaces.ReplaceAllString(s, " ")) if r := []rune(s); len(r) > n { s = string(r[:n-1]) + "…" } return s } var dateLayouts = []string{ time.RFC1123Z, time.RFC1123, time.RFC3339, time.RFC3339Nano, "Mon, 2 Jan 2006 15:04:05 -0700", "Mon, 2 Jan 2006 15:04:05 MST", "2 Jan 2006 15:04:05 -0700", "2006-01-02T15:04:05", "2006-01-02", } func parseDate(s string) time.Time { s = strings.TrimSpace(s) for _, l := range dateLayouts { if t, err := time.Parse(l, s); err == nil { return t.UTC() } } return time.Time{} } func firstNonEmpty(vals ...string) string { for _, v := range vals { if strings.TrimSpace(v) != "" { return strings.TrimSpace(v) } } return "" }