Phase 10, part 7: posting accounts, and who may post to which
Social accounts become posting accounts: several per network, the company's and each person's own, with their tokens kept per account. The old sign-ins are adopted as the company's. Admins say who may post to which (Settings → Posting accounts); a draft can go out from one account or a copy to several, each recording who posted it and as what. Signing an account out, or removing its owner, holds the posts scheduled to it and tells whoever scheduled them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2309,6 +2309,41 @@ starts** (multi-tenant still doesn't).
|
||||
`connections:changed`). Tokens Supermarket refreshes itself aren't
|
||||
counted. The existing pages stay where they were, behind admin access.
|
||||
|
||||
**Part 7 built 2026-11-25** on `phase10`.
|
||||
- Schema 35: `posting_accounts` (network: x, linkedin, linkedin_page,
|
||||
reddit; name; the network's ID for it; owner, 0 for the company's;
|
||||
expiry) and `posting_grants`; drafts get `account_id` (0: the company's
|
||||
account for its channel), `written_by`, `posted_by` and `posted_as`.
|
||||
`internal/posting` keeps them; each account's tokens are in the secrets
|
||||
store as `acct:<id>:access` and `:refresh` (refreshed tokens are saved
|
||||
there, per account).
|
||||
- The old single sign-ins become the company's accounts the first time
|
||||
they're seen (at start, or when the old app's import brings them), and
|
||||
their old secrets are cleared.
|
||||
- Signing in: admins connect the company's accounts on Social accounts
|
||||
(each card lists its accounts, with *Sign out*); anyone with Content
|
||||
edit connects their own under Your account (`/auth/<network>/start?for=me`,
|
||||
the person recorded in the OAuth state; only they can finish it). The
|
||||
same app keys serve both. One LinkedIn page sign-in for the company,
|
||||
following the page chosen.
|
||||
- Settings → Posting accounts: people against accounts. Admins may post
|
||||
to all; a person's own account is theirs; ticks give others. Members
|
||||
also need Content edit.
|
||||
- On a draft, *Post as* lists the accounts the person may post to that
|
||||
work (signed in, not expired, a page chosen), the draft's current one
|
||||
ticked. Several ticked: the draft goes to the first and a copy (same
|
||||
batch) to each other, all published or scheduled together. Posting as
|
||||
an account needs the right, checked when publishing and scheduling, and
|
||||
again when a scheduled post falls due. Published posts say which account
|
||||
they went out as.
|
||||
- Signing an account out (its owner, or an admin), or removing a person
|
||||
(their own accounts go), sends posts scheduled to it back to Posts with
|
||||
why, and emails whoever scheduled them; drafts waiting for it fall back
|
||||
to the company's account.
|
||||
- The LinkedIn *post as you or the page* choice became the account choice;
|
||||
reminders of running-out sign-ins cover every account.
|
||||
- Agents get the same grid in Phase 11.
|
||||
|
||||
1. **Users and sessions.**
|
||||
- Tables:
|
||||
- `users`: email, name, kind (person or agent), status (invited,
|
||||
|
||||
@@ -132,13 +132,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}, nil, li.ID); err == nil || !strings.Contains(err.Error(), "isn't connected") {
|
||||
if _, err := Publish(ctx, d, ChannelPublishers{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}, nil, x.ID); err == nil {
|
||||
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, x.ID); err == nil {
|
||||
t.Fatal("expected the failure")
|
||||
}
|
||||
got, _ := GetDraft(d, x.ID)
|
||||
@@ -149,7 +149,7 @@ func TestDraftsAndPublish(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pub.err = nil
|
||||
got, err = Publish(ctx, d, Publishers{ChannelX: pub}, nil, x.ID)
|
||||
got, err = Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, x.ID)
|
||||
if err != nil || got.Status != StatusPublished || got.PostURL == "" || got.Error != "" {
|
||||
t.Fatalf("publish: %+v, %v", got, err)
|
||||
}
|
||||
@@ -157,7 +157,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}, nil, x.ID); !errors.Is(err, ErrBusy) {
|
||||
if _, err := Publish(ctx, d, ChannelPublishers{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) {
|
||||
@@ -170,7 +170,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}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
|
||||
if _, err := Publish(ctx, d, ChannelPublishers{ChannelX: pub}, nil, long[0].ID); err == nil || !strings.Contains(err.Error(), "295 characters including the link") {
|
||||
t.Errorf("over-long post: %v", err)
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ func TestScheduleAndDue(t *testing.T) {
|
||||
// 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)
|
||||
got, err := Publish(context.Background(), d, ChannelPublishers{ChannelLinkedIn: pub}, tags, soon.ID)
|
||||
if err != nil || got.Status != StatusPublished {
|
||||
t.Fatalf("publish scheduled: %+v, %v", got, err)
|
||||
}
|
||||
@@ -405,7 +405,7 @@ func TestLinkedInAuthor(t *testing.T) {
|
||||
t.Error("an unknown author was taken")
|
||||
}
|
||||
pub := &fakePub{}
|
||||
if _, err := Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
|
||||
if _, err := Publish(ctx, d, ChannelPublishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !pub.got.AsPage {
|
||||
@@ -419,7 +419,7 @@ func TestLinkedInAuthor(t *testing.T) {
|
||||
if err := SetLinkedInAs(d, dr.ID, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, dr.ID)
|
||||
Publish(ctx, d, ChannelPublishers{ChannelLinkedIn: pub}, nil, dr.ID)
|
||||
}
|
||||
}
|
||||
if pub.got.AsPage {
|
||||
|
||||
@@ -80,7 +80,11 @@ type Draft struct {
|
||||
PublishAt time.Time // when a scheduled draft goes out
|
||||
SignalID int64 // the buying signal it was written for; 0: none
|
||||
SignalSlug string // that signal's campaign tag
|
||||
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page
|
||||
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page (before posting accounts)
|
||||
AccountID int64 // the posting account it goes out from; 0: the company's for its channel
|
||||
WrittenBy int64 // who wrote it (asked the AI for it); 0: unknown, or the local edition
|
||||
PostedBy int64 // who published or scheduled it
|
||||
PostedAs string // the account it went out as, once it did
|
||||
}
|
||||
|
||||
// AsPage is the LinkedIn author choice for the company page.
|
||||
@@ -193,9 +197,9 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
|
||||
if dr.Channel != ChannelLinkedIn {
|
||||
as = ""
|
||||
}
|
||||
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
|
||||
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as); err != nil {
|
||||
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
|
||||
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as, dr.AccountID, dr.WrittenBy); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, id := range dr.ItemIDs {
|
||||
@@ -220,7 +224,8 @@ 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, ''), COALESCE(publish_at, ''), title, target,
|
||||
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as`
|
||||
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as,
|
||||
account_id, written_by, posted_by, posted_as`
|
||||
|
||||
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
|
||||
defer rows.Close()
|
||||
@@ -230,7 +235,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
|
||||
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, &publishAt, &dr.Title, &dr.Target,
|
||||
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs); err != nil {
|
||||
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs, &dr.AccountID, &dr.WrittenBy, &dr.PostedBy, &dr.PostedAs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
|
||||
@@ -417,3 +422,56 @@ func UpdateTitle(d *db.DB, id int64, title string) error {
|
||||
title, formatTime(time.Now()), id, ChannelReddit, StatusDraft, StatusFailed)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
// SetAccount chooses the posting account a draft goes out from (0: the
|
||||
// company's for its channel).
|
||||
func SetAccount(d *db.DB, id, account int64) error {
|
||||
res, err := d.Exec(`UPDATE drafts SET account_id = ?, updated_at = ? WHERE id = ? AND status IN (?, ?, ?)`,
|
||||
account, formatTime(time.Now()), id, StatusDraft, StatusFailed, StatusScheduled)
|
||||
return oneRow(res, err)
|
||||
}
|
||||
|
||||
// SetPostedBy records who published or scheduled a draft.
|
||||
func SetPostedBy(d *db.DB, id, user int64) error {
|
||||
_, err := d.Exec(`UPDATE drafts SET posted_by = ? WHERE id = ?`, user, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Copy makes a copy of a draft for another posting account, in the same
|
||||
// batch, waiting in Posts; it returns the copy's ID.
|
||||
func Copy(d *db.DB, id, account int64) (int64, error) {
|
||||
dr, err := GetDraft(d, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ids, _ := json.Marshal(nonNil(dr.ItemIDs))
|
||||
var sig any
|
||||
if dr.SignalID != 0 {
|
||||
sig = dr.SignalID
|
||||
}
|
||||
return d.Insert(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as, account_id, written_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, dr.Batch, dr.InventoryName, dr.Kind, dr.Channel, dr.Title, dr.Target, dr.Content,
|
||||
dr.SourceURL, string(ids), sig, dr.LinkedInAs, account, dr.WrittenBy)
|
||||
}
|
||||
|
||||
// HoldForAccount sends the scheduled drafts going out from an account back
|
||||
// to Posts, with the reason: the account was signed out or removed. It
|
||||
// returns them, to tell their writers.
|
||||
func HoldForAccount(d *db.DB, account int64, reason string) ([]Draft, error) {
|
||||
rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE account_id = ? AND status = ?`, account, StatusScheduled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
held, err := scanDrafts(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = d.Exec(`UPDATE drafts SET status = ?, error = ?, account_id = 0, updated_at = ? WHERE account_id = ? AND status = ?`,
|
||||
StatusFailed, reason, formatTime(time.Now()), account, StatusScheduled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Drafts waiting in Posts for it fall back to the company's account.
|
||||
_, err = d.Exec(`UPDATE drafts SET account_id = 0 WHERE account_id = ? AND status IN (?, ?)`, account, StatusDraft, StatusFailed)
|
||||
return held, err
|
||||
}
|
||||
|
||||
@@ -24,8 +24,24 @@ type Publisher interface {
|
||||
Publish(ctx context.Context, p Post) (string, error)
|
||||
}
|
||||
|
||||
// Publishers are the channels that can post now, by channel ID.
|
||||
type Publishers map[string]Publisher
|
||||
// Publishers find where a draft goes out: its publisher and the account's
|
||||
// name, or why it can't.
|
||||
type Publishers interface {
|
||||
For(dr *Draft) (Publisher, string, error)
|
||||
}
|
||||
|
||||
// ChannelPublishers is a publisher per channel: for tests, and anything
|
||||
// without posting accounts.
|
||||
type ChannelPublishers map[string]Publisher
|
||||
|
||||
// For is the draft's channel's publisher.
|
||||
func (c ChannelPublishers) For(dr *Draft) (Publisher, string, error) {
|
||||
p := c[dr.Channel]
|
||||
if p == nil {
|
||||
return nil, "", fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName())
|
||||
}
|
||||
return p, "", nil
|
||||
}
|
||||
|
||||
// ErrBusy means the draft is already being published.
|
||||
var ErrBusy = errors.New("this draft is already being published, or was published")
|
||||
@@ -44,9 +60,9 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
|
||||
if !dr.Editable() && dr.Status != StatusScheduled {
|
||||
return dr, ErrBusy
|
||||
}
|
||||
pub := pubs[dr.Channel]
|
||||
if pub == nil {
|
||||
return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName())
|
||||
pub, as, err := pubs.For(dr)
|
||||
if err != nil {
|
||||
return dr, err
|
||||
}
|
||||
if problem := dr.Problem(); problem != "" {
|
||||
return dr, fmt.Errorf("%s. Fix it first", problem)
|
||||
@@ -73,8 +89,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
|
||||
dr.Status, dr.Error = StatusFailed, pubErr.Error()
|
||||
return dr, pubErr
|
||||
}
|
||||
if _, err := d.Exec(`UPDATE drafts SET status = ?, post_url = ?, published_at = ?, updated_at = ? WHERE id = ?`,
|
||||
StatusPublished, postURL, now, now, id); err != nil {
|
||||
if _, err := d.Exec(`UPDATE drafts SET status = ?, post_url = ?, published_at = ?, updated_at = ?, posted_as = ? WHERE id = ?`,
|
||||
StatusPublished, postURL, now, now, as, id); err != nil {
|
||||
// It went out: say so, so the user doesn't post it again.
|
||||
return dr, fmt.Errorf("published to %s (%s), but couldn't record it: %w", dr.ChannelName(), postURL, err)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestRedditDraftsAndCache(t *testing.T) {
|
||||
}
|
||||
|
||||
pub := &fakePub{}
|
||||
if _, err := Publish(context.Background(), d, Publishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
|
||||
if _, err := Publish(context.Background(), d, ChannelPublishers{ChannelReddit: pub}, utm.NewTagger([]string{"acme.example"}), dr.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(pub.calls[0], "r/selfhosted|New title|Body|https://acme.example/a?utm_") ||
|
||||
|
||||
@@ -120,6 +120,31 @@ CREATE TABLE throttle (
|
||||
count INTEGER NOT NULL DEFAULT 0,
|
||||
since TEXT NOT NULL -- when the count started
|
||||
);
|
||||
`,
|
||||
},
|
||||
// 35
|
||||
{
|
||||
Note: "posting accounts (several per network, the company's and people's own), who may post to them, and who wrote and posted each draft",
|
||||
SQLite: `
|
||||
CREATE TABLE posting_accounts (
|
||||
id INTEGER PRIMARY KEY,
|
||||
network TEXT NOT NULL, -- x, linkedin, linkedin_page, reddit
|
||||
name TEXT NOT NULL DEFAULT '', -- as shown: @acme, u/jo, the page's or the member's name
|
||||
external TEXT NOT NULL DEFAULT '', -- the network's ID for it: a URN, a username
|
||||
owner_id INTEGER NOT NULL DEFAULT 0, -- 0: the company's; else the user whose own account it is
|
||||
created_by INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL DEFAULT '' -- when the sign-in runs out (LinkedIn); '' if renewed
|
||||
);
|
||||
CREATE TABLE posting_grants (
|
||||
account_id INTEGER NOT NULL REFERENCES posting_accounts(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL,
|
||||
PRIMARY KEY (account_id, user_id)
|
||||
);
|
||||
ALTER TABLE drafts ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0; -- 0: the company's account for the channel
|
||||
ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ type Pending struct {
|
||||
Verifier string // PKCE, X only
|
||||
RedirectURI string
|
||||
Started time.Time
|
||||
For int64 `json:",omitempty"` // a person signing in their own posting account; 0: the company's
|
||||
}
|
||||
|
||||
// --- X ---
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
// Package posting keeps the social accounts posts go out from: several per
|
||||
// network, the company's and people's own, each signed in once by its
|
||||
// owner or an admin, and who may post to which. Their tokens are in the
|
||||
// secrets store, under acct:<id>:… .
|
||||
package posting
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
// Networks an account can be on.
|
||||
const (
|
||||
X = "x"
|
||||
LinkedIn = "linkedin" // a member, posting as themselves
|
||||
LinkedInPage = "linkedin_page" // a company page
|
||||
Reddit = "reddit"
|
||||
)
|
||||
|
||||
// NetworkName is a network as people say it.
|
||||
func NetworkName(n string) string {
|
||||
switch n {
|
||||
case X:
|
||||
return "X"
|
||||
case LinkedIn:
|
||||
return "LinkedIn"
|
||||
case LinkedInPage:
|
||||
return "LinkedIn page"
|
||||
case Reddit:
|
||||
return "Reddit"
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// Channel is the draft channel an account posts for: a LinkedIn page posts
|
||||
// LinkedIn drafts.
|
||||
func Channel(network string) string {
|
||||
if network == LinkedInPage {
|
||||
return LinkedIn
|
||||
}
|
||||
return network
|
||||
}
|
||||
|
||||
// Account is somewhere posts can go out from.
|
||||
type Account struct {
|
||||
ID int64
|
||||
Network string
|
||||
Name string
|
||||
External string
|
||||
Owner int64 // 0: the company's
|
||||
CreatedBy int64
|
||||
Created time.Time
|
||||
Expires time.Time // zero if Supermarket renews the sign-in itself
|
||||
}
|
||||
|
||||
// Label is the account as a list shows it: "X @acme".
|
||||
func (a *Account) Label() string {
|
||||
n := a.Name
|
||||
if n == "" {
|
||||
n = "(unnamed)"
|
||||
}
|
||||
return NetworkName(a.Network) + " " + n
|
||||
}
|
||||
|
||||
// Expired says whether the sign-in has run out.
|
||||
func (a *Account) Expired(now time.Time) bool { return !a.Expires.IsZero() && !now.Before(a.Expires) }
|
||||
|
||||
// Secret names for an account's tokens.
|
||||
func AccessName(id int64) string { return fmt.Sprintf("acct:%d:access", id) }
|
||||
func RefreshName(id int64) string { return fmt.Sprintf("acct:%d:refresh", id) }
|
||||
|
||||
const timeFormat = "2006-01-02T15:04:05.000Z"
|
||||
|
||||
func ts(t time.Time) string {
|
||||
if t.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return t.UTC().Format(timeFormat)
|
||||
}
|
||||
|
||||
func parseTS(s string) time.Time {
|
||||
t, _ := time.Parse(timeFormat, s)
|
||||
return t
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("no such posting account")
|
||||
|
||||
const cols = `id, network, name, external, owner_id, created_by, created_at, expires_at`
|
||||
|
||||
func scan(row interface{ Scan(...any) error }) (*Account, error) {
|
||||
var a Account
|
||||
var created, expires string
|
||||
if err := row.Scan(&a.ID, &a.Network, &a.Name, &a.External, &a.Owner, &a.CreatedBy, &created, &expires); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
a.Created, a.Expires = parseTS(created), parseTS(expires)
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// Save signs an account in: a new one, or, for the same network, owner and
|
||||
// external ID, the existing one with new tokens. refresh may be "".
|
||||
func Save(d *db.DB, sec *secrets.Store, a *Account, access, refresh string, now time.Time) error {
|
||||
if a.Network != X && a.Network != LinkedIn && a.Network != LinkedInPage && a.Network != Reddit {
|
||||
return fmt.Errorf("no network %q", a.Network)
|
||||
}
|
||||
var id int64
|
||||
err := d.QueryRow(`SELECT id FROM posting_accounts WHERE network = ? AND owner_id = ? AND external = ?`, a.Network, a.Owner, a.External).Scan(&id)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
a.Created = now
|
||||
a.ID, err = d.Insert(`INSERT INTO posting_accounts (network, name, external, owner_id, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
a.Network, a.Name, a.External, a.Owner, a.CreatedBy, ts(now), ts(a.Expires))
|
||||
case err == nil:
|
||||
a.ID = id
|
||||
_, err = d.Exec(`UPDATE posting_accounts SET name = ?, expires_at = ? WHERE id = ?`, a.Name, ts(a.Expires), id)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sec.Set(map[string]string{AccessName(a.ID): access, RefreshName(a.ID): refresh})
|
||||
}
|
||||
|
||||
// SaveTokens keeps refreshed tokens.
|
||||
func SaveTokens(sec *secrets.Store, id int64, access, refresh string) error {
|
||||
up := map[string]string{AccessName(id): access}
|
||||
if refresh != "" {
|
||||
up[RefreshName(id)] = refresh
|
||||
}
|
||||
return sec.Set(up)
|
||||
}
|
||||
|
||||
// Rename changes what an account is called (a LinkedIn page chosen).
|
||||
func Rename(d *db.DB, id int64, name, external string) error {
|
||||
_, err := d.Exec(`UPDATE posting_accounts SET name = ?, external = ? WHERE id = ?`, name, external, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get finds an account.
|
||||
func Get(d *db.DB, id int64) (*Account, error) {
|
||||
return scan(d.QueryRow(`SELECT `+cols+` FROM posting_accounts WHERE id = ?`, id))
|
||||
}
|
||||
|
||||
// List is every account: the company's first, then by network and name.
|
||||
func List(d *db.DB) ([]*Account, error) {
|
||||
rows, err := d.Query(`SELECT ` + cols + ` FROM posting_accounts ORDER BY owner_id <> 0, network, name COLLATE NOCASE, id`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Account
|
||||
for rows.Next() {
|
||||
a, err := scan(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Company is the company's first account on a network, or nil: where a
|
||||
// draft without an account goes.
|
||||
func Company(d *db.DB, network string) (*Account, error) {
|
||||
a, err := scan(d.QueryRow(`SELECT `+cols+` FROM posting_accounts WHERE network = ? AND owner_id = 0 ORDER BY id LIMIT 1`, network))
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// Remove signs an account out: its tokens and grants go.
|
||||
func Remove(d *db.DB, sec *secrets.Store, id int64) error {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`DELETE FROM posting_grants WHERE account_id = ?`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM posting_accounts WHERE id = ?`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return err
|
||||
}
|
||||
return sec.Set(map[string]string{AccessName(id): "", RefreshName(id): ""})
|
||||
}
|
||||
|
||||
// OwnedBy are a user's own accounts.
|
||||
func OwnedBy(d *db.DB, user int64) ([]*Account, error) {
|
||||
all, err := List(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []*Account
|
||||
for _, a := range all {
|
||||
if a.Owner == user {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Grants are who may post to which account, beyond its owner and the
|
||||
// admins: account → users.
|
||||
func Grants(d *db.DB) (map[int64]map[int64]bool, error) {
|
||||
rows, err := d.Query(`SELECT account_id, user_id FROM posting_grants`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[int64]map[int64]bool{}
|
||||
for rows.Next() {
|
||||
var a, u int64
|
||||
if err := rows.Scan(&a, &u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out[a] == nil {
|
||||
out[a] = map[int64]bool{}
|
||||
}
|
||||
out[a][u] = true
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetGrants replaces who may post to which: account → users.
|
||||
func SetGrants(d *db.DB, grants map[int64][]int64) error {
|
||||
tx, err := d.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`DELETE FROM posting_grants`); err != nil {
|
||||
return err
|
||||
}
|
||||
for a, us := range grants {
|
||||
for _, u := range us {
|
||||
if _, err := tx.Exec(`INSERT INTO posting_grants (account_id, user_id) VALUES (?, ?)`, a, u); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Granted says whether a user was given an account (not counting their own
|
||||
// or being an admin).
|
||||
func Granted(d *db.DB, account, user int64) (bool, error) {
|
||||
var n int
|
||||
err := d.QueryRow(`SELECT count(*) FROM posting_grants WHERE account_id = ? AND user_id = ?`, account, user).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// ForgetUser takes a removed user's grants away. Their own accounts are
|
||||
// removed by the caller (Remove), which holds their posts first.
|
||||
func ForgetUser(d *db.DB, user int64) error {
|
||||
_, err := d.Exec(`DELETE FROM posting_grants WHERE user_id = ?`, user)
|
||||
return err
|
||||
}
|
||||
|
||||
// Legacy: before posting accounts, each network had one sign-in, in
|
||||
// secrets named for it. Adopt makes those the company's accounts, once.
|
||||
|
||||
type legacy struct {
|
||||
network, access, refresh, name string
|
||||
}
|
||||
|
||||
// Adopt turns the old single sign-ins into the company's accounts, and
|
||||
// clears the old secrets. names gives each one's shown name and external
|
||||
// ID (from the old record of sign-ins). It returns how many it adopted.
|
||||
func Adopt(d *db.DB, sec *secrets.Store, names func(network string) (name, external string, expires time.Time), now time.Time) (int, error) {
|
||||
olds := []legacy{
|
||||
{X, secrets.XAccessToken, secrets.XRefreshToken, ""},
|
||||
{LinkedIn, secrets.LinkedInAccessToken, "", ""},
|
||||
{LinkedInPage, secrets.LinkedInPageAccessToken, "", ""},
|
||||
{Reddit, secrets.RedditAccessToken, secrets.RedditRefreshToken, ""},
|
||||
}
|
||||
n := 0
|
||||
for _, o := range olds {
|
||||
tok := sec.Get(o.access)
|
||||
if tok == "" {
|
||||
continue
|
||||
}
|
||||
name, external, expires := names(o.network)
|
||||
a := &Account{Network: o.network, Name: name, External: external, Expires: expires}
|
||||
refresh := ""
|
||||
if o.refresh != "" {
|
||||
refresh = sec.Get(o.refresh)
|
||||
}
|
||||
if err := Save(d, sec, a, tok, refresh, now); err != nil {
|
||||
return n, err
|
||||
}
|
||||
clear := map[string]string{o.access: ""}
|
||||
if o.refresh != "" {
|
||||
clear[o.refresh] = ""
|
||||
}
|
||||
if err := sec.Set(clear); err != nil {
|
||||
return n, err
|
||||
}
|
||||
n++
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Label for a list of accounts: "X @acme, LinkedIn Jo".
|
||||
func Labels(list []*Account) string {
|
||||
var parts []string
|
||||
for _, a := range list {
|
||||
parts = append(parts, a.Label())
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package posting
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
func open(t *testing.T) (*db.DB, *secrets.Store) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
d, err := db.Open(filepath.Join(dir, "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
sec, err := secrets.Open(filepath.Join(dir, "secrets.json"))
|
||||
if db.OnPostgres() {
|
||||
sec, err = secrets.OpenDB(d, []byte("0123456789abcdef0123456789abcdef"), nil)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return d, sec
|
||||
}
|
||||
|
||||
func TestAccounts(t *testing.T) {
|
||||
d, sec := open(t)
|
||||
now := time.Now()
|
||||
co := &Account{Network: X, Name: "@acme", External: "acme"}
|
||||
if err := Save(d, sec, co, "tok", "ref", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sec.Get(AccessName(co.ID)) != "tok" || sec.Get(RefreshName(co.ID)) != "ref" {
|
||||
t.Error("tokens")
|
||||
}
|
||||
// The same account signed in again: updated, not doubled.
|
||||
again := &Account{Network: X, Name: "@acme", External: "acme"}
|
||||
Save(d, sec, again, "tok2", "", now)
|
||||
if again.ID != co.ID || sec.Get(AccessName(co.ID)) != "tok2" || sec.Has(RefreshName(co.ID)) {
|
||||
t.Errorf("again: %d %q", again.ID, sec.Get(AccessName(co.ID)))
|
||||
}
|
||||
jo := &Account{Network: X, Name: "@jo", External: "jo", Owner: 7}
|
||||
Save(d, sec, jo, "t", "", now)
|
||||
if err := Save(d, sec, &Account{Network: "myspace"}, "t", "", now); err == nil {
|
||||
t.Error("unknown network")
|
||||
}
|
||||
if c, _ := Company(d, X); c == nil || c.ID != co.ID {
|
||||
t.Errorf("company: %+v", c)
|
||||
}
|
||||
if c, _ := Company(d, Reddit); c != nil {
|
||||
t.Error("no Reddit account")
|
||||
}
|
||||
list, _ := List(d)
|
||||
if len(list) != 2 || list[0].ID != co.ID {
|
||||
t.Errorf("list: %+v", list)
|
||||
}
|
||||
if own, _ := OwnedBy(d, 7); len(own) != 1 || own[0].ID != jo.ID {
|
||||
t.Errorf("own: %+v", own)
|
||||
}
|
||||
if Channel(LinkedInPage) != LinkedIn || co.Label() != "X @acme" {
|
||||
t.Error("labels")
|
||||
}
|
||||
|
||||
if err := SetGrants(d, map[int64][]int64{co.ID: {7, 8}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, _ := Granted(d, co.ID, 8); !ok {
|
||||
t.Error("not granted")
|
||||
}
|
||||
ForgetUser(d, 8)
|
||||
if ok, _ := Granted(d, co.ID, 8); ok {
|
||||
t.Error("forgotten user still granted")
|
||||
}
|
||||
g, _ := Grants(d)
|
||||
if !g[co.ID][7] || len(g[co.ID]) != 1 {
|
||||
t.Errorf("grants %v", g)
|
||||
}
|
||||
if err := Remove(d, sec, co.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Get(d, co.ID); err != ErrNotFound || sec.Has(AccessName(co.ID)) {
|
||||
t.Error("not removed")
|
||||
}
|
||||
if g, _ := Grants(d); len(g) != 0 {
|
||||
t.Error("grants outlived the account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdopt(t *testing.T) {
|
||||
d, sec := open(t)
|
||||
sec.Set(map[string]string{secrets.XAccessToken: "xt", secrets.XRefreshToken: "xr", secrets.RedditAccessToken: "rt"})
|
||||
exp := time.Now().Add(time.Hour)
|
||||
n, err := Adopt(d, sec, func(network string) (string, string, time.Time) {
|
||||
return "n-" + network, "e-" + network, exp
|
||||
}, time.Now())
|
||||
if err != nil || n != 2 {
|
||||
t.Fatalf("%d %v", n, err)
|
||||
}
|
||||
x, _ := Company(d, X)
|
||||
if x == nil || x.Name != "n-x" || sec.Get(AccessName(x.ID)) != "xt" || sec.Get(RefreshName(x.ID)) != "xr" || sec.Has(secrets.XAccessToken) {
|
||||
t.Errorf("x: %+v", x)
|
||||
}
|
||||
if n, _ := Adopt(d, sec, func(string) (string, string, time.Time) { return "", "", time.Time{} }, time.Now()); n != 0 {
|
||||
t.Error("adopted twice")
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,10 @@ var routeAreas = map[string]string{
|
||||
// Old addresses that only redirect.
|
||||
"=/profile": areaSignedIn, "=/core": areaSignedIn,
|
||||
|
||||
"/settings": areaAdmin, "/auth": areaAdmin,
|
||||
"/settings": areaAdmin,
|
||||
// Signing in to a posting account: admins for the company's, anyone
|
||||
// with Content for their own (oauthStart checks which).
|
||||
"/auth": areaSignedIn,
|
||||
|
||||
"/content": "content", "/posts": "content", "/inbox": "content", "/drafts": "content", "/reddit": "content",
|
||||
"/prospects": "prospects", "/signals": "prospects", "/lead-sources": "prospects", "/funnel": "prospects",
|
||||
|
||||
+20
-2
@@ -10,6 +10,8 @@ import (
|
||||
|
||||
"rsc.io/qr"
|
||||
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
@@ -23,8 +25,12 @@ type accountData struct {
|
||||
Zones []string
|
||||
Emails []emailKind // the emails they may choose
|
||||
Photos bool // there's file storage for a photo
|
||||
Problem string // under the form it's about
|
||||
Section string // which form: profile, password, two-factor
|
||||
|
||||
// Their own posting accounts, and the networks they can connect.
|
||||
Posting []*posting.Account
|
||||
Connectable []grant
|
||||
Problem string // under the form it's about
|
||||
Section string // which form: profile, password, two-factor
|
||||
|
||||
// Setting up two-factor sign-in.
|
||||
Secret string
|
||||
@@ -79,6 +85,18 @@ func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, v *viewer
|
||||
return
|
||||
}
|
||||
d.U, d.Role, d.Zones, d.Emails, d.Photos = u, v.Member.Role, commonZones, emailsFor(v.Member), s.Files != nil
|
||||
if v.Member.Can("content", true) {
|
||||
d.Posting, _ = posting.OwnedBy(s.DB, u.ID)
|
||||
if s.Secrets.Has(secrets.XClientID) {
|
||||
d.Connectable = append(d.Connectable, grant{"x", "X"})
|
||||
}
|
||||
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})
|
||||
}
|
||||
|
||||
+12
-75
@@ -34,58 +34,6 @@ func (s *Server) fetcher() *fetcher.Fetcher {
|
||||
return f
|
||||
}
|
||||
|
||||
// publishers are the channels signed in for posting.
|
||||
func (s *Server) publishers() content.Publishers {
|
||||
pubs := content.Publishers{}
|
||||
if tok := s.Secrets.Get(secrets.XAccessToken); tok != "" {
|
||||
c := twitter.New("", tok, 0)
|
||||
// X access tokens last two hours; refresh tokens are single-use, so
|
||||
// each new one is saved before the old is gone.
|
||||
if s.Secrets.Has(secrets.XRefreshToken) && s.Secrets.Has(secrets.XClientID) {
|
||||
c.SetTokenRefresher(func(ctx context.Context) (string, string, error) {
|
||||
res, err := oauth.RefreshX(ctx, s.Secrets.Get(secrets.XClientID),
|
||||
s.Secrets.Get(secrets.XClientSecret), s.Secrets.Get(secrets.XRefreshToken))
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
updates := map[string]string{secrets.XAccessToken: res.AccessToken}
|
||||
if res.RefreshToken != "" {
|
||||
updates[secrets.XRefreshToken] = res.RefreshToken
|
||||
}
|
||||
if err := s.Secrets.Set(updates); err != nil {
|
||||
// Keep going with the new token; the next start will need
|
||||
// a new sign-in.
|
||||
s.Log.Error("x: couldn't save the refreshed token; sign in to X again later", "err", err)
|
||||
}
|
||||
return res.AccessToken, res.RefreshToken, nil
|
||||
})
|
||||
}
|
||||
pubs[content.ChannelX] = xPublisher{c}
|
||||
}
|
||||
var li linkedInPublisher
|
||||
if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" {
|
||||
if e := s.linkedInExpiry(); e != nil && e.Expired() {
|
||||
li.meErr = expiredPublisher{*e}.err()
|
||||
} else {
|
||||
li.me = linkedin.New(tok, urn)
|
||||
}
|
||||
}
|
||||
if tok, org := s.Secrets.Get(secrets.LinkedInPageAccessToken), s.liPage(); tok != "" && org != nil {
|
||||
if e := s.linkedInPageExpiry(); e != nil && e.Expired() {
|
||||
li.pageErr = expiredPublisher{*e}.err()
|
||||
} else {
|
||||
li.page = linkedin.New(tok, org.URN)
|
||||
}
|
||||
}
|
||||
if li.me != nil || li.page != nil || li.meErr != nil || li.pageErr != nil {
|
||||
pubs[content.ChannelLinkedIn] = li
|
||||
}
|
||||
if c := s.redditUser(); c != nil {
|
||||
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
|
||||
}
|
||||
return pubs
|
||||
}
|
||||
|
||||
// expiredPublisher stands in for a network whose sign-in ran out: it posts
|
||||
// nothing and says so, rather than letting the network answer 401.
|
||||
type expiredPublisher struct{ e Expiry }
|
||||
@@ -163,31 +111,20 @@ func (p redditPublisher) Publish(ctx context.Context, post content.Post) (string
|
||||
// --- Reddit ---
|
||||
|
||||
func (s *Server) redditUserAgent() string {
|
||||
return reddit.UserAgent(s.Version, s.Secrets.Get(secrets.RedditUsername))
|
||||
name := ""
|
||||
if a := s.companyReddit(); a != nil {
|
||||
name = a.External
|
||||
}
|
||||
return reddit.UserAgent(s.Version, name)
|
||||
}
|
||||
|
||||
// redditUser is a client signed in as the user, or nil. Access tokens last
|
||||
// an hour; a refused one is refreshed and saved.
|
||||
// redditUser is a client signed in as the company's Reddit account, or nil.
|
||||
func (s *Server) redditUser() *reddit.Client {
|
||||
tok := s.Secrets.Get(secrets.RedditAccessToken)
|
||||
if tok == "" {
|
||||
a := s.companyReddit()
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
return reddit.New(tok, s.redditUserAgent(), func(ctx context.Context) (string, error) {
|
||||
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
|
||||
s.redditUserAgent(), s.Secrets.Get(secrets.RedditRefreshToken))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
updates := map[string]string{secrets.RedditAccessToken: res.AccessToken}
|
||||
if res.RefreshToken != "" {
|
||||
updates[secrets.RedditRefreshToken] = res.RefreshToken
|
||||
}
|
||||
if err := s.Secrets.Set(updates); err != nil {
|
||||
s.Log.Error("reddit: couldn't save the refreshed token", "err", err)
|
||||
}
|
||||
return res.AccessToken, nil
|
||||
})
|
||||
return s.redditClient(a)
|
||||
}
|
||||
|
||||
// redditReader reads subreddits: as the user if signed in, else as the
|
||||
@@ -251,11 +188,11 @@ const redditHistoryTTL = 10 * time.Minute
|
||||
// redditHistory is the signed-in account's recent posts, or nil if they
|
||||
// can't be read.
|
||||
func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
|
||||
user := s.Secrets.Get(secrets.RedditUsername)
|
||||
c := s.redditUser()
|
||||
if c == nil || user == "" {
|
||||
a := s.companyReddit()
|
||||
if a == nil || a.External == "" {
|
||||
return nil
|
||||
}
|
||||
user, c := a.External, s.redditClient(a)
|
||||
s.mu.Lock()
|
||||
h, at := s.redditHist, s.redditHistAt
|
||||
s.mu.Unlock()
|
||||
|
||||
@@ -22,10 +22,10 @@ type service struct {
|
||||
|
||||
var services = []service{
|
||||
{"ai", "AI provider", "Writing: posts, pages, briefs, the profile draft", "/settings/ai", []string{secrets.AnthropicAPIKey, secrets.OpenAIAPIKey}},
|
||||
{"x", "X", "Posting, and reading partners' posts", "/settings/accounts#network-X", []string{secrets.XAccessToken, secrets.XBearerToken}},
|
||||
{"linkedin", "LinkedIn", "Posting as a person", "/settings/accounts#network-LinkedIn", []string{secrets.LinkedInAccessToken}},
|
||||
{"linkedin_page", "LinkedIn page", "Posting as the company's page", "/settings/accounts", []string{secrets.LinkedInPageAccessToken}},
|
||||
{"reddit", "Reddit", "Posting to subreddits", "/settings/accounts#network-Reddit", []string{secrets.RedditAccessToken}},
|
||||
{"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}},
|
||||
@@ -111,6 +111,25 @@ func (s *Server) setSecrets(r *http.Request, updates map[string]string) error {
|
||||
return s.DB.PutJSON(connChangesKey, changes)
|
||||
}
|
||||
|
||||
// recordConnection records who connected (or removed) a service, for
|
||||
// sign-ins kept outside the secrets' names (posting accounts).
|
||||
func (s *Server) recordConnection(r *http.Request, service string, set bool) {
|
||||
changes := map[string]connChange{}
|
||||
_, _ = s.DB.GetJSON(connChangesKey, &changes)
|
||||
v := viewerOf(r)
|
||||
who, id := "you", int64(0)
|
||||
if v.User != nil {
|
||||
who, id = v.User.Name, v.User.ID
|
||||
if who == "" {
|
||||
who = v.User.Email
|
||||
}
|
||||
}
|
||||
changes[service] = connChange{By: who, UserID: id, At: time.Now().UTC(), Removed: !set}
|
||||
if err := s.DB.PutJSON(connChangesKey, changes); err != nil {
|
||||
s.Log.Warn("connections: recording a change", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// serviceSet says whether any of a service's secrets is set.
|
||||
func (s *Server) serviceSet(id string) bool {
|
||||
for _, sv := range services {
|
||||
@@ -162,12 +181,34 @@ func (s *Server) connectionsPage(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = s.DB.GetJSON(connChangesKey, &changes)
|
||||
_, _ = 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}
|
||||
postingNames := map[string]string{}
|
||||
for _, a := range s.postingAccounts() {
|
||||
if s.working(a) {
|
||||
postingCount[a.Network]++
|
||||
if postingNames[a.Network] != "" {
|
||||
postingNames[a.Network] += ", "
|
||||
}
|
||||
postingNames[a.Network] += a.Name
|
||||
}
|
||||
}
|
||||
var rows []connRow
|
||||
for _, sv := range services {
|
||||
row := connRow{service: sv, State: "missing"}
|
||||
if s.serviceSet(sv.ID) {
|
||||
row.State = "connected"
|
||||
}
|
||||
if n, ok := postingCount[sv.ID]; ok {
|
||||
reading := row.State == "connected" // X's key for reading posts
|
||||
row.State, row.Detail = "missing", ""
|
||||
switch {
|
||||
case n > 0:
|
||||
row.State, row.Detail = "connected", postingNames[sv.ID]
|
||||
case reading:
|
||||
row.State, row.Detail = "connected", "Reading only: no account to post to"
|
||||
}
|
||||
}
|
||||
if sv.ID == "ai" {
|
||||
row.State = "missing"
|
||||
if cfg, err := ai.LoadConfig(s.DB); err == nil {
|
||||
|
||||
@@ -151,7 +151,7 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn := s.connected()
|
||||
conn := s.connected(localOwner) // any account that works: which channels can be written for
|
||||
var chans []channelChoice
|
||||
for _, c := range content.Channels {
|
||||
chans = append(chans, channelChoice{c, conn[c.ID]})
|
||||
@@ -354,6 +354,11 @@ func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if v := viewerOf(r); v.User != nil {
|
||||
for i := range drafts {
|
||||
drafts[i].WrittenBy = v.User.ID
|
||||
}
|
||||
}
|
||||
if _, err := content.CreateDrafts(s.DB, drafts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+136
-25
@@ -71,16 +71,23 @@ func groupBatches(drafts []content.Draft) []*draftBatch {
|
||||
return batches
|
||||
}
|
||||
|
||||
func (s *Server) connected() map[string]bool {
|
||||
// connected says, by channel, whether the viewer has an account to post to.
|
||||
func (s *Server) connected(v *viewer) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for id, p := range s.publishers() {
|
||||
if _, expired := p.(expiredPublisher); expired {
|
||||
continue
|
||||
for ch, list := range s.usableAccounts(v) {
|
||||
out[ch] = len(list) > 0
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// chosenAccounts is the account each draft goes out from, as things stand:
|
||||
// its own, or the company's for its channel.
|
||||
func (s *Server) chosenAccounts(drafts []content.Draft) map[int64]int64 {
|
||||
out := map[int64]int64{}
|
||||
for i := range drafts {
|
||||
if a, err := s.draftAccount(&drafts[i]); err == nil && a != nil {
|
||||
out[drafts[i].ID] = a.ID
|
||||
}
|
||||
if li, ok := p.(linkedInPublisher); ok && li.me == nil && li.page == nil {
|
||||
continue // only expired sign-ins
|
||||
}
|
||||
out[id] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -103,8 +110,9 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
|
||||
"Reminders": s.reminders(),
|
||||
"Sections": sections,
|
||||
"Reddit": s.redditViews(r.Context(), pending),
|
||||
"Connected": s.connected(),
|
||||
"Page": s.liPageIfSignedIn(),
|
||||
"Connected": s.connected(viewerOf(r)),
|
||||
"Accounts": s.usableAccounts(viewerOf(r)),
|
||||
"Chosen": s.chosenAccounts(pending),
|
||||
"Tagged": s.tagger() != nil,
|
||||
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
|
||||
"Zone": time.Now().Format("MST"),
|
||||
@@ -174,7 +182,7 @@ func (s *Server) renderScheduled(w http.ResponseWriter, r *http.Request, errMsg
|
||||
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"),
|
||||
"Drafts": drafts, "Connected": s.connected(viewerOf(r)), "Zone": time.Now().Format("MST"),
|
||||
}})
|
||||
}
|
||||
|
||||
@@ -258,24 +266,70 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The accounts chosen to post to: this draft goes to the first; the
|
||||
// others get copies, published or scheduled with it.
|
||||
var copies []int64
|
||||
switch action {
|
||||
case "save", "publish", "schedule":
|
||||
chosen, err := s.chosenFromForm(r, id)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
if len(chosen) > 0 {
|
||||
if err := content.SetAccount(s.DB, id, chosen[0]); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if action != "save" {
|
||||
if err := s.checkPostAs(viewerOf(r), id); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
for _, a := range chosen[min(1, len(chosen)):] {
|
||||
cid, err := content.Copy(s.DB, id, a)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
copies = append(copies, cid)
|
||||
}
|
||||
}
|
||||
}
|
||||
by := int64(0)
|
||||
if v := viewerOf(r); v.User != nil {
|
||||
by = v.User.ID
|
||||
}
|
||||
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()
|
||||
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)
|
||||
if err != nil {
|
||||
name := "the channel"
|
||||
if d != nil {
|
||||
name = d.ChannelName()
|
||||
}
|
||||
failed = append(failed, fmt.Sprintf("Couldn't publish to %s: %v", name, err))
|
||||
continue
|
||||
}
|
||||
fail(fmt.Errorf("Couldn't publish to %s: %w", name, err))
|
||||
return
|
||||
reddit = reddit || d.Channel == content.ChannelReddit
|
||||
s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by)
|
||||
}
|
||||
if d.Channel == content.ChannelReddit {
|
||||
if reddit {
|
||||
s.forgetRedditHistory()
|
||||
}
|
||||
if len(failed) > 0 {
|
||||
fail(errors.New(strings.Join(failed, " ")))
|
||||
return
|
||||
}
|
||||
redirect(w, r, back, "published")
|
||||
case "schedule":
|
||||
at, err := parseWhen(r.PostForm.Get("when"), time.Now())
|
||||
@@ -292,9 +346,12 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
|
||||
fail(fmt.Errorf("%s: fix it before scheduling", problem))
|
||||
return
|
||||
}
|
||||
if err := content.Schedule(s.DB, id, at); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
for _, did := range append([]int64{id}, copies...) {
|
||||
if err := content.Schedule(s.DB, did, at); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
_ = content.SetPostedBy(s.DB, did, by)
|
||||
}
|
||||
redirect(w, r, back, "scheduled")
|
||||
case "open":
|
||||
@@ -396,9 +453,15 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
pctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
_, err := content.Publish(pctx, s.DB, pubs, tags, d.ID)
|
||||
cancel()
|
||||
var err error
|
||||
if d.PostedBy != 0 {
|
||||
err = s.checkPostAs(s.viewerFor(d.PostedBy), d.ID)
|
||||
}
|
||||
if err == nil {
|
||||
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:
|
||||
@@ -443,3 +506,51 @@ func redditSubmitURL(d *content.Draft, tags *utm.Tagger, info *reddit.Subreddit)
|
||||
q.Del("text")
|
||||
return base + "?" + q.Encode()
|
||||
}
|
||||
|
||||
// chosenFromForm reads the accounts chosen on a draft's form (accounts=<id>,
|
||||
// several): each must be one the viewer may post to, for the draft's
|
||||
// channel.
|
||||
func (s *Server) chosenFromForm(r *http.Request, id int64) ([]int64, error) {
|
||||
raw, sent := r.PostForm["accounts"]
|
||||
if !sent {
|
||||
return nil, nil
|
||||
}
|
||||
d, err := content.GetDraft(s.DB, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
usable := map[int64]bool{}
|
||||
for _, a := range s.usableAccounts(viewerOf(r))[d.Channel] {
|
||||
usable[a.ID] = true
|
||||
}
|
||||
var out []int64
|
||||
seen := map[int64]bool{}
|
||||
for _, v := range raw {
|
||||
a, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || !usable[a] {
|
||||
return nil, errors.New("you can't post to one of the accounts chosen: choose among those listed")
|
||||
}
|
||||
if !seen[a] {
|
||||
seen[a] = true
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// checkPostAs says why a viewer may not post a draft from its account, or
|
||||
// nil if they may.
|
||||
func (s *Server) checkPostAs(v *viewer, id int64) error {
|
||||
d, err := content.GetDraft(s.DB, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
a, err := s.draftAccount(d)
|
||||
if err != nil || a == nil {
|
||||
return err // Publish says it isn't connected
|
||||
}
|
||||
if !s.mayPostAs(v, a) {
|
||||
return fmt.Errorf("you may not post as %s: choose another account, or ask an admin", a.Label())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
linkedinapi "supermarket/internal/api/linkedin"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/posting"
|
||||
)
|
||||
|
||||
// Posting as the company page needs a second LinkedIn app with the
|
||||
@@ -56,7 +56,7 @@ func (s *Server) liPage() *linkedinapi.Org {
|
||||
}
|
||||
|
||||
func (s *Server) pageSetup() *pageSetup {
|
||||
p := &pageSetup{Scopes: s.liPageScopes(), Signed: s.Secrets.Has(secrets.LinkedInPageAccessToken), Chosen: s.liPage()}
|
||||
p := &pageSetup{Scopes: s.liPageScopes(), Signed: s.companyPage() != nil, Chosen: s.liPage()}
|
||||
s.DB.GetJSON(liPageOrgsKey, &p.Orgs)
|
||||
s.DB.GetJSON(liPageNoteKey, &p.Note)
|
||||
s.DB.GetJSON(content.LinkedInDefaultKey, &p.Default)
|
||||
@@ -64,19 +64,13 @@ func (s *Server) pageSetup() *pageSetup {
|
||||
}
|
||||
|
||||
// linkedInPageExpiry is when the page's sign-in runs out, or nil.
|
||||
func (s *Server) linkedInPageExpiry() *Expiry {
|
||||
if !s.Secrets.Has(secrets.LinkedInPageAccessToken) {
|
||||
return nil
|
||||
}
|
||||
c := s.connections()[liPageProvider]
|
||||
at := c.Expires
|
||||
if at.IsZero() {
|
||||
if c.At.IsZero() {
|
||||
return nil
|
||||
}
|
||||
at = c.At.Add(linkedInTokenLife)
|
||||
}
|
||||
return &Expiry{Network: liPageNetwork, At: at}
|
||||
func (s *Server) linkedInPageExpiry() *Expiry { return s.companyExpiry(posting.LinkedInPage) }
|
||||
|
||||
// companyPage is the company's LinkedIn page account, or nil.
|
||||
func (s *Server) companyPage() *posting.Account {
|
||||
s.adoptLegacy()
|
||||
a, _ := posting.Company(s.DB, posting.LinkedInPage)
|
||||
return a
|
||||
}
|
||||
|
||||
// pageOrgs lists the pages the page sign-in may post for, and keeps them.
|
||||
@@ -120,7 +114,10 @@ func (s *Server) linkedInPageSave(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
switch r.PostFormValue("do") {
|
||||
case "refresh":
|
||||
tok := s.Secrets.Get(secrets.LinkedInPageAccessToken)
|
||||
tok := ""
|
||||
if a := s.companyPage(); a != nil {
|
||||
tok = s.Secrets.Get(posting.AccessName(a.ID))
|
||||
}
|
||||
if tok == "" {
|
||||
redirect(w, r, "/settings/accounts", "")
|
||||
return
|
||||
@@ -171,6 +168,12 @@ func (s *Server) linkedInPageSave(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if a, o := s.companyPage(), s.liPage(); a != nil && o != nil && a.External != o.URN {
|
||||
if err := posting.Rename(s.DB, a.ID, o.Name, o.URN); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
redirect(w, r, "/settings/accounts", "saved")
|
||||
}
|
||||
|
||||
@@ -190,7 +193,7 @@ var errNoMe = errors.New("this draft posts as you, but LinkedIn isn't connected:
|
||||
// liPageIfSignedIn is the chosen page when the page app is signed in, for
|
||||
// the "post as" choice on LinkedIn drafts.
|
||||
func (s *Server) liPageIfSignedIn() *linkedinapi.Org {
|
||||
if !s.Secrets.Has(secrets.LinkedInPageAccessToken) {
|
||||
if s.companyPage() == nil {
|
||||
return nil
|
||||
}
|
||||
return s.liPage()
|
||||
|
||||
+25
-30
@@ -18,8 +18,8 @@ import (
|
||||
"supermarket/internal/core"
|
||||
"supermarket/internal/crm"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
// Connection is a social account the user signed in to.
|
||||
@@ -55,28 +55,29 @@ func (e Expiry) Days() int { return int(time.Until(e.At) / (24 * time.Hour)) }
|
||||
|
||||
// linkedInExpiry is when the LinkedIn sign-in runs out, or nil if LinkedIn
|
||||
// isn't connected.
|
||||
func (s *Server) linkedInExpiry() *Expiry {
|
||||
if !s.Secrets.Has(secrets.LinkedInAccessToken) {
|
||||
func (s *Server) linkedInExpiry() *Expiry { return s.companyExpiry(posting.LinkedIn) }
|
||||
|
||||
// companyExpiry is when the company's account on a network runs out, or
|
||||
// nil if it's renewed by itself (or there's none).
|
||||
func (s *Server) companyExpiry(network string) *Expiry {
|
||||
s.adoptLegacy()
|
||||
a, err := posting.Company(s.DB, network)
|
||||
if err != nil || a == nil || a.Expires.IsZero() {
|
||||
return nil
|
||||
}
|
||||
c := s.connections()["linkedin"]
|
||||
at := c.Expires
|
||||
if at.IsZero() {
|
||||
if c.At.IsZero() {
|
||||
return nil // a token from the old app: when it was made is unknown
|
||||
}
|
||||
at = c.At.Add(linkedInTokenLife)
|
||||
}
|
||||
return &Expiry{Network: "LinkedIn", At: at}
|
||||
return &Expiry{Network: a.Label(), At: a.Expires}
|
||||
}
|
||||
|
||||
// reminders are the sign-ins running out soon, or already, for the
|
||||
// Overview and Posts.
|
||||
// Overview and Posts: every account's.
|
||||
func (s *Server) reminders() []Expiry {
|
||||
var out []Expiry
|
||||
for _, e := range []*Expiry{s.linkedInExpiry(), s.linkedInPageExpiry()} {
|
||||
if e != nil && e.Soon() {
|
||||
out = append(out, *e)
|
||||
for _, a := range s.postingAccounts() {
|
||||
if a.Expires.IsZero() {
|
||||
continue
|
||||
}
|
||||
if e := (Expiry{Network: a.Label(), At: a.Expires}); e.Soon() {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
@@ -140,7 +141,7 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
Detail: ifElse(p.IsSet(), p.Name, "Describe the company, its products and its customers (the AI can draft it from your website)")},
|
||||
{Label: "Market", Done: len(entries) > 0, Link: "/market",
|
||||
Detail: inventorySummary(counts)},
|
||||
{Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken) || s.Secrets.Has(secrets.RedditAccessToken),
|
||||
{Label: "Social accounts", Done: len(s.postingAccounts()) > 0,
|
||||
Link: "/settings/accounts", Detail: s.connectionSummary(conns)},
|
||||
{Label: "Federated Core", Done: s.Core != nil, Link: "/settings/core",
|
||||
Detail: ifElse(s.Core != nil, coreDomain(s.Core), "No Core found; run `configure core` in CoreDesktop")},
|
||||
@@ -209,20 +210,14 @@ func inventorySummary(c map[string]int) string {
|
||||
return plural(c[inventory.Partner], "partner") + ", " + plural(c[inventory.Competitor], "competitor") + ", " + plural(c[inventory.Watch], "watched")
|
||||
}
|
||||
|
||||
func (s *Server) connectionSummary(c map[string]Connection) string {
|
||||
func (s *Server) connectionSummary(map[string]Connection) string {
|
||||
var parts []string
|
||||
if a := c["x"].Account; a != "" {
|
||||
parts = append(parts, "X @"+a)
|
||||
} else if s.Secrets.Has(secrets.XAccessToken) {
|
||||
parts = append(parts, "X")
|
||||
}
|
||||
if e := s.linkedInExpiry(); e != nil && e.Expired() {
|
||||
parts = append(parts, "LinkedIn (expired)")
|
||||
} else if s.Secrets.Has(secrets.LinkedInAccessToken) {
|
||||
parts = append(parts, "LinkedIn")
|
||||
}
|
||||
if a := c["reddit"].Account; a != "" {
|
||||
parts = append(parts, "Reddit u/"+a)
|
||||
for _, a := range s.postingAccounts() {
|
||||
label := a.Label()
|
||||
if a.Expired(time.Now()) {
|
||||
label += " (expired)"
|
||||
}
|
||||
parts = append(parts, label)
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "Connect X, LinkedIn or Reddit"
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/linkedin"
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// Posting accounts: the social accounts posts go out from, several per
|
||||
// network: the company's, and people's own. Admins may post to every one,
|
||||
// and say who else may (Settings → Posting accounts); a person's own
|
||||
// account is theirs.
|
||||
|
||||
var adoptMu sync.Mutex
|
||||
|
||||
// adoptLegacy turns the single sign-ins from before posting accounts into
|
||||
// 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) {
|
||||
return
|
||||
}
|
||||
adoptMu.Lock()
|
||||
defer adoptMu.Unlock()
|
||||
conns := s.connections()
|
||||
expiry := func(c Connection) time.Time {
|
||||
if !c.Expires.IsZero() || c.At.IsZero() {
|
||||
return c.Expires
|
||||
}
|
||||
return c.At.Add(linkedInTokenLife)
|
||||
}
|
||||
n, err := posting.Adopt(s.DB, s.Secrets, func(network string) (string, string, time.Time) {
|
||||
switch network {
|
||||
case posting.X:
|
||||
a := conns["x"].Account
|
||||
if a == "" {
|
||||
return "the company's account", "", time.Time{}
|
||||
}
|
||||
return "@" + a, a, time.Time{}
|
||||
case posting.LinkedIn:
|
||||
return "the company's member", s.Secrets.Get(secrets.LinkedInAuthorURN), expiry(conns["linkedin"])
|
||||
case posting.LinkedInPage:
|
||||
if o := s.liPage(); o != nil {
|
||||
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())
|
||||
if err != nil {
|
||||
s.Log.Error("posting accounts: adopting the old sign-ins", "err", err)
|
||||
} else if n > 0 {
|
||||
s.Log.Info("posting accounts: the old sign-ins are now the company's accounts", "count", n)
|
||||
}
|
||||
}
|
||||
|
||||
// postingAccounts are every account.
|
||||
func (s *Server) postingAccounts() []*posting.Account {
|
||||
s.adoptLegacy()
|
||||
list, err := posting.List(s.DB)
|
||||
if err != nil {
|
||||
s.Log.Error("posting accounts: listing", "err", err)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// mayPostAs says whether a viewer may post to an account: admins to all,
|
||||
// people to their own and to those they were given.
|
||||
func (s *Server) mayPostAs(v *viewer, a *posting.Account) bool {
|
||||
if v.Member.Admin() {
|
||||
return true
|
||||
}
|
||||
if v.User == nil || !v.Member.Can("content", true) {
|
||||
return false
|
||||
}
|
||||
if a.Owner == v.User.ID {
|
||||
return true
|
||||
}
|
||||
ok, err := posting.Granted(s.DB, a.ID, v.User.ID)
|
||||
return err == nil && ok
|
||||
}
|
||||
|
||||
// viewerFor is a user as a viewer: for work done for them later, such as a
|
||||
// scheduled post. On the local edition, the owner.
|
||||
func (s *Server) viewerFor(user int64) *viewer {
|
||||
if !s.signsIn() {
|
||||
return localOwner
|
||||
}
|
||||
u, err := users.ByID(s.DB, user)
|
||||
if err != nil || u.Status != users.Active {
|
||||
return &viewer{}
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
if err != nil {
|
||||
return &viewer{}
|
||||
}
|
||||
return &viewer{User: u, Member: m}
|
||||
}
|
||||
|
||||
// working says whether an account can post now: signed in, not expired,
|
||||
// and (a LinkedIn page) with its page chosen.
|
||||
func (s *Server) working(a *posting.Account) bool {
|
||||
return s.Secrets.Has(posting.AccessName(a.ID)) && !a.Expired(time.Now()) &&
|
||||
(a.Network != posting.LinkedInPage || a.External != "")
|
||||
}
|
||||
|
||||
// usableAccounts are the accounts a viewer may post a channel's drafts to
|
||||
// now, by channel.
|
||||
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) {
|
||||
ch := posting.Channel(a.Network)
|
||||
out[ch] = append(out[ch], a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// draftAccount is the account a draft goes out from: its own, or the
|
||||
// company's for its channel (LinkedIn: as the draft said, member or page,
|
||||
// else whichever there is). nil if there's none.
|
||||
func (s *Server) draftAccount(dr *content.Draft) (*posting.Account, error) {
|
||||
s.adoptLegacy()
|
||||
if dr.AccountID != 0 {
|
||||
a, err := posting.Get(s.DB, dr.AccountID)
|
||||
if errors.Is(err, posting.ErrNotFound) {
|
||||
return nil, errors.New("the account this draft was to go out from was signed out: choose another")
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
nets := []string{dr.Channel}
|
||||
if dr.Channel == content.ChannelLinkedIn {
|
||||
nets = []string{posting.LinkedIn, posting.LinkedInPage}
|
||||
if dr.LinkedInAs == content.AsPage {
|
||||
nets = []string{posting.LinkedInPage, posting.LinkedIn}
|
||||
}
|
||||
}
|
||||
for _, n := range nets {
|
||||
a, err := posting.Company(s.DB, n)
|
||||
if err != nil || a != nil {
|
||||
return a, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// accountPublishers find each draft's account and post as it.
|
||||
type accountPublishers struct{ s *Server }
|
||||
|
||||
func (s *Server) publishers() content.Publishers { return accountPublishers{s} }
|
||||
|
||||
func (p accountPublishers) For(dr *content.Draft) (content.Publisher, string, error) {
|
||||
a, err := p.s.draftAccount(dr)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if a == nil {
|
||||
return nil, "", fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName())
|
||||
}
|
||||
if posting.Channel(a.Network) != dr.Channel {
|
||||
return nil, "", fmt.Errorf("%s can't post %s drafts", a.Label(), dr.ChannelName())
|
||||
}
|
||||
if a.Expired(time.Now()) {
|
||||
return nil, "", expiredPublisher{Expiry{Network: a.Label(), At: a.Expires}}.err()
|
||||
}
|
||||
pub, err := p.s.publisherFor(a)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return pub, a.Label(), nil
|
||||
}
|
||||
|
||||
// asPublisher posts to LinkedIn as a member or as a page, whatever the
|
||||
// draft says: the account decides.
|
||||
type asPublisher struct {
|
||||
p content.Publisher
|
||||
page bool
|
||||
}
|
||||
|
||||
func (a asPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
|
||||
post.AsPage = a.page
|
||||
return a.p.Publish(ctx, post)
|
||||
}
|
||||
|
||||
// publisherFor posts as one account.
|
||||
func (s *Server) publisherFor(a *posting.Account) (content.Publisher, error) {
|
||||
if s.testPublisher != nil {
|
||||
return s.testPublisher(a), nil
|
||||
}
|
||||
tok := s.Secrets.Get(posting.AccessName(a.ID))
|
||||
if tok == "" {
|
||||
return nil, fmt.Errorf("%s isn't signed in: sign in again under Settings → Social accounts", a.Label())
|
||||
}
|
||||
switch a.Network {
|
||||
case posting.X:
|
||||
c := twitter.New("", tok, 0)
|
||||
// X access tokens last two hours; refresh tokens are single-use, so
|
||||
// each new one is saved before the old is gone.
|
||||
if s.Secrets.Has(posting.RefreshName(a.ID)) && s.Secrets.Has(secrets.XClientID) {
|
||||
id := a.ID
|
||||
c.SetTokenRefresher(func(ctx context.Context) (string, string, error) {
|
||||
res, err := oauth.RefreshX(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), 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("x: couldn't save the refreshed token; sign in to X again later", "account", id, "err", err)
|
||||
}
|
||||
return res.AccessToken, res.RefreshToken, nil
|
||||
})
|
||||
}
|
||||
return xPublisher{c}, nil
|
||||
case posting.LinkedIn:
|
||||
return asPublisher{linkedInPublisher{me: linkedin.New(tok, a.External)}, false}, nil
|
||||
case posting.LinkedInPage:
|
||||
if a.External == "" {
|
||||
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 {
|
||||
held, err := content.HoldForAccount(s.DB, a.ID, "Not published: "+a.Label()+" "+why+". Choose another account, then publish or schedule it again.")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := posting.Remove(s.DB, s.Secrets, a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Log.Info("posting accounts: removed", "account", a.Label(), "why", why, "held", len(held))
|
||||
s.tellWriters(held, a.Label()+" "+why)
|
||||
return nil
|
||||
}
|
||||
|
||||
// tellWriters emails the people who scheduled posts that were held.
|
||||
func (s *Server) tellWriters(held []content.Draft, what string) {
|
||||
if !s.signsIn() || len(held) == 0 {
|
||||
return
|
||||
}
|
||||
per := map[int64]int{}
|
||||
for _, d := range held {
|
||||
who := d.PostedBy
|
||||
if who == 0 {
|
||||
who = d.WrittenBy
|
||||
}
|
||||
if who != 0 {
|
||||
per[who]++
|
||||
}
|
||||
}
|
||||
for id, n := range per {
|
||||
u, err := users.ByID(s.DB, id)
|
||||
if err != nil || u.Status != users.Active {
|
||||
continue
|
||||
}
|
||||
posts := "a scheduled post"
|
||||
if n > 1 {
|
||||
posts = strconv.Itoa(n) + " scheduled posts"
|
||||
}
|
||||
s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Supermarket: " + posts + " held back",
|
||||
Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + what + ", so " + posts + " you scheduled for it won't go out. " +
|
||||
"They're back in Posts: choose another account, then publish or schedule them again.\n\n" + s.PublicURL + "/posts\n"})
|
||||
}
|
||||
}
|
||||
|
||||
// Settings → Posting accounts: who may post to which.
|
||||
|
||||
type postingGrid struct {
|
||||
Accounts []*posting.Account
|
||||
People []users.TeamUser
|
||||
Grants map[int64]map[int64]bool
|
||||
Working map[int64]bool
|
||||
Owners map[int64]string
|
||||
}
|
||||
|
||||
func (s *Server) postingPage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.admin(w, r) == nil {
|
||||
return
|
||||
}
|
||||
g := postingGrid{Accounts: s.postingAccounts(), Working: map[int64]bool{}, Owners: map[int64]string{}}
|
||||
var err error
|
||||
if g.Grants, err = posting.Grants(s.DB); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
members, err := users.Members(s.DB, users.Team)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
for _, m := range members {
|
||||
if m.Kind == users.Person && m.Status != users.Disabled {
|
||||
g.People = append(g.People, m)
|
||||
}
|
||||
g.Owners[m.ID] = m.Name
|
||||
}
|
||||
for _, a := range g.Accounts {
|
||||
g.Working[a.ID] = s.working(a)
|
||||
}
|
||||
s.render(w, r, "posting", page{Title: "Posting accounts", Nav: "settings/posting", Data: g})
|
||||
}
|
||||
|
||||
func (s *Server) postingSave(w http.ResponseWriter, r *http.Request) {
|
||||
if s.admin(w, r) == nil {
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
accounts := s.postingAccounts()
|
||||
known := map[int64]*posting.Account{}
|
||||
for _, a := range accounts {
|
||||
known[a.ID] = a
|
||||
}
|
||||
grants := map[int64][]int64{}
|
||||
for _, v := range r.PostForm["grant"] { // <account>:<user>
|
||||
var a, u int64
|
||||
if _, err := fmt.Sscanf(v, "%d:%d", &a, &u); err != nil || known[a] == nil || known[a].Owner == u {
|
||||
continue
|
||||
}
|
||||
grants[a] = append(grants[a], u)
|
||||
}
|
||||
if err := posting.SetGrants(s.DB, grants); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.Log.Info("posting accounts: who may post changed", "by", viewerOf(r).User.Email)
|
||||
redirect(w, r, "/settings/posting", "saved")
|
||||
}
|
||||
|
||||
// postingRemove signs an account out: an admin any, a person their own.
|
||||
func (s *Server) postingRemove(w http.ResponseWriter, r *http.Request) {
|
||||
v := viewerOf(r)
|
||||
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
a, err := posting.Get(s.DB, id)
|
||||
if errors.Is(err, posting.ErrNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
mine := v.User != nil && a.Owner == v.User.ID
|
||||
if !mine && !v.Member.Admin() {
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
why := "was signed out"
|
||||
if mine {
|
||||
why = "was signed out by its owner"
|
||||
}
|
||||
if err := s.removeAccount(a, why); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
back := "/settings/accounts"
|
||||
if strings.HasPrefix(r.URL.Path, "/settings/account/") {
|
||||
back = "/settings/account#posting"
|
||||
}
|
||||
redirect(w, r, back, "account-removed")
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// fakePosts records what went out, and from which account.
|
||||
type fakePosts struct {
|
||||
mu sync.Mutex
|
||||
sent []string // "<account label>: <text>"
|
||||
}
|
||||
|
||||
type fakePub struct {
|
||||
f *fakePosts
|
||||
a *posting.Account
|
||||
}
|
||||
|
||||
func (p fakePub) Publish(_ context.Context, post content.Post) (string, error) {
|
||||
p.f.mu.Lock()
|
||||
defer p.f.mu.Unlock()
|
||||
p.f.sent = append(p.f.sent, p.a.Label()+": "+post.Text)
|
||||
return "https://x.com/" + p.a.External + "/status/" + strconv.Itoa(len(p.f.sent)), nil
|
||||
}
|
||||
|
||||
func ids(as ...*posting.Account) []string {
|
||||
var out []string
|
||||
for _, a := range as {
|
||||
out = append(out, strconv.FormatInt(a.ID, 10))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestPostingAccounts(t *testing.T) {
|
||||
s, h := newServerEdition(t)
|
||||
sent := &fakePosts{}
|
||||
s.testPublisher = func(a *posting.Account) content.Publisher { return fakePub{sent, a} }
|
||||
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
|
||||
oc := sessionFor(t, s, owner)
|
||||
jo := addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"content": users.Edit})
|
||||
jc := sessionFor(t, s, jo)
|
||||
viewer := addUser(t, s, "vi@example.com", users.Member, map[string]users.Access{"content": users.View})
|
||||
|
||||
now := time.Now()
|
||||
company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
|
||||
posting.Save(s.DB, s.Secrets, company, "t1", "", now)
|
||||
own := &posting.Account{Network: posting.X, Name: "@jo", External: "jo", Owner: jo.ID}
|
||||
posting.Save(s.DB, s.Secrets, own, "t2", "", now)
|
||||
|
||||
content.CreateDrafts(s.DB, []content.Draft{{Channel: content.ChannelX, Content: "Hello", WrittenBy: jo.ID}})
|
||||
ds, _ := content.ListDrafts(s.DB, 1, content.StatusDraft)
|
||||
draft := strconv.FormatInt(ds[0].ID, 10)
|
||||
|
||||
// Jo sees only her own account; the owner sees both.
|
||||
body := as(h, jc, http.MethodGet, "/posts", nil).Body.String()
|
||||
if !strings.Contains(body, "X @jo") || strings.Contains(body, "X @acme") {
|
||||
t.Errorf("jo's choices: %s", body)
|
||||
}
|
||||
if body := as(h, oc, http.MethodGet, "/posts", nil).Body.String(); !strings.Contains(body, "X @jo") || !strings.Contains(body, "X @acme") {
|
||||
t.Error("owner's choices")
|
||||
}
|
||||
// The draft goes to the company's account by default, which Jo may not
|
||||
// post to; nor may she choose it.
|
||||
if rec := as(h, jc, http.MethodPost, "/drafts/"+draft+"/publish", url.Values{"content": {"Hello"}}); rec.Code == http.StatusSeeOther || !strings.Contains(rec.Body.String(), "may not post as X @acme") {
|
||||
t.Errorf("jo to the company's: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := as(h, jc, http.MethodPost, "/drafts/"+draft+"/publish", url.Values{"content": {"Hello"}, "accounts": ids(company)}); rec.Code == http.StatusSeeOther {
|
||||
t.Errorf("jo chose the company's: %d", rec.Code)
|
||||
}
|
||||
if len(sent.sent) != 0 {
|
||||
t.Fatalf("sent %v", sent.sent)
|
||||
}
|
||||
// The owner lets her: the grid.
|
||||
if rec := as(h, sessionFor(t, s, viewer), http.MethodGet, "/settings/posting", nil); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("member on the grid: %d", rec.Code)
|
||||
}
|
||||
grid := as(h, oc, http.MethodGet, "/settings/posting", nil).Body.String()
|
||||
if !strings.Contains(grid, `name="grant" value="`+strconv.FormatInt(company.ID, 10)+`:`+strconv.FormatInt(jo.ID, 10)+`"`) {
|
||||
t.Errorf("grid: %s", grid)
|
||||
}
|
||||
as(h, oc, http.MethodPost, "/settings/posting", url.Values{"grant": {strconv.FormatInt(company.ID, 10) + ":" + strconv.FormatInt(jo.ID, 10), "999:1"}})
|
||||
if ok, _ := posting.Granted(s.DB, company.ID, jo.ID); !ok {
|
||||
t.Fatal("not granted")
|
||||
}
|
||||
// Now to both at once: a copy each, and each records who and as what.
|
||||
rec := as(h, jc, http.MethodPost, "/drafts/"+draft+"/publish", url.Values{"content": {"Hello all"}, "accounts": ids(own, company)})
|
||||
if rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("publish to both: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(sent.sent) != 2 || sent.sent[0] != "X @jo: Hello all" || sent.sent[1] != "X @acme: Hello all" {
|
||||
t.Errorf("sent %v", sent.sent)
|
||||
}
|
||||
pub, _ := content.ListDrafts(s.DB, 10, content.StatusPublished)
|
||||
if len(pub) != 2 {
|
||||
t.Fatalf("published %d", len(pub))
|
||||
}
|
||||
for _, d := range pub {
|
||||
if d.PostedBy != jo.ID || d.WrittenBy != jo.ID || d.PostedAs == "" || d.Batch != ds[0].Batch {
|
||||
t.Errorf("published %+v", d)
|
||||
}
|
||||
}
|
||||
if body := as(h, jc, http.MethodGet, "/content/published", nil).Body.String(); !strings.Contains(body, "as X @acme") {
|
||||
t.Error("published list doesn't say where")
|
||||
}
|
||||
|
||||
// Jo schedules a post to her own account, then signs it out: it's held,
|
||||
// and she's told.
|
||||
content.CreateDrafts(s.DB, []content.Draft{{Channel: content.ChannelX, Content: "Later", WrittenBy: jo.ID}})
|
||||
ds, _ = content.ListDrafts(s.DB, 1, content.StatusDraft)
|
||||
later := strconv.FormatInt(ds[0].ID, 10)
|
||||
when := time.Now().Add(48 * time.Hour).Format(dateTimeLocal)
|
||||
if rec := as(h, jc, http.MethodPost, "/drafts/"+later+"/schedule", url.Values{"content": {"Later"}, "accounts": ids(own), "when": {when}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("schedule: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// Someone else can't sign Jo's account out; she can.
|
||||
member2 := addUser(t, s, "kim@example.com", users.Member, map[string]users.Access{"content": users.Edit})
|
||||
if rec := as(h, sessionFor(t, s, member2), http.MethodPost, "/settings/account/posting/"+strconv.FormatInt(own.ID, 10)+"/remove", url.Values{}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("someone else signs it out: %d", rec.Code)
|
||||
}
|
||||
if rec := as(h, jc, http.MethodPost, "/settings/account/posting/"+strconv.FormatInt(own.ID, 10)+"/remove", url.Values{}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("sign out own: %d", rec.Code)
|
||||
}
|
||||
d, _ := content.GetDraft(s.DB, ds[0].ID)
|
||||
if d.Status != content.StatusFailed || !strings.Contains(d.Error, "X @jo was signed out") || d.AccountID != 0 {
|
||||
t.Errorf("held: %+v", d)
|
||||
}
|
||||
m := waitMail(t, s, "jo@example.com", 1)
|
||||
if !strings.Contains(m.Subject, "held back") {
|
||||
t.Errorf("mail %+v", m)
|
||||
}
|
||||
|
||||
// A scheduled post whose writer lost the right to post as its account
|
||||
// is held when it falls due.
|
||||
content.CreateDrafts(s.DB, []content.Draft{{Channel: content.ChannelX, Content: "Due", WrittenBy: jo.ID}})
|
||||
ds, _ = content.ListDrafts(s.DB, 1, content.StatusDraft)
|
||||
content.SetAccount(s.DB, ds[0].ID, company.ID)
|
||||
content.Schedule(s.DB, ds[0].ID, time.Now().Add(time.Minute))
|
||||
content.SetPostedBy(s.DB, ds[0].ID, jo.ID)
|
||||
posting.SetGrants(s.DB, nil)
|
||||
s.publishDue(context.Background(), time.Now().Add(2*time.Minute))
|
||||
if d, _ := content.GetDraft(s.DB, ds[0].ID); d.Status != content.StatusFailed || !strings.Contains(d.Error, "may not post as") {
|
||||
t.Errorf("due without the right: %+v", d)
|
||||
}
|
||||
if len(sent.sent) != 2 {
|
||||
t.Errorf("sent %v", sent.sent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnAccountSignIn(t *testing.T) {
|
||||
s, h := newServerEdition(t)
|
||||
addUser(t, s, "owner@example.com", users.Owner, nil)
|
||||
jo := addUser(t, s, "jo@example.com", users.Member, map[string]users.Access{"content": users.Edit})
|
||||
jc := sessionFor(t, s, jo)
|
||||
seo := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit})
|
||||
s.Secrets.Set(map[string]string{secrets.XClientID: "cid"})
|
||||
|
||||
if body := as(h, jc, http.MethodGet, "/settings/account", nil).Body.String(); !strings.Contains(body, "Connect your X") {
|
||||
t.Error("no connect button")
|
||||
}
|
||||
// The company's accounts need an admin.
|
||||
if rec := as(h, jc, http.MethodPost, "/auth/x/start", url.Values{}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("member, company account: %d", rec.Code)
|
||||
}
|
||||
if rec := as(h, sessionFor(t, s, seo), http.MethodPost, "/auth/x/start?for=me", url.Values{}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("member without Content: %d", rec.Code)
|
||||
}
|
||||
rec := as(h, jc, http.MethodPost, "/auth/x/start?for=me", url.Values{})
|
||||
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "client_id=cid") {
|
||||
t.Fatalf("start: %d %s", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
loc, _ := url.Parse(rec.Header().Get("Location"))
|
||||
var p oauth.Pending
|
||||
if ok, _ := s.DB.GetJSON(oauthFlowKey+loc.Query().Get("state"), &p); !ok || p.For != jo.ID {
|
||||
t.Errorf("pending %+v", p)
|
||||
}
|
||||
// Another person can't finish Jo's sign-in.
|
||||
other := sessionFor(t, s, seo)
|
||||
if rec := as(h, other, http.MethodGet, "/auth/x/callback?code=c&state="+loc.Query().Get("state"), nil); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("someone else's callback: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
+97
-87
@@ -28,10 +28,12 @@ import (
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/content"
|
||||
"supermarket/internal/core"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/legacy"
|
||||
"supermarket/internal/metrics"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
@@ -74,6 +76,8 @@ type Server struct {
|
||||
jobsOnce sync.Once
|
||||
setupDone atomic.Bool // the team has its owner (server edition)
|
||||
|
||||
testPublisher func(*posting.Account) content.Publisher // tests: posts nowhere
|
||||
|
||||
// Reddit: an app-only token for reading rules before sign-in, and the
|
||||
// account's recent posts for the warnings.
|
||||
redditAppToken string
|
||||
@@ -338,6 +342,10 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload)
|
||||
mux.HandleFunc("GET /settings/about", s.aboutPage)
|
||||
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
|
||||
mux.HandleFunc("GET /settings/posting", s.postingPage)
|
||||
mux.HandleFunc("POST /settings/posting", s.postingSave)
|
||||
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
|
||||
mux.HandleFunc("POST /settings/account/posting/{id}/remove", s.postingRemove)
|
||||
mux.HandleFunc("GET /settings/core", s.corePage)
|
||||
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
|
||||
|
||||
@@ -659,93 +667,95 @@ func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name str
|
||||
|
||||
// Messages shown after a redirect, by code, so no user text is reflected.
|
||||
var flashes = map[string]string{
|
||||
"saved": "Saved.",
|
||||
"welcome": "Welcome: you're the owner. Start with the company's profile.",
|
||||
"signed-out": "Signed out.",
|
||||
"password-reset": "Your new password is saved: sign in with it.",
|
||||
"password-changed": "Password changed. You're signed out everywhere else.",
|
||||
"session-ended": "Signed out there.",
|
||||
"sessions-ended": "Signed out everywhere else.",
|
||||
"two-factor-off": "Two-factor sign-in is off.",
|
||||
"codes-low": "You're running out of recovery codes: make new ones below.",
|
||||
"invited": "Invitation sent.",
|
||||
"withdrawn": "Invitation withdrawn.",
|
||||
"disabled": "The account is turned off, and signed out.",
|
||||
"enabled": "The account is back on.",
|
||||
"unlocked": "Unlocked.",
|
||||
"two-factor-reset": "Two-factor sign-in is reset: they sign in with their password, then can turn it on again.",
|
||||
"signed-out-user": "Signed out everywhere.",
|
||||
"removed": "Removed.",
|
||||
"joined": "Welcome to Supermarket.",
|
||||
"deleted": "Deleted.",
|
||||
"x-connected": "X is connected.",
|
||||
"li-connected": "LinkedIn is connected.",
|
||||
"site-created": "The site is started: its first commit is on Gitea. Build its first pages below.",
|
||||
"li-page-connected": "The LinkedIn page app is connected.",
|
||||
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
|
||||
"synced": "Synced from Search Console.",
|
||||
"report-written": "This week's report is written.",
|
||||
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
|
||||
"pinged": "Sent to IndexNow.",
|
||||
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
|
||||
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
|
||||
"keywords-found": "Looked for keywords: the candidates are below.",
|
||||
"top-read": "Read the live top results.",
|
||||
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
|
||||
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
|
||||
"declined": "Declined.",
|
||||
"keyword-picked": "Picked. Write its brief when you're ready.",
|
||||
"keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.",
|
||||
"keyword-back": "Back among the candidates.",
|
||||
"signups-saved": "Saved. The pages' sign-ups were read again with it.",
|
||||
"next-dismissed": "Hidden for 90 days.",
|
||||
"link-added": "Added, and checked.",
|
||||
"links-checked": "Checked %d links.",
|
||||
"link-forgotten": "Forgotten.",
|
||||
"partners-read": "Looked at the partners' pages: %d new places to ask for a link.",
|
||||
"alternatives-read": "Searched: %d new lists that leave you out.",
|
||||
"optouts-synced": "Synced: %d new on the suppression list.",
|
||||
"listed": "Added to the mailing list.",
|
||||
"bing-read": "Read the links from Bing.",
|
||||
"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.",
|
||||
"rejected": "Set aside.",
|
||||
"reconsidered": "Back in New.",
|
||||
"suppressed": "Added to the suppression list.",
|
||||
"unsuppressed": "Taken off the suppression list.",
|
||||
"prospect-added": "Added. Review it below.",
|
||||
"crm-retried": "Queued again: Hermes tries it on its next run.",
|
||||
"crm-cancelled": "Taken back: Hermes won't do it.",
|
||||
"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.",
|
||||
"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.",
|
||||
"verified": "Checked with Hunter.io: the result is on each person.",
|
||||
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
|
||||
"queued": "Queued: it goes out in turn, within your sending hours.",
|
||||
"unqueued": "Back in Drafts.",
|
||||
"sent": "Sent.",
|
||||
"marked-sent": "Marked as sent.",
|
||||
"reply-recorded": "Reply recorded.",
|
||||
"checked": "Inbox checked: what it found is above.",
|
||||
"test-sent": "Test email sent: check your inbox.",
|
||||
"oauth-expired": "That sign-in took too long or was already used. Try again.",
|
||||
"dismissed": "Dismissed.",
|
||||
"restored": "Restored.",
|
||||
"drafted": "Drafts written. Review them below.",
|
||||
"published": "Published.",
|
||||
"discarded": "Discarded.",
|
||||
"scheduled": "Scheduled.",
|
||||
"posted": "Marked as posted: it's under Content → Published.",
|
||||
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
|
||||
"saved": "Saved.",
|
||||
"welcome": "Welcome: you're the owner. Start with the company's profile.",
|
||||
"signed-out": "Signed out.",
|
||||
"password-reset": "Your new password is saved: sign in with it.",
|
||||
"password-changed": "Password changed. You're signed out everywhere else.",
|
||||
"session-ended": "Signed out there.",
|
||||
"sessions-ended": "Signed out everywhere else.",
|
||||
"two-factor-off": "Two-factor sign-in is off.",
|
||||
"codes-low": "You're running out of recovery codes: make new ones below.",
|
||||
"invited": "Invitation sent.",
|
||||
"withdrawn": "Invitation withdrawn.",
|
||||
"disabled": "The account is turned off, and signed out.",
|
||||
"enabled": "The account is back on.",
|
||||
"unlocked": "Unlocked.",
|
||||
"two-factor-reset": "Two-factor sign-in is reset: they sign in with their password, then can turn it on again.",
|
||||
"signed-out-user": "Signed out everywhere.",
|
||||
"removed": "Removed.",
|
||||
"joined": "Welcome to Supermarket.",
|
||||
"account-removed": "Signed out: posts scheduled to it are back in Posts.",
|
||||
"own-account-connected": "Connected: you can post as it, and an admin can let others.",
|
||||
"deleted": "Deleted.",
|
||||
"x-connected": "X is connected.",
|
||||
"li-connected": "LinkedIn is connected.",
|
||||
"site-created": "The site is started: its first commit is on Gitea. Build its first pages below.",
|
||||
"li-page-connected": "The LinkedIn page app is connected.",
|
||||
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
|
||||
"synced": "Synced from Search Console.",
|
||||
"report-written": "This week's report is written.",
|
||||
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
|
||||
"pinged": "Sent to IndexNow.",
|
||||
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
|
||||
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
|
||||
"keywords-found": "Looked for keywords: the candidates are below.",
|
||||
"top-read": "Read the live top results.",
|
||||
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
|
||||
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
|
||||
"declined": "Declined.",
|
||||
"keyword-picked": "Picked. Write its brief when you're ready.",
|
||||
"keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.",
|
||||
"keyword-back": "Back among the candidates.",
|
||||
"signups-saved": "Saved. The pages' sign-ups were read again with it.",
|
||||
"next-dismissed": "Hidden for 90 days.",
|
||||
"link-added": "Added, and checked.",
|
||||
"links-checked": "Checked %d links.",
|
||||
"link-forgotten": "Forgotten.",
|
||||
"partners-read": "Looked at the partners' pages: %d new places to ask for a link.",
|
||||
"alternatives-read": "Searched: %d new lists that leave you out.",
|
||||
"optouts-synced": "Synced: %d new on the suppression list.",
|
||||
"listed": "Added to the mailing list.",
|
||||
"bing-read": "Read the links from Bing.",
|
||||
"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.",
|
||||
"rejected": "Set aside.",
|
||||
"reconsidered": "Back in New.",
|
||||
"suppressed": "Added to the suppression list.",
|
||||
"unsuppressed": "Taken off the suppression list.",
|
||||
"prospect-added": "Added. Review it below.",
|
||||
"crm-retried": "Queued again: Hermes tries it on its next run.",
|
||||
"crm-cancelled": "Taken back: Hermes won't do it.",
|
||||
"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.",
|
||||
"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.",
|
||||
"verified": "Checked with Hunter.io: the result is on each person.",
|
||||
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
|
||||
"queued": "Queued: it goes out in turn, within your sending hours.",
|
||||
"unqueued": "Back in Drafts.",
|
||||
"sent": "Sent.",
|
||||
"marked-sent": "Marked as sent.",
|
||||
"reply-recorded": "Reply recorded.",
|
||||
"checked": "Inbox checked: what it found is above.",
|
||||
"test-sent": "Test email sent: check your inbox.",
|
||||
"oauth-expired": "That sign-in took too long or was already used. Try again.",
|
||||
"dismissed": "Dismissed.",
|
||||
"restored": "Restored.",
|
||||
"drafted": "Drafts written. Review them below.",
|
||||
"published": "Published.",
|
||||
"discarded": "Discarded.",
|
||||
"scheduled": "Scheduled.",
|
||||
"posted": "Marked as posted: it's under Content → Published.",
|
||||
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
|
||||
}
|
||||
|
||||
// sentence starts a message with a capital letter: errors from deeper
|
||||
|
||||
+18
-11
@@ -24,6 +24,7 @@ import (
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/mcpserver"
|
||||
"supermarket/internal/models"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
@@ -430,39 +431,45 @@ func TestProfileDraftNeedsAI(t *testing.T) {
|
||||
|
||||
func TestLinkedInExpiryReminders(t *testing.T) {
|
||||
s, h := newTestServer(t, nil)
|
||||
_ = s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: "tok", secrets.LinkedInAuthorURN: "urn:li:person:1"})
|
||||
day := 24 * time.Hour
|
||||
get := func(path string) string { return do(h, http.MethodGet, path, nil, nil).Body.String() }
|
||||
signIn := func(expires time.Time) {
|
||||
t.Helper()
|
||||
a := &posting.Account{Network: posting.LinkedIn, Name: "Pat", External: "urn:li:person:1", Expires: expires}
|
||||
if err := posting.Save(s.DB, s.Secrets, a, "tok", "", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Plenty of time: the card says until when, no reminders.
|
||||
_ = s.saveConnection("linkedin", Connection{At: time.Now(), Expires: time.Now().Add(50 * day)})
|
||||
signIn(time.Now().Add(50 * day))
|
||||
if !strings.Contains(get("/settings/accounts"), "The sign-in lasts until") || strings.Contains(get("/"), "Reconnect LinkedIn") {
|
||||
t.Error("50 days left: wrong reminders")
|
||||
}
|
||||
if !s.connected()["linkedin"] {
|
||||
if !s.connected(localOwner)["linkedin"] {
|
||||
t.Error("50 days left: should be connected")
|
||||
}
|
||||
|
||||
// Saved before expiries were recorded, 50 days ago: 10 days left.
|
||||
_ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-50 * day)})
|
||||
// 10 days left.
|
||||
signIn(time.Now().Add(10*day - time.Hour))
|
||||
for _, path := range []string{"/", "/posts"} {
|
||||
if body := get(path); !strings.Contains(body, "LinkedIn's sign-in expires in 9 days") && !strings.Contains(body, "LinkedIn's sign-in expires in 10 days") {
|
||||
t.Errorf("%s: no 10-day reminder", path)
|
||||
if body := get(path); !strings.Contains(body, "LinkedIn Pat's sign-in expires in 9 days") && !strings.Contains(body, "LinkedIn Pat's sign-in expires in 10 days") {
|
||||
t.Errorf("%s: no 10-day reminder: %s", path, body)
|
||||
}
|
||||
}
|
||||
|
||||
// Expired: reminders, not connected, and publishing says why.
|
||||
_ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-61 * day), Expires: time.Now().Add(-day)})
|
||||
if body := get("/"); !strings.Contains(body, "LinkedIn's sign-in expired on") {
|
||||
signIn(time.Now().Add(-day))
|
||||
if body := get("/"); !strings.Contains(body, "LinkedIn Pat's sign-in expired on") {
|
||||
t.Error("expired: no reminder on the Overview")
|
||||
}
|
||||
if !strings.Contains(get("/settings/accounts"), "The sign-in expired on") {
|
||||
t.Error("expired: the card doesn't say so")
|
||||
}
|
||||
if s.connected()["linkedin"] {
|
||||
if s.connected(localOwner)["linkedin"] {
|
||||
t.Error("expired: still counted as connected")
|
||||
}
|
||||
if _, err := s.publishers()["linkedin"].Publish(context.Background(), content.Post{Text: "hi"}); err == nil ||
|
||||
if _, _, err := s.publishers().For(&content.Draft{Channel: content.ChannelLinkedIn}); err == nil ||
|
||||
!strings.Contains(err.Error(), "reconnect LinkedIn") {
|
||||
t.Errorf("expired publish: %v", err)
|
||||
}
|
||||
|
||||
+87
-33
@@ -14,6 +14,7 @@ import (
|
||||
"supermarket/internal/api/reddit"
|
||||
"supermarket/internal/api/twitter"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
@@ -236,6 +237,7 @@ type connectInfo struct {
|
||||
Note string
|
||||
Expiry *Expiry // when the sign-in runs out, for LinkedIn
|
||||
Page *pageSetup // the company page's choices, for the LinkedIn page
|
||||
Accounts []*posting.Account
|
||||
}
|
||||
|
||||
func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -246,16 +248,24 @@ func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// networks are the cards on the Social accounts tab, as things stand.
|
||||
func (s *Server) networks() []network {
|
||||
names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.LinkedInPageAccessToken, secrets.RedditAccessToken}
|
||||
var names []string
|
||||
for _, f := range accountFields {
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
set := s.secretState(names...)
|
||||
conns := s.connections()
|
||||
accts := s.postingAccounts()
|
||||
netOf := map[string]string{"x": posting.X, "linkedin": posting.LinkedIn, liPageProvider: posting.LinkedInPage, "reddit": posting.Reddit}
|
||||
connect := func(provider, token, setup, note string, ready bool, account func(string) string) *connectInfo {
|
||||
c := conns[provider]
|
||||
return &connectInfo{Provider: provider, Redirect: s.callbackURL(provider),
|
||||
Setup: setup, Note: note, Ready: ready, Signed: set[token], Account: account(c.Account), At: c.At}
|
||||
c := &connectInfo{Provider: provider, Redirect: s.callbackURL(provider), Setup: setup, Note: note, Ready: ready}
|
||||
for _, a := range accts {
|
||||
if a.Network == netOf[provider] {
|
||||
c.Accounts = append(c.Accounts, a)
|
||||
if a.Owner == 0 && !c.Signed {
|
||||
c.Signed, c.Account, c.At = true, a.Name, a.Created
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
at := func(prefix string) func(string) string {
|
||||
return func(a string) string {
|
||||
@@ -344,6 +354,20 @@ const oauthTTL = 15 * time.Minute
|
||||
|
||||
func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
|
||||
provider := r.PathValue("provider")
|
||||
// Admins connect the company's accounts (and Search Console); anyone
|
||||
// with Content may connect their own posting account.
|
||||
v := viewerOf(r)
|
||||
forUser := int64(0)
|
||||
if r.URL.Query().Get("for") == "me" && v.User != nil {
|
||||
if provider == "google" || provider == liPageProvider || !v.Member.Can("content", true) {
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
forUser = v.User.ID
|
||||
} else if !v.Member.Admin() {
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
var (
|
||||
authURL string
|
||||
p *oauth.Pending
|
||||
@@ -393,6 +417,7 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
p.For = forUser
|
||||
// Kept in the database: the callback may reach another copy of the app.
|
||||
if err := s.DB.PutJSON(oauthFlowKey+p.State, p); err != nil {
|
||||
s.serverError(w, err)
|
||||
@@ -455,11 +480,40 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if provider == "google" {
|
||||
back, nav = "/settings/search", "settings/search"
|
||||
}
|
||||
if p != nil && p.For != 0 {
|
||||
back, nav = "/settings/account#posting", "settings/account"
|
||||
}
|
||||
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
|
||||
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
|
||||
redirect(w, r, back, "oauth-expired")
|
||||
return
|
||||
}
|
||||
// The same person who started it: the company's sign-ins need an
|
||||
// admin, a person's own the person.
|
||||
v := viewerOf(r)
|
||||
if (p.For != 0 && (v.User == nil || v.User.ID != p.For)) || (p.For == 0 && !v.Member.Admin()) {
|
||||
s.forbidden(w, r)
|
||||
return
|
||||
}
|
||||
who := int64(0)
|
||||
if v.User != nil {
|
||||
who = v.User.ID
|
||||
}
|
||||
// saveAccount keeps a posting account's sign-in.
|
||||
saveAccount := func(network, name, external, access, refresh string, expires time.Time) error {
|
||||
a := &posting.Account{Network: network, Name: name, External: external, Owner: p.For, CreatedBy: who, Expires: expires}
|
||||
if err := posting.Save(s.DB, s.Secrets, a, access, refresh, time.Now()); err != nil {
|
||||
return err
|
||||
}
|
||||
s.recordConnection(r, network, true)
|
||||
return nil
|
||||
}
|
||||
ownMsg := func(msg string) string {
|
||||
if p.For != 0 {
|
||||
return "own-account-connected"
|
||||
}
|
||||
return msg
|
||||
}
|
||||
fail := func(msg string) {
|
||||
s.Log.Warn("oauth: sign-in failed", "provider", provider, "reason", msg)
|
||||
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: nav, Error: msg,
|
||||
@@ -515,14 +569,15 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
s.Log.Warn("x: couldn't verify the new token", "err", err)
|
||||
}
|
||||
if err := s.setSecrets(r, map[string]string{secrets.XAccessToken: res.AccessToken, secrets.XRefreshToken: res.RefreshToken}); err != nil {
|
||||
name := "@" + account
|
||||
if account == "" {
|
||||
name = "X account"
|
||||
}
|
||||
if err := saveAccount(posting.X, name, account, res.AccessToken, res.RefreshToken, time.Time{}); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.saveConnection("x", Connection{Account: account, At: time.Now()}); err != nil {
|
||||
s.Log.Error("saving connection", "err", err)
|
||||
}
|
||||
redirect(w, r, "/settings/accounts", "x-connected")
|
||||
redirect(w, r, back, ownMsg("x-connected"))
|
||||
case "linkedin":
|
||||
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInClientID), s.Secrets.Get(secrets.LinkedInClientSecret), code, p)
|
||||
if err != nil {
|
||||
@@ -534,44 +589,47 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
fail("Signed in, but couldn't find your LinkedIn member ID: " + err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.setSecrets(r, map[string]string{secrets.LinkedInAccessToken: res.AccessToken, secrets.LinkedInAuthorURN: urn}); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
life := res.ExpiresIn
|
||||
if life <= 0 {
|
||||
life = linkedInTokenLife
|
||||
}
|
||||
now := time.Now()
|
||||
if err := s.saveConnection("linkedin", Connection{Account: urn, At: now, Expires: now.Add(life)}); err != nil {
|
||||
s.Log.Error("saving connection", "err", err)
|
||||
name := "LinkedIn member"
|
||||
if v.User != nil {
|
||||
name = v.User.Name
|
||||
if name == "" {
|
||||
name = v.User.Email
|
||||
}
|
||||
}
|
||||
redirect(w, r, "/settings/accounts", "li-connected")
|
||||
if err := saveAccount(posting.LinkedIn, name, urn, res.AccessToken, "", time.Now().Add(life)); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, back, ownMsg("li-connected"))
|
||||
case liPageProvider:
|
||||
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInPageClientID), s.Secrets.Get(secrets.LinkedInPageClientSecret), code, p)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.setSecrets(r, map[string]string{secrets.LinkedInPageAccessToken: res.AccessToken}); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
life := res.ExpiresIn
|
||||
if life <= 0 {
|
||||
life = linkedInTokenLife
|
||||
}
|
||||
now := time.Now()
|
||||
_, listErr := s.pageOrgs(ctx, res.AccessToken)
|
||||
if listErr != nil {
|
||||
s.Log.Warn("linkedin page: couldn't list the pages", "err", listErr)
|
||||
}
|
||||
account := ""
|
||||
name, urn := "the company page", ""
|
||||
if o := s.liPage(); o != nil {
|
||||
account = o.Name
|
||||
name, urn = o.Name, o.URN
|
||||
}
|
||||
if err := s.saveConnection(liPageProvider, Connection{Account: account, At: now, Expires: now.Add(life)}); err != nil {
|
||||
s.Log.Error("saving connection", "err", err)
|
||||
// One page sign-in for the company: a new one replaces it.
|
||||
if old, _ := posting.Company(s.DB, posting.LinkedInPage); old != nil && old.External != urn {
|
||||
_ = posting.Rename(s.DB, old.ID, name, urn)
|
||||
}
|
||||
if err := saveAccount(posting.LinkedInPage, name, urn, res.AccessToken, "", time.Now().Add(life)); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
redirect(w, r, "/settings/accounts", "li-page-connected")
|
||||
case "reddit":
|
||||
@@ -586,16 +644,12 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
fail("Signed in, but couldn't read the Reddit account's name: " + err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.setSecrets(r, map[string]string{secrets.RedditAccessToken: res.AccessToken,
|
||||
secrets.RedditRefreshToken: res.RefreshToken, secrets.RedditUsername: name}); err != nil {
|
||||
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()
|
||||
if err := s.saveConnection("reddit", Connection{Account: name, At: time.Now()}); err != nil {
|
||||
s.Log.Error("saving connection", "err", err)
|
||||
}
|
||||
redirect(w, r, "/settings/accounts", "reddit-connected")
|
||||
redirect(w, r, back, ownMsg("reddit-connected"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
|
||||
@@ -59,22 +59,29 @@ func TestLinkedInPageSettings(t *testing.T) {
|
||||
t.Errorf("bad manual: %s", body)
|
||||
}
|
||||
|
||||
// A LinkedIn draft offers the page, and the choice is saved.
|
||||
// The sign-in is now the company's page account, posting as the page
|
||||
// chosen.
|
||||
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org": {"urn:li:organization:111"}, "default": {"page"}})
|
||||
pa := s.companyPage()
|
||||
if pa == nil || pa.External != "urn:li:organization:111" || pa.Name != "Federated Computer" || s.Secrets.Has(secrets.LinkedInPageAccessToken) {
|
||||
t.Fatalf("page account: %+v", pa)
|
||||
}
|
||||
// A LinkedIn draft offers it, and the choice is saved.
|
||||
if _, err := content.CreateDrafts(s.DB, []content.Draft{{Channel: content.ChannelLinkedIn, Content: "Hello"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ds, _ := content.ListDrafts(s.DB, 1, content.StatusDraft)
|
||||
body = do(h, http.MethodGet, "/posts", nil, nil).Body.String()
|
||||
if !strings.Contains(body, `name="linkedin_as"`) || !strings.Contains(body, `<option value="page" selected>Federated Computer</option>`) {
|
||||
want := `<input type="checkbox" name="accounts" value="` + strconv.FormatInt(pa.ID, 10) + `" checked> LinkedIn page Federated Computer`
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("posts: %s", body)
|
||||
}
|
||||
postForm(h, "/drafts/"+strconv.FormatInt(ds[0].ID, 10)+"/save", url.Values{"content": {"Hello"}, "linkedin_as": {""}})
|
||||
if dr, _ := content.GetDraft(s.DB, ds[0].ID); dr.LinkedInAs != "" {
|
||||
t.Errorf("switched: %q", dr.LinkedInAs)
|
||||
postForm(h, "/drafts/"+strconv.FormatInt(ds[0].ID, 10)+"/save", url.Values{"content": {"Hello"}, "accounts": {strconv.FormatInt(pa.ID, 10)}})
|
||||
if dr, _ := content.GetDraft(s.DB, ds[0].ID); dr.AccountID != pa.ID {
|
||||
t.Errorf("chosen: %d", dr.AccountID)
|
||||
}
|
||||
// The page counts as LinkedIn being connected, even without the member sign-in.
|
||||
if !s.connected()[content.ChannelLinkedIn] {
|
||||
if !s.connected(localOwner)[content.ChannelLinkedIn] {
|
||||
t.Error("LinkedIn not connected with only the page")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,3 +517,11 @@ fieldset.access .access-grid label { margin: 0; }
|
||||
fieldset.readonly { border: 0; padding: 0; margin: 0; min-width: 0; }
|
||||
fieldset.readonly button, fieldset.readonly input[type="submit"], fieldset.readonly input[type="file"] { display: none; }
|
||||
fieldset.readonly input, fieldset.readonly textarea, fieldset.readonly select { background: hsl(var(--muted)); color: hsl(var(--foreground)); }
|
||||
.table-scroll { overflow-x: auto; }
|
||||
table.grid td, table.grid th { text-align: center; }
|
||||
table.grid td:first-child, table.grid th:first-child { text-align: left; }
|
||||
ul.accounts { list-style: none; padding: 0; margin: 0 0 0.75rem; }
|
||||
ul.accounts li { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; padding: 0.3rem 0; border-bottom: 1px solid hsl(var(--border)); }
|
||||
ul.accounts form.inline { margin: 0 0 0 auto; }
|
||||
fieldset.post-as { border: 0; padding: 0; margin: 0.5rem 0; }
|
||||
fieldset.post-as label { display: inline-flex; margin-right: 1rem; }
|
||||
|
||||
@@ -72,6 +72,20 @@
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
{{if or .Posting .Connectable}}
|
||||
<section class="card" id="posting">
|
||||
<h2>Your posting accounts</h2>
|
||||
<p class="help">Your own social accounts, to post as yourself. They're yours to post to; an admin can let others too. Signing one out takes it out of everyone's list, and posts scheduled to it come back to Posts.</p>
|
||||
{{if .Posting}}<ul class="accounts">{{range .Posting}}
|
||||
<li><strong>{{.Label}}</strong>{{if not .Expires.IsZero}} <span class="muted small">until {{.Expires.Local.Format "2 Jan 2006"}}</span>{{end}}
|
||||
<form class="inline" method="post" action="/settings/account/posting/{{.ID}}/remove"><button type="submit" class="secondary small">Sign out</button></form></li>
|
||||
{{end}}</ul>{{end}}
|
||||
<div class="actions">{{range .Connectable}}
|
||||
<form class="inline" method="post" action="/auth/{{.ID}}/start?for=me"><button type="submit" class="secondary">Connect your {{.Name}}</button></form>
|
||||
{{end}}</div>
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<section class="card" id="sessions">
|
||||
<h2>Where you're signed in</h2>
|
||||
<table class="list">
|
||||
|
||||
@@ -32,7 +32,11 @@
|
||||
{{with .Connect}}
|
||||
<div class="signin">
|
||||
<h3>Sign in to post</h3>
|
||||
{{if .Signed}}<p>Connected{{with .Account}} as <strong>{{.}}</strong>{{end}}{{if not .At.IsZero}}, {{ago .At}}{{end}}.</p>{{end}}
|
||||
{{if .Accounts}}<ul class="accounts">{{range .Accounts}}
|
||||
<li><strong>{{.Name}}</strong> <span class="muted small">{{if eq .Owner 0}}the company's{{else}}someone's own{{end}}, since {{.Created.Local.Format "2 Jan 2006"}}{{if not .Expires.IsZero}}, until {{.Expires.Local.Format "2 Jan 2006"}}{{end}}</span>
|
||||
<form class="inline" method="post" action="/settings/posting/{{.ID}}/remove" data-confirm="Sign {{.Name}} out? Posts scheduled to it go back to Posts."><button type="submit" class="secondary small">Sign out</button></form></li>
|
||||
{{end}}</ul>
|
||||
<p class="help">Who may post to each: <a href="/settings/posting">Settings → Posting accounts</a>.</p>{{end}}
|
||||
{{with .Expiry}}
|
||||
{{if .Expired}}<p class="error">The sign-in expired on {{.At.Local.Format "2 Jan 2006"}}: reconnect to publish again.</p>
|
||||
{{else if .Soon}}<p class="warn-text"><strong>The sign-in expires {{if eq .Days 0}}today{{else if eq .Days 1}}tomorrow{{else}}in {{.Days}} days{{end}}, on {{.At.Local.Format "2 Jan 2006"}}.</strong> Reconnect now to keep posting.</p>
|
||||
@@ -40,7 +44,7 @@
|
||||
{{end}}
|
||||
<p class="help">{{.Setup}} <code>{{.Redirect}}</code>{{with .Note}}<br>{{.}}{{end}}</p>
|
||||
<form method="post" action="/auth/{{.Provider}}/start">
|
||||
<button type="submit" {{if not .Ready}}disabled title="Save the client ID{{if ne .Provider "x"}} and secret{{end}} first"{{end}}>{{if .Signed}}Reconnect{{else}}Connect{{end}} {{$name}}</button>
|
||||
<button type="submit" {{if not .Ready}}disabled title="Save the client ID{{if ne .Provider "x"}} and secret{{end}} first"{{end}}>{{if .Signed}}Add or reconnect a company account{{else}}Connect {{$name}}{{end}}</button>
|
||||
</form>
|
||||
</div>
|
||||
{{with .Page}}{{$pg := .}}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
{{range .Drafts}}
|
||||
<tr>
|
||||
<td>{{.PublishedAt.Local.Format "2 Jan 2006 15:04"}}</td>
|
||||
<td>{{.Where}}</td>
|
||||
<td>{{.Where}}{{with .PostedAs}}<br><span class="muted small">as {{.}}</span>{{end}}</td>
|
||||
<td>{{.InventoryName}}</td>
|
||||
<td class="post-text">{{if .PostURL}}<a href="{{.PostURL}}" target="_blank" rel="noopener noreferrer">{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}</a>{{else}}{{if .Title}}<strong>{{.Title}}</strong> {{end}}{{truncate 200 .Content}}{{end}}</td>
|
||||
</tr>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$page := .Page}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
|
||||
{{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.
|
||||
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
|
||||
@@ -43,11 +43,13 @@
|
||||
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 and (eq .Channel "linkedin") $page}}
|
||||
<label class="small inline-label">Post as
|
||||
<select name="linkedin_as"><option value="">You</option><option value="page" {{if eq .LinkedInAs "page"}}selected{{end}}>{{$page.Name}}</option></select>
|
||||
</label>
|
||||
{{else if eq .LinkedInAs "page"}}<p class="warn-text small">This draft posts as the company page, which isn't connected: set it up under <a href="/settings/accounts">Settings → Social accounts</a>.</p>{{end}}
|
||||
{{$d := .}}{{$accts := index $accounts .Channel}}
|
||||
{{if $accts}}
|
||||
<fieldset class="post-as">
|
||||
<legend class="small">Post as{{if gt (len $accts) 1}} <span class="muted">(choose several to post a copy to each)</span>{{end}}</legend>
|
||||
{{range $accts}}<label class="check small"><input type="checkbox" name="accounts" value="{{.ID}}" {{if eq (index $chosen $d.ID) .ID}}checked{{end}}> {{.Label}}</label>{{end}}
|
||||
</fieldset>
|
||||
{{end}}
|
||||
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}</p>
|
||||
<div class="actions">
|
||||
<button type="submit" name="action" value="publish" formaction="/drafts/{{.ID}}/publish"
|
||||
|
||||
@@ -146,6 +146,7 @@
|
||||
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
|
||||
<div class="nav-label">Connections</div>
|
||||
<a href="/settings/connections" {{if eq .Nav "settings/connections"}}aria-current="page"{{end}}>{{template "icon" "core"}}All connections</a>
|
||||
<a href="/settings/posting" {{if eq .Nav "settings/posting"}}aria-current="page"{{end}}>{{template "icon" "accounts"}}Posting accounts</a>
|
||||
<a href="/settings/accounts" {{if eq .Nav "settings/accounts"}}aria-current="page"{{end}}>{{template "icon" "accounts"}}Social accounts</a>
|
||||
<a href="/settings/core" {{if eq .Nav "settings/core"}}aria-current="page"{{end}}>{{template "icon" "core"}}Core & Hermes</a>
|
||||
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
|
||||
@@ -172,7 +173,7 @@
|
||||
<section class="card warn reminder" role="status">
|
||||
<p><strong>{{if .Expired}}{{.Network}}'s sign-in expired on {{.At.Local.Format "2 Jan 2006"}}.{{else}}{{.Network}}'s sign-in expires {{if eq .Days 0}}today{{else if eq .Days 1}}tomorrow{{else}}in {{.Days}} days{{end}}, on {{.At.Local.Format "2 Jan 2006"}}.{{end}}</strong>
|
||||
{{if .Expired}}Nothing can be published to {{.Network}} until you reconnect; scheduled posts for it come back to Posts.{{else}}After that, nothing can be published to {{.Network}} until you reconnect.{{end}}</p>
|
||||
<a class="button" href="/settings/accounts#network-{{.Network}}">Reconnect {{.Network}}</a>
|
||||
<a class="button" href="/settings/accounts">Reconnect {{.Network}}</a>
|
||||
</section>
|
||||
{{end}}{{end}}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
|
||||
<h2>Posting accounts</h2>
|
||||
<p class="lede">The accounts posts go out from, and who may post to each. Admins may post to all of them; a person's own account is theirs. Tick to let someone else post to an account: the post records who wrote it and which account it went out as.</p>
|
||||
{{if not .Accounts}}
|
||||
<section class="card empty"><p>No posting accounts yet. Connect the company's under <a href="/settings/accounts">Social accounts</a>; each person can connect their own under Your account.</p></section>
|
||||
{{else}}
|
||||
<form class="card" method="post" action="/settings/posting">
|
||||
<div class="table-scroll">
|
||||
<table class="list grid">
|
||||
<thead><tr><th>Person</th>{{range .Accounts}}<th>{{.Label}}<br><span class="muted small">{{if eq .Owner 0}}the company's{{else}}{{index $d.Owners .Owner}}'s own{{end}}{{if not (index $d.Working .ID)}} · not working{{end}}</span></th>{{end}}</tr></thead>
|
||||
<tbody>
|
||||
{{range $p := .People}}<tr>
|
||||
<td>{{if .Name}}{{.Name}}{{else}}{{.Email}}{{end}}<br><span class="muted small">{{if .Admin}}admin{{else if .Can "content" true}}member{{else}}no Content: can't post{{end}}</span></td>
|
||||
{{range $a := $d.Accounts}}<td>
|
||||
{{if $p.Admin}}<input type="checkbox" checked disabled title="Admins may post to every account">
|
||||
{{else if eq $a.Owner $p.ID}}<input type="checkbox" checked disabled title="Their own account">
|
||||
{{else}}<input type="checkbox" name="grant" value="{{$a.ID}}:{{$p.ID}}" {{with index $d.Grants $a.ID}}{{if index . $p.ID}}checked{{end}}{{end}} aria-label="{{$p.Email}} may post to {{$a.Label}}">{{end}}
|
||||
</td>{{end}}
|
||||
</tr>{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="help">Members also need edit on Content to post at all.</p>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
{{end}}
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
+13
-1
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"supermarket/internal/appmail"
|
||||
"supermarket/internal/posting"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
@@ -440,7 +441,18 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
case "remove":
|
||||
if err = turnOffTwoFactor(s, u); err == nil {
|
||||
err = turnOffTwoFactor(s, u)
|
||||
if own, lerr := posting.OwnedBy(s.DB, u.ID); err == nil && lerr == nil {
|
||||
for _, a := range own {
|
||||
if err = s.removeAccount(a, "was signed out: its owner left the team"); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = posting.ForgetUser(s.DB, u.ID)
|
||||
}
|
||||
if err == nil {
|
||||
err = users.Delete(s.DB, u.ID)
|
||||
}
|
||||
if err == nil {
|
||||
|
||||
Reference in New Issue
Block a user