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.
 
 
 
 

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