Phase 1, part 3: Reddit

- Sign in with a Reddit web app; access tokens refresh automatically,
  and an app-only token reads rules before sign-in.
- Reddit drafts: a title and text for one subreddit, chosen when
  writing. The subreddit's guidelines and rules go into the prompt, which
  asks for a community member's post that discloses the affiliation and
  avoids marketing language.
- The Inbox shows the subreddit's rules (cached for a day, with Refresh)
  and warns, without blocking, about promotion rules, restricted
  subreddits, link-only subreddits, posting in the same subreddit within
  a week, more than 1 in 10 recent posts linking to the company's sites,
  and new accounts.
- Publishing makes a text post with the source link at the end, or a
  link post where the subreddit takes only links.
- Migration 4 adds the draft's title and subreddit, and the rules cache.
  Publishers now take a Post, which carries the title and subreddit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 13:51:16 -07:00
co-authored by Claude Opus 5.5
parent b0f06058ec
commit 0e34f574b7
27 changed files with 1404 additions and 91 deletions
+30 -18
View File
@@ -330,7 +330,7 @@ mcphub failed.
### Phase 1: Content (today's pipeline, generalized) + Reddit
**Status (2026-11-20): parts 1 and 2 of 4 built on `phase0-foundation`.** Phase 1 is
**Status (2026-11-20): parts 1, 2 and 3 of 4 built on `phase0-foundation`.** Phase 1 is
built in four parts, each committed on its own: (1) the pipeline, items 1–2
below, for X and LinkedIn; (2) the approval inbox, schedule and UTM tags,
item 5; (3) Reddit, item 4; (4) promoting our own products, the rest of
@@ -366,7 +366,28 @@ Part 2 (commit `f275f03`):
- The container now runs in the computer's time zone (`SUPERMARKET_TZ` in
compose.env, from /etc/localtime), so times show and parse correctly.
**Not yet tried for real.** Parts 1 and 2 are covered by tests with fake AI
Part 3, Reddit:
- A third channel, `reddit`: a draft has a `title` and a `target`
subreddit (migration 4), chosen when writing, with suggestions from the
entry's and the profile's subreddits. Reddit is never pre-checked.
- Sign-in through a Reddit "web app" (`duration=permanent`; scopes
identity, submit, read, history). The hour-long access token is
refreshed on a 401 and saved. Before sign-in, rules are read with an
app-only token (client credentials).
- Subreddit info (description, posting guidelines, rules, allowed post
types) is cached in `subreddits` for a day. It goes into the prompt and
is shown with the draft, with a Refresh button.
- The prompt asks for a community member's post that says where they work:
no hashtags, emoji or marketing language, following the rules.
- Publishing: a text post with "Source: <link>" at the end, or a link post
where the subreddit takes only links.
- Warnings, never blocking (`content.RedditWarnings`): promotion-related
rules, restricted subreddits, wrong post type, a post in the same
subreddit in the past 7 days, more than 1 in 10 recent posts linking to
the company's own sites (counting this one), and a new account. They use
the account's last 100 posts, cached for 10 minutes.
**Not yet tried for real.** Parts 1–3 are covered by tests with fake AI
and channel clients, and the rebuilt app runs (schema 3). But the
installed app has no profile, AI key, inventory or social sign-ins yet, so no
real fetch, generation or post has been made. Before relying on it:
@@ -376,6 +397,9 @@ real fetch, generation or post has been made. Before relying on it:
3. Connect X and LinkedIn, publish one draft now, schedule one a few
minutes ahead, and check that both go out, with UTM tags on a link to
the company's site.
4. Register a Reddit web app, connect it, write a Reddit draft for a
subreddit, and check its rules and warnings. Post to a test subreddit
you moderate first.
The database before migration 2 is backed up at
`~/.local/share/supermarket/app.db.pre-phase1`. Commits on
@@ -384,23 +408,11 @@ so `git push` can't prompt from Claude Code). The branch stays off `main`
until the user decides to merge; posting works again now, which was the
condition for merging.
**To pick this up: part 3, Reddit** (item 4):
- OAuth for a Reddit "web app" (callback
`http://localhost:8470/auth/reddit/callback`), stored like X's and
LinkedIn's tokens, with refresh. A third channel, `reddit`: a draft is a
title plus body, written for one subreddit.
- Subreddits come from the profile's accounts and the inventory entries.
Show each subreddit's rules (`/r/<sub>/about/rules`) next to the draft,
and its self-promotion limits.
- Every Reddit post needs explicit approval, so never "publish all".
Warn about posting too often: per subreddit, and the share of the
account's posts that link to the company.
- Caveat: Reddit's Data API terms require approval for commercial use.
Low-volume, human-approved posting from a personal app is the intended
scope; say so in the README.
**To pick this up: part 4, own-product promotion** (the rest of item 3):
drafts from the product list, the company's blog RSS, site pages and
releases, with `kind` = `product`.
Then part 4, own-product promotion: drafts from the product list, the
company's blog RSS, site pages and releases, with `kind` = `product`.
The plan for Phase 1, as first written:
1. Port fetch → browse → select → generate → approve → publish into the web
UI, keeping the dismiss feature, tracking of what was posted where, partial
posting, and X length handling.
+17 -4
View File
@@ -6,13 +6,13 @@ Everything starts from your **company profile** (what you sell, to whom, in what
| 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, in progress: X and LinkedIn work |
| Content | Drafts posts from partner and competitor news and your own products; you review them and publish to X, LinkedIn and Reddit | Phase 1, in progress: X, LinkedIn and Reddit work |
| 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 |
| 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 |
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 most of the Content module (Phase 1): fetching, writing drafts, an Inbox for approval, scheduled publishing to X and LinkedIn, 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 most of the Content module (Phase 1): fetching, writing drafts, an Inbox for approval, scheduled publishing to X, LinkedIn and Reddit, and UTM tags. See [PLAN.md](PLAN.md) for the whole plan.
## Install
@@ -103,12 +103,25 @@ Links to your own websites and product pages (from the profile) get UTM tags whe
Reading X needs a bearer token from an X API plan with read access; YouTube needs a free API key; RSS needs nothing. Posting needs the sign-ins below.
## Signing in to X and LinkedIn
### 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 the Inbox. 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.
Before you publish, the Inbox warns, without blocking, when:
- 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.
## Signing in to X, LinkedIn and Reddit
Sign-ins come back to Supermarket at `http://localhost:8470/auth/<provider>/callback`. Register these callback URLs in your apps:
- X developer portal, your app's *User authentication settings*: `http://localhost:8470/auth/x/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 → Credentials
The old terminal app used `http://localhost:8080/callback`; you can remove that one.
@@ -138,7 +151,7 @@ SUPERMARKET_DATA=/tmp/cm SUPERMARKET_ADDR=127.0.0.1:8470 go run ./cmd/supermarke
| `internal/legacy` | One-time import from the old terminal app |
| `internal/content` | The Content module: fetched items, per-channel drafts, prompts, scheduling, publishing |
| `internal/utm` | UTM tags for links to the company's own sites |
| `internal/api`, `internal/fetcher` | X, LinkedIn, YouTube and RSS clients, and fetching for an inventory entry |
| `internal/api`, `internal/fetcher` | X, LinkedIn, Reddit, YouTube and RSS clients, and fetching for an inventory entry |
| `hermes/setup.sh` | Connects Hermes |
Database changes go in `internal/db/db.go` as a new migration; never edit one that has shipped.
+297
View File
@@ -0,0 +1,297 @@
// 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 → Credentials")
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 fmt.Errorf("Reddit said 403 Forbidden: the subreddit may be private, or the account banned from it")
case res.StatusCode == http.StatusNotFound:
return fmt.Errorf("Reddit said 404: no such subreddit or user")
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
}
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
@@ -0,0 +1,85 @@
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)
}
}
}
+6 -2
View File
@@ -83,8 +83,12 @@ type fakePub struct {
err error
}
func (f *fakePub) Publish(_ context.Context, text, src string) (string, error) {
f.calls = append(f.calls, text+"|"+src)
func (f *fakePub) Publish(_ context.Context, p Post) (string, error) {
call := p.Text + "|" + p.SourceURL
if p.Target != "" {
call = "r/" + p.Target + "|" + p.Title + "|" + call
}
f.calls = append(f.calls, call)
if f.err != nil {
return "", f.err
}
+53 -6
View File
@@ -19,8 +19,12 @@ import (
const (
ChannelX = "x"
ChannelLinkedIn = "linkedin"
ChannelReddit = "reddit"
)
// RedditTitleLimit is the longest title Reddit takes.
const RedditTitleLimit = 300
// Channel describes where drafts are published.
type Channel struct {
ID string
@@ -32,6 +36,7 @@ type Channel struct {
var Channels = []Channel{
{ChannelX, "X", 280},
{ChannelLinkedIn, "LinkedIn", 3000},
{ChannelReddit, "Reddit", 40000},
}
// ChannelByID returns the channel, or false.
@@ -61,6 +66,8 @@ type Draft struct {
InventoryName string
Kind string // the entry's relationship
Channel string
Title string // Reddit only
Target string // Reddit: the subreddit, without r/
Content string
SourceURL string // added when publishing: appended on X, a link preview on LinkedIn
ItemIDs []string
@@ -94,7 +101,36 @@ func (d *Draft) Limit() int {
}
// TooLong reports whether the draft can't be published as it is.
func (d *Draft) TooLong() bool { return d.Length() > d.Limit() }
func (d *Draft) TooLong() bool {
return d.Length() > d.Limit() || utf8.RuneCountInString(d.Title) > RedditTitleLimit
}
// Problem says what stops the draft from being published, or "".
func (d *Draft) Problem() string {
switch {
case d.Channel == ChannelReddit && strings.TrimSpace(d.Title) == "":
return "the Reddit post needs a title"
case d.Channel == ChannelReddit && d.Target == "":
return "the Reddit post has no subreddit"
case utf8.RuneCountInString(d.Title) > RedditTitleLimit:
return fmt.Sprintf("the title is %d characters; Reddit allows %d", utf8.RuneCountInString(d.Title), RedditTitleLimit)
case d.Length() > d.Limit():
withLink := ""
if d.Channel == ChannelX && d.SourceURL != "" {
withLink = " including the link"
}
return fmt.Sprintf("the post is %d characters%s; %s allows %d", d.Length(), withLink, d.ChannelName(), d.Limit())
}
return ""
}
// Where is the channel plus, for Reddit, the subreddit: "Reddit r/golang".
func (d *Draft) Where() string {
if d.Target != "" {
return d.ChannelName() + " r/" + d.Target
}
return d.ChannelName()
}
// ChannelName is the channel's display name.
func (d *Draft) ChannelName() string {
@@ -131,9 +167,9 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
return "", fmt.Errorf("unknown channel %q", dr.Channel)
}
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, content, source_url, item_ids)
VALUES (?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil {
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil {
return "", err
}
for _, id := range dr.ItemIDs {
@@ -157,7 +193,7 @@ func nonNil(s []string) []string {
}
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, '')`
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target`
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close()
@@ -166,7 +202,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
var dr Draft
var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt); err != nil {
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
@@ -320,3 +356,14 @@ func FailScheduled(d *db.DB, id int64, reason string) error {
StatusFailed, reason, formatTime(time.Now()), id, StatusScheduled)
return oneRow(res, err)
}
// UpdateTitle saves an edited Reddit title.
func UpdateTitle(d *db.DB, id int64, title string) error {
title = strings.Join(strings.Fields(title), " ")
if title == "" {
return errors.New("the title is empty")
}
res, err := d.Exec(`UPDATE drafts SET title = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?)`,
title, formatTime(time.Now()), id, ChannelReddit, StatusDraft, StatusFailed)
return oneRow(res, err)
}
+79 -2
View File
@@ -2,11 +2,13 @@ package content
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/inventory"
"supermarket/internal/profile"
@@ -18,6 +20,10 @@ type Request struct {
Entry *inventory.Entry
Items []Item
Channels []string // channel IDs, in Channels order
// Reddit: the subreddit to write for, and what's known about it (nil
// if its rules couldn't be read).
Subreddit string
SubredditInfo *reddit.Subreddit
}
// SourceURL is the link the drafts carry: the first item's.
@@ -55,15 +61,30 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
if _, ok := ChannelByID(ch); !ok {
return nil, fmt.Errorf("unknown channel %q", ch)
}
if ch == ChannelReddit && req.Subreddit == "" {
return nil, errors.New("choose a subreddit to write the Reddit post for")
}
}
src := req.SourceURL()
props := map[string]any{}
for _, ch := range req.Channels {
c, _ := ChannelByID(ch)
if ch == ChannelReddit {
props[ch] = map[string]any{
"type": "object",
"properties": map[string]any{
"title": map[string]any{"type": "string", "description": "The post's title"},
"body": map[string]any{"type": "string", "description": "The post's text"},
},
"required": []string{"title", "body"},
"additionalProperties": false,
}
continue
}
props[ch] = map[string]any{"type": "string", "description": "The " + c.Name + " post"}
}
var out map[string]string
var out map[string]json.RawMessage
err := ai.GenerateJSON(ctx, client, ai.Request{
Task: ai.TaskContent,
System: systemPrompt(req.Profile),
@@ -86,7 +107,24 @@ func Generate(ctx context.Context, client ai.Client, req Request) ([]Draft, erro
}
var drafts []Draft
for _, ch := range req.Channels {
text := strings.TrimSpace(out[ch])
if ch == ChannelReddit {
var rp struct{ Title, Body string }
_ = json.Unmarshal(out[ch], &rp)
if strings.TrimSpace(rp.Body) == "" || strings.TrimSpace(rp.Title) == "" {
return nil, errors.New("the model wrote no Reddit title or text")
}
title := strings.Join(strings.Fields(rp.Title), " ")
if r := []rune(title); len(r) > RedditTitleLimit {
title = string(r[:RedditTitleLimit-1]) + "…"
}
drafts = append(drafts, Draft{InventoryName: req.Entry.Name, Kind: req.Entry.Relationship, Channel: ch,
Title: title, Target: reddit.CleanName(req.Subreddit), Content: strings.TrimSpace(rp.Body),
SourceURL: src, ItemIDs: ids, Status: StatusDraft})
continue
}
var text string
_ = json.Unmarshal(out[ch], &text)
text = strings.TrimSpace(text)
if text == "" {
return nil, fmt.Errorf("the model wrote nothing for %s", ch)
}
@@ -227,6 +265,8 @@ func userPrompt(req Request, src string) string {
case ChannelLinkedIn:
fmt.Fprintf(&b, "- linkedin: a LinkedIn post, usually 400 to 1,300 characters and never more than %d. "+
"A strong first line, short paragraphs, then up to 3 hashtags on the last line. Plain text, no markdown.\n", limit)
case ChannelReddit:
b.WriteString(redditInstructions(req))
}
}
if src != "" {
@@ -238,3 +278,40 @@ func userPrompt(req Request, src string) string {
func oneLine(s string) string {
return strings.Join(strings.Fields(s), " ")
}
// redditInstructions asks for a post that a community would welcome: Reddit
// punishes marketing, so the rules are stricter than for other channels.
func redditInstructions(req Request) string {
var b strings.Builder
sub := reddit.CleanName(req.Subreddit)
fmt.Fprintf(&b, "- reddit: an object with a title (at most %d characters) and a body, for r/%s. "+
"Write as a member of the community who works at %s, and say so plainly in the body (\"I work at %s\"). "+
"Lead with what's useful or interesting to this community, not with the company. No hashtags, no emoji, no marketing language, "+
"no calls to action. Usually 80 to 250 words, in Reddit's markdown. The title must read like a normal post title, not a headline ad. "+
"Follow the subreddit's rules below; if they forbid promotion, write a genuine discussion post that doesn't promote anything.\n",
RedditTitleLimit, sub, req.Profile.Name, req.Profile.Name)
if info := req.SubredditInfo; info != nil {
b.WriteString("<subreddit>\n")
if info.Description != "" {
fmt.Fprintf(&b, "About r/%s: %s\n", sub, oneLine(info.Description))
}
if info.SubmitText != "" {
fmt.Fprintf(&b, "Posting guidelines: %s\n", oneLine(truncateRunes(info.SubmitText, 1500)))
}
for i, r := range info.Rules {
if r.Kind == "comment" {
continue
}
fmt.Fprintf(&b, "Rule %d: %s. %s\n", i+1, r.Name, oneLine(truncateRunes(r.Description, 400)))
}
b.WriteString("</subreddit>\n")
}
return b.String()
}
func truncateRunes(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n]) + "…"
}
return s
}
+12 -9
View File
@@ -10,9 +10,17 @@ import (
"supermarket/internal/utm"
)
// Post is what a publisher sends.
type Post struct {
Text string
SourceURL string // tagged, if it's the company's
Title string // Reddit
Target string // Reddit: the subreddit
}
// Publisher posts to one channel and returns the post's URL.
type Publisher interface {
Publish(ctx context.Context, text, sourceURL string) (string, error)
Publish(ctx context.Context, p Post) (string, error)
}
// Publishers are the channels that can post now, by channel ID.
@@ -39,13 +47,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
if pub == nil {
return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Credentials", dr.ChannelName())
}
if dr.TooLong() {
withLink := ""
if dr.Channel == ChannelX && dr.SourceURL != "" {
withLink = " including the link"
}
return dr, fmt.Errorf("the post is %d characters%s; %s allows %d. Shorten it first",
dr.Length(), withLink, dr.ChannelName(), dr.Limit())
if problem := dr.Problem(); problem != "" {
return dr, fmt.Errorf("%s. Fix it first", problem)
}
res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
@@ -62,7 +65,7 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
p := dr.UTM()
text, src = tags.Text(text, p), tags.URL(src, p)
}
postURL, pubErr := pub.Publish(ctx, text, src)
postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target})
now := formatTime(time.Now())
if pubErr != nil {
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`,
+145
View File
@@ -0,0 +1,145 @@
package content
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/db"
)
// SubredditMaxAge is how long a subreddit's cached rules are used before
// they're fetched again.
const SubredditMaxAge = 24 * time.Hour
// GetSubreddit returns the cached subreddit, or nil.
func GetSubreddit(d *db.DB, name string) (*reddit.Subreddit, error) {
var raw string
err := d.QueryRow(`SELECT data FROM subreddits WHERE name = ?`, reddit.CleanName(name)).Scan(&raw)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
var s reddit.Subreddit
if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, err
}
return &s, nil
}
// SaveSubreddit caches a subreddit's rules.
func SaveSubreddit(d *db.DB, s *reddit.Subreddit) error {
raw, err := json.Marshal(s)
if err != nil {
return err
}
_, err = d.Exec(`INSERT INTO subreddits (name, data, fetched_at) VALUES (?, ?, ?)
ON CONFLICT (name) DO UPDATE SET data = excluded.data, fetched_at = excluded.fetched_at`,
s.Name, string(raw), formatTime(s.FetchedAt))
return err
}
// Reddit's self-promotion guideline: at most one post in ten about your own
// work. Posting to the same subreddit more than about weekly reads as spam.
const (
ownShareLimit = 0.10
sameSubWindow = 7 * 24 * time.Hour
historyWindow = 30 * 24 * time.Hour
)
var promoRule = regexp.MustCompile(`(?i)promot|advertis|spam|marketing|self-?post|affiliat|commercial|vendor|blogspam`)
// RedditCheck is what the warnings are worked out from.
type RedditCheck struct {
Target string
HasLink bool // the draft carries a link
OwnLink bool // to the company's own site
Info *reddit.Subreddit // nil if the rules couldn't be read
History []reddit.Submission // the account's recent posts; nil if unknown
Own func(url string) bool
Now time.Time
}
// RedditWarnings lists reasons to think twice before posting. They never
// block publishing: the user decides.
func RedditWarnings(c RedditCheck) []string {
var w []string
sub := "r/" + c.Target
if c.Info == nil {
w = append(w, "Couldn't read "+sub+"'s rules: check them on Reddit before posting.")
} else {
if c.Info.Type == "restricted" || c.Info.Type == "private" {
w = append(w, fmt.Sprintf("%s is %s: only approved users can post.", sub, c.Info.Type))
}
if !c.Info.AllowsText() && !c.HasLink {
w = append(w, sub+" only takes link posts, and this draft has no link.")
} else if !c.Info.AllowsText() {
w = append(w, sub+" only takes link posts: it will be posted as the title and the link, without the text.")
}
for _, r := range c.Info.Rules {
if promoRule.MatchString(r.Name + " " + r.Description) {
w = append(w, fmt.Sprintf("%s has a rule about this: “%s”.", sub, r.Name))
}
}
}
if c.History == nil {
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 {
if n == 1 {
return ""
}
return "s"
}
+137
View File
@@ -0,0 +1,137 @@
package content
import (
"context"
"strings"
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/inventory"
"supermarket/internal/utm"
)
func TestGenerateReddit(t *testing.T) {
entry := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner}
items := []Item{{ContentItem: item("1", "Jitsi", time.Now())}}
info := &reddit.Subreddit{Name: "selfhosted", Description: "Self-hosting", SubmitText: "Flair your post.",
Rules: []reddit.Rule{{Name: "No spam", Description: "10% rule", Kind: "link"}, {Name: "Be civil", Kind: "comment"}}}
f := &fakeAI{replies: []string{`{"x": "Short", "reddit": {"title": " Jitsi 3 is out ", "body": "I work at Acme. Details."}}`}}
drafts, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items,
Channels: []string{ChannelX, ChannelReddit}, Subreddit: "r/selfhosted", SubredditInfo: info})
if err != nil {
t.Fatal(err)
}
r := drafts[1]
if r.Channel != ChannelReddit || r.Title != "Jitsi 3 is out" || r.Target != "selfhosted" || r.Content != "I work at Acme. Details." {
t.Fatalf("reddit draft = %+v", r)
}
prompt := f.reqs[0].Prompt
for _, want := range []string{"r/selfhosted", "I work at Acme", "No hashtags", "Flair your post.", "Rule 1: No spam"} {
if !strings.Contains(prompt, want) {
t.Errorf("prompt lacks %q", want)
}
}
if strings.Contains(prompt, "Be civil") {
t.Error("comment-only rules needn't go in the prompt")
}
props := f.reqs[0].Schema["properties"].(map[string]any)
if props["reddit"].(map[string]any)["type"] != "object" {
t.Errorf("reddit schema = %v", props["reddit"])
}
// A Reddit draft needs a subreddit.
if _, err := Generate(context.Background(), f, Request{Profile: testProfile(), Entry: entry, Items: items, Channels: []string{ChannelReddit}}); err == nil {
t.Error("expected an error without a subreddit")
}
}
func TestRedditDraftsAndCache(t *testing.T) {
d := openDB(t)
_, err := CreateDrafts(d, []Draft{{Channel: ChannelReddit, Title: "Hi", Target: "selfhosted", Content: "Body", SourceURL: "https://acme.example/a"}})
if err != nil {
t.Fatal(err)
}
ds, _ := ListDrafts(d, 1, StatusDraft)
dr := ds[0]
if dr.Title != "Hi" || dr.Target != "selfhosted" || dr.Where() != "Reddit r/selfhosted" || dr.Problem() != "" {
t.Fatalf("draft = %+v (%s)", dr, dr.Problem())
}
if err := UpdateTitle(d, dr.ID, " New title "); err != nil {
t.Fatal(err)
}
if err := UpdateTitle(d, dr.ID, " "); err == nil {
t.Error("empty title accepted")
}
got, _ := GetDraft(d, dr.ID)
if got.Title != "New title" {
t.Errorf("title = %q", got.Title)
}
got.Title = strings.Repeat("t", 301)
if !strings.Contains(got.Problem(), "title is 301") {
t.Errorf("problem = %q", got.Problem())
}
pub := &fakePub{}
if _, err := Publish(context.Background(), d, Publishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") ||
!strings.Contains(pub.calls[0], "utm_source=reddit") {
t.Errorf("published %q", pub.calls[0])
}
if s, err := GetSubreddit(d, "selfhosted"); s != nil || err != nil {
t.Fatalf("empty cache: %v %v", s, err)
}
at := time.Now().UTC().Truncate(time.Second)
if err := SaveSubreddit(d, &reddit.Subreddit{Name: "selfhosted", SubmissionType: "self", Rules: []reddit.Rule{{Name: "R"}}, FetchedAt: at}); err != nil {
t.Fatal(err)
}
s, err := GetSubreddit(d, "r/SelfHosted")
if err != nil || s == nil || len(s.Rules) != 1 || !s.FetchedAt.Equal(at) || s.AllowsLinks() {
t.Errorf("cached = %+v, %v", s, err)
}
}
func TestRedditWarnings(t *testing.T) {
now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
own := utm.NewTagger([]string{"acme.example"}).Own
info := &reddit.Subreddit{Name: "selfhosted", SubmissionType: "link", Type: "restricted",
Rules: []reddit.Rule{{Name: "No self-promotion"}, {Name: "Be nice"}}}
has := func(ws []string, sub string) bool {
for _, w := range ws {
if strings.Contains(w, sub) {
return true
}
}
return false
}
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") {
t.Errorf("rules warnings = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Now: now}); !has(w, "Couldn't read r/x's rules") {
t.Errorf("no info = %q", w)
}
if w := RedditWarnings(RedditCheck{Target: "x", Info: &reddit.Subreddit{}, History: []reddit.Submission{}, Now: now}); !has(w, "hasn't posted before") {
t.Errorf("new account = %q", w)
}
history := []reddit.Submission{
{Subreddit: "SelfHosted", URL: "https://acme.example/1", Created: now.Add(-2 * 24 * time.Hour)},
{Subreddit: "homelab", Text: "see https://acme.example/2)", IsSelf: true, Created: now.Add(-10 * 24 * time.Hour)},
{Subreddit: "golang", Created: now.Add(-20 * 24 * time.Hour)},
{Subreddit: "selfhosted", URL: "https://acme.example/old", Created: now.Add(-60 * 24 * time.Hour)},
}
w = RedditWarnings(RedditCheck{Target: "selfhosted", Info: &reddit.Subreddit{}, History: history, Own: own, OwnLink: true, HasLink: true, Now: now})
if !has(w, "posted in r/selfhosted 1 time in the past week") || !has(w, "3 of your 4 posts") {
t.Errorf("history warnings = %q", w)
}
// Without a link of our own, the share isn't the issue.
w = RedditWarnings(RedditCheck{Target: "golang", Info: &reddit.Subreddit{}, History: history, Own: own, Now: now})
if len(w) != 0 {
t.Errorf("clean post = %q", w)
}
}
+11
View File
@@ -118,6 +118,17 @@ DROP TABLE posts;
`
ALTER TABLE drafts ADD COLUMN publish_at TEXT;
CREATE INDEX drafts_due ON drafts (status, publish_at);
`,
// 4: Reddit. A Reddit draft has a title and is for one subreddit
// (target). Subreddits' rules are cached so the Inbox can show them.
`
ALTER TABLE drafts ADD COLUMN title TEXT NOT NULL DEFAULT '';
ALTER TABLE drafts ADD COLUMN target TEXT NOT NULL DEFAULT '';
CREATE TABLE subreddits (
name TEXT PRIMARY KEY COLLATE NOCASE,
data TEXT NOT NULL,
fetched_at TEXT NOT NULL
);
`,
}
+63
View File
@@ -147,6 +147,69 @@ func LinkedInExchange(ctx context.Context, clientID, clientSecret, code string,
return tokenResponse(req)
}
// --- Reddit ---
const (
redditAuthURL = "https://www.reddit.com/api/v1/authorize"
redditTokenURL = "https://www.reddit.com/api/v1/access_token"
// identity: who signed in; submit: post; read: subreddit rules and the
// account's own posts; history: the account's posts for the warnings.
redditScopes = "identity submit read history"
)
// RedditStart begins Reddit's authorization-code flow. duration=permanent
// returns a refresh token: access tokens last an hour.
func RedditStart(clientID, redirectURI string) (string, *Pending, error) {
state, err := randomString()
if err != nil {
return "", nil, err
}
params := url.Values{
"client_id": {clientID},
"response_type": {"code"},
"state": {state},
"redirect_uri": {redirectURI},
"duration": {"permanent"},
"scope": {redditScopes},
}
p := &Pending{Provider: "reddit", State: state, RedirectURI: redirectURI, Started: time.Now()}
return redditAuthURL + "?" + params.Encode(), p, nil
}
// RedditExchange swaps the callback's code for tokens.
func RedditExchange(ctx context.Context, clientID, clientSecret, userAgent, code string, p *Pending) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {p.RedirectURI},
})
}
// RefreshReddit gets a new access token. Reddit keeps the refresh token.
func RefreshReddit(ctx context.Context, clientID, clientSecret, userAgent, refreshToken string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {refreshToken},
})
}
// RedditAppToken gets an app-only token, for reading subreddits' rules
// before anyone has signed in.
func RedditAppToken(ctx context.Context, clientID, clientSecret, userAgent string) (*Result, error) {
return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{"grant_type": {"client_credentials"}})
}
func redditToken(ctx context.Context, clientID, clientSecret, userAgent string, data url.Values) (*Result, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, redditTokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", userAgent)
req.SetBasicAuth(clientID, clientSecret)
return tokenResponse(req)
}
// --- shared ---
func tokenResponse(req *http.Request) (*Result, error) {
+6
View File
@@ -31,6 +31,12 @@ const (
LinkedInAuthorURN = "linkedin.author_urn"
YouTubeAPIKey = "youtube.api_key"
RedditClientID = "reddit.client_id"
RedditClientSecret = "reddit.client_secret"
RedditAccessToken = "reddit.access_token"
RedditRefreshToken = "reddit.refresh_token"
RedditUsername = "reddit.username"
)
// Store is the secrets file. It is safe for concurrent use.
+13
View File
@@ -124,3 +124,16 @@ func Slug(s string) string {
// Any reports whether the tagger knows any of the company's hosts.
func (t *Tagger) Any() bool { return t != nil && len(t.hosts) > 0 }
// HasOwnLink reports whether text contains a link to the company's sites.
func (t *Tagger) HasOwnLink(text string) bool {
if !t.Any() {
return false
}
for _, m := range links.FindAllString(text, -1) {
if t.Own(strings.TrimRight(m, ".,;:!?)]}'")) {
return true
}
}
return false
}
+159 -5
View File
@@ -2,8 +2,13 @@ package web
import (
"context"
"errors"
"fmt"
"strings"
"time"
"supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/rss"
"supermarket/internal/api/twitter"
"supermarket/internal/api/youtube"
@@ -59,6 +64,9 @@ func (s *Server) publishers() content.Publishers {
if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" {
pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)}
}
if c := s.redditUser(); c != nil {
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
}
return pubs
}
@@ -66,9 +74,10 @@ type xPublisher struct{ c *twitter.Client }
// Publish appends the source link to the post, as the old app did; X shows
// it as a card.
func (p xPublisher) Publish(ctx context.Context, text, sourceURL string) (string, error) {
if sourceURL != "" {
text += "\n\n" + sourceURL
func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
text := post.Text
if post.SourceURL != "" {
text += "\n\n" + post.SourceURL
}
return p.c.PostTweet(ctx, text)
}
@@ -76,6 +85,151 @@ func (p xPublisher) Publish(ctx context.Context, text, sourceURL string) (string
type linkedInPublisher struct{ c *linkedin.Client }
// Publish attaches the source link as an article preview.
func (p linkedInPublisher) Publish(ctx context.Context, text, sourceURL string) (string, error) {
return p.c.PostUpdate(ctx, text, sourceURL)
func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
return p.c.PostUpdate(ctx, post.Text, post.SourceURL)
}
type redditPublisher struct {
s *Server
c *reddit.Client
}
// Publish makes a text post with the source link at the end, or, where the
// subreddit only takes links, a link post of the title and the link.
func (p redditPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
info, _ := p.s.subreddit(ctx, post.Target, false)
if info != nil && !info.AllowsText() {
if post.SourceURL == "" {
return "", fmt.Errorf("r/%s only takes link posts, and this draft has no link", post.Target)
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, URL: post.SourceURL})
}
text := post.Text
if post.SourceURL != "" && !strings.Contains(text, post.SourceURL) {
text += "\n\nSource: " + post.SourceURL
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, Text: text})
}
// --- Reddit ---
func (s *Server) redditUserAgent() string {
return reddit.UserAgent(s.Version, s.Secrets.Get(secrets.RedditUsername))
}
// redditUser is a client signed in as the user, or nil. Access tokens last
// an hour; a refused one is refreshed and saved.
func (s *Server) redditUser() *reddit.Client {
tok := s.Secrets.Get(secrets.RedditAccessToken)
if tok == "" {
return nil
}
return reddit.New(tok, s.redditUserAgent(), func(ctx context.Context) (string, error) {
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), s.Secrets.Get(secrets.RedditRefreshToken))
if err != nil {
return "", err
}
updates := map[string]string{secrets.RedditAccessToken: res.AccessToken}
if res.RefreshToken != "" {
updates[secrets.RedditRefreshToken] = res.RefreshToken
}
if err := s.Secrets.Set(updates); err != nil {
s.Log.Error("reddit: couldn't save the refreshed token", "err", err)
}
return res.AccessToken, nil
})
}
// redditReader reads subreddits: as the user if signed in, else as the
// app (with its client ID and secret), else nil.
func (s *Server) redditReader(ctx context.Context) (*reddit.Client, error) {
if c := s.redditUser(); c != nil {
return c, nil
}
id, secret := s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret)
if id == "" || secret == "" {
return nil, errors.New("add Reddit's client ID and secret under Settings → Credentials to read subreddits")
}
s.mu.Lock()
tok, exp := s.redditAppToken, s.redditAppTokenExp
s.mu.Unlock()
if tok == "" || time.Now().After(exp) {
res, err := oauth.RedditAppToken(ctx, id, secret, s.redditUserAgent())
if err != nil {
return nil, err
}
tok = res.AccessToken
s.mu.Lock()
// Reddit's app tokens last an hour; renew a little early.
s.redditAppToken, s.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
s.mu.Unlock()
}
return reddit.New(tok, s.redditUserAgent(), nil), nil
}
// subreddit returns a subreddit's rules: cached if fresh enough (or if
// fetching fails), fetched otherwise. refresh forces a fetch.
func (s *Server) subreddit(ctx context.Context, name string, refresh bool) (*reddit.Subreddit, error) {
name = reddit.CleanName(name)
cached, err := content.GetSubreddit(s.DB, name)
if err != nil {
return nil, err
}
if cached != nil && !refresh && time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
c, err := s.redditReader(ctx)
if err == nil {
var info *reddit.Subreddit
if info, err = c.SubredditInfo(ctx, name); err == nil {
if serr := content.SaveSubreddit(s.DB, info); serr != nil {
s.Log.Error("caching subreddit", "name", name, "err", serr)
}
return info, nil
}
}
if cached != nil {
return cached, nil // stale beats nothing
}
return nil, err
}
// redditHistoryTTL is how long the account's recent posts are kept in
// memory for the warnings.
const redditHistoryTTL = 10 * time.Minute
// redditHistory is the signed-in account's recent posts, or nil if they
// can't be read.
func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
user := s.Secrets.Get(secrets.RedditUsername)
c := s.redditUser()
if c == nil || user == "" {
return nil
}
s.mu.Lock()
h, at := s.redditHist, s.redditHistAt
s.mu.Unlock()
if h != nil && time.Since(at) < redditHistoryTTL {
return h
}
h, err := c.Submitted(ctx, user)
if err != nil {
s.Log.Warn("reddit: couldn't read the account's posts", "err", err)
return nil
}
if h == nil {
h = []reddit.Submission{}
}
s.mu.Lock()
s.redditHist, s.redditHistAt = h, time.Now()
s.mu.Unlock()
return h
}
// forgetRedditHistory drops the cached posts after posting.
func (s *Server) forgetRedditHistory() {
s.mu.Lock()
s.redditHist = nil
s.mu.Unlock()
}
+40 -11
View File
@@ -10,6 +10,7 @@ import (
"time"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/fetcher"
"supermarket/internal/inventory"
@@ -62,6 +63,7 @@ type entryPage struct {
Since time.Time
Channels []channelChoice
ProfileSet bool
Subreddits []string // suggestions: the entry's, then the profile's
// After a fetch
Fetched bool
NewItems int
@@ -105,7 +107,17 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
for _, c := range content.Channels {
chans = append(chans, channelChoice{c, pubs[c.ID] != nil})
}
return &entryPage{Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
var subs []string
seen := map[string]bool{}
for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} {
for _, sr := range list {
if n := reddit.CleanName(sr); n != "" && !seen[strings.ToLower(n)] {
seen[strings.ToLower(n)] = true
subs = append(subs, n)
}
}
}
return &entryPage{Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil
}
@@ -232,15 +244,6 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
if err != nil {
return err
}
groups := [][]content.Item{items}
if perItem {
groups = groups[:0]
for _, it := range items {
groups = append(groups, []content.Item{it})
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
// Keep channels in display order whatever order the form sent.
var ordered []string
for _, c := range content.Channels {
@@ -251,9 +254,35 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
}
}
}
req := content.Request{Profile: p, Entry: e}
for _, ch := range ordered {
if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit"))
if req.Subreddit == "" {
return errors.New("choose a subreddit for the Reddit post")
}
// The rules go into the prompt; without them the model is told
// to be careful, and the Inbox warns.
info, err := s.subreddit(r.Context(), req.Subreddit, false)
if err != nil {
s.Log.Warn("reddit: couldn't read the subreddit's rules", "subreddit", req.Subreddit, "err", err)
}
req.SubredditInfo = info
}
}
groups := [][]content.Item{items}
if perItem {
groups = groups[:0]
for _, it := range items {
groups = append(groups, []content.Item{it})
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
written := 0
for _, g := range groups {
drafts, err := content.Generate(ctx, client, content.Request{Profile: p, Entry: e, Items: g, Channels: ordered})
req.Items, req.Channels = g, ordered
drafts, err := content.Generate(ctx, client, req)
if err != nil {
if written > 0 {
return fmt.Errorf("wrote %d set(s) of drafts, then: %w", written, err)
+76
View File
@@ -9,10 +9,12 @@ import (
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/models"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
func TestContentPages(t *testing.T) {
@@ -197,3 +199,77 @@ func mustID(s string) int64 {
n, _ := strconv.ParseInt(s, 10, 64)
return n
}
func TestRedditInInbox(t *testing.T) {
s, h := newTestServer(t, nil)
if _, err := content.CreateDrafts(s.DB, []content.Draft{
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelReddit, Title: "Jitsi 3", Target: "selfhosted", Content: "I work at Acme.", SourceURL: "https://jitsi.example/3"},
{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelReddit, Title: "Other", Target: "homelab", Content: "Body"},
}); err != nil {
t.Fatal(err)
}
if err := content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "selfhosted", SubmitText: "Flair it.", SubmissionType: "self",
Rules: []reddit.Rule{{Name: "No self-promotion", Description: "Limit it."}}, FetchedAt: time.Now()}); err != nil {
t.Fatal(err)
}
body := do(h, http.MethodGet, "/inbox", nil, nil).Body.String()
for _, want := range []string{"Reddit r/selfhosted", `name="title" value="Jitsi 3"`, "Flair it.", "No self-promotion",
"has a rule about this", "Couldn&#39;t read r/homelab&#39;s rules", `action="/reddit/rules/homelab"`, "Read rules", "text only"} {
if !strings.Contains(body, want) {
t.Errorf("inbox lacks %q", want)
}
}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
var id string
for _, d := range ds {
if d.Target == "selfhosted" {
id = strconv.FormatInt(d.ID, 10)
}
}
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {"Jitsi 3 is out"}, "content": {"Edited"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
}
if d, _ := content.GetDraft(s.DB, mustID(id)); d.Title != "Jitsi 3 is out" || d.Content != "Edited" {
t.Errorf("saved: %+v", d)
}
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "the title is empty") {
t.Errorf("empty title: %s", rec.Body.String())
}
if rec := postForm(h, "/drafts/"+id+"/publish", nil); !strings.Contains(rec.Body.String(), "Reddit isn&#39;t connected") {
t.Errorf("publish without Reddit: %s", rec.Body.String())
}
// 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.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusBadRequest {
t.Errorf("reddit start without credentials: %d", rec.Code)
}
_ = s.Secrets.Set(map[string]string{secrets.RedditClientID: "id", secrets.RedditClientSecret: "sec"})
rec := postForm(h, "/auth/reddit/start", nil)
if loc := rec.Header().Get("Location"); rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "https://www.reddit.com/api/v1/authorize?") ||
!strings.Contains(loc, "duration=permanent") || !strings.Contains(loc, "submit") {
t.Errorf("reddit start: %d %s", rec.Code, loc)
}
}
func TestWriteRedditNeedsSubreddit(t *testing.T) {
s, h := newTestServer(t, nil)
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Accounts: profile.Accounts{Subreddits: []string{"selfhosted"}}})
e := &inventory.Entry{Name: "Jitsi", Relationship: inventory.Partner, Subreddits: []string{"r/jitsi", "selfhosted"}}
_ = inventory.Save(s.DB, e)
id := strconv.FormatInt(e.ID, 10)
_, _ = content.SaveItems(s.DB, []models.ContentItem{{ID: "a", Source: models.SourceRSS, Body: "x", PublishedAt: time.Now(), AppName: "Jitsi"}})
body := do(h, http.MethodGet, "/content/"+id, nil, nil).Body.String()
if !strings.Contains(body, `<option value="jitsi">`) || strings.Count(body, `<option value="selfhosted">`) != 1 {
t.Errorf("subreddit suggestions:\n%s", body)
}
_ = s.Secrets.Set(map[string]string{secrets.AnthropicAPIKey: "k"})
rec := postForm(h, "/content/"+id+"/items", url.Values{"action": {"write"}, "item": {"a"}, "channel": {"reddit"}, "subreddit": {" "}})
if !strings.Contains(rec.Body.String(), "choose a subreddit") {
t.Errorf("write without subreddit: %s", rec.Body.String())
}
}
+58 -2
View File
@@ -9,6 +9,7 @@ import (
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
@@ -93,6 +94,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
}
s.render(w, r, "inbox", page{Title: "Inbox", Nav: "inbox", Error: errMsg, Data: map[string]any{
"Sections": sections,
"Reddit": s.redditViews(r.Context(), pending),
"Connected": s.connected(),
"Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
@@ -100,6 +102,51 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
}})
}
// redditView is what the Inbox shows with a Reddit draft.
type redditView struct {
Info *reddit.Subreddit
Warnings []string
}
// redditViews works out the rules and warnings for the Reddit drafts. It
// reads the account's recent posts once (cached for a few minutes).
func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[int64]*redditView {
views := map[int64]*redditView{}
var history []reddit.Submission
historyRead := false
tags := s.tagger()
for _, d := range drafts {
if d.Channel != content.ChannelReddit {
continue
}
if !historyRead {
hctx, cancel := context.WithTimeout(ctx, 8*time.Second)
history = s.redditHistory(hctx)
cancel()
historyRead = true
}
info, _ := content.GetSubreddit(s.DB, d.Target)
check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now()}
if tags != nil {
check.Own = tags.Own
check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content)
}
views[d.ID] = &redditView{Info: info, Warnings: content.RedditWarnings(check)}
}
return views
}
// refreshRules fetches a subreddit's rules again.
func (s *Server) refreshRules(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
if _, err := s.subreddit(ctx, r.PathValue("name"), true); err != nil {
s.renderInbox(w, r, "Couldn't read the subreddit's rules: "+err.Error())
return
}
redirect(w, r, "/inbox", "rules-refreshed")
}
// The Content module's own lists of approved and published drafts.
func (s *Server) scheduledPage(w http.ResponseWriter, r *http.Request) {
@@ -178,6 +225,12 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
action := r.PathValue("action")
switch action {
case "save", "publish", "schedule":
if title, sent := r.PostForm["title"]; sent {
if err := content.UpdateTitle(s.DB, id, title[0]); err != nil {
fail(err)
return
}
}
if text, sent := r.PostForm["content"]; sent {
if err := content.UpdateDraft(s.DB, id, text[0]); err != nil {
fail(err)
@@ -200,6 +253,9 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(fmt.Errorf("Couldn't publish to %s: %w", name, err))
return
}
if d.Channel == content.ChannelReddit {
s.forgetRedditHistory()
}
redirect(w, r, back, "published")
case "schedule":
at, err := parseWhen(r.PostForm.Get("when"), time.Now())
@@ -212,8 +268,8 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err)
return
}
if d.TooLong() {
fail(fmt.Errorf("the %s post is %d characters; it allows %d. Shorten it before scheduling", d.ChannelName(), d.Length(), d.Limit()))
if problem := d.Problem(); problem != "" {
fail(fmt.Errorf("%s: fix it before scheduling", problem))
return
}
if err := content.Schedule(s.DB, id, at); err != nil {
+5 -2
View File
@@ -90,7 +90,7 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
Detail: ifElse(aiErr == nil, aiCfg.Provider+" · "+aiCfg.Model, "Choose Anthropic or a server on your network")},
{Label: "Inventory", Done: len(entries) > 0, Link: "/inventory",
Detail: inventorySummary(counts)},
{Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken),
{Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken) || s.Secrets.Has(secrets.RedditAccessToken),
Link: "/settings/credentials", Detail: s.connectionSummary(conns)},
{Label: "Federated Core", Done: s.Core != nil, Link: "/core",
Detail: ifElse(s.Core != nil, coreDomain(s.Core), "No Core found; run `configure core` in CoreDesktop")},
@@ -162,8 +162,11 @@ func (s *Server) connectionSummary(c map[string]Connection) string {
if s.Secrets.Has(secrets.LinkedInAccessToken) {
parts = append(parts, "LinkedIn")
}
if a := c["reddit"].Account; a != "" {
parts = append(parts, "Reddit u/"+a)
}
if len(parts) == 0 {
return "Connect X and LinkedIn"
return "Connect X, LinkedIn or Reddit"
}
return strings.Join(parts, ", ")
}
+25 -14
View File
@@ -14,6 +14,7 @@ import (
"sync"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/core"
"supermarket/internal/db"
@@ -49,6 +50,13 @@ type Server struct {
mu sync.Mutex
pending map[string]*oauth.Pending // OAuth flows by state
// 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
}
// Handler builds the routes.
@@ -102,6 +110,7 @@ func (s *Server) Handler() (http.Handler, error) {
redirect(w, r, "/inbox", r.URL.Query().Get("msg"))
})
mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction)
mux.HandleFunc("POST /reddit/rules/{name}", s.refreshRules)
mux.HandleFunc("GET /core", s.corePage)
mux.HandleFunc("GET /core/checks", s.coreChecks)
@@ -131,7 +140,7 @@ func (s *Server) guard(next http.Handler) http.Handler {
h.Set("X-Frame-Options", "DENY")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "same-origin")
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self' https://twitter.com https://x.com https://www.linkedin.com; frame-ancestors 'none'")
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self' https://twitter.com https://x.com https://www.linkedin.com https://www.reddit.com; frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}
@@ -243,19 +252,21 @@ func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) {
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"imported": "Imported.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
"scheduled": "Scheduled.",
"unscheduled": "Back in the Inbox: edit it, then publish or schedule it again.",
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"reddit-connected": "Reddit is connected.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
"scheduled": "Scheduled.",
"unscheduled": "Back in the Inbox: edit it, then publish or schedule it again.",
}
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
+42 -8
View File
@@ -8,6 +8,7 @@ import (
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
@@ -144,6 +145,8 @@ var credentialFields = []struct {
{"LinkedIn", secrets.LinkedInClientID, "Client ID", "From your app at linkedin.com/developers."},
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret", ""},
{"YouTube", secrets.YouTubeAPIKey, "API key", "Free, from console.cloud.google.com (YouTube Data API v3)."},
{"Reddit", secrets.RedditClientID, "Client ID", "From a \"web app\" at reddit.com/prefs/apps: the string under the app's name."},
{"Reddit", secrets.RedditClientSecret, "Client secret", ""},
}
func (s *Server) credentialsPage(w http.ResponseWriter, r *http.Request) {
@@ -151,15 +154,17 @@ func (s *Server) credentialsPage(w http.ResponseWriter, r *http.Request) {
for _, f := range credentialFields {
names = append(names, f.Name)
}
names = append(names, secrets.XAccessToken, secrets.LinkedInAccessToken)
names = append(names, secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.RedditAccessToken)
s.render(w, r, "credentials", page{Title: "Credentials", Nav: "settings", Data: map[string]any{
"Fields": credentialFields,
"Set": s.secretState(names...),
"Connections": s.connections(),
"XRedirect": s.PublicURL + "/auth/x/callback",
"LIRedirect": s.PublicURL + "/auth/linkedin/callback",
"XToken": secrets.XAccessToken,
"LIToken": secrets.LinkedInAccessToken,
"Fields": credentialFields,
"Set": s.secretState(names...),
"Connections": s.connections(),
"XRedirect": s.PublicURL + "/auth/x/callback",
"LIRedirect": s.PublicURL + "/auth/linkedin/callback",
"RedditRedirect": s.PublicURL + "/auth/reddit/callback",
"RedditToken": secrets.RedditAccessToken,
"XToken": secrets.XAccessToken,
"LIToken": secrets.LinkedInAccessToken,
}})
}
@@ -215,6 +220,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
authURL, p, err = oauth.LinkedInStart(id, s.PublicURL+"/auth/linkedin/callback")
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.PublicURL+"/auth/reddit/callback")
default:
http.NotFound(w, r)
return
@@ -302,6 +314,28 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/credentials", "li-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 := s.Secrets.Set(map[string]string{secrets.RedditAccessToken: res.AccessToken,
secrets.RedditRefreshToken: res.RefreshToken, secrets.RedditUsername: name}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.forgetRedditHistory()
if err := s.saveConnection("reddit", Connection{Account: name, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/credentials", "reddit-connected")
default:
http.NotFound(w, r)
}
+5
View File
@@ -146,3 +146,8 @@ button.small { padding: 0.3rem 0.8rem; font-size: 0.85rem; }
.row-actions form { display: inline-block; margin: 0 0.25rem 0.25rem 0; }
.post-text { overflow-wrap: anywhere; }
.small { font-size: 0.85rem; }
.warnings { margin: 0 0 0.75rem; padding: 0.6rem 0.9rem 0.6rem 2rem; background: #fff7e6; border: 1px solid #f5d48f; border-radius: 8px; color: #6b4100; font-size: 0.9rem; }
.rules { margin: 0 0 0.5rem; font-size: 0.9rem; }
.rules summary { cursor: pointer; color: var(--cyan-dark); }
.rules .guidelines { white-space: pre-line; color: var(--muted); }
form.inline { display: inline-block; margin: 0 0 0.75rem; }
+7 -1
View File
@@ -60,8 +60,14 @@
<fieldset class="choice">
<legend>Channels</legend>
{{range .Channels}}
<label class="check"><input type="checkbox" name="channel" value="{{.ID}}" {{if .Connected}}checked{{end}}> {{.Name}}{{if not .Connected}} <span class="muted">(not connected: you can draft, but not publish yet)</span>{{end}}</label>
{{/* 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>
{{end}}
<label class="small">Subreddit, for Reddit
<input name="subreddit" list="subreddits" placeholder="e.g. selfhosted" autocomplete="off">
<datalist id="subreddits">{{range .Subreddits}}<option value="{{.}}">{{end}}</datalist>
<span class="help">One subreddit per post. Its rules are read and followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span>
</label>
</fieldset>
<fieldset class="choice">
<legend>Posts</legend>
@@ -14,9 +14,9 @@
{{range .Drafts}}
<tr>
<td>{{.PublishedAt.Local.Format "2 Jan 2006 15:04"}}</td>
<td>{{.ChannelName}}</td>
<td>{{.Where}}</td>
<td>{{.InventoryName}}</td>
<td class="post-text">{{if .PostURL}}<a href="{{.PostURL}}" target="_blank" rel="noopener noreferrer">{{truncate 200 .Content}}</a>{{else}}{{truncate 200 .Content}}{{end}}</td>
<td class="post-text">{{if .PostURL}}<a href="{{.PostURL}}" target="_blank" rel="noopener noreferrer">{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}</a>{{else}}{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}{{end}}</td>
</tr>
{{end}}
</tbody>
@@ -14,9 +14,9 @@
{{range .Drafts}}
<tr>
<td>{{.PublishAt.Local.Format "Mon 2 Jan 15:04"}}</td>
<td>{{.ChannelName}}{{if not (index $conn .Channel)}}<br><span class="warn-text small">not connected</span>{{end}}</td>
<td>{{.Where}}{{if not (index $conn .Channel)}}<br><span class="warn-text small">not connected</span>{{end}}</td>
<td>{{.InventoryName}}</td>
<td class="post-text">{{truncate 200 .Content}}</td>
<td class="post-text">{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}</td>
<td class="row-actions">
<form method="post" action="/drafts/{{.ID}}/publish" data-busy="Publishing…">
<input type="hidden" name="from" value="scheduled">
+7
View File
@@ -39,6 +39,13 @@
<p class="help">In your LinkedIn app's Auth settings, add this redirect URL: <code>{{.LIRedirect}}</code></p>
<form method="post" action="/auth/linkedin/start"><button type="submit" {{if not (and (index $set "linkedin.client_id") (index $set "linkedin.client_secret"))}}disabled{{end}}>{{if index $set .LIToken}}Reconnect{{else}}Connect{{end}} LinkedIn</button></form>
</div>
<div>
<h3>Reddit</h3>
{{with index .Connections "reddit"}}{{if .Account}}<p>Connected as u/{{.Account}}, {{ago .At}}.</p>{{end}}{{end}}
<p class="help">At reddit.com/prefs/apps, create a <strong>web app</strong> with this redirect URI: <code>{{.RedditRedirect}}</code>.
Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.</p>
<form method="post" action="/auth/reddit/start"><button type="submit" {{if not (and (index $set "reddit.client_id") (index $set "reddit.client_secret"))}}disabled{{end}}>{{if index $set .RedditToken}}Reconnect{{else}}Connect{{end}} Reddit</button></form>
</div>
</div>
</section>
{{end}}{{end}}
+22 -3
View File
@@ -1,4 +1,4 @@
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$now := .Now}}{{$zone := .Zone}}
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Inbox</h1>
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it.
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
@@ -16,12 +16,31 @@
<div class="drafts">
{{range .Drafts}}
<div class="draft{{if eq .Status "failed"}} failed{{end}}">
<h3>{{.ChannelName}}</h3>
<h3>{{.Where}}</h3>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
{{$rv := index $reddit .ID}}
{{if $rv}}
{{if $rv.Warnings}}<ul class="warnings">{{range $rv.Warnings}}<li>{{.}}</li>{{end}}</ul>{{end}}
{{with $rv.Info}}
<details class="rules">
<summary>r/{{.Name}}'s rules{{if .Rules}} ({{len .Rules}}){{end}} · read {{ago .FetchedAt}}</summary>
{{if .SubmitText}}<p class="guidelines">{{truncate 1200 .SubmitText}}</p>{{end}}
{{if .Rules}}<ol>{{range .Rules}}<li><strong>{{.Name}}</strong>{{if .Description}}: {{truncate 500 .Description}}{{end}}</li>{{end}}</ol>{{end}}
<p class="muted small">Posts: {{if eq .SubmissionType "self"}}text only{{else if eq .SubmissionType "link"}}links only{{else}}text or links{{end}}{{if .Subscribers}} · {{.Subscribers}} members{{end}}</p>
</details>
{{end}}
<form method="post" action="/reddit/rules/{{.Target}}" class="inline"><button type="submit" class="secondary small">{{if $rv.Info}}Refresh rules{{else}}Read rules{{end}}</button></form>
{{end}}
<form method="post" action="/drafts/{{.ID}}/save" data-busy-on="publish" data-busy="Publishing…">
{{if eq .Channel "reddit"}}
<label class="small">Title
<input name="title" value="{{.Title}}" maxlength="300" required>
</label>
{{end}}
<textarea name="content" rows="{{if eq .Channel "x"}}5{{else}}12{{end}}"
data-count="{{.Channel}}" data-limit="{{.Limit}}" data-reserve="{{if eq .Channel "x"}}{{xreserve .SourceURL}}{{else}}0{{end}}"
aria-describedby="count-{{.ID}}">{{.Content}}</textarea>
{{if eq .Channel "reddit"}}{{if .SourceURL}}<p class="help">The source link is added at the end as “Source: …”.</p>{{end}}{{end}}
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}</p>
<div class="actions">
<button type="submit" name="action" value="publish" formaction="/drafts/{{.ID}}/publish"
@@ -36,7 +55,7 @@
</div>
{{if not (index $conn .Channel)}}<p class="help">{{.ChannelName}} isn't connected: <a href="/settings/credentials">sign in</a> before it's due.</p>{{end}}
</form>
<form method="post" action="/drafts/{{.ID}}/discard" data-confirm="Discard this {{.ChannelName}} draft?">
<form method="post" action="/drafts/{{.ID}}/discard" data-confirm="Discard this {{.Where}} draft?">
<button type="submit" class="danger small">Discard</button>
</form>
</div>