Files
supermarket/internal/web/inbox.go
T
davidandClaude Opus 5.5 4b2d791909 LinkedIn publishing works again; rename Inbox to Posts
LinkedIn:
- The API version was fixed at 202501, retired by LinkedIn (426
  NONEXISTENT_VERSION). It's now the month before last, stepping back a
  month (up to four) if LinkedIn says a version isn't active.
- The versioned Posts API needs a title for a link's article card (422).
  Supermarket reads the linked page's title and description and sends
  them, falling back to the page's address as the title.
Tested for real: a post with a link went out to the member's profile.

Inbox is now Posts: the menu, page, messages and docs; the page moves to
/posts, and /inbox redirects there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 12:50:06 -07:00

433 lines
12 KiB
Go

package web
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"supermarket/internal/api/reddit"
"supermarket/internal/content"
"supermarket/internal/profile"
"supermarket/internal/utm"
)
// --- Posts: everything waiting for the user's approval ---
// inboxSection is one module's share of Posts. Later phases add their
// own (prospects to send to the CRM, SEO changes to open as pull requests).
type inboxSection struct {
Module string
Batches []*draftBatch
}
type draftBatch struct {
Batch string
InventoryName string
Kind string
CreatedAt time.Time
SourceURL string
Drafts []content.Draft
}
// inboxCount is the number shown next to Inbox in the menu.
func (s *Server) inboxCount() int {
n, err := content.CountDrafts(s.DB)
if err != nil {
s.Log.Error("counting the inbox", "err", err)
}
return n
}
// groupBatches puts drafts written together side by side, channels in
// display order, keeping the order the drafts came in.
func groupBatches(drafts []content.Draft) []*draftBatch {
var batches []*draftBatch
byID := map[string]*draftBatch{}
for _, d := range drafts {
b := byID[d.Batch]
if b == nil {
b = &draftBatch{Batch: d.Batch, InventoryName: d.InventoryName, Kind: d.Kind, CreatedAt: d.CreatedAt, SourceURL: d.SourceURL}
byID[d.Batch] = b
batches = append(batches, b)
}
b.Drafts = append(b.Drafts, d)
}
for _, b := range batches {
ordered := make([]content.Draft, 0, len(b.Drafts))
for _, c := range content.Channels {
for _, d := range b.Drafts {
if d.Channel == c.ID {
ordered = append(ordered, d)
}
}
}
b.Drafts = ordered
}
return batches
}
func (s *Server) connected() map[string]bool {
out := map[string]bool{}
for id, p := range s.publishers() {
if _, expired := p.(expiredPublisher); !expired {
out[id] = true
}
}
return out
}
func (s *Server) inboxPage(w http.ResponseWriter, r *http.Request) {
s.renderInbox(w, r, "")
}
func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg string) {
pending, err := content.ListDrafts(s.DB, 200, content.StatusDraft, content.StatusFailed)
if err != nil {
s.serverError(w, err)
return
}
var sections []inboxSection
if len(pending) > 0 {
sections = append(sections, inboxSection{Module: "Content", Batches: groupBatches(pending)})
}
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),
"Connected": s.connected(),
"Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
"Zone": time.Now().Format("MST"),
}})
}
// redditView is what Posts 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()
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 {
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(),
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)}
}
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, "/posts", "rules-refreshed")
}
// The Content module's own lists of approved and published drafts.
func (s *Server) scheduledPage(w http.ResponseWriter, r *http.Request) {
s.renderScheduled(w, r, "")
}
func (s *Server) renderScheduled(w http.ResponseWriter, r *http.Request, errMsg string) {
drafts, err := content.ListDrafts(s.DB, 500, content.StatusScheduled)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-scheduled", page{Title: "Scheduled", Nav: "content/scheduled", Error: errMsg, Data: map[string]any{
"Drafts": drafts, "Connected": s.connected(), "Zone": time.Now().Format("MST"),
}})
}
func (s *Server) publishedPage(w http.ResponseWriter, r *http.Request) {
drafts, err := content.ListDrafts(s.DB, 200, content.StatusPublished)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "content-published", page{Title: "Published", Nav: "content/published", Data: map[string]any{"Drafts": drafts}})
}
// dateTimeLocal is the format of <input type="datetime-local">, read in the
// app's time zone (the computer's; see compose.yaml).
const dateTimeLocal = "2006-01-02T15:04"
func parseWhen(v string, now time.Time) (time.Time, error) {
v = strings.TrimSpace(v)
if v == "" {
return time.Time{}, errors.New("choose a date and time to publish")
}
at, err := time.ParseInLocation(dateTimeLocal, v, time.Local)
if err != nil {
return time.Time{}, fmt.Errorf("%q isn't a date and time", v)
}
// A minute's grace for a time picked as "now".
if at.Before(now.Add(-time.Minute)) {
return time.Time{}, errors.New("that time has passed: pick a later one, or publish now")
}
return at, nil
}
// draftAction saves, publishes, schedules, unschedules or discards one draft.
func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Where the form was: Posts, or the Scheduled list.
fromScheduled := r.PostForm.Get("from") == "scheduled"
back := "/posts"
if fromScheduled {
back = "/content/scheduled"
}
fail := func(err error) {
if errors.Is(err, content.ErrNoDraft) {
http.NotFound(w, r)
return
}
if fromScheduled {
s.renderScheduled(w, r, err.Error())
} else {
s.renderInbox(w, r, err.Error())
}
}
action := r.PathValue("action")
switch action {
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)
return
}
}
if text, sent := r.PostForm["content"]; sent {
if err := content.UpdateDraft(s.DB, id, text[0]); err != nil {
fail(err)
return
}
}
}
switch action {
case "save":
redirect(w, r, back, "saved")
case "publish":
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), id)
if err != nil {
name := "the channel"
if d != nil {
name = d.ChannelName()
}
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())
if err != nil {
fail(err)
return
}
d, err := content.GetDraft(s.DB, id)
if err != nil {
fail(err)
return
}
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 {
fail(err)
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)
return
}
redirect(w, r, "/posts", "unscheduled")
case "discard":
if err := content.DiscardDraft(s.DB, id); err != nil {
fail(err)
return
}
redirect(w, r, back, "discarded")
default:
http.NotFound(w, r)
}
}
// tagger adds UTM tags to links to the company's websites and product
// pages; nil if the profile lists none.
func (s *Server) tagger() *utm.Tagger {
p, err := profile.Load(s.DB)
if err != nil {
s.Log.Error("loading the profile for UTM tags", "err", err)
return nil
}
var sites []string
for _, w := range p.Websites {
sites = append(sites, w.URL)
}
for _, pr := range p.Products {
sites = append(sites, pr.URL)
}
t := utm.NewTagger(sites)
if !t.Any() {
return nil
}
return t
}
// --- The scheduler ---
// schedulerInterval is how often due drafts are looked for.
const schedulerInterval = 30 * time.Second
// RunScheduler publishes scheduled drafts when they're due, until ctx ends.
// The container runs all the time, so the browser needn't be open.
func (s *Server) RunScheduler(ctx context.Context) {
tick := time.NewTicker(schedulerInterval)
defer tick.Stop()
for {
s.publishDue(ctx, time.Now())
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
func (s *Server) publishDue(ctx context.Context, now time.Time) {
due, err := content.Due(s.DB, now)
if err != nil {
s.Log.Error("scheduler: listing due drafts", "err", err)
return
}
if len(due) == 0 {
return
}
pubs, tags := s.publishers(), s.tagger()
for _, d := range due {
if ctx.Err() != nil {
return
}
pctx, cancel := context.WithTimeout(ctx, 60*time.Second)
_, err := content.Publish(pctx, s.DB, pubs, tags, d.ID)
cancel()
if err != nil {
// A failed post is recorded on the draft by Publish. One refused
// before posting (not connected, too long) is still scheduled:
// send it back to Posts rather than retry it forever.
if ferr := content.FailScheduled(s.DB, d.ID, err.Error()); ferr != nil && !errors.Is(ferr, content.ErrNotEditable) {
s.Log.Error("scheduler: recording a failure", "draft", d.ID, "err", ferr)
}
s.Log.Warn("scheduler: publishing failed", "draft", d.ID, "channel", d.Channel, "err", err)
continue
}
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()
}