闭社主体 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.

71 lines
2.0 KiB

8 years ago
  1. require 'singleton'
  2. class FeedManager
  3. include Singleton
  4. MAX_ITEMS = 800
  5. def key(type, id)
  6. "feed:#{type}:#{id}"
  7. end
  8. def filter?(timeline_type, status, receiver)
  9. if timeline_type == :home
  10. filter_from_home?(status, receiver)
  11. else
  12. filter_from_mentions?(status, receiver)
  13. end
  14. end
  15. def push(timeline_type, account, status)
  16. redis.zadd(key(timeline_type, account.id), status.id, status.reblog? ? status.reblog_of_id : status.id)
  17. trim(timeline_type, account.id)
  18. broadcast(account.id, type: 'update', timeline: timeline_type, message: inline_render(account, status))
  19. end
  20. def broadcast(timeline_id, options = {})
  21. ActionCable.server.broadcast("timeline:#{timeline_id}", options)
  22. end
  23. def trim(type, account_id)
  24. return unless redis.zcard(key(type, account_id)) > FeedManager::MAX_ITEMS
  25. last = redis.zrevrange(key(type, account_id), FeedManager::MAX_ITEMS - 1, FeedManager::MAX_ITEMS - 1)
  26. redis.zremrangebyscore(key(type, account_id), '-inf', "(#{last.last}")
  27. end
  28. def inline_render(target_account, status)
  29. rabl_scope = Class.new do
  30. include RoutingHelper
  31. def initialize(account)
  32. @account = account
  33. end
  34. def current_user
  35. @account.try(:user)
  36. end
  37. def current_account
  38. @account
  39. end
  40. end
  41. Rabl::Renderer.new('api/v1/statuses/show', status, view_path: 'app/views', format: :json, scope: rabl_scope.new(target_account)).render
  42. end
  43. private
  44. def redis
  45. $redis
  46. end
  47. # Filter status out of the home feed if it is a reply to someone the user doesn't follow
  48. def filter_from_home?(status, receiver)
  49. replied_to_user = status.reply? ? status.thread.try(:account) : nil
  50. (status.reply? && !(receiver.id == replied_to_user.id || replied_to_user.id == status.account_id || receiver.following?(replied_to_user))) || (status.reblog? && receiver.blocking?(status.reblog.account))
  51. end
  52. def filter_from_mentions?(status, receiver)
  53. receiver.blocking?(status.account)
  54. end
  55. end