Merge branch 'fix/credo-issues' into 'develop'
[akkoma] / lib / pleroma / web / activity_pub / mrf / keyword_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.KeywordPolicy do
6 @behaviour Pleroma.Web.ActivityPub.MRF
7 defp string_matches?(string, pattern) when is_binary(pattern) do
8 String.contains?(string, pattern)
9 end
10
11 defp string_matches?(string, pattern) do
12 String.match?(string, pattern)
13 end
14
15 defp check_reject(%{"object" => %{"content" => content}} = message) do
16 if Enum.any?(Pleroma.Config.get([:mrf_keyword, :reject]), fn pattern ->
17 string_matches?(content, pattern)
18 end) do
19 {:reject, nil}
20 else
21 {:ok, message}
22 end
23 end
24
25 defp check_ftl_removal(%{"to" => to, "object" => %{"content" => content}} = message) do
26 if "https://www.w3.org/ns/activitystreams#Public" in to and
27 Enum.any?(Pleroma.Config.get([:mrf_keyword, :federated_timeline_removal]), fn pattern ->
28 string_matches?(content, pattern)
29 end) do
30 to = List.delete(to, "https://www.w3.org/ns/activitystreams#Public")
31 cc = ["https://www.w3.org/ns/activitystreams#Public" | message["cc"] || []]
32
33 message =
34 message
35 |> Map.put("to", to)
36 |> Map.put("cc", cc)
37
38 {:ok, message}
39 else
40 {:ok, message}
41 end
42 end
43
44 defp check_replace(%{"object" => %{"content" => content}} = message) do
45 content =
46 Enum.reduce(Pleroma.Config.get([:mrf_keyword, :replace]), content, fn {pattern, replacement},
47 acc ->
48 String.replace(acc, pattern, replacement)
49 end)
50
51 {:ok, put_in(message["object"]["content"], content)}
52 end
53
54 @impl true
55 def filter(%{"object" => %{"content" => nil}} = message) do
56 {:ok, message}
57 end
58
59 @impl true
60 def filter(%{"type" => "Create", "object" => %{"content" => _content}} = message) do
61 with {:ok, message} <- check_reject(message),
62 {:ok, message} <- check_ftl_removal(message),
63 {:ok, message} <- check_replace(message) do
64 {:ok, message}
65 else
66 _e ->
67 {:reject, nil}
68 end
69 end
70
71 @impl true
72 def filter(message), do: {:ok, message}
73 end