Reddit: posted by hand, with the rules pasted

Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 11:48:54 -07:00
co-authored by Claude Opus 5.5
parent bae468e01c
commit 5451fe6d63
33 changed files with 382 additions and 1107 deletions
-3
View File
@@ -93,9 +93,6 @@ func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer
if s.Secrets.Has(secrets.LinkedInClientID) && s.Secrets.Has(secrets.LinkedInClientSecret) {
d.Connectable = append(d.Connectable, grant{"linkedin", "LinkedIn"})
}
if s.Secrets.Has(secrets.RedditClientID) && s.Secrets.Has(secrets.RedditClientSecret) {
d.Connectable = append(d.Connectable, grant{"reddit", "Reddit"})
}
}
for _, ss := range list {
d.Sessions = append(d.Sessions, sessionRow{Session: ss, This: ss.ID == v.Session.ID})
+1 -1
View File
@@ -128,7 +128,7 @@ type draftArgs struct {
Text string `json:"text" jsonschema:"the post; within the channel's limit (X: 280 characters, counting the source link as 23)"`
Title string `json:"title,omitempty" jsonschema:"Reddit only: the post's title"`
Subreddit string `json:"subreddit,omitempty" jsonschema:"Reddit only: where it goes, without r/"`
SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card)"`
SourceURL string `json:"source_url,omitempty" jsonschema:"the link the post is about; added when publishing (on X after the text, on LinkedIn as a card, on Reddit at the end as \"Source: …\")"`
Entry string `json:"entry,omitempty" jsonschema:"the Market entry it's about, or own; empty for none"`
SignalID int64 `json:"signal_id,omitempty" jsonschema:"the buying signal it's written for (signals_list), so its links count for it"`
ItemIDs []string `json:"item_ids,omitempty" jsonschema:"the fetched items it's written from (content_items), marked as used"`
-141
View File
@@ -2,19 +2,15 @@ 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"
"supermarket/internal/content"
"supermarket/internal/fetcher"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
"supermarket/internal/site"
)
@@ -85,140 +81,3 @@ func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (stri
link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)")
return c.PostUpdate(ctx, post.Text, link)
}
type redditPublisher struct {
s *Server
c *reddit.Client
}
// Publish makes a text post with the source link at the end, or, where the
// subreddit only takes links, a link post of the title and the link.
func (p redditPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
info, _ := p.s.subreddit(ctx, post.Target, false)
if info != nil && !info.AllowsText() {
if post.SourceURL == "" {
return "", fmt.Errorf("r/%s only takes link posts, and this draft has no link", post.Target)
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, URL: post.SourceURL})
}
text := post.Text
if post.SourceURL != "" && !strings.Contains(text, post.SourceURL) {
text += "\n\nSource: " + post.SourceURL
}
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, Text: text})
}
// --- Reddit ---
func (s *Server) redditUserAgent() string {
name := ""
if a := s.companyReddit(); a != nil {
name = a.External
}
return reddit.UserAgent(s.Version, name)
}
// redditUser is a client signed in as the company's Reddit account, or nil.
func (s *Server) redditUser() *reddit.Client {
a := s.companyReddit()
if a == nil {
return nil
}
return s.redditClient(a)
}
// redditReader reads subreddits: as the user if signed in, else as the
// app (with its client ID and secret), else nil.
func (s *Server) redditReader(ctx context.Context) (*reddit.Client, error) {
if c := s.redditUser(); c != nil {
return c, nil
}
id, secret := s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret)
if id == "" || secret == "" {
return nil, errors.New("add Reddit's client ID and secret under Settings → Social accounts to read subreddits")
}
tc := s.cache()
tc.mu.Lock()
tok, exp := tc.redditAppToken, tc.redditAppTokenExp
tc.mu.Unlock()
if tok == "" || time.Now().After(exp) {
res, err := oauth.RedditAppToken(ctx, id, secret, s.redditUserAgent())
if err != nil {
return nil, err
}
tok = res.AccessToken
tc.mu.Lock()
// Reddit's app tokens last an hour; renew a little early.
tc.redditAppToken, tc.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
tc.mu.Unlock()
}
return reddit.New(tok, s.redditUserAgent(), nil), nil
}
// subreddit returns a subreddit's rules: cached if fresh enough (or if
// fetching fails), fetched otherwise. refresh forces a fetch.
func (s *Server) subreddit(ctx context.Context, name string, refresh bool) (*reddit.Subreddit, error) {
name = reddit.CleanName(name)
cached, err := content.GetSubreddit(s.DB, name)
if err != nil {
return nil, err
}
if cached != nil && !refresh && time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
c, err := s.redditReader(ctx)
if err == nil {
var info *reddit.Subreddit
if info, err = c.SubredditInfo(ctx, name); err == nil {
if serr := content.SaveSubreddit(s.DB, info); serr != nil {
s.Log.Error("caching subreddit", "name", name, "err", serr)
}
return info, nil
}
}
if cached != nil {
return cached, nil // stale beats nothing
}
return nil, err
}
// redditHistoryTTL is how long the account's recent posts are kept in
// memory for the warnings.
const redditHistoryTTL = 10 * time.Minute
// redditHistory is the signed-in account's recent posts, or nil if they
// can't be read.
func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
a := s.companyReddit()
if a == nil || a.External == "" {
return nil
}
user, c := a.External, s.redditClient(a)
tc := s.cache()
tc.mu.Lock()
h, at := tc.redditHist, tc.redditHistAt
tc.mu.Unlock()
if h != nil && time.Since(at) < redditHistoryTTL {
return h
}
h, err := c.Submitted(ctx, user)
if err != nil {
s.Log.Warn("reddit: couldn't read the account's posts", "err", err)
return nil
}
if h == nil {
h = []reddit.Submission{}
}
tc.mu.Lock()
tc.redditHist, tc.redditHistAt = h, time.Now()
tc.mu.Unlock()
return h
}
// forgetRedditHistory drops the cached posts after posting.
func (s *Server) forgetRedditHistory() {
tc := s.cache()
tc.mu.Lock()
tc.redditHist = nil
tc.mu.Unlock()
}
+1 -4
View File
@@ -25,7 +25,6 @@ var services = []service{
{"x", "X", "Posting, and reading partners' posts", "/settings/accounts#network-X", []string{secrets.XBearerToken}},
{"linkedin", "LinkedIn", "Posting as a person", "/settings/accounts#network-LinkedIn", nil},
{"linkedin_page", "LinkedIn page", "Posting as the company's page", "/settings/accounts", nil},
{"reddit", "Reddit", "Posting to subreddits", "/settings/accounts#network-Reddit", nil},
{"youtube", "YouTube", "Reading partners' videos", "/settings/accounts", []string{secrets.YouTubeAPIKey}},
{"google", "Google Search Console", "SEO: what ranks, the morning check", "/settings/search", []string{secrets.GoogleRefreshToken}},
{"bing", "Bing Webmaster", "SEO: links to the sites", "/settings/search", []string{secrets.BingAPIKey}},
@@ -195,7 +194,7 @@ func (s *Server) connectionsPage(w http.ResponseWriter, r *http.Request) {
_, _ = s.DB.GetJSON(connChecksKey, &checks)
signins := s.connections()
// The posting networks count their accounts.
postingCount := map[string]int{"x": 0, "linkedin": 0, "linkedin_page": 0, "reddit": 0}
postingCount := map[string]int{"x": 0, "linkedin": 0, "linkedin_page": 0}
postingNames := map[string]string{}
for _, a := range s.postingAccounts() {
if s.working(a) {
@@ -283,8 +282,6 @@ func connectionName(id string) string {
return "linkedin"
case "linkedin_page":
return liPageProvider
case "reddit":
return "reddit"
case "google":
return "google"
}
+6 -7
View File
@@ -10,7 +10,6 @@ import (
"time"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/api/sitemap"
"supermarket/internal/content"
"supermarket/internal/db"
@@ -160,7 +159,7 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
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)] {
if n := content.CleanSubreddit(sr); n != "" && !seen[strings.ToLower(n)] {
seen[strings.ToLower(n)] = true
subs = append(subs, n)
}
@@ -322,15 +321,15 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
}
for _, ch := range ordered {
if ch == content.ChannelReddit {
req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit"))
req.Subreddit = content.CleanSubreddit(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 Posts warns.
info, err := s.subreddit(r.Context(), req.Subreddit, false)
// The rules pasted for it go into the prompt; without them the
// model is told to be careful, and Posts asks for them.
info, err := content.GetSubreddit(s.DB, req.Subreddit)
if err != nil {
s.Log.Warn("reddit: couldn't read the subreddit's rules", "subreddit", req.Subreddit, "err", err)
s.Log.Error("reading a subreddit's rules", "subreddit", req.Subreddit, "err", err)
}
req.SubredditInfo = info
}
+29 -26
View File
@@ -11,7 +11,6 @@ import (
"testing"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/models"
@@ -210,17 +209,22 @@ func TestRedditInInbox(t *testing.T) {
}); 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 {
if err := content.SaveRules(s.DB, "selfhosted", "1. Flair it.\n2. No self-promotion", time.Now()); err != nil {
t.Fatal(err)
}
body := do(h, http.MethodGet, "/posts", nil, nil).Body.String()
for _, want := range []string{"Reddit r/selfhosted", `name="title" value="Jitsi 3"`, "Flair it.", "No self-promotion",
"has a rule about this", "Couldn&#39;t read r/homelab&#39;s rules", `action="/reddit/rules/homelab"`, "Read rules", "text only"} {
for _, want := range []string{"Reddit r/selfhosted", `name="title" id="title-`, `value="Jitsi 3"`, "1. Flair it.", "has a rule about this",
"r/homelab's rules · not pasted yet", `action="/reddit/rules/homelab"`, `href="https://www.reddit.com/r/homelab/about/rules"`,
"Copy title", `data-copy-suffix="
Source: https://jitsi.example/3"`} {
if !strings.Contains(body, want) {
t.Errorf("inbox lacks %q", want)
}
}
if strings.Contains(body, "Publish now") || strings.Contains(body, "Schedule</button>") {
t.Error("Reddit drafts mustn't offer Publish now")
}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
var id string
@@ -238,22 +242,28 @@ func TestRedditInInbox(t *testing.T) {
if rec := postForm(h, "/drafts/"+id+"/save", url.Values{"title": {""}}); !strings.Contains(rec.Body.String(), "The title is empty") {
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())
for _, action := range []string{"publish", "schedule"} {
if rec := postForm(h, "/drafts/"+id+"/"+action, url.Values{"when": {time.Now().Add(time.Hour).Format("2006-01-02T15:04")}}); !strings.Contains(rec.Body.String(), "posted by hand") {
t.Errorf("%s a Reddit draft: %s", action, rec.Body.String())
}
}
// Reading rules needs Reddit credentials.
if rec := postForm(h, "/reddit/rules/homelab", nil); !strings.Contains(rec.Body.String(), "client ID and secret") {
t.Errorf("refresh without credentials: %d %s", rec.Code, rec.Body.String())
// Pasting the rules keeps them; emptying the box forgets them.
if rec := postForm(h, "/reddit/rules/homelab", url.Values{"rules": {"No memes."}}); rec.Code != http.StatusSeeOther {
t.Fatalf("save rules: %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)
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr == nil || sr.Rules != "No memes." {
t.Errorf("rules = %+v", sr)
}
_ = 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)
postForm(h, "/reddit/rules/homelab", url.Values{"rules": {""}})
if sr, _ := content.GetSubreddit(s.DB, "homelab"); sr != nil {
t.Error("emptied rules kept")
}
// Reddit has no sign-in any more.
if rec := postForm(h, "/auth/reddit/start", nil); rec.Code != http.StatusNotFound {
t.Errorf("reddit start: %d", rec.Code)
}
if strings.Contains(do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String(), "network-Reddit") {
t.Error("Social accounts still has a Reddit card")
}
}
@@ -328,14 +338,13 @@ func TestPostRedditByHand(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
_ = content.SaveSubreddit(s.DB, &reddit.Subreddit{Name: "linksonly", SubmissionType: "link", FetchedAt: time.Now()})
ids := map[string]string{}
ds, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
for _, d := range ds {
ids[d.Target] = strconv.FormatInt(d.ID, 10)
}
if body := do(h, http.MethodGet, "/posts", nil, nil).Body.String(); !strings.Contains(body, "Open in Reddit") ||
!strings.Contains(body, "can't post to Reddit for you yet") || !strings.Contains(body, `action="/drafts/`+ids["selfhosted"]+`/posted"`) {
!strings.Contains(body, "Post it yourself") || !strings.Contains(body, `action="/drafts/`+ids["selfhosted"]+`/posted"`) {
t.Error("inbox lacks the by-hand controls")
}
@@ -352,12 +361,6 @@ func TestPostRedditByHand(t *testing.T) {
t.Errorf("open should save the edits and leave it a draft: %+v", d)
}
// A links-only subreddit gets a link post.
loc, _ = url.Parse(postForm(h, "/drafts/"+ids["linksonly"]+"/open", nil).Header().Get("Location"))
if q := loc.Query(); q.Get("text") != "" || !strings.HasPrefix(q.Get("url"), "https://acme.example/w?") {
t.Errorf("link post: %s", loc)
}
// Mark as posted: a bad link is refused, a good one recorded.
if rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/posted", url.Values{"post_url": {"not a link"}}); !strings.Contains(rec.Body.String(), "isn&#39;t a link to a post") {
t.Error("bad post link accepted")
+49 -52
View File
@@ -10,7 +10,6 @@ import (
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
@@ -109,7 +108,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
s.render(w, r, "inbox", page{Title: "Posts", Nav: "content/posts", Error: errMsg, Data: map[string]any{
"Reminders": s.reminders(),
"Sections": sections,
"Reddit": s.redditViews(r.Context(), pending),
"Reddit": s.redditViews(pending),
"Connected": s.connected(viewerOf(r)),
"Accounts": s.usableAccounts(viewerOf(r)),
"Chosen": s.chosenAccounts(pending),
@@ -121,52 +120,47 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
// redditView is what Posts shows with a Reddit draft.
type redditView struct {
Info *reddit.Subreddit
Info *content.Subreddit // the rules pasted; nil if none
RulesURL string
Suffix string // added after the text when it's copied: the source link
Warnings []string
}
// 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 {
// redditViews works out the rules and warnings for the Reddit drafts.
func (s *Server) redditViews(drafts []content.Draft) map[int64]*redditView {
views := map[int64]*redditView{}
var history []reddit.Submission
historyRead := false
tags := s.tagger()
recorded, err := content.RecordedRedditPosts(s.DB, time.Now().Add(-8*24*time.Hour))
if err != nil {
s.Log.Error("reading recorded Reddit posts", "err", err)
}
for _, d := range drafts {
for i, 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, err := content.GetSubreddit(s.DB, d.Target)
if err != nil {
s.Log.Error("reading a subreddit's rules", "subreddit", d.Target, "err", err)
}
info, _ := content.GetSubreddit(s.DB, d.Target)
check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now(),
check := content.RedditCheck{Target: d.Target, Info: info, Now: time.Now(),
Promo: d.Kind == content.KindProduct, Recorded: recorded}
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)}
views[d.ID] = &redditView{Info: info, RulesURL: content.RulesURL(d.Target),
Suffix: redditSuffix(&drafts[i], tags), 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())
// saveRules keeps the rules pasted for a subreddit.
func (s *Server) saveRules(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
redirect(w, r, "/posts", "rules-refreshed")
if err := content.SaveRules(s.DB, r.PathValue("name"), r.PostForm.Get("rules"), time.Now()); err != nil {
s.renderInbox(w, r, "Couldn't save the rules: "+err.Error())
return
}
redirect(w, r, "/posts", "rules-saved")
}
// The Content module's own lists of approved and published drafts.
@@ -308,7 +302,6 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
var failed []string
reddit := false
for _, did := range append([]int64{id}, copies...) {
_ = content.SetPostedBy(s.DB, did, by)
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), did)
@@ -320,13 +313,9 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
failed = append(failed, fmt.Sprintf("Couldn't publish to %s: %v", name, err))
continue
}
reddit = reddit || d.Channel == content.ChannelReddit
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL)
}
if reddit {
s.forgetRedditHistory()
}
if len(failed) > 0 {
fail(errors.New(strings.Join(failed, " ")))
return
@@ -363,8 +352,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err)
return
}
info, _ := content.GetSubreddit(s.DB, d.Target)
http.Redirect(w, r, redditSubmitURL(d, s.tagger(), info), http.StatusSeeOther)
http.Redirect(w, r, redditSubmitURL(d, s.tagger()), http.StatusSeeOther)
case "posted":
postURL := strings.TrimSpace(r.PostForm.Get("post_url"))
if postURL != "" {
@@ -377,7 +365,6 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
fail(err)
return
}
s.forgetRedditHistory()
redirect(w, r, back, "posted")
case "unschedule":
if err := content.Unschedule(s.DB, id); err != nil {
@@ -484,26 +471,36 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) {
// and still open; past it, the text is left for the user to paste.
const maxSubmitURL = 7500
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled
// in: a text post with the source link at the end, or a link post where the
// subreddit only takes links. It uses old.reddit.com, whose submit page
// reliably takes the title and text from the address.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger, info *reddit.Subreddit) string {
// redditText is what goes in a Reddit post: the draft's text with links to
// the company's sites tagged, and the source link at the end.
func redditText(d *content.Draft, tags *utm.Tagger) string {
text, src := content.Manual(d, tags)
base := "https://old.reddit.com/submit"
if sub := reddit.CleanName(d.Target); sub != "" {
base = "https://old.reddit.com/r/" + url.PathEscape(sub) + "/submit"
}
q := url.Values{"title": {d.Title}}
if info != nil && !info.AllowsText() && src != "" {
q.Set("url", src)
return base + "?" + q.Encode()
}
if src != "" && !strings.Contains(text, src) {
text += "\n\nSource: " + src
}
q.Set("selftext", "true")
q.Set("text", text)
return text
}
// redditSuffix is what Copy text adds after the text on screen: the source
// link, tagged, unless the text already has it.
func redditSuffix(d *content.Draft, tags *utm.Tagger) string {
text, src := content.Manual(d, tags)
if src == "" || strings.Contains(text, src) {
return ""
}
return "\n\nSource: " + src
}
// redditSubmitURL is Reddit's submit page for the draft's subreddit, filled
// in as a text post. It uses old.reddit.com, whose submit page reliably
// takes the title and text from the address. Text too long for an address
// is left out, for the user to paste.
func redditSubmitURL(d *content.Draft, tags *utm.Tagger) string {
base := "https://old.reddit.com/submit"
if sub := content.CleanSubreddit(d.Target); sub != "" {
base = "https://old.reddit.com/r/" + url.PathEscape(sub) + "/submit"
}
q := url.Values{"title": {d.Title}, "selftext": {"true"}, "text": {redditText(d, tags)}}
if u := base + "?" + q.Encode(); len(u) <= maxSubmitURL {
return u
}
+1 -30
View File
@@ -12,8 +12,6 @@ import (
"supermarket/examples"
"supermarket/internal/ai"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
@@ -39,7 +37,6 @@ type entryData struct {
DraftURL string // the address to fill in from
Filled []string // after filling in: what was filled
Suggestions []inventory.Suggestion
CanCheck bool // Reddit could be asked about the suggestions
Drafted bool
Today string // for new price rows
Blank []int // empty price rows to show
@@ -179,9 +176,7 @@ func (s *Server) inventoryFill(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
defer cancel()
check := s.subredditCheck(ctx)
d.CanCheck = check != nil
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check)
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours)
d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true
if err != nil {
// Links read before the model failed are kept.
@@ -277,30 +272,6 @@ func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}
// subredditCheck looks subreddits up on Reddit for Fill, using the cache
// and caching what it reads (drafting for the subreddit uses it later). It's
// nil if Reddit can't be asked: no client ID and secret.
func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
c, err := s.redditReader(ctx)
if err != nil {
return nil
}
return func(ctx context.Context, name string) (*reddit.Subreddit, error) {
if cached, err := content.GetSubreddit(s.DB, name); err == nil && cached != nil &&
time.Since(cached.FetchedAt) < content.SubredditMaxAge {
return cached, nil
}
info, err := c.SubredditInfo(ctx, name)
if err != nil {
return nil, err
}
if err := content.SaveSubreddit(s.DB, info); err != nil {
s.Log.Error("caching subreddit", "name", name, "err", err)
}
return info, nil
}
}
// marketRoom says why a new entry can't be added (the plan's limit), or nil.
func (s *Server) marketRoom(e *inventory.Entry) error {
if e.ID != 0 {
+1 -1
View File
@@ -220,7 +220,7 @@ func (s *Server) connectionSummary(map[string]Connection) string {
parts = append(parts, label)
}
if len(parts) == 0 {
return "Connect X, LinkedIn or Reddit"
return "Connect X or LinkedIn"
}
return strings.Join(parts, ", ")
}
+4 -35
View File
@@ -11,7 +11,6 @@ import (
"time"
"supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/content"
@@ -32,7 +31,7 @@ var adoptMu sync.Mutex
// the company's accounts, the first time they're seen.
func (s *Server) adoptLegacy() {
if !s.Secrets.Has(secrets.XAccessToken) && !s.Secrets.Has(secrets.LinkedInAccessToken) &&
!s.Secrets.Has(secrets.LinkedInPageAccessToken) && !s.Secrets.Has(secrets.RedditAccessToken) {
!s.Secrets.Has(secrets.LinkedInPageAccessToken) {
return
}
adoptMu.Lock()
@@ -59,9 +58,6 @@ func (s *Server) adoptLegacy() {
return o.Name, o.URN, expiry(conns[liPageProvider])
}
return "the company page", "", expiry(conns[liPageProvider])
case posting.Reddit:
u := s.Secrets.Get(secrets.RedditUsername)
return "u/" + u, u, time.Time{}
}
return "", "", time.Time{}
}, time.Now())
@@ -127,7 +123,9 @@ func (s *Server) working(a *posting.Account) bool {
func (s *Server) usableAccounts(v *viewer) map[string][]*posting.Account {
out := map[string][]*posting.Account{}
for _, a := range s.postingAccounts() {
if s.working(a) && s.mayPostAs(v, a) {
// Reddit accounts signed in before are left unused: Reddit is
// posted to by hand.
if a.Network != posting.Reddit && s.working(a) && s.mayPostAs(v, a) {
ch := posting.Channel(a.Network)
out[ch] = append(out[ch], a)
}
@@ -236,39 +234,10 @@ func (s *Server) publisherFor(a *posting.Account) (content.Publisher, error) {
return nil, errors.New("choose which company page " + a.Label() + " posts as, under Settings → Social accounts")
}
return asPublisher{linkedInPublisher{page: linkedin.New(tok, a.External)}, true}, nil
case posting.Reddit:
return redditPublisher{s: s, c: s.redditClient(a)}, nil
}
return nil, fmt.Errorf("no network %q", a.Network)
}
// redditClient is signed in as a Reddit account; refused tokens are
// refreshed and saved.
func (s *Server) redditClient(a *posting.Account) *reddit.Client {
id, ua := a.ID, reddit.UserAgent(s.Version, a.External)
return reddit.New(s.Secrets.Get(posting.AccessName(id)), ua, func(ctx context.Context) (string, error) {
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret), ua, s.Secrets.Get(posting.RefreshName(id)))
if err != nil {
return "", err
}
if err := posting.SaveTokens(s.Secrets, id, res.AccessToken, res.RefreshToken); err != nil {
s.Log.Error("reddit: couldn't save the refreshed token", "account", id, "err", err)
}
return res.AccessToken, nil
})
}
// companyReddit is the company's Reddit account, for reading rules and
// the account's history; nil if none.
func (s *Server) companyReddit() *posting.Account {
s.adoptLegacy()
a, err := posting.Company(s.DB, posting.Reddit)
if err != nil || a == nil || !s.Secrets.Has(posting.AccessName(a.ID)) {
return nil
}
return a
}
// removeAccount signs an account out: scheduled posts to it go back to
// Posts, and their writers are told.
func (s *Server) removeAccount(a *posting.Account, why string) error {
+1 -1
View File
@@ -42,7 +42,7 @@ var settingsPages = []struct {
}{
{hit{"Company profile", "Settings · your company, products, websites, voice and targets", "/settings/profile", ""},
"profile company products websites voice tone audience keywords feeds subreddits accounts"},
{hit{"Social accounts", "Settings · X, LinkedIn, Reddit and YouTube keys and sign-ins", "/settings/accounts", ""},
{hit{"Social accounts", "Settings · X, LinkedIn and YouTube keys and sign-ins", "/settings/accounts", ""},
"social accounts credentials keys x twitter linkedin reddit youtube sign in connect oauth bearer token"},
{hit{"AI", "Settings · provider, model, API keys and the Hermes key", "/settings/ai", ""},
"ai provider model anthropic claude openai ollama lm studio api key hermes effort"},
+3 -11
View File
@@ -25,7 +25,6 @@ import (
"unicode"
"unicode/utf8"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/appmail"
"supermarket/internal/billing"
@@ -111,12 +110,6 @@ type state struct {
// teamCache is what's kept in memory for a team.
type teamCache struct {
mu sync.Mutex
// Reddit: an app-only token for reading rules before sign-in, and the
// account's recent posts for the warnings.
redditAppToken string
redditAppTokenExp time.Time
redditHist []reddit.Submission
redditHistAt time.Time
// Google's access token, which lasts an hour.
googleToken string
googleExpires time.Time
@@ -448,7 +441,7 @@ func (s *Server) Handler() (http.Handler, error) {
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
})
mux.HandleFunc("POST /drafts/{id}/{action}", (*Server).draftAction)
mux.HandleFunc("POST /reddit/rules/{name}", (*Server).refreshRules)
mux.HandleFunc("POST /reddit/rules/{name}", (*Server).saveRules)
mux.HandleFunc("GET /prospects", (*Server).prospectsPage)
mux.HandleFunc("GET /prospects/new", (*Server).prospectForm)
@@ -870,7 +863,7 @@ type module struct {
}
var modules = []module{
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/posts"},
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X and LinkedIn; Reddit posts are written for you to post yourself.", "/posts"},
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo/check"},
{"sites", "Sites", "Phase 5", "Build pages from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"},
@@ -1026,7 +1019,6 @@ var flashes = map[string]string{
"audited": "The audit is done.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
@@ -1040,7 +1032,7 @@ var flashes = map[string]string{
"prospect-exists": "Already there: nothing new was added. It's in the list below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"rules-saved": "Rules saved: new drafts for that subreddit follow them.",
"imported": "Imported.",
"imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.",
"hunter-done": "Hunter.io search done: the result is on the card.",
+2 -37
View File
@@ -11,7 +11,6 @@ import (
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/reddit"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/posting"
@@ -158,7 +157,6 @@ type secretField struct {
const (
xConsole = "https://console.x.com"
linkedInApps = "https://www.linkedin.com/developers/apps"
redditApps = "https://www.reddit.com/prefs/apps"
googleCreds = "https://console.cloud.google.com/apis/credentials"
anthropicKeys = "https://platform.claude.com/settings/keys"
)
@@ -187,10 +185,6 @@ var accountFields = []secretField{
"A second LinkedIn app, linked to the company page, with the Community Management API approved by LinkedIn (it must be the app's only product). Its Auth tab has the ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"Reddit", secrets.RedditClientID, "Client ID",
"Create app → choose \"web app\" and enter the redirect URI above. The client ID is the string under the app's name.", redditApps},
{"Reddit", secrets.RedditClientSecret, "Client secret",
"On the same app, next to \"secret\".", redditApps},
{"YouTube", secrets.YouTubeAPIKey, "API key",
"Free. In Google Cloud, enable the YouTube Data API v3 for a project, then Credentials → Create credentials → API key. For reading channels' videos.", googleCreds},
}
@@ -254,7 +248,7 @@ func (s *Server) networks() []network {
}
set := s.secretState(names...)
accts := s.postingAccounts()
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage, "reddit": posting.Reddit}
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage}
connect := func(provider, token, setup, note string, ready bool, account func(string) string) *connectInfo {
c := &connectInfo{Provider: provider, Redirect: s.callbackURL(provider), Setup: setup, Note: note, Ready: ready}
for _, a := range accts {
@@ -276,7 +270,7 @@ func (s *Server) networks() []network {
}
}
var nets []network
for _, name := range []string{"X", "LinkedIn", liPageNetwork, "Reddit", "YouTube"} {
for _, name := range []string{"X", "LinkedIn", liPageNetwork, "YouTube"} {
n := network{Name: name, Set: set}
for _, f := range accountFields {
if f.Group == name {
@@ -297,10 +291,6 @@ func (s *Server) networks() []network {
set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup()
case "Reddit":
n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:",
"Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.",
set[secrets.RedditClientID] && set[secrets.RedditClientSecret], at("u/"))
}
nets = append(nets, n)
}
@@ -395,13 +385,6 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes())
case "reddit":
id := s.Secrets.Get(secrets.RedditClientID)
if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) {
http.Error(w, "Save Reddit's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.RedditStart(id, s.callbackURL("reddit"))
case "google":
id := s.Secrets.Get(secrets.GoogleClientID)
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
@@ -632,24 +615,6 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
return
}
redirect(w, r, "/settings/accounts", "li-page-connected")
case "reddit":
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), code, p)
if err != nil {
fail(err.Error())
return
}
name, err := reddit.New(res.AccessToken, s.redditUserAgent(), nil).Me(ctx)
if err != nil {
fail("Signed in, but couldn't read the Reddit account's name: " + err.Error())
return
}
if err := saveAccount(posting.Reddit, "u/"+name, name, res.AccessToken, res.RefreshToken, time.Time{}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
s.forgetRedditHistory()
redirect(w, r, back, ownMsg("reddit-connected"))
default:
http.NotFound(w, r)
}
+2
View File
@@ -67,6 +67,8 @@
if (src && navigator.clipboard) {
// A field's current value (with edits), else an element's text.
var value = "value" in src ? src.value : src.textContent;
// data-copy-suffix: added after it (a Reddit post's source link).
value += copy.getAttribute("data-copy-suffix") || "";
navigator.clipboard.writeText(value).then(function () {
var label = copy.textContent;
copy.textContent = "Copied";
+2 -2
View File
@@ -78,12 +78,12 @@
<legend>Channels</legend>
{{range .Channels}}
{{/* Reddit is never pre-checked: each post there is a deliberate choice. */}}
<label class="check"><input type="checkbox" name="channel" value="{{.ID}}" {{if and .Connected (ne .ID "reddit")}}checked{{end}}> {{.Name}}{{if not .Connected}} <span class="muted">(not connected: you can draft, but not publish yet)</span>{{end}}</label>
<label class="check"><input type="checkbox" name="channel" value="{{.ID}}" {{if and .Connected (ne .ID "reddit")}}checked{{end}}> {{.Name}}{{if eq .ID "reddit"}} <span class="muted">(you post it yourself)</span>{{else if not .Connected}} <span class="muted">(not connected: you can draft, but not publish yet)</span>{{end}}</label>
{{end}}
<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>
<span class="help">One subreddit per post. The rules you've pasted for it (on Posts) are followed when writing{{if .Subreddits}}; suggestions come from this entry and your profile{{end}}.</span>
</label>
</fieldset>
{{if .Signals}}
+3 -5
View File
@@ -6,7 +6,7 @@
<input type="hidden" name="id" value="{{$e.ID}}">
<section class="card">
<h2>Fill in with AI</h2>
<p class="help">Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords, hashtags and subreddits from the AI (subreddits checked with Reddit first), set against your <a href="/settings/profile">company profile</a>. What you've typed stays. Nothing is saved until you press Save.</p>
<p class="help">Reads their website and fills in the boxes that are still empty: links and accounts straight from the pages, and a description, talking points, keywords, hashtags and subreddits from the AI, set against your <a href="/settings/profile">company profile</a>. What you've typed stays. Nothing is saved until you press Save.</p>
{{if .NoAI}}<p class="warn-text">This needs the AI: first <a href="/settings/ai">set up the AI</a>, then come back. Or fill in the form by hand.</p>{{end}}
<div class="row">
<input name="draft_url" type="text" inputmode="url" value="{{.DraftURL}}" placeholder="https://example.com" aria-label="Their website">
@@ -17,18 +17,16 @@
{{with .Suggestions}}
<details class="suggestions" open>
<summary>Subreddits the AI suggested</summary>
{{if not $.Data.CanCheck}}<p class="warn-text small">Not checked with Reddit, so some may not exist: add Reddit's client ID and secret under <a href="/settings/accounts">Settings → Social accounts</a> and fill in again to check them.</p>{{end}}
<ul>
{{range .}}
<li class="{{if .Kept}}kept{{else}}dropped{{end}}">
<a href="https://www.reddit.com/r/{{.Name}}/" target="_blank" rel="noopener noreferrer">r/{{.Name}}</a>
{{with .Info}}<span class="muted small">{{.Subscribers}} members · {{if eq .SubmissionType "self"}}text posts only{{else if eq .SubmissionType "link"}}link posts only{{else}}text or links{{end}}</span>{{end}}
{{if .Kept}}{{if and .Problem $.Data.CanCheck}}<span class="warn-text small">{{.Problem}}</span>{{end}}{{else}}<span class="small">left out: {{.Problem}}</span>{{end}}
{{if not .Kept}}<span class="small">left out: more than enough already</span>{{end}}
{{with .Why}}<span class="help">{{.}}</span>{{end}}
</li>
{{end}}
</ul>
<p class="help">The ones kept are in the Subreddits box below. Look at each on Reddit before posting there: the AI picks by topic, not by how a community treats companies.</p>
<p class="help">The ones kept are in the Subreddits box below. They aren't checked with Reddit, so one may not exist, or be private: open each before posting there. The AI picks by topic, not by how a community treats companies.</p>
</details>
{{end}}
</section>
+23 -19
View File
@@ -1,6 +1,6 @@
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$accounts := .Accounts}}{{$chosen := .Chosen}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Posts</h1>
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it.
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it. Reddit posts you post yourself.
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
{{template "reminders" .Reminders}}
@@ -23,26 +23,37 @@
{{$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 class="rules" {{if not $rv.Info}}open{{end}}>
<summary>r/{{.Target}}'s rules{{with $rv.Info}} · pasted {{ago .SavedAt}}{{else}} · not pasted yet{{end}}</summary>
<form method="post" action="/reddit/rules/{{.Target}}">
<p class="help">Supermarket can't read them from Reddit. <a href="{{$rv.RulesURL}}" target="_blank" rel="noopener noreferrer">Open r/{{.Target}}'s rules ↗</a>, copy them, and paste them here: the next drafts for r/{{.Target}} follow them, and the warnings above use them. To use them for this draft, write it again after saving.</p>
<textarea name="rules" rows="6" aria-label="r/{{.Target}}'s rules" placeholder="Paste the rules here">{{with $rv.Info}}{{.Rules}}{{end}}</textarea>
<button type="submit" class="secondary small">Save rules</button>
</form>
</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>
<input name="title" id="title-{{.ID}}" 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}}" id="text-{{.ID}}">{{.Content}}</textarea>
{{if eq .Channel "reddit"}}{{if .SourceURL}}<p class="help">The source link is added at the end as “Source: …”.</p>{{end}}{{end}}
{{if eq .Channel "reddit"}}
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}</p>
<div class="by-hand">
<p class="small"><strong>Post it yourself.</strong> <em>Open in Reddit</em> saves your edits and opens r/{{.Target}}'s submit page in a new tab with the title and text filled in{{if .SourceURL}} (links to your sites tagged){{end}}. If a box comes up empty, copy it from here. Check it there and post.</p>
<div class="row">
<button type="submit" formaction="/drafts/{{.ID}}/open" formtarget="_blank">Open in Reddit ↗</button>
<button type="button" class="secondary small" data-copy="title-{{.ID}}">Copy title</button>
<button type="button" class="secondary small" data-copy="text-{{.ID}}" data-copy-suffix="{{with $rv}}{{.Suffix}}{{end}}">Copy text</button>
<button type="submit" class="secondary small">Save</button>
</div>
</div>
{{else}}
{{$d := .}}{{$accts := index $accounts .Channel}}
{{if $accts}}
<fieldset class="post-as">
@@ -62,15 +73,8 @@
</label>
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/schedule">Schedule</button>
</div>
{{if eq .Channel "reddit"}}
<div class="by-hand">
<p class="small"><strong>Or post it yourself</strong>{{if not (index $conn .Channel)}}, since Supermarket can't post to Reddit for you yet{{end}}: this saves your edits and opens r/{{.Target}}'s submit page in a new tab with the title and text filled in{{if .SourceURL}} (links to your sites tagged){{end}}. Check it there and post.</p>
<div class="row">
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/open" formtarget="_blank">Open in Reddit ↗</button>
<button type="button" class="secondary small" data-copy="text-{{.ID}}">Copy text</button>
</div>
</div>
{{else if not (index $conn .Channel)}}<p class="help">{{.ChannelName}} isn't connected: <a href="/settings/accounts">sign in</a> before it's due.</p>{{end}}
{{if not (index $conn .Channel)}}<p class="help">{{.ChannelName}} isn't connected: <a href="/settings/accounts">sign in</a> before it's due.</p>{{end}}
{{end}}
</form>
{{if eq .Channel "reddit"}}
<form method="post" action="/drafts/{{.ID}}/posted" class="by-hand-done">