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