LinkedIn publishing works again; rename Inbox to Posts
LinkedIn: - The API version was fixed at 202501, retired by LinkedIn (426 NONEXISTENT_VERSION). It's now the month before last, stepping back a month (up to four) if LinkedIn says a version isn't active. - The versioned Posts API needs a title for a link's article card (422). Supermarket reads the linked page's title and description and sends them, falling back to the page's address as the title. Tested for real: a post with a link went out to the member's profile. Inbox is now Posts: the menu, page, messages and docs; the page moves to /posts, and /inbox redirects there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,19 +7,32 @@ import (
|
||||
"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 (
|
||||
apiBase = "https://api.linkedin.com"
|
||||
linkedinVersion = "202501"
|
||||
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 {
|
||||
@@ -27,12 +40,23 @@ func New(accessToken, authorURN string) *Client {
|
||||
accessToken: accessToken,
|
||||
authorURN: authorURN,
|
||||
http: &http.Client{Timeout: 15 * time.Second},
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// PostUpdate creates a LinkedIn post. If sourceURL is non-empty it is attached
|
||||
// as an article card (LinkedIn will fetch the title and thumbnail automatically).
|
||||
func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string, error) {
|
||||
// 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,
|
||||
@@ -45,8 +69,16 @@ func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string
|
||||
LifecycleState: "PUBLISHED",
|
||||
IsReshareDisabledByAuthor: false,
|
||||
}
|
||||
if sourceURL != "" {
|
||||
pr.Content = &postContent{Article: articleContent{Source: sourceURL}}
|
||||
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)
|
||||
@@ -54,22 +86,34 @@ func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string
|
||||
return "", err
|
||||
}
|
||||
|
||||
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", linkedinVersion)
|
||||
req.Header.Set("X-Restli-Protocol-Version", "2.0.0")
|
||||
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
|
||||
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
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode == http.StatusUnauthorized {
|
||||
return "", ErrUnauthorized
|
||||
}
|
||||
@@ -141,5 +185,16 @@ type postContent struct {
|
||||
}
|
||||
|
||||
type articleContent struct {
|
||||
Source string `json:"source"`
|
||||
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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package linkedin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVersion(t *testing.T) {
|
||||
now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
|
||||
for back, want := range map[int]string{0: "202611", 2: "202609", 11: "202512"} {
|
||||
if got := version(now, back); got != want {
|
||||
t.Errorf("version(%d) = %s, want %s", back, got, want)
|
||||
}
|
||||
}
|
||||
// 31 March minus one month mustn't land in March again.
|
||||
if got := version(time.Date(2026, 3, 31, 0, 0, 0, 0, time.UTC), 1); got != "202602" {
|
||||
t.Errorf("from 31 March: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostStepsBackFromRetiredVersions(t *testing.T) {
|
||||
var asked []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
v := r.Header.Get("LinkedIn-Version")
|
||||
asked = append(asked, v)
|
||||
if v > "202608" { // pretend only August and earlier are active
|
||||
w.WriteHeader(http.StatusUpgradeRequired)
|
||||
w.Write([]byte(`{"status":426,"code":"NONEXISTENT_VERSION"}`))
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-RestLi-Id", "urn:li:share:1")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := apiBase
|
||||
apiBase = srv.URL
|
||||
defer func() { apiBase = old }()
|
||||
|
||||
c := New("tok", "urn:li:person:1")
|
||||
c.now = func() time.Time { return time.Date(2026, 11, 21, 0, 0, 0, 0, time.UTC) }
|
||||
url, err := c.PostUpdate(context.Background(), "hi", nil)
|
||||
if err != nil || !strings.Contains(url, "urn:li:share:1") {
|
||||
t.Fatalf("post: %q %v", url, err)
|
||||
}
|
||||
if strings.Join(asked, ",") != "202609,202608" {
|
||||
t.Errorf("versions asked: %v", asked)
|
||||
}
|
||||
|
||||
// Gives up after a few, with LinkedIn's answer.
|
||||
asked = nil
|
||||
c.now = func() time.Time { return time.Date(2027, 12, 1, 0, 0, 0, 0, time.UTC) }
|
||||
if _, err := c.PostUpdate(context.Background(), "hi", nil); err == nil || !strings.Contains(err.Error(), "426") || len(asked) != versionAttempts {
|
||||
t.Errorf("give up: %v after %v", err, asked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostSendsTheArticleTitle(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var b map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&b)
|
||||
bodies = append(bodies, b)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := apiBase
|
||||
apiBase = srv.URL
|
||||
defer func() { apiBase = old }()
|
||||
c := New("tok", "urn:li:person:1")
|
||||
|
||||
article := func(i int) map[string]any {
|
||||
return bodies[i]["content"].(map[string]any)["article"].(map[string]any)
|
||||
}
|
||||
if _, err := c.PostUpdate(context.Background(), "hi", &Link{URL: "https://acme.example/w?utm_source=linkedin", Title: " Widget 2 ", Description: "Faster."}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := article(0); a["title"] != "Widget 2" || a["description"] != "Faster." || a["source"] != "https://acme.example/w?utm_source=linkedin" {
|
||||
t.Errorf("article: %v", a)
|
||||
}
|
||||
// No title read: the address stands in, as LinkedIn requires one.
|
||||
if _, err := c.PostUpdate(context.Background(), "hi", &Link{URL: "https://www.acme.example/blog/post/"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a := article(1); a["title"] != "acme.example/blog/post" {
|
||||
t.Errorf("fallback title: %v", a["title"])
|
||||
}
|
||||
if _, has := article(1)["description"]; has {
|
||||
t.Error("an empty description should be left out")
|
||||
}
|
||||
// No link: no content at all.
|
||||
if _, err := c.PostUpdate(context.Background(), "hi", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, has := bodies[2]["content"]; has {
|
||||
t.Error("a post without a link has no content")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user