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:
2026-11-25 09:26:34 -07:00
co-authored by Claude Opus 5.5
parent a4dd36f5a4
commit bb4772637c
31 changed files with 1758 additions and 325 deletions
+322
View File
@@ -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, ", ")
}