Merge branch 'develop' into feature/addressable-lists
[akkoma] / lib / pleroma / web / activity_pub / mrf / anti_link_spam_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2019 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 require Logger
9
10 # has the user successfully posted before?
11 defp old_user?(%User{} = u) do
12 u.info.note_count > 0 || u.info.follower_count > 0
13 end
14
15 # does the post contain links?
16 defp contains_links?(%{"content" => content} = _object) do
17 content
18 |> Floki.filter_out("a.mention,a.hashtag,a[rel~=\"tag\"],a.zrl")
19 |> Floki.attribute("a", "href")
20 |> length() > 0
21 end
22
23 defp contains_links?(_), do: false
24
25 def filter(%{"type" => "Create", "actor" => actor, "object" => object} = message) do
26 with {:ok, %User{} = u} <- User.get_or_fetch_by_ap_id(actor),
27 {:contains_links, true} <- {:contains_links, contains_links?(object)},
28 {:old_user, true} <- {:old_user, old_user?(u)} do
29 {:ok, message}
30 else
31 {:contains_links, false} ->
32 {:ok, message}
33
34 {:old_user, false} ->
35 {:reject, nil}
36
37 {:error, _} ->
38 {:reject, nil}
39
40 e ->
41 Logger.warn("[MRF anti-link-spam] WTF: unhandled error #{inspect(e)}")
42 {:reject, nil}
43 end
44 end
45
46 # in all other cases, pass through
47 def filter(message), do: {:ok, message}
48 end