Phase 1, part 4: promote the company's own products
- Content lists the company first, at /content/own: its products from the profile (always there to pick from), its own feeds (a new profile field for the blog, news and releases), and new or updated pages from its websites' sitemaps, with each page's title and description. - Drafts from it are kind "product" (utm_campaign=product), filed under the company's name, and prompted to promote the company's own work without unsupported claims; on Reddit, in the makers' voice, with a warning that self-promotion is often restricted. This completes Phase 1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,212 @@
|
||||
// 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)<title[^>]*>(.*?)</title>`)
|
||||
metaRe = regexp.MustCompile(`(?is)<meta\s[^>]*>`)
|
||||
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{}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package sitemap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewPages(t *testing.T) {
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/sitemap.xml":
|
||||
w.Write([]byte(`<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<sitemap><loc>` + srv.URL + `/posts.xml</loc></sitemap><sitemap><loc>https://elsewhere.example/x.xml</loc></sitemap></sitemapindex>`))
|
||||
case "/posts.xml":
|
||||
w.Write([]byte(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url><loc>` + srv.URL + `/new</loc><lastmod>2026-11-19</lastmod></url>
|
||||
<url><loc>` + srv.URL + `/newer</loc><lastmod>2026-11-20T08:00:00+00:00</lastmod></url>
|
||||
<url><loc>` + srv.URL + `/old</loc><lastmod>2026-01-01</lastmod></url>
|
||||
<url><loc>` + srv.URL + `/undated</loc></url>
|
||||
<url><loc>https://elsewhere.example/page</loc><lastmod>2026-11-20</lastmod></url>
|
||||
</urlset>`))
|
||||
case "/newer":
|
||||
w.Write([]byte(`<html><head><title>Release 2.0 & more</title>
|
||||
<meta name="description" content="Faster sync."><meta property="og:description" content="ignored"></head></html>`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New("test")
|
||||
pages, err := c.NewPages(context.Background(), srv.URL+"/blog/", time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(pages) != 2 || !strings.HasSuffix(pages[0].URL, "/newer") || !strings.HasSuffix(pages[1].URL, "/new") {
|
||||
t.Fatalf("pages = %+v", pages)
|
||||
}
|
||||
it, err := c.Item(context.Background(), pages[0], "_own")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if it.Title != "Release 2.0 & more" || it.Body != "Faster sync." || !strings.HasPrefix(it.ID, "page:") || it.AppName != "_own" {
|
||||
t.Errorf("item = %+v", it)
|
||||
}
|
||||
if _, err := c.Item(context.Background(), pages[1], "_own"); err == nil {
|
||||
t.Error("expected an error for a missing page")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageInfoOG(t *testing.T) {
|
||||
title, desc := PageInfo(`<meta content='OG title' property='og:title'><meta property="og:description" content="OG desc">`)
|
||||
if title != "OG title" || desc != "OG desc" {
|
||||
t.Errorf("got %q, %q", title, desc)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user