package linkedin import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" ) var apiBase = "https://api.linkedin.com" // a variable for tests // LinkedIn's REST API is versioned by month (YYYYMM), and each version is // retired after about a year. Rather than a fixed version that goes stale, // Supermarket asks for the month before last (surely released), and steps // back a month if LinkedIn says that one isn't active. const ( versionLag = 2 // months before now versionAttempts = 4 // versions tried before giving up ) // version is the LinkedIn-Version for the month back months before now. func version(now time.Time, back int) string { return now.AddDate(0, -back, -now.Day()+1).Format("200601") } type Client struct { accessToken string authorURN string http *http.Client now func() time.Time } func New(accessToken, authorURN string) *Client { return &Client{ accessToken: accessToken, authorURN: authorURN, http: &http.Client{Timeout: 15 * time.Second}, now: time.Now, } } // Link is a page attached to a post as an article card. LinkedIn's API // doesn't read the page itself: the card shows the title and description // given here (a title is required). type Link struct { URL, Title, Description string } // maxArticleTitle keeps a card's title to a sensible length. const maxArticleTitle = 200 // PostUpdate creates a LinkedIn post, with link (if not nil) attached as an // article card. func (c *Client) PostUpdate(ctx context.Context, text string, link *Link) (string, error) { pr := postRequest{ Author: c.authorURN, Commentary: text, Visibility: "PUBLIC", Distribution: distribution{ FeedDistribution: "MAIN_FEED", TargetEntities: []any{}, ThirdPartyDistributionChannels: []any{}, }, LifecycleState: "PUBLISHED", IsReshareDisabledByAuthor: false, } if link != nil && link.URL != "" { title := strings.TrimSpace(link.Title) if title == "" { title = fallbackTitle(link.URL) } if r := []rune(title); len(r) > maxArticleTitle { title = string(r[:maxArticleTitle-1]) + "…" } pr.Content = &postContent{Article: articleContent{Source: link.URL, Title: title, Description: strings.TrimSpace(link.Description)}} } body, err := json.Marshal(pr) if err != nil { return "", err } var ( res *http.Response raw []byte ) for attempt := 0; ; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBase+"/rest/posts", strings.NewReader(string(body))) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+c.accessToken) req.Header.Set("Content-Type", "application/json") 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(res.Body) res.Body.Close() // 426: that version isn't active. Nothing was posted; try an // earlier one. if res.StatusCode == http.StatusUpgradeRequired && attempt+1 < versionAttempts { continue } break } if res.StatusCode == http.StatusUnauthorized { return "", ErrUnauthorized } if res.StatusCode != http.StatusCreated { return "", fmt.Errorf("linkedin HTTP %d: %s", res.StatusCode, raw) } postID := res.Header.Get("X-RestLi-Id") if postID == "" { return "", nil } return "https://www.linkedin.com/feed/update/" + postID + "/", nil } // GetAuthorURN fetches the LinkedIn person URN for the owner of accessToken. // ErrUnauthorized is LinkedIn refusing the access token, usually because it // expired (they last 60 days and can't be renewed without signing in again). var ErrUnauthorized = errors.New("LinkedIn refused the sign-in; it has probably expired: reconnect LinkedIn under Settings → Social accounts") func GetAuthorURN(ctx context.Context, accessToken string) (string, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/v2/userinfo", nil) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+accessToken) res, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if res.StatusCode != http.StatusOK { return "", fmt.Errorf("userinfo HTTP %d: %s", res.StatusCode, raw) } var info struct { Sub string `json:"sub"` Name string `json:"name"` } if err := json.Unmarshal(raw, &info); err != nil { return "", err } if info.Sub == "" { return "", fmt.Errorf("no sub in userinfo response: %s", raw) } return "urn:li:person:" + info.Sub, nil } type postRequest struct { Author string `json:"author"` Commentary string `json:"commentary"` Visibility string `json:"visibility"` Distribution distribution `json:"distribution"` Content *postContent `json:"content,omitempty"` LifecycleState string `json:"lifecycleState"` IsReshareDisabledByAuthor bool `json:"isReshareDisabledByAuthor"` } type distribution struct { FeedDistribution string `json:"feedDistribution"` TargetEntities []any `json:"targetEntities"` ThirdPartyDistributionChannels []any `json:"thirdPartyDistributionChannels"` } type postContent struct { Article articleContent `json:"article"` } type articleContent struct { Source string `json:"source"` Title string `json:"title"` Description string `json:"description,omitempty"` } // fallbackTitle is a card title for a page whose own title couldn't be // read: its address without the scheme. func fallbackTitle(u string) string { if p, err := url.Parse(u); err == nil && p.Host != "" { return strings.TrimSuffix(strings.TrimPrefix(p.Host, "www.")+p.Path, "/") } 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 }