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>
This commit is contained in:
2026-11-30 11:48:54 -07:00
co-authored by Claude Opus 5.5
parent bae468e01c
commit 5451fe6d63
33 changed files with 382 additions and 1107 deletions
-309
View File
@@ -1,309 +0,0 @@
// Package reddit talks to Reddit's API: the signed-in user, submitting
// posts, a subreddit's rules, and the account's recent posts (for the
// posting-too-often warnings).
package reddit
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Hosts. Authenticated calls go to oauth.reddit.com.
const (
apiBase = "https://oauth.reddit.com"
// TitleLimit and BodyLimit are Reddit's limits for a post.
TitleLimit = 300
BodyLimit = 40000
)
// TokenRefresher gets a new access token after a 401.
type TokenRefresher func(ctx context.Context) (string, error)
// Client calls Reddit as one user (or as the app, for reading).
type Client struct {
token string
userAgent string
refresh TokenRefresher
http *http.Client
base string // for tests
}
// New returns a client. Reddit asks every client for a unique User-Agent;
// see UserAgent.
func New(accessToken, userAgent string, refresh TokenRefresher) *Client {
return &Client{token: accessToken, userAgent: userAgent, refresh: refresh,
http: &http.Client{Timeout: 20 * time.Second}, base: apiBase}
}
// UserAgent is the User-Agent Reddit's rules ask for.
func UserAgent(version, username string) string {
ua := "web:supermarket:" + version
if username != "" {
ua += " (by /u/" + username + ")"
}
return ua
}
// ErrUnauthorized means the token was refused even after a refresh.
var ErrUnauthorized = errors.New("Reddit refused the sign-in: connect Reddit again under Settings → Social accounts")
// ErrNotFound and ErrForbidden are what Reddit answers for a subreddit or
// user that doesn't exist (or was banned), and for a private one.
var (
ErrNotFound = errors.New("Reddit said 404: no such subreddit or user")
ErrForbidden = errors.New("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it")
)
func (c *Client) do(ctx context.Context, method, path string, form url.Values, out any) error {
for attempt := 0; ; attempt++ {
var body io.Reader
if form != nil {
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("User-Agent", c.userAgent)
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
res, err := c.http.Do(req)
if err != nil {
return err
}
raw, _ := io.ReadAll(io.LimitReader(res.Body, 4<<20))
res.Body.Close()
if res.StatusCode == http.StatusUnauthorized && attempt == 0 && c.refresh != nil {
tok, err := c.refresh(ctx)
if err != nil {
return fmt.Errorf("%w (%v)", ErrUnauthorized, err)
}
c.token = tok
continue
}
switch {
case res.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case res.StatusCode == http.StatusForbidden:
return ErrForbidden
case res.StatusCode == http.StatusNotFound:
return ErrNotFound
case res.StatusCode == http.StatusTooManyRequests:
return fmt.Errorf("Reddit is rate-limiting this app; try again in a few minutes")
case res.StatusCode != http.StatusOK:
return fmt.Errorf("reddit HTTP %d: %.300s", res.StatusCode, raw)
}
if out == nil {
return nil
}
return json.Unmarshal(raw, out)
}
}
// Me returns the signed-in user's name.
func (c *Client) Me(ctx context.Context) (string, error) {
var me struct {
Name string `json:"name"`
}
if err := c.do(ctx, http.MethodGet, "/api/v1/me", nil, &me); err != nil {
return "", err
}
if me.Name == "" {
return "", errors.New("Reddit didn't say who is signed in")
}
return me.Name, nil
}
// Post is a submission.
type Post struct {
Subreddit string
Title string
Text string // a text ("self") post's body
URL string // set for a link post; then Text is ignored
}
// Submit posts to a subreddit and returns the post's URL.
func (c *Client) Submit(ctx context.Context, p Post) (string, error) {
form := url.Values{
"api_type": {"json"},
"sr": {p.Subreddit},
"title": {p.Title},
"resubmit": {"true"},
"sendreplies": {"true"},
}
if p.URL != "" {
form.Set("kind", "link")
form.Set("url", p.URL)
} else {
form.Set("kind", "self")
form.Set("text", p.Text)
}
var out struct {
JSON struct {
Errors [][]any `json:"errors"`
Data struct {
URL string `json:"url"`
} `json:"data"`
} `json:"json"`
}
if err := c.do(ctx, http.MethodPost, "/api/submit", form, &out); err != nil {
return "", err
}
if len(out.JSON.Errors) > 0 {
var msgs []string
for _, e := range out.JSON.Errors {
// Each error is [code, message, field].
if len(e) > 1 {
msgs = append(msgs, fmt.Sprint(e[1]))
} else if len(e) > 0 {
msgs = append(msgs, fmt.Sprint(e[0]))
}
}
return "", fmt.Errorf("Reddit refused the post: %s", strings.Join(msgs, "; "))
}
if out.JSON.Data.URL == "" {
return "", errors.New("Reddit accepted the post but didn't return its address")
}
return out.JSON.Data.URL, nil
}
// Rule is one of a subreddit's rules.
type Rule struct {
Name string `json:"name"`
Description string `json:"description"`
Kind string `json:"kind"` // link, comment, all
}
// Subreddit is what the app shows and tells the model about a subreddit.
type Subreddit struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"` // public description
SubmitText string `json:"submit_text"` // posting guidelines shown when posting
SubmissionType string `json:"submission_type"` // any, link, self
Type string `json:"type"` // public, restricted, private
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
Rules []Rule `json:"rules"`
FetchedAt time.Time `json:"fetched_at"`
}
// AllowsText reports whether text posts are allowed.
func (s *Subreddit) AllowsText() bool { return s.SubmissionType != "link" }
// AllowsLinks reports whether link posts are allowed.
func (s *Subreddit) AllowsLinks() bool { return s.SubmissionType != "self" }
// SubredditInfo fetches a subreddit's description, guidelines and rules.
func (c *Client) SubredditInfo(ctx context.Context, name string) (*Subreddit, error) {
name = CleanName(name)
var about struct {
Data struct {
DisplayName string `json:"display_name"`
Title string `json:"title"`
PublicDescription string `json:"public_description"`
SubmitText string `json:"submit_text"`
SubmissionType string `json:"submission_type"`
SubredditType string `json:"subreddit_type"`
Over18 bool `json:"over18"`
Subscribers int `json:"subscribers"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about", nil, &about); err != nil {
return nil, err
}
if about.Data.DisplayName == "" {
// Reddit sometimes answers a missing subreddit with an empty listing
// rather than a 404.
return nil, ErrNotFound
}
var rules struct {
Rules []struct {
ShortName string `json:"short_name"`
Description string `json:"description"`
Kind string `json:"kind"`
} `json:"rules"`
}
if err := c.do(ctx, http.MethodGet, "/r/"+url.PathEscape(name)+"/about/rules", nil, &rules); err != nil {
return nil, err
}
d := about.Data
s := &Subreddit{Name: firstNonEmpty(d.DisplayName, name), Title: d.Title, Description: d.PublicDescription,
SubmitText: d.SubmitText, SubmissionType: firstNonEmpty(d.SubmissionType, "any"), Type: d.SubredditType,
Over18: d.Over18, Subscribers: d.Subscribers, FetchedAt: time.Now().UTC()}
for _, r := range rules.Rules {
s.Rules = append(s.Rules, Rule{Name: r.ShortName, Description: r.Description, Kind: r.Kind})
}
return s, nil
}
// Submission is one of the account's past posts.
type Submission struct {
Subreddit string
Title string
URL string // the link, for link posts
Text string
IsSelf bool
Created time.Time
}
// Submitted returns the user's recent posts, newest first (up to 100).
func (c *Client) Submitted(ctx context.Context, username string) ([]Submission, error) {
var out struct {
Data struct {
Children []struct {
Data struct {
Subreddit string `json:"subreddit"`
Title string `json:"title"`
URL string `json:"url"`
Selftext string `json:"selftext"`
IsSelf bool `json:"is_self"`
CreatedUTC float64 `json:"created_utc"`
} `json:"data"`
} `json:"children"`
} `json:"data"`
}
path := "/user/" + url.PathEscape(username) + "/submitted?limit=100&sort=new&raw_json=1"
if err := c.do(ctx, http.MethodGet, path, nil, &out); err != nil {
return nil, err
}
var subs []Submission
for _, ch := range out.Data.Children {
d := ch.Data
subs = append(subs, Submission{Subreddit: d.Subreddit, Title: d.Title, URL: d.URL, Text: d.Selftext,
IsSelf: d.IsSelf, Created: time.Unix(int64(d.CreatedUTC), 0).UTC()})
}
return subs, nil
}
// CleanName turns "r/selfhosted", "/r/selfhosted/" or a subreddit URL into
// "selfhosted".
func CleanName(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return s
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if v != "" {
return v
}
}
return ""
}
-85
View File
@@ -1,85 +0,0 @@
package reddit
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestClient(t *testing.T) {
var submitted string
refreshed := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-Agent") != "web:supermarket:test (by /u/pat)" {
t.Errorf("User-Agent = %q", r.Header.Get("User-Agent"))
}
if r.Header.Get("Authorization") == "Bearer old" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/api/v1/me":
w.Write([]byte(`{"name":"pat"}`))
case "/api/submit":
r.ParseForm()
submitted = r.PostForm.Encode()
if r.PostForm.Get("sr") == "strict" {
w.Write([]byte(`{"json":{"errors":[["SUBREDDIT_NOTALLOWED","you aren't allowed to post there.","sr"]]}}`))
return
}
w.Write([]byte(`{"json":{"errors":[],"data":{"url":"https://www.reddit.com/r/selfhosted/comments/abc/hi/"}}}`))
case "/r/selfhosted/about":
w.Write([]byte(`{"data":{"display_name":"selfhosted","public_description":"Self-hosting","submit_text":"No spam.","submission_type":"self","subreddit_type":"public","subscribers":500000}}`))
case "/r/selfhosted/about/rules":
w.Write([]byte(`{"rules":[{"short_name":"No self-promotion","description":"Limit it to 10%.","kind":"link"}]}`))
case "/user/pat/submitted":
w.Write([]byte(`{"data":{"children":[{"data":{"subreddit":"selfhosted","title":"T","url":"https://acme.example/x","is_self":false,"created_utc":1794000000}}]}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
c := New("old", UserAgent("test", "pat"), func(context.Context) (string, error) {
refreshed++
return "new", nil
})
c.base = srv.URL
ctx := context.Background()
if name, err := c.Me(ctx); err != nil || name != "pat" || refreshed != 1 {
t.Fatalf("Me = %q, %v (refreshed %d)", name, err, refreshed)
}
u, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", Text: "Body"})
if err != nil || !strings.Contains(u, "/comments/abc/") || !strings.Contains(submitted, "kind=self") || !strings.Contains(submitted, "text=Body") {
t.Errorf("Submit = %q, %v; sent %s", u, err, submitted)
}
if _, err := c.Submit(ctx, Post{Subreddit: "selfhosted", Title: "Hi", URL: "https://acme.example"}); err != nil || !strings.Contains(submitted, "kind=link") {
t.Errorf("link post sent %s (%v)", submitted, err)
}
if _, err := c.Submit(ctx, Post{Subreddit: "strict", Title: "Hi", Text: "x"}); err == nil || !strings.Contains(err.Error(), "aren't allowed") {
t.Errorf("refused submit: %v", err)
}
s, err := c.SubredditInfo(ctx, "/r/selfhosted/")
if err != nil || s.SubmitText != "No spam." || len(s.Rules) != 1 || s.Rules[0].Name != "No self-promotion" || s.AllowsLinks() || !s.AllowsText() {
t.Errorf("SubredditInfo = %+v, %v", s, err)
}
subs, err := c.Submitted(ctx, "pat")
if err != nil || len(subs) != 1 || subs[0].Subreddit != "selfhosted" || subs[0].Created.Year() != 2026 {
t.Errorf("Submitted = %+v, %v", subs, err)
}
if _, err := c.SubredditInfo(ctx, "nope"); err == nil {
t.Error("expected 404")
}
}
func TestCleanName(t *testing.T) {
for in, want := range map[string]string{"selfhosted": "selfhosted", "r/selfhosted": "selfhosted", "/r/selfhosted/": "selfhosted",
"https://www.reddit.com/r/homelab/top?t=week": "homelab", " r/Go ": "Go"} {
if got := CleanName(in); got != want {
t.Errorf("CleanName(%q) = %q, want %q", in, got, want)
}
}
}
+13 -3
View File
@@ -293,6 +293,10 @@ func GetDraft(d *db.DB, id int64) (*Draft, error) {
// 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)
@@ -370,9 +374,15 @@ func Schedule(d *db.DB, id int64, at time.Time) error {
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)
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.
+9 -18
View File
@@ -8,7 +8,6 @@ import (
"strings"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/inventory"
"supermarket/internal/profile"
@@ -24,7 +23,7 @@ type Request struct {
// Reddit: the subreddit to write for, and what's known about it (nil
// if its rules couldn't be read).
Subreddit string
SubredditInfo *reddit.Subreddit
SubredditInfo *Subreddit // the rules pasted for it; nil if none
// Signal, if set, is the buying signal the posts are written for.
Signal *signals.Signal
}
@@ -133,7 +132,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
title = string(r[:RedditTitleLimit-1]) + "…"
}
drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, SignalID: req.signalID(),
Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body),
Title: title, Target: CleanSubreddit(req.Subreddit), Content: strings.TrimSpace(rp.Body),
SourceURL: src, ItemIDs: ids, Status: StatusDraft})
continue
}
@@ -314,7 +313,7 @@ func oneLine(s string) string {
// punishes marketing, so the rules are stricter than for other channels.
func redditInstructions(req Request) string {
var b strings.Builder
sub := reddit.CleanName(req.Subreddit)
sub := CleanSubreddit(req.Subreddit)
fmt.Fprintf(&b, "- reddit: an object with a title (at most %d characters) and a body, for r/%s. "+
"Write as a member of the community who works at %s, and say so plainly in the body (\"I work at %s\"). "+
"Lead with what's useful or interesting to this community, not with the company. No hashtags, no emoji, no marketing language, "+
@@ -326,20 +325,12 @@ func redditInstructions(req Request) string {
"about it, and invite questions and feedback.\n")
}
if info := req.SubredditInfo; info != nil {
b.WriteString("<subreddit>\n")
if info.Description != "" {
fmt.Fprintf(&b, "About r/%s: %s\n", sub, oneLine(info.Description))
}
if info.SubmitText != "" {
fmt.Fprintf(&b, "Posting guidelines: %s\n", oneLine(truncateRunes(info.SubmitText, 1500)))
}
for i, r := range info.Rules {
if r.Kind == "comment" {
continue
}
fmt.Fprintf(&b, "Rule %d: %s. %s\n", i+1, r.Name, oneLine(truncateRunes(r.Description, 400)))
}
b.WriteString("</subreddit>\n")
b.WriteString("<subreddit_rules>\n")
b.WriteString(truncateRunes(info.Rules, 6000))
b.WriteString("\n</subreddit_rules>\n")
} else {
fmt.Fprintf(&b, " r/%s's rules weren't given: follow Reddit's usual norms (no self-promotion beyond one post in ten, no spam), "+
"and keep the post useful even if promotion turns out to be forbidden.\n", sub)
}
return b.String()
}
+3
View File
@@ -60,6 +60,9 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
if !dr.Editable() && dr.Status != StatusScheduled {
return dr, ErrBusy
}
if dr.Channel == ChannelReddit {
return dr, ErrByHand
}
pub, as, err := pubs.For(dr)
if err != nil {
return dr, err
+91 -103
View File
@@ -9,153 +9,141 @@ import (
"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
// Reddit posts are always posted by hand: Reddit's API isn't open to
// apps like this one. Supermarket writes the post, opens the subreddit's
// submit page filled in, and records the post once the user marks it as
// posted. A subreddit's rules can't be read either, so the user pastes
// them; drafting and the warnings use what was pasted.
// 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)
// Subreddit is what the user told Supermarket about a subreddit: its rules,
// as pasted from Reddit.
type Subreddit struct {
Name string `json:"name"`
Rules string `json:"pasted_rules"`
SavedAt time.Time `json:"-"`
}
// MaxRules is the most rules text kept for a subreddit.
const MaxRules = 20000
// CleanSubreddit turns "r/selfhosted", "/r/selfhosted/" or a subreddit URL
// into "selfhosted".
func CleanSubreddit(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return s
}
// RulesURL is where Reddit shows a subreddit's rules.
func RulesURL(name string) string {
return "https://www.reddit.com/r/" + CleanSubreddit(name) + "/about/rules"
}
// GetSubreddit returns the subreddit's pasted rules, or nil if none were
// pasted. (Rows from before, read through Reddit's API, have none.)
func GetSubreddit(d *db.DB, name string) (*Subreddit, error) {
var raw, at string
err := d.QueryRow(`SELECT data, fetched_at FROM subreddits WHERE name = ?`, CleanSubreddit(name)).Scan(&raw, &at)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
var s reddit.Subreddit
var s Subreddit
if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, err
}
if strings.TrimSpace(s.Rules) == "" {
return nil, nil
}
s.SavedAt = parseTime(at)
return &s, nil
}
// SaveSubreddit caches a subreddit's rules.
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error {
raw, err := json.Marshal(s)
// SaveRules keeps the rules pasted for a subreddit. Empty rules forget them.
func SaveRules(d *db.DB, name, rules string, now time.Time) error {
name = CleanSubreddit(name)
if name == "" {
return errors.New("no subreddit")
}
rules = strings.TrimSpace(strings.ReplaceAll(rules, "\r\n", "\n"))
if len([]rune(rules)) > MaxRules {
return fmt.Errorf("that's more than %d characters: paste just the rules", MaxRules)
}
if rules == "" {
_, err := d.Exec(`DELETE FROM subreddits WHERE name = ?`, name)
return err
}
raw, err := json.Marshal(Subreddit{Name: name, Rules: rules})
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))
name, string(raw), formatTime(now))
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
)
// Posting to the same subreddit more than about weekly reads as spam.
const sameSubWindow = 7 * 24 * time.Hour
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`)
// RedditPost is a Reddit post Supermarket knows of: one the user marked as
// posted (or, before, one it published).
type RedditPost struct {
Subreddit string
Created time.Time
}
// 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
Promo bool // it promotes the company's own product
Info *reddit.Subreddit // nil if the rules couldn't be read
History []reddit.Submission // the account's recent posts; nil if unknown
// Recorded is the Reddit posts Supermarket knows of (published or
// marked as posted), used for the same-subreddit check when History
// is unknown. They're not the whole account, so they don't count for
// the own-link share or the new-account warning.
Recorded []reddit.Submission
Own func(url string) bool
Target string
Promo bool // it promotes the company's own product
Info *Subreddit // nil if no rules were pasted
Recorded []RedditPost
Now time.Time
}
// RedditWarnings lists reasons to think twice before posting. They never
// block publishing: the user decides.
// block posting: the user decides.
func RedditWarnings(c RedditCheck) []string {
var w []string
sub := "r/" + c.Target
if c.Promo {
w = append(w, "This promotes your own work. Many subreddits allow that only in designated threads, or not at all: check the rules.")
}
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.Info != nil {
for _, line := range strings.Split(c.Info.Rules, "\n") {
line = strings.TrimSpace(line)
if promoRule.MatchString(line) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, truncateRunes(line, 200)))
}
}
}
if c.History == nil {
var inSub []time.Time
for _, s := range c.Recorded {
if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < sameSubWindow {
inSub = append(inSub, s.Created)
}
}
if len(inSub) > 0 {
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week through Supermarket, last on %s. Most communities expect less.",
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
}
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 {
for _, s := range c.Recorded {
if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < 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.",
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week through Supermarket, 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 ""
@@ -163,24 +151,24 @@ func plural(n int) string {
return "s"
}
// RecordedRedditPosts are the Reddit posts Supermarket published, or the
// user marked as posted, since then, newest first.
func RecordedRedditPosts(d *db.DB, since time.Time) ([]reddit.Submission, error) {
rows, err := d.Query(`SELECT target, title, content, source_url, published_at FROM drafts
// RecordedRedditPosts are the Reddit posts marked as posted (or published)
// since then, newest first.
func RecordedRedditPosts(d *db.DB, since time.Time) ([]RedditPost, error) {
rows, err := d.Query(`SELECT target, published_at FROM drafts
WHERE channel = ? AND status = ? AND published_at >= ? ORDER BY published_at DESC`,
ChannelReddit, StatusPublished, formatTime(since))
if err != nil {
return nil, err
}
defer rows.Close()
var out []reddit.Submission
var out []RedditPost
for rows.Next() {
var s reddit.Submission
var s RedditPost
var at string
if err := rows.Scan(&s.Subreddit, &s.Title, &s.Text, &s.URL, &at); err != nil {
if err := rows.Scan(&s.Subreddit, &at); err != nil {
return nil, err
}
s.IsSelf, s.Created = true, parseTime(at)
s.Created = parseTime(at)
out = append(out, s)
}
return out, rows.Err()
+58 -38
View File
@@ -2,20 +2,18 @@ package content
import (
"context"
"errors"
"strings"
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/inventory"
"supermarket/internal/utm"
)
func TestGenerateReddit(t *testing.T) {
entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner}
items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}}
info := &reddit.Subreddit{Name: "selfhosted", Description: "Self-hosting", SubmitText: "Flair your post.",
Rules: []reddit.Rule{{Name: "No spam", Description: "10% rule", Kind: "link"}, {Name: "Be civil", Kind: "comment"}}}
info := &Subreddit{Name: "selfhosted", Rules: "1. No spam: the 10% rule\n2. Flair your post."}
f := &fakeAI{replies: []string{`{"x": "Short", "reddit": {"title": " Jitsi 3 is out ", "body": "I work at Acme. Details."}}`}}
drafts, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info})
@@ -27,13 +25,19 @@ func TestGenerateReddit(t *testing.T) {
t.Fatalf("reddit draft = %+v", r)
}
prompt := f.reqs[0].Prompt
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "Flair your post.", "Rule 1: No spam"} {
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "2. Flair your post.", "1. No spam: the 10% rule"} {
if !strings.Contains(prompt, want) {
t.Errorf("prompt lacks %q", want)
}
}
if strings.Contains(prompt, "Be civil") {
t.Error("comment-only rules needn't go in the prompt")
// Without rules, the model is told they weren't given.
f = &fakeAI{replies: []string{`{"reddit": {"title": "T", "body": "B"}}`}}
if _, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelReddit}, Subreddit: "selfhosted"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(f.reqs[0].Prompt, "rules weren't given") {
t.Error("no note about missing rules")
}
props := f.reqs[0].Schema["properties"].(map[string]any)
if props["reddit"].(map[string]any)["type"] != "object" {
@@ -71,33 +75,56 @@ func TestRedditDraftsAndCache(t *testing.T) {
t.Errorf("problem = %q", got.Problem())
}
// Reddit drafts are posted by hand: never published or scheduled.
pub := &fakePub{}
if _, err := Publish(context.Background(), d, ChannelPublishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
if _, err := Publish(context.Background(), d, ChannelPublishers{ChannelReddit: pub}, nil, dr.ID); !errors.Is(err, ErrByHand) || len(pub.calls) != 0 {
t.Errorf("publish: %v, %d calls", err, len(pub.calls))
}
if err := Schedule(d, dr.ID, time.Now().Add(time.Hour)); !errors.Is(err, ErrByHand) {
t.Errorf("schedule: %v", err)
}
if err := MarkPosted(d, dr.ID, "https://www.reddit.com/r/selfhosted/comments/abc"); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") ||
!strings.Contains(pub.calls[0], "utm_source=reddit") {
t.Errorf("published %q", pub.calls[0])
if rec, _ := RecordedRedditPosts(d, time.Now().Add(-time.Hour)); len(rec) != 1 || rec[0].Subreddit != "selfhosted" {
t.Errorf("recorded = %+v", rec)
}
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
t.Fatalf("empty cache: %v %v", s, err)
t.Fatalf("no rules yet: %v %v", s, err)
}
at := time.Now().UTC().Truncate(time.Second)
if err := SaveSubreddit(d, &reddit.Subreddit{Name: "selfhosted", SubmissionType: "self", Rules: []reddit.Rule{{Name: "R"}}, FetchedAt: at}); err != nil {
// A row from before, read through Reddit's API, counts as no rules.
if _, err := d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES ('selfhosted', '{"name":"selfhosted","rules":[{"name":"R"}]}', '')`); err != nil {
t.Fatal(err)
}
s, err := GetSubreddit(d, "r/SelfHosted")
if err != nil || s == nil || len(s.Rules) != 1 || !s.FetchedAt.Equal(at) || s.AllowsLinks() {
t.Errorf("cached = %+v, %v", s, err)
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
t.Fatalf("old row: %v %v", s, err)
}
at := time.Now().UTC().Truncate(time.Second)
if err := SaveRules(d, "r/selfhosted", " 1. Be nice\r\n2. No ads ", at); err != nil {
t.Fatal(err)
}
s, err := GetSubreddit(d, "https://www.reddit.com/r/selfhosted/about/rules")
if err != nil || s == nil || s.Rules != "1. Be nice\n2. No ads" || !s.SavedAt.Equal(at) {
t.Errorf("saved = %+v, %v", s, err)
}
if err := SaveRules(d, "selfhosted", strings.Repeat("x", MaxRules+1), at); err == nil {
t.Error("too long accepted")
}
if err := SaveRules(d, "selfhosted", " ", at); err != nil {
t.Fatal(err)
}
if s, _ := GetSubreddit(d, "selfhosted"); s != nil {
t.Error("emptied rules kept")
}
if RulesURL("r/selfhosted") != "https://www.reddit.com/r/selfhosted/about/rules" {
t.Error(RulesURL("r/selfhosted"))
}
}
func TestRedditWarnings(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
own := utm.NewTagger([]string{"acme.example"}).Own
info := &reddit.Subreddit{Name: "selfhosted", SubmissionType: "link", Type: "restricted",
Rules: []reddit.Rule{{Name: "No self-promotion"}, {Name: "Be nice"}}}
info := &Subreddit{Name: "selfhosted", Rules: "1. No self-promotion\n2. Be nice"}
has := func(ws []string, sub string) bool {
for _, w := range ws {
@@ -109,29 +136,22 @@ func TestRedditWarnings(t *testing.T) {
}
w := RedditWarnings(RedditCheck{Target: "selfhosted", Info: info, Now: now})
if !has(w, "restricted") || !has(w, "has no link") || !has(w, "“No self-promotion”") || has(w, "Be nice") || has(w, "past week") {
if !has(w, "“1. No self-promotion”") || has(w, "Be nice") || has(w, "past week") {
t.Errorf("rules warnings = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Now: now}); !has(w, "Couldn't read r/x's rules") {
t.Errorf("no info = %q", w)
if w := RedditWarnings(RedditCheck{Target: "x", Promo: true, Now: now}); !has(w, "promotes your own work") {
t.Errorf("promo = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Info: &reddit.Subreddit{}, History: []reddit.Submission{}, Now: now}); !has(w, "hasn't posted before") {
t.Errorf("new account = %q", w)
recorded := []RedditPost{
{Subreddit: "SelfHosted", Created: now.Add(-2 * 24 * time.Hour)},
{Subreddit: "selfhosted", Created: now.Add(-20 * 24 * time.Hour)},
{Subreddit: "homelab", Created: now.Add(-1 * 24 * time.Hour)},
}
history := []reddit.Submission{
{Subreddit: "SelfHosted", URL: "https://acme.example/1", Created: now.Add(-2 * 24 * time.Hour)},
{Subreddit: "homelab", Text: "see https://acme.example/2)", IsSelf: true, Created: now.Add(-10 * 24 * time.Hour)},
{Subreddit: "golang", Created: now.Add(-20 * 24 * time.Hour)},
{Subreddit: "selfhosted", URL: "https://acme.example/old", Created: now.Add(-60 * 24 * time.Hour)},
w = RedditWarnings(RedditCheck{Target: "selfhosted", Recorded: recorded, Now: now})
if !has(w, "posted in r/selfhosted 1 time in the past week") {
t.Errorf("recorded warnings = %q", w)
}
w = RedditWarnings(RedditCheck{Target: "selfhosted", Info: &reddit.Subreddit{}, History: history, Own: own, OwnLink: true, HasLink: true, Now: now})
if !has(w, "posted in r/selfhosted 1 time in the past week") || !has(w, "3 of your 4 posts") {
t.Errorf("history warnings = %q", w)
}
// Without a link of our own, the share isn't the issue.
w = RedditWarnings(RedditCheck{Target: "golang", Info: &reddit.Subreddit{}, History: history, Own: own, Now: now})
if len(w) != 0 {
if w := RedditWarnings(RedditCheck{Target: "golang", Recorded: recorded, Now: now}); len(w) != 0 {
t.Errorf("clean post = %q", w)
}
}
+28 -44
View File
@@ -2,12 +2,11 @@ package inventory
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile"
"supermarket/internal/site"
)
@@ -18,17 +17,12 @@ const maxFeeds = 3
// maxSubreddits is how many suggested subreddits Fill puts in the box.
const maxSubreddits = 5
// SubredditCheck looks a subreddit up on Reddit. It returns reddit.ErrNotFound
// or reddit.ErrForbidden for one that doesn't exist or is private.
type SubredditCheck func(ctx context.Context, name string) (*reddit.Subreddit, error)
// Suggestion is a subreddit the AI suggested, and what Reddit said about it.
// Suggestion is a subreddit the AI suggested. Reddit can't be asked
// whether it exists, so the user looks before posting there.
type Suggestion struct {
Name string
Why string // the model's reason
Info *reddit.Subreddit // nil if not checked
Kept bool // put in the Subreddits box
Problem string // why it was left out, or why it's unchecked
Name string
Why string // the model's reason
Kept bool // put in the Subreddits box; false: more than enough already
}
// FillResult says what Fill did.
@@ -47,7 +41,7 @@ type FillResult struct {
// there is one), keywords and hashtags. If the site links to no subreddit,
// the model suggests some, and check (if not nil) drops the ones that don't
// exist or that can't be posted to; models invent believable names.
func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile, check SubredditCheck) (*FillResult, error) {
func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours *profile.Profile) (*FillResult, error) {
res := &FillResult{}
st, err := site.Read(ctx, siteURL, "Supermarket/1 (inventory draft)")
if err != nil {
@@ -125,16 +119,14 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours
var keep []string
seen := map[string]bool{}
for _, sub := range d.Subreddits {
name := reddit.CleanName(sub.Name)
name := cleanSubreddit(sub.Name)
if name == "" || seen[strings.ToLower(name)] {
continue
}
seen[strings.ToLower(name)] = true
sg := checkSubreddit(ctx, check, name, sub.Why)
if sg.Kept && len(keep) < maxSubreddits {
keep = append(keep, sg.Name)
} else if sg.Kept {
sg.Kept, sg.Problem = false, "more than enough already"
sg := Suggestion{Name: name, Why: strings.TrimSpace(sub.Why), Kept: len(keep) < maxSubreddits}
if sg.Kept {
keep = append(keep, name)
}
res.Suggestions = append(res.Suggestions, sg)
}
@@ -143,34 +135,26 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours
return res, nil
}
// checkSubreddit asks Reddit about a suggested subreddit. One Reddit can't
// be asked about (no keys, rate limit) is kept, marked unchecked.
func checkSubreddit(ctx context.Context, check SubredditCheck, name, why string) Suggestion {
sg := Suggestion{Name: name, Why: strings.TrimSpace(why), Kept: true}
if check == nil {
sg.Problem = "not checked"
return sg
// cleanSubreddit turns "r/selfhosted" or a subreddit URL into
// "selfhosted", and drops what can't be a subreddit's name.
func cleanSubreddit(s string) string {
s = strings.TrimSpace(s)
if i := strings.Index(s, "/r/"); i >= 0 {
s = s[i+3:]
}
info, err := check(ctx, name)
switch {
case errors.Is(err, reddit.ErrNotFound):
sg.Kept, sg.Problem = false, "doesn't exist, or was banned"
case errors.Is(err, reddit.ErrForbidden):
sg.Kept, sg.Problem = false, "private"
case err != nil:
sg.Problem = "not checked: " + err.Error()
case info.Type == "private":
sg.Kept, sg.Problem = false, "private"
case info.Over18:
sg.Kept, sg.Problem = false, "marked 18+"
case info.Type == "restricted" || info.Type == "archived":
sg.Kept, sg.Problem = false, info.Type+": only approved accounts can post"
default:
sg.Name, sg.Info = info.Name, info // Reddit's spelling of the name
s = strings.TrimPrefix(s, "r/")
if i := strings.IndexAny(s, "/?#"); i >= 0 {
s = s[:i]
}
return sg
if !subredditName.MatchString(s) {
return ""
}
return s
}
// subredditName is what Reddit allows in a subreddit's name.
var subredditName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_]{1,20}$`)
const fillSystem = `You fill in an entry in a company's marketing inventory: another company or project it posts about, as a partner, a competitor, or one to watch. The marketing team reviews and corrects what you write.
Rules:
@@ -185,7 +169,7 @@ Rules:
Without a company profile, leave talking_points empty.
- keywords: up to eight phrases they own or compete on.
- hashtags: up to five, only ones their pages use or that name them or their product.
- subreddits: up to eight subreddits where talking about them would reach the company's audience: for a partner, where their users and the company's customers talk; for a competitor, where people compare or ask about tools like theirs; for one to watch, where their field is discussed. Names without r/, real subreddits you're confident exist, active and on topic; general ones (like technology) only if nothing narrower fits. why: one short phrase on who is there. They'll be checked against Reddit before use.`
- subreddits: up to eight subreddits where talking about them would reach the company's audience: for a partner, where their users and the company's customers talk; for a competitor, where people compare or ask about tools like theirs; for one to watch, where their field is discussed. Names without r/, real subreddits you're confident exist, active and on topic; general ones (like technology) only if nothing narrower fits. why: one short phrase on who is there. The team looks at each on Reddit before posting there.`
func fillPrompt(e *Entry, ours *profile.Profile, st *site.Site) string {
var b strings.Builder
+9 -38
View File
@@ -3,7 +3,6 @@ package inventory
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -11,7 +10,6 @@ import (
"testing"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile"
)
@@ -52,7 +50,7 @@ func TestFillKeepsWhatWasTyped(t *testing.T) {
}}
e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"}
ours := &profile.Profile{Name: "Acme", Description: "Self-hosted widgets."}
res, err := Fill(context.Background(), fake, e, srv.URL, ours, nil)
res, err := Fill(context.Background(), fake, e, srv.URL, ours)
if err != nil {
t.Fatal(err)
}
@@ -83,7 +81,7 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) {
fake := &fakeAI{}
e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t",
Keywords: []string{"k"}, Hashtags: []string{"#h"}, Subreddits: []string{"selfhosted"}}
if _, err := Fill(context.Background(), fake, e, srv.URL, nil, nil); err != nil {
if _, err := Fill(context.Background(), fake, e, srv.URL, nil); err != nil {
t.Fatal(err)
}
if fake.calls != 0 {
@@ -94,58 +92,31 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) {
}
}
func TestFillChecksSuggestedSubreddits(t *testing.T) {
func TestFillSuggestsSubreddits(t *testing.T) {
srv := rivalSite(t)
fake := &fakeAI{reply: map[string]any{
"name": "", "description": "", "talking_points": "", "keywords": []string{}, "hashtags": []string{},
"subreddits": []map[string]string{
{"name": "r/selfhosted", "why": "self-hosters"},
{"name": "SelfHosted", "why": "again"},
{"name": "madeupwidgets", "why": "invented"},
{"name": "secretclub", "why": "private"},
{"name": "announcements", "why": "restricted"},
{"name": "homelab", "why": "home servers"},
{"name": "slowreddit", "why": "rate limited"},
{"name": "not a name!", "why": "junk"},
{"name": "https://www.reddit.com/r/homelab/", "why": "home servers"},
{"name": "one", "why": ""}, {"name": "two", "why": ""}, {"name": "three", "why": ""}, {"name": "four", "why": ""},
},
}}
check := func(_ context.Context, name string) (*reddit.Subreddit, error) {
switch name {
case "selfhosted":
return &reddit.Subreddit{Name: "selfhosted", Type: "public", Subscribers: 500000}, nil
case "homelab":
return &reddit.Subreddit{Name: "homelab", Type: "public"}, nil
case "secretclub":
return nil, reddit.ErrForbidden
case "announcements":
return &reddit.Subreddit{Name: "announcements", Type: "restricted"}, nil
case "slowreddit":
return nil, errors.New("rate limited")
}
return nil, reddit.ErrNotFound
}
e := &Entry{Name: "Rival", Relationship: Partner}
res, err := Fill(context.Background(), fake, e, srv.URL, nil, check)
res, err := Fill(context.Background(), fake, e, srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if got := strings.Join(e.Subreddits, ","); got != "selfhosted,homelab,slowreddit" {
if got := strings.Join(e.Subreddits, ","); got != "selfhosted,homelab,one,two,three" {
t.Errorf("subreddits = %q", got)
}
var notes []string
for _, sg := range res.Suggestions {
notes = append(notes, fmt.Sprintf("%s:%v", sg.Name, sg.Kept))
}
if got := strings.Join(notes, " "); got != "selfhosted:true madeupwidgets:false secretclub:false announcements:false homelab:true slowreddit:true" {
if got := strings.Join(notes, " "); got != "selfhosted:true homelab:true one:true two:true three:true four:false" {
t.Errorf("suggestions = %s", got)
}
if res.Suggestions[5].Problem == "" || res.Suggestions[0].Info == nil {
t.Errorf("unchecked one should say so, checked one should carry its info: %+v", res.Suggestions)
}
// Without a check, suggestions are kept, marked unchecked.
e = &Entry{Name: "Rival", Relationship: Partner}
res, _ = Fill(context.Background(), fake, e, srv.URL, nil, nil)
if len(e.Subreddits) != 5 || !strings.Contains(res.Suggestions[0].Problem, "not checked") {
t.Errorf("unchecked: %q %+v", e.Subreddits, res.Suggestions)
}
}
+1 -64
View File
@@ -1,5 +1,5 @@
// Package oauth runs the OAuth 2.0 authorization-code flows for X,
// LinkedIn, Reddit and Google. The web app sends the browser to AuthURL, and its callback
// LinkedIn and Google. The web app sends the browser to AuthURL, and its callback
// handler calls Exchange with the code the provider sends back.
package oauth
@@ -161,69 +161,6 @@ func LinkedInExchange(ctx context.Context, clientID, clientSecret, code string,
return tokenResponse(req)
}
// --- Reddit ---
const (
redditAuthURL = "https://www.reddit.com/api/v1/authorize"
redditTokenURL = "https://www.reddit.com/api/v1/access_token"
// identity: who signed in; submit: post; read: subreddit rules and the
// account's own posts; history: the account's posts for the warnings.
redditScopes = "identity submit read history"
)
// RedditStart begins Reddit's authorization-code flow. duration=permanent
// returns a refresh token: access tokens last an hour.
func RedditStart(clientID, redirectURI string) (string, *Pending, error) {
state, err := randomString()
if err != nil {
return "", nil, err
}
params := url.Values{
"client_id": {clientID},
"response_type": {"code"},
"state": {state},
"redirect_uri": {redirectURI},
"duration": {"permanent"},
"scope": {redditScopes},
}
p := &Pending{Provider: "reddit", State: state, RedirectURI: redirectURI, Started: time.Now()}
return redditAuthURL + "?" + params.Encode(), p, nil
}
// RedditExchange swaps the callback's code for tokens.
func RedditExchange(ctx context.Context, clientID, clientSecret, userAgent, code string, p *Pending) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {p.RedirectURI},
})
}
// RefreshReddit gets a new access token. Reddit keeps the refresh token.
func RefreshReddit(ctx context.Context, clientID, clientSecret, userAgent, refreshToken string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
})
}
// RedditAppToken gets an app-only token, for reading subreddits' rules
// before anyone has signed in.
func RedditAppToken(ctx context.Context, clientID, clientSecret, userAgent string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{"grant_type": {"client_credentials"}})
}
func redditToken(ctx context.Context, clientID, clientSecret, userAgent string, data url.Values) (*Result, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, redditTokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", userAgent)
req.SetBasicAuth(clientID, clientSecret)
return tokenResponse(req)
}
// --- shared ---
func tokenResponse(req *http.Request) (*Result, error) {
+2 -3
View File
@@ -20,7 +20,7 @@ const (
X = "x"
LinkedIn = "linkedin" // a member, posting as themselves
LinkedInPage = "linkedin_page" // a company page
Reddit = "reddit"
Reddit = "reddit" // only from before: Reddit is now posted to by hand
)
// NetworkName is a network as people say it.
@@ -109,7 +109,7 @@ func scan(row interface{ Scan(...any) error }) (*Account, error) {
// Save signs an account in: a new one, or, for the same network, owner and
// external ID, the existing one with new tokens. refresh may be "".
func Save(d *db.DB, sec *secrets.Store, a *Account, access, refresh string, now time.Time) error {
if a.Network != X && a.Network != LinkedIn && a.Network != LinkedInPage && a.Network != Reddit {
if a.Network != X && a.Network != LinkedIn && a.Network != LinkedInPage {
return fmt.Errorf("no network %q", a.Network)
}
var id int64
@@ -283,7 +283,6 @@ func Adopt(d *db.DB, sec *secrets.Store, names func(network string) (name, exter
{X, secrets.XAccessToken, secrets.XRefreshToken, ""},
{LinkedIn, secrets.LinkedInAccessToken, "", ""},
{LinkedInPage, secrets.LinkedInPageAccessToken, "", ""},
{Reddit, secrets.RedditAccessToken, secrets.RedditRefreshToken, ""},
}
n := 0
for _, o := range olds {
+1 -1
View File
@@ -92,7 +92,7 @@ func TestAccounts(t *testing.T) {
func TestAdopt(t *testing.T) {
d, sec := open(t)
sec.Set(map[string]string{secrets.XAccessToken: "xt", secrets.XRefreshToken: "xr", secrets.RedditAccessToken: "rt"})
sec.Set(map[string]string{secrets.XAccessToken: "xt", secrets.XRefreshToken: "xr", secrets.LinkedInAccessToken: "lt"})
exp := time.Now().Add(time.Hour)
n, err := Adopt(d, sec, func(network string) (string, string, time.Time) {
return "n-" + network, "e-" + network, exp
-6
View File
@@ -57,12 +57,6 @@ const (
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
RedditClientID = "reddit.client_id"
RedditClientSecret = "reddit.client_secret"
RedditAccessToken = "reddit.access_token"
RedditRefreshToken = "reddit.refresh_token"
RedditUsername = "reddit.username"
)
// Store is the secrets: a file, or the database. It is safe for
-3
View File
@@ -93,9 +93,6 @@ func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer
if s.Secrets.Has(secrets.LinkedInClientID) && s.Secrets.Has(secrets.LinkedInClientSecret) {
d.Connectable = append(d.Connectable, grant{"linkedin", "LinkedIn"})
}
if s.Secrets.Has(secrets.RedditClientID) && s.Secrets.Has(secrets.RedditClientSecret) {
d.Connectable = append(d.Connectable, grant{"reddit", "Reddit"})
}
}
for _, ss := range list {
d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID})
+1 -1
View File
@@ -128,7 +128,7 @@ type draftArgs struct {
Text string `json:"text" jsonschema:"the post; within the channel's limit (X: 280 characters, counting the source link as 23)"`
Title string `json:"title,omitempty" jsonschema:"Reddit only: the post's title"`
Subreddit string `json:"subreddit,omitempty" jsonschema:"Reddit only: where it goes, without r/"`
SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card)"`
SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card, on Reddit at the end as \"Source: …\")"`
Entry string `json:"entry,omitempty" jsonschema:"the Market entry it's about, or own; empty for none"`
SignalID int64 `json:"signal_id,omitempty" jsonschema:"the buying signal it's written for (signals_list), so its links count for it"`
ItemIDs []string `json:"item_ids,omitempty" jsonschema:"the fetched items it's written from (content_items), marked as used"`
-141
View File
@@ -2,19 +2,15 @@ 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"
"supermarket/internal/content"
"supermarket/internal/fetcher"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
"supermarket/internal/site"
)
@@ -85,140 +81,3 @@ func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (stri
link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)")
return c.PostUpdate(ctx, post.Text, link)
}
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 {
name := ""
if a := s.companyReddit(); a != nil {
name = a.External
}
return reddit.UserAgent(s.Version, name)
}
// redditUser is a client signed in as the company's Reddit account, or nil.
func (s *Server) redditUser() *reddit.Client {
a := s.companyReddit()
if a == nil {
return nil
}
return s.redditClient(a)
}
// 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 → Social accounts to read subreddits")
}
tc := s.cache()
tc.mu.Lock()
tok, exp := tc.redditAppToken, tc.redditAppTokenExp
tc.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
tc.mu.Lock()
// Reddit's app tokens last an hour; renew a little early.
tc.redditAppToken, tc.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
tc.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 {
a := s.companyReddit()
if a == nil || a.External == "" {
return nil
}
user, c := a.External, s.redditClient(a)
tc := s.cache()
tc.mu.Lock()
h, at := tc.redditHist, tc.redditHistAt
tc.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{}
}
tc.mu.Lock()
tc.redditHist, tc.redditHistAt = h, time.Now()
tc.mu.Unlock()
return h
}
// forgetRedditHistory drops the cached posts after posting.
func (s *Server) forgetRedditHistory() {
tc := s.cache()
tc.mu.Lock()
tc.redditHist = nil
tc.mu.Unlock()
}
+1 -4
View File
@@ -25,7 +25,6 @@ var services = []service{
{"x", "X", "Posting, and reading partners' posts", "/settings/accounts#network-X", []string{secrets.XBearerToken}},
{"linkedin", "LinkedIn", "Posting as a person", "/settings/accounts#network-LinkedIn", nil},
{"linkedin_page", "LinkedIn page", "Posting as the company's page", "/settings/accounts", nil},
{"reddit", "Reddit", "Posting to subreddits", "/settings/accounts#network-Reddit", nil},
{"youtube", "YouTube", "Reading partners' videos", "/settings/accounts", []string{secrets.YouTubeAPIKey}},
{"google", "Google Search Console", "SEO: what ranks, the morning check", "/settings/search", []string{secrets.GoogleRefreshToken}},
{"bing", "Bing Webmaster", "SEO: links to the sites", "/settings/search", []string{secrets.BingAPIKey}},
@@ -195,7 +194,7 @@ func (s *Server) connectionsPage(w http.ResponseWriter, r *http.Request) {
_, _ = s.DB.GetJSON(connChecksKey, &checks)
signins := s.connections()
// The posting networks count their accounts.
postingCount := map[string]int{"x": 0, "linkedin": 0, "linkedin_page": 0, "reddit": 0}
postingCount := map[string]int{"x": 0, "linkedin": 0, "linkedin_page": 0}
postingNames := map[string]string{}
for _, a := range s.postingAccounts() {
if s.working(a) {
@@ -283,8 +282,6 @@ func connectionName(id string) string {
return "linkedin"
case "linkedin_page":
return liPageProvider
case "reddit":
return "reddit"
case "google":
return "google"
}
+6 -7
View File
@@ -10,7 +10,6 @@ import (
"time"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/sitemap"
"supermarket/internal/content"
"supermarket/internal/db"
@@ -160,7 +159,7 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
seen := map[string]bool{}
for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} {
for _, sr := range list {
if n := reddit.CleanName(sr); n != "" && !seen[strings.ToLower(n)] {
if n := content.CleanSubreddit(sr); n != "" && !seen[strings.ToLower(n)] {
seen[strings.ToLower(n)] = true
subs = append(subs, n)
}
@@ -322,15 +321,15 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
}
for _, ch := range ordered {
if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit"))
req.Subreddit = content.CleanSubreddit(r.PostForm.Get("subreddit"))
if req.Subreddit == "" {
return errors.New("choose a subreddit for the Reddit post")
}
// The rules go into the prompt; without them the model is told
// to be careful, and Posts warns.
info, err := s.subreddit(r.Context(), req.Subreddit, false)
// The rules pasted for it go into the prompt; without them the
// model is told to be careful, and Posts asks for them.
info, err := content.GetSubreddit(s.DB, req.Subreddit)
if err != nil {
s.Log.Warn("reddit: couldn't read the subreddit's rules", "subreddit", req.Subreddit, "err", err)
s.Log.Error("reading a subreddit's rules", "subreddit", req.Subreddit, "err", err)
}
req.SubredditInfo = info
}
+29 -26
View File
@@ -11,7 +11,6 @@ import (
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/models"
@@ -210,17 +209,22 @@ func TestRedditInInbox(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
if err := content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "selfhosted", SubmitText: "Flair it.", SubmissionType: "self",
Rules: []reddit.Rule{{Name: "No self-promotion", Description: "Limit it."}}, FetchedAt: time.Now()}); err != nil {
if err := content.SaveRules(s.DB, "selfhosted", "1. Flair it.\n2. No self-promotion", time.Now()); err != nil {
t.Fatal(err)
}
body := do(h, http.MethodGet, "/posts", nil, nil).Body.String()
for _, want := range []string{"Reddit r/selfhosted", `name="title" value="Jitsi 3"`, "Flair it.", "No self-promotion",
"has a rule about this", "Couldn&#39;t read r/homelab&#39;s rules", `action="/reddit/rules/homelab"`, "Read rules", "text only"} {
for _, want := range []string{"Reddit r/selfhosted", `name="title" id="title-`, `value="Jitsi 3"`, "1. Flair it.", "has a rule about this",
"r/homelab's rules · not pasted yet", `action="/reddit/rules/homelab"`, `href="https://www.reddit.com/r/homelab/about/rules"`,
"Copy title", `data-copy-suffix="
Source: https://jitsi.example/3"`} {
if !strings.Contains(body, want) {
t.Errorf("inbox lacks %q", want)
}
}
if strings.Contains(body, "Publish now") || strings.Contains(body, "Schedule</button>") {
t.Error("Reddit drafts mustn't offer Publish now")
}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
var id string
@@ -238,22 +242,28 @@ func TestRedditInInbox(t *testing.T) {
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "The title is empty") {
t.Errorf("empty title: %s", rec.Body.String())
}
if rec := postForm(h, "/drafts/"+id+"/publish", nil); !strings.Contains(rec.Body.String(), "Reddit isn&#39;t connected") {
t.Errorf("publish without Reddit: %s", rec.Body.String())
for _, action := range []string{"publish", "schedule"} {
if rec := postForm(h, "/drafts/"+id+"/"+action, url.Values{"when": {time.Now().Add(time.Hour).Format("2006-01-02T15:04")}}); !strings.Contains(rec.Body.String(), "posted by hand") {
t.Errorf("%s a Reddit draft: %s", action, rec.Body.String())
}
}
// Reading rules needs Reddit credentials.
if rec := postForm(h, "/reddit/rules/homelab", nil); !strings.Contains(rec.Body.String(), "client ID and secret") {
t.Errorf("refresh without credentials: %d %s", rec.Code, rec.Body.String())
// Pasting the rules keeps them; emptying the box forgets them.
if rec := postForm(h, "/reddit/rules/homelab", url.Values{"rules": {"No memes."}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save rules: %d %s", rec.Code, rec.Body.String())
}
// Signing in needs the client ID and secret first.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusBadRequest {
t.Errorf("reddit start without credentials: %d", rec.Code)
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr == nil || sr.Rules != "No memes." {
t.Errorf("rules = %+v", sr)
}
_ = s.Secrets.Set(map[string]string{secrets.RedditClientID: "id", secrets.RedditClientSecret: "sec"})
rec := postForm(h, "/auth/reddit/start", nil)
if loc := rec.Header().Get("Location"); rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "https://www.reddit.com/api/v1/authorize?") ||
!strings.Contains(loc, "duration=permanent") || !strings.Contains(loc, "submit") {
t.Errorf("reddit start: %d %s", rec.Code, loc)
postForm(h, "/reddit/rules/homelab", url.Values{"rules": {""}})
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr != nil {
t.Error("emptied rules kept")
}
// Reddit has no sign-in any more.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusNotFound {
t.Errorf("reddit start: %d", rec.Code)
}
if strings.Contains(do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String(), "network-Reddit") {
t.Error("Social accounts still has a Reddit card")
}
}
@@ -328,14 +338,13 @@ func TestPostRedditByHand(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
_ = content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "linksonly", SubmissionType: "link", FetchedAt: time.Now()})
ids := map[string]string{}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
for _, d := range ds {
ids[d.Target] = strconv.FormatInt(d.ID, 10)
}
if body := do(h, http.MethodGet, "/posts", nil, nil).Body.String(); !strings.Contains(body, "Open in Reddit") ||
!strings.Contains(body, "can't post to Reddit for you yet") || !strings.Contains(body, `action="/drafts/`+ids["selfhosted"]+`/posted"`) {
!strings.Contains(body, "Post it yourself") || !strings.Contains(body, `action="/drafts/`+ids["selfhosted"]+`/posted"`) {
t.Error("inbox lacks the by-hand controls")
}
@@ -352,12 +361,6 @@ func TestPostRedditByHand(t *testing.T) {
t.Errorf("open should save the edits and leave it a draft: %+v", d)
}
// A links-only subreddit gets a link post.
loc, _ = url.Parse(postForm(h, "/drafts/"+ids["linksonly"]+"/open", nil).Header().Get("Location"))
if q := loc.Query(); q.Get("text") != "" || !strings.HasPrefix(q.Get("url"), "https://acme.example/w?") {
t.Errorf("link post: %s", loc)
}
// Mark as posted: a bad link is refused, a good one recorded.
if rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/posted", url.Values{"post_url": {"not a link"}}); !strings.Contains(rec.Body.String(), "isn&#39;t a link to a post") {
t.Error("bad post link accepted")
+49 -52
View File
@@ -10,7 +10,6 @@ import (
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
@@ -109,7 +108,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
s.render(w, r, "inbox", page{Title: "Posts", Nav: "content/posts", Error: errMsg, Data: map[string]any{
"Reminders": s.reminders(),
"Sections": sections,
"Reddit": s.redditViews(r.Context(), pending),
"Reddit": s.redditViews(pending),
"Connected": s.connected(viewerOf(r)),
"Accounts": s.usableAccounts(viewerOf(r)),
"Chosen": s.chosenAccounts(pending),
@@ -121,52 +120,47 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
// redditView is what Posts shows with a Reddit draft.
type redditView struct {
Info *reddit.Subreddit
Info *content.Subreddit // the rules pasted; nil if none
RulesURL string
Suffix string // added after the text when it's copied: the source link
Warnings []string
}
// redditViews works out the rules and warnings for the Reddit drafts. It
// reads the account's recent posts once (cached for a few minutes).
func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[int64]*redditView {
// redditViews works out the rules and warnings for the Reddit drafts.
func (s *Server) redditViews(drafts []content.Draft) map[int64]*redditView {
views := map[int64]*redditView{}
var history []reddit.Submission
historyRead := false
tags := s.tagger()
recorded, err := content.RecordedRedditPosts(s.DB, time.Now().Add(-8*24*time.Hour))
if err != nil {
s.Log.Error("reading recorded Reddit posts", "err", err)
}
for _, d := range drafts {
for i, d := range drafts {
if d.Channel != content.ChannelReddit {
continue
}
if !historyRead {
hctx, cancel := context.WithTimeout(ctx, 8*time.Second)
history = s.redditHistory(hctx)
cancel()
historyRead = true
info, err := content.GetSubreddit(s.DB, d.Target)
if err != nil {
s.Log.Error("reading a subreddit's rules", "subreddit", d.Target, "err", err)
}
info, _ := content.GetSubreddit(s.DB, d.Target)
check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now(),
check := content.RedditCheck{Target: d.Target, Info: info, Now: time.Now(),
Promo: d.Kind == content.KindProduct, Recorded: recorded}
if tags != nil {
check.Own = tags.Own
check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content)
}
views[d.ID] = &redditView{Info: info, Warnings: content.RedditWarnings(check)}
views[d.ID] = &redditView{Info: info, RulesURL: content.RulesURL(d.Target),
Suffix: redditSuffix(&drafts[i], tags), Warnings: content.RedditWarnings(check)}
}
return views
}
// refreshRules fetches a subreddit's rules again.
func (s *Server) refreshRules(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
if _, err := s.subreddit(ctx, r.PathValue("name"), true); err != nil {
s.renderInbox(w, r, "Couldn't read the subreddit's rules: "+err.Error())
// saveRules keeps the rules pasted for a subreddit.
func (s *Server) saveRules(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
redirect(w, r, "/posts", "rules-refreshed")
if err := content.SaveRules(s.DB, r.PathValue("name"), r.PostForm.Get("rules"), time.Now()); err != nil {
s.renderInbox(w, r, "Couldn't save the rules: "+err.Error())
return
}
redirect(w, r, "/posts", "rules-saved")
}
// The Content module's own lists of approved and published drafts.
@@ -308,7 +302,6 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
var failed []string
reddit := false
for _, did := range append([]int64{id}, copies...) {
_ = content.SetPostedBy(s.DB, did, by)
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), did)
@@ -320,13 +313,9 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
failed = append(failed, fmt.Sprintf("Couldn't publish to %s: %v", name, err))
continue
}
reddit = reddit || d.Channel == content.ChannelReddit
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL)
}
if reddit {
s.forgetRedditHistory()
}
if len(failed) > 0 {
fail(errors.New(strings.Join(failed, " ")))
return
@@ -363,8 +352,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err)
return
}
info, _ := content.GetSubreddit(s.DB, d.Target)
http.Redirect(w, r, redditSubmitURL(d, s.tagger(), info), http.StatusSeeOther)
http.Redirect(w, r, redditSubmitURL(d, s.tagger()), http.StatusSeeOther)
case "posted":
postURL := strings.TrimSpace(r.PostForm.Get("post_url"))
if postURL != "" {
@@ -377,7 +365,6 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err)
return
}
s.forgetRedditHistory()
redirect(w, r, back, "posted")
case "unschedule":
if err := content.Unschedule(s.DB, id); err != nil {
@@ -484,26 +471,36 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) {
// and still open; past it, the text is left for the user to paste.
const maxSubmitURL = 7500
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled
// in: a text post with the source link at the end, or a link post where the
// subreddit only takes links. It uses old.reddit.com, whose submit page
// reliably takes the title and text from the address.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger, info *reddit.Subreddit) string {
// redditText is what goes in a Reddit post: the draft's text with links to
// the company's sites tagged, and the source link at the end.
func redditText(d *content.Draft, tags *utm.Tagger) string {
text, src := content.Manual(d, tags)
base := "https://old.reddit.com/submit"
if sub := reddit.CleanName(d.Target); sub != "" {
base = "https://old.reddit.com/r/" + url.PathEscape(sub) + "/submit"
}
q := url.Values{"title": {d.Title}}
if info != nil && !info.AllowsText() && src != "" {
q.Set("url", src)
return base + "?" + q.Encode()
}
if src != "" && !strings.Contains(text, src) {
text += "\n\nSource: " + src
}
q.Set("selftext", "true")
q.Set("text", text)
return text
}
// redditSuffix is what Copy text adds after the text on screen: the source
// link, tagged, unless the text already has it.
func redditSuffix(d *content.Draft, tags *utm.Tagger) string {
text, src := content.Manual(d, tags)
if src == "" || strings.Contains(text, src) {
return ""
}
return "\n\nSource: " + src
}
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled
// in as a text post. It uses old.reddit.com, whose submit page reliably
// takes the title and text from the address. Text too long for an address
// is left out, for the user to paste.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger) string {
base := "https://old.reddit.com/submit"
if sub := content.CleanSubreddit(d.Target); sub != "" {
base = "https://old.reddit.com/r/" + url.PathEscape(sub) + "/submit"
}
q := url.Values{"title": {d.Title}, "selftext": {"true"}, "text": {redditText(d, tags)}}
if u := base + "?" + q.Encode(); len(u) <= maxSubmitURL {
return u
}
+1 -30
View File
@@ -12,8 +12,6 @@ import (
"supermarket/examples"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
@@ -39,7 +37,6 @@ type entryData struct {
DraftURL string // the address to fill in from
Filled []string // after filling in: what was filled
Suggestions []inventory.Suggestion
CanCheck bool // Reddit could be asked about the suggestions
Drafted bool
Today string // for new price rows
Blank []int // empty price rows to show
@@ -179,9 +176,7 @@ func (s *Server) inventoryFill(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
defer cancel()
check := s.subredditCheck(ctx)
d.CanCheck = check != nil
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check)
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours)
d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true
if err != nil {
// Links read before the model failed are kept.
@@ -277,30 +272,6 @@ func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}
// subredditCheck looks subreddits up on Reddit for Fill, using the cache
// and caching what it reads (drafting for the subreddit uses it later). It's
// nil if Reddit can't be asked: no client ID and secret.
func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
c, err := s.redditReader(ctx)
if err != nil {
return nil
}
return func(ctx context.Context, name string) (*reddit.Subreddit, error) {
if cached, err := content.GetSubreddit(s.DB, name); err == nil && cached != nil &&
time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
info, err := c.SubredditInfo(ctx, name)
if err != nil {
return nil, err
}
if err := content.SaveSubreddit(s.DB, info); err != nil {
s.Log.Error("caching subreddit", "name", name, "err", err)
}
return info, nil
}
}
// marketRoom says why a new entry can't be added (the plan's limit), or nil.
func (s *Server) marketRoom(e *inventory.Entry) error {
if e.ID != 0 {
+1 -1
View File
@@ -220,7 +220,7 @@ func (s *Server) connectionSummary(map[string]Connection) string {
parts = append(parts, label)
}
if len(parts) == 0 {
return "Connect X, LinkedIn or Reddit"
return "Connect X or LinkedIn"
}
return strings.Join(parts, ", ")
}
+4 -35
View File
@@ -11,7 +11,6 @@ import (
"time"
"supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/content"
@@ -32,7 +31,7 @@ var adoptMu sync.Mutex
// the company's accounts, the first time they're seen.
func (s *Server) adoptLegacy() {
if !s.Secrets.Has(secrets.XAccessToken) && !s.Secrets.Has(secrets.LinkedInAccessToken) &&
!s.Secrets.Has(secrets.LinkedInPageAccessToken) && !s.Secrets.Has(secrets.RedditAccessToken) {
!s.Secrets.Has(secrets.LinkedInPageAccessToken) {
return
}
adoptMu.Lock()
@@ -59,9 +58,6 @@ func (s *Server) adoptLegacy() {
return o.Name, o.URN, expiry(conns[liPageProvider])
}
return "the company page", "", expiry(conns[liPageProvider])
case posting.Reddit:
u := s.Secrets.Get(secrets.RedditUsername)
return "u/" + u, u, time.Time{}
}
return "", "", time.Time{}
}, time.Now())
@@ -127,7 +123,9 @@ func (s *Server) working(a *posting.Account) bool {
func (s *Server) usableAccounts(v *viewer) map[string][]*posting.Account {
out := map[string][]*posting.Account{}
for _, a := range s.postingAccounts() {
if s.working(a) && s.mayPostAs(v, a) {
// Reddit accounts signed in before are left unused: Reddit is
// posted to by hand.
if a.Network != posting.Reddit && s.working(a) && s.mayPostAs(v, a) {
ch := posting.Channel(a.Network)
out[ch] = append(out[ch], a)
}
@@ -236,39 +234,10 @@ func (s *Server) publisherFor(a *posting.Account) (content.Publisher, error) {
return nil, errors.New("choose which company page " + a.Label() + " posts as, under Settings → Social accounts")
}
return asPublisher{linkedInPublisher{page: linkedin.New(tok, a.External)}, true}, nil
case posting.Reddit:
return redditPublisher{s: s, c: s.redditClient(a)}, nil
}
return nil, fmt.Errorf("no network %q", a.Network)
}
// redditClient is signed in as a Reddit account; refused tokens are
// refreshed and saved.
func (s *Server) redditClient(a *posting.Account) *reddit.Client {
id, ua := a.ID, reddit.UserAgent(s.Version, a.External)
return reddit.New(s.Secrets.Get(posting.AccessName(id)), ua, func(ctx context.Context) (string, error) {
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret), ua, s.Secrets.Get(posting.RefreshName(id)))
if err != nil {
return "", err
}
if err := posting.SaveTokens(s.Secrets, id, res.AccessToken, res.RefreshToken); err != nil {
s.Log.Error("reddit: couldn't save the refreshed token", "account", id, "err", err)
}
return res.AccessToken, nil
})
}
// companyReddit is the company's Reddit account, for reading rules and
// the account's history; nil if none.
func (s *Server) companyReddit() *posting.Account {
s.adoptLegacy()
a, err := posting.Company(s.DB, posting.Reddit)
if err != nil || a == nil || !s.Secrets.Has(posting.AccessName(a.ID)) {
return nil
}
return a
}
// removeAccount signs an account out: scheduled posts to it go back to
// Posts, and their writers are told.
func (s *Server) removeAccount(a *posting.Account, why string) error {
+1 -1
View File
@@ -42,7 +42,7 @@ var settingsPages = []struct {
}{
{hit{"Company profile", "Settings · your company, products, websites, voice and targets", "/settings/profile", ""},
"profile company products websites voice tone audience keywords feeds subreddits accounts"},
{hit{"Social accounts", "Settings · X, LinkedIn, Reddit and YouTube keys and sign-ins", "/settings/accounts", ""},
{hit{"Social accounts", "Settings · X, LinkedIn and YouTube keys and sign-ins", "/settings/accounts", ""},
"social accounts credentials keys x twitter linkedin reddit youtube sign in connect oauth bearer token"},
{hit{"AI", "Settings · provider, model, API keys and the Hermes key", "/settings/ai", ""},
"ai provider model anthropic claude openai ollama lm studio api key hermes effort"},
+3 -11
View File
@@ -25,7 +25,6 @@ import (
"unicode"
"unicode/utf8"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/billing"
@@ -111,12 +110,6 @@ type state struct {
// teamCache is what's kept in memory for a team.
type teamCache struct {
mu sync.Mutex
// Reddit: an app-only token for reading rules before sign-in, and the
// account's recent posts for the warnings.
redditAppToken string
redditAppTokenExp time.Time
redditHist []reddit.Submission
redditHistAt time.Time
// Google's access token, which lasts an hour.
googleToken string
googleExpires time.Time
@@ -448,7 +441,7 @@ func (s *Server) Handler() (http.Handler, error) {
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
})
mux.HandleFunc("POST /drafts/{id}/{action}", (*Server).draftAction)
mux.HandleFunc("POST /reddit/rules/{name}", (*Server).refreshRules)
mux.HandleFunc("POST /reddit/rules/{name}", (*Server).saveRules)
mux.HandleFunc("GET /prospects", (*Server).prospectsPage)
mux.HandleFunc("GET /prospects/new", (*Server).prospectForm)
@@ -870,7 +863,7 @@ type module struct {
}
var modules = []module{
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/posts"},
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X and LinkedIn; Reddit posts are written for you to post yourself.", "/posts"},
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo/check"},
{"sites", "Sites", "Phase 5", "Build pages from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"},
@@ -1026,7 +1019,6 @@ var flashes = map[string]string{
"audited": "The audit is done.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
@@ -1040,7 +1032,7 @@ var flashes = map[string]string{
"prospect-exists": "Already there: nothing new was added. It's in the list below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"rules-saved": "Rules saved: new drafts for that subreddit follow them.",
"imported": "Imported.",
"imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.",
"hunter-done": "Hunter.io search done: the result is on the card.",
+2 -37
View File
@@ -11,7 +11,6 @@ import (
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/posting"
@@ -158,7 +157,6 @@ type secretField struct {
const (
xConsole = "https://console.x.com"
linkedInApps = "https://www.linkedin.com/developers/apps"
redditApps = "https://www.reddit.com/prefs/apps"
googleCreds = "https://console.cloud.google.com/apis/credentials"
anthropicKeys = "https://platform.claude.com/settings/keys"
)
@@ -187,10 +185,6 @@ var accountFields = []secretField{
"A second LinkedIn app, linked to the company page, with the Community Management API approved by LinkedIn (it must be the app's only product). Its Auth tab has the ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"Reddit", secrets.RedditClientID, "Client ID",
"Create app → choose \"web app\" and enter the redirect URI above. The client ID is the string under the app's name.", redditApps},
{"Reddit", secrets.RedditClientSecret, "Client secret",
"On the same app, next to \"secret\".", redditApps},
{"YouTube", secrets.YouTubeAPIKey, "API key",
"Free. In Google Cloud, enable the YouTube Data API v3 for a project, then Credentials → Create credentials → API key. For reading channels' videos.", googleCreds},
}
@@ -254,7 +248,7 @@ func (s *Server) networks() []network {
}
set := s.secretState(names...)
accts := s.postingAccounts()
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage, "reddit": posting.Reddit}
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage}
connect := func(provider, token, setup, note string, ready bool, account func(string) string) *connectInfo {
c := &connectInfo{Provider: provider, Redirect: s.callbackURL(provider), Setup: setup, Note: note, Ready: ready}
for _, a := range accts {
@@ -276,7 +270,7 @@ func (s *Server) networks() []network {
}
}
var nets []network
for _, name := range []string{"X", "LinkedIn", liPageNetwork, "Reddit", "YouTube"} {
for _, name := range []string{"X", "LinkedIn", liPageNetwork, "YouTube"} {
n := network{Name: name, Set: set}
for _, f := range accountFields {
if f.Group == name {
@@ -297,10 +291,6 @@ func (s *Server) networks() []network {
set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup()
case "Reddit":
n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:",
"Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.",
set[secrets.RedditClientID] && set[secrets.RedditClientSecret], at("u/"))
}
nets = append(nets, n)
}
@@ -395,13 +385,6 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes())
case "reddit":
id := s.Secrets.Get(secrets.RedditClientID)
if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) {
http.Error(w, "Save Reddit's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.RedditStart(id, s.callbackURL("reddit"))
case "google":
id := s.Secrets.Get(secrets.GoogleClientID)
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
@@ -632,24 +615,6 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
return
}
redirect(w, r, "/settings/accounts", "li-page-connected")
case "reddit":
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), code, p)
if err != nil {
fail(err.Error())
return
}
name, err := reddit.New(res.AccessToken, s.redditUserAgent(), nil).Me(ctx)
if err != nil {
fail("Signed in, but couldn't read the Reddit account's name: " + err.Error())
return
}
if err := saveAccount(posting.Reddit, "u/"+name, name, res.AccessToken, res.RefreshToken, time.Time{}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.forgetRedditHistory()
redirect(w, r, back, ownMsg("reddit-connected"))
default:
http.NotFound(w, r)
}
+2
View File
@@ -67,6 +67,8 @@
if (src && navigator.clipboard) {
// A field's current value (with edits), else an element's text.
var value = "value" in src ? src.value : src.textContent;
// data-copy-suffix: added after it (a Reddit post's source link).
value += copy.getAttribute("data-copy-suffix") || "";
navigator.clipboard.writeText(value).then(function () {
var label = copy.textContent;
copy.textContent = "Copied";
+2 -2
View File
@@ -78,12 +78,12 @@
<legend>Channels</legend>
{{range .Channels}}
{{/* Reddit is never pre-checked: each post there is a deliberate choice. */}}
<label class="check"><input type="checkbox" name="channel" value="{{.ID}}" {{if and .Connected (ne .ID "reddit")}}checked{{end}}> {{.Name}}{{if not .Connected}} <span class="muted">(not connected: you can draft, but not publish yet)</span>{{end}}</label>
<label class="check"><input type="checkbox" name="channel" value="{{.ID}}" {{if and .Connected (ne .ID "reddit")}}checked{{end}}> {{.Name}}{{if eq .ID "reddit"}} <span class="muted">(you post it yourself)</span>{{else if not .Connected}} <span class="muted">(not connected: you can draft, but not publish yet)</span>{{end}}</label>
{{end}}
<label class="small">Subreddit, for Reddit
<input name="subreddit" list="subreddits" placeholder="e.g. selfhosted" autocomplete="off">
<datalist id="subreddits">{{range .Subreddits}}<option value="{{.}}">{{end}}</datalist>
<span class="help">One subreddit per post. Its rules are read and followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span>
<span class="help">One subreddit per post. The rules you've pasted for it (on Posts) are followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span>
</label>
</fieldset>
{{if .Signals}}
+3 -5
View File
@@ -6,7 +6,7 @@
<input type="hidden" name="id" value="{{$e.ID}}">
<section class="card">
<h2>Fill in with AI</h2>
<p class="help">Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords, hashtags and subreddits from the AI (subreddits checked with Reddit first), set against your <a href="/settings/profile">company profile</a>. What you've typed stays. Nothing is saved until you press Save.</p>
<p class="help">Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords, hashtags and subreddits from the AI, set against your <a href="/settings/profile">company profile</a>. What you've typed stays. Nothing is saved until you press Save.</p>
{{if .NoAI}}<p class="warn-text">This needs the AI: first <a href="/settings/ai">set up the AI</a>, then come back. Or fill in the form by hand.</p>{{end}}
<div class="row">
<input name="draft_url" type="text" inputmode="url" value="{{.DraftURL}}" placeholder="https://example.com" aria-label="Their website">
@@ -17,18 +17,16 @@
{{with .Suggestions}}
<details class="suggestions" open>
<summary>Subreddits the AI suggested</summary>
{{if not $.Data.CanCheck}}<p class="warn-text small">Not checked with Reddit, so some may not exist: add Reddit's client ID and secret under <a href="/settings/accounts">Settings → Social accounts</a> and fill in again to check them.</p>{{end}}
<ul>
{{range .}}
<li class="{{if .Kept}}kept{{else}}dropped{{end}}">
<a href="https://www.reddit.com/r/{{.Name}}/" target="_blank" rel="noopener noreferrer">r/{{.Name}}</a>
{{with .Info}}<span class="muted small">{{.Subscribers}} members · {{if eq .SubmissionType "self"}}text posts only{{else if eq .SubmissionType "link"}}link posts only{{else}}text or links{{end}}</span>{{end}}
{{if .Kept}}{{if and .Problem $.Data.CanCheck}}<span class="warn-text small">{{.Problem}}</span>{{end}}{{else}}<span class="small">left out: {{.Problem}}</span>{{end}}
{{if not .Kept}}<span class="small">left out: more than enough already</span>{{end}}
{{with .Why}}<span class="help">{{.}}</span>{{end}}
</li>
{{end}}
</ul>
<p class="help">The ones kept are in the Subreddits box below. Look at each on Reddit before posting there: the AI picks by topic, not by how a community treats companies.</p>
<p class="help">The ones kept are in the Subreddits box below. They aren't checked with Reddit, so one may not exist, or be private: open each before posting there. The AI picks by topic, not by how a community treats companies.</p>
</details>
{{end}}
</section>
+23 -19
View File
@@ -1,6 +1,6 @@
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$accounts := .Accounts}}{{$chosen := .Chosen}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Posts</h1>
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it.
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it. Reddit posts you post yourself.
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
{{template "reminders" .Reminders}}
@@ -23,26 +23,37 @@
{{$rv := index $reddit .ID}}
{{if $rv}}
{{if $rv.Warnings}}<ul class="warnings">{{range $rv.Warnings}}<li>{{.}}</li>{{end}}</ul>{{end}}
{{with $rv.Info}}
<details class="rules">
<summary>r/{{.Name}}'s rules{{if .Rules}} ({{len .Rules}}){{end}} · read {{ago .FetchedAt}}</summary>
{{if .SubmitText}}<p class="guidelines">{{truncate 1200 .SubmitText}}</p>{{end}}
{{if .Rules}}<ol>{{range .Rules}}<li><strong>{{.Name}}</strong>{{if .Description}}: {{truncate 500 .Description}}{{end}}</li>{{end}}</ol>{{end}}
<p class="muted small">Posts: {{if eq .SubmissionType "self"}}text only{{else if eq .SubmissionType "link"}}links only{{else}}text or links{{end}}{{if .Subscribers}} · {{.Subscribers}} members{{end}}</p>
<details class="rules" {{if not $rv.Info}}open{{end}}>
<summary>r/{{.Target}}'s rules{{with $rv.Info}} · pasted {{ago .SavedAt}}{{else}} · not pasted yet{{end}}</summary>
<form method="post" action="/reddit/rules/{{.Target}}">
<p class="help">Supermarket can't read them from Reddit. <a href="{{$rv.RulesURL}}" target="_blank" rel="noopener noreferrer">Open r/{{.Target}}'s rules ↗</a>, copy them, and paste them here: the next drafts for r/{{.Target}} follow them, and the warnings above use them. To use them for this draft, write it again after saving.</p>
<textarea name="rules" rows="6" aria-label="r/{{.Target}}'s rules" placeholder="Paste the rules here">{{with $rv.Info}}{{.Rules}}{{end}}</textarea>
<button type="submit" class="secondary small">Save rules</button>
</form>
</details>
{{end}}
<form method="post" action="/reddit/rules/{{.Target}}" class="inline"><button type="submit" class="secondary small">{{if $rv.Info}}Refresh rules{{else}}Read rules{{end}}</button></form>
{{end}}
<form method="post" action="/drafts/{{.ID}}/save" data-busy-on="publish" data-busy="Publishing…">
{{if eq .Channel "reddit"}}
<label class="small">Title
<input name="title" value="{{.Title}}" maxlength="300" required>
<input name="title" id="title-{{.ID}}" value="{{.Title}}" maxlength="300" required>
</label>
{{end}}
<textarea name="content" rows="{{if eq .Channel "x"}}5{{else}}12{{end}}"
data-count="{{.Channel}}" data-limit="{{.Limit}}" data-reserve="{{if eq .Channel "x"}}{{xreserve .SourceURL}}{{else}}0{{end}}"
aria-describedby="count-{{.ID}}" id="text-{{.ID}}">{{.Content}}</textarea>
{{if eq .Channel "reddit"}}{{if .SourceURL}}<p class="help">The source link is added at the end as “Source: …”.</p>{{end}}{{end}}
{{if eq .Channel "reddit"}}
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}</p>
<div class="by-hand">
<p class="small"><strong>Post it yourself.</strong> <em>Open in Reddit</em> saves your edits and opens r/{{.Target}}'s submit page in a new tab with the title and text filled in{{if .SourceURL}} (links to your sites tagged){{end}}. If a box comes up empty, copy it from here. Check it there and post.</p>
<div class="row">
<button type="submit" formaction="/drafts/{{.ID}}/open" formtarget="_blank">Open in Reddit ↗</button>
<button type="button" class="secondary small" data-copy="title-{{.ID}}">Copy title</button>
<button type="button" class="secondary small" data-copy="text-{{.ID}}" data-copy-suffix="{{with $rv}}{{.Suffix}}{{end}}">Copy text</button>
<button type="submit" class="secondary small">Save</button>
</div>
</div>
{{else}}
{{$d := .}}{{$accts := index $accounts .Channel}}
{{if $accts}}
<fieldset class="post-as">
@@ -62,15 +73,8 @@
</label>
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/schedule">Schedule</button>
</div>
{{if eq .Channel "reddit"}}
<div class="by-hand">
<p class="small"><strong>Or post it yourself</strong>{{if not (index $conn .Channel)}}, since Supermarket can't post to Reddit for you yet{{end}}: this saves your edits and opens r/{{.Target}}'s submit page in a new tab with the title and text filled in{{if .SourceURL}} (links to your sites tagged){{end}}. Check it there and post.</p>
<div class="row">
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/open" formtarget="_blank">Open in Reddit ↗</button>
<button type="button" class="secondary small" data-copy="text-{{.ID}}">Copy text</button>
</div>
</div>
{{else if not (index $conn .Channel)}}<p class="help">{{.ChannelName}} isn't connected: <a href="/settings/accounts">sign in</a> before it's due.</p>{{end}}
{{if not (index $conn .Channel)}}<p class="help">{{.ChannelName}} isn't connected: <a href="/settings/accounts">sign in</a> before it's due.</p>{{end}}
{{end}}
</form>
{{if eq .Channel "reddit"}}
<form method="post" action="/drafts/{{.ID}}/posted" class="by-hand-done">