90 lines
2.2 KiB
Go
90 lines
2.2 KiB
Go
package social
|
|
|
|
import (
|
|
"context"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// TrendingTag represents a hashtag with its occurrence count
|
|
type TrendingTag struct {
|
|
Tag string `json:"tag"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
// trendingHashtagRegex matches #word patterns in post content
|
|
var trendingHashtagRegex = regexp.MustCompile(`#(\w+)`)
|
|
|
|
const trendingCacheKey = "trending:hashtags"
|
|
const trendingCacheTTL = 15 * time.Minute
|
|
const trendingCacheLimit = 50
|
|
|
|
// GetTrendingHashtags extracts hashtags from recent posts and returns them sorted by count.
|
|
// Posts from the last 7 days are considered. Uses Redis cache if available (15 min TTL).
|
|
func (s *Service) GetTrendingHashtags(ctx context.Context, limit int) ([]TrendingTag, error) {
|
|
if limit <= 0 {
|
|
limit = 10
|
|
}
|
|
if limit > 50 {
|
|
limit = 50
|
|
}
|
|
|
|
// Try cache first (cache stores top 50, we slice to limit)
|
|
if s.cacheService != nil {
|
|
var cached []TrendingTag
|
|
if err := s.cacheService.Get(ctx, trendingCacheKey, &cached); err == nil {
|
|
if len(cached) >= limit {
|
|
return cached[:limit], nil
|
|
}
|
|
return cached, nil
|
|
}
|
|
}
|
|
|
|
var posts []Post
|
|
if err := s.db.WithContext(ctx).
|
|
Where("created_at > NOW() - INTERVAL '7 days'").
|
|
Where("deleted_at IS NULL").
|
|
Where("content != '' AND content IS NOT NULL").
|
|
Select("content").
|
|
Find(&posts).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
counts := make(map[string]int)
|
|
for _, p := range posts {
|
|
matches := trendingHashtagRegex.FindAllStringSubmatch(p.Content, -1)
|
|
for _, m := range matches {
|
|
if len(m) >= 2 {
|
|
tag := "#" + strings.ToLower(m[1])
|
|
counts[tag]++
|
|
}
|
|
}
|
|
}
|
|
|
|
var result []TrendingTag
|
|
for tag, count := range counts {
|
|
result = append(result, TrendingTag{Tag: tag, Count: count})
|
|
}
|
|
sort.Slice(result, func(i, j int) bool {
|
|
if result[i].Count != result[j].Count {
|
|
return result[i].Count > result[j].Count
|
|
}
|
|
return result[i].Tag < result[j].Tag
|
|
})
|
|
|
|
// Cache full result (top 50) for future requests
|
|
if s.cacheService != nil && len(result) > 0 {
|
|
toCache := result
|
|
if len(toCache) > trendingCacheLimit {
|
|
toCache = toCache[:trendingCacheLimit]
|
|
}
|
|
_ = s.cacheService.Set(ctx, trendingCacheKey, toCache, trendingCacheTTL)
|
|
}
|
|
|
|
if len(result) > limit {
|
|
result = result[:limit]
|
|
}
|
|
return result, nil
|
|
}
|