diff --git a/internal/api/linkedin/client.go b/internal/api/linkedin/client.go index 1b981f5..fd71d65 100644 --- a/internal/api/linkedin/client.go +++ b/internal/api/linkedin/client.go @@ -3,6 +3,7 @@ package linkedin import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -69,6 +70,9 @@ func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string defer res.Body.Close() raw, _ := io.ReadAll(res.Body) + if res.StatusCode == http.StatusUnauthorized { + return "", ErrUnauthorized + } if res.StatusCode != http.StatusCreated { return "", fmt.Errorf("linkedin HTTP %d: %s", res.StatusCode, raw) } @@ -81,6 +85,10 @@ func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string } // 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 { diff --git a/internal/content/publish.go b/internal/content/publish.go index 1a978ca..c6a842c 100644 --- a/internal/content/publish.go +++ b/internal/content/publish.go @@ -45,7 +45,7 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i } pub := pubs[dr.Channel] if pub == nil { - return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Credentials", dr.ChannelName()) + return dr, fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName()) } if problem := dr.Problem(); problem != "" { return dr, fmt.Errorf("%s. Fix it first", problem) diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go index 3c59ba9..ca04459 100644 --- a/internal/oauth/oauth.go +++ b/internal/oauth/oauth.go @@ -23,6 +23,7 @@ var httpClient = &http.Client{Timeout: 20 * time.Second} type Result struct { AccessToken string RefreshToken string + ExpiresIn time.Duration // how long the access token lasts, if the provider said } // Pending is a started flow, kept by the caller until the callback arrives. @@ -225,6 +226,7 @@ func tokenResponse(req *http.Request) (*Result, error) { var out struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` + ExpiresIn int64 `json:"expires_in"` } if err := json.Unmarshal(raw, &out); err != nil { return nil, err @@ -232,7 +234,8 @@ func tokenResponse(req *http.Request) (*Result, error) { if out.AccessToken == "" { return nil, fmt.Errorf("no access_token in the token response") } - return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil + return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken, + ExpiresIn: time.Duration(out.ExpiresIn) * time.Second}, nil } func pkce() (verifier, challenge string, err error) { diff --git a/internal/web/channels.go b/internal/web/channels.go index 7e9963d..b93f4d0 100644 --- a/internal/web/channels.go +++ b/internal/web/channels.go @@ -62,7 +62,11 @@ func (s *Server) publishers() content.Publishers { pubs[content.ChannelX] = xPublisher{c} } if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" { - pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)} + if e := s.linkedInExpiry(); e != nil && e.Expired() { + pubs[content.ChannelLinkedIn] = expiredPublisher{*e} + } else { + pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)} + } } if c := s.redditUser(); c != nil { pubs[content.ChannelReddit] = redditPublisher{s: s, c: c} @@ -70,6 +74,15 @@ func (s *Server) publishers() content.Publishers { return pubs } +// expiredPublisher stands in for a network whose sign-in ran out: it posts +// nothing and says so, rather than letting the network answer 401. +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", + p.e.Network, p.e.At.Local().Format("2 Jan 2006"), p.e.Network) +} + type xPublisher struct{ c *twitter.Client } // Publish appends the source link to the post, as the old app did; X shows diff --git a/internal/web/content.go b/internal/web/content.go index dfe41cd..c4b9313 100644 --- a/internal/web/content.go +++ b/internal/web/content.go @@ -148,10 +148,10 @@ func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, if err != nil { return nil, err } - pubs := s.publishers() + conn := s.connected() var chans []channelChoice for _, c := range content.Channels { - chans = append(chans, channelChoice{c, pubs[c.ID] != nil}) + chans = append(chans, channelChoice{c, conn[c.ID]}) } var subs []string seen := map[string]bool{} diff --git a/internal/web/inbox.go b/internal/web/inbox.go index ce890da..a8ab849 100644 --- a/internal/web/inbox.go +++ b/internal/web/inbox.go @@ -72,8 +72,10 @@ func groupBatches(drafts []content.Draft) []*draftBatch { func (s *Server) connected() map[string]bool { out := map[string]bool{} - for id := range s.publishers() { - out[id] = true + for id, p := range s.publishers() { + if _, expired := p.(expiredPublisher); !expired { + out[id] = true + } } return out } @@ -93,6 +95,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri sections = append(sections, inboxSection{Module: "Content", Batches: groupBatches(pending)}) } s.render(w, r, "inbox", page{Title: "Inbox", Nav: "content/inbox", Error: errMsg, Data: map[string]any{ + "Reminders": s.reminders(), "Sections": sections, "Reddit": s.redditViews(r.Context(), pending), "Connected": s.connected(), diff --git a/internal/web/pages.go b/internal/web/pages.go index a75cf06..7d2a828 100644 --- a/internal/web/pages.go +++ b/internal/web/pages.go @@ -25,6 +25,57 @@ import ( type Connection struct { Account string `json:"account"` At time.Time `json:"at"` + // Expires is when the sign-in stops working, for networks whose tokens + // can't be renewed (LinkedIn); zero for ones Supermarket renews itself. + Expires time.Time `json:"expires,omitempty"` +} + +// linkedInTokenLife is how long LinkedIn's access tokens last, for +// sign-ins saved before the expiry was recorded. +const linkedInTokenLife = 60 * 24 * time.Hour + +// expiryWarning is how long before a sign-in expires the reminders start. +const expiryWarning = 14 * 24 * time.Hour + +// Expiry is when a sign-in runs out, if it does. +type Expiry struct { + Network string // e.g. LinkedIn + At time.Time +} + +// Expired reports whether it has run out. +func (e Expiry) Expired() bool { return !time.Now().Before(e.At) } + +// Soon reports whether it runs out within expiryWarning (or has). +func (e Expiry) Soon() bool { return time.Until(e.At) < expiryWarning } + +// Days is how many whole days are left (0 on the last day). +func (e Expiry) Days() int { return int(time.Until(e.At) / (24 * time.Hour)) } + +// linkedInExpiry is when the LinkedIn sign-in runs out, or nil if LinkedIn +// isn't connected. +func (s *Server) linkedInExpiry() *Expiry { + if !s.Secrets.Has(secrets.LinkedInAccessToken) { + return nil + } + c := s.connections()["linkedin"] + at := c.Expires + if at.IsZero() { + if c.At.IsZero() { + return nil // a token from the old app: when it was made is unknown + } + at = c.At.Add(linkedInTokenLife) + } + return &Expiry{Network: "LinkedIn", At: at} +} + +// reminders are the sign-ins running out soon, or already, for the +// Overview and the Inbox. +func (s *Server) reminders() []Expiry { + if e := s.linkedInExpiry(); e != nil && e.Soon() { + return []Expiry{*e} + } + return nil } const connectionsKey = "connections" @@ -107,6 +158,7 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) { "ImportErr": errString(s.ImportErr), "QueuedPosts": queued, "Scheduled": len(scheduled), + "Reminders": s.reminders(), "Pending": pending, }}) } @@ -153,7 +205,9 @@ func (s *Server) connectionSummary(c map[string]Connection) string { } else if s.Secrets.Has(secrets.XAccessToken) { parts = append(parts, "X") } - if s.Secrets.Has(secrets.LinkedInAccessToken) { + if e := s.linkedInExpiry(); e != nil && e.Expired() { + parts = append(parts, "LinkedIn (expired)") + } else if s.Secrets.Has(secrets.LinkedInAccessToken) { parts = append(parts, "LinkedIn") } if a := c["reddit"].Account; a != "" { diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 74ef8bc..bcaeeb7 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -2,6 +2,7 @@ package web import ( "bytes" + "context" "encoding/json" "io" "log/slog" @@ -403,3 +404,43 @@ func TestProfileDraftNeedsAI(t *testing.T) { t.Error("warning shown with an AI key saved") } } + +func TestLinkedInExpiryReminders(t *testing.T) { + s, h := newTestServer(t, nil) + _ = s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: "tok", secrets.LinkedInAuthorURN: "urn:li:person:1"}) + day := 24 * time.Hour + get := func(path string) string { return do(h, http.MethodGet, path, nil, nil).Body.String() } + + // Plenty of time: the card says until when, no reminders. + _ = s.saveConnection("linkedin", Connection{At: time.Now(), Expires: time.Now().Add(50 * day)}) + if !strings.Contains(get("/settings/accounts"), "The sign-in lasts until") || strings.Contains(get("/"), "Reconnect LinkedIn") { + t.Error("50 days left: wrong reminders") + } + if !s.connected()["linkedin"] { + t.Error("50 days left: should be connected") + } + + // Saved before expiries were recorded, 50 days ago: 10 days left. + _ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-50 * day)}) + for _, path := range []string{"/", "/inbox"} { + if body := get(path); !strings.Contains(body, "LinkedIn's sign-in expires in 9 days") && !strings.Contains(body, "LinkedIn's sign-in expires in 10 days") { + t.Errorf("%s: no 10-day reminder", path) + } + } + + // Expired: reminders, not connected, and publishing says why. + _ = s.saveConnection("linkedin", Connection{At: time.Now().Add(-61 * day), Expires: time.Now().Add(-day)}) + if body := get("/"); !strings.Contains(body, "LinkedIn's sign-in expired on") { + t.Error("expired: no reminder on the Overview") + } + if !strings.Contains(get("/settings/accounts"), "The sign-in expired on") { + t.Error("expired: the card doesn't say so") + } + if s.connected()["linkedin"] { + t.Error("expired: still counted as connected") + } + if _, err := s.publishers()["linkedin"].Publish(context.Background(), content.Post{Text: "hi"}); err == nil || + !strings.Contains(err.Error(), "reconnect LinkedIn") { + t.Errorf("expired publish: %v", err) + } +} diff --git a/internal/web/settings.go b/internal/web/settings.go index 9162f72..01ad19b 100644 --- a/internal/web/settings.go +++ b/internal/web/settings.go @@ -228,6 +228,7 @@ type connectInfo struct { Account string At time.Time Note string + Expiry *Expiry // when the sign-in runs out, for LinkedIn } func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) { @@ -272,6 +273,7 @@ func (s *Server) networks() []network { case "LinkedIn": 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 "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.", @@ -444,7 +446,12 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) { fail("Signed in, but couldn't save the token: " + err.Error()) return } - if err := s.saveConnection("linkedin", Connection{Account: urn, At: time.Now()}); err != nil { + life := res.ExpiresIn + if life <= 0 { + life = linkedInTokenLife + } + now := time.Now() + if err := s.saveConnection("linkedin", Connection{Account: urn, At: now, Expires: now.Add(life)}); err != nil { s.Log.Error("saving connection", "err", err) } redirect(w, r, "/settings/accounts", "li-connected") diff --git a/internal/web/static/app.css b/internal/web/static/app.css index d03d358..4db7560 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -361,3 +361,7 @@ form.inline { display: inline-block; margin: 0 0 0.75rem; } /* A key's label, with where to get it */ .label-row { display: flex; align-items: baseline; gap: 0.75rem; } .get-it { margin-left: auto; font-size: 0.82rem; font-weight: 600; white-space: nowrap; } + +/* A sign-in running out */ +.reminder { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap; } +.reminder p { margin: 0; flex: 1; min-width: 16rem; } diff --git a/internal/web/templates/accounts.html b/internal/web/templates/accounts.html index db202b8..e9fc5cc 100644 --- a/internal/web/templates/accounts.html +++ b/internal/web/templates/accounts.html @@ -33,6 +33,11 @@
Connected{{with .Account}} as {{.}}{{end}}{{if not .At.IsZero}}, {{ago .At}}{{end}}.
{{end}} + {{with .Expiry}} + {{if .Expired}}The sign-in expired on {{.At.Local.Format "2 Jan 2006"}}: reconnect to publish again.
+ {{else if .Soon}}The sign-in expires {{if eq .Days 0}}today{{else if eq .Days 1}}tomorrow{{else}}in {{.Days}} days{{end}}, on {{.At.Local.Format "2 Jan 2006"}}. Reconnect now to keep posting.
+ {{else}}The sign-in lasts until {{.At.Local.Format "2 Jan 2006"}}; {{.Network}} doesn't let it be renewed without signing in again. Supermarket reminds you two weeks before.
{{end}} + {{end}}{{.Setup}} {{.Redirect}}{{with .Note}}
{{.}}{{end}}
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}}
+{{template "reminders" .Reminders}} + {{if .Sections}} {{range .Sections}}{{if .Expired}}{{.Network}}'s sign-in expired on {{.At.Local.Format "2 Jan 2006"}}.{{else}}{{.Network}}'s sign-in expires {{if eq .Days 0}}today{{else if eq .Days 1}}tomorrow{{else}}in {{.Days}} days{{end}}, on {{.At.Local.Format "2 Jan 2006"}}.{{end}} + {{if .Expired}}Nothing can be published to {{.Network}} until you reconnect; scheduled posts for it come back to the Inbox.{{else}}After that, nothing can be published to {{.Network}} until you reconnect.{{end}}
+ Reconnect {{.Network}} +