Files
supermarket/internal/api/rss/rss.go
T
davidandClaude Opus 5.5 c36f786ae9 Fixes from the first round of TEST.md
SEO: a domain property (sc-domain:) covers every subdomain, so the shop,
Gitea and forum were counted as the website. What ranks, the morning
check, the Monday report, keywords, change candidates and the audit's
traffic now read only the website's own host (with or without www).
The report keeps pages worth a proposal apart from "Waiting for your
yes", explains only moves past the thresholds, and says "places up/down".

Also:
- Feed summaries drop the posts' scripts and styles.
- Spend you log can't be negative.
- Test and check buttons can't be clicked twice while they run.
- Previews show the site's web fonts and icon sprites.
- Backups are read without leaving -wal/-shm files; deleting one removes
  them, and leftovers are swept at start.
- The Overview's setup flags a CRM that Hermes can't reach.
- Import now says what came in; adding a prospect that exists says so;
  prospects can be deleted.
- Signal tags and brief addresses keep accented letters (Ü → u).
- Page errors start with a capital; clearer messages for bad uploads,
  CRM retry and cancel, keywords, and the finished audit.
- The module you're in stays unfolded in the sidebar.
- A picked keyword can be unpicked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 06:31:42 -07:00

225 lines
6.2 KiB
Go

// 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 (
// Elements whose text isn't text: a post's own scripts and styles.
code = regexp.MustCompile(`(?is)<(script|style|noscript|template)\b[^>]*>.*?</(script|style|noscript|template)\s*>`)
tags = regexp.MustCompile(`(?s)<[^>]*>`)
spaces = regexp.MustCompile(`\s+`)
)
// clean turns feed HTML into plain text of at most n characters. Some
// feeds escape their HTML once more, so it's stripped again after
// unescaping.
func clean(s string, n int) string {
strip := func(s string) string { return tags.ReplaceAllString(code.ReplaceAllString(s, " "), " ") }
s = strip(s)
if u := html.UnescapeString(s); u != s && strings.Contains(u, "<") {
s = html.UnescapeString(strip(u))
} else {
s = u
}
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 ""
}