diff --git a/PLAN.md b/PLAN.md index bc7784d..05810c4 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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 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:` 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 + 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 Not in any phase yet; picked up when the user asks. diff --git a/TEST.md b/TEST.md index 745eca6..c96584b 100644 --- a/TEST.md +++ b/TEST.md @@ -62,6 +62,23 @@ Throughout, also notice: - [ ] LinkedIn shows when its 60-day sign-in runs out. - [ ] 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//admin and save. +- [ ] Choose "New LinkedIn drafts post as: The company page": new LinkedIn + drafts in Posts show *Post as: *; 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 - [ ] It shows your Core's domain, email and name from `core.conf`. diff --git a/internal/api/linkedin/client.go b/internal/api/linkedin/client.go index 5d6d73e..d33b2ef 100644 --- a/internal/api/linkedin/client.go +++ b/internal/api/linkedin/client.go @@ -198,3 +198,115 @@ func fallbackTitle(u string) string { } 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 string `json:"id"` + Name string `json:"name"` + Vanity string `json:"vanity"` // linkedin.com/company/ + 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 +} diff --git a/internal/api/linkedin/client_test.go b/internal/api/linkedin/client_test.go index 5afdd2e..516e9d0 100644 --- a/internal/api/linkedin/client_test.go +++ b/internal/api/linkedin/client_test.go @@ -100,3 +100,72 @@ func TestPostSendsTheArticleTitle(t *testing.T) { 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) + } +} diff --git a/internal/content/content_test.go b/internal/content/content_test.go index 2b09a47..828f774 100644 --- a/internal/content/content_test.go +++ b/internal/content/content_test.go @@ -82,9 +82,11 @@ func TestItems(t *testing.T) { type fakePub struct { calls []string err error + got Post // the last post } func (f *fakePub) Publish(_ context.Context, p Post) (string, error) { + f.got = p call := p.Text + "|" + p.SourceURL if p.Target != "" { call = "r/" + p.Target + "|" + p.Title + "|" + call @@ -366,3 +368,61 @@ func TestDraftsForSignal(t *testing.T) { 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") + } +} diff --git a/internal/content/drafts.go b/internal/content/drafts.go index 1c45398..9cf1697 100644 --- a/internal/content/drafts.go +++ b/internal/content/drafts.go @@ -80,8 +80,16 @@ type Draft struct { PublishAt time.Time // when a scheduled draft goes out SignalID int64 // the buying signal it was written for; 0: none SignalSlug string // that signal's campaign tag + LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page } +// 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 // source link on X. func (d *Draft) Length() int { @@ -157,6 +165,11 @@ func newBatchID() string { // their items as used. func CreateDrafts(d *db.DB, drafts []Draft) (string, error) { 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() if err != nil { return "", err @@ -173,9 +186,16 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) { if dr.SignalID != 0 { sig = dr.SignalID } - if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel, - strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig); err != nil { + as := dr.LinkedInAs + if dr.Channel == ChannelLinkedIn && as == "" { + 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 } 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, 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) { defer rows.Close() @@ -210,7 +230,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) { var ids, created, updated, published, publishAt string if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content, &dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target, - &dr.SignalID, &dr.SignalSlug); err != nil { + &dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs); err != nil { return nil, err } _ = json.Unmarshal([]byte(ids), &dr.ItemIDs) @@ -279,6 +299,17 @@ func UpdateDraft(d *db.DB, id int64, text string) error { 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. func DiscardDraft(d *db.DB, id int64) error { res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`, diff --git a/internal/content/publish.go b/internal/content/publish.go index 905473e..eaa0c6f 100644 --- a/internal/content/publish.go +++ b/internal/content/publish.go @@ -16,6 +16,7 @@ type Post struct { SourceURL string // tagged, if it's the company's Title string // Reddit Target string // Reddit: the subreddit + AsPage bool // LinkedIn: post as the company page } // 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) - 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()) if pubErr != nil { if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`, diff --git a/internal/db/db.go b/internal/db/db.go index e98ecdd..7c3c5f3 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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 checked_at TEXT; 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 ''; `, } diff --git a/internal/oauth/linkedin_test.go b/internal/oauth/linkedin_test.go new file mode 100644 index 0000000..a9d661c --- /dev/null +++ b/internal/oauth/linkedin_test.go @@ -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) + } +} diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 1f3a47e..38bba8c 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -113,9 +113,20 @@ const ( 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, // no PKCE). 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() if err != nil { return "", nil, err @@ -124,10 +135,10 @@ func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) { "response_type": {"code"}, "client_id": {clientID}, "redirect_uri": {redirectURI}, - "scope": {linkedInScopes}, + "scope": {scopes}, "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 } diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index b124745..25af964 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -29,6 +29,10 @@ const ( LinkedInClientSecret = "linkedin.client_secret" LinkedInAccessToken = "linkedin.access_token" 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" diff --git a/internal/web/channels.go b/internal/web/channels.go index c485e1f..a24182c 100644 --- a/internal/web/channels.go +++ b/internal/web/channels.go @@ -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 { diff --git a/internal/web/inbox.go b/internal/web/inbox.go index 8af371f..007f378 100644 --- a/internal/web/inbox.go +++ b/internal/web/inbox.go @@ -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": diff --git a/internal/web/linkedinpage.go b/internal/web/linkedinpage.go new file mode 100644 index 0000000..7ba86d1 --- /dev/null +++ b/internal/web/linkedinpage.go @@ -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//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() +} diff --git a/internal/web/pages.go b/internal/web/pages.go index ee1d5eb..ca57f61 100644 --- a/internal/web/pages.go +++ b/internal/web/pages.go @@ -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" diff --git a/internal/web/server.go b/internal/web/server.go index e06bafe..ba6b06f 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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) { diff --git a/internal/web/settings.go b/internal/web/settings.go index 4080d19..550cfe5 100644 --- a/internal/web/settings.go +++ b/internal/web/settings.go @@ -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) diff --git a/internal/web/settings_linkedin_test.go b/internal/web/settings_linkedin_test.go new file mode 100644 index 0000000..3ac0f3a --- /dev/null +++ b/internal/web/settings_linkedin_test.go @@ -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, ``) { + 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) + } +} diff --git a/internal/web/templates/accounts.html b/internal/web/templates/accounts.html index e9fc5cc..d7d393a 100644 --- a/internal/web/templates/accounts.html +++ b/internal/web/templates/accounts.html @@ -43,6 +43,34 @@ + {{with .Page}}{{$pg := .}} + + {{end}} {{end}} {{end}} diff --git a/internal/web/templates/inbox.html b/internal/web/templates/inbox.html index a275ee7..bd8363f 100644 --- a/internal/web/templates/inbox.html +++ b/internal/web/templates/inbox.html @@ -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}}

Posts

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

@@ -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}} {{if eq .Channel "reddit"}}{{if .SourceURL}}

The source link is added at the end as “Source: …”.

{{end}}{{end}} + {{if and (eq .Channel "linkedin") $page}} + + {{else if eq .LinkedInAs "page"}}

This draft posts as the company page, which isn't connected: set it up under Settings → Social accounts.

{{end}}

{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}