diff --git a/internal/content/publish.go b/internal/content/publish.go index c6a842c..1f0831a 100644 --- a/internal/content/publish.go +++ b/internal/content/publish.go @@ -60,11 +60,7 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i return dr, err } - text, src := dr.Content, dr.SourceURL - if tags != nil { - p := dr.UTM() - text, src = tags.Text(text, p), tags.URL(src, p) - } + text, src := Manual(dr, tags) postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target}) now := formatTime(time.Now()) if pubErr != nil { @@ -92,3 +88,26 @@ func (d *Draft) UTM() utm.Params { } return utm.Params{Source: d.Channel, Medium: "social", Campaign: d.Kind, Content: content} } + +// MarkPosted records a draft the user posted by hand (on a network +// Supermarket can't post to for them), with the post's address if they +// gave one. +func MarkPosted(d *db.DB, id int64, postURL string) error { + now := formatTime(time.Now()) + res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', post_url = ?, published_at = ?, updated_at = ? + WHERE id = ? AND status IN (?, ?, ?)`, + StatusPublished, postURL, now, now, id, StatusDraft, StatusFailed, StatusScheduled) + return oneRow(res, err) +} + +// Manual is a draft as it would be published, for posting by hand: links +// to the company's sites tagged, and the source link added the way the +// channel's publisher would add it. +func Manual(dr *Draft, tags *utm.Tagger) (text, sourceURL string) { + text, sourceURL = dr.Content, dr.SourceURL + if tags != nil { + p := dr.UTM() + text, sourceURL = tags.Text(text, p), tags.URL(sourceURL, p) + } + return text, sourceURL +} diff --git a/internal/web/content_test.go b/internal/web/content_test.go index 7edca1d..2e69b22 100644 --- a/internal/web/content_test.go +++ b/internal/web/content_test.go @@ -316,3 +316,64 @@ func TestOwnContentPage(t *testing.T) { t.Errorf("write: %s", rec.Body.String()) } } + +func TestPostRedditByHand(t *testing.T) { + s, h := newTestServer(t, nil) + _ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://acme.example"}}}) + if _, err := content.CreateDrafts(s.DB, []content.Draft{ + {InventoryName: "Acme", Kind: "product", Channel: content.ChannelReddit, Title: "Widget 2", Target: "selfhosted", + Content: "We made a widget.", SourceURL: "https://acme.example/widget"}, + {InventoryName: "Acme", Kind: "product", Channel: content.ChannelReddit, Title: "Links", Target: "linksonly", + Content: "Body", SourceURL: "https://acme.example/w"}, + }); 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, "/inbox", 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"`) { + t.Error("inbox lacks the by-hand controls") + } + + // Open saves the edits, then goes to Reddit's submit page, filled in and tagged. + rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/open", url.Values{"title": {"Widget 2 is out"}, "content": {"Edited."}}) + loc, _ := url.Parse(rec.Header().Get("Location")) + q := loc.Query() + if rec.Code != http.StatusSeeOther || loc.Host != "old.reddit.com" || loc.Path != "/r/selfhosted/submit" || + q.Get("title") != "Widget 2 is out" || q.Get("selftext") != "true" || + !strings.HasPrefix(q.Get("text"), "Edited.\n\nSource: https://acme.example/widget?") || !strings.Contains(q.Get("text"), "utm_source=reddit") { + t.Errorf("open: %d %s", rec.Code, loc) + } + if d, _ := content.GetDraft(s.DB, mustID(ids["selfhosted"])); d.Title != "Widget 2 is out" || d.Content != "Edited." || d.Status != content.StatusDraft { + 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't a link to a post") { + t.Error("bad post link accepted") + } + post := "https://www.reddit.com/r/selfhosted/comments/abc/widget_2/" + if rec := postForm(h, "/drafts/"+ids["selfhosted"]+"/posted", url.Values{"post_url": {post}}); rec.Code != http.StatusSeeOther { + t.Fatalf("posted: %d %s", rec.Code, rec.Body.String()) + } + if d, _ := content.GetDraft(s.DB, mustID(ids["selfhosted"])); d.Status != content.StatusPublished || d.PostURL != post || d.PublishedAt.IsZero() { + t.Errorf("posted: %+v", d) + } + if !strings.Contains(do(h, http.MethodGet, "/content/published", nil, nil).Body.String(), post) { + t.Error("the post isn't listed under Published") + } + // Without a link it still counts as posted. + if rec := postForm(h, "/drafts/"+ids["linksonly"]+"/posted", nil); rec.Code != http.StatusSeeOther { + t.Errorf("posted without a link: %d", rec.Code) + } +} diff --git a/internal/web/inbox.go b/internal/web/inbox.go index a8ab849..e21106b 100644 --- a/internal/web/inbox.go +++ b/internal/web/inbox.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "net/url" "strconv" "strings" "time" @@ -228,7 +229,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) { action := r.PathValue("action") switch action { - case "save", "publish", "schedule": + case "save", "publish", "schedule", "open": if title, sent := r.PostForm["title"]; sent { if err := content.UpdateTitle(s.DB, id, title[0]); err != nil { fail(err) @@ -281,6 +282,30 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) { return } redirect(w, r, back, "scheduled") + case "open": + // Post by hand: the edits are saved above; now off to Reddit's + // submit page, filled in, in the tab the form opened. + d, err := content.GetDraft(s.DB, id) + if err != nil { + fail(err) + return + } + info, _ := content.GetSubreddit(s.DB, d.Target) + http.Redirect(w, r, redditSubmitURL(d, s.tagger(), info), http.StatusSeeOther) + case "posted": + postURL := strings.TrimSpace(r.PostForm.Get("post_url")) + if postURL != "" { + if u, err := url.Parse(postURL); err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + fail(errors.New("that isn't a link to a post: copy the address from your browser, or leave it empty")) + return + } + } + if err := content.MarkPosted(s.DB, id, postURL); err != nil { + fail(err) + return + } + s.forgetRedditHistory() + redirect(w, r, back, "posted") case "unschedule": if err := content.Unschedule(s.DB, id); err != nil { fail(err) @@ -370,3 +395,34 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) { s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel) } } + +// maxSubmitURL is about as long as a link to Reddit's submit page can be +// 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 { + 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) + if u := base + "?" + q.Encode(); len(u) <= maxSubmitURL { + return u + } + q.Del("text") + return base + "?" + q.Encode() +} diff --git a/internal/web/server.go b/internal/web/server.go index 0fda20a..c3bf94f 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -160,7 +160,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 https://www.reddit.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 https://old.reddit.com; frame-ancestors 'none'") next.ServeHTTP(w, r) }) } @@ -336,6 +336,7 @@ var flashes = map[string]string{ "published": "Published.", "discarded": "Discarded.", "scheduled": "Scheduled.", + "posted": "Marked as posted: it's under Content → Published.", "unscheduled": "Back in the Inbox: edit it, then publish or schedule it again.", } diff --git a/internal/web/static/app.css b/internal/web/static/app.css index 4db7560..384fb6a 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -365,3 +365,9 @@ form.inline { display: inline-block; margin: 0 0 0.75rem; } /* A sign-in running out */ .reminder { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; } .reminder p { margin: 0; flex: 1; min-width: 16rem; } + +/* Posting a Reddit draft by hand */ +.by-hand { border-top: 1px dashed hsl(var(--border)); margin-top: 0.75rem; padding-top: 0.75rem; } +.by-hand p { margin: 0 0 0.5rem; } +.by-hand-done { margin: 0.5rem 0 0.75rem; } +.by-hand-done .row input { margin: 0; } diff --git a/internal/web/static/app.js b/internal/web/static/app.js index 5c7f7e0..60a4770 100644 --- a/internal/web/static/app.js +++ b/internal/web/static/app.js @@ -44,7 +44,9 @@ if (copy) { var src = document.getElementById(copy.getAttribute("data-copy")); if (src && navigator.clipboard) { - navigator.clipboard.writeText(src.textContent).then(function () { + // A field's current value (with edits), else an element's text. + var value = "value" in src ? src.value : src.textContent; + navigator.clipboard.writeText(value).then(function () { var label = copy.textContent; copy.textContent = "Copied"; setTimeout(function () { copy.textContent = label; }, 1500); diff --git a/internal/web/templates/inbox.html b/internal/web/templates/inbox.html index 02c0ce5..31c1da5 100644 --- a/internal/web/templates/inbox.html +++ b/internal/web/templates/inbox.html @@ -41,7 +41,7 @@ {{end}} + aria-describedby="count-{{.ID}}" id="text-{{.ID}}">{{.Content}} {{if eq .Channel "reddit"}}{{if .SourceURL}}
The source link is added at the end as “Source: …”.
{{end}}{{end}}{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}
{{.ChannelName}} isn't connected: sign in before it's due.
{{end}} + {{if eq .Channel "reddit"}} +Or post it yourself{{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.
+{{.ChannelName}} isn't connected: sign in before it's due.
{{end}} + {{if eq .Channel "reddit"}} + + {{end}}