total rebase
[anni] / static / modules / inline_quote_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.InlineQuotePolicy do
6   @moduledoc "Force a quote line into the message content."
7   @behaviour Pleroma.Web.ActivityPub.MRF.Policy
8
9   defp build_inline_quote(template, url) do
10     quote_line = String.replace(template, "{url}", "<a href=\"#{url}\">#{url}</a>")
11
12     "<span class=\"quote-inline\"><br/><br/>#{quote_line}</span>"
13   end
14
15   defp has_inline_quote?(content, quote_url) do
16     cond do
17       # Does the quote URL exist in the content?
18       content =~ quote_url -> true
19       # Does the content already have a .quote-inline span?
20       content =~ "<span class=\"quote-inline\">" -> true
21       # No inline quote found
22       true -> false
23     end
24   end
25
26   defp filter_object(%{"quoteUrl" => quote_url} = object) do
27     content = object["content"] || ""
28
29     if has_inline_quote?(content, quote_url) do
30       object
31     else
32       template = Pleroma.Config.get([:mrf_inline_quote, :template])
33
34       content =
35         if String.ends_with?(content, "</p>"),
36           do:
37             String.trim_trailing(content, "</p>") <>
38               build_inline_quote(template, quote_url) <> "</p>",
39           else: content <> build_inline_quote(template, quote_url)
40
41       Map.put(object, "content", content)
42     end
43   end
44
45   @impl true
46   def filter(%{"object" => %{"quoteUrl" => _} = object} = activity) do
47     {:ok, Map.put(activity, "object", filter_object(object))}
48   end
49
50   @impl true
51   def filter(object), do: {:ok, object}
52
53   @impl true
54   def describe, do: {:ok, %{}}
55
56   @impl Pleroma.Web.ActivityPub.MRF.Policy
57   def history_awareness, do: :auto
58
59   @impl true
60   def config_description do
61     %{
62       key: :mrf_inline_quote,
63       related_policy: "Pleroma.Web.ActivityPub.MRF.InlineQuotePolicy",
64       label: "MRF Inline Quote Policy",
65       description: "Force quote url to appear in post content.",
66       children: [
67         %{
68           key: :template,
69           type: :string,
70           description:
71             "The template to append to the post. `{url}` will be replaced with the actual link to the quoted post.",
72           suggestions: ["<bdi>RT:</bdi> {url}"]
73         }
74       ]
75     }
76   end
77 end