package web import ( "context" "supermarket/internal/api/linkedin" "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 != "" { pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)} } return pubs } 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, text, sourceURL string) (string, error) { if sourceURL != "" { text += "\n\n" + 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, text, sourceURL string) (string, error) { return p.c.PostUpdate(ctx, text, sourceURL) }