Merge branch 'bugfix/fix-mrf-reject-match' into 'develop'
[akkoma] / lib / pleroma / formatter.ex
1 defmodule Pleroma.Formatter do
2 alias Pleroma.User
3 alias Pleroma.Web.MediaProxy
4 alias Pleroma.HTML
5
6 @tag_regex ~r/\#\w+/u
7 def parse_tags(text, data \\ %{}) do
8 Regex.scan(@tag_regex, text)
9 |> Enum.map(fn ["#" <> tag = full_tag] -> {full_tag, String.downcase(tag)} end)
10 |> (fn map ->
11 if data["sensitive"] in [true, "True", "true", "1"],
12 do: [{"#nsfw", "nsfw"}] ++ map,
13 else: map
14 end).()
15 end
16
17 def parse_mentions(text) do
18 # Modified from https://www.w3.org/TR/html5/forms.html#valid-e-mail-address
19 regex =
20 ~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
21
22 Regex.scan(regex, text)
23 |> List.flatten()
24 |> Enum.uniq()
25 |> Enum.map(fn "@" <> match = full_match ->
26 {full_match, User.get_cached_by_nickname(match)}
27 end)
28 |> Enum.filter(fn {_match, user} -> user end)
29 end
30
31 @finmoji [
32 "a_trusted_friend",
33 "alandislands",
34 "association",
35 "auroraborealis",
36 "baby_in_a_box",
37 "bear",
38 "black_gold",
39 "christmasparty",
40 "crosscountryskiing",
41 "cupofcoffee",
42 "education",
43 "fashionista_finns",
44 "finnishlove",
45 "flag",
46 "forest",
47 "four_seasons_of_bbq",
48 "girlpower",
49 "handshake",
50 "happiness",
51 "headbanger",
52 "icebreaker",
53 "iceman",
54 "joulutorttu",
55 "kaamos",
56 "kalsarikannit_f",
57 "kalsarikannit_m",
58 "karjalanpiirakka",
59 "kicksled",
60 "kokko",
61 "lavatanssit",
62 "losthopes_f",
63 "losthopes_m",
64 "mattinykanen",
65 "meanwhileinfinland",
66 "moominmamma",
67 "nordicfamily",
68 "out_of_office",
69 "peacemaker",
70 "perkele",
71 "pesapallo",
72 "polarbear",
73 "pusa_hispida_saimensis",
74 "reindeer",
75 "sami",
76 "sauna_f",
77 "sauna_m",
78 "sauna_whisk",
79 "sisu",
80 "stuck",
81 "suomimainittu",
82 "superfood",
83 "swan",
84 "the_cap",
85 "the_conductor",
86 "the_king",
87 "the_voice",
88 "theoriginalsanta",
89 "tomoffinland",
90 "torillatavataan",
91 "unbreakable",
92 "waiting",
93 "white_nights",
94 "woollysocks"
95 ]
96
97 @finmoji_with_filenames Enum.map(@finmoji, fn finmoji ->
98 {finmoji, "/finmoji/128px/#{finmoji}-128.png"}
99 end)
100
101 @emoji_from_file (with {:ok, default} <- File.read("config/emoji.txt") do
102 custom =
103 with {:ok, custom} <- File.read("config/custom_emoji.txt") do
104 custom
105 else
106 _e -> ""
107 end
108
109 (default <> "\n" <> custom)
110 |> String.trim()
111 |> String.split(~r/\n+/)
112 |> Enum.map(fn line ->
113 [name, file] = String.split(line, ~r/,\s*/)
114 {name, file}
115 end)
116 else
117 _ -> []
118 end)
119
120 @emoji_from_globs (
121 static_path = Path.join(:code.priv_dir(:pleroma), "static")
122
123 globs =
124 Application.get_env(:pleroma, :emoji, [])
125 |> Keyword.get(:shortcode_globs, [])
126
127 paths =
128 Enum.map(globs, fn glob ->
129 Path.join(static_path, glob)
130 |> Path.wildcard()
131 end)
132 |> Enum.concat()
133
134 Enum.map(paths, fn path ->
135 shortcode = Path.basename(path, Path.extname(path))
136 external_path = Path.join("/", Path.relative_to(path, static_path))
137 {shortcode, external_path}
138 end)
139 )
140
141 @emoji @finmoji_with_filenames ++ @emoji_from_globs ++ @emoji_from_file
142
143 def emojify(text, emoji \\ @emoji)
144 def emojify(text, nil), do: text
145
146 def emojify(text, emoji) do
147 Enum.reduce(emoji, text, fn {emoji, file}, text ->
148 emoji = HTML.strip_tags(emoji)
149 file = HTML.strip_tags(file)
150
151 String.replace(
152 text,
153 ":#{emoji}:",
154 "<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{
155 MediaProxy.url(file)
156 }' />"
157 )
158 |> HTML.filter_tags()
159 end)
160 end
161
162 def get_emoji(text) when is_binary(text) do
163 Enum.filter(@emoji, fn {emoji, _} -> String.contains?(text, ":#{emoji}:") end)
164 end
165
166 def get_emoji(_), do: []
167
168 def get_custom_emoji() do
169 @emoji
170 end
171
172 @link_regex ~r/[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+/ui
173
174 # IANA got a list https://www.iana.org/assignments/uri-schemes/ but
175 # Stuff like ipfs isn’t in it
176 # There is very niche stuff
177 @uri_schemes [
178 "https://",
179 "http://",
180 "dat://",
181 "dweb://",
182 "gopher://",
183 "ipfs://",
184 "ipns://",
185 "irc:",
186 "ircs:",
187 "magnet:",
188 "mailto:",
189 "mumble:",
190 "ssb://",
191 "xmpp:"
192 ]
193
194 # TODO: make it use something other than @link_regex
195 def html_escape(text) do
196 Regex.split(@link_regex, text, include_captures: true)
197 |> Enum.map_every(2, fn chunk ->
198 {:safe, part} = Phoenix.HTML.html_escape(chunk)
199 part
200 end)
201 |> Enum.join("")
202 end
203
204 @doc "changes scheme:... urls to html links"
205 def add_links({subs, text}) do
206 additionnal_schemes =
207 Application.get_env(:pleroma, :uri_schemes, [])
208 |> Keyword.get(:additionnal_schemes, [])
209
210 links =
211 text
212 |> String.split([" ", "\t", "<br>"])
213 |> Enum.filter(fn word -> String.starts_with?(word, @uri_schemes ++ additionnal_schemes) end)
214 |> Enum.filter(fn word -> Regex.match?(@link_regex, word) end)
215 |> Enum.map(fn url -> {Ecto.UUID.generate(), url} end)
216 |> Enum.sort_by(fn {_, url} -> -String.length(url) end)
217
218 uuid_text =
219 links
220 |> Enum.reduce(text, fn {uuid, url}, acc -> String.replace(acc, url, uuid) end)
221
222 subs =
223 subs ++
224 Enum.map(links, fn {uuid, url} ->
225 {uuid, "<a href=\"#{url}\">#{url}</a>"}
226 end)
227
228 {subs, uuid_text}
229 end
230
231 @doc "Adds the links to mentioned users"
232 def add_user_links({subs, text}, mentions) do
233 mentions =
234 mentions
235 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
236 |> Enum.map(fn {name, user} -> {name, user, Ecto.UUID.generate()} end)
237
238 uuid_text =
239 mentions
240 |> Enum.reduce(text, fn {match, _user, uuid}, text ->
241 String.replace(text, match, uuid)
242 end)
243
244 subs =
245 subs ++
246 Enum.map(mentions, fn {match, %User{ap_id: ap_id, info: info}, uuid} ->
247 ap_id = info["source_data"]["url"] || ap_id
248
249 short_match = String.split(match, "@") |> tl() |> hd()
250
251 {uuid,
252 "<span><a class='mention' href='#{ap_id}'>@<span>#{short_match}</span></a></span>"}
253 end)
254
255 {subs, uuid_text}
256 end
257
258 @doc "Adds the hashtag links"
259 def add_hashtag_links({subs, text}, tags) do
260 tags =
261 tags
262 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
263 |> Enum.map(fn {name, short} -> {name, short, Ecto.UUID.generate()} end)
264
265 uuid_text =
266 tags
267 |> Enum.reduce(text, fn {match, _short, uuid}, text ->
268 String.replace(text, match, uuid)
269 end)
270
271 subs =
272 subs ++
273 Enum.map(tags, fn {tag_text, tag, uuid} ->
274 url = "<a href='#{Pleroma.Web.base_url()}/tag/#{tag}' rel='tag'>#{tag_text}</a>"
275 {uuid, url}
276 end)
277
278 {subs, uuid_text}
279 end
280
281 def finalize({subs, text}) do
282 Enum.reduce(subs, text, fn {uuid, replacement}, result_text ->
283 String.replace(result_text, uuid, replacement)
284 end)
285 end
286 end