1 defmodule Pleroma.Repo.Migrations.FixBlockedFollows do
9 unfollow_blocked = Config.get([:activitypub, :unfollow_blocked])
11 if unfollow_blocked do
13 |> where([activity], fragment("? ->> 'type' = 'Block'", activity.data))
14 |> distinct([activity], [
17 "coalesce((?)->'object'->>'id', (?)->>'object')",
22 |> order_by([activity], [fragment("? desc nulls last", activity.id)])
23 |> select([activity], %{
24 blocker: activity.actor,
26 fragment("coalesce((?)->'object'->>'id', (?)->>'object')", activity.data, activity.data),
27 created_at: activity.id
30 |> Enum.map(&unfollow_if_blocked/1)
32 |> Enum.each(&update_follower_count/1)
39 def unfollow_if_blocked(%{blocker: blocker_id, blocked: blocked_id, created_at: blocked_at}) do
42 activity in "activities",
43 where: fragment("? ->> 'type' = 'Follow'", activity.data),
44 where: activity.actor == ^blocked_id,
45 # this is to use the index
48 "coalesce((?)->'object'->>'id', (?)->>'object') = ?",
53 where: activity.id > ^blocked_at,
54 where: fragment("(?)->>'state' = 'accept'", activity.data),
55 order_by: [fragment("? desc nulls last", activity.id)]
58 unless Repo.exists?(query) do
59 blocker = "users" |> select([:id, :local]) |> Repo.get_by(ap_id: blocker_id)
60 blocked = "users" |> select([:id]) |> Repo.get_by(ap_id: blocked_id)
62 if !is_nil(blocker) && !is_nil(blocked) do
63 unfollow(blocked, blocker)
68 def unfollow(%{id: follower_id}, %{id: followed_id} = followed) do
69 following_relationship =
70 "following_relationships"
71 |> where(follower_id: ^follower_id, following_id: ^followed_id, state: "accept")
75 case following_relationship do
79 %{id: following_relationship_id} ->
80 "following_relationships"
81 |> where(id: ^following_relationship_id)
88 def update_follower_count(%{id: user_id} = user) do
89 if user.local or !Pleroma.Config.get([:instance, :external_user_synchronization]) do
90 follower_count_query =
92 |> where([u], u.id != ^user_id)
93 |> where([u], u.deactivated != ^true)
94 |> join(:inner, [u], r in "following_relationships",
96 on: r.following_id == ^user_id and r.follower_id == u.id
98 |> where([relationships: r], r.state == "accept")
99 |> select([u], %{count: count(u.id)})
102 |> where(id: ^user_id)
103 |> join(:inner, [u], s in subquery(follower_count_query))
105 set: [follower_count: s.count]
107 |> Repo.update_all([])
111 def update_follower_count(_), do: :noop