LinkedIn tokens last 60 days and can't be renewed without signing in again. The expiry LinkedIn reports is now recorded (60 days from sign-in for older connections). The LinkedIn card says until when; from two weeks before, the Overview, the Inbox and the card remind you, with a Reconnect button. Once expired, LinkedIn counts as not connected, due posts come back to the Inbox saying why, and a 401 from LinkedIn reads "reconnect LinkedIn" instead of the raw error. Also fixes a leftover "Settings → Credentials" in a publish error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
8.1 KiB
Go
249 lines
8.1 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"supermarket/internal/api/linkedin"
|
|
"supermarket/internal/api/reddit"
|
|
"supermarket/internal/api/rss"
|
|
"supermarket/internal/api/twitter"
|
|
"supermarket/internal/api/youtube"
|
|
"supermarket/internal/content"
|
|
"supermarket/internal/fetcher"
|
|
"supermarket/internal/oauth"
|
|
"supermarket/internal/secrets"
|
|
)
|
|
|
|
// fetchMaxResults is how many posts or videos one source returns per fetch.
|
|
const fetchMaxResults = 20
|
|
|
|
// fetcher builds a fetcher from the saved credentials.
|
|
func (s *Server) fetcher() *fetcher.Fetcher {
|
|
f := &fetcher.Fetcher{RSS: rss.New("Supermarket/" + s.Version + " (feed reader)")}
|
|
if tok := s.Secrets.Get(secrets.XBearerToken); tok != "" {
|
|
f.Twitter = twitter.New(tok, "", fetchMaxResults)
|
|
}
|
|
if key := s.Secrets.Get(secrets.YouTubeAPIKey); key != "" {
|
|
f.YouTube = youtube.New(key, fetchMaxResults)
|
|
}
|
|
return f
|
|
}
|
|
|
|
// publishers are the channels signed in for posting.
|
|
func (s *Server) publishers() content.Publishers {
|
|
pubs := content.Publishers{}
|
|
if tok := s.Secrets.Get(secrets.XAccessToken); tok != "" {
|
|
c := twitter.New("", tok, 0)
|
|
// X access tokens last two hours; refresh tokens are single-use, so
|
|
// each new one is saved before the old is gone.
|
|
if s.Secrets.Has(secrets.XRefreshToken) && s.Secrets.Has(secrets.XClientID) {
|
|
c.SetTokenRefresher(func(ctx context.Context) (string, string, error) {
|
|
res, err := oauth.RefreshX(ctx, s.Secrets.Get(secrets.XClientID),
|
|
s.Secrets.Get(secrets.XClientSecret), s.Secrets.Get(secrets.XRefreshToken))
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
updates := map[string]string{secrets.XAccessToken: res.AccessToken}
|
|
if res.RefreshToken != "" {
|
|
updates[secrets.XRefreshToken] = res.RefreshToken
|
|
}
|
|
if err := s.Secrets.Set(updates); err != nil {
|
|
// Keep going with the new token; the next start will need
|
|
// a new sign-in.
|
|
s.Log.Error("x: couldn't save the refreshed token; sign in to X again later", "err", err)
|
|
}
|
|
return res.AccessToken, res.RefreshToken, nil
|
|
})
|
|
}
|
|
pubs[content.ChannelX] = xPublisher{c}
|
|
}
|
|
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}
|
|
} else {
|
|
pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)}
|
|
}
|
|
}
|
|
if c := s.redditUser(); c != nil {
|
|
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
|
|
}
|
|
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
|
|
// it as a card.
|
|
func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
|
|
text := post.Text
|
|
if post.SourceURL != "" {
|
|
text += "\n\n" + post.SourceURL
|
|
}
|
|
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) {
|
|
return p.c.PostUpdate(ctx, post.Text, post.SourceURL)
|
|
}
|
|
|
|
type redditPublisher struct {
|
|
s *Server
|
|
c *reddit.Client
|
|
}
|
|
|
|
// Publish makes a text post with the source link at the end, or, where the
|
|
// subreddit only takes links, a link post of the title and the link.
|
|
func (p redditPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
|
|
info, _ := p.s.subreddit(ctx, post.Target, false)
|
|
if info != nil && !info.AllowsText() {
|
|
if post.SourceURL == "" {
|
|
return "", fmt.Errorf("r/%s only takes link posts, and this draft has no link", post.Target)
|
|
}
|
|
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, URL: post.SourceURL})
|
|
}
|
|
text := post.Text
|
|
if post.SourceURL != "" && !strings.Contains(text, post.SourceURL) {
|
|
text += "\n\nSource: " + post.SourceURL
|
|
}
|
|
return p.c.Submit(ctx, reddit.Post{Subreddit: post.Target, Title: post.Title, Text: text})
|
|
}
|
|
|
|
// --- Reddit ---
|
|
|
|
func (s *Server) redditUserAgent() string {
|
|
return reddit.UserAgent(s.Version, s.Secrets.Get(secrets.RedditUsername))
|
|
}
|
|
|
|
// redditUser is a client signed in as the user, or nil. Access tokens last
|
|
// an hour; a refused one is refreshed and saved.
|
|
func (s *Server) redditUser() *reddit.Client {
|
|
tok := s.Secrets.Get(secrets.RedditAccessToken)
|
|
if tok == "" {
|
|
return nil
|
|
}
|
|
return reddit.New(tok, s.redditUserAgent(), func(ctx context.Context) (string, error) {
|
|
res, err := oauth.RefreshReddit(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
|
|
s.redditUserAgent(), s.Secrets.Get(secrets.RedditRefreshToken))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
updates := map[string]string{secrets.RedditAccessToken: res.AccessToken}
|
|
if res.RefreshToken != "" {
|
|
updates[secrets.RedditRefreshToken] = res.RefreshToken
|
|
}
|
|
if err := s.Secrets.Set(updates); err != nil {
|
|
s.Log.Error("reddit: couldn't save the refreshed token", "err", err)
|
|
}
|
|
return res.AccessToken, nil
|
|
})
|
|
}
|
|
|
|
// redditReader reads subreddits: as the user if signed in, else as the
|
|
// app (with its client ID and secret), else nil.
|
|
func (s *Server) redditReader(ctx context.Context) (*reddit.Client, error) {
|
|
if c := s.redditUser(); c != nil {
|
|
return c, nil
|
|
}
|
|
id, secret := s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret)
|
|
if id == "" || secret == "" {
|
|
return nil, errors.New("add Reddit's client ID and secret under Settings → Social accounts to read subreddits")
|
|
}
|
|
s.mu.Lock()
|
|
tok, exp := s.redditAppToken, s.redditAppTokenExp
|
|
s.mu.Unlock()
|
|
if tok == "" || time.Now().After(exp) {
|
|
res, err := oauth.RedditAppToken(ctx, id, secret, s.redditUserAgent())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tok = res.AccessToken
|
|
s.mu.Lock()
|
|
// Reddit's app tokens last an hour; renew a little early.
|
|
s.redditAppToken, s.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
|
|
s.mu.Unlock()
|
|
}
|
|
return reddit.New(tok, s.redditUserAgent(), nil), nil
|
|
}
|
|
|
|
// subreddit returns a subreddit's rules: cached if fresh enough (or if
|
|
// fetching fails), fetched otherwise. refresh forces a fetch.
|
|
func (s *Server) subreddit(ctx context.Context, name string, refresh bool) (*reddit.Subreddit, error) {
|
|
name = reddit.CleanName(name)
|
|
cached, err := content.GetSubreddit(s.DB, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if cached != nil && !refresh && time.Since(cached.FetchedAt) < content.SubredditMaxAge {
|
|
return cached, nil
|
|
}
|
|
c, err := s.redditReader(ctx)
|
|
if err == nil {
|
|
var info *reddit.Subreddit
|
|
if info, err = c.SubredditInfo(ctx, name); err == nil {
|
|
if serr := content.SaveSubreddit(s.DB, info); serr != nil {
|
|
s.Log.Error("caching subreddit", "name", name, "err", serr)
|
|
}
|
|
return info, nil
|
|
}
|
|
}
|
|
if cached != nil {
|
|
return cached, nil // stale beats nothing
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
// redditHistoryTTL is how long the account's recent posts are kept in
|
|
// memory for the warnings.
|
|
const redditHistoryTTL = 10 * time.Minute
|
|
|
|
// redditHistory is the signed-in account's recent posts, or nil if they
|
|
// can't be read.
|
|
func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
|
|
user := s.Secrets.Get(secrets.RedditUsername)
|
|
c := s.redditUser()
|
|
if c == nil || user == "" {
|
|
return nil
|
|
}
|
|
s.mu.Lock()
|
|
h, at := s.redditHist, s.redditHistAt
|
|
s.mu.Unlock()
|
|
if h != nil && time.Since(at) < redditHistoryTTL {
|
|
return h
|
|
}
|
|
h, err := c.Submitted(ctx, user)
|
|
if err != nil {
|
|
s.Log.Warn("reddit: couldn't read the account's posts", "err", err)
|
|
return nil
|
|
}
|
|
if h == nil {
|
|
h = []reddit.Submission{}
|
|
}
|
|
s.mu.Lock()
|
|
s.redditHist, s.redditHistAt = h, time.Now()
|
|
s.mu.Unlock()
|
|
return h
|
|
}
|
|
|
|
// forgetRedditHistory drops the cached posts after posting.
|
|
func (s *Server) forgetRedditHistory() {
|
|
s.mu.Lock()
|
|
s.redditHist = nil
|
|
s.mu.Unlock()
|
|
}
|