Ensure we can update contentMap on update
[akkoma] / lib / pleroma / emoji / formatter.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Emoji.Formatter do
6 alias Pleroma.Emoji
7 alias Pleroma.HTML
8 alias Pleroma.Web.Endpoint
9 alias Pleroma.Web.MediaProxy
10
11 def emojify(text) do
12 emojify(text, Emoji.get_all())
13 end
14
15 def emojify(text, nil), do: text
16
17 def emojify(text, emoji, strip \\ false) do
18 Enum.reduce(emoji, text, fn
19 {_, %Emoji{safe_code: emoji, safe_file: file}}, text ->
20 String.replace(text, ":#{emoji}:", prepare_emoji_html(emoji, file, strip))
21
22 {unsafe_emoji, unsafe_file}, text ->
23 emoji = HTML.strip_tags(unsafe_emoji)
24 file = HTML.strip_tags(unsafe_file)
25 String.replace(text, ":#{emoji}:", prepare_emoji_html(emoji, file, strip))
26 end)
27 |> HTML.filter_tags()
28 end
29
30 defp prepare_emoji_html(_emoji, _file, true), do: ""
31
32 defp prepare_emoji_html(emoji, file, _strip) do
33 "<img class='emoji' alt='#{emoji}' title='#{emoji}' src='#{MediaProxy.url(file)}' />"
34 end
35
36 def demojify(text) do
37 emojify(text, Emoji.get_all(), true)
38 end
39
40 def demojify(text, nil), do: text
41
42 @doc "Outputs a list of the emoji-Maps in a text"
43 def get_emoji_map(text) when is_binary(text) do
44 Emoji.get_all()
45 |> Enum.filter(fn {emoji, %Emoji{}} -> String.contains?(text, ":#{emoji}:") end)
46 |> Enum.reduce(%{}, fn {name, %Emoji{file: file}}, acc ->
47 Map.put(acc, name, to_string(URI.merge(Endpoint.url(), file)))
48 end)
49 end
50
51 def get_emoji_map(_), do: %{}
52 end