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:
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user