[#2332] Misc. improvements per code change requests.
[akkoma] / lib / pleroma / formatter.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Formatter do
6 alias Pleroma.HTML
7 alias Pleroma.User
8
9 @safe_mention_regex ~r/^(\s*(?<mentions>(@.+?\s+){1,})+)(?<rest>.*)/s
10 @link_regex ~r"((?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~%:/?#[\]@!\$&'\(\)\*\+,;=.]+)|[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+"ui
11 @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
12
13 @auto_linker_config hashtag: true,
14 hashtag_handler: &Pleroma.Formatter.hashtag_handler/4,
15 mention: true,
16 mention_handler: &Pleroma.Formatter.mention_handler/4,
17 scheme: true
18
19 def escape_mention_handler("@" <> nickname = mention, buffer, _, _) do
20 case User.get_cached_by_nickname(nickname) do
21 %User{} ->
22 # escape markdown characters with `\\`
23 # (we don't want something like @user__name to be parsed by markdown)
24 String.replace(mention, @markdown_characters_regex, "\\\\\\1")
25
26 _ ->
27 buffer
28 end
29 end
30
31 def mention_handler("@" <> nickname, buffer, opts, acc) do
32 case User.get_cached_by_nickname(nickname) do
33 %User{id: id} = user ->
34 ap_id = get_ap_id(user)
35 nickname_text = get_nickname_text(nickname, opts)
36
37 link =
38 ~s(<span class="h-card"><a data-user="#{id}" class="u-url mention" href="#{ap_id}" rel="ugc">@<span>#{
39 nickname_text
40 }</span></a></span>)
41
42 {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, user})}}
43
44 _ ->
45 {buffer, acc}
46 end
47 end
48
49 def hashtag_handler("#" <> tag = tag_text, _buffer, _opts, acc) do
50 tag = String.downcase(tag)
51 url = "#{Pleroma.Web.base_url()}/tag/#{tag}"
52 link = ~s(<a class="hashtag" data-tag="#{tag}" href="#{url}" rel="tag ugc">#{tag_text}</a>)
53
54 {link, %{acc | tags: MapSet.put(acc.tags, {tag_text, tag})}}
55 end
56
57 @doc """
58 Parses a text and replace plain text links with HTML. Returns a tuple with a result text, mentions, and hashtags.
59
60 If the 'safe_mention' option is given, only consecutive mentions at the start the post are actually mentioned.
61 """
62 @spec linkify(String.t(), keyword()) ::
63 {String.t(), [{String.t(), User.t()}], [{String.t(), String.t()}]}
64 def linkify(text, options \\ []) do
65 options = options ++ @auto_linker_config
66
67 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
68 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
69 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
70
71 {text_mentions, %{mentions: mentions}} = AutoLinker.link_map(mentions, acc, options)
72 {text_rest, %{tags: tags}} = AutoLinker.link_map(rest, acc, options)
73
74 {text_mentions <> text_rest, MapSet.to_list(mentions), MapSet.to_list(tags)}
75 else
76 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
77 {text, %{mentions: mentions, tags: tags}} = AutoLinker.link_map(text, acc, options)
78
79 {text, MapSet.to_list(mentions), MapSet.to_list(tags)}
80 end
81 end
82
83 @doc """
84 Escapes a special characters in mention names.
85 """
86 def mentions_escape(text, options \\ []) do
87 options =
88 Keyword.merge(options,
89 mention: true,
90 url: false,
91 mention_handler: &Pleroma.Formatter.escape_mention_handler/4
92 )
93
94 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
95 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
96 AutoLinker.link(mentions, options) <> AutoLinker.link(rest, options)
97 else
98 AutoLinker.link(text, options)
99 end
100 end
101
102 def html_escape({text, mentions, hashtags}, type) do
103 {html_escape(text, type), mentions, hashtags}
104 end
105
106 def html_escape(text, "text/html") do
107 HTML.filter_tags(text)
108 end
109
110 def html_escape(text, "text/plain") do
111 Regex.split(@link_regex, text, include_captures: true)
112 |> Enum.map_every(2, fn chunk ->
113 {:safe, part} = Phoenix.HTML.html_escape(chunk)
114 part
115 end)
116 |> Enum.join("")
117 end
118
119 def truncate(text, max_length \\ 200, omission \\ "...") do
120 # Remove trailing whitespace
121 text = Regex.replace(~r/([^ \t\r\n])([ \t]+$)/u, text, "\\g{1}")
122
123 if String.length(text) < max_length do
124 text
125 else
126 length_with_omission = max_length - String.length(omission)
127 String.slice(text, 0, length_with_omission) <> omission
128 end
129 end
130
131 defp get_ap_id(%User{source_data: %{"url" => url}}) when is_binary(url), do: url
132 defp get_ap_id(%User{ap_id: ap_id}), do: ap_id
133
134 defp get_nickname_text(nickname, %{mentions_format: :full}), do: User.full_nickname(nickname)
135 defp get_nickname_text(nickname, _), do: User.local_nickname(nickname)
136 end