5b6adbb4baf7919b59691deaba13f9638378c3f5
[anni] / lib / pleroma / web / activity_pub / mrf / follow_bot_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.FollowBotPolicy do
6   @behaviour Pleroma.Web.ActivityPub.MRF.Policy
7   alias Pleroma.Config
8   alias Pleroma.User
9   alias Pleroma.Web.CommonAPI
10
11   require Logger
12
13   @impl true
14   def filter(message) do
15     with follower_nickname <- Config.get([:mrf_follow_bot, :follower_nickname]),
16          %User{actor_type: "Service"} = follower <-
17            User.get_cached_by_nickname(follower_nickname),
18          %{"type" => "Create", "object" => %{"type" => "Note"}} <- message do
19       try_follow(follower, message)
20     else
21       nil ->
22         Logger.warn(
23           "#{__MODULE__} skipped because of missing `:mrf_follow_bot, :follower_nickname` configuration, the :follower_nickname
24             account does not exist, or the account is not correctly configured as a bot."
25         )
26
27         {:ok, message}
28
29       _ ->
30         {:ok, message}
31     end
32   end
33
34   defp try_follow(follower, message) do
35     to = Map.get(message, "to", [])
36     cc = Map.get(message, "cc", [])
37     actor = [message["actor"]]
38
39     Enum.concat([to, cc, actor])
40     |> List.flatten()
41     |> Enum.uniq()
42     |> User.get_all_by_ap_id()
43     |> Enum.each(fn user ->
44       with false <- user.local,
45            false <- User.following?(follower, user),
46            false <- User.locked?(user),
47            false <- (user.bio || "") |> String.downcase() |> String.contains?("nobot") do
48         Logger.debug(
49           "#{__MODULE__}: Follow request from #{follower.nickname} to #{user.nickname}"
50         )
51
52         CommonAPI.follow(follower, user)
53       end
54     end)
55
56     {:ok, message}
57   end
58
59   @impl true
60   def describe do
61     {:ok, %{}}
62   end
63 end