1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Emoji do
7 This GenServer stores in an ETS table the list of the loaded emojis,
8 and also allows to reload the list at runtime.
12 alias Pleroma.Emoji.Loader
21 {:read_concurrency, true}
24 defstruct [:code, :file, :tags, :safe_code, :safe_file]
26 @doc "Build emoji struct"
27 def build({code, file, tags}) do
32 safe_code: Pleroma.HTML.strip_tags(code),
33 safe_file: Pleroma.HTML.strip_tags(file)
37 def build({code, file}), do: build({code, file, []})
41 GenServer.start_link(__MODULE__, [], name: __MODULE__)
44 @doc "Reloads the emojis from disk."
47 GenServer.call(__MODULE__, :reload)
50 @doc "Returns the path of the emoji `name`."
51 @spec get(String.t()) :: String.t() | nil
54 if String.starts_with?(name, ":") do
56 |> String.replace_leading(":", "")
57 |> String.replace_trailing(":", "")
62 case :ets.lookup(@ets, name) do
68 @spec exist?(String.t()) :: boolean()
69 def exist?(name), do: not is_nil(get(name))
71 @doc "Returns all the emojos!!"
72 @spec get_all() :: list({String.t(), String.t(), String.t()})
77 @doc "Clear out old emojis"
78 def clear_all, do: :ets.delete_all_objects(@ets)
82 @ets = :ets.new(@ets, @ets_options)
83 GenServer.cast(self(), :reload)
88 def handle_cast(:reload, state) do
89 update_emojis(Loader.load())
94 def handle_call(:reload, _from, state) do
95 update_emojis(Loader.load())
100 def terminate(_, _) do
105 def code_change(_old_vsn, state, _extra) do
106 update_emojis(Loader.load())
110 defp update_emojis(emojis) do
111 :ets.insert(@ets, emojis)
114 @external_resource "lib/pleroma/emoji-test.txt"
116 regional_indicators =
117 Enum.map(127_462..127_487, fn codepoint ->
124 |> String.split("\n")
125 |> Enum.filter(fn line ->
126 line != "" and not String.starts_with?(line, "#") and
127 String.contains?(line, "qualified")
129 |> Enum.map(fn line ->
131 |> String.split(";", parts: 2)
135 |> Enum.map(fn codepoint ->
136 <<String.to_integer(codepoint, 16)::utf8>>
142 emojis = emojis ++ regional_indicators
144 for emoji <- emojis do
145 def is_unicode_emoji?(unquote(emoji)), do: true
148 def is_unicode_emoji?(_), do: false
150 def stripped_name(name) when is_binary(name) do
152 |> String.replace_leading(":", "")
153 |> String.replace_trailing(":", "")
156 def stripped_name(name), do: name
158 def maybe_quote(name) when is_binary(name) do
159 if is_unicode_emoji?(name) do
162 if String.starts_with?(name, ":") do
170 def maybe_quote(name), do: name
172 def emoji_url(%{"type" => "EmojiReact", "content" => _, "tag" => []}), do: nil
174 def emoji_url(%{"type" => "EmojiReact", "content" => emoji, "tag" => tags}) do
177 |> Enum.find(fn tag -> tag["type"] == "Emoji" && tag["name"] == stripped_name(emoji) end)
188 def emoji_url(_), do: nil