Deprecate transparency_exclusions
[akkoma] / lib / pleroma / emoji / loader.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.Loader do
6 @moduledoc """
7 The Loader emoji from:
8
9 * emoji packs in INSTANCE-DIR/emoji
10 * the files: `config/emoji.txt` and `config/custom_emoji.txt`
11 * glob paths, nested folder is used as tag name for grouping e.g. priv/static/emoji/custom/nested_folder
12 """
13 alias Pleroma.Config
14 alias Pleroma.Emoji
15
16 require Logger
17
18 @mix_env Mix.env()
19
20 @type pattern :: Regex.t() | module() | String.t()
21 @type patterns :: pattern() | [pattern()]
22 @type group_patterns :: keyword(patterns())
23 @type emoji :: {String.t(), Emoji.t()}
24
25 @doc """
26 Loads emojis from files/packs.
27
28 returns list emojis in format:
29 `{"000", "/emoji/freespeechextremist.com/000.png", ["Custom"]}`
30 """
31 @spec load() :: list(emoji)
32 def load do
33 emoji_dir_path = Path.join(Config.get!([:instance, :static_dir]), "emoji")
34
35 emoji_groups = Config.get([:emoji, :groups])
36
37 emojis =
38 case File.ls(emoji_dir_path) do
39 {:error, :enoent} ->
40 # The custom emoji directory doesn't exist,
41 # don't do anything
42 []
43
44 {:error, e} ->
45 # There was some other error
46 Logger.error("Could not access the custom emoji directory #{emoji_dir_path}: #{e}")
47 []
48
49 {:ok, results} ->
50 grouped =
51 Enum.group_by(results, fn file ->
52 File.dir?(Path.join(emoji_dir_path, file))
53 end)
54
55 packs = grouped[true] || []
56 files = grouped[false] || []
57
58 # Print the packs we've found
59 Logger.info("Found emoji packs: #{Enum.join(packs, ", ")}")
60
61 if not Enum.empty?(files) do
62 Logger.warn(
63 "Found files in the emoji folder. These will be ignored, please move them to a subdirectory\nFound files: #{
64 Enum.join(files, ", ")
65 }"
66 )
67 end
68
69 emojis =
70 Enum.flat_map(packs, fn pack ->
71 load_pack(Path.join(emoji_dir_path, pack), emoji_groups)
72 end)
73
74 Emoji.clear_all()
75 emojis
76 end
77
78 # Compat thing for old custom emoji handling & default emoji,
79 # it should run even if there are no emoji packs
80 shortcode_globs = Config.get([:emoji, :shortcode_globs], [])
81
82 # for testing emoji.txt entries we do not want exposed in normal operation
83 test_emoji =
84 if @mix_env == :test do
85 load_from_file("test/config/emoji.txt", emoji_groups)
86 else
87 []
88 end
89
90 emojis_txt =
91 (load_from_file("config/emoji.txt", emoji_groups) ++
92 load_from_file("config/custom_emoji.txt", emoji_groups) ++
93 load_from_globs(shortcode_globs, emoji_groups) ++
94 test_emoji)
95 |> Enum.reject(fn value -> value == nil end)
96
97 Enum.map(emojis ++ emojis_txt, &prepare_emoji/1)
98 end
99
100 defp prepare_emoji({code, _, _} = emoji), do: {code, Emoji.build(emoji)}
101
102 defp load_pack(pack_dir, emoji_groups) do
103 pack_name = Path.basename(pack_dir)
104
105 pack_file = Path.join(pack_dir, "pack.json")
106
107 if File.exists?(pack_file) do
108 contents = Jason.decode!(File.read!(pack_file))
109
110 contents["files"]
111 |> Enum.map(fn {name, rel_file} ->
112 filename = Path.join("/emoji/#{pack_name}", rel_file)
113 {name, filename, ["pack:#{pack_name}"]}
114 end)
115 else
116 # Load from emoji.txt / all files
117 emoji_txt = Path.join(pack_dir, "emoji.txt")
118
119 if File.exists?(emoji_txt) do
120 load_from_file(emoji_txt, emoji_groups)
121 else
122 extensions = Config.get([:emoji, :pack_extensions])
123
124 Logger.info(
125 "No emoji.txt found for pack \"#{pack_name}\", assuming all #{
126 Enum.join(extensions, ", ")
127 } files are emoji"
128 )
129
130 make_shortcode_to_file_map(pack_dir, extensions)
131 |> Enum.map(fn {shortcode, rel_file} ->
132 filename = Path.join("/emoji/#{pack_name}", rel_file)
133
134 {shortcode, filename, [to_string(match_extra(emoji_groups, filename))]}
135 end)
136 end
137 end
138 end
139
140 def make_shortcode_to_file_map(pack_dir, exts) do
141 find_all_emoji(pack_dir, exts)
142 |> Enum.map(&Path.relative_to(&1, pack_dir))
143 |> Enum.map(fn f -> {f |> Path.basename() |> Path.rootname(), f} end)
144 |> Enum.into(%{})
145 end
146
147 def find_all_emoji(dir, exts) do
148 dir
149 |> File.ls!()
150 |> Enum.flat_map(fn f ->
151 filepath = Path.join(dir, f)
152
153 if File.dir?(filepath) do
154 find_all_emoji(filepath, exts)
155 else
156 [filepath]
157 end
158 end)
159 |> Enum.filter(fn f -> Path.extname(f) in exts end)
160 end
161
162 defp load_from_file(file, emoji_groups) do
163 if File.exists?(file) do
164 load_from_file_stream(File.stream!(file), emoji_groups)
165 else
166 []
167 end
168 end
169
170 defp load_from_file_stream(stream, emoji_groups) do
171 stream
172 |> Stream.map(&String.trim/1)
173 |> Stream.map(fn line ->
174 case String.split(line, ~r/,\s*/) do
175 [name, file] ->
176 {name, file, [to_string(match_extra(emoji_groups, file))]}
177
178 [name, file | tags] ->
179 {name, file, tags}
180
181 _ ->
182 nil
183 end
184 end)
185 |> Enum.to_list()
186 end
187
188 defp load_from_globs(globs, emoji_groups) do
189 static_path = Path.join(:code.priv_dir(:pleroma), "static")
190
191 paths =
192 Enum.map(globs, fn glob ->
193 Path.join(static_path, glob)
194 |> Path.wildcard()
195 end)
196 |> Enum.concat()
197
198 Enum.map(paths, fn path ->
199 tag = match_extra(emoji_groups, Path.join("/", Path.relative_to(path, static_path)))
200 shortcode = Path.basename(path, Path.extname(path))
201 external_path = Path.join("/", Path.relative_to(path, static_path))
202 {shortcode, external_path, [to_string(tag)]}
203 end)
204 end
205
206 @doc """
207 Finds a matching group for the given emoji filename
208 """
209 @spec match_extra(group_patterns(), String.t()) :: atom() | nil
210 def match_extra(group_patterns, filename) do
211 match_group_patterns(group_patterns, fn pattern ->
212 case pattern do
213 %Regex{} = regex -> Regex.match?(regex, filename)
214 string when is_binary(string) -> filename == string
215 end
216 end)
217 end
218
219 defp match_group_patterns(group_patterns, matcher) do
220 Enum.find_value(group_patterns, fn {group, patterns} ->
221 patterns =
222 patterns
223 |> List.wrap()
224 |> Enum.map(fn pattern ->
225 if String.contains?(pattern, "*") do
226 ~r(#{String.replace(pattern, "*", ".*")})
227 else
228 pattern
229 end
230 end)
231
232 Enum.any?(patterns, matcher) && group
233 end)
234 end
235 end