Merge branch 'update-service-files-of-openrc-and-systemd-to-new-recommended-paths...
[akkoma] / lib / pleroma / formatter.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Formatter do
6 alias Pleroma.User
7 alias Pleroma.Web.MediaProxy
8 alias Pleroma.HTML
9 alias Pleroma.Emoji
10
11 @tag_regex ~r/((?<=[^&])|\A)(\#)(\w+)/u
12 @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
13
14 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
15 @mentions_regex ~r/@[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]*@?[a-zA-Z0-9_-](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/u
16
17 def parse_tags(text, data \\ %{}) do
18 Regex.scan(@tag_regex, text)
19 |> Enum.map(fn ["#" <> tag = full_tag | _] -> {full_tag, String.downcase(tag)} end)
20 |> (fn map ->
21 if data["sensitive"] in [true, "True", "true", "1"],
22 do: [{"#nsfw", "nsfw"}] ++ map,
23 else: map
24 end).()
25 end
26
27 @doc "Parses mentions text and returns list {nickname, user}."
28 @spec parse_mentions(binary()) :: list({binary(), User.t()})
29 def parse_mentions(text) do
30 Regex.scan(@mentions_regex, text)
31 |> List.flatten()
32 |> Enum.uniq()
33 |> Enum.map(fn nickname ->
34 with nickname <- String.trim_leading(nickname, "@"),
35 do: {"@" <> nickname, User.get_cached_by_nickname(nickname)}
36 end)
37 |> Enum.filter(fn {_match, user} -> user end)
38 end
39
40 def emojify(text) do
41 emojify(text, Emoji.get_all())
42 end
43
44 def emojify(text, nil), do: text
45
46 def emojify(text, emoji, strip \\ false) do
47 Enum.reduce(emoji, text, fn {emoji, file}, text ->
48 emoji = HTML.strip_tags(emoji)
49 file = HTML.strip_tags(file)
50
51 String.replace(
52 text,
53 ":#{emoji}:",
54 if not strip do
55 "<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{
56 MediaProxy.url(file)
57 }' />"
58 else
59 ""
60 end
61 )
62 |> HTML.filter_tags()
63 end)
64 end
65
66 def demojify(text) do
67 emojify(text, Emoji.get_all(), true)
68 end
69
70 def demojify(text, nil), do: text
71
72 def get_emoji(text) when is_binary(text) do
73 Enum.filter(Emoji.get_all(), fn {emoji, _} -> String.contains?(text, ":#{emoji}:") end)
74 end
75
76 def get_emoji(_), do: []
77
78 @link_regex ~r/[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+/ui
79
80 @uri_schemes Application.get_env(:pleroma, :uri_schemes, [])
81 @valid_schemes Keyword.get(@uri_schemes, :valid_schemes, [])
82
83 # TODO: make it use something other than @link_regex
84 def html_escape(text, "text/html") do
85 HTML.filter_tags(text)
86 end
87
88 def html_escape(text, "text/plain") do
89 Regex.split(@link_regex, text, include_captures: true)
90 |> Enum.map_every(2, fn chunk ->
91 {:safe, part} = Phoenix.HTML.html_escape(chunk)
92 part
93 end)
94 |> Enum.join("")
95 end
96
97 @doc """
98 Escapes a special characters in mention names.
99 """
100 @spec mentions_escape(String.t(), list({String.t(), any()})) :: String.t()
101 def mentions_escape(text, mentions) do
102 mentions
103 |> Enum.reduce(text, fn {name, _}, acc ->
104 escape_name = String.replace(name, @markdown_characters_regex, "\\\\\\1")
105 String.replace(acc, name, escape_name)
106 end)
107 end
108
109 @doc "changes scheme:... urls to html links"
110 def add_links({subs, text}) do
111 links =
112 text
113 |> String.split([" ", "\t", "<br>"])
114 |> Enum.filter(fn word -> String.starts_with?(word, @valid_schemes) end)
115 |> Enum.filter(fn word -> Regex.match?(@link_regex, word) end)
116 |> Enum.map(fn url -> {Ecto.UUID.generate(), url} end)
117 |> Enum.sort_by(fn {_, url} -> -String.length(url) end)
118
119 uuid_text =
120 links
121 |> Enum.reduce(text, fn {uuid, url}, acc -> String.replace(acc, url, uuid) end)
122
123 subs =
124 subs ++
125 Enum.map(links, fn {uuid, url} ->
126 {uuid, "<a href=\"#{url}\">#{url}</a>"}
127 end)
128
129 {subs, uuid_text}
130 end
131
132 @doc "Adds the links to mentioned users"
133 def add_user_links({subs, text}, mentions, options \\ []) do
134 mentions =
135 mentions
136 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
137 |> Enum.map(fn {name, user} -> {name, user, Ecto.UUID.generate()} end)
138
139 uuid_text =
140 mentions
141 |> Enum.reduce(text, fn {match, _user, uuid}, text ->
142 String.replace(text, match, uuid)
143 end)
144
145 subs =
146 subs ++
147 Enum.map(mentions, fn {match, %User{id: id, ap_id: ap_id, info: info}, uuid} ->
148 ap_id =
149 if is_binary(info.source_data["url"]) do
150 info.source_data["url"]
151 else
152 ap_id
153 end
154
155 nickname =
156 if options[:format] == :full do
157 User.full_nickname(match)
158 else
159 User.local_nickname(match)
160 end
161
162 {uuid,
163 "<span class='h-card'><a data-user='#{id}' class='u-url mention' href='#{ap_id}'>" <>
164 "@<span>#{nickname}</span></a></span>"}
165 end)
166
167 {subs, uuid_text}
168 end
169
170 @doc "Adds the hashtag links"
171 def add_hashtag_links({subs, text}, tags) do
172 tags =
173 tags
174 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
175 |> Enum.map(fn {name, short} -> {name, short, Ecto.UUID.generate()} end)
176
177 uuid_text =
178 tags
179 |> Enum.reduce(text, fn {match, _short, uuid}, text ->
180 String.replace(text, ~r/((?<=[^&])|(\A))#{match}/, uuid)
181 end)
182
183 subs =
184 subs ++
185 Enum.map(tags, fn {tag_text, tag, uuid} ->
186 url =
187 "<a class='hashtag' data-tag='#{tag}' href='#{Pleroma.Web.base_url()}/tag/#{tag}' rel='tag'>#{
188 tag_text
189 }</a>"
190
191 {uuid, url}
192 end)
193
194 {subs, uuid_text}
195 end
196
197 def finalize({subs, text}) do
198 Enum.reduce(subs, text, fn {uuid, replacement}, result_text ->
199 String.replace(result_text, uuid, replacement)
200 end)
201 end
202
203 def truncate(text, max_length \\ 200, omission \\ "...") do
204 # Remove trailing whitespace
205 text = Regex.replace(~r/([^ \t\r\n])([ \t]+$)/u, text, "\\g{1}")
206
207 if String.length(text) < max_length do
208 text
209 else
210 length_with_omission = max_length - String.length(omission)
211 String.slice(text, 0, length_with_omission) <> omission
212 end
213 end
214 end