Merge remote-tracking branch 'origin/develop' into manifest
[akkoma] / lib / pleroma / formatter.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.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 defp linkify_opts do
14 Pleroma.Config.get(Pleroma.Formatter) ++
15 [
16 hashtag: true,
17 hashtag_handler: &Pleroma.Formatter.hashtag_handler/4,
18 mention: true,
19 mention_handler: &Pleroma.Formatter.mention_handler/4
20 ]
21 end
22
23 def escape_mention_handler("@" <> nickname = mention, buffer, _, _) do
24 case User.get_cached_by_nickname(nickname) do
25 %User{} ->
26 # escape markdown characters with `\\`
27 # (we don't want something like @user__name to be parsed by markdown)
28 String.replace(mention, @markdown_characters_regex, "\\\\\\1")
29
30 _ ->
31 buffer
32 end
33 end
34
35 def mention_handler("@" <> nickname, buffer, opts, acc) do
36 case User.get_cached_by_nickname(nickname) do
37 %User{id: id} = user ->
38 user_url = user.uri || user.ap_id
39 nickname_text = get_nickname_text(nickname, opts)
40
41 link =
42 Phoenix.HTML.Tag.content_tag(
43 :span,
44 Phoenix.HTML.Tag.content_tag(
45 :a,
46 ["@", Phoenix.HTML.Tag.content_tag(:span, nickname_text)],
47 "data-user": id,
48 class: "u-url mention",
49 href: user_url,
50 rel: "ugc"
51 ),
52 class: "h-card"
53 )
54 |> Phoenix.HTML.safe_to_string()
55
56 {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, user})}}
57
58 _ ->
59 {buffer, acc}
60 end
61 end
62
63 def hashtag_handler("#" <> tag = tag_text, _buffer, _opts, acc) do
64 tag = String.downcase(tag)
65 url = "#{Pleroma.Web.Endpoint.url()}/tag/#{tag}"
66
67 link =
68 Phoenix.HTML.Tag.content_tag(:a, tag_text,
69 class: "hashtag",
70 "data-tag": tag,
71 href: url,
72 rel: "tag ugc"
73 )
74 |> Phoenix.HTML.safe_to_string()
75
76 {link, %{acc | tags: MapSet.put(acc.tags, {tag_text, tag})}}
77 end
78
79 @doc """
80 Parses a text and replace plain text links with HTML. Returns a tuple with a result text, mentions, and hashtags.
81
82 If the 'safe_mention' option is given, only consecutive mentions at the start the post are actually mentioned.
83 """
84 @spec linkify(String.t(), keyword()) ::
85 {String.t(), [{String.t(), User.t()}], [{String.t(), String.t()}]}
86 def linkify(text, options \\ []) do
87 options = linkify_opts() ++ options
88
89 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
90 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
91 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
92
93 {text_mentions, %{mentions: mentions}} = Linkify.link_map(mentions, acc, options)
94 {text_rest, %{tags: tags}} = Linkify.link_map(rest, acc, options)
95
96 {text_mentions <> text_rest, MapSet.to_list(mentions), MapSet.to_list(tags)}
97 else
98 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
99 {text, %{mentions: mentions, tags: tags}} = Linkify.link_map(text, acc, options)
100
101 {text, MapSet.to_list(mentions), MapSet.to_list(tags)}
102 end
103 end
104
105 @doc """
106 Escapes a special characters in mention names.
107 """
108 def mentions_escape(text, options \\ []) do
109 options =
110 Keyword.merge(options,
111 mention: true,
112 url: false,
113 mention_handler: &Pleroma.Formatter.escape_mention_handler/4
114 )
115
116 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
117 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
118 Linkify.link(mentions, options) <> Linkify.link(rest, options)
119 else
120 Linkify.link(text, options)
121 end
122 end
123
124 def markdown_to_html(text) do
125 Earmark.as_html!(text, %Earmark.Options{compact_output: true})
126 end
127
128 def html_escape({text, mentions, hashtags}, type) do
129 {html_escape(text, type), mentions, hashtags}
130 end
131
132 def html_escape(text, "text/html") do
133 HTML.filter_tags(text)
134 end
135
136 def html_escape(text, "text/plain") do
137 Regex.split(@link_regex, text, include_captures: true)
138 |> Enum.map_every(2, fn chunk ->
139 {:safe, part} = Phoenix.HTML.html_escape(chunk)
140 part
141 end)
142 |> Enum.join("")
143 end
144
145 def truncate(text, max_length \\ 200, omission \\ "...") do
146 # Remove trailing whitespace
147 text = Regex.replace(~r/([^ \t\r\n])([ \t]+$)/u, text, "\\g{1}")
148
149 if String.length(text) < max_length do
150 text
151 else
152 length_with_omission = max_length - String.length(omission)
153 String.slice(text, 0, length_with_omission) <> omission
154 end
155 end
156
157 defp get_nickname_text(nickname, %{mentions_format: :full}), do: User.full_nickname(nickname)
158 defp get_nickname_text(nickname, _), do: User.local_nickname(nickname)
159 end