about summary refs log tree commit diff
path: root/app/models/concerns/status_threading_concern.rb
blob: 65f8e112e61cfd6028d3f29838d830649d8d7d0f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# frozen_string_literal: true

module StatusThreadingConcern
  extend ActiveSupport::Concern

  def ancestors(account = nil)
    find_statuses_from_tree_path(ancestor_ids, account)
  end

  def descendants(account = nil)
    find_statuses_from_tree_path(descendant_ids, account)
  end

  private

  def ancestor_ids
    Rails.cache.fetch("ancestors:#{id}") do
      ancestors_without_self.pluck(:id)
    end
  end

  def ancestors_without_self
    ancestor_statuses - [self]
  end

  def ancestor_statuses
    Status.find_by_sql([<<-SQL.squish, id: id])
      WITH RECURSIVE search_tree(id, in_reply_to_id, path)
      AS (
        SELECT id, in_reply_to_id, ARRAY[id]
        FROM statuses
        WHERE id = :id
        UNION ALL
        SELECT statuses.id, statuses.in_reply_to_id, path || statuses.id
        FROM search_tree
        JOIN statuses ON statuses.id = search_tree.in_reply_to_id
        WHERE NOT statuses.id = ANY(path)
      )
      SELECT id
      FROM search_tree
      ORDER BY path DESC
    SQL
  end

  def descendant_ids
    descendants_without_self.pluck(:id)
  end

  def descendants_without_self
    descendant_statuses - [self]
  end

  def descendant_statuses
    Status.find_by_sql([<<-SQL.squish, id: id])
      WITH RECURSIVE search_tree(id, path)
      AS (
        SELECT id, ARRAY[id]
        FROM statuses
        WHERE id = :id
        UNION ALL
        SELECT statuses.id, path || statuses.id
        FROM search_tree
        JOIN statuses ON statuses.in_reply_to_id = search_tree.id
        WHERE NOT statuses.id = ANY(path)
      )
      SELECT id
      FROM search_tree
      ORDER BY path
    SQL
  end

  def find_statuses_from_tree_path(ids, account)
    statuses = statuses_with_accounts(ids).to_a

    # FIXME: n+1 bonanza
    statuses.reject! { |status| filter_from_context?(status, account) }

    # Order ancestors/descendants by tree path
    statuses.sort_by! { |status| ids.index(status.id) }
  end

  def statuses_with_accounts(ids)
    Status.where(id: ids).includes(:account)
  end

  def filter_from_context?(status, account)
    StatusFilter.new(status, account).filtered?
  end
end