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
+159 -5
View File
@@ -2,8 +2,13 @@ package web
import (
"context"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/rss"
"supermarket/internal/api/twitter"
"supermarket/internal/api/youtube"
@@ -59,6 +64,9 @@ func (s *Server) publishers() content.Publishers {
if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" {
pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)}
}
if c := s.redditUser(); c != nil {
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
}
return pubs
}
@@ -66,9 +74,10 @@ type xPublisher struct{ c *twitter.Client }
// Publish appends the source link to the post, as the old app did; X shows
// it as a card.
func (p xPublisher) Publish(ctx context.Context, text, sourceURL string) (string, error) {
if sourceURL != "" {
text += "\n\n" + sourceURL
func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
text := post.Text
if post.SourceURL != "" {
text += "\n\n" + post.SourceURL
}
return p.c.PostTweet(ctx, text)
}
@@ -76,6 +85,151 @@ func (p xPublisher) Publish(ctx context.Context, text, sourceURL string) (string
type linkedInPublisher struct{ c *linkedin.Client }
// Publish attaches the source link as an article preview.
func (p linkedInPublisher) Publish(ctx context.Context, text, sourceURL string) (string, error) {
return p.c.PostUpdate(ctx, text, sourceURL)
func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
return p.c.PostUpdate(ctx, post.Text, post.SourceURL)
}
type redditPublisher struct {
s *Server
c *reddit.Client
}
// Publish makes a text post with the source link at the end, or, where the
// subreddit only takes links, a link post of the title and the link.
func (p redditPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
info, _ := p.s.subreddit(ctx, post.Target, false)
if info != nil && !info.AllowsText() {
if post.SourceURL == "" {
return "", fmt.Errorf("r/%s only takes link posts, and this draft has no link", post.Target)
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, URL: post.SourceURL})
}
text := post.Text
if post.SourceURL != "" && !strings.Contains(text, post.SourceURL) {
text += "\n\nSource: " + post.SourceURL
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, Text: text})
}
// --- Reddit ---
func (s *Server) redditUserAgent() string {
return reddit.UserAgent(s.Version, s.Secrets.Get(secrets.RedditUsername))
}
// redditUser is a client signed in as the user, or nil. Access tokens last
// an hour; a refused one is refreshed and saved.
func (s *Server) redditUser() *reddit.Client {
tok := s.Secrets.Get(secrets.RedditAccessToken)
if tok == "" {
return nil
}
return reddit.New(tok, s.redditUserAgent(), func(ctx context.Context) (string, error) {
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), s.Secrets.Get(secrets.RedditRefreshToken))
if err != nil {
return "", err
}
updates := map[string]string{secrets.RedditAccessToken: res.AccessToken}
if res.RefreshToken != "" {
updates[secrets.RedditRefreshToken] = res.RefreshToken
}
if err := s.Secrets.Set(updates); err != nil {
s.Log.Error("reddit: couldn't save the refreshed token", "err", err)
}
return res.AccessToken, nil
})
}
// redditReader reads subreddits: as the user if signed in, else as the
// app (with its client ID and secret), else nil.
func (s *Server) redditReader(ctx context.Context) (*reddit.Client, error) {
if c := s.redditUser(); c != nil {
return c, nil
}
id, secret := s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret)
if id == "" || secret == "" {
return nil, errors.New("add Reddit's client ID and secret under Settings → Credentials to read subreddits")
}
s.mu.Lock()
tok, exp := s.redditAppToken, s.redditAppTokenExp
s.mu.Unlock()
if tok == "" || time.Now().After(exp) {
res, err := oauth.RedditAppToken(ctx, id, secret, s.redditUserAgent())
if err != nil {
return nil, err
}
tok = res.AccessToken
s.mu.Lock()
// Reddit's app tokens last an hour; renew a little early.
s.redditAppToken, s.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
s.mu.Unlock()
}
return reddit.New(tok, s.redditUserAgent(), nil), nil
}
// subreddit returns a subreddit's rules: cached if fresh enough (or if
// fetching fails), fetched otherwise. refresh forces a fetch.
func (s *Server) subreddit(ctx context.Context, name string, refresh bool) (*reddit.Subreddit, error) {
name = reddit.CleanName(name)
cached, err := content.GetSubreddit(s.DB, name)
if err != nil {
return nil, err
}
if cached != nil && !refresh && time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
c, err := s.redditReader(ctx)
if err == nil {
var info *reddit.Subreddit
if info, err = c.SubredditInfo(ctx, name); err == nil {
if serr := content.SaveSubreddit(s.DB, info); serr != nil {
s.Log.Error("caching subreddit", "name", name, "err", serr)
}
return info, nil
}
}
if cached != nil {
return cached, nil // stale beats nothing
}
return nil, err
}
// redditHistoryTTL is how long the account's recent posts are kept in
// memory for the warnings.
const redditHistoryTTL = 10 * time.Minute
// redditHistory is the signed-in account's recent posts, or nil if they
// can't be read.
func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
user := s.Secrets.Get(secrets.RedditUsername)
c := s.redditUser()
if c == nil || user == "" {
return nil
}
s.mu.Lock()
h, at := s.redditHist, s.redditHistAt
s.mu.Unlock()
if h != nil && time.Since(at) < redditHistoryTTL {
return h
}
h, err := c.Submitted(ctx, user)
if err != nil {
s.Log.Warn("reddit: couldn't read the account's posts", "err", err)
return nil
}
if h == nil {
h = []reddit.Submission{}
}
s.mu.Lock()
s.redditHist, s.redditHistAt = h, time.Now()
s.mu.Unlock()
return h
}
// forgetRedditHistory drops the cached posts after posting.
func (s *Server) forgetRedditHistory() {
s.mu.Lock()
s.redditHist = nil
s.mu.Unlock()
}