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