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.
 
 
 
 

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