Add short documentation on every MRF Policy
[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 @moduledoc "Reject or Word-Replace messages with a keyword or regex"
7
8 @behaviour Pleroma.Web.ActivityPub.MRF
9 defp string_matches?(string, _) when not is_binary(string) do
10 false
11 end
12
13 defp string_matches?(string, pattern) when is_binary(pattern) do
14 String.contains?(string, pattern)
15 end
16
17 defp string_matches?(string, pattern) do
18 String.match?(string, pattern)
19 end
20
21 defp check_reject(%{"object" => %{"content" => content, "summary" => summary}} = message) do
22 if Enum.any?(Pleroma.Config.get([:mrf_keyword, :reject]), fn pattern ->
23 string_matches?(content, pattern) or string_matches?(summary, pattern)
24 end) do
25 {:reject, nil}
26 else
27 {:ok, message}
28 end
29 end
30
31 defp check_ftl_removal(
32 %{"to" => to, "object" => %{"content" => content, "summary" => summary}} = message
33 ) do
34 if "https://www.w3.org/ns/activitystreams#Public" in to and
35 Enum.any?(Pleroma.Config.get([:mrf_keyword, :federated_timeline_removal]), fn pattern ->
36 string_matches?(content, pattern) or string_matches?(summary, pattern)
37 end) do
38 to = List.delete(to, "https://www.w3.org/ns/activitystreams#Public")
39 cc = ["https://www.w3.org/ns/activitystreams#Public" | message["cc"] || []]
40
41 message =
42 message
43 |> Map.put("to", to)
44 |> Map.put("cc", cc)
45
46 {:ok, message}
47 else
48 {:ok, message}
49 end
50 end
51
52 defp check_replace(%{"object" => %{"content" => content, "summary" => summary}} = message) do
53 content =
54 if is_binary(content) do
55 content
56 else
57 ""
58 end
59
60 summary =
61 if is_binary(summary) do
62 summary
63 else
64 ""
65 end
66
67 {content, summary} =
68 Enum.reduce(
69 Pleroma.Config.get([:mrf_keyword, :replace]),
70 {content, summary},
71 fn {pattern, replacement}, {content_acc, summary_acc} ->
72 {String.replace(content_acc, pattern, replacement),
73 String.replace(summary_acc, pattern, replacement)}
74 end
75 )
76
77 {:ok,
78 message
79 |> put_in(["object", "content"], content)
80 |> put_in(["object", "summary"], summary)}
81 end
82
83 @impl true
84 def filter(%{"type" => "Create", "object" => %{"content" => _content}} = message) do
85 with {:ok, message} <- check_reject(message),
86 {:ok, message} <- check_ftl_removal(message),
87 {:ok, message} <- check_replace(message) do
88 {:ok, message}
89 else
90 _e ->
91 {:reject, nil}
92 end
93 end
94
95 @impl true
96 def filter(message), do: {:ok, message}
97 end