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