Files
davidandClaude Opus 5.5 98913971ea 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>
2026-11-22 15:05:30 -07:00

198 lines
5.9 KiB
Go

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()
}