Files
davidandClaude Opus 5.5 5451fe6d63 Reddit: posted by hand, with the rules pasted
Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:48:54 -07:00

488 lines
17 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 Posts
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
SignalID int64 // the buying signal it was written for; 0: none
SignalSlug string // that signal's campaign tag
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page (before posting accounts)
AccountID int64 // the posting account it goes out from; 0: the company's for its channel
WrittenBy int64 // who wrote it (asked the AI for it); 0: unknown, or the local edition
PostedBy int64 // who published or scheduled it
PostedAs string // the account it went out as, once it did
}
// AsPage is the LinkedIn author choice for the company page.
const AsPage = "page"
// LinkedInDefaultKey is the setting saying whether new LinkedIn drafts
// post as the company page ("page") or as you ("").
const LinkedInDefaultKey = "linkedin:post-as"
// 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()
// Read before the transaction: it holds the database's one connection.
var liDefault string
if _, err := d.GetJSON(LinkedInDefaultKey, &liDefault); err != nil {
return "", err
}
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))
var sig any
if dr.SignalID != 0 {
sig = dr.SignalID
}
as := dr.LinkedInAs
if dr.Channel == ChannelLinkedIn && as == "" {
as = liDefault
}
if dr.Channel != ChannelLinkedIn {
as = ""
}
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as, dr.AccountID, dr.WrittenBy); 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,
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as,
account_id, written_by, posted_by, posted_as`
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,
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs, &dr.AccountID, &dr.WrittenBy, &dr.PostedBy, &dr.PostedAs); 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")
// ErrByHand is the answer to publishing or scheduling a Reddit draft: you
// post those yourself.
var ErrByHand = errors.New("Reddit posts are posted by hand: open the subreddit's submit page from the draft, post it there, then mark it as posted")
// 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)
}
// SetLinkedInAs chooses who a LinkedIn draft posts as: "" for you,
// AsPage for the company page.
func SetLinkedInAs(d *db.DB, id int64, as string) error {
if as != "" && as != AsPage {
return fmt.Errorf("unknown author %q", as)
}
res, err := d.Exec(`UPDATE drafts SET linkedin_as = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?, ?)`,
as, formatTime(time.Now()), id, ChannelLinkedIn, StatusDraft, StatusFailed, StatusScheduled)
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
}
// ForSignal lists the posts written for a signal, newest first: the
// published ones, then the rest that aren't discarded.
func ForSignal(d *db.DB, signalID int64, limit int) ([]Draft, error) {
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE signal_id = ? AND status != ?
ORDER BY published_at IS NULL, published_at DESC, id DESC LIMIT ?`, signalID, StatusDiscarded, limit)
if err != nil {
return nil, err
}
return scanDrafts(rows)
}
// 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 (?, ?) AND channel <> ?`,
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed, ChannelReddit)
err = oneRow(res, err)
if errors.Is(err, ErrNotEditable) {
if dr, gerr := GetDraft(d, id); gerr == nil && dr.Channel == ChannelReddit {
return ErrByHand
}
}
return err
}
// Unschedule sends a scheduled draft back to Posts, 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
// Posts 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 Posts 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 Posts 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)
}
// SetAccount chooses the posting account a draft goes out from (0: the
// company's for its channel).
func SetAccount(d *db.DB, id, account int64) error {
res, err := d.Exec(`UPDATE drafts SET account_id = ?, updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
account, formatTime(time.Now()), id, StatusDraft, StatusFailed, StatusScheduled)
return oneRow(res, err)
}
// SetPostedBy records who published or scheduled a draft.
func SetPostedBy(d *db.DB, id, user int64) error {
_, err := d.Exec(`UPDATE drafts SET posted_by = ? WHERE id = ?`, user, id)
return err
}
// Copy makes a copy of a draft for another posting account, in the same
// batch, waiting in Posts; it returns the copy's ID.
func Copy(d *db.DB, id, account int64) (int64, error) {
dr, err := GetDraft(d, id)
if err != nil {
return 0, err
}
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
var sig any
if dr.SignalID != 0 {
sig = dr.SignalID
}
return d.Insert(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, dr.Batch, dr.InventoryName, dr.Kind, dr.Channel, dr.Title, dr.Target, dr.Content,
dr.SourceURL, string(ids), sig, dr.LinkedInAs, account, dr.WrittenBy)
}
// HoldForAccount sends the scheduled drafts going out from an account back
// to Posts, with the reason: the account was signed out or removed. It
// returns them, to tell their writers.
func HoldForAccount(d *db.DB, account int64, reason string) ([]Draft, error) {
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE account_id = ? AND status = ?`, account, StatusScheduled)
if err != nil {
return nil, err
}
held, err := scanDrafts(rows)
if err != nil {
return nil, err
}
_, err = d.Exec(`UPDATE drafts SET status = ?, error = ?, account_id = 0, updated_at = ? WHERE account_id = ? AND status = ?`,
StatusFailed, reason, formatTime(time.Now()), account, StatusScheduled)
if err != nil {
return nil, err
}
// Drafts waiting in Posts for it fall back to the company's account.
_, err = d.Exec(`UPDATE drafts SET account_id = 0 WHERE account_id = ? AND status IN (?, ?)`, account, StatusDraft, StatusFailed)
return held, err
}