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:
@@ -62,13 +62,24 @@ func (s *Server) publishers() content.Publishers {
|
||||
}
|
||||
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() {
|
||||
pubs[content.ChannelLinkedIn] = expiredPublisher{*e}
|
||||
li.meErr = expiredPublisher{*e}.err()
|
||||
} 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 {
|
||||
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
|
||||
}
|
||||
@@ -80,7 +91,11 @@ func (s *Server) publishers() content.Publishers {
|
||||
type expiredPublisher struct{ e Expiry }
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -96,12 +111,23 @@ func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, err
|
||||
return p.c.PostTweet(ctx, text)
|
||||
}
|
||||
|
||||
type linkedInPublisher struct{ c *linkedin.Client }
|
||||
|
||||
// Publish attaches the source link as an article preview.
|
||||
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 == "" {
|
||||
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
|
||||
// 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)
|
||||
defer cancel()
|
||||
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 {
|
||||
|
||||
+13
-2
@@ -74,9 +74,13 @@ func groupBatches(drafts []content.Draft) []*draftBatch {
|
||||
func (s *Server) connected() map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for id, p := range s.publishers() {
|
||||
if _, expired := p.(expiredPublisher); !expired {
|
||||
out[id] = true
|
||||
if _, expired := p.(expiredPublisher); expired {
|
||||
continue
|
||||
}
|
||||
if li, ok := p.(linkedInPublisher); ok && li.me == nil && li.page == nil {
|
||||
continue // only expired sign-ins
|
||||
}
|
||||
out[id] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -100,6 +104,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
|
||||
"Sections": sections,
|
||||
"Reddit": s.redditViews(r.Context(), pending),
|
||||
"Connected": s.connected(),
|
||||
"Page": s.liPageIfSignedIn(),
|
||||
"Tagged": s.tagger() != nil,
|
||||
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
|
||||
"Zone": time.Now().Format("MST"),
|
||||
@@ -246,6 +251,12 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
case "save":
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -72,10 +72,13 @@ func (s *Server) linkedInExpiry() *Expiry {
|
||||
// reminders are the sign-ins running out soon, or already, for the
|
||||
// Overview and Posts.
|
||||
func (s *Server) reminders() []Expiry {
|
||||
if e := s.linkedInExpiry(); e != nil && e.Soon() {
|
||||
return []Expiry{*e}
|
||||
var out []Expiry
|
||||
for _, e := range []*Expiry{s.linkedInExpiry(), s.linkedInPageExpiry()} {
|
||||
if e != nil && e.Soon() {
|
||||
out = append(out, *e)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return out
|
||||
}
|
||||
|
||||
const connectionsKey = "connections"
|
||||
|
||||
+52
-50
@@ -119,6 +119,7 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
|
||||
mux.HandleFunc("GET /settings/accounts", s.accountsPage)
|
||||
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("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.
|
||||
var flashes = map[string]string{
|
||||
"saved": "Saved.",
|
||||
"deleted": "Deleted.",
|
||||
"x-connected": "X is connected.",
|
||||
"li-connected": "LinkedIn 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.",
|
||||
"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.",
|
||||
"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.",
|
||||
"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.",
|
||||
"deleted": "Deleted.",
|
||||
"x-connected": "X is connected.",
|
||||
"li-connected": "LinkedIn is connected.",
|
||||
"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.",
|
||||
"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.",
|
||||
"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.",
|
||||
"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.",
|
||||
}
|
||||
|
||||
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
|
||||
|
||||
@@ -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},
|
||||
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret",
|
||||
"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",
|
||||
"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",
|
||||
@@ -228,7 +232,8 @@ type connectInfo struct {
|
||||
Account string
|
||||
At time.Time
|
||||
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) {
|
||||
@@ -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.
|
||||
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 {
|
||||
names = append(names, f.Name)
|
||||
}
|
||||
@@ -259,7 +264,7 @@ func (s *Server) networks() []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}
|
||||
for _, f := range accountFields {
|
||||
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:", "",
|
||||
set[secrets.LinkedInClientID] && set[secrets.LinkedInClientSecret], func(string) string { return "" })
|
||||
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":
|
||||
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.",
|
||||
@@ -351,6 +362,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
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":
|
||||
id := s.Secrets.Get(secrets.RedditClientID)
|
||||
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)
|
||||
}
|
||||
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":
|
||||
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
|
||||
s.redditUserAgent(), code, p)
|
||||
|
||||
@@ -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't a company page'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)
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
</form>
|
||||
</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/<number>/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}}
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
@@ -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>
|
||||
<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,6 +43,11 @@
|
||||
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}}
|
||||
<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"
|
||||
|
||||
Reference in New Issue
Block a user