logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

status_threading_concern.rb (2275B)


  1. # frozen_string_literal: true
  2. module StatusThreadingConcern
  3. extend ActiveSupport::Concern
  4. def ancestors(limit, account = nil)
  5. find_statuses_from_tree_path(ancestor_ids(limit), account)
  6. end
  7. def descendants(account = nil)
  8. find_statuses_from_tree_path(descendant_ids, account)
  9. end
  10. private
  11. def ancestor_ids(limit)
  12. key = "ancestors:#{id}"
  13. ancestors = Rails.cache.fetch(key)
  14. if ancestors.nil? || ancestors[:limit] < limit
  15. ids = ancestor_statuses(limit).pluck(:id).reverse!
  16. Rails.cache.write key, limit: limit, ids: ids
  17. ids
  18. else
  19. ancestors[:ids].last(limit)
  20. end
  21. end
  22. def ancestor_statuses(limit)
  23. Status.find_by_sql([<<-SQL.squish, id: in_reply_to_id, limit: limit])
  24. WITH RECURSIVE search_tree(id, in_reply_to_id, path)
  25. AS (
  26. SELECT id, in_reply_to_id, ARRAY[id]
  27. FROM statuses
  28. WHERE id = :id
  29. UNION ALL
  30. SELECT statuses.id, statuses.in_reply_to_id, path || statuses.id
  31. FROM search_tree
  32. JOIN statuses ON statuses.id = search_tree.in_reply_to_id
  33. WHERE NOT statuses.id = ANY(path)
  34. )
  35. SELECT id
  36. FROM search_tree
  37. ORDER BY path
  38. LIMIT :limit
  39. SQL
  40. end
  41. def descendant_ids
  42. descendant_statuses.pluck(:id)
  43. end
  44. def descendant_statuses
  45. Status.find_by_sql([<<-SQL.squish, id: id])
  46. WITH RECURSIVE search_tree(id, path)
  47. AS (
  48. SELECT id, ARRAY[id]
  49. FROM statuses
  50. WHERE in_reply_to_id = :id
  51. UNION ALL
  52. SELECT statuses.id, path || statuses.id
  53. FROM search_tree
  54. JOIN statuses ON statuses.in_reply_to_id = search_tree.id
  55. WHERE NOT statuses.id = ANY(path)
  56. )
  57. SELECT id
  58. FROM search_tree
  59. ORDER BY path
  60. SQL
  61. end
  62. def find_statuses_from_tree_path(ids, account)
  63. statuses = statuses_with_accounts(ids).to_a
  64. # FIXME: n+1 bonanza
  65. statuses.reject! { |status| filter_from_context?(status, account) }
  66. # Order ancestors/descendants by tree path
  67. statuses.sort_by! { |status| ids.index(status.id) }
  68. end
  69. def statuses_with_accounts(ids)
  70. Status.where(id: ids).includes(:account)
  71. end
  72. def filter_from_context?(status, account)
  73. StatusFilter.new(status, account).filtered?
  74. end
  75. end