Phase 1, part 1: fetch, write and publish posts from the web app

Brings back posting, which Phase 0 removed with the terminal interface.

- Content page: per inventory entry, fetch its X account, X hashtag
  search, YouTube channel and RSS/Atom feeds (new), then select, dismiss
  or restore the fetched items, which are kept in the database.
- Writing: one AI call returns a draft per channel (X and LinkedIn),
  prompted from the company profile, the entry's relationship, talking
  points and mention policy, and each channel's rules. Fetched text is
  quoted as untrusted. An over-long X draft gets one request to shorten.
- Drafts page: edit with a live length counter that counts like X, then
  publish each draft on its own. A draft is claimed before posting so it
  can't go out twice; failures are kept on the draft for a retry; X
  tokens are refreshed and saved.
- Migration 2 adds content_items and drafts, and turns queued posts into
  drafts for the platforms they hadn't reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 12:58:24 -07:00
co-authored by Claude Opus 5.5
parent abf410d097
commit 13bf18facc
29 changed files with 2484 additions and 95 deletions
+395
View File
@@ -0,0 +1,395 @@
package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/ai"
"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})
}
drafts, _ := content.CountDrafts(s.DB)
s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{
"Rows": rows, "Drafts": drafts,
}})
}
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
Drafts int
// 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})
}
drafts, _ := content.CountDrafts(s.DB)
return &entryPage{Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet(), Drafts: drafts}, 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, "/drafts", "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
}
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()
// 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
}
}
}
written := 0
for _, g := range groups {
drafts, err := content.Generate(ctx, client, content.Request{Profile: p, Entry: e, Items: g, Channels: ordered})
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
}
// --- Drafts ---
type draftBatch struct {
Batch string
InventoryName string
Kind string
CreatedAt time.Time
SourceURL string
Drafts []content.Draft
}
func (s *Server) draftsPage(w http.ResponseWriter, r *http.Request) {
s.renderDrafts(w, r, "")
}
func (s *Server) renderDrafts(w http.ResponseWriter, r *http.Request, errMsg string) {
pending, err := content.ListDrafts(s.DB, 200, content.StatusDraft, content.StatusFailed)
if err != nil {
s.serverError(w, err)
return
}
var batches []*draftBatch
byID := map[string]*draftBatch{}
for _, d := range pending {
b := byID[d.Batch]
if b == nil {
b = &draftBatch{Batch: d.Batch, InventoryName: d.InventoryName, Kind: d.Kind, CreatedAt: d.CreatedAt, SourceURL: d.SourceURL}
byID[d.Batch] = b
batches = append(batches, b)
}
b.Drafts = append(b.Drafts, d)
}
for _, b := range batches {
// X first, then LinkedIn, whatever order they were stored in.
ordered := make([]content.Draft, 0, len(b.Drafts))
for _, c := range content.Channels {
for _, d := range b.Drafts {
if d.Channel == c.ID {
ordered = append(ordered, d)
}
}
}
b.Drafts = ordered
}
published, err := content.ListDrafts(s.DB, 20, content.StatusPublished)
if err != nil {
s.serverError(w, err)
return
}
pubs := s.publishers()
connected := map[string]bool{}
for id := range pubs {
connected[id] = true
}
s.render(w, r, "drafts", page{Title: "Drafts", Nav: "content", Error: errMsg, Data: map[string]any{
"Batches": batches, "Published": published, "Connected": connected,
}})
}
func (s *Server) draftID(w http.ResponseWriter, r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return 0, false
}
return id, true
}
// draftAction saves, publishes or discards one draft.
func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
id, ok := s.draftID(w, r)
if !ok {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fail := func(err error) {
if errors.Is(err, content.ErrNoDraft) {
http.NotFound(w, r)
return
}
s.renderDrafts(w, r, err.Error())
}
action := r.PathValue("action")
if action == "save" || action == "publish" {
if text, sent := r.PostForm["content"]; sent {
if err := content.UpdateDraft(s.DB, id, text[0]); err != nil {
fail(err)
return
}
}
}
switch action {
case "save":
redirect(w, r, "/drafts", "saved")
case "publish":
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
d, err := content.Publish(ctx, s.DB, s.publishers(), id)
if err != nil {
name := "the channel"
if d != nil {
name = d.ChannelName()
}
fail(fmt.Errorf("Couldn't publish to %s: %w", name, err))
return
}
redirect(w, r, "/drafts", "published")
case "discard":
if err := content.DiscardDraft(s.DB, id); err != nil {
fail(err)
return
}
redirect(w, r, "/drafts", "discarded")
default:
http.NotFound(w, r)
}
}