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