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