Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[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.Emoji
7 alias Pleroma.HTML
8 alias Pleroma.User
9 alias Pleroma.Web.MediaProxy
10
11 @safe_mention_regex ~r/^(\s*(?<mentions>@.+?\s+)+)(?<rest>.*)/
12 @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
13 @link_regex ~r{((?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~%:/?#[\]@!\$&'\(\)\*\+,;=.]+)|[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+}ui
14 # credo:disable-for-previous-line Credo.Check.Readability.MaxLineLength
15
16 @auto_linker_config hashtag: true,
17 hashtag_handler: &Pleroma.Formatter.hashtag_handler/4,
18 mention: true,
19 mention_handler: &Pleroma.Formatter.mention_handler/4
20
21 def mention_handler("@" <> nickname, buffer, opts, acc) do
22 case User.get_cached_by_nickname(nickname) do
23 %User{id: id} = user ->
24 ap_id = get_ap_id(user)
25 nickname_text = get_nickname_text(nickname, opts) |> maybe_escape(opts)
26
27 link =
28 "<span class='h-card'><a data-user='#{id}' class='u-url mention' href='#{ap_id}'>@<span>#{
29 nickname_text
30 }</span></a></span>"
31
32 {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, user})}}
33
34 _ ->
35 {buffer, acc}
36 end
37 end
38
39 def hashtag_handler("#" <> tag = tag_text, _buffer, _opts, acc) do
40 tag = String.downcase(tag)
41 url = "#{Pleroma.Web.base_url()}/tag/#{tag}"
42 link = "<a class='hashtag' data-tag='#{tag}' href='#{url}' rel='tag'>#{tag_text}</a>"
43
44 {link, %{acc | tags: MapSet.put(acc.tags, {tag_text, tag})}}
45 end
46
47 @doc """
48 Parses a text and replace plain text links with HTML. Returns a tuple with a result text, mentions, and hashtags.
49
50 If the 'safe_mention' option is given, only consecutive mentions at the start the post are actually mentioned.
51 """
52 @spec linkify(String.t(), keyword()) ::
53 {String.t(), [{String.t(), User.t()}], [{String.t(), String.t()}]}
54 def linkify(text, options \\ []) do
55 options = options ++ @auto_linker_config
56
57 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
58 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
59 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
60
61 {text_mentions, %{mentions: mentions}} = AutoLinker.link_map(mentions, acc, options)
62 {text_rest, %{tags: tags}} = AutoLinker.link_map(rest, acc, options)
63
64 {text_mentions <> text_rest, MapSet.to_list(mentions), MapSet.to_list(tags)}
65 else
66 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
67 {text, %{mentions: mentions, tags: tags}} = AutoLinker.link_map(text, acc, options)
68
69 {text, MapSet.to_list(mentions), MapSet.to_list(tags)}
70 end
71 end
72
73 def emojify(text) do
74 emojify(text, Emoji.get_all())
75 end
76
77 def emojify(text, nil), do: text
78
79 def emojify(text, emoji, strip \\ false) do
80 Enum.reduce(emoji, text, fn emoji_data, text ->
81 emoji = HTML.strip_tags(elem(emoji_data, 0))
82 file = HTML.strip_tags(elem(emoji_data, 1))
83
84 html =
85 if not strip do
86 "<img height='32px' width='32px' alt='#{emoji}' title='#{emoji}' src='#{
87 MediaProxy.url(file)
88 }' />"
89 else
90 ""
91 end
92
93 String.replace(text, ":#{emoji}:", html) |> HTML.filter_tags()
94 end)
95 end
96
97 def demojify(text) do
98 emojify(text, Emoji.get_all(), true)
99 end
100
101 def demojify(text, nil), do: text
102
103 def get_emoji(text) when is_binary(text) do
104 Enum.filter(Emoji.get_all(), fn {emoji, _, _} -> String.contains?(text, ":#{emoji}:") end)
105 end
106
107 def get_emoji(_), do: []
108
109 def html_escape({text, mentions, hashtags}, type) do
110 {html_escape(text, type), mentions, hashtags}
111 end
112
113 def html_escape(text, "text/html") do
114 HTML.filter_tags(text)
115 end
116
117 def html_escape(text, "text/plain") do
118 Regex.split(@link_regex, text, include_captures: true)
119 |> Enum.map_every(2, fn chunk ->
120 {:safe, part} = Phoenix.HTML.html_escape(chunk)
121 part
122 end)
123 |> Enum.join("")
124 end
125
126 def truncate(text, max_length \\ 200, omission \\ "...") do
127 # Remove trailing whitespace
128 text = Regex.replace(~r/([^ \t\r\n])([ \t]+$)/u, text, "\\g{1}")
129
130 if String.length(text) < max_length do
131 text
132 else
133 length_with_omission = max_length - String.length(omission)
134 String.slice(text, 0, length_with_omission) <> omission
135 end
136 end
137
138 defp get_ap_id(%User{info: %{source_data: %{"url" => url}}}) when is_binary(url), do: url
139 defp get_ap_id(%User{ap_id: ap_id}), do: ap_id
140
141 defp get_nickname_text(nickname, %{mentions_format: :full}), do: User.full_nickname(nickname)
142 defp get_nickname_text(nickname, _), do: User.local_nickname(nickname)
143
144 defp maybe_escape(str, %{mentions_escape: true}) do
145 String.replace(str, @markdown_characters_regex, "\\\\\\1")
146 end
147
148 defp maybe_escape(str, _), do: str
149 end