Files
supermarket/internal/web/content.go
T
davidandClaude Opus 5.5 0e34f574b7 Phase 1, part 3: Reddit
- Sign in with a Reddit web app; access tokens refresh automatically,
  and an app-only token reads rules before sign-in.
- Reddit drafts: a title and text for one subreddit, chosen when
  writing. The subreddit's guidelines and rules go into the prompt, which
  asks for a community member's post that discloses the affiliation and
  avoids marketing language.
- The Inbox shows the subreddit's rules (cached for a day, with Refresh)
  and warns, without blocking, about promotion rules, restricted
  subreddits, link-only subreddits, posting in the same subreddit within
  a week, more than 1 in 10 recent posts linking to the company's sites,
  and new accounts.
- Publishing makes a text post with the source link at the end, or a
  link post where the subreddit takes only links.
- Migration 4 adds the draft's title and subreddit, and the rules cache.
  Publishers now take a Post, which carries the title and subreddit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:51:16 -07:00

299 lines
7.5 KiB
Go

package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/fetcher"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
// maxPerItem caps "one post per item", which makes one AI call per item.
const maxPerItem = 10
// --- Sources: entries and their fetched items ---
type contentRow struct {
Entry inventory.Entry
Sources []string
Waiting int
LastChecked time.Time
}
func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) {
entries, err := inventory.List(s.DB, "")
if err != nil {
s.serverError(w, err)
return
}
counts, err := content.Counts(s.DB)
if err != nil {
s.serverError(w, err)
return
}
rows := make([]contentRow, 0, len(entries))
for _, e := range entries {
last, _ := content.LastChecked(s.DB, e.Name)
rows = append(rows, contentRow{Entry: e, 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}})
}
type channelChoice struct {
content.Channel
Connected bool
}
type entryPage struct {
Entry *inventory.Entry
Sources []string
Items []content.Item
ShowDismissed bool
LastChecked time.Time
Since time.Time
Channels []channelChoice
ProfileSet bool
Subreddits []string // suggestions: the entry's, then the profile's
// After a fetch
Fetched bool
NewItems int
Errors []string
Skipped []string
}
func (s *Server) loadEntry(w http.ResponseWriter, r *http.Request) *inventory.Entry {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return nil
}
e, err := inventory.Get(s.DB, id)
if err != nil {
s.serverError(w, err)
return nil
}
if e == nil {
http.NotFound(w, r)
}
return e
}
func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, error) {
items, err := content.ListItems(s.DB, e.Name, showDismissed, 200)
if err != nil {
return nil, err
}
last, err := content.LastChecked(s.DB, e.Name)
if err != nil {
return nil, err
}
since, _ := content.Since(s.DB, e.Name, time.Now())
p, err := profile.Load(s.DB)
if err != nil {
return nil, err
}
pubs := s.publishers()
var chans []channelChoice
for _, c := range content.Channels {
chans = append(chans, channelChoice{c, pubs[c.ID] != nil})
}
var subs []string
seen := map[string]bool{}
for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} {
for _, sr := range list {
if n := reddit.CleanName(sr); n != "" && !seen[strings.ToLower(n)] {
seen[strings.ToLower(n)] = true
subs = append(subs, n)
}
}
}
return &entryPage{Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil
}
func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
d, err := s.entryData(e, r.URL.Query().Get("dismissed") == "1")
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-entry", page{Title: e.Name, Nav: "content", Data: d})
}
func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
now := time.Now()
since, err := content.Since(s.DB, e.Name, now)
if err != nil {
s.serverError(w, err)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second)
defer cancel()
res := s.fetcher().Fetch(ctx, e, since)
n, err := content.SaveItems(s.DB, res.Items)
if err != nil {
s.serverError(w, err)
return
}
// Only move the start of the next fetch on if every source answered, so
// a failed source is read from the same point next time.
if len(res.Errors) == 0 {
if err := content.SetLastChecked(s.DB, e.Name, now); err != nil {
s.serverError(w, err)
return
}
}
d, err := s.entryData(e, false)
if err != nil {
s.serverError(w, err)
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})
}
// contentItems handles the item list's buttons: dismiss, restore, write.
func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) {
e := s.loadEntry(w, r)
if e == nil {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ids := r.PostForm["item"]
back := fmt.Sprintf("/content/%d", e.ID)
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})
}
if len(ids) == 0 {
showErr("Select at least one item first.")
return
}
switch r.PostForm.Get("action") {
case "dismiss":
if err := content.Dismiss(s.DB, ids); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back, "dismissed")
case "restore":
if err := content.Restore(s.DB, ids); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back+"?dismissed=1", "restored")
case "write":
if err := s.writeDrafts(r, e, ids); err != nil {
showErr(err.Error())
return
}
redirect(w, r, "/inbox", "drafted")
default:
http.Error(w, "unknown action", http.StatusBadRequest)
}
}
func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string) error {
channels := r.PostForm["channel"]
if len(channels) == 0 {
return errors.New("choose at least one channel to write for")
}
perItem := r.PostForm.Get("mode") == "each"
if perItem && len(ids) > maxPerItem {
return fmt.Errorf("one post per item works on up to %d items at a time; you selected %d", maxPerItem, len(ids))
}
p, err := profile.Load(s.DB)
if err != nil {
return err
}
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
return err
}
client, err := ai.New(cfg, s.Secrets)
if err != nil {
return err
}
items, err := content.GetItems(s.DB, ids)
if err != nil {
return err
}
// Keep channels in display order whatever order the form sent.
var ordered []string
for _, c := range content.Channels {
for _, ch := range channels {
if ch == c.ID {
ordered = append(ordered, c.ID)
break
}
}
}
req := content.Request{Profile: p, Entry: e}
for _, ch := range ordered {
if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit"))
if req.Subreddit == "" {
return errors.New("choose a subreddit for the Reddit post")
}
// The rules go into the prompt; without them the model is told
// to be careful, and the Inbox warns.
info, err := s.subreddit(r.Context(), req.Subreddit, false)
if err != nil {
s.Log.Warn("reddit: couldn't read the subreddit's rules", "subreddit", req.Subreddit, "err", err)
}
req.SubredditInfo = info
}
}
groups := [][]content.Item{items}
if perItem {
groups = groups[:0]
for _, it := range items {
groups = append(groups, []content.Item{it})
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
written := 0
for _, g := range groups {
req.Items, req.Channels = g, ordered
drafts, err := content.Generate(ctx, client, req)
if err != nil {
if written > 0 {
return fmt.Errorf("wrote %d set(s) of drafts, then: %w", written, err)
}
return err
}
if _, err := content.CreateDrafts(s.DB, drafts); err != nil {
return err
}
written++
}
return nil
}