move to 2.5.5
[anni] / lib / pleroma / web / activity_pub / mrf / anti_link_spam_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.AntiLinkSpamPolicy do
6   alias Pleroma.User
7
8   @behaviour Pleroma.Web.ActivityPub.MRF.Policy
9
10   require Logger
11
12   @impl true
13   def history_awareness, do: :auto
14
15   # has the user successfully posted before?
16   defp old_user?(%User{} = u) do
17     u.note_count > 0 || u.follower_count > 0
18   end
19
20   # does the post contain links?
21   defp contains_links?(%{"content" => content} = _object) do
22     content
23     |> Floki.parse_fragment!()
24     |> Floki.filter_out("a.mention,a.hashtag,a[rel~=\"tag\"],a.zrl")
25     |> Floki.attribute("a", "href")
26     |> length() > 0
27   end
28
29   defp contains_links?(_), do: false
30
31   @impl true
32   def filter(%{"type" => "Create", "actor" => actor, "object" => object} = message) do
33     with {:ok, %User{local: false} = u} <- User.get_or_fetch_by_ap_id(actor),
34          {:contains_links, true} <- {:contains_links, contains_links?(object)},
35          {:old_user, true} <- {:old_user, old_user?(u)} do
36       {:ok, message}
37     else
38       {:ok, %User{local: true}} ->
39         {:ok, message}
40
41       {:contains_links, false} ->
42         {:ok, message}
43
44       {:old_user, false} ->
45         {:reject, "[AntiLinkSpamPolicy] User has no posts nor followers"}
46
47       {:error, _} ->
48         {:reject, "[AntiLinkSpamPolicy] Failed to get or fetch user by ap_id"}
49
50       e ->
51         {:reject, "[AntiLinkSpamPolicy] Unhandled error #{inspect(e)}"}
52     end
53   end
54
55   # in all other cases, pass through
56   def filter(message), do: {:ok, message}
57
58   @impl true
59   def describe, do: {:ok, %{}}
60 end