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" "supermarket/internal/site" ) // 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 } // 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 "", p.err() } func (p expiredPublisher) err() 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) } // Publish attaches the source link as an article preview. func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) { c := p.me switch { case post.AsPage && p.pageErr != nil: return "", p.pageErr case post.AsPage && p.page == nil: return "", errNoPage case post.AsPage: c = p.page case p.meErr != nil: return "", p.meErr case p.me == nil: return "", errNoMe } if post.SourceURL == "" { return c.PostUpdate(ctx, post.Text, nil) } // LinkedIn wants the card's title from us. A page that can't be read // still gets a card, titled with its address. link := &linkedin.Link{URL: post.SourceURL} ictx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)") return c.PostUpdate(ctx, post.Text, link) } 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 { name := "" if a := s.companyReddit(); a != nil { name = a.External } return reddit.UserAgent(s.Version, name) } // redditUser is a client signed in as the company's Reddit account, or nil. func (s *Server) redditUser() *reddit.Client { a := s.companyReddit() if a == nil { return nil } return s.redditClient(a) } // 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 { a := s.companyReddit() if a == nil || a.External == "" { return nil } user, c := a.External, s.redditClient(a) 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() }