Phase 6 part 4: post as the LinkedIn company page

A second LinkedIn app (Community Management API) with its own sign-in on
Settings → Social accounts: the pages the member may post for are listed
and one chosen, new LinkedIn drafts default to the page or to you, and
each draft can switch before it's published. Schema 25.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:05:30 -07:00
co-authored by Claude Opus 5.5
parent 2c42857419
commit 98913971ea
20 changed files with 841 additions and 74 deletions
+23
View File
@@ -1455,6 +1455,29 @@ Tested with Node running the script on a form's data. Not done for real:
creating the Lead Capture in EspoCRM, and the pull request on the real creating the Lead Capture in EspoCRM, and the pull request on the real
site. site.
**Part 4 built (2026-11-22; schema 25: `drafts.linkedin_as`).** From
LinkedIn's docs (Microsoft Learn, community-management): posting as a page
is the same `POST /rest/posts` with `author: urn:li:organization:<id>` and
`w_organization_social`, for members with an approved ADMINISTRATOR,
CONTENT_ADMIN(ISTRATOR) or DIRECT_SPONSORED_CONTENT_POSTER role;
`GET /rest/organizationAcls?q=roleAssignee&state=APPROVED` lists the
member's roles (the docs name the field `organizationTarget` or
`organization`: both are read), and `GET
/rest/organizationsLookup?ids=List(…)` names the pages without needing
admin. The docs don't say which scope the role list needs.
- Settings → Social accounts has a **LinkedIn page** card: the second app's
client ID and secret, its own sign-in (`/auth/linkedin-page/…`, its own
redirect URL), the scopes it asks for (default `w_organization_social
r_organization_admin`, editable to match the approved app), the pages
listed after sign-in to choose from (or a page number typed in, from its
admin address, when they can't be listed), and whether new LinkedIn
drafts default to the page. The only page is chosen automatically. Its
60-day expiry is reminded like LinkedIn's.
- Each LinkedIn draft in Posts has *Post as: You / <the page>*; the
publisher posts with the page's token and URN, or the member's, and says
which sign-in is missing or expired.
Not tried for real: it waits on LinkedIn approving the page app.
### Future enhancements ### Future enhancements
Not in any phase yet; picked up when the user asks. Not in any phase yet; picked up when the user asks.
+17
View File
@@ -62,6 +62,23 @@ Throughout, also notice:
- [ ] LinkedIn shows when its 60-day sign-in runs out. - [ ] LinkedIn shows when its 60-day sign-in runs out.
- [ ] Removing a key (the *remove* box, then Save) removes it. - [ ] Removing a key (the *remove* box, then Save) removes it.
### LinkedIn page
- [ ] Settings → Social accounts has a *LinkedIn page* card with its own
redirect URL (…/auth/linkedin-page/callback).
- [ ] Once LinkedIn approves the page app (Community Management API), save
its client ID and secret and *Connect LinkedIn page*: the pages you
administer are listed (the only one is chosen).
- [ ] If they aren't listed (a permission missing), type the page's number
from linkedin.com/company/<number>/admin and save.
- [ ] Choose "New LinkedIn drafts post as: The company page": new LinkedIn
drafts in Posts show *Post as: <the page>*; switch one to *You* and
save.
- [ ] Publish a draft as the page: it appears on the company page, not your
profile; one as you still goes to your profile.
- [ ] Two weeks before the page sign-in expires, the Overview and Posts
remind you.
### Core & Hermes ### Core & Hermes
- [ ] It shows your Core's domain, email and name from `core.conf`. - [ ] It shows your Core's domain, email and name from `core.conf`.
+112
View File
@@ -198,3 +198,115 @@ func fallbackTitle(u string) string {
} }
return u return u
} }
// --- Company pages (the Community Management API) ---
// Org is a LinkedIn company page the signed-in member may post for.
type Org struct {
URN string `json:"urn"` // urn:li:organization:<id>
ID string `json:"id"`
Name string `json:"name"`
Vanity string `json:"vanity"` // linkedin.com/company/<vanity>
Role string `json:"role"`
}
// postingRoles may post on a page's behalf (w_organization_social). The
// docs name the content role both ways.
var postingRoles = map[string]bool{"ADMINISTRATOR": true, "CONTENT_ADMIN": true, "CONTENT_ADMINISTRATOR": true,
"DIRECT_SPONSORED_CONTENT_POSTER": true}
// get sends a versioned REST GET, stepping back a version on 426 as
// PostUpdate does, and decodes the JSON answer.
func (c *Client) get(ctx context.Context, path string, out any) error {
var (
res *http.Response
raw []byte
)
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+path, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("LinkedIn-Version", version(c.now(), versionLag+attempt))
req.Header.Set("X-Restli-Protocol-Version", "2.0.0")
res, err = c.http.Do(req)
if err != nil {
return err
}
raw, _ = io.ReadAll(io.LimitReader(res.Body, 4<<20))
res.Body.Close()
if res.StatusCode == http.StatusUpgradeRequired && attempt+1 < versionAttempts {
continue
}
break
}
switch {
case res.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case res.StatusCode == http.StatusForbidden:
return fmt.Errorf("LinkedIn refused (403): the app may lack the permission for this (%s)", strings.TrimSpace(string(raw[:min(len(raw), 300)])))
case res.StatusCode != http.StatusOK:
return fmt.Errorf("linkedin HTTP %d: %s", res.StatusCode, raw[:min(len(raw), 300)])
}
return json.Unmarshal(raw, out)
}
// Organizations lists the company pages the member has an approved role on
// that may post (administrator, content admin, sponsored content poster),
// with their names.
func (c *Client) Organizations(ctx context.Context) ([]Org, error) {
var acls struct {
Elements []struct {
Role string `json:"role"`
State string `json:"state"`
Organization string `json:"organization"`
OrganizationTarget string `json:"organizationTarget"`
} `json:"elements"`
}
if err := c.get(ctx, "/rest/organizationAcls?q=roleAssignee&state=APPROVED&count=100", &acls); err != nil {
return nil, err
}
var orgs []Org
seen := map[string]bool{}
for _, e := range acls.Elements {
urn := e.OrganizationTarget
if urn == "" {
urn = e.Organization
}
id := strings.TrimPrefix(urn, "urn:li:organization:")
if id == urn || id == "" || e.State != "APPROVED" || !postingRoles[e.Role] || seen[id] {
continue
}
seen[id] = true
orgs = append(orgs, Org{URN: urn, ID: id, Role: e.Role})
}
if len(orgs) == 0 {
return nil, nil
}
ids := make([]string, len(orgs))
for i, o := range orgs {
ids[i] = o.ID
}
var look struct {
Results map[string]struct {
LocalizedName string `json:"localizedName"`
VanityName string `json:"vanityName"`
} `json:"results"`
}
// organizationsLookup doesn't need the administrator role; a page
// whose name can't be read is still listed, by its ID.
if err := c.get(ctx, "/rest/organizationsLookup?ids=List("+strings.Join(ids, ",")+")", &look); err == nil {
for i := range orgs {
if r, ok := look.Results[orgs[i].ID]; ok {
orgs[i].Name, orgs[i].Vanity = r.LocalizedName, r.VanityName
}
}
}
for i := range orgs {
if orgs[i].Name == "" {
orgs[i].Name = "Page " + orgs[i].ID
}
}
return orgs, nil
}
+69
View File
@@ -100,3 +100,72 @@ func TestPostSendsTheArticleTitle(t *testing.T) {
t.Error("a post without a link has no content") t.Error("a post without a link has no content")
} }
} }
func TestOrganizations(t *testing.T) {
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.RequestURI())
if r.Header.Get("Authorization") != "Bearer page-tok" || r.Header.Get("X-Restli-Protocol-Version") != "2.0.0" || r.Header.Get("LinkedIn-Version") == "" {
t.Errorf("headers: %v", r.Header)
}
switch r.URL.Path {
case "/rest/organizationAcls":
w.Write([]byte(`{"elements":[
{"role":"ADMINISTRATOR","state":"APPROVED","organizationTarget":"urn:li:organization:111"},
{"role":"CONTENT_ADMIN","state":"APPROVED","organization":"urn:li:organization:222"},
{"role":"ANALYST","state":"APPROVED","organizationTarget":"urn:li:organization:333"},
{"role":"ADMINISTRATOR","state":"REQUESTED","organizationTarget":"urn:li:organization:444"},
{"role":"DIRECT_SPONSORED_CONTENT_POSTER","state":"APPROVED","organizationTarget":"urn:li:organization:111"}]}`))
case "/rest/organizationsLookup":
w.Write([]byte(`{"results":{"111":{"localizedName":"Federated Computer","vanityName":"federated-computer"}},"statuses":{"111":200,"222":404}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
orgs, err := New("page-tok", "").Organizations(context.Background())
if err != nil {
t.Fatal(err)
}
if len(orgs) != 2 || orgs[0].URN != "urn:li:organization:111" || orgs[0].Name != "Federated Computer" || orgs[0].Vanity != "federated-computer" ||
orgs[0].Role != "ADMINISTRATOR" || orgs[1].ID != "222" || orgs[1].Name != "Page 222" {
t.Errorf("orgs: %+v", orgs)
}
if !strings.Contains(paths[0], "q=roleAssignee") || !strings.Contains(paths[0], "state=APPROVED") || paths[1] != "/rest/organizationsLookup?ids=List(111,222)" {
t.Errorf("paths: %v", paths)
}
}
func TestOrganizationsRefused(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"message":"Not enough permissions to access: organizationAcls"}`))
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
if _, err := New("t", "").Organizations(context.Background()); err == nil || !strings.Contains(err.Error(), "may lack the permission") {
t.Errorf("err: %v", err)
}
}
func TestPostAsAPage(t *testing.T) {
var body map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("X-RestLi-Id", "urn:li:share:9")
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
u, err := New("t", "urn:li:organization:111").PostUpdate(context.Background(), "Hello", nil)
if err != nil || u != "https://www.linkedin.com/feed/update/urn:li:share:9/" || body["author"] != "urn:li:organization:111" {
t.Errorf("%s %v %v", u, err, body)
}
}
+60
View File
@@ -82,9 +82,11 @@ func TestItems(t *testing.T) {
type fakePub struct { type fakePub struct {
calls []string calls []string
err error err error
got Post // the last post
} }
func (f *fakePub) Publish(_ context.Context, p Post) (string, error) { func (f *fakePub) Publish(_ context.Context, p Post) (string, error) {
f.got = p
call := p.Text + "|" + p.SourceURL call := p.Text + "|" + p.SourceURL
if p.Target != "" { if p.Target != "" {
call = "r/" + p.Target + "|" + p.Title + "|" + call call = "r/" + p.Target + "|" + p.Title + "|" + call
@@ -366,3 +368,61 @@ func TestDraftsForSignal(t *testing.T) {
t.Errorf("prompt lacks the signal: %s", prompt) t.Errorf("prompt lacks the signal: %s", prompt)
} }
} }
func TestLinkedInAuthor(t *testing.T) {
d := openDB(t)
ctx := context.Background()
mk := func() (li, x Draft) {
if _, err := CreateDrafts(d, []Draft{{Channel: ChannelLinkedIn, Content: "Hello LinkedIn"}, {Channel: ChannelX, Content: "Hello X"}}); err != nil {
t.Fatal(err)
}
ds, _ := ListDrafts(d, 2, StatusDraft)
for _, dr := range ds {
if dr.Channel == ChannelLinkedIn {
li = dr
} else {
x = dr
}
}
return
}
li, x := mk()
if li.LinkedInAs != "" || x.LinkedInAs != "" {
t.Errorf("default: %q %q", li.LinkedInAs, x.LinkedInAs)
}
// With the page as the default, new LinkedIn drafts post as it; X's don't change.
d.PutJSON(LinkedInDefaultKey, AsPage)
DiscardDraft(d, li.ID)
DiscardDraft(d, x.ID)
li, x = mk()
if li.LinkedInAs != AsPage || x.LinkedInAs != "" {
t.Errorf("page default: %q %q", li.LinkedInAs, x.LinkedInAs)
}
if err := SetLinkedInAs(d, x.ID, AsPage); err == nil {
t.Error("an X draft took a LinkedIn author")
}
if err := SetLinkedInAs(d, li.ID, "someone"); err == nil {
t.Error("an unknown author was taken")
}
pub := &fakePub{}
if _, err := Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
t.Fatal(err)
}
if !pub.got.AsPage {
t.Errorf("published as: %+v", pub.got)
}
// Switched back to you before publishing.
_, _ = mk()
ds, _ := ListDrafts(d, 5, StatusDraft)
for _, dr := range ds {
if dr.Channel == ChannelLinkedIn {
if err := SetLinkedInAs(d, dr.ID, ""); err != nil {
t.Fatal(err)
}
Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, dr.ID)
}
}
if pub.got.AsPage {
t.Error("published as the page after switching")
}
}
+36 -5
View File
@@ -80,8 +80,16 @@ type Draft struct {
PublishAt time.Time // when a scheduled draft goes out PublishAt time.Time // when a scheduled draft goes out
SignalID int64 // the buying signal it was written for; 0: none SignalID int64 // the buying signal it was written for; 0: none
SignalSlug string // that signal's campaign tag SignalSlug string // that signal's campaign tag
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page
} }
// AsPage is the LinkedIn author choice for the company page.
const AsPage = "page"
// LinkedInDefaultKey is the setting saying whether new LinkedIn drafts
// post as the company page ("page") or as you ("").
const LinkedInDefaultKey = "linkedin:post-as"
// Length is the draft's length as its channel counts it, including the // Length is the draft's length as its channel counts it, including the
// source link on X. // source link on X.
func (d *Draft) Length() int { func (d *Draft) Length() int {
@@ -157,6 +165,11 @@ func newBatchID() string {
// their items as used. // their items as used.
func CreateDrafts(d *db.DB, drafts []Draft) (string, error) { func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
batch := newBatchID() batch := newBatchID()
// Read before the transaction: it holds the database's one connection.
var liDefault string
if _, err := d.GetJSON(LinkedInDefaultKey, &liDefault); err != nil {
return "", err
}
tx, err := d.Begin() tx, err := d.Begin()
if err != nil { if err != nil {
return "", err return "", err
@@ -173,9 +186,16 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
if dr.SignalID != 0 { if dr.SignalID != 0 {
sig = dr.SignalID sig = dr.SignalID
} }
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id) as := dr.LinkedInAs
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel, if dr.Channel == ChannelLinkedIn && as == "" {
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig); err != nil { as = liDefault
}
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 {
return "", err return "", err
} }
for _, id := range dr.ItemIDs { for _, id := range dr.ItemIDs {
@@ -200,7 +220,7 @@ func nonNil(s []string) []string {
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error, 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, 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), '')` COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as`
func scanDrafts(rows *sql.Rows) ([]Draft, error) { func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close() defer rows.Close()
@@ -210,7 +230,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
var ids, created, updated, published, publishAt string var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content, 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.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target,
&dr.SignalID, &dr.SignalSlug); err != nil { &dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs); err != nil {
return nil, err return nil, err
} }
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs) _ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
@@ -279,6 +299,17 @@ func UpdateDraft(d *db.DB, id int64, text string) error {
return oneRow(res, err) return oneRow(res, err)
} }
// SetLinkedInAs chooses who a LinkedIn draft posts as: "" for you,
// AsPage for the company page.
func SetLinkedInAs(d *db.DB, id int64, as string) error {
if as != "" && as != AsPage {
return fmt.Errorf("unknown author %q", as)
}
res, err := d.Exec(`UPDATE drafts SET linkedin_as = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?, ?)`,
as, formatTime(time.Now()), id, ChannelLinkedIn, StatusDraft, StatusFailed, StatusScheduled)
return oneRow(res, err)
}
// DiscardDraft drops a draft without publishing it. // DiscardDraft drops a draft without publishing it.
func DiscardDraft(d *db.DB, id int64) error { func DiscardDraft(d *db.DB, id int64) error {
res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`, res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`,
+3 -1
View File
@@ -16,6 +16,7 @@ type Post struct {
SourceURL string // tagged, if it's the company's SourceURL string // tagged, if it's the company's
Title string // Reddit Title string // Reddit
Target string // Reddit: the subreddit Target string // Reddit: the subreddit
AsPage bool // LinkedIn: post as the company page
} }
// Publisher posts to one channel and returns the post's URL. // Publisher posts to one channel and returns the post's URL.
@@ -61,7 +62,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
} }
text, src := Manual(dr, tags) text, src := Manual(dr, tags)
postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target}) postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target,
AsPage: dr.Channel == ChannelLinkedIn && dr.LinkedInAs == AsPage})
now := formatTime(time.Now()) now := formatTime(time.Now())
if pubErr != nil { if pubErr != nil {
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`, if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`,
+4
View File
@@ -609,6 +609,10 @@ ALTER TABLE site_pages ADD COLUMN live_at TEXT;
ALTER TABLE site_pages ADD COLUMN gone_at TEXT; ALTER TABLE site_pages ADD COLUMN gone_at TEXT;
ALTER TABLE site_pages ADD COLUMN checked_at TEXT; ALTER TABLE site_pages ADD COLUMN checked_at TEXT;
ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT ''; ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT '';
`,
// 25: a LinkedIn draft posts as the member ('') or the company page ('page').
`
ALTER TABLE drafts ADD COLUMN linkedin_as TEXT NOT NULL DEFAULT '';
`, `,
} }
+23
View File
@@ -0,0 +1,23 @@
package oauth
import (
"net/url"
"testing"
)
func TestLinkedInStartScopes(t *testing.T) {
raw, p, err := LinkedInStartScopes("linkedin-page", "cid", "http://localhost:8470/auth/linkedin-page/callback", LinkedInPageScopes)
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(raw)
q := u.Query()
if q.Get("scope") != "w_organization_social r_organization_admin" || q.Get("client_id") != "cid" || q.Get("state") != p.State ||
p.Provider != "linkedin-page" || p.RedirectURI != "http://localhost:8470/auth/linkedin-page/callback" {
t.Errorf("%s %+v", raw, p)
}
raw, p, _ = LinkedInStart("cid", "http://x/cb")
if u, _ := url.Parse(raw); u.Query().Get("scope") != "w_member_social openid profile" || p.Provider != "linkedin" {
t.Errorf("member: %s", raw)
}
}
+13 -2
View File
@@ -113,9 +113,20 @@ const (
linkedInScopes = "w_member_social openid profile" linkedInScopes = "w_member_social openid profile"
) )
// LinkedInPageScopes are asked of the company page's app (the Community
// Management API): posting as the page, and listing the pages the member
// administers. The approved app's Auth tab shows what it may ask for.
const LinkedInPageScopes = "w_organization_social r_organization_admin"
// LinkedInStart begins LinkedIn's authorization-code flow (client secret, // LinkedInStart begins LinkedIn's authorization-code flow (client secret,
// no PKCE). // no PKCE).
func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) { func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) {
return LinkedInStartScopes("linkedin", clientID, redirectURI, linkedInScopes)
}
// LinkedInStartScopes begins it for another LinkedIn app (the company
// page's), with its own provider name and scopes.
func LinkedInStartScopes(provider, clientID, redirectURI, scopes string) (string, *Pending, error) {
state, err := randomString() state, err := randomString()
if err != nil { if err != nil {
return "", nil, err return "", nil, err
@@ -124,10 +135,10 @@ func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) {
"response_type": {"code"}, "response_type": {"code"},
"client_id": {clientID}, "client_id": {clientID},
"redirect_uri": {redirectURI}, "redirect_uri": {redirectURI},
"scope": {linkedInScopes}, "scope": {scopes},
"state": {state}, "state": {state},
} }
p := &Pending{Provider: "linkedin", State: state, RedirectURI: redirectURI, Started: time.Now()} p := &Pending{Provider: provider, State: state, RedirectURI: redirectURI, Started: time.Now()}
return linkedInAuthURL + "?" + params.Encode(), p, nil return linkedInAuthURL + "?" + params.Encode(), p, nil
} }
+4
View File
@@ -29,6 +29,10 @@ const (
LinkedInClientSecret = "linkedin.client_secret" LinkedInClientSecret = "linkedin.client_secret"
LinkedInAccessToken = "linkedin.access_token" LinkedInAccessToken = "linkedin.access_token"
LinkedInAuthorURN = "linkedin.author_urn" LinkedInAuthorURN = "linkedin.author_urn"
// The company page's own LinkedIn app (Community Management API)
LinkedInPageClientID = "linkedin_page.client_id"
LinkedInPageClientSecret = "linkedin_page.client_secret"
LinkedInPageAccessToken = "linkedin_page.access_token"
YouTubeAPIKey = "youtube.api_key" YouTubeAPIKey = "youtube.api_key"
+33 -7
View File
@@ -62,13 +62,24 @@ func (s *Server) publishers() content.Publishers {
} }
pubs[content.ChannelX] = xPublisher{c} pubs[content.ChannelX] = xPublisher{c}
} }
var li linkedInPublisher
if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" { if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" {
if e := s.linkedInExpiry(); e != nil && e.Expired() { if e := s.linkedInExpiry(); e != nil && e.Expired() {
pubs[content.ChannelLinkedIn] = expiredPublisher{*e} li.meErr = expiredPublisher{*e}.err()
} else { } else {
pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)} 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 { if c := s.redditUser(); c != nil {
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c} pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
} }
@@ -80,7 +91,11 @@ func (s *Server) publishers() content.Publishers {
type expiredPublisher struct{ e Expiry } type expiredPublisher struct{ e Expiry }
func (p expiredPublisher) Publish(context.Context, content.Post) (string, error) { func (p expiredPublisher) Publish(context.Context, content.Post) (string, error) {
return "", fmt.Errorf("%s's sign-in expired on %s: reconnect %s under Settings → Social accounts, then publish again", return "", p.err()
}
func (p expiredPublisher) err() error {
return fmt.Errorf("%s's sign-in expired on %s: reconnect %s under Settings → Social accounts, then publish again",
p.e.Network, p.e.At.Local().Format("2 Jan 2006"), p.e.Network) p.e.Network, p.e.At.Local().Format("2 Jan 2006"), p.e.Network)
} }
@@ -96,12 +111,23 @@ func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, err
return p.c.PostTweet(ctx, text) return p.c.PostTweet(ctx, text)
} }
type linkedInPublisher struct{ c *linkedin.Client }
// Publish attaches the source link as an article preview. // Publish attaches the source link as an article preview.
func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) { func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
c := p.me
switch {
case post.AsPage && p.pageErr != nil:
return "", p.pageErr
case post.AsPage && p.page == nil:
return "", errNoPage
case post.AsPage:
c = p.page
case p.meErr != nil:
return "", p.meErr
case p.me == nil:
return "", errNoMe
}
if post.SourceURL == "" { if post.SourceURL == "" {
return p.c.PostUpdate(ctx, post.Text, nil) return c.PostUpdate(ctx, post.Text, nil)
} }
// LinkedIn wants the card's title from us. A page that can't be read // LinkedIn wants the card's title from us. A page that can't be read
// still gets a card, titled with its address. // still gets a card, titled with its address.
@@ -109,7 +135,7 @@ func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (stri
ictx, cancel := context.WithTimeout(ctx, 10*time.Second) ictx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel() defer cancel()
link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)") link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)")
return p.c.PostUpdate(ctx, post.Text, link) return c.PostUpdate(ctx, post.Text, link)
} }
type redditPublisher struct { type redditPublisher struct {
+13 -2
View File
@@ -74,9 +74,13 @@ func groupBatches(drafts []content.Draft) []*draftBatch {
func (s *Server) connected() map[string]bool { func (s *Server) connected() map[string]bool {
out := map[string]bool{} out := map[string]bool{}
for id, p := range s.publishers() { for id, p := range s.publishers() {
if _, expired := p.(expiredPublisher); !expired { if _, expired := p.(expiredPublisher); expired {
out[id] = true continue
} }
if li, ok := p.(linkedInPublisher); ok && li.me == nil && li.page == nil {
continue // only expired sign-ins
}
out[id] = true
} }
return out return out
} }
@@ -100,6 +104,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
"Sections": sections, "Sections": sections,
"Reddit": s.redditViews(r.Context(), pending), "Reddit": s.redditViews(r.Context(), pending),
"Connected": s.connected(), "Connected": s.connected(),
"Page": s.liPageIfSignedIn(),
"Tagged": s.tagger() != nil, "Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal), "Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
"Zone": time.Now().Format("MST"), "Zone": time.Now().Format("MST"),
@@ -246,6 +251,12 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
return return
} }
} }
if as, sent := r.PostForm["linkedin_as"]; sent {
if err := content.SetLinkedInAs(s.DB, id, as[0]); err != nil {
fail(err)
return
}
}
} }
switch action { switch action {
case "save": case "save":
+197
View File
@@ -0,0 +1,197 @@
package web
import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/content"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
)
// Posting as the company page needs a second LinkedIn app with the
// Community Management API, which LinkedIn approves by hand; see PLAN.md,
// Future enhancements item 1.
const (
liPageScopesKey = "linkedin-page:scopes"
liPageOrgsKey = "linkedin-page:orgs" // the pages the sign-in may post for
liPageOrgKey = "linkedin-page:org" // the one chosen
liPageNoteKey = "linkedin-page:note" // why the pages couldn't be listed
liPageProvider = "linkedin-page"
liPageNetwork = "LinkedIn page"
)
// pageSetup is the company page's part of its card.
type pageSetup struct {
Orgs []linkedinapi.Org
Chosen *linkedinapi.Org
Default string // content.AsPage or ""
Scopes string
Note string // why listing failed
Signed bool
Approved string // what the user must have from LinkedIn
}
func (s *Server) liPageScopes() string {
var sc string
if _, err := s.DB.GetJSON(liPageScopesKey, &sc); err == nil && strings.TrimSpace(sc) != "" {
return sc
}
return oauth.LinkedInPageScopes
}
// liPage is the chosen company page, or nil.
func (s *Server) liPage() *linkedinapi.Org {
var o linkedinapi.Org
if ok, _ := s.DB.GetJSON(liPageOrgKey, &o); !ok || o.URN == "" {
return nil
}
return &o
}
func (s *Server) pageSetup() *pageSetup {
p := &pageSetup{Scopes: s.liPageScopes(), Signed: s.Secrets.Has(secrets.LinkedInPageAccessToken), Chosen: s.liPage()}
s.DB.GetJSON(liPageOrgsKey, &p.Orgs)
s.DB.GetJSON(liPageNoteKey, &p.Note)
s.DB.GetJSON(content.LinkedInDefaultKey, &p.Default)
return p
}
// 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}
}
// pageOrgs lists the pages the page sign-in may post for, and keeps them.
func (s *Server) pageOrgs(ctx context.Context, token string) ([]linkedinapi.Org, error) {
orgs, err := linkedinapi.New(token, "").Organizations(ctx)
note := ""
if err != nil {
note = err.Error()
} else if len(orgs) == 0 {
note = "LinkedIn lists no page you may post for: you need an approved administrator or content admin role on the company page."
}
_ = s.DB.PutJSON(liPageNoteKey, note)
if err != nil {
return nil, err
}
if err := s.DB.PutJSON(liPageOrgsKey, orgs); err != nil {
return nil, err
}
// The only page, or the chosen one gone: choose for the user.
cur := s.liPage()
still := false
for _, o := range orgs {
if cur != nil && o.URN == cur.URN {
still = true
}
}
if len(orgs) == 1 && !still {
_ = s.DB.PutJSON(liPageOrgKey, orgs[0])
}
return orgs, nil
}
var orgID = regexp.MustCompile(`(?:urn:li:organization:|linkedin\.com/company/)?(\d{3,})\b`)
// linkedInPageSave saves the page's settings: which page, what new
// LinkedIn drafts default to, and the scopes the sign-in asks for.
func (s *Server) linkedInPageSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch r.PostFormValue("do") {
case "refresh":
tok := s.Secrets.Get(secrets.LinkedInPageAccessToken)
if tok == "" {
redirect(w, r, "/settings/accounts", "")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
_, _ = s.pageOrgs(ctx, tok)
redirect(w, r, "/settings/accounts", "saved")
return
}
if sc := strings.Join(strings.Fields(r.PostFormValue("scopes")), " "); sc != "" {
if err := s.DB.PutJSON(liPageScopesKey, sc); err != nil {
s.serverError(w, err)
return
}
}
def := ""
if r.PostFormValue("default") == content.AsPage {
def = content.AsPage
}
if err := s.DB.PutJSON(content.LinkedInDefaultKey, def); err != nil {
s.serverError(w, err)
return
}
choice := strings.TrimSpace(r.PostFormValue("org"))
if manual := strings.TrimSpace(r.PostFormValue("org_manual")); manual != "" {
m := orgID.FindStringSubmatch(manual)
if m == nil {
s.render(w, r, "message", page{Title: "LinkedIn page", Nav: "settings/accounts",
Error: "That isn't a company page's number: it's in the page admin view's address, linkedin.com/company/<number>/admin.",
Data: map[string]string{"Back": "/settings/accounts"}})
return
}
o := linkedinapi.Org{URN: "urn:li:organization:" + m[1], ID: m[1], Name: "Page " + m[1]}
if err := s.DB.PutJSON(liPageOrgKey, o); err != nil {
s.serverError(w, err)
return
}
} else if choice != "" {
var orgs []linkedinapi.Org
s.DB.GetJSON(liPageOrgsKey, &orgs)
for _, o := range orgs {
if o.URN == choice {
if err := s.DB.PutJSON(liPageOrgKey, o); err != nil {
s.serverError(w, err)
return
}
}
}
}
redirect(w, r, "/settings/accounts", "saved")
}
// linkedInPublisher posts as you or as the company page, as each draft
// says.
type linkedInPublisher struct {
me *linkedinapi.Client // nil: you aren't signed in
meErr error // why not (an expired sign-in)
page *linkedinapi.Client // nil: no page set up
pageErr error
}
var errNoPage = errors.New("this draft posts as the company page, which isn't set up: connect the LinkedIn page under Settings → Social accounts, or post it as you")
var errNoMe = errors.New("this draft posts as you, but LinkedIn isn't connected: connect it under Settings → Social accounts, or post it as the company page")
// 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) {
return nil
}
return s.liPage()
}
+6 -3
View File
@@ -72,10 +72,13 @@ func (s *Server) linkedInExpiry() *Expiry {
// reminders are the sign-ins running out soon, or already, for the // reminders are the sign-ins running out soon, or already, for the
// Overview and Posts. // Overview and Posts.
func (s *Server) reminders() []Expiry { func (s *Server) reminders() []Expiry {
if e := s.linkedInExpiry(); e != nil && e.Soon() { var out []Expiry
return []Expiry{*e} for _, e := range []*Expiry{s.linkedInExpiry(), s.linkedInPageExpiry()} {
if e != nil && e.Soon() {
out = append(out, *e)
}
} }
return nil return out
} }
const connectionsKey = "connections" const connectionsKey = "connections"
+52 -50
View File
@@ -119,6 +119,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/accounts", s.accountsPage) mux.HandleFunc("GET /settings/accounts", s.accountsPage)
mux.HandleFunc("POST /settings/accounts", s.accountsSave) mux.HandleFunc("POST /settings/accounts", s.accountsSave)
mux.HandleFunc("POST /settings/accounts/linkedin-page", s.linkedInPageSave)
mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart) mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart)
mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback) mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback)
@@ -503,56 +504,57 @@ func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) {
// Messages shown after a redirect, by code, so no user text is reflected. // Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{ var flashes = map[string]string{
"saved": "Saved.", "saved": "Saved.",
"deleted": "Deleted.", "deleted": "Deleted.",
"x-connected": "X is connected.", "x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.", "li-connected": "LinkedIn is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.", "li-page-connected": "The LinkedIn page app is connected.",
"synced": "Synced from Search Console.", "google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"report-written": "This week's report is written.", "synced": "Synced from Search Console.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.", "report-written": "This week's report is written.",
"pinged": "Sent to IndexNow.", "setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.", "pinged": "Sent to IndexNow.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.", "brief-written": "Brief written. Read it, answer its questions, then write the page.",
"keywords-found": "Looked for keywords: the candidates are below.", "page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"top-read": "Read the live top results.", "keywords-found": "Looked for keywords: the candidates are below.",
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.", "top-read": "Read the live top results.",
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.", "proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
"declined": "Declined.", "approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.", "declined": "Declined.",
"no-data": "There isn't two weeks of Search Console data yet.", "auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"reddit-connected": "Reddit is connected.", "no-data": "There isn't two weeks of Search Console data yet.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).", "reddit-connected": "Reddit is connected.",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.", "crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.", "crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"rejected": "Set aside.", "accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
"reconsidered": "Back in New.", "rejected": "Set aside.",
"suppressed": "Added to the suppression list.", "reconsidered": "Back in New.",
"unsuppressed": "Taken off the suppression list.", "suppressed": "Added to the suppression list.",
"prospect-added": "Added. Review it below.", "unsuppressed": "Taken off the suppression list.",
"outcome": "Outcome recorded.", "prospect-added": "Added. Review it below.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.", "outcome": "Outcome recorded.",
"rules-refreshed": "Rules refreshed.", "discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"imported": "Imported.", "rules-refreshed": "Rules refreshed.",
"hunter-done": "Hunter.io search done: the result is on the card.", "imported": "Imported.",
"verified": "Checked with Hunter.io: the result is on each person.", "hunter-done": "Hunter.io search done: the result is on the card.",
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.", "verified": "Checked with Hunter.io: the result is on each person.",
"queued": "Queued: it goes out in turn, within your sending hours.", "drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
"unqueued": "Back in Drafts.", "queued": "Queued: it goes out in turn, within your sending hours.",
"sent": "Sent.", "unqueued": "Back in Drafts.",
"marked-sent": "Marked as sent.", "sent": "Sent.",
"reply-recorded": "Reply recorded.", "marked-sent": "Marked as sent.",
"checked": "Inbox checked: what it found is above.", "reply-recorded": "Reply recorded.",
"test-sent": "Test email sent: check your inbox.", "checked": "Inbox checked: what it found is above.",
"oauth-expired": "That sign-in took too long or was already used. Try again.", "test-sent": "Test email sent: check your inbox.",
"dismissed": "Dismissed.", "oauth-expired": "That sign-in took too long or was already used. Try again.",
"restored": "Restored.", "dismissed": "Dismissed.",
"drafted": "Drafts written. Review them below.", "restored": "Restored.",
"published": "Published.", "drafted": "Drafts written. Review them below.",
"discarded": "Discarded.", "published": "Published.",
"scheduled": "Scheduled.", "discarded": "Discarded.",
"posted": "Marked as posted: it's under Content → Published.", "scheduled": "Scheduled.",
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.", "posted": "Marked as posted: it's under Content → Published.",
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
} }
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) { func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
+48 -3
View File
@@ -180,6 +180,10 @@ var accountFields = []secretField{
"Create an app (it needs a LinkedIn company page), add the products Share on LinkedIn and Sign In with LinkedIn using OpenID Connect, then open the Auth tab.", linkedInApps}, "Create an app (it needs a LinkedIn company page), add the products Share on LinkedIn and Sign In with LinkedIn using OpenID Connect, then open the Auth tab.", linkedInApps},
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret", {"LinkedIn", secrets.LinkedInClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps}, "On the same Auth tab, under the client ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientID, "Client ID",
"A second LinkedIn app, linked to the company page, with the Community Management API approved by LinkedIn (it must be the app's only product). Its Auth tab has the ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"Reddit", secrets.RedditClientID, "Client ID", {"Reddit", secrets.RedditClientID, "Client ID",
"Create app → choose \"web app\" and enter the redirect URI below. The client ID is the string under the app's name.", redditApps}, "Create app → choose \"web app\" and enter the redirect URI below. The client ID is the string under the app's name.", redditApps},
{"Reddit", secrets.RedditClientSecret, "Client secret", {"Reddit", secrets.RedditClientSecret, "Client secret",
@@ -228,7 +232,8 @@ type connectInfo struct {
Account string Account string
At time.Time At time.Time
Note string Note string
Expiry *Expiry // when the sign-in runs out, for LinkedIn Expiry *Expiry // when the sign-in runs out, for LinkedIn
Page *pageSetup // the company page's choices, for the LinkedIn page
} }
func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) { func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
@@ -239,7 +244,7 @@ func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
// networks are the cards on the Social accounts tab, as things stand. // networks are the cards on the Social accounts tab, as things stand.
func (s *Server) networks() []network { func (s *Server) networks() []network {
names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.RedditAccessToken} names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.LinkedInPageAccessToken, secrets.RedditAccessToken}
for _, f := range accountFields { for _, f := range accountFields {
names = append(names, f.Name) names = append(names, f.Name)
} }
@@ -259,7 +264,7 @@ func (s *Server) networks() []network {
} }
} }
var nets []network var nets []network
for _, name := range []string{"X", "LinkedIn", "Reddit", "YouTube"} { for _, name := range []string{"X", "LinkedIn", liPageNetwork, "Reddit", "YouTube"} {
n := network{Name: name, Set: set} n := network{Name: name, Set: set}
for _, f := range accountFields { for _, f := range accountFields {
if f.Group == name { if f.Group == name {
@@ -274,6 +279,12 @@ func (s *Server) networks() []network {
n.Connect = connect("linkedin", secrets.LinkedInAccessToken, "In your LinkedIn app's Auth settings, add this redirect URL:", "", n.Connect = connect("linkedin", secrets.LinkedInAccessToken, "In your LinkedIn app's Auth settings, add this redirect URL:", "",
set[secrets.LinkedInClientID] && set[secrets.LinkedInClientSecret], func(string) string { return "" }) set[secrets.LinkedInClientID] && set[secrets.LinkedInClientSecret], func(string) string { return "" })
n.Connect.Expiry = s.linkedInExpiry() n.Connect.Expiry = s.linkedInExpiry()
case liPageNetwork:
n.Connect = connect(liPageProvider, secrets.LinkedInPageAccessToken, "In the page app's Auth settings, add this redirect URL:",
"Posts can then go out as the company page instead of you; each LinkedIn draft says which.",
set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup()
case "Reddit": case "Reddit":
n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:", n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:",
"Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.", "Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.",
@@ -351,6 +362,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return return
} }
authURL, p, err = oauth.LinkedInStart(id, s.callbackURL("linkedin")) authURL, p, err = oauth.LinkedInStart(id, s.callbackURL("linkedin"))
case liPageProvider:
id := s.Secrets.Get(secrets.LinkedInPageClientID)
if id == "" || !s.Secrets.Has(secrets.LinkedInPageClientSecret) {
http.Error(w, "Save the LinkedIn page app's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes())
case "reddit": case "reddit":
id := s.Secrets.Get(secrets.RedditClientID) id := s.Secrets.Get(secrets.RedditClientID)
if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) { if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) {
@@ -489,6 +507,33 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
s.Log.Error("saving connection", "err", err) s.Log.Error("saving connection", "err", err)
} }
redirect(w, r, "/settings/accounts", "li-connected") redirect(w, r, "/settings/accounts", "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.Secrets.Set(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 := ""
if o := s.liPage(); o != nil {
account = o.Name
}
if err := s.saveConnection(liPageProvider, Connection{Account: account, At: now, Expires: now.Add(life)}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "li-page-connected")
case "reddit": case "reddit":
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret), res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), code, p) s.redditUserAgent(), code, p)
+94
View File
@@ -0,0 +1,94 @@
package web
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"testing"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/content"
"supermarket/internal/secrets"
)
func TestLinkedInPageSettings(t *testing.T) {
s, h := newTestServer(t, nil)
body := do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
if !strings.Contains(body, `id="network-LinkedIn page"`) || !strings.Contains(body, "/auth/linkedin-page/callback") ||
!strings.Contains(body, "Once connected, choose the page here") || !strings.Contains(body, `value="w_organization_social r_organization_admin"`) {
t.Errorf("card: %s", body)
}
// Without the app's keys, the sign-in can't start.
if rec := postForm(h, "/auth/linkedin-page/start", nil); rec.Code != http.StatusBadRequest {
t.Errorf("start without keys: %d", rec.Code)
}
s.Secrets.Set(map[string]string{secrets.LinkedInPageClientID: "cid", secrets.LinkedInPageClientSecret: "sec"})
postForm(h, "/settings/accounts/linkedin-page", url.Values{"scopes": {"w_organization_social rw_organization_admin"}})
rec := postForm(h, "/auth/linkedin-page/start", nil)
loc, _ := url.Parse(rec.Header().Get("Location"))
if rec.Code != http.StatusSeeOther || loc.Query().Get("scope") != "w_organization_social rw_organization_admin" || loc.Query().Get("client_id") != "cid" {
t.Errorf("start: %d %s", rec.Code, loc)
}
// Signed in (the callback's work), with two pages listed.
s.Secrets.Set(map[string]string{secrets.LinkedInPageAccessToken: "page-tok"})
s.DB.PutJSON(liPageOrgsKey, []linkedinapi.Org{{URN: "urn:li:organization:111", ID: "111", Name: "Federated Computer", Role: "ADMINISTRATOR"},
{URN: "urn:li:organization:222", ID: "222", Name: "Other", Role: "CONTENT_ADMIN"}})
body = do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
if !strings.Contains(body, `value="urn:li:organization:111"`) || !strings.Contains(body, "Federated Computer") {
t.Errorf("pages: %s", body)
}
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org": {"urn:li:organization:111"}, "default": {"page"}})
if o := s.liPage(); o == nil || o.Name != "Federated Computer" {
t.Errorf("chosen: %+v", o)
}
var def string
s.DB.GetJSON(content.LinkedInDefaultKey, &def)
if def != content.AsPage {
t.Errorf("default: %q", def)
}
// Typed in by hand, from the page's admin address.
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org_manual": {"https://www.linkedin.com/company/87654321/admin/"}})
if o := s.liPage(); o == nil || o.URN != "urn:li:organization:87654321" {
t.Errorf("manual: %+v", o)
}
if body := postForm(h, "/settings/accounts/linkedin-page", url.Values{"org_manual": {"federated"}}).Body.String(); !strings.Contains(body, "isn&#39;t a company page&#39;s number") {
t.Errorf("bad manual: %s", body)
}
// A LinkedIn draft offers the page, and the choice is saved.
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org": {"urn:li:organization:111"}, "default": {"page"}})
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>`) {
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)
}
// The page counts as LinkedIn being connected, even without the member sign-in.
if !s.connected()[content.ChannelLinkedIn] {
t.Error("LinkedIn not connected with only the page")
}
}
func TestLinkedInPublisherChoosesTheAuthor(t *testing.T) {
ctx := context.Background()
if _, err := (linkedInPublisher{}).Publish(ctx, content.Post{Text: "x", AsPage: true}); !errors.Is(err, errNoPage) {
t.Errorf("no page: %v", err)
}
if _, err := (linkedInPublisher{page: linkedinapi.New("t", "urn:li:organization:1")}).Publish(ctx, content.Post{Text: "x"}); !errors.Is(err, errNoMe) {
t.Errorf("no member: %v", err)
}
expired := errors.New("expired")
if _, err := (linkedInPublisher{pageErr: expired}).Publish(ctx, content.Post{Text: "x", AsPage: true}); !errors.Is(err, expired) {
t.Errorf("expired page: %v", err)
}
}
+28
View File
@@ -43,6 +43,34 @@
<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}}Reconnect{{else}}Connect{{end}} {{$name}}</button>
</form> </form>
</div> </div>
{{with .Page}}{{$pg := .}}
<form method="post" action="/settings/accounts/linkedin-page" class="signin">
<h3>The company page</h3>
{{if .Signed}}
{{if .Orgs}}
<fieldset><legend>Post as</legend>
{{range .Orgs}}<label class="check"><input type="radio" name="org" value="{{.URN}}" {{if and $pg.Chosen (eq $pg.Chosen.URN .URN)}}checked{{end}}> {{.Name}}{{with .Vanity}} <span class="muted small">linkedin.com/company/{{.}}</span>{{end}} <span class="badge">{{.Role}}</span></label>{{end}}
</fieldset>
{{else}}
{{with .Note}}<p class="warn-text">Couldn't list your pages: {{.}}</p>{{end}}
<label>The page's number <span class="muted">(from its admin view: linkedin.com/company/&lt;number&gt;/admin)</span>
<input name="org_manual" value="{{with $pg.Chosen}}{{.ID}}{{end}}" placeholder="12345678"></label>
{{end}}
{{with .Chosen}}<p class="small">Posting as <strong>{{.Name}}</strong>.</p>{{end}}
{{else}}<p class="help">Once connected, choose the page here.</p>{{end}}
<fieldset><legend>New LinkedIn drafts post as</legend>
<label class="check"><input type="radio" name="default" value="" {{if ne .Default "page"}}checked{{end}}> You</label>
<label class="check"><input type="radio" name="default" value="page" {{if eq .Default "page"}}checked{{end}}> The company page</label>
<span class="help">Each draft can still be switched before it's published.</span>
</fieldset>
<label>Permissions to ask for <input name="scopes" value="{{.Scopes}}">
<span class="help">As on the approved app's Auth tab: posting as the page (<code>w_organization_social</code>) and reading the pages you manage (<code>r_organization_admin</code> or <code>rw_organization_admin</code>). Reconnect after changing them.</span></label>
<div class="row">
<button type="submit" class="secondary">Save</button>
{{if .Signed}}<button type="submit" class="secondary" name="do" value="refresh">List my pages again</button>{{end}}
</div>
</form>
{{end}}
{{end}} {{end}}
</section> </section>
{{end}} {{end}}
+6 -1
View File
@@ -1,4 +1,4 @@
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}} {{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$page := .Page}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Posts</h1> <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. <p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it.
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p> {{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
@@ -43,6 +43,11 @@
data-count="{{.Channel}}" data-limit="{{.Limit}}" data-reserve="{{if eq .Channel "x"}}{{xreserve .SourceURL}}{{else}}0{{end}}" 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> 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 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}}
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}</p> <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"> <div class="actions">
<button type="submit" name="action" value="publish" formaction="/drafts/{{.ID}}/publish" <button type="submit" name="action" value="publish" formaction="/drafts/{{.ID}}/publish"