apollo-backend/internal/worker/trending.go

288 lines
7.9 KiB
Go
Raw Permalink Normal View History

2021-10-10 15:51:42 +00:00
package worker
import (
"context"
"fmt"
2022-05-26 22:56:53 +00:00
"math/rand"
2021-10-10 15:51:42 +00:00
"os"
2022-05-26 22:17:49 +00:00
"sort"
2021-10-10 15:51:42 +00:00
"time"
"github.com/DataDog/datadog-go/statsd"
"github.com/go-redis/redis/v8"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/sideshow/apns2"
"github.com/sideshow/apns2/payload"
"github.com/sideshow/apns2/token"
2022-05-23 18:17:25 +00:00
"go.uber.org/zap"
2021-10-10 15:51:42 +00:00
"github.com/christianselig/apollo-backend/internal/domain"
"github.com/christianselig/apollo-backend/internal/reddit"
"github.com/christianselig/apollo-backend/internal/repository"
)
type trendingWorker struct {
2022-05-23 18:17:25 +00:00
logger *zap.Logger
2021-10-10 15:51:42 +00:00
statsd *statsd.Client
redis *redis.Client
reddit *reddit.Client
2022-11-02 04:49:20 +00:00
apns *apns2.Client
2021-10-10 15:51:42 +00:00
accountRepo domain.AccountRepository
deviceRepo domain.DeviceRepository
subredditRepo domain.SubredditRepository
watcherRepo domain.WatcherRepository
}
2022-05-01 17:04:05 +00:00
const trendingNotificationTitleFormat = "🔥 r/%s Trending"
2021-10-10 15:51:42 +00:00
2022-11-02 04:49:20 +00:00
func NewTrendingWorker(ctx context.Context, logger *zap.Logger, statsd *statsd.Client, db *pgxpool.Pool, redis *redis.Client, consumers int) Worker {
2021-10-10 15:51:42 +00:00
reddit := reddit.NewClient(
os.Getenv("REDDIT_CLIENT_ID"),
os.Getenv("REDDIT_CLIENT_SECRET"),
statsd,
2022-03-12 17:50:05 +00:00
redis,
2021-10-10 15:51:42 +00:00
consumers,
)
2022-11-02 04:49:20 +00:00
var apns *apns2.Client
2021-10-10 15:51:42 +00:00
{
authKey, err := token.AuthKeyFromFile(os.Getenv("APPLE_KEY_PATH"))
if err != nil {
panic(err)
}
2022-11-02 04:49:20 +00:00
tok := &token.Token{
2021-10-10 15:51:42 +00:00
AuthKey: authKey,
KeyID: os.Getenv("APPLE_KEY_ID"),
TeamID: os.Getenv("APPLE_TEAM_ID"),
}
2022-11-02 04:49:20 +00:00
apns = apns2.NewTokenClient(tok).Production()
2021-10-10 15:51:42 +00:00
}
return &trendingWorker{
logger,
statsd,
redis,
reddit,
apns,
repository.NewPostgresAccount(db),
repository.NewPostgresDevice(db),
repository.NewPostgresSubreddit(db),
repository.NewPostgresWatcher(db),
}
}
2022-11-02 04:49:20 +00:00
func (tw *trendingWorker) Process(ctx context.Context, args ...interface{}) error {
2022-11-02 05:11:49 +00:00
id := int64(args[0].(float64))
2022-11-02 04:49:20 +00:00
tw.logger.Debug("starting job", zap.Int64("subreddit#id", id))
2021-10-10 15:51:42 +00:00
2022-11-02 04:49:20 +00:00
subreddit, err := tw.subredditRepo.GetByID(ctx, id)
2021-10-10 15:51:42 +00:00
if err != nil {
2022-11-02 04:49:20 +00:00
tw.logger.Error("failed to fetch subreddit from database", zap.Error(err), zap.Int64("subreddit#id", id))
return nil
2021-10-10 15:51:42 +00:00
}
2022-11-02 04:49:20 +00:00
watchers, err := tw.watcherRepo.GetByTrendingSubredditID(ctx, subreddit.ID)
2021-10-10 15:51:42 +00:00
if err != nil {
2022-11-02 04:49:20 +00:00
tw.logger.Error("failed to fetch watchers from database",
2022-05-23 18:17:25 +00:00
zap.Error(err),
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 04:49:20 +00:00
return err
2021-10-10 15:51:42 +00:00
}
if len(watchers) == 0 {
2022-11-02 04:49:20 +00:00
tw.logger.Debug("no watchers for subreddit, bailing early",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 04:49:20 +00:00
return nil
2021-10-10 15:51:42 +00:00
}
2022-05-26 22:56:53 +00:00
// Grab last month's top posts so we calculate a trending average
i := rand.Intn(len(watchers))
watcher := watchers[i]
2022-11-02 04:49:20 +00:00
rac := tw.reddit.NewAuthenticatedClient(watcher.Account.AccountID, watcher.Account.RefreshToken, watcher.Account.AccessToken)
2022-05-26 22:56:53 +00:00
2022-10-27 00:46:17 +00:00
tps, err := rac.SubredditTop(ctx, subreddit.Name, reddit.WithQuery("t", "week"), reddit.WithQuery("show", "all"), reddit.WithQuery("limit", "25"))
2021-10-10 15:51:42 +00:00
if err != nil {
2022-11-02 04:49:20 +00:00
tw.logger.Error("failed to fetch weeks's top posts",
2022-05-23 18:17:25 +00:00
zap.Error(err),
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 05:32:42 +00:00
return nil
2021-10-10 15:51:42 +00:00
}
2022-05-23 18:17:25 +00:00
2022-11-02 04:49:20 +00:00
tw.logger.Debug("loaded weeks's top posts",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int("count", tps.Count),
)
2021-10-10 15:51:42 +00:00
if tps.Count == 0 {
2022-11-02 04:49:20 +00:00
tw.logger.Debug("no top posts, bailing early",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 04:49:20 +00:00
return nil
2021-10-10 15:51:42 +00:00
}
if tps.Count < 20 {
2022-11-02 04:49:20 +00:00
tw.logger.Debug("no top posts, bailing early",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int("count", tps.Count),
)
2022-11-02 04:49:20 +00:00
return nil
2021-10-10 15:51:42 +00:00
}
2022-05-26 22:17:49 +00:00
sort.SliceStable(tps.Children, func(i, j int) bool {
return tps.Children[i].Score > tps.Children[j].Score
})
2021-10-10 15:51:42 +00:00
middlePost := tps.Count / 2
medianScore := tps.Children[middlePost].Score
2022-11-02 04:49:20 +00:00
tw.logger.Debug("calculated median score",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int64("score", medianScore),
)
2021-10-10 15:51:42 +00:00
2022-05-26 22:56:53 +00:00
// Grab hot posts and filter out anything that's > 2 days old
i = rand.Intn(len(watchers))
watcher = watchers[i]
2022-11-02 04:49:20 +00:00
rac = tw.reddit.NewAuthenticatedClient(watcher.Account.AccountID, watcher.Account.RefreshToken, watcher.Account.AccessToken)
2022-07-04 13:49:30 +00:00
2022-10-27 00:46:17 +00:00
hps, err := rac.SubredditHot(ctx, subreddit.Name, reddit.WithQuery("show", "all"), reddit.WithQuery("always_show_media", "1"))
2021-10-10 15:51:42 +00:00
if err != nil {
2022-11-02 04:49:20 +00:00
tw.logger.Error("failed to fetch hot posts",
2022-05-23 18:17:25 +00:00
zap.Error(err),
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 04:49:20 +00:00
return err
2021-10-10 15:51:42 +00:00
}
2022-11-02 04:49:20 +00:00
tw.logger.Debug("loaded hot posts",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int("count", hps.Count),
)
2021-10-10 15:51:42 +00:00
// Trending only counts for posts less than 2 days old
2022-03-28 21:05:01 +00:00
threshold := time.Now().Add(-24 * time.Hour * 2)
2021-10-10 15:51:42 +00:00
for _, post := range hps.Children {
if post.Score < medianScore {
continue
}
2022-03-28 21:05:01 +00:00
if post.CreatedAt.Before(threshold) {
2021-10-10 15:51:42 +00:00
break
}
notification := &apns2.Notification{}
notification.Topic = "com.christianselig.Apollo"
notification.Payload = payloadFromTrendingPost(post)
for _, watcher := range watchers {
2022-03-28 21:05:01 +00:00
if watcher.CreatedAt.After(post.CreatedAt) {
2021-10-10 15:51:42 +00:00
continue
}
lockKey := fmt.Sprintf("watcher:trending:%d:%s", watcher.DeviceID, post.ID)
2022-11-02 04:49:20 +00:00
notified, _ := tw.redis.Get(ctx, lockKey).Bool()
2021-10-10 15:51:42 +00:00
if notified {
2022-11-02 04:49:20 +00:00
tw.logger.Debug("already notified, skipping",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int64("watcher#id", watcher.ID),
zap.String("post#id", post.ID),
)
2021-10-10 15:51:42 +00:00
continue
}
2022-11-02 04:49:20 +00:00
tw.redis.SetEX(ctx, lockKey, true, 48*time.Hour)
2021-10-10 15:51:42 +00:00
2022-11-02 04:49:20 +00:00
if err := tw.watcherRepo.IncrementHits(ctx, watcher.ID); err != nil {
tw.logger.Error("could not increment hits",
2022-05-23 18:17:25 +00:00
zap.Error(err),
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.Int64("watcher#id", watcher.ID),
)
2022-11-02 04:49:20 +00:00
return err
2021-10-10 15:51:42 +00:00
}
notification.DeviceToken = watcher.Device.APNSToken
2022-11-02 04:49:20 +00:00
res, err := tw.apns.Push(notification)
if err != nil {
2022-11-02 04:49:20 +00:00
_ = tw.statsd.Incr("apns.notification.errors", []string{}, 1)
tw.logger.Error("failed to send notification",
2022-05-23 18:17:25 +00:00
zap.Error(err),
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.String("post#id", post.ID),
zap.String("apns", watcher.Device.APNSToken),
)
} else if !res.Sent() {
2022-11-02 04:49:20 +00:00
_ = tw.statsd.Incr("apns.notification.errors", []string{}, 1)
tw.logger.Error("notification not sent",
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.String("post#id", post.ID),
zap.String("apns", watcher.Device.APNSToken),
2022-05-23 18:17:25 +00:00
zap.Int("response#status", res.StatusCode),
zap.String("response#reason", res.Reason),
)
2021-10-10 15:51:42 +00:00
} else {
2022-11-02 04:49:20 +00:00
_ = tw.statsd.Incr("apns.notification.sent", []string{}, 1)
tw.logger.Info("sent notification",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
zap.String("post#id", post.ID),
2022-05-25 20:05:49 +00:00
zap.Int64("post#score", post.Score),
2022-05-23 18:17:25 +00:00
zap.String("device#token", watcher.Device.APNSToken),
)
2021-10-10 15:51:42 +00:00
}
}
}
2022-11-02 04:49:20 +00:00
tw.logger.Debug("finishing job",
2022-05-23 18:17:25 +00:00
zap.Int64("subreddit#id", id),
zap.String("subreddit#name", subreddit.NormalizedName()),
)
2022-11-02 04:49:20 +00:00
return nil
2021-10-10 15:51:42 +00:00
}
func payloadFromTrendingPost(post *reddit.Thing) *payload.Payload {
title := fmt.Sprintf(trendingNotificationTitleFormat, post.Subreddit)
payload := payload.
NewPayload().
AlertTitle(title).
AlertBody(post.Title).
AlertSummaryArg(post.Subreddit).
Category("trending-post").
2021-10-10 15:51:42 +00:00
Custom("post_title", post.Title).
Custom("post_id", post.ID).
Custom("subreddit", post.Subreddit).
Custom("author", post.Author).
Custom("post_age", post.CreatedAt).
2022-05-01 17:36:35 +00:00
ThreadID("trending-post").
2021-10-10 15:51:42 +00:00
MutableContent().
Sound("traloop.wav")
if post.Thumbnail != "" && !post.Over18 {
2022-05-01 17:33:09 +00:00
payload.Custom("thumbnail", post.Thumbnail)
}
2021-10-10 15:51:42 +00:00
return payload
}