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>
This commit is contained in:
2026-11-20 13:51:16 -07:00
co-authored by Claude Opus 5.5
parent b0f06058ec
commit 0e34f574b7
27 changed files with 1404 additions and 91 deletions
+145
View File
@@ -0,0 +1,145 @@
package content
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/db"
)
// SubredditMaxAge is how long a subreddit's cached rules are used before
// they're fetched again.
const SubredditMaxAge = 24 * time.Hour
// GetSubreddit returns the cached subreddit, or nil.
func GetSubreddit(d *db.DB, name string) (*reddit.Subreddit, error) {
var raw string
err := d.QueryRow(`SELECT data FROM subreddits WHERE name = ?`, reddit.CleanName(name)).Scan(&raw)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
var s reddit.Subreddit
if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, err
}
return &s, nil
}
// SaveSubreddit caches a subreddit's rules.
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error {
raw, err := json.Marshal(s)
if err != nil {
return err
}
_, err = d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES (?, ?, ?)
ON CONFLICT (name) DO UPDATE SET data = excluded.data, fetched_at = excluded.fetched_at`,
s.Name, string(raw), formatTime(s.FetchedAt))
return err
}
// Reddit's self-promotion guideline: at most one post in ten about your own
// work. Posting to the same subreddit more than about weekly reads as spam.
const (
ownShareLimit = 0.10
sameSubWindow = 7 * 24 * time.Hour
historyWindow = 30 * 24 * time.Hour
)
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`)
// RedditCheck is what the warnings are worked out from.
type RedditCheck struct {
Target string
HasLink bool // the draft carries a link
OwnLink bool // to the company's own site
Info *reddit.Subreddit // nil if the rules couldn't be read
History []reddit.Submission // the account's recent posts; nil if unknown
Own func(url string) bool
Now time.Time
}
// RedditWarnings lists reasons to think twice before posting. They never
// block publishing: the user decides.
func RedditWarnings(c RedditCheck) []string {
var w []string
sub := "r/" + c.Target
if c.Info == nil {
w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.")
} else {
if c.Info.Type == "restricted" || c.Info.Type == "private" {
w = append(w, fmt.Sprintf("%s is %s: only approved users can post.", sub, c.Info.Type))
}
if !c.Info.AllowsText() && !c.HasLink {
w = append(w, sub+" only takes link posts, and this draft has no link.")
} else if !c.Info.AllowsText() {
w = append(w, sub+" only takes link posts: it will be posted as the title and the link, without the text.")
}
for _, r := range c.Info.Rules {
if promoRule.MatchString(r.Name + " " + r.Description) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, r.Name))
}
}
}
if c.History == nil {
return w
}
if len(c.History) == 0 {
w = append(w, "This account hasn't posted before. Communities often remove a new account's first posts, especially promotional ones: take part in discussions first.")
return w
}
var inSub []time.Time
recent, own := 0, 0
for _, s := range c.History {
age := c.Now.Sub(s.Created)
if strings.EqualFold(s.Subreddit, c.Target) && age < sameSubWindow {
inSub = append(inSub, s.Created)
}
if age < historyWindow {
recent++
if c.Own != nil && (c.Own(s.URL) || containsOwnLink(s.Text, c.Own)) {
own++
}
}
}
if len(inSub) > 0 {
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week, last on %s. Most communities expect less.",
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
}
// Count this post as one more own link, if it has one.
if c.OwnLink {
share := float64(own+1) / float64(recent+1)
if share > ownShareLimit && own+1 > 1 {
w = append(w, fmt.Sprintf("With this one, %d of your %d posts in the past 30 days link to your own sites. Reddit's guideline is at most 1 in 10.",
own+1, recent+1))
}
}
return w
}
var urlPattern = regexp.MustCompile(`https?://[^\s)\]>"]+`)
func containsOwnLink(text string, own func(string) bool) bool {
for _, u := range urlPattern.FindAllString(text, -1) {
if own(u) {
return true
}
}
return false
}
func plural(n int) string {
if n == 1 {
return ""
}
return "s"
}