activitypub utils: fix recipient check when the message is unaddressed (mastodon)
[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 @instance Application.get_env(:pleroma, :instance)
98
99 @finmoji_with_filenames (if Keyword.get(@instance, :finmoji_enabled) do
100 Enum.map(@finmoji, fn finmoji ->
101 {finmoji, "/finmoji/128px/#{finmoji}-128.png"}
102 end)
103 else
104 []
105 end)
106
107 @emoji_from_file (with {:ok, default} <- File.read("config/emoji.txt") do
108 custom =
109 with {:ok, custom} <- File.read("config/custom_emoji.txt") do
110 custom
111 else
112 _e -> ""
113 end
114
115 (default <> "\n" <> custom)
116 |> String.trim()
117 |> String.split(~r/\n+/)
118 |> Enum.map(fn line ->
119 [name, file] = String.split(line, ~r/,\s*/)
120 {name, file}
121 end)
122 else
123 _ -> []
124 end)
125
126 @emoji_from_globs (
127 static_path = Path.join(:code.priv_dir(:pleroma), "static")
128
129 globs =
130 Application.get_env(:pleroma, :emoji, [])
131 |> Keyword.get(:shortcode_globs, [])
132
133 paths =
134 Enum.map(globs, fn glob ->
135 Path.join(static_path, glob)
136 |> Path.wildcard()
137 end)
138 |> Enum.concat()
139
140 Enum.map(paths, fn path ->
141 shortcode = Path.basename(path, Path.extname(path))
142 external_path = Path.join("/", Path.relative_to(path, static_path))
143 {shortcode, external_path}
144 end)
145 )
146
147 @emoji @finmoji_with_filenames ++ @emoji_from_globs ++ @emoji_from_file
148
149 def emojify(text, emoji \\ @emoji)
150 def emojify(text, nil), do: text
151
152 def emojify(text, emoji) do
153 Enum.reduce(emoji, text, fn {emoji, file}, text ->
154 emoji = HTML.strip_tags(emoji)
155 file = HTML.strip_tags(file)
156
157 String.replace(
158 text,
159 ":#{emoji}:",
160 "<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{
161 MediaProxy.url(file)
162 }' />"
163 )
164 |> HTML.filter_tags()
165 end)
166 end
167
168 def get_emoji(text) when is_binary(text) do
169 Enum.filter(@emoji, fn {emoji, _} -> String.contains?(text, ":#{emoji}:") end)
170 end
171
172 def get_emoji(_), do: []
173
174 def get_custom_emoji() do
175 @emoji
176 end
177
178 @link_regex ~r/[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+/ui
179
180 @uri_schemes Application.get_env(:pleroma, :uri_schemes, [])
181 @valid_schemes Keyword.get(@uri_schemes, :valid_schemes, [])
182
183 # TODO: make it use something other than @link_regex
184 def html_escape(text, "text/html") do
185 HTML.filter_tags(text)
186 end
187
188 def html_escape(text, "text/plain") do
189 Regex.split(@link_regex, text, include_captures: true)
190 |> Enum.map_every(2, fn chunk ->
191 {:safe, part} = Phoenix.HTML.html_escape(chunk)
192 part
193 end)
194 |> Enum.join("")
195 end
196
197 @doc "changes scheme:... urls to html links"
198 def add_links({subs, text}) do
199 links =
200 text
201 |> String.split([" ", "\t", "<br>"])
202 |> Enum.filter(fn word -> String.starts_with?(word, @valid_schemes) end)
203 |> Enum.filter(fn word -> Regex.match?(@link_regex, word) end)
204 |> Enum.map(fn url -> {Ecto.UUID.generate(), url} end)
205 |> Enum.sort_by(fn {_, url} -> -String.length(url) end)
206
207 uuid_text =
208 links
209 |> Enum.reduce(text, fn {uuid, url}, acc -> String.replace(acc, url, uuid) end)
210
211 subs =
212 subs ++
213 Enum.map(links, fn {uuid, url} ->
214 {uuid, "<a href=\"#{url}\">#{url}</a>"}
215 end)
216
217 {subs, uuid_text}
218 end
219
220 @doc "Adds the links to mentioned users"
221 def add_user_links({subs, text}, mentions) do
222 mentions =
223 mentions
224 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
225 |> Enum.map(fn {name, user} -> {name, user, Ecto.UUID.generate()} end)
226
227 uuid_text =
228 mentions
229 |> Enum.reduce(text, fn {match, _user, uuid}, text ->
230 String.replace(text, match, uuid)
231 end)
232
233 subs =
234 subs ++
235 Enum.map(mentions, fn {match, %User{ap_id: ap_id, info: info}, uuid} ->
236 ap_id =
237 if is_binary(info["source_data"]["url"]) do
238 info["source_data"]["url"]
239 else
240 ap_id
241 end
242
243 short_match = String.split(match, "@") |> tl() |> hd()
244
245 {uuid,
246 "<span><a class='mention' href='#{ap_id}'>@<span>#{short_match}</span></a></span>"}
247 end)
248
249 {subs, uuid_text}
250 end
251
252 @doc "Adds the hashtag links"
253 def add_hashtag_links({subs, text}, tags) do
254 tags =
255 tags
256 |> Enum.sort_by(fn {name, _} -> -String.length(name) end)
257 |> Enum.map(fn {name, short} -> {name, short, Ecto.UUID.generate()} end)
258
259 uuid_text =
260 tags
261 |> Enum.reduce(text, fn {match, _short, uuid}, text ->
262 String.replace(text, match, uuid)
263 end)
264
265 subs =
266 subs ++
267 Enum.map(tags, fn {tag_text, tag, uuid} ->
268 url = "<a href='#{Pleroma.Web.base_url()}/tag/#{tag}' rel='tag'>#{tag_text}</a>"
269 {uuid, url}
270 end)
271
272 {subs, uuid_text}
273 end
274
275 def finalize({subs, text}) do
276 Enum.reduce(subs, text, fn {uuid, replacement}, result_text ->
277 String.replace(result_text, uuid, replacement)
278 end)
279 end
280 end