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.
 
 
 
 

290 lines
12 KiB

  1. # frozen_string_literal: true
  2. require 'singleton'
  3. class FeedManager
  4. include Singleton
  5. MAX_ITEMS = 400
  6. # Must be <= MAX_ITEMS or the tracking sets will grow forever
  7. REBLOG_FALLOFF = 40
  8. def key(type, id, subtype = nil)
  9. return "feed:#{type}:#{id}" unless subtype
  10. "feed:#{type}:#{id}:#{subtype}"
  11. end
  12. def filter?(timeline_type, status, receiver_id)
  13. if timeline_type == :home
  14. filter_from_home?(status, receiver_id)
  15. elsif timeline_type == :mentions
  16. filter_from_mentions?(status, receiver_id)
  17. else
  18. false
  19. end
  20. end
  21. def push_to_home(account, status)
  22. return false unless add_to_feed(:home, account.id, status)
  23. trim(:home, account.id)
  24. PushUpdateWorker.perform_async(account.id, status.id, "timeline:#{account.id}") if push_update_required?("timeline:#{account.id}")
  25. true
  26. end
  27. def unpush_from_home(account, status)
  28. return false unless remove_from_feed(:home, account.id, status)
  29. Redis.current.publish("timeline:#{account.id}", Oj.dump(event: :delete, payload: status.id.to_s))
  30. true
  31. end
  32. def push_to_list(list, status)
  33. return false unless add_to_feed(:list, list.id, status)
  34. trim(:list, list.id)
  35. PushUpdateWorker.perform_async(list.account_id, status.id, "timeline:list:#{list.id}") if push_update_required?("timeline:list:#{list.id}")
  36. true
  37. end
  38. def unpush_from_list(list, status)
  39. return false unless remove_from_feed(:list, list.id, status)
  40. Redis.current.publish("timeline:list:#{list.id}", Oj.dump(event: :delete, payload: status.id.to_s))
  41. true
  42. end
  43. def trim(type, account_id)
  44. timeline_key = key(type, account_id)
  45. reblog_key = key(type, account_id, 'reblogs')
  46. # Remove any items past the MAX_ITEMS'th entry in our feed
  47. redis.zremrangebyrank(timeline_key, '0', (-(FeedManager::MAX_ITEMS + 1)).to_s)
  48. # Get the score of the REBLOG_FALLOFF'th item in our feed, and stop
  49. # tracking anything after it for deduplication purposes.
  50. falloff_rank = FeedManager::REBLOG_FALLOFF - 1
  51. falloff_range = redis.zrevrange(timeline_key, falloff_rank, falloff_rank, with_scores: true)
  52. falloff_score = falloff_range&.first&.last&.to_i || 0
  53. # Get any reblogs we might have to clean up after.
  54. redis.zrangebyscore(reblog_key, 0, falloff_score).each do |reblogged_id|
  55. # Remove it from the set of reblogs we're tracking *first* to avoid races.
  56. redis.zrem(reblog_key, reblogged_id)
  57. # Just drop any set we might have created to track additional reblogs.
  58. # This means that if this reblog is deleted, we won't automatically insert
  59. # another reblog, but also that any new reblog can be inserted into the
  60. # feed.
  61. redis.del(key(type, account_id, "reblogs:#{reblogged_id}"))
  62. end
  63. end
  64. def merge_into_timeline(from_account, into_account)
  65. timeline_key = key(:home, into_account.id)
  66. query = from_account.statuses.limit(FeedManager::MAX_ITEMS / 4)
  67. if redis.zcard(timeline_key) >= FeedManager::MAX_ITEMS / 4
  68. oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true)&.first&.last&.to_i || 0
  69. query = query.where('id > ?', oldest_home_score)
  70. end
  71. query.each do |status|
  72. next if status.direct_visibility? || filter?(:home, status, into_account)
  73. add_to_feed(:home, into_account.id, status)
  74. end
  75. trim(:home, into_account.id)
  76. end
  77. def unmerge_from_timeline(from_account, into_account)
  78. timeline_key = key(:home, into_account.id)
  79. oldest_home_score = redis.zrange(timeline_key, 0, 0, with_scores: true)&.first&.last&.to_i || 0
  80. from_account.statuses.select('id, reblog_of_id').where('id > ?', oldest_home_score).reorder(nil).find_each do |status|
  81. remove_from_feed(:home, into_account.id, status)
  82. end
  83. end
  84. def clear_from_timeline(account, target_account)
  85. timeline_key = key(:home, account.id)
  86. timeline_status_ids = redis.zrange(timeline_key, 0, -1)
  87. target_statuses = Status.where(id: timeline_status_ids, account: target_account)
  88. target_statuses.each do |status|
  89. unpush_from_home(account, status)
  90. end
  91. end
  92. def populate_feed(account)
  93. added = 0
  94. limit = FeedManager::MAX_ITEMS / 2
  95. max_id = nil
  96. loop do
  97. statuses = Status.as_home_timeline(account)
  98. .paginate_by_max_id(limit, max_id)
  99. break if statuses.empty?
  100. statuses.each do |status|
  101. next if filter_from_home?(status, account)
  102. added += 1 if add_to_feed(:home, account.id, status)
  103. end
  104. break unless added.zero?
  105. max_id = statuses.last.id
  106. end
  107. end
  108. private
  109. def redis
  110. Redis.current
  111. end
  112. def push_update_required?(timeline_id)
  113. redis.exists("subscribed:#{timeline_id}")
  114. end
  115. def blocks_or_mutes?(receiver_id, account_ids, context)
  116. Block.where(account_id: receiver_id, target_account_id: account_ids).any? ||
  117. (context == :home ? Mute.where(account_id: receiver_id, target_account_id: account_ids).any? : Mute.where(account_id: receiver_id, target_account_id: account_ids, hide_notifications: true).any?)
  118. end
  119. def filter_from_home?(status, receiver_id)
  120. return false if receiver_id == status.account_id
  121. return true if status.reply? && (status.in_reply_to_id.nil? || status.in_reply_to_account_id.nil?)
  122. return true if phrase_filtered?(status, receiver_id, :home)
  123. check_for_blocks = status.mentions.pluck(:account_id)
  124. check_for_blocks.concat([status.account_id])
  125. check_for_blocks.concat([status.reblog.account_id]) if status.reblog?
  126. return true if blocks_or_mutes?(receiver_id, check_for_blocks, :home)
  127. if status.reply? && !status.in_reply_to_account_id.nil? # Filter out if it's a reply
  128. should_filter = !Follow.where(account_id: receiver_id, target_account_id: status.in_reply_to_account_id).exists? # and I'm not following the person it's a reply to
  129. should_filter &&= receiver_id != status.in_reply_to_account_id # and it's not a reply to me
  130. should_filter &&= status.account_id != status.in_reply_to_account_id # and it's not a self-reply
  131. return should_filter
  132. elsif status.reblog? # Filter out a reblog
  133. should_filter = Follow.where(account_id: receiver_id, target_account_id: status.account_id, show_reblogs: false).exists? # if the reblogger's reblogs are suppressed
  134. should_filter ||= Block.where(account_id: status.reblog.account_id, target_account_id: receiver_id).exists? # or if the author of the reblogged status is blocking me
  135. should_filter ||= AccountDomainBlock.where(account_id: receiver_id, domain: status.reblog.account.domain).exists? # or the author's domain is blocked
  136. return should_filter
  137. end
  138. false
  139. end
  140. def filter_from_mentions?(status, receiver_id)
  141. return true if receiver_id == status.account_id
  142. return true if phrase_filtered?(status, receiver_id, :notifications)
  143. # This filter is called from NotifyService, but already after the sender of
  144. # the notification has been checked for mute/block. Therefore, it's not
  145. # necessary to check the author of the toot for mute/block again
  146. check_for_blocks = status.mentions.pluck(:account_id)
  147. check_for_blocks.concat([status.in_reply_to_account]) if status.reply? && !status.in_reply_to_account_id.nil?
  148. should_filter = blocks_or_mutes?(receiver_id, check_for_blocks, :mentions) # Filter if it's from someone I blocked, in reply to someone I blocked, or mentioning someone I blocked (or muted)
  149. should_filter ||= (status.account.silenced? && !Follow.where(account_id: receiver_id, target_account_id: status.account_id).exists?) # of if the account is silenced and I'm not following them
  150. should_filter
  151. end
  152. def phrase_filtered?(status, receiver_id, context)
  153. active_filters = Rails.cache.fetch("filters:#{receiver_id}") { CustomFilter.where(account_id: receiver_id).active_irreversible.to_a }.to_a
  154. active_filters.select! { |filter| filter.context.include?(context.to_s) && !filter.expired? }
  155. active_filters.map! { |filter| Regexp.new(Regexp.escape(filter.phrase), true) }
  156. return false if active_filters.empty?
  157. combined_regex = active_filters.reduce { |memo, obj| Regexp.union(memo, obj) }
  158. !combined_regex.match(status.text).nil? ||
  159. (status.spoiler_text.present? && !combined_regex.match(status.spoiler_text).nil?)
  160. end
  161. # Adds a status to an account's feed, returning true if a status was
  162. # added, and false if it was not added to the feed. Note that this is
  163. # an internal helper: callers must call trim or push updates if
  164. # either action is appropriate.
  165. def add_to_feed(timeline_type, account_id, status)
  166. timeline_key = key(timeline_type, account_id)
  167. reblog_key = key(timeline_type, account_id, 'reblogs')
  168. if status.reblog?
  169. # If the original status or a reblog of it is within
  170. # REBLOG_FALLOFF statuses from the top, do not re-insert it into
  171. # the feed
  172. rank = redis.zrevrank(timeline_key, status.reblog_of_id)
  173. return false if !rank.nil? && rank < FeedManager::REBLOG_FALLOFF
  174. reblog_rank = redis.zrevrank(reblog_key, status.reblog_of_id)
  175. if reblog_rank.nil?
  176. # This is not something we've already seen reblogged, so we
  177. # can just add it to the feed (and note that we're
  178. # reblogging it).
  179. redis.zadd(timeline_key, status.id, status.id)
  180. redis.zadd(reblog_key, status.id, status.reblog_of_id)
  181. else
  182. # Another reblog of the same status was already in the
  183. # REBLOG_FALLOFF most recent statuses, so we note that this
  184. # is an "extra" reblog, by storing it in reblog_set_key.
  185. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  186. redis.sadd(reblog_set_key, status.id)
  187. return false
  188. end
  189. else
  190. # A reblog may reach earlier than the original status because of the
  191. # delay of the worker deliverying the original status, the late addition
  192. # by merging timelines, and other reasons.
  193. # If such a reblog already exists, just do not re-insert it into the feed.
  194. rank = redis.zrevrank(reblog_key, status.id)
  195. return false unless rank.nil?
  196. redis.zadd(timeline_key, status.id, status.id)
  197. end
  198. true
  199. end
  200. # Removes an individual status from a feed, correctly handling cases
  201. # with reblogs, and returning true if a status was removed. As with
  202. # `add_to_feed`, this does not trigger push updates, so callers must
  203. # do so if appropriate.
  204. def remove_from_feed(timeline_type, account_id, status)
  205. timeline_key = key(timeline_type, account_id)
  206. if status.reblog?
  207. # 1. If the reblogging status is not in the feed, stop.
  208. status_rank = redis.zrevrank(timeline_key, status.id)
  209. return false if status_rank.nil?
  210. # 2. Remove reblog from set of this status's reblogs.
  211. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  212. redis.srem(reblog_set_key, status.id)
  213. # 3. Re-insert another reblog or original into the feed if one
  214. # remains in the set. We could pick a random element, but this
  215. # set should generally be small, and it seems ideal to show the
  216. # oldest potential such reblog.
  217. other_reblog = redis.smembers(reblog_set_key).map(&:to_i).sort.first
  218. redis.zadd(timeline_key, other_reblog, other_reblog) if other_reblog
  219. # 4. Remove the reblogging status from the feed (as normal)
  220. # (outside conditional)
  221. else
  222. # If the original is getting deleted, no use for reblog references
  223. redis.del(key(timeline_type, account_id, "reblogs:#{status.id}"))
  224. end
  225. redis.zrem(timeline_key, status.id)
  226. end
  227. end