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:
+159
-5
@@ -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
@@ -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)
|
||||
|
||||
@@ -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't read r/homelab'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'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
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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}}
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user