闭社主体 forked from https://github.com/tootsuite/mastodon
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.

58 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. class Feed
  3. def initialize(type, account)
  4. @type = type
  5. @account = account
  6. end
  7. def get(limit, max_id = nil, since_id = nil)
  8. max_id = '+inf' if max_id.blank?
  9. since_id = '-inf' if since_id.blank?
  10. unhydrated = redis.zrevrangebyscore(key, "(#{max_id}", "(#{since_id}", limit: [0, limit], with_scores: true).map(&:last).map(&:to_i)
  11. # If we're after most recent items and none are there, we need to precompute the feed
  12. if unhydrated.empty? && max_id == '+inf' && since_id == '-inf'
  13. RegenerationWorker.perform_async(@account.id, @type)
  14. @statuses = Status.send("as_#{@type}_timeline", @account).paginate_by_max_id(limit, nil, nil)
  15. else
  16. status_map = cache(unhydrated)
  17. @statuses = unhydrated.map { |id| status_map[id] }.compact
  18. end
  19. @statuses
  20. end
  21. private
  22. def cache(ids)
  23. raw = Status.where(id: ids).to_a
  24. uncached_ids = []
  25. cached_keys_with_value = Rails.cache.read_multi(*raw.map(&:cache_key))
  26. raw.each do |status|
  27. uncached_ids << status.id unless cached_keys_with_value.key?(status.cache_key)
  28. end
  29. unless uncached_ids.empty?
  30. uncached = Status.where(id: uncached_ids).with_includes.map { |s| [s.id, s] }.to_h
  31. uncached.values.each do |status|
  32. Rails.cache.write(status.cache_key, status)
  33. end
  34. end
  35. cached = cached_keys_with_value.values.map { |s| [s.id, s] }.to_h
  36. cached.merge!(uncached) unless uncached_ids.empty?
  37. cached
  38. end
  39. def key
  40. FeedManager.instance.key(@type, @account.id)
  41. end
  42. def redis
  43. Redis.current
  44. end
  45. end