// Package sitemap finds a website's new or updated pages from its // sitemap.xml, and reads each page's title and description. package sitemap import ( "context" "crypto/sha256" "encoding/hex" "encoding/xml" "fmt" "html" "io" "net/http" "net/url" "regexp" "sort" "strings" "time" "supermarket/internal/models" ) const ( maxSitemapBytes = 10 << 20 maxPageBytes = 2 << 20 maxChildMaps = 10 // sitemaps read from a sitemap index // MaxPages caps the pages read per site and fetch. MaxPages = 15 ) // Client reads sitemaps and pages. 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} } type urlset struct { XMLName xml.Name URLs []struct { Loc string `xml:"loc"` LastMod string `xml:"lastmod"` } `xml:"url"` Sitemaps []struct { Loc string `xml:"loc"` } `xml:"sitemap"` } // Page is a page found in a sitemap. type Page struct { URL string LastMod time.Time } // NewPages returns the site's pages changed after since, newest first, at // most MaxPages. Pages without a date are skipped: there's no telling // whether they're new. func (c *Client) NewPages(ctx context.Context, siteURL string, since time.Time) ([]Page, error) { u, err := url.Parse(strings.TrimSpace(siteURL)) if err != nil || u.Host == "" { return nil, fmt.Errorf("%q isn't a website address", siteURL) } root := u.Scheme + "://" + u.Host + "/sitemap.xml" pages, err := c.read(ctx, root, u.Host, 0) if err != nil { return nil, err } var out []Page for _, p := range pages { if p.LastMod.After(since) { out = append(out, p) } } sort.Slice(out, func(i, j int) bool { return out[i].LastMod.After(out[j].LastMod) }) if len(out) > MaxPages { out = out[:MaxPages] } return out, nil } // AllPages returns every page a sitemap lists, from the given sitemap // address (or the site's /sitemap.xml when it's empty). func (c *Client) AllPages(ctx context.Context, siteURL, mapURL string) ([]Page, error) { u, err := url.Parse(strings.TrimSpace(siteURL)) if err != nil || u.Host == "" { return nil, fmt.Errorf("%q isn't a website address", siteURL) } if mapURL == "" { mapURL = u.Scheme + "://" + u.Host + "/sitemap.xml" } return c.read(ctx, mapURL, u.Host, 0) } func (c *Client) read(ctx context.Context, mapURL, host string, depth int) ([]Page, error) { data, err := c.get(ctx, mapURL, maxSitemapBytes) if err != nil { return nil, fmt.Errorf("%s: %w", mapURL, err) } var doc urlset if err := xml.Unmarshal(data, &doc); err != nil { return nil, fmt.Errorf("%s isn't a sitemap: %w", mapURL, err) } var pages []Page for _, x := range doc.URLs { loc := strings.TrimSpace(x.Loc) if !sameHost(loc, host) { continue } pages = append(pages, Page{URL: loc, LastMod: parseDate(x.LastMod)}) } if depth == 0 { for i, sm := range doc.Sitemaps { if i >= maxChildMaps { break } loc := strings.TrimSpace(sm.Loc) if !sameHost(loc, host) { continue } child, err := c.read(ctx, loc, host, 1) if err != nil { return nil, err } pages = append(pages, child...) } } return pages, nil } func sameHost(raw, host string) bool { u, err := url.Parse(raw) return err == nil && strings.EqualFold(strings.TrimPrefix(u.Hostname(), "www."), strings.TrimPrefix(strings.Split(host, ":")[0], "www.")) } func (c *Client) get(ctx context.Context, u string, limit int64) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", c.userAgent) 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) } return io.ReadAll(io.LimitReader(res.Body, limit)) } var ( titleRe = regexp.MustCompile(`(?is)]*>(.*?)`) metaRe = regexp.MustCompile(`(?is)]*>`) attrRe = regexp.MustCompile(`(?is)(name|property|content)\s*=\s*("([^"]*)"|'([^']*)')`) spaces = regexp.MustCompile(`\s+`) ) // Item reads a page's title and description into a content item. func (c *Client) Item(ctx context.Context, p Page, entryName string) (models.ContentItem, error) { data, err := c.get(ctx, p.URL, maxPageBytes) if err != nil { return models.ContentItem{}, fmt.Errorf("%s: %w", p.URL, err) } title, desc := PageInfo(string(data)) h := sha256.Sum256([]byte(p.URL + "|" + p.LastMod.Format(time.RFC3339))) return models.ContentItem{ // The date is part of the ID, so an updated page shows up again. ID: "page:" + hex.EncodeToString(h[:12]), Source: models.SourcePage, Title: title, Body: desc, URL: p.URL, PublishedAt: p.LastMod, AppName: entryName, }, nil } // PageInfo finds an HTML page's title and description (og: or meta). func PageInfo(page string) (title, desc string) { if m := titleRe.FindStringSubmatch(page); m != nil { title = clean(m[1]) } for _, tag := range metaRe.FindAllString(page, -1) { var name, content string for _, a := range attrRe.FindAllStringSubmatch(tag, -1) { v := a[3] + a[4] switch strings.ToLower(a[1]) { case "name", "property": name = strings.ToLower(v) case "content": content = v } } switch name { case "og:title": if title == "" { title = clean(content) } case "description", "og:description": if desc == "" { desc = clean(content) } } } return title, desc } func clean(s string) string { return strings.TrimSpace(spaces.ReplaceAllString(html.UnescapeString(s), " ")) } func parseDate(s string) time.Time { s = strings.TrimSpace(s) for _, l := range []string{time.RFC3339, "2006-01-02T15:04:05-07:00", "2006-01-02T15:04Z07:00", "2006-01-02"} { if t, err := time.Parse(l, s); err == nil { return t.UTC() } } return time.Time{} }