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