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
+8
View File
@@ -48,6 +48,14 @@ Schema 44.
schema per team, sign-up, domains proved, platform admins; billing with schema per team, sign-up, domains proved, platform admins; billing with
Stripe (Phase 14), not yet tried against Stripe's test mode. Stripe (Phase 14), not yet tried against Stripe's test mode.
**Reddit is posted by hand (2026-11-30).** Reddit's API isn't open to
apps like this, so its sign-in, keys, publishing, scheduling and reading
of rules and history are gone (`internal/api/reddit` too). Supermarket
writes the post; the user pastes each subreddit's rules once (kept in
`subreddits` as `pasted_rules`, given to the model), opens the submit page
filled in or copies the title and text, posts, and marks it posted. The
warnings come from the pasted rules and the posts marked as posted.
**Next: testing by hand with TEST.md**, in three passes: local, then **Next: testing by hand with TEST.md**, in three passes: local, then
server with the Core, then multi-tenant (TEST.md's table says which server with the Core, then multi-tenant (TEST.md's table says which
sections go with each pass). What the passes find gets fixed as it comes. sections go with each pass). What the passes find gets fixed as it comes.
+15 -15
View File
@@ -6,13 +6,13 @@ Everything starts from your **company profile** (what you sell, to whom, in what
| Module | What it does | Status | | Module | What it does | Status |
|--------|--------------|--------| |--------|--------------|--------|
| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X, LinkedIn and Reddit | Phase 1: done | | Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X and LinkedIn, and post Reddit ones yourself | Phase 1: done |
| Prospects | Finds companies and people who fit your targets; the ones you approve go into your Core's EspoCRM through Hermes | Phase 2 | | Prospects | Finds companies and people who fit your targets; the ones you approve go into your Core's EspoCRM through Hermes | Phase 2 |
| SEO | Audits your websites for Google, Bing/DuckDuckGo and Brave, and opens fixes as pull requests on your Hugo repositories | Phase 3 | | SEO | Audits your websites for Google, Bing/DuckDuckGo and Brave, and opens fixes as pull requests on your Hugo repositories | Phase 3 |
| Metrics | Pipeline influence, CAC, CLV and NRR, from Stripe, EspoCRM and Plausible | Phase 4 | | Metrics | Pipeline influence, CAC, CLV and NRR, from Stripe, EspoCRM and Plausible | Phase 4 |
| Sites | Builds pages and sites from a component library and publishes them through Gitea | Phase 5 | | Sites | Builds pages and sites from a component library and publishes them through Gitea | Phase 5 |
This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the Content module (Phase 1): posts about partners, competitors and your own products, a Posts page for approval, scheduled publishing to X, LinkedIn and Reddit, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan. This version has the foundation (Phase 0): the web app, the company profile, the inventory, the AI provider, credentials, and the bridge to your Core through Hermes. It also has the Content module (Phase 1): posts about partners, competitors and your own products, a Posts page for approval, scheduled publishing to X and LinkedIn, Reddit posts written for you to post yourself, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan.
## Install ## Install
@@ -36,8 +36,8 @@ Then open Supermarket and:
1. **Settings → AI**: Anthropic, with Hermes' key (shared by `supermarket hermes`) or your own, or an LLM server on your network, such as Ollama. Servers found by CoreDesktop's `configure ai-servers` are offered. 1. **Settings → AI**: Anthropic, with Hermes' key (shared by `supermarket hermes`) or your own, or an LLM server on your network, such as Ollama. Servers found by CoreDesktop's `configure ai-servers` are offered.
2. **Settings → Profile**: enter your website and press *Draft*. Correct the draft and save it. 2. **Settings → Profile**: enter your website and press *Draft*. Correct the draft and save it.
3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits are checked with Reddit first (with the Reddit client ID and secret saved), and ones that don't exist, are private or are restricted are left out. What you typed stays; nothing is saved until you press Save. 3. **Inventory**: add your partners and competitors, or import a list. On an entry, *Fill in the empty boxes* reads their website: links, accounts and feeds come straight from the pages, and the AI drafts a description, talking points set against your profile, keywords, hashtags and subreddits. Suggested subreddits aren't checked with Reddit: open each before posting there. What you typed stays; nothing is saved until you press Save.
4. **Settings → Social accounts**: connect X, LinkedIn and Reddit. 4. **Settings → Social accounts**: connect X and LinkedIn. Reddit needs nothing: you post Reddit drafts yourself.
The menu on the left has a search box at the top (press `/` to jump to it), then the **Overview** with a card per module, the **Inventory**, and the modules: **Content** (Posts, Sources, Scheduled, Published), and the ones still to come. **Settings**, at the bottom, holds the Profile, Social accounts, Core & Hermes, and AI. Search finds posts, fetched items, inventory entries, your products and settings pages. The look follows brain (Federated's superbrain), including a dark theme that follows your system's setting. The menu on the left has a search box at the top (press `/` to jump to it), then the **Overview** with a card per module, the **Inventory**, and the modules: **Content** (Posts, Sources, Scheduled, Published), and the ones still to come. **Settings**, at the bottom, holds the Profile, Social accounts, Core & Hermes, and AI. Search finds posts, fetched items, inventory entries, your products and settings pages. The look follows brain (Federated's superbrain), including a dark theme that follows your system's setting.
@@ -187,23 +187,23 @@ Reading X needs a bearer token from an X API plan with read access; YouTube need
### Reddit ### Reddit
A Reddit draft is a title and a text for one subreddit, which you choose when writing (suggestions come from the entry's and the profile's subreddits). The subreddit's rules and posting guidelines are read, given to the model, and shown with the draft in Posts. Reddit drafts are written as a community member who says where they work, without hashtags or marketing language. The source link goes at the end of the text; a subreddit that only takes links gets the title and the link. Reddit's API isn't open to apps like Supermarket, so Reddit posts are written by Supermarket and posted by you. A Reddit draft is a title and a text for one subreddit, which you choose when writing (suggestions come from the entry's and the profile's subreddits). It's written as a community member who says where they work, without hashtags or marketing language. The source link goes at the end of the text.
Before you publish, Posts warns, without blocking, when: Supermarket can't read a subreddit's rules either, so you paste them: each Reddit draft in Posts has a box for its subreddit's rules, with a link to them on Reddit. Pasted once, they're given to the model for every later draft for that subreddit.
- the subreddit has a rule about self-promotion, is restricted, or doesn't take that kind of post,
- you posted in that subreddit in the past week,
- more than 1 in 10 of your posts in the past 30 days would link to your own sites (Reddit's guideline),
- the account has no posts yet.
Reddit's Data API terms need Reddit's approval for commercial use. Supermarket is meant for a few hand-approved posts, never volume or automation: every post needs you to press Publish or Schedule. To post: *Open in Reddit* saves your edits and opens the subreddit's submit page with the title and text filled in (links to your sites tagged); *Copy title* and *Copy text* are there for a box that comes up empty. Post it on Reddit, then *Mark as posted*, with the post's link if you like: it moves to Published.
## Signing in to X, LinkedIn and Reddit Posts warns, without blocking, when:
- the draft promotes your own work,
- the pasted rules have a line about self-promotion, advertising or spam,
- you marked a post in that subreddit as posted in the past week.
## Signing in to X and LinkedIn
Sign-ins come back to Supermarket at `http://localhost:8470/auth/<provider>/callback` (X: `127.0.0.1` instead of `localhost`). Register these callback URLs in your apps: Sign-ins come back to Supermarket at `http://localhost:8470/auth/<provider>/callback` (X: `127.0.0.1` instead of `localhost`). Register these callback URLs in your apps:
- X developer portal, your app's *User authentication settings*: `http://127.0.0.1:8470/auth/x/callback`. X refuses `localhost` in callback URLs; `127.0.0.1` is the same machine, and Supermarket sends X this address. - X developer portal, your app's *User authentication settings*: `http://127.0.0.1:8470/auth/x/callback`. X refuses `localhost` in callback URLs; `127.0.0.1` is the same machine, and Supermarket sends X this address.
- LinkedIn developer portal, your app's *Auth* tab: `http://localhost:8470/auth/linkedin/callback` - LinkedIn developer portal, your app's *Auth* tab: `http://localhost:8470/auth/linkedin/callback`
- Reddit, [reddit.com/prefs/apps](https://www.reddit.com/prefs/apps): create a **web app** with the redirect URI `http://localhost:8470/auth/reddit/callback`, and put its client ID and secret under Settings → Social accounts
The old terminal app used `http://localhost:8080/callback`; you can remove that one. The old terminal app used `http://localhost:8080/callback`; you can remove that one.
@@ -251,8 +251,8 @@ unlocks it). Settings → Activity shows who did what.
**Social accounts and Search Console.** Each service's developer app needs the **Social accounts and Search Console.** Each service's developer app needs the
server's addresses as its redirect URLs: `https://<domain>/auth/x/callback`, server's addresses as its redirect URLs: `https://<domain>/auth/x/callback`,
`…/auth/linkedin/callback`, `…/auth/linkedin-page/callback`, `…/auth/linkedin/callback`, `…/auth/linkedin-page/callback` and
`…/auth/reddit/callback` and `…/auth/google/callback`. `…/auth/google/callback`.
**Backups.** Postgres is dumped every night at 03:00, and two weeks of dumps **Backups.** Postgres is dumped every night at 03:00, and two weeks of dumps
are kept, in the `pgbackups` volume; Settings → Backups lists them and says are kept, in the `pgbackups` volume; Settings → Backups lists them and says
+16 -5
View File
@@ -201,16 +201,27 @@ Throughout, also notice:
- [ ] Editing a draft and saving keeps the edit. - [ ] Editing a draft and saving keeps the edit.
- [ ] Links to your own sites get UTM tags when published; other links - [ ] Links to your own sites get UTM tags when published; other links
don't. don't.
- [ ] For Reddit, choosing a subreddit shows its rules, and the draft - [ ] A Reddit draft in Posts has a box for its subreddit's rules, open
respects them. while none are pasted, with a link that opens them on Reddit. Paste
them and *Save rules*: they're kept, and a rule about
self-promotion shows as a warning. Write another draft for that
subreddit: it respects them.
- [ ] Choosing Reddit when writing says "(you post it yourself)", and the
Market entry's suggested subreddits say they aren't checked.
### Publishing ### Publishing
- [ ] **(real)** *Publish* on an X draft posts it, and it moves to - [ ] **(real)** *Publish* on an X draft posts it, and it moves to
Published with a link to the post. Published with a link to the post.
- [ ] **(real)** The same for LinkedIn. - [ ] **(real)** The same for LinkedIn.
- [ ] Reddit: *Open in Reddit* opens the submit page filled in; *Mark as - [ ] Reddit drafts have no *Publish now* or *Schedule*. *Open in Reddit*
posted* moves it to Published. saves the edits and opens the subreddit's submit page with the title
and text filled in (source link at the end, tagged). *Copy title* and
*Copy text* copy what's on screen, the text with the source link.
- [ ] **(real)** Post it on Reddit, paste the post's link and *Mark as
posted*: it moves to Published. A later draft for the same
subreddit warns that you posted there in the past week.
- [ ] Settings → Social accounts has no Reddit card.
- [ ] *Schedule* a draft for a few minutes ahead: it shows under Scheduled, - [ ] *Schedule* a draft for a few minutes ahead: it shows under Scheduled,
and goes out at that time (in your local time zone). and goes out at that time (in your local time zone).
- [ ] *Unschedule* puts it back in Posts. - [ ] *Unschedule* puts it back in Posts.
@@ -839,7 +850,7 @@ The detailed checks for agents (Phase 11) are in section 15.
On the local edition first: On the local edition first:
- [ ] Nothing asks anyone to sign in; Settings has no Users or Your account. - [ ] Nothing asks anyone to sign in; Settings has no Users or Your account.
Every form still works (each now carries a hidden `csrf` field). Every form still works (each now carries a hidden `csrf` field).
- [ ] Your old X, LinkedIn and Reddit sign-ins show under Social accounts as - [ ] Your old X and LinkedIn sign-ins show under Social accounts as
the company's accounts, with *Sign out*; Settings → Posting accounts the company's accounts, with *Sign out*; Settings → Posting accounts
lists them. A LinkedIn draft's *Post as* lists the member and the page. lists them. A LinkedIn draft's *Post as* lists the member and the page.
- [ ] Settings → All connections lists every service, who connected it, and - [ ] Settings → All connections lists every service, who connected it, and
-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. // published.
var ErrNotEditable = errors.New("this draft can't be changed any more") 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. // UpdateDraft saves edited text.
func UpdateDraft(d *db.DB, id int64, text string) error { func UpdateDraft(d *db.DB, id int64, text string) error {
text = strings.TrimSpace(text) 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") return errors.New("that's more than a year away")
} }
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ? res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ?
WHERE id = ? AND status IN (?, ?)`, WHERE id = ? AND status IN (?, ?) AND channel <> ?`,
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed) StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed, ChannelReddit)
return oneRow(res, err) 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. // Unschedule sends a scheduled draft back to Posts, to edit or drop.
+9 -18
View File
@@ -8,7 +8,6 @@ import (
"strings" "strings"
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/profile" "supermarket/internal/profile"
@@ -24,7 +23,7 @@ type Request struct {
// Reddit: the subreddit to write for, and what's known about it (nil // Reddit: the subreddit to write for, and what's known about it (nil
// if its rules couldn't be read). // if its rules couldn't be read).
Subreddit string 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, if set, is the buying signal the posts are written for.
Signal *signals.Signal Signal *signals.Signal
} }
@@ -133,7 +132,7 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
title = string(r[:RedditTitleLimit-1]) + "…" title = string(r[:RedditTitleLimit-1]) + "…"
} }
drafts = append(drafts, Draft{InventoryName: name, Kind: req.Entry.Relationship, Channel: ch, SignalID: req.signalID(), 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}) SourceURL: src, ItemIDs: ids, Status: StatusDraft})
continue continue
} }
@@ -314,7 +313,7 @@ func oneLine(s string) string {
// punishes marketing, so the rules are stricter than for other channels. // punishes marketing, so the rules are stricter than for other channels.
func redditInstructions(req Request) string { func redditInstructions(req Request) string {
var b strings.Builder 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. "+ 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\"). "+ "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, "+ "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") "about it, and invite questions and feedback.\n")
} }
if info := req.SubredditInfo; info != nil { if info := req.SubredditInfo; info != nil {
b.WriteString("<subreddit>\n") b.WriteString("<subreddit_rules>\n")
if info.Description != "" { b.WriteString(truncateRunes(info.Rules, 6000))
fmt.Fprintf(&b, "About r/%s: %s\n", sub, oneLine(info.Description)) b.WriteString("\n</subreddit_rules>\n")
} } else {
if info.SubmitText != "" { 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), "+
fmt.Fprintf(&b, "Posting guidelines: %s\n", oneLine(truncateRunes(info.SubmitText, 1500))) "and keep the post useful even if promotion turns out to be forbidden.\n", sub)
}
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")
} }
return b.String() 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 { if !dr.Editable() && dr.Status != StatusScheduled {
return dr, ErrBusy return dr, ErrBusy
} }
if dr.Channel == ChannelReddit {
return dr, ErrByHand
}
pub, as, err := pubs.For(dr) pub, as, err := pubs.For(dr)
if err != nil { if err != nil {
return dr, err return dr, err
+86 -98
View File
@@ -9,97 +9,128 @@ import (
"strings" "strings"
"time" "time"
"supermarket/internal/api/reddit"
"supermarket/internal/db" "supermarket/internal/db"
) )
// SubredditMaxAge is how long a subreddit's cached rules are used before // Reddit posts are always posted by hand: Reddit's API isn't open to
// they're fetched again. // apps like this one. Supermarket writes the post, opens the subreddit's
const SubredditMaxAge = 24 * time.Hour // 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. // Subreddit is what the user told Supermarket about a subreddit: its rules,
func GetSubreddit(d *db.DB, name string) (*reddit.Subreddit, error) { // as pasted from Reddit.
var raw string type Subreddit struct {
err := d.QueryRow(`SELECT data FROM subreddits WHERE name = ?`, reddit.CleanName(name)).Scan(&raw) 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) { if errors.Is(err, sql.ErrNoRows) {
return nil, nil return nil, nil
} }
if err != nil { if err != nil {
return nil, err return nil, err
} }
var s reddit.Subreddit var s Subreddit
if err := json.Unmarshal([]byte(raw), &s); err != nil { if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, err return nil, err
} }
if strings.TrimSpace(s.Rules) == "" {
return nil, nil
}
s.SavedAt = parseTime(at)
return &s, nil return &s, nil
} }
// SaveSubreddit caches a subreddit's rules. // SaveRules keeps the rules pasted for a subreddit. Empty rules forget them.
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error { func SaveRules(d *db.DB, name, rules string, now time.Time) error {
raw, err := json.Marshal(s) 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 { if err != nil {
return err return err
} }
_, err = d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES (?, ?, ?) _, 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`, 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 return err
} }
// Reddit's self-promotion guideline: at most one post in ten about your own // Posting to the same subreddit more than about weekly reads as spam.
// work. Posting to the same subreddit more than about weekly reads as spam. const sameSubWindow = 7 * 24 * time.Hour
const (
ownShareLimit = 0.10
sameSubWindow = 7 * 24 * time.Hour
historyWindow = 30 * 24 * time.Hour
)
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`) 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. // RedditCheck is what the warnings are worked out from.
type RedditCheck struct { type RedditCheck struct {
Target string 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 Promo bool // it promotes the company's own product
Info *reddit.Subreddit // nil if the rules couldn't be read Info *Subreddit // nil if no rules were pasted
History []reddit.Submission // the account's recent posts; nil if unknown Recorded []RedditPost
// 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
Now time.Time Now time.Time
} }
// RedditWarnings lists reasons to think twice before posting. They never // 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 { func RedditWarnings(c RedditCheck) []string {
var w []string var w []string
sub := "r/" + c.Target sub := "r/" + c.Target
if c.Promo { 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.") 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 { if c.Info != nil {
w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.") for _, line := range strings.Split(c.Info.Rules, "\n") {
} else { line = strings.TrimSpace(line)
if c.Info.Type == "restricted" || c.Info.Type == "private" { if promoRule.MatchString(line) {
w = append(w, fmt.Sprintf("%s is %s: only approved users can post.", sub, c.Info.Type)) w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, truncateRunes(line, 200)))
}
if !c.Info.AllowsText() && !c.HasLink {
w = append(w, sub+" only takes link posts, and this draft has no link.")
} else if !c.Info.AllowsText() {
w = append(w, sub+" only takes link posts: it will be posted as the title and the link, without the text.")
}
for _, r := range c.Info.Rules {
if promoRule.MatchString(r.Name + " " + r.Description) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, r.Name))
} }
} }
} }
if c.History == nil {
var inSub []time.Time var inSub []time.Time
for _, s := range c.Recorded { for _, s := range c.Recorded {
if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < sameSubWindow { if strings.EqualFold(s.Subreddit, c.Target) && c.Now.Sub(s.Created) < sameSubWindow {
@@ -111,49 +142,6 @@ func RedditWarnings(c RedditCheck) []string {
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan"))) sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
} }
return w return w
}
if len(c.History) == 0 {
w = append(w, "This account hasn't posted before. Communities often remove a new account's first posts, especially promotional ones: take part in discussions first.")
return w
}
var inSub []time.Time
recent, own := 0, 0
for _, s := range c.History {
age := c.Now.Sub(s.Created)
if strings.EqualFold(s.Subreddit, c.Target) && age < sameSubWindow {
inSub = append(inSub, s.Created)
}
if age < historyWindow {
recent++
if c.Own != nil && (c.Own(s.URL) || containsOwnLink(s.Text, c.Own)) {
own++
}
}
}
if len(inSub) > 0 {
w = append(w, fmt.Sprintf("You posted in %s %d time%s in the past week, last on %s. Most communities expect less.",
sub, len(inSub), plural(len(inSub)), inSub[0].Local().Format("2 Jan")))
}
// Count this post as one more own link, if it has one.
if c.OwnLink {
share := float64(own+1) / float64(recent+1)
if share > ownShareLimit && own+1 > 1 {
w = append(w, fmt.Sprintf("With this one, %d of your %d posts in the past 30 days link to your own sites. Reddit's guideline is at most 1 in 10.",
own+1, recent+1))
}
}
return w
}
var urlPattern = regexp.MustCompile(`https?://[^\s)\]>"]+`)
func containsOwnLink(text string, own func(string) bool) bool {
for _, u := range urlPattern.FindAllString(text, -1) {
if own(u) {
return true
}
}
return false
} }
func plural(n int) string { func plural(n int) string {
@@ -163,24 +151,24 @@ func plural(n int) string {
return "s" return "s"
} }
// RecordedRedditPosts are the Reddit posts Supermarket published, or the // RecordedRedditPosts are the Reddit posts marked as posted (or published)
// user marked as posted, since then, newest first. // since then, newest first.
func RecordedRedditPosts(d *db.DB, since time.Time) ([]reddit.Submission, error) { func RecordedRedditPosts(d *db.DB, since time.Time) ([]RedditPost, error) {
rows, err := d.Query(`SELECT target, title, content, source_url, published_at FROM drafts rows, err := d.Query(`SELECT target, published_at FROM drafts
WHERE channel = ? AND status = ? AND published_at >= ? ORDER BY published_at DESC`, WHERE channel = ? AND status = ? AND published_at >= ? ORDER BY published_at DESC`,
ChannelReddit, StatusPublished, formatTime(since)) ChannelReddit, StatusPublished, formatTime(since))
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer rows.Close() defer rows.Close()
var out []reddit.Submission var out []RedditPost
for rows.Next() { for rows.Next() {
var s reddit.Submission var s RedditPost
var at string 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 return nil, err
} }
s.IsSelf, s.Created = true, parseTime(at) s.Created = parseTime(at)
out = append(out, s) out = append(out, s)
} }
return out, rows.Err() return out, rows.Err()
+58 -38
View File
@@ -2,20 +2,18 @@ package content
import ( import (
"context" "context"
"errors"
"strings" "strings"
"testing" "testing"
"time" "time"
"supermarket/internal/api/reddit"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/utm"
) )
func TestGenerateReddit(t *testing.T) { func TestGenerateReddit(t *testing.T) {
entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner} entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner}
items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}} items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}}
info := &reddit.Subreddit{Name: "selfhosted", Description: "Self-hosting", SubmitText: "Flair your post.", info := &Subreddit{Name: "selfhosted", Rules: "1. No spam: the 10% rule\n2. Flair your post."}
Rules: []reddit.Rule{{Name: "No spam", Description: "10% rule", Kind: "link"}, {Name: "Be civil", Kind: "comment"}}}
f := &fakeAI{replies: []string{`{"x": "Short", "reddit": {"title": " Jitsi 3 is out ", "body": "I work at Acme. Details."}}`}} 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, drafts, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info}) Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info})
@@ -27,13 +25,19 @@ func TestGenerateReddit(t *testing.T) {
t.Fatalf("reddit draft = %+v", r) t.Fatalf("reddit draft = %+v", r)
} }
prompt := f.reqs[0].Prompt 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) { if !strings.Contains(prompt, want) {
t.Errorf("prompt lacks %q", want) t.Errorf("prompt lacks %q", want)
} }
} }
if strings.Contains(prompt, "Be civil") { // Without rules, the model is told they weren't given.
t.Error("comment-only rules needn't go in the prompt") 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) props := f.reqs[0].Schema["properties"].(map[string]any)
if props["reddit"].(map[string]any)["type"] != "object" { if props["reddit"].(map[string]any)["type"] != "object" {
@@ -71,33 +75,56 @@ func TestRedditDraftsAndCache(t *testing.T) {
t.Errorf("problem = %q", got.Problem()) t.Errorf("problem = %q", got.Problem())
} }
// Reddit drafts are posted by hand: never published or scheduled.
pub := &fakePub{} 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) t.Fatal(err)
} }
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") || if rec, _ := RecordedRedditPosts(d, time.Now().Add(-time.Hour)); len(rec) != 1 || rec[0].Subreddit != "selfhosted" {
!strings.Contains(pub.calls[0], "utm_source=reddit") { t.Errorf("recorded = %+v", rec)
t.Errorf("published %q", pub.calls[0])
} }
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil { 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) // A row from before, read through Reddit's API, counts as no rules.
if err := SaveSubreddit(d, &reddit.Subreddit{Name: "selfhosted", SubmissionType: "self", Rules: []reddit.Rule{{Name: "R"}}, FetchedAt: at}); err != nil { if _, err := d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES ('selfhosted', '{"name":"selfhosted","rules":[{"name":"R"}]}', '')`); err != nil {
t.Fatal(err) t.Fatal(err)
} }
s, err := GetSubreddit(d, "r/SelfHosted") if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
if err != nil || s == nil || len(s.Rules) != 1 || !s.FetchedAt.Equal(at) || s.AllowsLinks() { t.Fatalf("old row: %v %v", s, err)
t.Errorf("cached = %+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) { func TestRedditWarnings(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
own := utm.NewTagger([]string{"acme.example"}).Own info := &Subreddit{Name: "selfhosted", Rules: "1. No self-promotion\n2. Be nice"}
info := &reddit.Subreddit{Name: "selfhosted", SubmissionType: "link", Type: "restricted",
Rules: []reddit.Rule{{Name: "No self-promotion"}, {Name: "Be nice"}}}
has := func(ws []string, sub string) bool { has := func(ws []string, sub string) bool {
for _, w := range ws { for _, w := range ws {
@@ -109,29 +136,22 @@ func TestRedditWarnings(t *testing.T) {
} }
w := RedditWarnings(RedditCheck{Target: "selfhosted", Info: info, Now: now}) 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) t.Errorf("rules warnings = %q", w)
} }
if w := RedditWarnings(RedditCheck{Target: "x", Now: now}); !has(w, "Couldn't read r/x's rules") { if w := RedditWarnings(RedditCheck{Target: "x", Promo: true, Now: now}); !has(w, "promotes your own work") {
t.Errorf("no info = %q", w) 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") { recorded := []RedditPost{
t.Errorf("new account = %q", w) {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)},
} }
w = RedditWarnings(RedditCheck{Target: "selfhosted", Recorded: recorded, Now: now})
history := []reddit.Submission{ if !has(w, "posted in r/selfhosted 1 time in the past week") {
{Subreddit: "SelfHosted", URL: "https://acme.example/1", Created: now.Add(-2 * 24 * time.Hour)}, t.Errorf("recorded warnings = %q", w)
{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", Info: &reddit.Subreddit{}, History: history, Own: own, OwnLink: true, HasLink: true, Now: now}) if w := RedditWarnings(RedditCheck{Target: "golang", Recorded: recorded, Now: now}); len(w) != 0 {
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 {
t.Errorf("clean post = %q", w) t.Errorf("clean post = %q", w)
} }
} }
+26 -42
View File
@@ -2,12 +2,11 @@ package inventory
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"regexp"
"strings" "strings"
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile" "supermarket/internal/profile"
"supermarket/internal/site" "supermarket/internal/site"
) )
@@ -18,17 +17,12 @@ const maxFeeds = 3
// maxSubreddits is how many suggested subreddits Fill puts in the box. // maxSubreddits is how many suggested subreddits Fill puts in the box.
const maxSubreddits = 5 const maxSubreddits = 5
// SubredditCheck looks a subreddit up on Reddit. It returns reddit.ErrNotFound // Suggestion is a subreddit the AI suggested. Reddit can't be asked
// or reddit.ErrForbidden for one that doesn't exist or is private. // whether it exists, so the user looks before posting there.
type SubredditCheck func(ctx context.Context, name string) (*reddit.Subreddit, error)
// Suggestion is a subreddit the AI suggested, and what Reddit said about it.
type Suggestion struct { type Suggestion struct {
Name string Name string
Why string // the model's reason Why string // the model's reason
Info *reddit.Subreddit // nil if not checked Kept bool // put in the Subreddits box; false: more than enough already
Kept bool // put in the Subreddits box
Problem string // why it was left out, or why it's unchecked
} }
// FillResult says what Fill did. // 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, // 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 // 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. // 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{} res := &FillResult{}
st, err := site.Read(ctx, siteURL, "Supermarket/1 (inventory draft)") st, err := site.Read(ctx, siteURL, "Supermarket/1 (inventory draft)")
if err != nil { if err != nil {
@@ -125,16 +119,14 @@ func Fill(ctx context.Context, client ai.Client, e *Entry, siteURL string, ours
var keep []string var keep []string
seen := map[string]bool{} seen := map[string]bool{}
for _, sub := range d.Subreddits { for _, sub := range d.Subreddits {
name := reddit.CleanName(sub.Name) name := cleanSubreddit(sub.Name)
if name == "" || seen[strings.ToLower(name)] { if name == "" || seen[strings.ToLower(name)] {
continue continue
} }
seen[strings.ToLower(name)] = true seen[strings.ToLower(name)] = true
sg := checkSubreddit(ctx, check, name, sub.Why) sg := Suggestion{Name: name, Why: strings.TrimSpace(sub.Why), Kept: len(keep) < maxSubreddits}
if sg.Kept && len(keep) < maxSubreddits { if sg.Kept {
keep = append(keep, sg.Name) keep = append(keep, name)
} else if sg.Kept {
sg.Kept, sg.Problem = false, "more than enough already"
} }
res.Suggestions = append(res.Suggestions, sg) 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 return res, nil
} }
// checkSubreddit asks Reddit about a suggested subreddit. One Reddit can't // cleanSubreddit turns "r/selfhosted" or a subreddit URL into
// be asked about (no keys, rate limit) is kept, marked unchecked. // "selfhosted", and drops what can't be a subreddit's name.
func checkSubreddit(ctx context.Context, check SubredditCheck, name, why string) Suggestion { func cleanSubreddit(s string) string {
sg := Suggestion{Name: name, Why: strings.TrimSpace(why), Kept: true} s = strings.TrimSpace(s)
if check == nil { if i := strings.Index(s, "/r/"); i >= 0 {
sg.Problem = "not checked" s = s[i+3:]
return sg
} }
info, err := check(ctx, name) s = strings.TrimPrefix(s, "r/")
switch { if i := strings.IndexAny(s, "/?#"); i >= 0 {
case errors.Is(err, reddit.ErrNotFound): s = s[:i]
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
} }
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. 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: Rules:
@@ -185,7 +169,7 @@ Rules:
Without a company profile, leave talking_points empty. Without a company profile, leave talking_points empty.
- keywords: up to eight phrases they own or compete on. - 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. - 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 { func fillPrompt(e *Entry, ours *profile.Profile, st *site.Site) string {
var b strings.Builder var b strings.Builder
+9 -38
View File
@@ -3,7 +3,6 @@ package inventory
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@@ -11,7 +10,6 @@ import (
"testing" "testing"
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/profile" "supermarket/internal/profile"
) )
@@ -52,7 +50,7 @@ func TestFillKeepsWhatWasTyped(t *testing.T) {
}} }}
e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"} e := &Entry{Name: "Rival", Relationship: Competitor, TwitterHandle: "typed"}
ours := &profile.Profile{Name: "Acme", Description: "Self-hosted widgets."} 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -83,7 +81,7 @@ func TestFillSkipsTheModelWhenNothingIsLeft(t *testing.T) {
fake := &fakeAI{} fake := &fakeAI{}
e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t", e := &Entry{Name: "Rival", Relationship: Partner, Description: "d", TalkingPoints: "t",
Keywords: []string{"k"}, Hashtags: []string{"#h"}, Subreddits: []string{"selfhosted"}} 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) t.Fatal(err)
} }
if fake.calls != 0 { 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) srv := rivalSite(t)
fake := &fakeAI{reply: map[string]any{ fake := &fakeAI{reply: map[string]any{
"name": "", "description": "", "talking_points": "", "keywords": []string{}, "hashtags": []string{}, "name": "", "description": "", "talking_points": "", "keywords": []string{}, "hashtags": []string{},
"subreddits": []map[string]string{ "subreddits": []map[string]string{
{"name": "r/selfhosted", "why": "self-hosters"}, {"name": "r/selfhosted", "why": "self-hosters"},
{"name": "SelfHosted", "why": "again"}, {"name": "SelfHosted", "why": "again"},
{"name": "madeupwidgets", "why": "invented"}, {"name": "not a name!", "why": "junk"},
{"name": "secretclub", "why": "private"}, {"name": "https://www.reddit.com/r/homelab/", "why": "home servers"},
{"name": "announcements", "why": "restricted"}, {"name": "one", "why": ""}, {"name": "two", "why": ""}, {"name": "three", "why": ""}, {"name": "four", "why": ""},
{"name": "homelab", "why": "home servers"},
{"name": "slowreddit", "why": "rate limited"},
}, },
}} }}
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} 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 { if err != nil {
t.Fatal(err) 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) t.Errorf("subreddits = %q", got)
} }
var notes []string var notes []string
for _, sg := range res.Suggestions { for _, sg := range res.Suggestions {
notes = append(notes, fmt.Sprintf("%s:%v", sg.Name, sg.Kept)) 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) 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, // 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. // handler calls Exchange with the code the provider sends back.
package oauth package oauth
@@ -161,69 +161,6 @@ func LinkedInExchange(ctx context.Context, clientID, clientSecret, code string,
return tokenResponse(req) 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 --- // --- shared ---
func tokenResponse(req *http.Request) (*Result, error) { func tokenResponse(req *http.Request) (*Result, error) {
+2 -3
View File
@@ -20,7 +20,7 @@ const (
X = "x" X = "x"
LinkedIn = "linkedin" // a member, posting as themselves LinkedIn = "linkedin" // a member, posting as themselves
LinkedInPage = "linkedin_page" // a company page 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. // 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 // 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 "". // 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 { 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) return fmt.Errorf("no network %q", a.Network)
} }
var id int64 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, ""}, {X, secrets.XAccessToken, secrets.XRefreshToken, ""},
{LinkedIn, secrets.LinkedInAccessToken, "", ""}, {LinkedIn, secrets.LinkedInAccessToken, "", ""},
{LinkedInPage, secrets.LinkedInPageAccessToken, "", ""}, {LinkedInPage, secrets.LinkedInPageAccessToken, "", ""},
{Reddit, secrets.RedditAccessToken, secrets.RedditRefreshToken, ""},
} }
n := 0 n := 0
for _, o := range olds { for _, o := range olds {
+1 -1
View File
@@ -92,7 +92,7 @@ func TestAccounts(t *testing.T) {
func TestAdopt(t *testing.T) { func TestAdopt(t *testing.T) {
d, sec := open(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) exp := time.Now().Add(time.Hour)
n, err := Adopt(d, sec, func(network string) (string, string, time.Time) { n, err := Adopt(d, sec, func(network string) (string, string, time.Time) {
return "n-" + network, "e-" + network, exp return "n-" + network, "e-" + network, exp
-6
View File
@@ -57,12 +57,6 @@ const (
PlausibleAPIKey = "plausible.api_key" PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only 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 // 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) { if s.Secrets.Has(secrets.LinkedInClientID) && s.Secrets.Has(secrets.LinkedInClientSecret) {
d.Connectable = append(d.Connectable, grant{"linkedin", "LinkedIn"}) 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 { for _, ss := range list {
d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID}) 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)"` 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"` 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/"` 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"` 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"` 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"` 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 ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings"
"time" "time"
"supermarket/internal/api/linkedin" "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/rss" "supermarket/internal/api/rss"
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/api/youtube" "supermarket/internal/api/youtube"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/fetcher" "supermarket/internal/fetcher"
"supermarket/internal/oauth"
"supermarket/internal/secrets" "supermarket/internal/secrets"
"supermarket/internal/site" "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)") link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)")
return c.PostUpdate(ctx, post.Text, link) 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}}, {"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", "LinkedIn", "Posting as a person", "/settings/accounts#network-LinkedIn", nil},
{"linkedin_page", "LinkedIn page", "Posting as the company's page", "/settings/accounts", 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}}, {"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}}, {"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}}, {"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) _, _ = s.DB.GetJSON(connChecksKey, &checks)
signins := s.connections() signins := s.connections()
// The posting networks count their accounts. // 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{} postingNames := map[string]string{}
for _, a := range s.postingAccounts() { for _, a := range s.postingAccounts() {
if s.working(a) { if s.working(a) {
@@ -283,8 +282,6 @@ func connectionName(id string) string {
return "linkedin" return "linkedin"
case "linkedin_page": case "linkedin_page":
return liPageProvider return liPageProvider
case "reddit":
return "reddit"
case "google": case "google":
return "google" return "google"
} }
+6 -7
View File
@@ -10,7 +10,6 @@ import (
"time" "time"
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/sitemap" "supermarket/internal/api/sitemap"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/db" "supermarket/internal/db"
@@ -160,7 +159,7 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
seen := map[string]bool{} seen := map[string]bool{}
for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} { for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} {
for _, sr := range list { 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 seen[strings.ToLower(n)] = true
subs = append(subs, n) subs = append(subs, n)
} }
@@ -322,15 +321,15 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
} }
for _, ch := range ordered { for _, ch := range ordered {
if ch == content.ChannelReddit { if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit")) req.Subreddit = content.CleanSubreddit(r.PostForm.Get("subreddit"))
if req.Subreddit == "" { if req.Subreddit == "" {
return errors.New("choose a subreddit for the Reddit post") return errors.New("choose a subreddit for the Reddit post")
} }
// The rules go into the prompt; without them the model is told // The rules pasted for it go into the prompt; without them the
// to be careful, and Posts warns. // model is told to be careful, and Posts asks for them.
info, err := s.subreddit(r.Context(), req.Subreddit, false) info, err := content.GetSubreddit(s.DB, req.Subreddit)
if err != nil { 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 req.SubredditInfo = info
} }
+29 -26
View File
@@ -11,7 +11,6 @@ import (
"testing" "testing"
"time" "time"
"supermarket/internal/api/reddit"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/models" "supermarket/internal/models"
@@ -210,17 +209,22 @@ func TestRedditInInbox(t *testing.T) {
}); err != nil { }); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "selfhosted", SubmitText: "Flair it.", SubmissionType: "self", if err := content.SaveRules(s.DB, "selfhosted", "1. Flair it.\n2. No self-promotion", time.Now()); err != nil {
Rules: []reddit.Rule{{Name: "No self-promotion", Description: "Limit it."}}, FetchedAt: time.Now()}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
body := do(h, http.MethodGet, "/posts", nil, nil).Body.String() 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", for _, want := range []string{"Reddit r/selfhosted", `name="title" id="title-`, `value="Jitsi 3"`, "1. Flair it.", "has a rule about this",
"has a rule about this", "Couldn&#39;t read r/homelab&#39;s rules", `action="/reddit/rules/homelab"`, "Read rules", "text only"} { "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) { if !strings.Contains(body, want) {
t.Errorf("inbox lacks %q", 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) ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
var id string 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") { 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()) 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") { for _, action := range []string{"publish", "schedule"} {
t.Errorf("publish without Reddit: %s", rec.Body.String()) 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())
} }
// Signing in needs the client ID and secret first. // Pasting the rules keeps them; emptying the box forgets them.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusBadRequest { if rec := postForm(h, "/reddit/rules/homelab", url.Values{"rules": {"No memes."}}); rec.Code != http.StatusSeeOther {
t.Errorf("reddit start without credentials: %d", rec.Code) t.Fatalf("save rules: %d %s", rec.Code, rec.Body.String())
} }
_ = s.Secrets.Set(map[string]string{secrets.RedditClientID: "id", secrets.RedditClientSecret: "sec"}) if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr == nil || sr.Rules != "No memes." {
rec := postForm(h, "/auth/reddit/start", nil) t.Errorf("rules = %+v", sr)
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") { postForm(h, "/reddit/rules/homelab", url.Values{"rules": {""}})
t.Errorf("reddit start: %d %s", rec.Code, loc) 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 { }); err != nil {
t.Fatal(err) t.Fatal(err)
} }
_ = content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "linksonly", SubmissionType: "link", FetchedAt: time.Now()})
ids := map[string]string{} ids := map[string]string{}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft) ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
for _, d := range ds { for _, d := range ds {
ids[d.Target] = strconv.FormatInt(d.ID, 10) 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") || 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") 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) 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. // 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") { 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") t.Error("bad post link accepted")
+49 -52
View File
@@ -10,7 +10,6 @@ import (
"strings" "strings"
"time" "time"
"supermarket/internal/api/reddit"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/profile" "supermarket/internal/profile"
"supermarket/internal/utm" "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{ s.render(w, r, "inbox", page{Title: "Posts", Nav: "content/posts", Error: errMsg, Data: map[string]any{
"Reminders": s.reminders(), "Reminders": s.reminders(),
"Sections": sections, "Sections": sections,
"Reddit": s.redditViews(r.Context(), pending), "Reddit": s.redditViews(pending),
"Connected": s.connected(viewerOf(r)), "Connected": s.connected(viewerOf(r)),
"Accounts": s.usableAccounts(viewerOf(r)), "Accounts": s.usableAccounts(viewerOf(r)),
"Chosen": s.chosenAccounts(pending), "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. // redditView is what Posts shows with a Reddit draft.
type redditView struct { 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 Warnings []string
} }
// redditViews works out the rules and warnings for the Reddit drafts. It // redditViews works out the rules and warnings for the Reddit drafts.
// reads the account's recent posts once (cached for a few minutes). func (s *Server) redditViews(drafts []content.Draft) map[int64]*redditView {
func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[int64]*redditView {
views := map[int64]*redditView{} views := map[int64]*redditView{}
var history []reddit.Submission
historyRead := false
tags := s.tagger() tags := s.tagger()
recorded, err := content.RecordedRedditPosts(s.DB, time.Now().Add(-8*24*time.Hour)) recorded, err := content.RecordedRedditPosts(s.DB, time.Now().Add(-8*24*time.Hour))
if err != nil { if err != nil {
s.Log.Error("reading recorded Reddit posts", "err", err) s.Log.Error("reading recorded Reddit posts", "err", err)
} }
for _, d := range drafts { for i, d := range drafts {
if d.Channel != content.ChannelReddit { if d.Channel != content.ChannelReddit {
continue continue
} }
if !historyRead { info, err := content.GetSubreddit(s.DB, d.Target)
hctx, cancel := context.WithTimeout(ctx, 8*time.Second) if err != nil {
history = s.redditHistory(hctx) s.Log.Error("reading a subreddit's rules", "subreddit", d.Target, "err", err)
cancel()
historyRead = true
} }
info, _ := content.GetSubreddit(s.DB, d.Target) check := content.RedditCheck{Target: d.Target, Info: info, Now: time.Now(),
check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now(),
Promo: d.Kind == content.KindProduct, Recorded: recorded} Promo: d.Kind == content.KindProduct, Recorded: recorded}
if tags != nil { views[d.ID] = &redditView{Info: info, RulesURL: content.RulesURL(d.Target),
check.Own = tags.Own Suffix: redditSuffix(&drafts[i], tags), Warnings: content.RedditWarnings(check)}
check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content)
}
views[d.ID] = &redditView{Info: info, Warnings: content.RedditWarnings(check)}
} }
return views return views
} }
// refreshRules fetches a subreddit's rules again. // saveRules keeps the rules pasted for a subreddit.
func (s *Server) refreshRules(w http.ResponseWriter, r *http.Request) { func (s *Server) saveRules(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) if err := r.ParseForm(); err != nil {
defer cancel() http.Error(w, err.Error(), http.StatusBadRequest)
if _, err := s.subreddit(ctx, r.PathValue("name"), true); err != nil {
s.renderInbox(w, r, "Couldn't read the subreddit's rules: "+err.Error())
return 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. // 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) ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel() defer cancel()
var failed []string var failed []string
reddit := false
for _, did := range append([]int64{id}, copies...) { for _, did := range append([]int64{id}, copies...) {
_ = content.SetPostedBy(s.DB, did, by) _ = content.SetPostedBy(s.DB, did, by)
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), did) 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)) failed = append(failed, fmt.Sprintf("Couldn't publish to %s: %v", name, err))
continue continue
} }
reddit = reddit || d.Channel == content.ChannelReddit
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by) 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) s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL)
} }
if reddit {
s.forgetRedditHistory()
}
if len(failed) > 0 { if len(failed) > 0 {
fail(errors.New(strings.Join(failed, " "))) fail(errors.New(strings.Join(failed, " ")))
return return
@@ -363,8 +352,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err) fail(err)
return return
} }
info, _ := content.GetSubreddit(s.DB, d.Target) http.Redirect(w, r, redditSubmitURL(d, s.tagger()), http.StatusSeeOther)
http.Redirect(w, r, redditSubmitURL(d, s.tagger(), info), http.StatusSeeOther)
case "posted": case "posted":
postURL := strings.TrimSpace(r.PostForm.Get("post_url")) postURL := strings.TrimSpace(r.PostForm.Get("post_url"))
if postURL != "" { if postURL != "" {
@@ -377,7 +365,6 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err) fail(err)
return return
} }
s.forgetRedditHistory()
redirect(w, r, back, "posted") redirect(w, r, back, "posted")
case "unschedule": case "unschedule":
if err := content.Unschedule(s.DB, id); err != nil { 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. // and still open; past it, the text is left for the user to paste.
const maxSubmitURL = 7500 const maxSubmitURL = 7500
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled // redditText is what goes in a Reddit post: the draft's text with links to
// in: a text post with the source link at the end, or a link post where the // the company's sites tagged, and the source link at the end.
// subreddit only takes links. It uses old.reddit.com, whose submit page func redditText(d *content.Draft, tags *utm.Tagger) string {
// reliably takes the title and text from the address.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger, info *reddit.Subreddit) string {
text, src := content.Manual(d, tags) 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) { if src != "" && !strings.Contains(text, src) {
text += "\n\nSource: " + src text += "\n\nSource: " + src
} }
q.Set("selftext", "true") return text
q.Set("text", 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 { if u := base + "?" + q.Encode(); len(u) <= maxSubmitURL {
return u return u
} }
+1 -30
View File
@@ -12,8 +12,6 @@ import (
"supermarket/examples" "supermarket/examples"
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory" "supermarket/internal/inventory"
"supermarket/internal/profile" "supermarket/internal/profile"
) )
@@ -39,7 +37,6 @@ type entryData struct {
DraftURL string // the address to fill in from DraftURL string // the address to fill in from
Filled []string // after filling in: what was filled Filled []string // after filling in: what was filled
Suggestions []inventory.Suggestion Suggestions []inventory.Suggestion
CanCheck bool // Reddit could be asked about the suggestions
Drafted bool Drafted bool
Today string // for new price rows Today string // for new price rows
Blank []int // empty price rows to show 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) ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
defer cancel() defer cancel()
check := s.subredditCheck(ctx) res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours)
d.CanCheck = check != nil
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check)
d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true
if err != nil { if err != nil {
// Links read before the model failed are kept. // 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) 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. // marketRoom says why a new entry can't be added (the plan's limit), or nil.
func (s *Server) marketRoom(e *inventory.Entry) error { func (s *Server) marketRoom(e *inventory.Entry) error {
if e.ID != 0 { if e.ID != 0 {
+1 -1
View File
@@ -220,7 +220,7 @@ func (s *Server) connectionSummary(map[string]Connection) string {
parts = append(parts, label) parts = append(parts, label)
} }
if len(parts) == 0 { if len(parts) == 0 {
return "Connect X, LinkedIn or Reddit" return "Connect X or LinkedIn"
} }
return strings.Join(parts, ", ") return strings.Join(parts, ", ")
} }
+4 -35
View File
@@ -11,7 +11,6 @@ import (
"time" "time"
"supermarket/internal/api/linkedin" "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/appmail" "supermarket/internal/appmail"
"supermarket/internal/content" "supermarket/internal/content"
@@ -32,7 +31,7 @@ var adoptMu sync.Mutex
// the company's accounts, the first time they're seen. // the company's accounts, the first time they're seen.
func (s *Server) adoptLegacy() { func (s *Server) adoptLegacy() {
if !s.Secrets.Has(secrets.XAccessToken) && !s.Secrets.Has(secrets.LinkedInAccessToken) && 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 return
} }
adoptMu.Lock() adoptMu.Lock()
@@ -59,9 +58,6 @@ func (s *Server) adoptLegacy() {
return o.Name, o.URN, expiry(conns[liPageProvider]) return o.Name, o.URN, expiry(conns[liPageProvider])
} }
return "the company page", "", 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{} return "", "", time.Time{}
}, time.Now()) }, time.Now())
@@ -127,7 +123,9 @@ func (s *Server) working(a *posting.Account) bool {
func (s *Server) usableAccounts(v *viewer) map[string][]*posting.Account { func (s *Server) usableAccounts(v *viewer) map[string][]*posting.Account {
out := map[string][]*posting.Account{} out := map[string][]*posting.Account{}
for _, a := range s.postingAccounts() { 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) ch := posting.Channel(a.Network)
out[ch] = append(out[ch], a) 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 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 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) 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 // removeAccount signs an account out: scheduled posts to it go back to
// Posts, and their writers are told. // Posts, and their writers are told.
func (s *Server) removeAccount(a *posting.Account, why string) error { 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", ""}, {hit{"Company profile", "Settings · your company, products, websites, voice and targets", "/settings/profile", ""},
"profile company products websites voice tone audience keywords feeds subreddits accounts"}, "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"}, "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", ""}, {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"}, "ai provider model anthropic claude openai ollama lm studio api key hermes effort"},
+3 -11
View File
@@ -25,7 +25,6 @@ import (
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/appmail" "supermarket/internal/appmail"
"supermarket/internal/billing" "supermarket/internal/billing"
@@ -111,12 +110,6 @@ type state struct {
// teamCache is what's kept in memory for a team. // teamCache is what's kept in memory for a team.
type teamCache struct { type teamCache struct {
mu sync.Mutex 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. // Google's access token, which lasts an hour.
googleToken string googleToken string
googleExpires time.Time googleExpires time.Time
@@ -448,7 +441,7 @@ func (s *Server) Handler() (http.Handler, error) {
redirect(w, r, "/posts", r.URL.Query().Get("msg")) redirect(w, r, "/posts", r.URL.Query().Get("msg"))
}) })
mux.HandleFunc("POST /drafts/{id}/{action}", (*Server).draftAction) 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", (*Server).prospectsPage)
mux.HandleFunc("GET /prospects/new", (*Server).prospectForm) mux.HandleFunc("GET /prospects/new", (*Server).prospectForm)
@@ -870,7 +863,7 @@ type module struct {
} }
var modules = []module{ 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"}, {"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"}, {"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"}, {"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.", "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.", "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.", "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-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.", "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.", "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.", "prospect-exists": "Already there: nothing new was added. It's in the list below.",
"outcome": "Outcome recorded.", "outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.", "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": "Imported.",
"imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.", "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.", "hunter-done": "Hunter.io search done: the result is on the card.",
+2 -37
View File
@@ -11,7 +11,6 @@ import (
"supermarket/internal/ai" "supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin" linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter" "supermarket/internal/api/twitter"
"supermarket/internal/oauth" "supermarket/internal/oauth"
"supermarket/internal/posting" "supermarket/internal/posting"
@@ -158,7 +157,6 @@ type secretField struct {
const ( const (
xConsole = "https://console.x.com" xConsole = "https://console.x.com"
linkedInApps = "https://www.linkedin.com/developers/apps" linkedInApps = "https://www.linkedin.com/developers/apps"
redditApps = "https://www.reddit.com/prefs/apps"
googleCreds = "https://console.cloud.google.com/apis/credentials" googleCreds = "https://console.cloud.google.com/apis/credentials"
anthropicKeys = "https://platform.claude.com/settings/keys" 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}, "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", {"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps}, "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", {"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}, "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...) set := s.secretState(names...)
accts := s.postingAccounts() 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 { 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} c := &connectInfo{Provider: provider, Redirect: s.callbackURL(provider), Setup: setup, Note: note, Ready: ready}
for _, a := range accts { for _, a := range accts {
@@ -276,7 +270,7 @@ func (s *Server) networks() []network {
} }
} }
var nets []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} n := network{Name: name, Set: set}
for _, f := range accountFields { for _, f := range accountFields {
if f.Group == name { 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 }) set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry() n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup() 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) nets = append(nets, n)
} }
@@ -395,13 +385,6 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return return
} }
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes()) 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": case "google":
id := s.Secrets.Get(secrets.GoogleClientID) id := s.Secrets.Get(secrets.GoogleClientID)
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) { if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
@@ -632,24 +615,6 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
return return
} }
redirect(w, r, "/settings/accounts", "li-page-connected") 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: default:
http.NotFound(w, r) http.NotFound(w, r)
} }
+2
View File
@@ -67,6 +67,8 @@
if (src && navigator.clipboard) { if (src && navigator.clipboard) {
// A field's current value (with edits), else an element's text. // A field's current value (with edits), else an element's text.
var value = "value" in src ? src.value : src.textContent; 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 () { navigator.clipboard.writeText(value).then(function () {
var label = copy.textContent; var label = copy.textContent;
copy.textContent = "Copied"; copy.textContent = "Copied";
+2 -2
View File
@@ -78,12 +78,12 @@
<legend>Channels</legend> <legend>Channels</legend>
{{range .Channels}} {{range .Channels}}
{{/* Reddit is never pre-checked: each post there is a deliberate choice. */}} {{/* 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}} {{end}}
<label class="small">Subreddit, for Reddit <label class="small">Subreddit, for Reddit
<input name="subreddit" list="subreddits" placeholder="e.g. selfhosted" autocomplete="off"> <input name="subreddit" list="subreddits" placeholder="e.g. selfhosted" autocomplete="off">
<datalist id="subreddits">{{range .Subreddits}}<option value="{{.}}">{{end}}</datalist> <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> </label>
</fieldset> </fieldset>
{{if .Signals}} {{if .Signals}}
+3 -5
View File
@@ -6,7 +6,7 @@
<input type="hidden" name="id" value="{{$e.ID}}"> <input type="hidden" name="id" value="{{$e.ID}}">
<section class="card"> <section class="card">
<h2>Fill in with AI</h2> <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}} {{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"> <div class="row">
<input name="draft_url" type="text" inputmode="url" value="{{.DraftURL}}" placeholder="https://example.com" aria-label="Their website"> <input name="draft_url" type="text" inputmode="url" value="{{.DraftURL}}" placeholder="https://example.com" aria-label="Their website">
@@ -17,18 +17,16 @@
{{with .Suggestions}} {{with .Suggestions}}
<details class="suggestions" open> <details class="suggestions" open>
<summary>Subreddits the AI suggested</summary> <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> <ul>
{{range .}} {{range .}}
<li class="{{if .Kept}}kept{{else}}dropped{{end}}"> <li class="{{if .Kept}}kept{{else}}dropped{{end}}">
<a href="https://www.reddit.com/r/{{.Name}}/" target="_blank" rel="noopener noreferrer">r/{{.Name}}</a> <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 not .Kept}}<span class="small">left out: more than enough already</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}}
{{with .Why}}<span class="help">{{.}}</span>{{end}} {{with .Why}}<span class="help">{{.}}</span>{{end}}
</li> </li>
{{end}} {{end}}
</ul> </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> </details>
{{end}} {{end}}
</section> </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}} {{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$accounts := .Accounts}}{{$chosen := .Chosen}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Posts</h1> <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> {{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
{{template "reminders" .Reminders}} {{template "reminders" .Reminders}}
@@ -23,26 +23,37 @@
{{$rv := index $reddit .ID}} {{$rv := index $reddit .ID}}
{{if $rv}} {{if $rv}}
{{if $rv.Warnings}}<ul class="warnings">{{range $rv.Warnings}}<li>{{.}}</li>{{end}}</ul>{{end}} {{if $rv.Warnings}}<ul class="warnings">{{range $rv.Warnings}}<li>{{.}}</li>{{end}}</ul>{{end}}
{{with $rv.Info}} <details class="rules" {{if not $rv.Info}}open{{end}}>
<details class="rules"> <summary>r/{{.Target}}'s rules{{with $rv.Info}} · pasted {{ago .SavedAt}}{{else}} · not pasted yet{{end}}</summary>
<summary>r/{{.Name}}'s rules{{if .Rules}} ({{len .Rules}}){{end}} · read {{ago .FetchedAt}}</summary> <form method="post" action="/reddit/rules/{{.Target}}">
{{if .SubmitText}}<p class="guidelines">{{truncate 1200 .SubmitText}}</p>{{end}} <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>
{{if .Rules}}<ol>{{range .Rules}}<li><strong>{{.Name}}</strong>{{if .Description}}: {{truncate 500 .Description}}{{end}}</li>{{end}}</ol>{{end}} <textarea name="rules" rows="6" aria-label="r/{{.Target}}'s rules" placeholder="Paste the rules here">{{with $rv.Info}}{{.Rules}}{{end}}</textarea>
<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> <button type="submit" class="secondary small">Save rules</button>
</form>
</details> </details>
{{end}} {{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…"> <form method="post" action="/drafts/{{.ID}}/save" data-busy-on="publish" data-busy="Publishing…">
{{if eq .Channel "reddit"}} {{if eq .Channel "reddit"}}
<label class="small">Title <label class="small">Title
<input name="title" value="{{.Title}}" maxlength="300" required> <input name="title" id="title-{{.ID}}" value="{{.Title}}" maxlength="300" required>
</label> </label>
{{end}} {{end}}
<textarea name="content" rows="{{if eq .Channel "x"}}5{{else}}12{{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}}" 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> 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"}}{{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}} {{$d := .}}{{$accts := index $accounts .Channel}}
{{if $accts}} {{if $accts}}
<fieldset class="post-as"> <fieldset class="post-as">
@@ -62,15 +73,8 @@
</label> </label>
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/schedule">Schedule</button> <button type="submit" class="secondary" formaction="/drafts/{{.ID}}/schedule">Schedule</button>
</div> </div>
{{if eq .Channel "reddit"}} {{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}}
<div class="by-hand"> {{end}}
<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}}
</form> </form>
{{if eq .Channel "reddit"}} {{if eq .Channel "reddit"}}
<form method="post" action="/drafts/{{.ID}}/posted" class="by-hand-done"> <form method="post" action="/drafts/{{.ID}}/posted" class="by-hand-done">