package content import ( "database/sql" "encoding/json" "errors" "fmt" "regexp" "strings" "time" "supermarket/internal/db" ) // 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. // 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 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 } // 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`, name, string(raw), formatTime(now)) return err } // 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 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 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 { 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))) } } } 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 } func plural(n int) string { if n == 1 { return "" } return "s" } // 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 []RedditPost for rows.Next() { var s RedditPost var at string if err := rows.Scan(&s.Subreddit, &at); err != nil { return nil, err } s.Created = parseTime(at) out = append(out, s) } return out, rows.Err() }