Files
supermarket/internal/content/drafts.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

370 lines
12 KiB
Go

package content
import (
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"unicode/utf8"
"supermarket/internal/api/twitter"
"supermarket/internal/db"
)
// Channels a draft can be for.
const (
ChannelX = "x"
ChannelLinkedIn = "linkedin"
ChannelReddit = "reddit"
)
// RedditTitleLimit is the longest title Reddit takes.
const RedditTitleLimit = 300
// Channel describes where drafts are published.
type Channel struct {
ID string
Name string
Limit int // characters, counted the way the channel counts them
}
// Channels lists the channels drafts can be written for, in display order.
var Channels = []Channel{
{ChannelX, "X", 280},
{ChannelLinkedIn, "LinkedIn", 3000},
{ChannelReddit, "Reddit", 40000},
}
// ChannelByID returns the channel, or false.
func ChannelByID(id string) (Channel, bool) {
for _, c := range Channels {
if c.ID == id {
return c, true
}
}
return Channel{}, false
}
// Draft statuses.
const (
StatusDraft = "draft" // waiting for review, in the Inbox
StatusScheduled = "scheduled" // approved, goes out at PublishAt
StatusPublishing = "publishing" // claimed by a publish in progress
StatusPublished = "published"
StatusFailed = "failed"
StatusDiscarded = "discarded"
)
// Draft is a post for one channel.
type Draft struct {
ID int64
Batch string // drafts written together share it
InventoryName string
Kind string // the entry's relationship
Channel string
Title string // Reddit only
Target string // Reddit: the subreddit, without r/
Content string
SourceURL string // added when publishing: appended on X, a link preview on LinkedIn
ItemIDs []string
Status string
Error string
PostURL string
CreatedAt time.Time
UpdatedAt time.Time
PublishedAt time.Time
PublishAt time.Time // when a scheduled draft goes out
}
// Length is the draft's length as its channel counts it, including the
// source link on X.
func (d *Draft) Length() int {
return Length(d.Channel, d.Content, d.SourceURL)
}
// Length counts content for channel.
func Length(channel, text, sourceURL string) int {
if channel == ChannelX {
return twitter.TweetLength(text, sourceURL)
}
return utf8.RuneCountInString(text)
}
// Limit is the channel's limit for the draft's text.
func (d *Draft) Limit() int {
c, _ := ChannelByID(d.Channel)
return c.Limit
}
// TooLong reports whether the draft can't be published as it is.
func (d *Draft) TooLong() bool {
return d.Length() > d.Limit() || utf8.RuneCountInString(d.Title) > RedditTitleLimit
}
// Problem says what stops the draft from being published, or "".
func (d *Draft) Problem() string {
switch {
case d.Channel == ChannelReddit && strings.TrimSpace(d.Title) == "":
return "the Reddit post needs a title"
case d.Channel == ChannelReddit && d.Target == "":
return "the Reddit post has no subreddit"
case utf8.RuneCountInString(d.Title) > RedditTitleLimit:
return fmt.Sprintf("the title is %d characters; Reddit allows %d", utf8.RuneCountInString(d.Title), RedditTitleLimit)
case d.Length() > d.Limit():
withLink := ""
if d.Channel == ChannelX && d.SourceURL != "" {
withLink = " including the link"
}
return fmt.Sprintf("the post is %d characters%s; %s allows %d", d.Length(), withLink, d.ChannelName(), d.Limit())
}
return ""
}
// Where is the channel plus, for Reddit, the subreddit: "Reddit r/golang".
func (d *Draft) Where() string {
if d.Target != "" {
return d.ChannelName() + " r/" + d.Target
}
return d.ChannelName()
}
// ChannelName is the channel's display name.
func (d *Draft) ChannelName() string {
if c, ok := ChannelByID(d.Channel); ok {
return c.Name
}
return d.Channel
}
// Editable reports whether the draft can still be changed and published.
func (d *Draft) Editable() bool {
return d.Status == StatusDraft || d.Status == StatusFailed
}
func newBatchID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// CreateDrafts stores drafts written together under one new batch and marks
// their items as used.
func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
batch := newBatchID()
tx, err := d.Begin()
if err != nil {
return "", err
}
defer tx.Rollback()
used := map[string]bool{}
var usedIDs []string
for _, dr := range drafts {
if _, ok := ChannelByID(dr.Channel); !ok {
return "", fmt.Errorf("unknown channel %q", dr.Channel)
}
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil {
return "", err
}
for _, id := range dr.ItemIDs {
if !used[id] {
used[id] = true
usedIDs = append(usedIDs, id)
}
}
}
if err := markUsed(tx, usedIDs); err != nil {
return "", err
}
return batch, tx.Commit()
}
func nonNil(s []string) []string {
if s == nil {
return []string{}
}
return s
}
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target`
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close()
var out []Draft
for rows.Next() {
var dr Draft
var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
dr.CreatedAt, dr.UpdatedAt, dr.PublishedAt = parseTime(created), parseTime(updated), parseTime(published)
dr.PublishAt = parseTime(publishAt)
out = append(out, dr)
}
return out, rows.Err()
}
// ListDrafts returns drafts with the given statuses, newest first.
func ListDrafts(d *db.DB, limit int, statuses ...string) ([]Draft, error) {
if len(statuses) == 0 {
return nil, errors.New("no statuses given")
}
args := make([]any, 0, len(statuses)+1)
for _, s := range statuses {
args = append(args, s)
}
args = append(args, limit)
order := "created_at DESC, id DESC"
if len(statuses) == 1 && statuses[0] == StatusPublished {
order = "published_at DESC, id DESC"
} else if len(statuses) == 1 && statuses[0] == StatusScheduled {
order = "publish_at, id"
}
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status IN (?`+
strings.Repeat(", ?", len(statuses)-1)+`) ORDER BY `+order+` LIMIT ?`, args...)
if err != nil {
return nil, err
}
return scanDrafts(rows)
}
// ErrNoDraft means there's no draft with that ID.
var ErrNoDraft = errors.New("no such draft")
// GetDraft returns one draft.
func GetDraft(d *db.DB, id int64) (*Draft, error) {
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE id = ?`, id)
if err != nil {
return nil, err
}
drafts, err := scanDrafts(rows)
if err != nil {
return nil, err
}
if len(drafts) == 0 {
return nil, ErrNoDraft
}
return &drafts[0], nil
}
// ErrNotEditable means the draft was published, discarded, or is being
// published.
var ErrNotEditable = errors.New("this draft can't be changed any more")
// UpdateDraft saves edited text.
func UpdateDraft(d *db.DB, id int64, text string) error {
text = strings.TrimSpace(text)
if text == "" {
return errors.New("the post is empty")
}
res, err := d.Exec(`UPDATE drafts SET content = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`,
text, formatTime(time.Now()), id, StatusDraft, StatusFailed)
return oneRow(res, err)
}
// DiscardDraft drops a draft without publishing it.
func DiscardDraft(d *db.DB, id int64) error {
res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`,
StatusDiscarded, formatTime(time.Now()), id, StatusDraft, StatusFailed)
return oneRow(res, err)
}
func oneRow(res sql.Result, err error) error {
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n != 1 {
return ErrNotEditable
}
return nil
}
// RecoverInterrupted marks drafts left "publishing" by a stopped app as
// failed: they may or may not have gone out, so the user checks first.
func RecoverInterrupted(d *db.DB) (int, error) {
res, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE status = ?`,
StatusFailed, "Supermarket stopped while publishing this. Check the channel before publishing it again.",
formatTime(time.Now()), StatusPublishing)
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
// CountDrafts is how many drafts wait for review.
func CountDrafts(d *db.DB) (int, error) {
var n int
err := d.QueryRow(`SELECT count(*) FROM drafts WHERE status IN (?, ?)`, StatusDraft, StatusFailed).Scan(&n)
return n, err
}
// Schedule approves a draft to go out at at. It must be one that can still
// be published, and at most a year ahead.
func Schedule(d *db.DB, id int64, at time.Time) error {
if at.After(time.Now().AddDate(1, 0, 0)) {
return errors.New("that's more than a year away")
}
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ?
WHERE id = ? AND status IN (?, ?)`,
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed)
return oneRow(res, err)
}
// Unschedule sends a scheduled draft back to the Inbox, to edit or drop.
func Unschedule(d *db.DB, id int64) error {
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = NULL, updated_at = ? WHERE id = ? AND status = ?`,
StatusDraft, formatTime(time.Now()), id, StatusScheduled)
return oneRow(res, err)
}
// MaxLate is how late a scheduled post may still go out, if the app was
// stopped when it was due. Later than that, news is stale: it goes back to
// the Inbox instead.
const MaxLate = 12 * time.Hour
// Due returns the scheduled drafts whose time has come, oldest first. Ones
// more than MaxLate overdue are sent back to the Inbox with a note.
func Due(d *db.DB, now time.Time) ([]Draft, error) {
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ?
WHERE status = ? AND publish_at < ?`,
StatusFailed, "Not published: Supermarket wasn't running when this was due. Publish or reschedule it.",
formatTime(now), StatusScheduled, formatTime(now.Add(-MaxLate))); err != nil {
return nil, err
}
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status = ? AND publish_at <= ?
ORDER BY publish_at, id`, StatusScheduled, formatTime(now))
if err != nil {
return nil, err
}
return scanDrafts(rows)
}
// FailScheduled sends a scheduled draft that couldn't go out (its channel
// was signed out, say) back to the Inbox with the reason.
func FailScheduled(d *db.DB, id int64, reason string) error {
res, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ? AND status = ?`,
StatusFailed, reason, formatTime(time.Now()), id, StatusScheduled)
return oneRow(res, err)
}
// UpdateTitle saves an edited Reddit title.
func UpdateTitle(d *db.DB, id int64, title string) error {
title = strings.Join(strings.Fields(title), " ")
if title == "" {
return errors.New("the title is empty")
}
res, err := d.Exec(`UPDATE drafts SET title = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?)`,
title, formatTime(time.Now()), id, ChannelReddit, StatusDraft, StatusFailed)
return oneRow(res, err)
}