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.
 
 
 
 

62 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. class TrendingTags
  3. KEY = 'trending_tags'
  4. HALF_LIFE = 1.day.to_i
  5. MAX_ITEMS = 500
  6. EXPIRE_HISTORY_AFTER = 7.days.seconds
  7. class << self
  8. def record_use!(tag, account, at_time = Time.now.utc)
  9. return if disallowed_hashtags.include?(tag.name) || account.silenced?
  10. increment_vote!(tag.id, at_time)
  11. increment_historical_use!(tag.id, at_time)
  12. increment_unique_use!(tag.id, account.id, at_time)
  13. end
  14. def get(limit)
  15. tag_ids = redis.zrevrange(KEY, 0, limit).map(&:to_i)
  16. tags = Tag.where(id: tag_ids).to_a.map { |tag| [tag.id, tag] }.to_h
  17. tag_ids.map { |tag_id| tags[tag_id] }.compact
  18. end
  19. private
  20. def increment_vote!(tag_id, at_time)
  21. redis.zincrby(KEY, (2**((at_time.to_i - epoch) / HALF_LIFE)).to_f, tag_id.to_s)
  22. redis.zremrangebyrank(KEY, 0, -MAX_ITEMS) if rand < (2.to_f / MAX_ITEMS)
  23. end
  24. def increment_historical_use!(tag_id, at_time)
  25. key = "activity:tags:#{tag_id}:#{at_time.beginning_of_day.to_i}"
  26. redis.incrby(key, 1)
  27. redis.expire(key, EXPIRE_HISTORY_AFTER)
  28. end
  29. def increment_unique_use!(tag_id, account_id, at_time)
  30. key = "activity:tags:#{tag_id}:#{at_time.beginning_of_day.to_i}:accounts"
  31. redis.pfadd(key, account_id)
  32. redis.expire(key, EXPIRE_HISTORY_AFTER)
  33. end
  34. # The epoch needs to be 2.5 years in the future if the half-life is one day
  35. # While dynamic, it will always be the same within one year
  36. def epoch
  37. @epoch ||= Date.new(Date.current.year + 2.5, 10, 1).to_datetime.to_i
  38. end
  39. def disallowed_hashtags
  40. return @disallowed_hashtags if defined?(@disallowed_hashtags)
  41. @disallowed_hashtags = Setting.disallowed_hashtags.nil? ? [] : Setting.disallowed_hashtags
  42. @disallowed_hashtags = @disallowed_hashtags.split(' ') if @disallowed_hashtags.is_a? String
  43. @disallowed_hashtags = @disallowed_hashtags.map(&:downcase)
  44. end
  45. def redis
  46. Redis.current
  47. end
  48. end
  49. end