move to 2.5.5
[anni] / lib / pleroma / web / activity_pub / mrf / no_empty_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.NoEmptyPolicy do
6   @moduledoc "Filter local activities which have no content"
7   @behaviour Pleroma.Web.ActivityPub.MRF.Policy
8
9   alias Pleroma.Web.Endpoint
10
11   @impl true
12   def filter(%{"actor" => actor} = object) do
13     with true <- is_local?(actor),
14          true <- is_eligible_type?(object),
15          true <- is_note?(object),
16          false <- has_attachment?(object),
17          true <- only_mentions?(object) do
18       {:reject, "[NoEmptyPolicy]"}
19     else
20       _ ->
21         {:ok, object}
22     end
23   end
24
25   def filter(object), do: {:ok, object}
26
27   defp is_local?(actor) do
28     if actor |> String.starts_with?("#{Endpoint.url()}") do
29       true
30     else
31       false
32     end
33   end
34
35   defp has_attachment?(%{
36          "object" => %{"type" => "Note", "attachment" => attachments}
37        })
38        when length(attachments) > 0,
39        do: true
40
41   defp has_attachment?(_), do: false
42
43   defp only_mentions?(%{"object" => %{"type" => "Note", "source" => source}}) do
44     source =
45       case source do
46         %{"content" => text} -> text
47         _ -> source
48       end
49
50     non_mentions =
51       source |> String.split() |> Enum.filter(&(not String.starts_with?(&1, "@"))) |> length
52
53     if non_mentions > 0 do
54       false
55     else
56       true
57     end
58   end
59
60   defp only_mentions?(_), do: false
61
62   defp is_note?(%{"object" => %{"type" => "Note"}}), do: true
63   defp is_note?(_), do: false
64
65   defp is_eligible_type?(%{"type" => type}) when type in ["Create", "Update"], do: true
66   defp is_eligible_type?(_), do: false
67
68   @impl true
69   def describe, do: {:ok, %{}}
70 end