From cd24f2a06dae05a86289227c488ce8447c26de86 Mon Sep 17 00:00:00 2001 From: David Young Date: Fri, 20 Nov 2026 14:42:37 -0700 Subject: [PATCH] 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 --- PLAN.md | 35 +++- README.md | 6 +- internal/api/sitemap/sitemap.go | 212 ++++++++++++++++++++++ internal/api/sitemap/sitemap_test.go | 61 +++++++ internal/content/generate.go | 19 +- internal/content/items.go | 3 +- internal/content/own.go | 91 ++++++++++ internal/content/own_test.go | 79 ++++++++ internal/content/reddit.go | 4 + internal/fetcher/fetcher.go | 29 +++ internal/models/models.go | 2 + internal/profile/profile.go | 5 + internal/web/content.go | 71 +++++++- internal/web/content_test.go | 43 +++++ internal/web/inbox.go | 3 +- internal/web/profile.go | 1 + internal/web/static/app.css | 1 + internal/web/templates/content-entry.html | 40 +++- internal/web/templates/content.html | 8 +- internal/web/templates/profile.html | 2 + 20 files changed, 685 insertions(+), 30 deletions(-) create mode 100644 internal/api/sitemap/sitemap.go create mode 100644 internal/api/sitemap/sitemap_test.go create mode 100644 internal/content/own.go create mode 100644 internal/content/own_test.go diff --git a/PLAN.md b/PLAN.md index a6a08d6..b7b1709 100644 --- a/PLAN.md +++ b/PLAN.md @@ -330,7 +330,7 @@ mcphub failed. ### Phase 1: Content (today's pipeline, generalized) + Reddit -**Status (2026-11-20): parts 1, 2 and 3 of 4 built on `phase0-foundation`.** Phase 1 is +**Status (2026-11-20): Phase 1 is built (all 4 parts) on `phase0-foundation`.** Phase 1 is built in four parts, each committed on its own: (1) the pipeline, items 1–2 below, for X and LinkedIn; (2) the approval inbox, schedule and UTM tags, item 5; (3) Reddit, item 4; (4) promoting our own products, the rest of @@ -366,7 +366,7 @@ Part 2 (commit `f275f03`): - The container now runs in the computer's time zone (`SUPERMARKET_TZ` in compose.env, from /etc/localtime), so times show and parse correctly. -Part 3, Reddit: +Part 3, Reddit (commit `0e34f57`): - A third channel, `reddit`: a draft has a `title` and a `target` subreddit (migration 4), chosen when writing, with suggestions from the entry's and the profile's subreddits. Reddit is never pre-checked. @@ -387,7 +387,25 @@ Part 3, Reddit: the company's own sites (counting this one), and a new account. They use the account's last 100 posts, cached for 10 minutes. -**Not yet tried for real.** Parts 1–3 are covered by tests with fake AI +Part 4, promoting our own products: +- A virtual inventory entry for the company (`content.OwnEntry`, items + stored under `_own`), shown first under Content as the company's name and + served at `/content/own`. It isn't stored in `inventory`. +- Products from the profile are kept in step as items + (`product:`, source `Product`), always there to pick from; they + don't count as waiting news. +- A new profile field, **Feeds**: the company's blog, news and release + feeds, fetched like an entry's RSS. +- Site pages: new or updated pages from each website's `sitemap.xml` + (sitemap indexes one level deep), newest 15 per fetch, with each page's + title and description. This runs only for the company's own sites. +- Drafts get kind `product` (so `utm_campaign=product`) and the company's + name. The prompt asks for posts that promote the company's own work with + claims the material supports. On Reddit it asks for the makers' voice and + invites feedback, and the Inbox warns that self-promotion is often + restricted. + +**Not yet tried for real.** Parts 1–4 are covered by tests with fake AI and channel clients, and the rebuilt app runs (schema 3). But the installed app has no profile, AI key, inventory or social sign-ins yet, so no real fetch, generation or post has been made. Before relying on it: @@ -400,6 +418,8 @@ real fetch, generation or post has been made. Before relying on it: 4. Register a Reddit web app, connect it, write a Reddit draft for a subreddit, and check its rules and warnings. Post to a test subreddit you moderate first. +5. Add a product and a blog or releases feed to the profile, open + Content → (company name), fetch, and write a post from a product. The database before migration 2 is backed up at `~/.local/share/supermarket/app.db.pre-phase1`. Commits on @@ -408,9 +428,12 @@ so `git push` can't prompt from Claude Code). The branch stays off `main` until the user decides to merge; posting works again now, which was the condition for merging. -**To pick this up: part 4, own-product promotion** (the rest of item 3): -drafts from the product list, the company's blog RSS, site pages and -releases, with `kind` = `product`. +**To pick this up:** try Phase 1 for real (the checklist above), fix what +that turns up, then decide whether to merge `phase0-foundation` into `main` +and tag `v0.1.0`. Then Phase 2, Prospects → EspoCRM, which depends on the +hub's EspoCRM tools (see Phase 0: `espocrm_search_records`, +`espocrm_get_record`, `espocrm_get_related_records`, +`espocrm_create_record`, `espocrm_update_record`, `espocrm_delete_record`). The plan for Phase 1, as first written: 1. Port fetch → browse → select → generate → approve → publish into the web diff --git a/README.md b/README.md index 7003cd3..8751747 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,13 @@ Everything starts from your **company profile** (what you sell, to whom, in what | Module | What it does | Status | |--------|--------------|--------| -| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X, LinkedIn and Reddit | Phase 1, in progress: X, LinkedIn and Reddit work | +| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X, LinkedIn and Reddit | Phase 1: done | | Prospects | Finds companies and people who fit your targets; the ones you approve go into your Core's EspoCRM through Hermes | Phase 2 | | SEO | Audits your websites for Google, Bing/DuckDuckGo and Brave, and opens fixes as pull requests on your Hugo repositories | Phase 3 | | Metrics | Pipeline influence, CAC, CLV and NRR, from Stripe, EspoCRM and Plausible | Phase 4 | | Sites | Builds pages and sites from a component library and publishes them through Gitea | Phase 5 | -This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has most of the Content module (Phase 1): fetching, writing drafts, an Inbox for approval, scheduled publishing to X, LinkedIn and Reddit, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan. +This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the Content module (Phase 1): posts about partners, competitors and your own products, an Inbox for approval, scheduled publishing to X, LinkedIn and Reddit, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan. ## Install @@ -101,6 +101,8 @@ To check the connection, open **Core & Hermes** in Supermarket and ask Hermes th Links to your own websites and product pages (from the profile) get UTM tags when published: `utm_source` is the channel, `utm_medium` is `social`, `utm_campaign` is the kind of post (partner, competitor, watch) and `utm_content` is the entry and draft. Links elsewhere are left as they are. Times are shown and read in your computer's time zone. +**Your own products.** The first row under Content is your company. It lists the products from your profile, ready to write about, and fetches your own feeds (blog, news, and releases: a GitHub or Gitea repository's `releases.atom` works) and new or updated pages from your websites' `sitemap.xml`. Add the feeds under Profile → Websites. Posts from it promote your work, under `utm_campaign=product`. + Reading X needs a bearer token from an X API plan with read access; YouTube needs a free API key; RSS needs nothing. Posting needs the sign-ins below. ### Reddit diff --git a/internal/api/sitemap/sitemap.go b/internal/api/sitemap/sitemap.go new file mode 100644 index 0000000..da2afba --- /dev/null +++ b/internal/api/sitemap/sitemap.go @@ -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)]*>(.*?)`) + 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{} +} diff --git a/internal/api/sitemap/sitemap_test.go b/internal/api/sitemap/sitemap_test.go new file mode 100644 index 0000000..42582b7 --- /dev/null +++ b/internal/api/sitemap/sitemap_test.go @@ -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(` +` + srv.URL + `/posts.xmlhttps://elsewhere.example/x.xml`)) + case "/posts.xml": + w.Write([]byte(` +` + srv.URL + `/new2026-11-19 +` + srv.URL + `/newer2026-11-20T08:00:00+00:00 +` + srv.URL + `/old2026-01-01 +` + srv.URL + `/undated +https://elsewhere.example/page2026-11-20 +`)) + case "/newer": + w.Write([]byte(`Release 2.0 & more +`)) + 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(``) + if title != "OG title" || desc != "OG desc" { + t.Errorf("got %q, %q", title, desc) + } +} diff --git a/internal/content/generate.go b/internal/content/generate.go index 16f61ef..ca0e745 100644 --- a/internal/content/generate.go +++ b/internal/content/generate.go @@ -101,6 +101,11 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro return nil, err } + // Drafts about the company itself are filed under its name. + name := req.Entry.Name + if IsOwn(req.Entry) { + name = req.Profile.Name + } ids := make([]string, 0, len(req.Items)) for _, it := range req.Items { ids = append(ids, it.ID) @@ -117,7 +122,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro if r := []rune(title); len(r) > RedditTitleLimit { title = string(r[:RedditTitleLimit-1]) + "…" } - drafts = append(drafts, Draft{InventoryName: req.Entry.Name, Kind: req.Entry.Relationship, Channel: ch, + drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body), SourceURL: src, ItemIDs: ids, Status: StatusDraft}) continue @@ -136,7 +141,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro } } drafts = append(drafts, Draft{ - InventoryName: req.Entry.Name, + InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, Content: text, @@ -227,11 +232,15 @@ func userPrompt(req Request, src string) string { } else { fmt.Fprintf(&b, "You may name %s.\n", e.Name) } + case KindProduct: + fmt.Fprintf(&b, "This is about our own work at %s: a product, a release, a blog post or a page on our site. Promote it: "+ + "say what's new or what it does, and the concrete benefit for the audience, with one clear next step that suits the channel "+ + "(try it, read more). Make only claims that the source material or the company information supports.\n", req.Profile.Name) default: fmt.Fprintf(&b, "Curate this news about %s for our audience: say what happened and why it matters to them. "+ "Don't promote our products or theirs.\n", e.Name) } - if e.Description != "" { + if e.Description != "" && !IsOwn(e) { fmt.Fprintf(&b, "About %s: %s\n", e.Name, oneLine(e.Description)) } if e.TalkingPoints != "" { @@ -290,6 +299,10 @@ func redditInstructions(req Request) string { "no calls to action. Usually 80 to 250 words, in Reddit's markdown. The title must read like a normal post title, not a headline ad. "+ "Follow the subreddit's rules below; if they forbid promotion, write a genuine discussion post that doesn't promote anything.\n", RedditTitleLimit, sub, req.Profile.Name, req.Profile.Name) + if req.Entry.Relationship == KindProduct { + b.WriteString(" This promotes our own work: write as the people who made it, share what's genuinely useful or interesting " + + "about it, and invite questions and feedback.\n") + } if info := req.SubredditInfo; info != nil { b.WriteString("\n") if info.Description != "" { diff --git a/internal/content/items.go b/internal/content/items.go index 0031c78..06763a8 100644 --- a/internal/content/items.go +++ b/internal/content/items.go @@ -117,7 +117,8 @@ func GetItems(d *db.DB, ids []string) ([]Item, error) { // Counts is how many items an entry has waiting (not used, not dismissed). func Counts(d *db.DB) (map[string]int, error) { rows, err := d.Query(`SELECT c.inventory_name, count(*)` + itemFrom + ` - WHERE d.item_id IS NULL AND c.used_at IS NULL GROUP BY c.inventory_name COLLATE NOCASE`) + WHERE d.item_id IS NULL AND c.used_at IS NULL AND c.source != 'Product' + GROUP BY c.inventory_name COLLATE NOCASE`) if err != nil { return nil, err } diff --git a/internal/content/own.go b/internal/content/own.go new file mode 100644 index 0000000..737ec0b --- /dev/null +++ b/internal/content/own.go @@ -0,0 +1,91 @@ +package content + +import ( + "fmt" + "strings" + "time" + + "supermarket/internal/db" + "supermarket/internal/inventory" + "supermarket/internal/models" + "supermarket/internal/profile" + "supermarket/internal/utm" +) + +// The company's own content (its products, feeds and site pages) is handled +// like an inventory entry that isn't stored: OwnEntry builds it from the +// profile. Its items are stored under OwnName. +const ( + OwnName = "_own" + KindProduct = "product" +) + +// OwnEntry is the company as a content source. +func OwnEntry(p *profile.Profile) *inventory.Entry { + e := &inventory.Entry{Name: OwnName, Relationship: KindProduct, RSS: p.Feeds, + Description: p.Description, Subreddits: p.Accounts.Subreddits} + for _, w := range p.Websites { + e.Websites = append(e.Websites, w.URL) + } + return e +} + +// IsOwn reports whether e is the company itself. +func IsOwn(e *inventory.Entry) bool { return e.Name == OwnName } + +// SyncProducts keeps an item for each product in the profile, so products +// can be selected and written about like fetched items. Removed products' +// items go; a product's item keeps its ID (and "drafted" mark) while its +// name stays the same. +func SyncProducts(d *db.DB, p *profile.Profile) error { + tx, err := d.Begin() + if err != nil { + return err + } + defer tx.Rollback() + keep := map[string]bool{} + for _, pr := range p.Products { + id := "product:" + utm.Slug(pr.Name) + if id == "product:" || keep[id] { + continue + } + keep[id] = true + var body strings.Builder + body.WriteString(pr.Description) + if len(pr.Benefits) > 0 { + fmt.Fprintf(&body, "\nBenefits: %s.", strings.Join(pr.Benefits, "; ")) + } + if pr.Pricing != "" { + fmt.Fprintf(&body, "\nPricing: %s", pr.Pricing) + } + if _, err := tx.Exec(`INSERT INTO content_items (id, inventory_name, source, title, body, url, published_at) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (id) DO UPDATE SET title = excluded.title, body = excluded.body, url = excluded.url`, + id, OwnName, string(models.SourceProduct), pr.Name, strings.TrimSpace(body.String()), pr.URL, + formatTime(time.Now())); err != nil { + return err + } + } + rows, err := tx.Query(`SELECT id FROM content_items WHERE inventory_name = ? AND source = ?`, OwnName, string(models.SourceProduct)) + if err != nil { + return err + } + var stale []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + if !keep[id] { + stale = append(stale, id) + } + } + rows.Close() + for _, id := range stale { + if _, err := tx.Exec(`DELETE FROM content_items WHERE id = ?`, id); err != nil { + return err + } + } + return tx.Commit() +} diff --git a/internal/content/own_test.go b/internal/content/own_test.go new file mode 100644 index 0000000..f89baf9 --- /dev/null +++ b/internal/content/own_test.go @@ -0,0 +1,79 @@ +package content + +import ( + "context" + "strings" + "testing" + + "supermarket/internal/models" + "supermarket/internal/profile" +) + +func TestOwnContent(t *testing.T) { + d := openDB(t) + p := testProfile() + p.Products = append(p.Products, profile.Product{Name: "Acme Mail", Description: "Hosted email.", URL: "https://acme.example/mail", Pricing: "$3/user"}) + p.Feeds = []string{"https://acme.example/blog/index.xml"} + p.Websites = []profile.Website{{URL: "https://acme.example"}} + if err := SyncProducts(d, p); err != nil { + t.Fatal(err) + } + items, _ := ListItems(d, OwnName, false, 10) + if len(items) != 2 { + t.Fatalf("items = %+v", items) + } + var mail Item + for _, it := range items { + if it.ID == "product:acme-mail" { + mail = it + } + } + if mail.Source != models.SourceProduct || mail.Title != "Acme Mail" || !strings.Contains(mail.Body, "Pricing: $3/user") { + t.Errorf("product item = %+v", mail) + } + if c, _ := Counts(d); c[OwnName] != 0 { + t.Errorf("products counted as waiting news: %v", c) + } + + // Writing about it marks it, and a re-sync keeps the mark; a removed + // product's item goes. + e := OwnEntry(p) + if !IsOwn(e) || e.Relationship != KindProduct || len(e.RSS) != 1 || e.Websites[0] != "https://acme.example" { + t.Errorf("own entry = %+v", e) + } + f := &fakeAI{replies: []string{`{"linkedin": "Try Acme Mail."}`}} + drafts, err := Generate(context.Background(), f, Request{Profile: p, Entry: e, Items: []Item{mail}, Channels: []string{ChannelLinkedIn}}) + if err != nil { + t.Fatal(err) + } + if drafts[0].InventoryName != "Acme" || drafts[0].Kind != KindProduct || drafts[0].SourceURL != "https://acme.example/mail" { + t.Errorf("draft = %+v", drafts[0]) + } + if !strings.Contains(f.reqs[0].Prompt, "our own work at Acme") || strings.Contains(f.reqs[0].Prompt, "About _own") { + t.Errorf("prompt:\n%s", f.reqs[0].Prompt) + } + if _, err := CreateDrafts(d, drafts); err != nil { + t.Fatal(err) + } + p.Products = p.Products[1:] + p.Products[0].Description = "Hosted email, now with calendars." + if err := SyncProducts(d, p); err != nil { + t.Fatal(err) + } + items, _ = ListItems(d, OwnName, false, 10) + if len(items) != 1 || !items[0].Used || !strings.Contains(items[0].Body, "calendars") { + t.Errorf("after re-sync: %+v", items) + } + + // On Reddit, product posts get a warning and a maker's voice. + if w := RedditWarnings(RedditCheck{Target: "selfhosted", Promo: true, Now: mail.FetchedAt}); !strings.Contains(w[0], "promotes your own work") { + t.Errorf("warnings = %q", w) + } + f = &fakeAI{replies: []string{`{"reddit": {"title": "We built a mail host", "body": "I work at Acme."}}`}} + if _, err := Generate(context.Background(), f, Request{Profile: p, Entry: e, Items: items, Channels: []string{ChannelReddit}, Subreddit: "selfhosted"}); err != nil { + t.Fatal(err) + } + if !strings.Contains(f.reqs[0].Prompt, "people who made it") { + t.Errorf("reddit product prompt:\n%s", f.reqs[0].Prompt) + } +} diff --git a/internal/content/reddit.go b/internal/content/reddit.go index bd9a349..5889cc6 100644 --- a/internal/content/reddit.go +++ b/internal/content/reddit.go @@ -61,6 +61,7 @@ type RedditCheck struct { Target string HasLink bool // the draft carries a link OwnLink bool // to the company's own site + Promo bool // it promotes the company's own product Info *reddit.Subreddit // nil if the rules couldn't be read History []reddit.Submission // the account's recent posts; nil if unknown Own func(url string) bool @@ -72,6 +73,9 @@ type RedditCheck struct { func RedditWarnings(c RedditCheck) []string { var w []string sub := "r/" + c.Target + if c.Promo { + w = append(w, "This promotes your own work. Many subreddits allow that only in designated threads, or not at all: check the rules.") + } if c.Info == nil { w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.") } else { diff --git a/internal/fetcher/fetcher.go b/internal/fetcher/fetcher.go index 81794a2..8387eae 100644 --- a/internal/fetcher/fetcher.go +++ b/internal/fetcher/fetcher.go @@ -11,6 +11,7 @@ import ( "time" "supermarket/internal/api/rss" + "supermarket/internal/api/sitemap" "supermarket/internal/api/twitter" "supermarket/internal/api/youtube" "supermarket/internal/inventory" @@ -22,6 +23,10 @@ type Fetcher struct { Twitter *twitter.Client YouTube *youtube.Client RSS *rss.Client + // Sitemap, if set, also reads new pages from the entry's websites' + // sitemaps. It's set for the company's own content only: a partner's + // every page change isn't news. + Sitemap *sitemap.Client } // Result is what a fetch found, and what failed or was skipped. @@ -78,6 +83,27 @@ func (f *Fetcher) Fetch(ctx context.Context, e *inventory.Entry, since time.Time } } + if f.Sitemap != nil { + for _, site := range e.Websites { + site := site + jobs = append(jobs, job{"sitemap " + site, func() ([]models.ContentItem, error) { + pages, err := f.Sitemap.NewPages(ctx, site, since) + if err != nil { + return nil, err + } + var items []models.ContentItem + for _, pg := range pages { + it, err := f.Sitemap.Item(ctx, pg, e.Name) + if err != nil { + continue // one unreadable page doesn't spoil the rest + } + items = append(items, it) + } + return items, nil + }}) + } + } + type batch struct { label string items []models.ContentItem @@ -126,6 +152,9 @@ func Sources(e *inventory.Entry) []string { if e.YouTubeChannelID != "" { out = append(out, "YouTube") } + if e.Relationship == "product" && len(e.Websites) > 0 { + out = append(out, "new pages on your websites") + } if n := len(e.RSS); n == 1 { out = append(out, "1 RSS feed") } else if n > 1 { diff --git a/internal/models/models.go b/internal/models/models.go index 4403495..9d023b8 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -10,6 +10,8 @@ const ( SourceTwitterSearch ContentSource = "X·Search" SourceYouTube ContentSource = "YouTube" SourceRSS ContentSource = "RSS" + SourcePage ContentSource = "Page" // a new or updated page on the company's site + SourceProduct ContentSource = "Product" // one of the company's products, from the profile ) // ContentItem is one fetched post, video or article. AppName is the diff --git a/internal/profile/profile.go b/internal/profile/profile.go index 177dc2e..ace0ba6 100644 --- a/internal/profile/profile.go +++ b/internal/profile/profile.go @@ -56,6 +56,10 @@ type Profile struct { Websites []Website `json:"websites"` Accounts Accounts `json:"accounts"` Keywords []string `json:"keywords"` + // Feeds are the company's own RSS/Atom feeds: its blog, news and + // releases (e.g. a GitHub or Gitea releases.atom), for promoting its + // own work. + Feeds []string `json:"feeds"` } // IsSet reports whether the profile has the minimum the other modules need. @@ -86,6 +90,7 @@ func (p *Profile) Clean() { p.Voice = strings.TrimSpace(p.Voice) p.Avoid = CleanList(p.Avoid) p.Keywords = CleanList(p.Keywords) + p.Feeds = CleanList(p.Feeds) products := p.Products[:0] for _, pr := range p.Products { diff --git a/internal/web/content.go b/internal/web/content.go index 6125320..09be315 100644 --- a/internal/web/content.go +++ b/internal/web/content.go @@ -11,9 +11,11 @@ import ( "supermarket/internal/ai" "supermarket/internal/api/reddit" + "supermarket/internal/api/sitemap" "supermarket/internal/content" "supermarket/internal/fetcher" "supermarket/internal/inventory" + "supermarket/internal/models" "supermarket/internal/profile" ) @@ -24,6 +26,8 @@ const maxPerItem = 10 type contentRow struct { Entry inventory.Entry + Own bool + Name string Sources []string Waiting int LastChecked time.Time @@ -40,10 +44,23 @@ func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } - rows := make([]contentRow, 0, len(entries)) + p, err := profile.Load(s.DB) + if err != nil { + s.serverError(w, err) + return + } + own := content.OwnEntry(p) + ownLast, _ := content.LastChecked(s.DB, own.Name) + ownSources := fetcher.Sources(own) + if len(p.Products) > 0 { + ownSources = append([]string{plural(len(p.Products), "product")}, ownSources...) + } + rows := make([]contentRow, 0, len(entries)+1) + rows = append(rows, contentRow{Entry: *own, Own: true, Name: ifElse(p.Name != "", p.Name, "Your company"), + Sources: ownSources, Waiting: counts[own.Name], LastChecked: ownLast}) for _, e := range entries { last, _ := content.LastChecked(s.DB, e.Name) - rows = append(rows, contentRow{Entry: e, Sources: fetcher.Sources(&e), + rows = append(rows, contentRow{Entry: e, Name: e.Name, Sources: fetcher.Sources(&e), Waiting: counts[strings.ToLower(e.Name)], LastChecked: last}) } s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{"Rows": rows}}) @@ -56,6 +73,10 @@ type channelChoice struct { type entryPage struct { Entry *inventory.Entry + Own bool // the company's own products, feeds and pages + Base string // the page's address: /content/ or /content/own + Name string // what to call the entry + Products []content.Item Sources []string Items []content.Item ShowDismissed bool @@ -72,6 +93,18 @@ type entryPage struct { } func (s *Server) loadEntry(w http.ResponseWriter, r *http.Request) *inventory.Entry { + if r.PathValue("id") == "own" { + p, err := profile.Load(s.DB) + if err != nil { + s.serverError(w, err) + return nil + } + if err := content.SyncProducts(s.DB, p); err != nil { + s.serverError(w, err) + return nil + } + return content.OwnEntry(p) + } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) @@ -93,6 +126,19 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, if err != nil { return nil, err } + // Products are always there to pick from; they're listed on their own. + var products []content.Item + if content.IsOwn(e) { + rest := items[:0] + for _, it := range items { + if it.Source == models.SourceProduct { + products = append(products, it) + } else { + rest = append(rest, it) + } + } + items = rest + } last, err := content.LastChecked(s.DB, e.Name) if err != nil { return nil, err @@ -117,7 +163,11 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, } } } - return &entryPage{Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed, + base, name := fmt.Sprintf("/content/%d", e.ID), e.Name + if content.IsOwn(e) { + base, name = "/content/own", ifElse(p.Name != "", p.Name, "Your company") + } + return &entryPage{Own: content.IsOwn(e), Base: base, Name: name, Products: products, Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed, LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil } @@ -131,7 +181,7 @@ func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } - s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Data: d}) + s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content", Data: d}) } func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) { @@ -147,7 +197,11 @@ func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) { } ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second) defer cancel() - res := s.fetcher().Fetch(ctx, e, since) + f := s.fetcher() + if content.IsOwn(e) { + f.Sitemap = sitemap.New("Supermarket/" + s.Version + " (sitemap reader)") + } + res := f.Fetch(ctx, e, since) n, err := content.SaveItems(s.DB, res.Items) if err != nil { s.serverError(w, err) @@ -167,7 +221,7 @@ func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) { return } d.Fetched, d.NewItems, d.Errors, d.Skipped = true, n, res.Errors, res.Skipped - s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Data: d}) + s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content", Data: d}) } // contentItems handles the item list's buttons: dismiss, restore, write. @@ -182,13 +236,16 @@ func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) { } ids := r.PostForm["item"] back := fmt.Sprintf("/content/%d", e.ID) + if content.IsOwn(e) { + back = "/content/own" + } showErr := func(msg string) { d, err := s.entryData(e, r.PostForm.Get("dismissed") == "1") if err != nil { s.serverError(w, err) return } - s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Error: msg, Data: d}) + s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content", Error: msg, Data: d}) } if len(ids) == 0 { showErr("Select at least one item first.") diff --git a/internal/web/content_test.go b/internal/web/content_test.go index 850f130..a750f63 100644 --- a/internal/web/content_test.go +++ b/internal/web/content_test.go @@ -2,7 +2,9 @@ package web import ( "context" + "fmt" "net/http" + "net/http/httptest" "net/url" "strconv" "strings" @@ -273,3 +275,44 @@ func TestWriteRedditNeedsSubreddit(t *testing.T) { t.Errorf("write without subreddit: %s", rec.Body.String()) } } + +func TestOwnContentPage(t *testing.T) { + var site *httptest.Server + site = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/sitemap.xml": + fmt.Fprintf(w, `%s/blog/launch%s`, site.URL, time.Now().UTC().Format("2006-01-02")) + case "/blog/launch": + w.Write([]byte(`We launched Acme Mail`)) + default: + http.NotFound(w, r) + } + })) + defer site.Close() + + s, h := newTestServer(t, nil) + _ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", + Products: []profile.Product{{Name: "Acme Mail", Description: "Hosted email.", URL: "https://acme.example/mail"}}, + Websites: []profile.Website{{URL: site.URL}}}) + + body := do(h, http.MethodGet, "/content", nil, nil).Body.String() + if !strings.Contains(body, `href="/content/own">Acme`) || !strings.Contains(body, "1 product, new pages on your websites") { + t.Errorf("content index:\n%s", body) + } + body = do(h, http.MethodGet, "/content/own", nil, nil).Body.String() + for _, want := range []string{"

Acme ", `value="product:acme-mail"`, `action="/content/own/fetch"`, + `href="/profile">Edit profile`, `action="/content/own/items"`} { + if !strings.Contains(body, want) { + t.Errorf("own page lacks %q", want) + } + } + rec := postForm(h, "/content/own/fetch", nil) + if body := rec.Body.String(); !strings.Contains(body, "1 new item") || !strings.Contains(body, "We launched Acme Mail") { + t.Errorf("fetch:\n%s", body) + } + // Writing goes through the same form; without an AI key, its error shows. + rec = postForm(h, "/content/own/items", url.Values{"action": {"write"}, "item": {"product:acme-mail"}, "channel": {"linkedin"}}) + if !strings.Contains(rec.Body.String(), "Anthropic API key") { + t.Errorf("write: %s", rec.Body.String()) + } +} diff --git a/internal/web/inbox.go b/internal/web/inbox.go index e3ecfff..3f230e5 100644 --- a/internal/web/inbox.go +++ b/internal/web/inbox.go @@ -126,7 +126,8 @@ func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[in historyRead = true } info, _ := content.GetSubreddit(s.DB, d.Target) - check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now()} + check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now(), + Promo: d.Kind == content.KindProduct} if tags != nil { check.Own = tags.Own check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content) diff --git a/internal/web/profile.go b/internal/web/profile.go index 0d57c6a..b5f8c59 100644 --- a/internal/web/profile.go +++ b/internal/web/profile.go @@ -48,6 +48,7 @@ func profileFromForm(r *http.Request) *profile.Profile { Voice: f.Get("voice"), Avoid: profile.Lines(f.Get("avoid")), Keywords: profile.Lines(f.Get("keywords")), + Feeds: profile.Lines(f.Get("feeds")), Targets: profile.Targets{ Industries: profile.Lines(f.Get("industries")), CompanySizes: profile.Lines(f.Get("company_sizes")), diff --git a/internal/web/static/app.css b/internal/web/static/app.css index e30b48a..a2d14b9 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -67,6 +67,7 @@ details.card[open] > summary { margin-bottom: 0.75rem; } .badge.partner { background: #e0f2f7; color: var(--cyan-dark); } .badge.competitor { background: #fbe4f0; color: var(--magenta); } .badge.watch { background: #eef0f4; color: var(--muted); } +.badge.product { background: #e7f6ed; color: var(--ok); } .tabs { display: flex; gap: 0.25rem; margin-bottom: 1rem; border-bottom: 1px solid var(--line); flex-wrap: wrap; } .tabs a { padding: 0.45rem 0.9rem; text-decoration: none; color: var(--muted); border-bottom: 2px solid transparent; text-transform: capitalize; } diff --git a/internal/web/templates/content-entry.html b/internal/web/templates/content-entry.html index 7795d3f..d4ae639 100644 --- a/internal/web/templates/content-entry.html +++ b/internal/web/templates/content-entry.html @@ -5,16 +5,18 @@ Published
-

{{.Entry.Name}} {{.Entry.Relationship}}

+

{{.Name}} {{.Entry.Relationship}}

-
+
- Edit entry + {{if .Own}}Edit profile{{else}}Edit entry{{end}}

- {{if .Sources}}Reads {{join .Sources ", "}}.{{else}}This entry has no sources yet: add an X handle, hashtags, a YouTube channel or RSS feeds to it.{{end}} + {{if .Own}}Posts that promote your own work: pick a product, or fetch your feeds and new pages on your websites. + {{if .Sources}}Reads {{join .Sources ", "}}.{{else}}Add your blog and release feeds, and your websites, to the profile to fetch them.{{end}} + {{else}}{{if .Sources}}Reads {{join .Sources ", "}}.{{else}}This entry has no sources yet: add an X handle, hashtags, a YouTube channel or RSS feeds to it.{{end}}{{end}} Last fetched {{ago .LastChecked}}; the next fetch looks for posts since {{.Since.Local.Format "2 Jan 15:04"}}.

@@ -28,13 +30,32 @@ {{end}} -{{if .Items}} -
+{{if or .Items (and .Products (not .ShowDismissed))}} + {{if .ShowDismissed}}{{end}} + {{if and .Products (not .ShowDismissed)}} +

Products

+
    + {{range .Products}} +
  • + +
  • + {{end}} +
+ {{if .Items}}

News from your feeds and sites

{{end}} + {{end}} + {{if .Items}}
    {{range .Items}}
  • @@ -50,6 +71,7 @@
  • {{end}}
+ {{end}} {{if .ShowDismissed}}
@@ -83,7 +105,7 @@
{{else}}
-

{{if .ShowDismissed}}Nothing dismissed.{{else}}No items yet. Fetch to see what {{.Entry.Name}} has been up to.{{end}}

+

{{if .ShowDismissed}}Nothing dismissed.{{else if .Own}}No products or news yet: add products, feeds or websites to your profile, then fetch.{{else}}No items yet. Fetch to see what {{.Name}} has been up to.{{end}}

{{end}} {{end}}{{end}} diff --git a/internal/web/templates/content.html b/internal/web/templates/content.html index 04283d4..947a24d 100644 --- a/internal/web/templates/content.html +++ b/internal/web/templates/content.html @@ -13,9 +13,15 @@ {{range .Rows}} - {{.Entry.Name}} + {{if .Own}} + {{.Name}} your own work + product + {{if .Sources}}{{join .Sources ", "}}{{else}}none: add products, websites or feeds to your profile{{end}} + {{else}} + {{.Name}} {{.Entry.Relationship}} {{if .Sources}}{{join .Sources ", "}}{{else}}none: add some{{end}} + {{end}} {{if .Waiting}}{{.Waiting}}{{end}} {{ago .LastChecked}} diff --git a/internal/web/templates/profile.html b/internal/web/templates/profile.html index 970da8c..5972338 100644 --- a/internal/web/templates/profile.html +++ b/internal/web/templates/profile.html @@ -85,6 +85,8 @@ {{end}}

To remove a website, clear its address.

+ {{with .P.Accounts}}