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.
 
 
 
 

362 line
16 KiB

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