Phase 1, part 2: Inbox, scheduled publishing and UTM tags
- Inbox: a top-level page, with a count in the menu, for everything waiting for approval; Content's drafts are reviewed there. /drafts redirects to it. - Scheduling: publish a draft now or at a time (migration 3 adds publish_at). A scheduler in the app publishes due drafts every 30 seconds. Posts more than 12 hours overdue, or refused before posting, go back to the Inbox with the reason. Content gets Scheduled and Published tabs. - UTM tags on links to the company's own websites and product pages, added when publishing; drafts stay untagged. - The container runs in the computer's time zone, so times are shown and read correctly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@ package content
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/models"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/utm"
|
||||
)
|
||||
|
||||
func openDB(t *testing.T) *db.DB {
|
||||
@@ -123,13 +125,13 @@ func TestDraftsAndPublish(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
// LinkedIn isn't connected: refused, and nothing changes.
|
||||
pub := &fakePub{}
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") {
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") {
|
||||
t.Errorf("publishing without a connection: %v", err)
|
||||
}
|
||||
|
||||
// A failure is recorded; the draft can be fixed and published again.
|
||||
pub.err = errors.New("HTTP 503")
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, x.ID); err == nil {
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); err == nil {
|
||||
t.Fatal("expected the failure")
|
||||
}
|
||||
got, _ := GetDraft(d, x.ID)
|
||||
@@ -140,7 +142,7 @@ func TestDraftsAndPublish(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub.err = nil
|
||||
got, err = Publish(ctx, d, Publishers{ChannelX: pub}, x.ID)
|
||||
got, err = Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID)
|
||||
if err != nil || got.Status != StatusPublished || got.PostURL == "" || got.Error != "" {
|
||||
t.Fatalf("publish: %+v, %v", got, err)
|
||||
}
|
||||
@@ -148,7 +150,7 @@ func TestDraftsAndPublish(t *testing.T) {
|
||||
t.Errorf("published %q", last)
|
||||
}
|
||||
// Published once: a second click doesn't post again, and it can't be edited.
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, x.ID); !errors.Is(err, ErrBusy) {
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID); !errors.Is(err, ErrBusy) {
|
||||
t.Errorf("second publish: %v", err)
|
||||
}
|
||||
if err := UpdateDraft(d, x.ID, "again"); !errors.Is(err, ErrNotEditable) {
|
||||
@@ -161,7 +163,7 @@ func TestDraftsAndPublish(t *testing.T) {
|
||||
// Too long for X: refused before calling X.
|
||||
_, _ = CreateDrafts(d, []Draft{{Channel: ChannelX, Content: strings.Repeat("a", 270), SourceURL: "https://example.com"}})
|
||||
long, _ := ListDrafts(d, 1, StatusDraft)
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelX: pub}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
|
||||
t.Errorf("over-long post: %v", err)
|
||||
}
|
||||
|
||||
@@ -256,3 +258,76 @@ func TestGenerate(t *testing.T) {
|
||||
t.Error("expected an error without a profile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleAndDue(t *testing.T) {
|
||||
d := openDB(t)
|
||||
_, _ = CreateDrafts(d, []Draft{
|
||||
{InventoryName: "Jitsi Meet", Kind: "partner", Channel: ChannelLinkedIn, Content: "See https://acme.example/blog.", SourceURL: "https://acme.example/news"},
|
||||
})
|
||||
_, _ = CreateDrafts(d, []Draft{{InventoryName: "Old", Kind: "watch", Channel: ChannelX, Content: "Stale"}})
|
||||
all, _ := ListDrafts(d, 10, StatusDraft)
|
||||
var soon, stale Draft
|
||||
for _, dr := range all {
|
||||
if dr.InventoryName == "Old" {
|
||||
stale = dr
|
||||
} else {
|
||||
soon = dr
|
||||
}
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
if err := Schedule(d, soon.ID, now.Add(time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Schedule(d, stale.ID, now.Add(-13*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UpdateDraft(d, soon.ID, "edit"); !errors.Is(err, ErrNotEditable) {
|
||||
t.Errorf("a scheduled draft must be unscheduled before editing: %v", err)
|
||||
}
|
||||
if err := Schedule(d, soon.ID, now.AddDate(2, 0, 0)); err == nil {
|
||||
t.Error("scheduling twice or two years out should fail")
|
||||
}
|
||||
if n(CountDrafts(d)) != 0 {
|
||||
t.Errorf("scheduled drafts still counted for review")
|
||||
}
|
||||
|
||||
// Not due yet; the stale one goes back to the Inbox with a note.
|
||||
due, err := Due(d, now)
|
||||
if err != nil || len(due) != 0 {
|
||||
t.Fatalf("due now = %+v, %v", due, err)
|
||||
}
|
||||
if got, _ := GetDraft(d, stale.ID); got.Status != StatusFailed || !strings.Contains(got.Error, "wasn't running") {
|
||||
t.Errorf("stale draft: %+v", got)
|
||||
}
|
||||
due, _ = Due(d, now.Add(2*time.Hour))
|
||||
if len(due) != 1 || due[0].ID != soon.ID || !due[0].PublishAt.Equal(now.Add(time.Hour)) {
|
||||
t.Fatalf("due later = %+v", due)
|
||||
}
|
||||
|
||||
// Publishing tags only the company's links, and stores the draft untagged.
|
||||
pub := &fakePub{}
|
||||
tags := utm.NewTagger([]string{"acme.example"})
|
||||
got, err := Publish(context.Background(), d, Publishers{ChannelLinkedIn: pub}, tags, soon.ID)
|
||||
if err != nil || got.Status != StatusPublished {
|
||||
t.Fatalf("publish scheduled: %+v, %v", got, err)
|
||||
}
|
||||
q := fmt.Sprintf("utm_campaign=partner&utm_content=jitsi-meet-%d&utm_medium=social&utm_source=linkedin", soon.ID)
|
||||
want := "See https://acme.example/blog?" + q + ".|https://acme.example/news?" + q
|
||||
if pub.calls[0] != want {
|
||||
t.Errorf("published\n%s\nwant\n%s", pub.calls[0], want)
|
||||
}
|
||||
if got.Content != "See https://acme.example/blog." {
|
||||
t.Errorf("stored content changed: %q", got.Content)
|
||||
}
|
||||
|
||||
// Unschedule sends it back for editing.
|
||||
_, _ = CreateDrafts(d, []Draft{{Channel: ChannelX, Content: "Later"}})
|
||||
later, _ := ListDrafts(d, 1, StatusDraft)
|
||||
_ = Schedule(d, later[0].ID, now.Add(time.Hour))
|
||||
if err := Unschedule(d, later[0].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := GetDraft(d, later[0].ID); got.Status != StatusDraft || !got.PublishAt.IsZero() {
|
||||
t.Errorf("unscheduled: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,8 @@ func ChannelByID(id string) (Channel, bool) {
|
||||
|
||||
// Draft statuses.
|
||||
const (
|
||||
StatusDraft = "draft"
|
||||
StatusDraft = "draft" // waiting for review, in the Inbox
|
||||
StatusScheduled = "scheduled" // approved, goes out at PublishAt
|
||||
StatusPublishing = "publishing" // claimed by a publish in progress
|
||||
StatusPublished = "published"
|
||||
StatusFailed = "failed"
|
||||
@@ -69,6 +70,7 @@ type Draft struct {
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
PublishedAt time.Time
|
||||
PublishAt time.Time // when a scheduled draft goes out
|
||||
}
|
||||
|
||||
// Length is the draft's length as its channel counts it, including the
|
||||
@@ -155,20 +157,21 @@ func nonNil(s []string) []string {
|
||||
}
|
||||
|
||||
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
|
||||
post_url, created_at, updated_at, COALESCE(published_at, '')`
|
||||
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, '')`
|
||||
|
||||
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
|
||||
defer rows.Close()
|
||||
var out []Draft
|
||||
for rows.Next() {
|
||||
var dr Draft
|
||||
var ids, created, updated, published string
|
||||
var ids, created, updated, published, publishAt string
|
||||
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
|
||||
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published); err != nil {
|
||||
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
|
||||
dr.CreatedAt, dr.UpdatedAt, dr.PublishedAt = parseTime(created), parseTime(updated), parseTime(published)
|
||||
dr.PublishAt = parseTime(publishAt)
|
||||
out = append(out, dr)
|
||||
}
|
||||
return out, rows.Err()
|
||||
@@ -187,6 +190,8 @@ func ListDrafts(d *db.DB, limit int, statuses ...string) ([]Draft, error) {
|
||||
order := "created_at DESC, id DESC"
|
||||
if len(statuses) == 1 && statuses[0] == StatusPublished {
|
||||
order = "published_at DESC, id DESC"
|
||||
} else if len(statuses) == 1 && statuses[0] == StatusScheduled {
|
||||
order = "publish_at, id"
|
||||
}
|
||||
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status IN (?`+
|
||||
strings.Repeat(", ?", len(statuses)-1)+`) ORDER BY `+order+` LIMIT ?`, args...)
|
||||
@@ -266,3 +271,52 @@ func CountDrafts(d *db.DB) (int, error) {
|
||||
err := d.QueryRow(`SELECT count(*) FROM drafts WHERE status IN (?, ?)`, StatusDraft, StatusFailed).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Schedule approves a draft to go out at at. It must be one that can still
|
||||
// be published, and at most a year ahead.
|
||||
func Schedule(d *db.DB, id int64, at time.Time) error {
|
||||
if at.After(time.Now().AddDate(1, 0, 0)) {
|
||||
return errors.New("that's more than a year away")
|
||||
}
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = ?, error = '', updated_at = ?
|
||||
WHERE id = ? AND status IN (?, ?)`,
|
||||
StatusScheduled, formatTime(at), formatTime(time.Now()), id, StatusDraft, StatusFailed)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
// Unschedule sends a scheduled draft back to the Inbox, to edit or drop.
|
||||
func Unschedule(d *db.DB, id int64) error {
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, publish_at = NULL, updated_at = ? WHERE id = ? AND status = ?`,
|
||||
StatusDraft, formatTime(time.Now()), id, StatusScheduled)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
// MaxLate is how late a scheduled post may still go out, if the app was
|
||||
// stopped when it was due. Later than that, news is stale: it goes back to
|
||||
// the Inbox instead.
|
||||
const MaxLate = 12 * time.Hour
|
||||
|
||||
// Due returns the scheduled drafts whose time has come, oldest first. Ones
|
||||
// more than MaxLate overdue are sent back to the Inbox with a note.
|
||||
func Due(d *db.DB, now time.Time) ([]Draft, error) {
|
||||
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ?
|
||||
WHERE status = ? AND publish_at < ?`,
|
||||
StatusFailed, "Not published: Supermarket wasn't running when this was due. Publish or reschedule it.",
|
||||
formatTime(now), StatusScheduled, formatTime(now.Add(-MaxLate))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status = ? AND publish_at <= ?
|
||||
ORDER BY publish_at, id`, StatusScheduled, formatTime(now))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return scanDrafts(rows)
|
||||
}
|
||||
|
||||
// FailScheduled sends a scheduled draft that couldn't go out (its channel
|
||||
// was signed out, say) back to the Inbox with the reason.
|
||||
func FailScheduled(d *db.DB, id int64, reason string) error {
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ? AND status = ?`,
|
||||
StatusFailed, reason, formatTime(time.Now()), id, StatusScheduled)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/utm"
|
||||
)
|
||||
|
||||
// Publisher posts to one channel and returns the post's URL.
|
||||
@@ -23,12 +24,15 @@ var ErrBusy = errors.New("this draft is already being published, or was publishe
|
||||
// Publish posts one draft. It claims the draft first, so a second click or a
|
||||
// second tab can't post it twice. A failure is recorded on the draft, which
|
||||
// can then be edited and published again.
|
||||
func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft, error) {
|
||||
//
|
||||
// Links to the company's own sites get UTM tags (tags may be nil); the draft
|
||||
// itself is kept without them.
|
||||
func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, id int64) (*Draft, error) {
|
||||
dr, err := GetDraft(d, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !dr.Editable() {
|
||||
if !dr.Editable() && dr.Status != StatusScheduled {
|
||||
return dr, ErrBusy
|
||||
}
|
||||
pub := pubs[dr.Channel]
|
||||
@@ -44,8 +48,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft,
|
||||
dr.Length(), withLink, dr.ChannelName(), dr.Limit())
|
||||
}
|
||||
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?)`,
|
||||
StatusPublishing, formatTime(time.Now()), id, StatusDraft, StatusFailed)
|
||||
res, err := d.Exec(`UPDATE drafts SET status = ?, error = '', updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
|
||||
StatusPublishing, formatTime(time.Now()), id, StatusDraft, StatusFailed, StatusScheduled)
|
||||
if err := oneRow(res, err); err != nil {
|
||||
if errors.Is(err, ErrNotEditable) {
|
||||
return dr, ErrBusy
|
||||
@@ -53,7 +57,12 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft,
|
||||
return dr, err
|
||||
}
|
||||
|
||||
postURL, pubErr := pub.Publish(ctx, dr.Content, dr.SourceURL)
|
||||
text, src := dr.Content, dr.SourceURL
|
||||
if tags != nil {
|
||||
p := dr.UTM()
|
||||
text, src = tags.Text(text, p), tags.URL(src, p)
|
||||
}
|
||||
postURL, pubErr := pub.Publish(ctx, text, src)
|
||||
now := formatTime(time.Now())
|
||||
if pubErr != nil {
|
||||
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`,
|
||||
@@ -70,3 +79,13 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, id int64) (*Draft,
|
||||
}
|
||||
return GetDraft(d, id)
|
||||
}
|
||||
|
||||
// UTM is the tags for the draft's links: the channel, the kind of post,
|
||||
// and which entry and draft it was.
|
||||
func (d *Draft) UTM() utm.Params {
|
||||
content := fmt.Sprintf("draft-%d", d.ID)
|
||||
if slug := utm.Slug(d.InventoryName); slug != "" {
|
||||
content = slug + "-" + fmt.Sprint(d.ID)
|
||||
}
|
||||
return utm.Params{Source: d.Channel, Medium: "social", Campaign: d.Kind, Content: content}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,12 @@ FROM posts p, (SELECT 'x' AS channel UNION ALL SELECT 'linkedin') c
|
||||
WHERE NOT EXISTS (SELECT 1 FROM json_each(p.posted_to) WHERE value = c.channel)
|
||||
ORDER BY p.generated_at, c.channel;
|
||||
DROP TABLE posts;
|
||||
`,
|
||||
// 3: scheduling. An approved draft is "scheduled" with the time it goes
|
||||
// out; "publish now" is a schedule for the present.
|
||||
`
|
||||
ALTER TABLE drafts ADD COLUMN publish_at TEXT;
|
||||
CREATE INDEX drafts_due ON drafts (status, publish_at);
|
||||
`,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// Package utm adds UTM tags to links that point at the company's own sites,
|
||||
// so its analytics (Plausible) can tell which posts brought visitors. Links
|
||||
// elsewhere are left alone: no one else's analytics will read the tags.
|
||||
package utm
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Params are the tags for one post.
|
||||
type Params struct {
|
||||
Source string // the channel: x, linkedin, reddit
|
||||
Medium string // "social"
|
||||
Campaign string // the kind of post: partner, competitor, watch, product
|
||||
Content string // which post: entry and draft
|
||||
}
|
||||
|
||||
// Tagger knows which hosts are the company's.
|
||||
type Tagger struct {
|
||||
hosts []string
|
||||
}
|
||||
|
||||
// NewTagger takes the company's site and product URLs (or bare hosts).
|
||||
func NewTagger(sites []string) *Tagger {
|
||||
t := &Tagger{}
|
||||
seen := map[string]bool{}
|
||||
for _, s := range sites {
|
||||
h := host(s)
|
||||
if h != "" && !seen[h] {
|
||||
seen[h] = true
|
||||
t.hosts = append(t.hosts, h)
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func host(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
if !strings.Contains(s, "://") {
|
||||
s = "https://" + s
|
||||
}
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
|
||||
}
|
||||
|
||||
// Own reports whether rawURL is on one of the company's hosts or their
|
||||
// subdomains.
|
||||
func (t *Tagger) Own(rawURL string) bool {
|
||||
h := host(rawURL)
|
||||
if h == "" || !strings.Contains(rawURL, "://") {
|
||||
return false
|
||||
}
|
||||
for _, own := range t.hosts {
|
||||
if h == own || strings.HasSuffix(h, "."+own) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// URL tags rawURL if it's the company's. Tags already in the link win.
|
||||
func (t *Tagger) URL(rawURL string, p Params) string {
|
||||
if t == nil || !t.Own(rawURL) {
|
||||
return rawURL
|
||||
}
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return rawURL
|
||||
}
|
||||
q := u.Query()
|
||||
for k, v := range map[string]string{
|
||||
"utm_source": p.Source, "utm_medium": p.Medium, "utm_campaign": p.Campaign, "utm_content": p.Content,
|
||||
} {
|
||||
if v != "" && q.Get(k) == "" {
|
||||
q.Set(k, v)
|
||||
}
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// links finds http(s) URLs in text. Trailing punctuation that usually ends
|
||||
// a sentence isn't part of the link.
|
||||
var links = regexp.MustCompile(`https?://[^\s<>"]+`)
|
||||
|
||||
// Text tags the company's links inside a post.
|
||||
func (t *Tagger) Text(text string, p Params) string {
|
||||
if t == nil || len(t.hosts) == 0 {
|
||||
return text
|
||||
}
|
||||
return links.ReplaceAllStringFunc(text, func(m string) string {
|
||||
trail := ""
|
||||
for len(m) > 0 && strings.ContainsRune(".,;:!?)]}'", rune(m[len(m)-1])) {
|
||||
trail = m[len(m)-1:] + trail
|
||||
m = m[:len(m)-1]
|
||||
}
|
||||
return t.URL(m, p) + trail
|
||||
})
|
||||
}
|
||||
|
||||
// Slug turns a name into a lowercase tag value: "Jitsi Meet" → "jitsi-meet".
|
||||
func Slug(s string) string {
|
||||
var b strings.Builder
|
||||
dash := false
|
||||
for _, r := range strings.ToLower(s) {
|
||||
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||
b.WriteRune(r)
|
||||
dash = false
|
||||
} else if b.Len() > 0 && !dash {
|
||||
b.WriteByte('-')
|
||||
dash = true
|
||||
}
|
||||
}
|
||||
return strings.TrimSuffix(b.String(), "-")
|
||||
}
|
||||
|
||||
// Any reports whether the tagger knows any of the company's hosts.
|
||||
func (t *Tagger) Any() bool { return t != nil && len(t.hosts) > 0 }
|
||||
@@ -0,0 +1,42 @@
|
||||
package utm
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTagger(t *testing.T) {
|
||||
tg := NewTagger([]string{"https://www.acme.example/", "acme.dev", "", "https://acme.example/pricing"})
|
||||
p := Params{Source: "x", Medium: "social", Campaign: "partner", Content: "jitsi-12"}
|
||||
|
||||
for in, want := range map[string]string{
|
||||
"https://acme.example/blog/post": "https://acme.example/blog/post?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x",
|
||||
"https://docs.acme.dev/x?a=1": "https://docs.acme.dev/x?a=1&utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x",
|
||||
"https://www.acme.example/?utm_source=newsletter#top": "https://www.acme.example/?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=newsletter#top",
|
||||
"https://jitsi.org/news": "https://jitsi.org/news",
|
||||
"https://notacme.example/": "https://notacme.example/",
|
||||
"https://x.com/acme/status/1": "https://x.com/acme/status/1",
|
||||
"": "",
|
||||
} {
|
||||
if got := tg.URL(in, p); got != want {
|
||||
t.Errorf("URL(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
text := "Read it (https://acme.example/a). Or https://jitsi.org/b, or https://acme.dev!"
|
||||
want := "Read it (https://acme.example/a?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x). " +
|
||||
"Or https://jitsi.org/b, or https://acme.dev?utm_campaign=partner&utm_content=jitsi-12&utm_medium=social&utm_source=x!"
|
||||
if got := tg.Text(text, p); got != want {
|
||||
t.Errorf("Text =\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
|
||||
var none *Tagger
|
||||
if none.URL("https://acme.example", p) != "https://acme.example" || NewTagger(nil).Text(text, p) != text {
|
||||
t.Error("a tagger without sites must change nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlug(t *testing.T) {
|
||||
for in, want := range map[string]string{"Jitsi Meet": "jitsi-meet", " Acme, Inc. ": "acme-inc", "Ünïcode 2": "n-code-2", "": ""} {
|
||||
if got := Slug(in); got != want {
|
||||
t.Errorf("Slug(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-129
@@ -45,10 +45,7 @@ func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) {
|
||||
rows = append(rows, contentRow{Entry: e, Sources: fetcher.Sources(&e),
|
||||
Waiting: counts[strings.ToLower(e.Name)], LastChecked: last})
|
||||
}
|
||||
drafts, _ := content.CountDrafts(s.DB)
|
||||
s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{
|
||||
"Rows": rows, "Drafts": drafts,
|
||||
}})
|
||||
s.render(w, r, "content", page{Title: "Content", Nav: "content", Data: map[string]any{"Rows": rows}})
|
||||
}
|
||||
|
||||
type channelChoice struct {
|
||||
@@ -65,7 +62,6 @@ type entryPage struct {
|
||||
Since time.Time
|
||||
Channels []channelChoice
|
||||
ProfileSet bool
|
||||
Drafts int
|
||||
// After a fetch
|
||||
Fetched bool
|
||||
NewItems int
|
||||
@@ -109,9 +105,8 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
|
||||
for _, c := range content.Channels {
|
||||
chans = append(chans, channelChoice{c, pubs[c.ID] != nil})
|
||||
}
|
||||
drafts, _ := content.CountDrafts(s.DB)
|
||||
return &entryPage{Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed,
|
||||
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet(), Drafts: drafts}, nil
|
||||
LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil
|
||||
}
|
||||
|
||||
func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -206,7 +201,7 @@ func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) {
|
||||
showErr(err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/drafts", "drafted")
|
||||
redirect(w, r, "/inbox", "drafted")
|
||||
default:
|
||||
http.Error(w, "unknown action", http.StatusBadRequest)
|
||||
}
|
||||
@@ -272,124 +267,3 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Drafts ---
|
||||
|
||||
type draftBatch struct {
|
||||
Batch string
|
||||
InventoryName string
|
||||
Kind string
|
||||
CreatedAt time.Time
|
||||
SourceURL string
|
||||
Drafts []content.Draft
|
||||
}
|
||||
|
||||
func (s *Server) draftsPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderDrafts(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderDrafts(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 batches []*draftBatch
|
||||
byID := map[string]*draftBatch{}
|
||||
for _, d := range pending {
|
||||
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 {
|
||||
// X first, then LinkedIn, whatever order they were stored in.
|
||||
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
|
||||
}
|
||||
published, err := content.ListDrafts(s.DB, 20, content.StatusPublished)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
pubs := s.publishers()
|
||||
connected := map[string]bool{}
|
||||
for id := range pubs {
|
||||
connected[id] = true
|
||||
}
|
||||
s.render(w, r, "drafts", page{Title: "Drafts", Nav: "content", Error: errMsg, Data: map[string]any{
|
||||
"Batches": batches, "Published": published, "Connected": connected,
|
||||
}})
|
||||
}
|
||||
|
||||
func (s *Server) draftID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
// draftAction saves, publishes or discards one draft.
|
||||
func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := s.draftID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
fail := func(err error) {
|
||||
if errors.Is(err, content.ErrNoDraft) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
s.renderDrafts(w, r, err.Error())
|
||||
}
|
||||
action := r.PathValue("action")
|
||||
if action == "save" || action == "publish" {
|
||||
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, "/drafts", "saved")
|
||||
case "publish":
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
d, err := content.Publish(ctx, s.DB, s.publishers(), 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
|
||||
}
|
||||
redirect(w, r, "/drafts", "published")
|
||||
case "discard":
|
||||
if err := content.DiscardDraft(s.DB, id); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/drafts", "discarded")
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -89,11 +90,15 @@ func TestDraftsPage(t *testing.T) {
|
||||
ids[d.Channel] = strconv.FormatInt(d.ID, 10)
|
||||
}
|
||||
|
||||
rec := do(h, http.MethodGet, "/drafts", nil, nil)
|
||||
if rec := do(h, http.MethodGet, "/drafts?msg=drafted", nil, nil); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/inbox?msg=drafted" {
|
||||
t.Errorf("old drafts page: %d %s", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
rec := do(h, http.MethodGet, "/inbox", nil, nil)
|
||||
body := rec.Body.String()
|
||||
if rec.Code != 200 || strings.Index(body, "X text") > strings.Index(body, "LinkedIn text") ||
|
||||
!strings.Contains(body, "31 / 280 including the link") || !strings.Contains(body, `data-reserve="25"`) {
|
||||
t.Errorf("drafts page (X should come first):\n%s", body)
|
||||
!strings.Contains(body, "31 / 280 including the link") || !strings.Contains(body, `data-reserve="25"`) ||
|
||||
!strings.Contains(body, `class="count-badge">2<`) {
|
||||
t.Errorf("inbox (X should come first, menu count 2):\n%s", body)
|
||||
}
|
||||
|
||||
// Save an edit.
|
||||
@@ -123,6 +128,71 @@ func TestDraftsPage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleFromInbox(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
if _, err := content.CreateDrafts(s.DB, []content.Draft{{InventoryName: "Jitsi", Kind: "partner", Channel: content.ChannelX, Content: "Soon"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
drafts, _ := content.ListDrafts(s.DB, 1, content.StatusDraft)
|
||||
id := strconv.FormatInt(drafts[0].ID, 10)
|
||||
|
||||
// A past time, or none, is refused.
|
||||
past := time.Now().Add(-time.Hour).Format(dateTimeLocal)
|
||||
if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {past}}); !strings.Contains(rec.Body.String(), "that time has passed") {
|
||||
t.Errorf("past time: %s", rec.Body.String())
|
||||
}
|
||||
if rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"when": {""}}); !strings.Contains(rec.Body.String(), "choose a date") {
|
||||
t.Errorf("no time: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
when := time.Now().Add(2 * time.Hour).Truncate(time.Minute)
|
||||
rec := postForm(h, "/drafts/"+id+"/schedule", url.Values{"content": {"Soon, edited"}, "when": {when.Format(dateTimeLocal)}})
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("schedule: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
d, _ := content.GetDraft(s.DB, mustID(id))
|
||||
if d.Status != content.StatusScheduled || !d.PublishAt.Equal(when) || d.Content != "Soon, edited" {
|
||||
t.Errorf("scheduled draft: %+v (want %v)", d, when)
|
||||
}
|
||||
body := do(h, http.MethodGet, "/content/scheduled", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "Soon, edited") || !strings.Contains(body, when.Format("15:04")) || !strings.Contains(body, "not connected") {
|
||||
t.Errorf("scheduled page:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(do(h, http.MethodGet, "/inbox", nil, nil).Body.String(), "Nothing waiting") {
|
||||
t.Error("a scheduled draft is still in the Inbox")
|
||||
}
|
||||
|
||||
// When it's due and X isn't connected, it goes back to the Inbox with
|
||||
// the reason instead of being retried for ever.
|
||||
s.publishDue(context.Background(), when.Add(time.Minute))
|
||||
d, _ = content.GetDraft(s.DB, mustID(id))
|
||||
if d.Status != content.StatusFailed || !strings.Contains(d.Error, "isn't connected") {
|
||||
t.Errorf("after the scheduler: %+v", d)
|
||||
}
|
||||
|
||||
// Unschedule from the Scheduled page.
|
||||
_ = content.Schedule(s.DB, mustID(id), when)
|
||||
if rec := postForm(h, "/drafts/"+id+"/unschedule", url.Values{"from": {"scheduled"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("unschedule: %d", rec.Code)
|
||||
}
|
||||
if d, _ := content.GetDraft(s.DB, mustID(id)); d.Status != content.StatusDraft {
|
||||
t.Errorf("unscheduled: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaggerFromProfile(t *testing.T) {
|
||||
s, _ := newTestServer(t, nil)
|
||||
if s.tagger() != nil {
|
||||
t.Error("no sites in the profile: no tagger")
|
||||
}
|
||||
_ = profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "x",
|
||||
Websites: []profile.Website{{URL: "https://acme.example"}}, Products: []profile.Product{{Name: "P", URL: "https://app.acme.dev/p"}}})
|
||||
tg := s.tagger()
|
||||
if tg == nil || !tg.Own("https://acme.example/blog") || !tg.Own("https://app.acme.dev/") || tg.Own("https://jitsi.org") {
|
||||
t.Errorf("tagger: %+v", tg)
|
||||
}
|
||||
}
|
||||
|
||||
func mustID(s string) int64 {
|
||||
n, _ := strconv.ParseInt(s, 10, 64)
|
||||
return n
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/utm"
|
||||
)
|
||||
|
||||
// --- The Inbox: everything waiting for the user's approval ---
|
||||
|
||||
// inboxSection is one module's share of the Inbox. 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 := range s.publishers() {
|
||||
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: "Inbox", Nav: "inbox", Error: errMsg, Data: map[string]any{
|
||||
"Sections": sections,
|
||||
"Connected": s.connected(),
|
||||
"Tagged": s.tagger() != nil,
|
||||
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
|
||||
"Zone": time.Now().Format("MST"),
|
||||
}})
|
||||
}
|
||||
|
||||
// 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", 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", 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: the Inbox, or the Scheduled list.
|
||||
fromScheduled := r.PostForm.Get("from") == "scheduled"
|
||||
back := "/inbox"
|
||||
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":
|
||||
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
|
||||
}
|
||||
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 d.TooLong() {
|
||||
fail(fmt.Errorf("the %s post is %d characters; it allows %d. Shorten it before scheduling", d.ChannelName(), d.Length(), d.Limit()))
|
||||
return
|
||||
}
|
||||
if err := content.Schedule(s.DB, id, at); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, back, "scheduled")
|
||||
case "unschedule":
|
||||
if err := content.Unschedule(s.DB, id); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/inbox", "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 the Inbox 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)
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -95,7 +95,12 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("GET /content/{id}", s.contentEntry)
|
||||
mux.HandleFunc("POST /content/{id}/fetch", s.contentFetch)
|
||||
mux.HandleFunc("POST /content/{id}/items", s.contentItems)
|
||||
mux.HandleFunc("GET /drafts", s.draftsPage)
|
||||
mux.HandleFunc("GET /content/scheduled", s.scheduledPage)
|
||||
mux.HandleFunc("GET /content/published", s.publishedPage)
|
||||
mux.HandleFunc("GET /inbox", s.inboxPage)
|
||||
mux.HandleFunc("GET /drafts", func(w http.ResponseWriter, r *http.Request) {
|
||||
redirect(w, r, "/inbox", r.URL.Query().Get("msg"))
|
||||
})
|
||||
mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction)
|
||||
|
||||
mux.HandleFunc("GET /core", s.corePage)
|
||||
@@ -201,6 +206,7 @@ type page struct {
|
||||
Flash string
|
||||
Error string
|
||||
Data any
|
||||
Inbox int // drafts waiting for review, shown in the menu
|
||||
}
|
||||
|
||||
// render writes a full page, or only its "content" block for htmx requests
|
||||
@@ -212,6 +218,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p
|
||||
return
|
||||
}
|
||||
p.Version = s.Version
|
||||
p.Inbox = s.inboxCount()
|
||||
if p.Flash == "" {
|
||||
p.Flash = flashes[r.URL.Query().Get("msg")]
|
||||
}
|
||||
@@ -247,6 +254,8 @@ var flashes = map[string]string{
|
||||
"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) {
|
||||
|
||||
@@ -89,7 +89,8 @@ func TestEveryPageRenders(t *testing.T) {
|
||||
for _, path := range []string{"/", "/?msg=saved", "/profile", "/inventory", "/inventory?relationship=partner",
|
||||
"/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export",
|
||||
"/settings/ai", "/settings/credentials", "/core", "/static/app.css", "/static/htmx.min.js", "/healthz",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/drafts", "/drafts?msg=drafted"} {
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/inbox", "/inbox?msg=drafted",
|
||||
"/content/scheduled", "/content/published"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String())
|
||||
|
||||
@@ -139,3 +139,10 @@ button.pill:hover { background: #e0f2f7; }
|
||||
.count { margin: 0.3rem 0 0; font-size: 0.85rem; color: var(--muted); text-align: right; }
|
||||
.count.over { color: var(--bad); font-weight: 600; }
|
||||
button.small { padding: 0.3rem 0.8rem; font-size: 0.85rem; }
|
||||
.count-badge { display: inline-block; min-width: 1.3rem; padding: 0 0.35rem; margin-left: 0.2rem; border-radius: 999px; background: var(--magenta); color: #fff; font-size: 0.75rem; font-weight: 700; text-align: center; line-height: 1.3rem; }
|
||||
.schedule { display: flex; gap: 0.5rem; align-items: flex-end; flex-wrap: wrap; margin-bottom: 0.5rem; }
|
||||
.schedule label { margin: 0; flex: 1; min-width: 12rem; }
|
||||
.row-actions { white-space: nowrap; }
|
||||
.row-actions form { display: inline-block; margin: 0 0.25rem 0.25rem 0; }
|
||||
.post-text { overflow-wrap: anywhere; }
|
||||
.small { font-size: 0.85rem; }
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{{define "content"}}{{with .Data}}
|
||||
<nav class="tabs">
|
||||
<a href="/content" aria-current="page">Sources</a>
|
||||
<a href="/drafts">Drafts{{if .Drafts}} ({{.Drafts}}){{end}}</a>
|
||||
<a href="/content/scheduled">Scheduled</a>
|
||||
<a href="/content/published">Published</a>
|
||||
</nav>
|
||||
<div class="heading">
|
||||
<h1>{{.Entry.Name}} <span class="badge {{.Entry.Relationship}}">{{.Entry.Relationship}}</span></h1>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{{define "content"}}{{with .Data}}
|
||||
<nav class="tabs">
|
||||
<a href="/content">Sources</a>
|
||||
<a href="/content/scheduled">Scheduled</a>
|
||||
<a href="/content/published" aria-current="page">Published</a>
|
||||
</nav>
|
||||
<h1>Published</h1>
|
||||
<p class="lede">The last 200 posts Supermarket published.</p>
|
||||
|
||||
{{if .Drafts}}
|
||||
<table class="list">
|
||||
<thead><tr><th>When</th><th>Channel</th><th>Entry</th><th>Post</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Drafts}}
|
||||
<tr>
|
||||
<td>{{.PublishedAt.Local.Format "2 Jan 2006 15:04"}}</td>
|
||||
<td>{{.ChannelName}}</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>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}
|
||||
<section class="card empty"><p>Nothing published yet.</p></section>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -0,0 +1,36 @@
|
||||
{{define "content"}}{{with .Data}}{{$conn := .Connected}}
|
||||
<nav class="tabs">
|
||||
<a href="/content">Sources</a>
|
||||
<a href="/content/scheduled" aria-current="page">Scheduled</a>
|
||||
<a href="/content/published">Published</a>
|
||||
</nav>
|
||||
<h1>Scheduled</h1>
|
||||
<p class="lede">Approved posts, in the order they go out ({{.Zone}}). Supermarket publishes them on time as long as it's running; one more than 12 hours late goes back to the Inbox instead.</p>
|
||||
|
||||
{{if .Drafts}}
|
||||
<table class="list">
|
||||
<thead><tr><th>When</th><th>Channel</th><th>Entry</th><th>Post</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{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>{{.InventoryName}}</td>
|
||||
<td class="post-text">{{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">
|
||||
<button type="submit" class="small" {{if not (index $conn .Channel)}}disabled{{end}}>Publish now</button>
|
||||
</form>
|
||||
<form method="post" action="/drafts/{{.ID}}/unschedule">
|
||||
<button type="submit" class="secondary small">Unschedule</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{else}}
|
||||
<section class="card empty"><p>Nothing scheduled. Schedule drafts from the <a href="/inbox">Inbox</a>.</p></section>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -1,10 +1,11 @@
|
||||
{{define "content"}}{{with .Data}}
|
||||
<nav class="tabs">
|
||||
<a href="/content" aria-current="page">Sources</a>
|
||||
<a href="/drafts">Drafts{{if .Drafts}} ({{.Drafts}}){{end}}</a>
|
||||
<a href="/content/scheduled">Scheduled</a>
|
||||
<a href="/content/published">Published</a>
|
||||
</nav>
|
||||
<h1>Content</h1>
|
||||
<p class="lede">Pick an inventory entry to fetch its latest news, choose what to write about, and get a draft for each channel to review on the <a href="/drafts">Drafts</a> page.</p>
|
||||
<p class="lede">Pick an inventory entry to fetch its latest news, choose what to write about, and get a draft for each channel to review in the <a href="/inbox">Inbox</a>.</p>
|
||||
|
||||
{{if .Rows}}
|
||||
<table class="list">
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<details class="card">
|
||||
<summary>Imported from the old terminal app {{ago .ImportStatus.At}}</summary>
|
||||
<ul>{{range .ImportStatus.Summary}}<li>{{.}}</li>{{end}}</ul>
|
||||
{{if .QueuedPosts}}<p>Its queued posts are now drafts: <a href="/drafts">{{.QueuedPosts}} waiting for review</a>.</p>{{end}}
|
||||
{{if .QueuedPosts}}<p>Its queued posts are now drafts: <a href="/inbox">{{.QueuedPosts}} waiting in the Inbox</a>.</p>{{end}}
|
||||
</details>
|
||||
{{end}}
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{{define "content"}}{{with .Data}}{{$conn := .Connected}}
|
||||
<nav class="tabs">
|
||||
<a href="/content">Sources</a>
|
||||
<a href="/drafts" aria-current="page">Drafts</a>
|
||||
</nav>
|
||||
<h1>Drafts</h1>
|
||||
<p class="lede">Each draft is for one channel, and is published on its own: if one channel fails, the other isn't posted twice. The source link is added when publishing.</p>
|
||||
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$now := .Now}}{{$zone := .Zone}}
|
||||
<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>
|
||||
|
||||
{{if .Batches}}
|
||||
{{if .Sections}}
|
||||
{{range .Sections}}
|
||||
<h2>{{.Module}}</h2>
|
||||
{{range .Batches}}
|
||||
<section class="card batch">
|
||||
<p class="meta">
|
||||
@@ -18,7 +17,7 @@
|
||||
{{range .Drafts}}
|
||||
<div class="draft{{if eq .Status "failed"}} failed{{end}}">
|
||||
<h3>{{.ChannelName}}</h3>
|
||||
{{if .Error}}<p class="error">Last attempt failed: {{.Error}}</p>{{end}}
|
||||
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
|
||||
<form method="post" action="/drafts/{{.ID}}/save" data-busy-on="publish" data-busy="Publishing…">
|
||||
<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}}"
|
||||
@@ -26,9 +25,16 @@
|
||||
<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"
|
||||
{{if not (index $conn .Channel)}}disabled title="Sign in to {{.ChannelName}} under Settings → Credentials"{{end}}>Publish to {{.ChannelName}}</button>
|
||||
{{if not (index $conn .Channel)}}disabled title="Sign in to {{.ChannelName}} under Settings → Credentials"{{end}}>Publish now</button>
|
||||
<button type="submit" class="secondary">Save</button>
|
||||
</div>
|
||||
<div class="schedule">
|
||||
<label class="small">Or publish at ({{$zone}})
|
||||
<input type="datetime-local" name="when" value="{{$now}}">
|
||||
</label>
|
||||
<button type="submit" class="secondary" formaction="/drafts/{{.ID}}/schedule">Schedule</button>
|
||||
</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?">
|
||||
<button type="submit" class="danger small">Discard</button>
|
||||
@@ -38,26 +44,10 @@
|
||||
</div>
|
||||
</section>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{else}}
|
||||
<section class="card empty">
|
||||
<p>No drafts waiting. Write some from the <a href="/content">Sources</a> page.</p>
|
||||
<p>Nothing waiting. Write posts from <a href="/content">Content</a>; scheduled ones are under <a href="/content/scheduled">Content → Scheduled</a>.</p>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
{{if .Published}}
|
||||
<h2>Recently published</h2>
|
||||
<table class="list">
|
||||
<thead><tr><th>When</th><th>Channel</th><th>Entry</th><th>Post</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Published}}
|
||||
<tr>
|
||||
<td>{{ago .PublishedAt}}</td>
|
||||
<td>{{.ChannelName}}</td>
|
||||
<td>{{.InventoryName}}</td>
|
||||
<td>{{if .PostURL}}<a href="{{.PostURL}}" target="_blank" rel="noopener noreferrer">{{truncate 80 .Content}}</a>{{else}}{{truncate 80 .Content}}{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
@@ -15,6 +15,7 @@
|
||||
<nav>
|
||||
<a href="/" {{if eq .Nav "home"}}aria-current="page"{{end}}>Overview</a>
|
||||
<a href="/profile" {{if eq .Nav "profile"}}aria-current="page"{{end}}>Profile</a>
|
||||
<a href="/inbox" {{if eq .Nav "inbox"}}aria-current="page"{{end}}>Inbox{{if .Inbox}} <span class="count-badge">{{.Inbox}}</span>{{end}}</a>
|
||||
<a href="/content" {{if eq .Nav "content"}}aria-current="page"{{end}}>Content</a>
|
||||
<a href="/inventory" {{if eq .Nav "inventory"}}aria-current="page"{{end}}>Inventory</a>
|
||||
<a href="/settings/ai" {{if eq .Nav "settings"}}aria-current="page"{{end}}>Settings</a>
|
||||
|
||||
Reference in New Issue
Block a user