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
+215
View File
@@ -0,0 +1,215 @@
// Package rss reads RSS 2.0 and Atom feeds into content items.
package rss
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"fmt"
"html"
"io"
"net/http"
"regexp"
"strings"
"time"
"supermarket/internal/models"
)
// maxFeedBytes caps how much of a feed is read.
const maxFeedBytes = 5 << 20
// maxBody caps an item's text: enough for the model to understand it.
const maxBody = 1500
// Client fetches feeds.
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}
}
// Fetch returns the feed's items published after since.
func (c *Client) Fetch(ctx context.Context, feedURL string, since time.Time, entryName string) ([]models.ContentItem, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Accept", "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.8")
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)
}
data, err := io.ReadAll(io.LimitReader(res.Body, maxFeedBytes))
if err != nil {
return nil, err
}
items, err := Parse(data, entryName)
if err != nil {
return nil, err
}
out := items[:0]
for _, it := range items {
// Items without a date are kept: some feeds leave it out.
if it.PublishedAt.IsZero() || it.PublishedAt.After(since) {
if it.PublishedAt.IsZero() {
it.PublishedAt = time.Now().UTC()
}
out = append(out, it)
}
}
return out, nil
}
type rssDoc struct {
XMLName xml.Name
Channel struct {
Title string `xml:"title"`
Items []rssItem `xml:"item"`
} `xml:"channel"`
// Atom
Title string `xml:"title"`
Entries []atomEntry `xml:"entry"`
}
type rssItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
GUID string `xml:"guid"`
PubDate string `xml:"pubDate"`
Date string `xml:"http://purl.org/dc/elements/1.1/ date"`
Description string `xml:"description"`
Content string `xml:"http://purl.org/rss/1.0/modules/content/ encoded"`
Author string `xml:"author"`
Creator string `xml:"http://purl.org/dc/elements/1.1/ creator"`
}
type atomEntry struct {
Title string `xml:"title"`
ID string `xml:"id"`
Links []struct {
Href string `xml:"href,attr"`
Rel string `xml:"rel,attr"`
} `xml:"link"`
Published string `xml:"published"`
Updated string `xml:"updated"`
Summary string `xml:"summary"`
Content string `xml:"content"`
Author struct {
Name string `xml:"name"`
} `xml:"author"`
}
// Parse reads an RSS 2.0 or Atom document.
func Parse(data []byte, entryName string) ([]models.ContentItem, error) {
var doc rssDoc
dec := xml.NewDecoder(strings.NewReader(string(data)))
dec.Strict = false
dec.CharsetReader = func(_ string, r io.Reader) (io.Reader, error) { return r, nil }
if err := dec.Decode(&doc); err != nil {
return nil, fmt.Errorf("not an RSS or Atom feed: %w", err)
}
var items []models.ContentItem
switch strings.ToLower(doc.XMLName.Local) {
case "rss", "rdf":
for _, it := range doc.Channel.Items {
key := firstNonEmpty(it.GUID, it.Link, it.Title)
if key == "" {
continue
}
items = append(items, models.ContentItem{
ID: itemID(key),
Source: models.SourceRSS,
Author: clean(firstNonEmpty(it.Creator, it.Author, doc.Channel.Title), 200),
Title: clean(it.Title, 300),
Body: clean(firstNonEmpty(it.Content, it.Description), maxBody),
URL: strings.TrimSpace(it.Link),
PublishedAt: parseDate(firstNonEmpty(it.PubDate, it.Date)),
AppName: entryName,
})
}
case "feed":
for _, e := range doc.Entries {
link := ""
for _, l := range e.Links {
if l.Rel == "" || l.Rel == "alternate" {
link = l.Href
break
}
}
key := firstNonEmpty(e.ID, link, e.Title)
if key == "" {
continue
}
items = append(items, models.ContentItem{
ID: itemID(key),
Source: models.SourceRSS,
Author: clean(firstNonEmpty(e.Author.Name, doc.Title), 200),
Title: clean(e.Title, 300),
Body: clean(firstNonEmpty(e.Summary, e.Content), maxBody),
URL: strings.TrimSpace(link),
PublishedAt: parseDate(firstNonEmpty(e.Published, e.Updated)),
AppName: entryName,
})
}
default:
return nil, fmt.Errorf("not an RSS or Atom feed (root element <%s>)", doc.XMLName.Local)
}
return items, nil
}
func itemID(key string) string {
h := sha256.Sum256([]byte(strings.TrimSpace(key)))
return "rss:" + hex.EncodeToString(h[:12])
}
var (
tags = regexp.MustCompile(`(?s)<[^>]*>`)
spaces = regexp.MustCompile(`\s+`)
)
// clean turns feed HTML into plain text of at most n characters.
func clean(s string, n int) string {
s = tags.ReplaceAllString(s, " ")
s = html.UnescapeString(s)
s = strings.TrimSpace(spaces.ReplaceAllString(s, " "))
if r := []rune(s); len(r) > n {
s = string(r[:n-1]) + "…"
}
return s
}
var dateLayouts = []string{
time.RFC1123Z, time.RFC1123, time.RFC3339, time.RFC3339Nano,
"Mon, 2 Jan 2006 15:04:05 -0700", "Mon, 2 Jan 2006 15:04:05 MST",
"2 Jan 2006 15:04:05 -0700", "2006-01-02T15:04:05", "2006-01-02",
}
func parseDate(s string) time.Time {
s = strings.TrimSpace(s)
for _, l := range dateLayouts {
if t, err := time.Parse(l, s); err == nil {
return t.UTC()
}
}
return time.Time{}
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return ""
}
+59
View File
@@ -0,0 +1,59 @@
package rss
import (
"strings"
"testing"
"time"
)
func TestParseRSS(t *testing.T) {
feed := `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel><title>Jitsi blog</title>
<item><title>Jitsi 3 &amp; more</title><link>https://jitsi.org/blog/3</link>
<guid>jitsi-3</guid><pubDate>Mon, 02 Nov 2026 10:00:00 +0000</pubDate>
<description><![CDATA[<p>New <b>release</b>.</p>]]></description><dc:creator>Saúl</dc:creator></item>
<item><title>No date</title><link>https://jitsi.org/blog/x</link></item>
</channel></rss>`
items, err := Parse([]byte(feed), "Jitsi")
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("got %d items", len(items))
}
it := items[0]
if it.Title != "Jitsi 3 & more" || it.Body != "New release ." || it.Author != "Saúl" || it.URL != "https://jitsi.org/blog/3" {
t.Errorf("item = %+v", it)
}
if !it.PublishedAt.Equal(time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC)) {
t.Errorf("date = %v", it.PublishedAt)
}
if !strings.HasPrefix(it.ID, "rss:") || it.ID == items[1].ID || it.AppName != "Jitsi" {
t.Errorf("ids %q %q", it.ID, items[1].ID)
}
if !items[1].PublishedAt.IsZero() || items[1].Author != "Jitsi blog" {
t.Errorf("undated item = %+v", items[1])
}
}
func TestParseAtom(t *testing.T) {
feed := `<feed xmlns="http://www.w3.org/2005/Atom"><title>Releases</title>
<entry><title>v2.0</title><id>tag:x,2026:2</id>
<link rel="alternate" href="https://example.com/v2"/><link rel="edit" href="https://example.com/edit"/>
<updated>2026-11-03T08:00:00Z</updated><summary>Faster.</summary><author><name>Ana</name></author></entry>
</feed>`
items, err := Parse([]byte(feed), "X")
if err != nil {
t.Fatal(err)
}
if len(items) != 1 || items[0].URL != "https://example.com/v2" || items[0].Body != "Faster." || items[0].Author != "Ana" {
t.Fatalf("items = %+v", items)
}
}
func TestParseRejectsHTML(t *testing.T) {
if _, err := Parse([]byte(`<html><body>hi</body></html>`), "X"); err == nil {
t.Fatal("expected an error for an HTML page")
}
}