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