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.
 
 
 
 

305 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. if status.reblog?
  126. check_for_blocks.concat([status.reblog.account_id])
  127. check_for_blocks.concat(status.reblog.mentions.pluck(:account_id))
  128. end
  129. return true if blocks_or_mutes?(receiver_id, check_for_blocks, :home)
  130. if status.reply? && !status.in_reply_to_account_id.nil? # Filter out if it's a reply
  131. 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
  132. should_filter &&= receiver_id != status.in_reply_to_account_id # and it's not a reply to me
  133. should_filter &&= status.account_id != status.in_reply_to_account_id # and it's not a self-reply
  134. return should_filter
  135. elsif status.reblog? # Filter out a reblog
  136. 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
  137. 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
  138. should_filter ||= AccountDomainBlock.where(account_id: receiver_id, domain: status.reblog.account.domain).exists? # or the author's domain is blocked
  139. return should_filter
  140. end
  141. false
  142. end
  143. def filter_from_mentions?(status, receiver_id)
  144. return true if receiver_id == status.account_id
  145. return true if phrase_filtered?(status, receiver_id, :notifications)
  146. # This filter is called from NotifyService, but already after the sender of
  147. # the notification has been checked for mute/block. Therefore, it's not
  148. # necessary to check the author of the toot for mute/block again
  149. check_for_blocks = status.mentions.pluck(:account_id)
  150. check_for_blocks.concat([status.in_reply_to_account]) if status.reply? && !status.in_reply_to_account_id.nil?
  151. 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)
  152. 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
  153. should_filter
  154. end
  155. def phrase_filtered?(status, receiver_id, context)
  156. active_filters = Rails.cache.fetch("filters:#{receiver_id}") { CustomFilter.where(account_id: receiver_id).active_irreversible.to_a }.to_a
  157. active_filters.select! { |filter| filter.context.include?(context.to_s) && !filter.expired? }
  158. active_filters.map! do |filter|
  159. if filter.whole_word
  160. sb = filter.phrase =~ /\A[[:word:]]/ ? '\b' : ''
  161. eb = filter.phrase =~ /[[:word:]]\z/ ? '\b' : ''
  162. /(?mix:#{sb}#{Regexp.escape(filter.phrase)}#{eb})/
  163. else
  164. /#{Regexp.escape(filter.phrase)}/i
  165. end
  166. end
  167. return false if active_filters.empty?
  168. combined_regex = active_filters.reduce { |memo, obj| Regexp.union(memo, obj) }
  169. status = status.reblog if status.reblog?
  170. !combined_regex.match(Formatter.instance.plaintext(status)).nil? ||
  171. (status.spoiler_text.present? && !combined_regex.match(status.spoiler_text).nil?)
  172. end
  173. # Adds a status to an account's feed, returning true if a status was
  174. # added, and false if it was not added to the feed. Note that this is
  175. # an internal helper: callers must call trim or push updates if
  176. # either action is appropriate.
  177. def add_to_feed(timeline_type, account_id, status)
  178. timeline_key = key(timeline_type, account_id)
  179. reblog_key = key(timeline_type, account_id, 'reblogs')
  180. if status.reblog?
  181. # If the original status or a reblog of it is within
  182. # REBLOG_FALLOFF statuses from the top, do not re-insert it into
  183. # the feed
  184. rank = redis.zrevrank(timeline_key, status.reblog_of_id)
  185. return false if !rank.nil? && rank < FeedManager::REBLOG_FALLOFF
  186. reblog_rank = redis.zrevrank(reblog_key, status.reblog_of_id)
  187. if reblog_rank.nil?
  188. # This is not something we've already seen reblogged, so we
  189. # can just add it to the feed (and note that we're
  190. # reblogging it).
  191. redis.zadd(timeline_key, status.id, status.id)
  192. redis.zadd(reblog_key, status.id, status.reblog_of_id)
  193. else
  194. # Another reblog of the same status was already in the
  195. # REBLOG_FALLOFF most recent statuses, so we note that this
  196. # is an "extra" reblog, by storing it in reblog_set_key.
  197. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  198. redis.sadd(reblog_set_key, status.id)
  199. return false
  200. end
  201. else
  202. # A reblog may reach earlier than the original status because of the
  203. # delay of the worker deliverying the original status, the late addition
  204. # by merging timelines, and other reasons.
  205. # If such a reblog already exists, just do not re-insert it into the feed.
  206. rank = redis.zrevrank(reblog_key, status.id)
  207. return false unless rank.nil?
  208. redis.zadd(timeline_key, status.id, status.id)
  209. end
  210. true
  211. end
  212. # Removes an individual status from a feed, correctly handling cases
  213. # with reblogs, and returning true if a status was removed. As with
  214. # `add_to_feed`, this does not trigger push updates, so callers must
  215. # do so if appropriate.
  216. def remove_from_feed(timeline_type, account_id, status)
  217. timeline_key = key(timeline_type, account_id)
  218. if status.reblog?
  219. # 1. If the reblogging status is not in the feed, stop.
  220. status_rank = redis.zrevrank(timeline_key, status.id)
  221. return false if status_rank.nil?
  222. # 2. Remove reblog from set of this status's reblogs.
  223. reblog_set_key = key(timeline_type, account_id, "reblogs:#{status.reblog_of_id}")
  224. redis.srem(reblog_set_key, status.id)
  225. # 3. Re-insert another reblog or original into the feed if one
  226. # remains in the set. We could pick a random element, but this
  227. # set should generally be small, and it seems ideal to show the
  228. # oldest potential such reblog.
  229. other_reblog = redis.smembers(reblog_set_key).map(&:to_i).min
  230. redis.zadd(timeline_key, other_reblog, other_reblog) if other_reblog
  231. # 4. Remove the reblogging status from the feed (as normal)
  232. # (outside conditional)
  233. else
  234. # If the original is getting deleted, no use for reblog references
  235. redis.del(key(timeline_type, account_id, "reblogs:#{status.id}"))
  236. end
  237. redis.zrem(timeline_key, status.id)
  238. end
  239. end