migrate to oban 2.0-rc1
[akkoma] / lib / pleroma / following_relationship.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.FollowingRelationship do
6 use Ecto.Schema
7
8 import Ecto.Changeset
9 import Ecto.Query
10
11 alias Ecto.Changeset
12 alias FlakeId.Ecto.CompatType
13 alias Pleroma.FollowingRelationship.State
14 alias Pleroma.Repo
15 alias Pleroma.User
16
17 schema "following_relationships" do
18 field(:state, State, default: :follow_pending)
19
20 belongs_to(:follower, User, type: CompatType)
21 belongs_to(:following, User, type: CompatType)
22
23 timestamps()
24 end
25
26 @doc "Returns underlying integer code for state atom"
27 def state_int_code(state_atom), do: State.__enum_map__() |> Keyword.fetch!(state_atom)
28
29 def accept_state_code, do: state_int_code(:follow_accept)
30
31 def changeset(%__MODULE__{} = following_relationship, attrs) do
32 following_relationship
33 |> cast(attrs, [:state])
34 |> put_assoc(:follower, attrs.follower)
35 |> put_assoc(:following, attrs.following)
36 |> validate_required([:state, :follower, :following])
37 |> unique_constraint(:follower_id,
38 name: :following_relationships_follower_id_following_id_index
39 )
40 |> validate_not_self_relationship()
41 end
42
43 def state_to_enum(state) when state in ["pending", "accept", "reject"] do
44 String.to_existing_atom("follow_#{state}")
45 end
46
47 def state_to_enum(state) do
48 raise "State is not convertible to Pleroma.FollowingRelationship.State: #{state}"
49 end
50
51 def get(%User{} = follower, %User{} = following) do
52 __MODULE__
53 |> where(follower_id: ^follower.id, following_id: ^following.id)
54 |> Repo.one()
55 end
56
57 def update(follower, following, :follow_reject), do: unfollow(follower, following)
58
59 def update(%User{} = follower, %User{} = following, state) do
60 case get(follower, following) do
61 nil ->
62 follow(follower, following, state)
63
64 following_relationship ->
65 following_relationship
66 |> cast(%{state: state}, [:state])
67 |> validate_required([:state])
68 |> Repo.update()
69 end
70 end
71
72 def follow(%User{} = follower, %User{} = following, state \\ :follow_accept) do
73 %__MODULE__{}
74 |> changeset(%{follower: follower, following: following, state: state})
75 |> Repo.insert(on_conflict: :nothing)
76 end
77
78 def unfollow(%User{} = follower, %User{} = following) do
79 case get(follower, following) do
80 %__MODULE__{} = following_relationship -> Repo.delete(following_relationship)
81 _ -> {:ok, nil}
82 end
83 end
84
85 def follower_count(%User{} = user) do
86 %{followers: user, deactivated: false}
87 |> User.Query.build()
88 |> Repo.aggregate(:count, :id)
89 end
90
91 def followers_query(%User{} = user) do
92 __MODULE__
93 |> join(:inner, [r], u in User, on: r.follower_id == u.id)
94 |> where([r], r.following_id == ^user.id)
95 |> where([r], r.state == ^:follow_accept)
96 end
97
98 def followers_ap_ids(%User{} = user, from_ap_ids \\ nil) do
99 query =
100 user
101 |> followers_query()
102 |> select([r, u], u.ap_id)
103
104 query =
105 if from_ap_ids do
106 where(query, [r, u], u.ap_id in ^from_ap_ids)
107 else
108 query
109 end
110
111 Repo.all(query)
112 end
113
114 def following_count(%User{id: nil}), do: 0
115
116 def following_count(%User{} = user) do
117 %{friends: user, deactivated: false}
118 |> User.Query.build()
119 |> Repo.aggregate(:count, :id)
120 end
121
122 def get_follow_requests(%User{id: id}) do
123 __MODULE__
124 |> join(:inner, [r], f in assoc(r, :follower))
125 |> where([r], r.state == ^:follow_pending)
126 |> where([r], r.following_id == ^id)
127 |> select([r, f], f)
128 |> Repo.all()
129 end
130
131 def following?(%User{id: follower_id}, %User{id: followed_id}) do
132 __MODULE__
133 |> where(follower_id: ^follower_id, following_id: ^followed_id, state: ^:follow_accept)
134 |> Repo.exists?()
135 end
136
137 def following_query(%User{} = user) do
138 __MODULE__
139 |> join(:inner, [r], u in User, on: r.following_id == u.id)
140 |> where([r], r.follower_id == ^user.id)
141 |> where([r], r.state == ^:follow_accept)
142 end
143
144 def outgoing_pending_follow_requests_query(%User{} = follower) do
145 __MODULE__
146 |> where([r], r.follower_id == ^follower.id)
147 |> where([r], r.state == ^:follow_pending)
148 end
149
150 def following(%User{} = user) do
151 following =
152 following_query(user)
153 |> select([r, u], u.follower_address)
154 |> Repo.all()
155
156 if not user.local or user.invisible do
157 following
158 else
159 [user.follower_address | following]
160 end
161 end
162
163 def move_following(origin, target) do
164 __MODULE__
165 |> join(:inner, [r], f in assoc(r, :follower))
166 |> where(following_id: ^origin.id)
167 |> where([r, f], f.allow_following_move == true)
168 |> limit(50)
169 |> preload([:follower])
170 |> Repo.all()
171 |> Enum.map(fn following_relationship ->
172 Repo.delete(following_relationship)
173 Pleroma.Web.CommonAPI.follow(following_relationship.follower, target)
174 end)
175 |> case do
176 [] ->
177 User.update_follower_count(origin)
178 :ok
179
180 _ ->
181 move_following(origin, target)
182 end
183 end
184
185 def all_between_user_sets(
186 source_users,
187 target_users
188 )
189 when is_list(source_users) and is_list(target_users) do
190 source_user_ids = User.binary_id(source_users)
191 target_user_ids = User.binary_id(target_users)
192
193 __MODULE__
194 |> where(
195 fragment(
196 "(follower_id = ANY(?) AND following_id = ANY(?)) OR \
197 (follower_id = ANY(?) AND following_id = ANY(?))",
198 ^source_user_ids,
199 ^target_user_ids,
200 ^target_user_ids,
201 ^source_user_ids
202 )
203 )
204 |> Repo.all()
205 end
206
207 def find(following_relationships, follower, following) do
208 Enum.find(following_relationships, fn
209 fr -> fr.follower_id == follower.id and fr.following_id == following.id
210 end)
211 end
212
213 @doc """
214 For a query with joined activity,
215 keeps rows where activity's actor is followed by user -or- is NOT domain-blocked by user.
216 """
217 def keep_following_or_not_domain_blocked(query, user) do
218 where(
219 query,
220 [_, activity],
221 fragment(
222 # "(actor's domain NOT in domain_blocks) OR (actor IS in followed AP IDs)"
223 """
224 NOT (substring(? from '.*://([^/]*)') = ANY(?)) OR
225 ? = ANY(SELECT ap_id FROM users AS u INNER JOIN following_relationships AS fr
226 ON u.id = fr.following_id WHERE fr.follower_id = ? AND fr.state = ?)
227 """,
228 activity.actor,
229 ^user.domain_blocks,
230 activity.actor,
231 ^User.binary_id(user.id),
232 ^accept_state_code()
233 )
234 )
235 end
236
237 defp validate_not_self_relationship(%Changeset{} = changeset) do
238 changeset
239 |> validate_follower_id_following_id_inequality()
240 |> validate_following_id_follower_id_inequality()
241 end
242
243 defp validate_follower_id_following_id_inequality(%Changeset{} = changeset) do
244 validate_change(changeset, :follower_id, fn _, follower_id ->
245 if follower_id == get_field(changeset, :following_id) do
246 [source_id: "can't be equal to following_id"]
247 else
248 []
249 end
250 end)
251 end
252
253 defp validate_following_id_follower_id_inequality(%Changeset{} = changeset) do
254 validate_change(changeset, :following_id, fn _, following_id ->
255 if following_id == get_field(changeset, :follower_id) do
256 [target_id: "can't be equal to follower_id"]
257 else
258 []
259 end
260 end)
261 end
262 end