The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

68 line
2.2 KiB

  1. # frozen_string_literal: true
  2. class TrendingTags
  3. KEY = 'trending_tags'
  4. EXPIRE_HISTORY_AFTER = 7.days.seconds
  5. EXPIRE_TRENDS_AFTER = 1.day.seconds
  6. THRESHOLD = 5
  7. class << self
  8. def record_use!(tag, account, at_time = Time.now.utc)
  9. return if disallowed_hashtags.include?(tag.name) || account.silenced? || account.bot?
  10. increment_historical_use!(tag.id, at_time)
  11. increment_unique_use!(tag.id, account.id, at_time)
  12. increment_vote!(tag.id, at_time)
  13. end
  14. def get(limit)
  15. key = "#{KEY}:#{Time.now.utc.beginning_of_day.to_i}"
  16. tag_ids = redis.zrevrange(key, 0, limit - 1).map(&:to_i)
  17. tags = Tag.where(id: tag_ids).to_a.map { |tag| [tag.id, tag] }.to_h
  18. tag_ids.map { |tag_id| tags[tag_id] }.compact
  19. end
  20. private
  21. def increment_historical_use!(tag_id, at_time)
  22. key = "activity:tags:#{tag_id}:#{at_time.beginning_of_day.to_i}"
  23. redis.incrby(key, 1)
  24. redis.expire(key, EXPIRE_HISTORY_AFTER)
  25. end
  26. def increment_unique_use!(tag_id, account_id, at_time)
  27. key = "activity:tags:#{tag_id}:#{at_time.beginning_of_day.to_i}:accounts"
  28. redis.pfadd(key, account_id)
  29. redis.expire(key, EXPIRE_HISTORY_AFTER)
  30. end
  31. def increment_vote!(tag_id, at_time)
  32. key = "#{KEY}:#{at_time.beginning_of_day.to_i}"
  33. expected = redis.pfcount("activity:tags:#{tag_id}:#{(at_time - 1.day).beginning_of_day.to_i}:accounts").to_f
  34. expected = 1.0 if expected.zero?
  35. observed = redis.pfcount("activity:tags:#{tag_id}:#{at_time.beginning_of_day.to_i}:accounts").to_f
  36. if expected > observed || observed < THRESHOLD
  37. redis.zrem(key, tag_id.to_s)
  38. else
  39. score = ((observed - expected)**2) / expected
  40. redis.zadd(key, score, tag_id.to_s)
  41. end
  42. redis.expire(key, EXPIRE_TRENDS_AFTER)
  43. end
  44. def disallowed_hashtags
  45. return @disallowed_hashtags if defined?(@disallowed_hashtags)
  46. @disallowed_hashtags = Setting.disallowed_hashtags.nil? ? [] : Setting.disallowed_hashtags
  47. @disallowed_hashtags = @disallowed_hashtags.split(' ') if @disallowed_hashtags.is_a? String
  48. @disallowed_hashtags = @disallowed_hashtags.map(&:downcase)
  49. end
  50. def redis
  51. Redis.current
  52. end
  53. end
  54. end