Merge branch 'ci/bump-elixir-lint' into 'develop'
[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: #{Enum.join(files, ", ")}"
64 )
65 end
66
67 emojis =
68 Enum.flat_map(packs, fn pack ->
69 load_pack(Path.join(emoji_dir_path, pack), emoji_groups)
70 end)
71
72 Emoji.clear_all()
73 emojis
74 end
75
76 # Compat thing for old custom emoji handling & default emoji,
77 # it should run even if there are no emoji packs
78 shortcode_globs = Config.get([:emoji, :shortcode_globs], [])
79
80 # for testing emoji.txt entries we do not want exposed in normal operation
81 test_emoji =
82 if @mix_env == :test do
83 load_from_file("test/config/emoji.txt", emoji_groups)
84 else
85 []
86 end
87
88 emojis_txt =
89 (load_from_file("config/emoji.txt", emoji_groups) ++
90 load_from_file("config/custom_emoji.txt", emoji_groups) ++
91 load_from_globs(shortcode_globs, emoji_groups) ++
92 test_emoji)
93 |> Enum.reject(fn value -> value == nil end)
94
95 Enum.map(emojis ++ emojis_txt, &prepare_emoji/1)
96 end
97
98 defp prepare_emoji({code, _, _} = emoji), do: {code, Emoji.build(emoji)}
99
100 defp load_pack(pack_dir, emoji_groups) do
101 pack_name = Path.basename(pack_dir)
102
103 pack_file = Path.join(pack_dir, "pack.json")
104
105 if File.exists?(pack_file) do
106 contents = Jason.decode!(File.read!(pack_file))
107
108 contents["files"]
109 |> Enum.map(fn {name, rel_file} ->
110 filename = Path.join("/emoji/#{pack_name}", rel_file)
111 {name, filename, ["pack:#{pack_name}"]}
112 end)
113 else
114 # Load from emoji.txt / all files
115 emoji_txt = Path.join(pack_dir, "emoji.txt")
116
117 if File.exists?(emoji_txt) do
118 load_from_file(emoji_txt, emoji_groups)
119 else
120 extensions = Config.get([:emoji, :pack_extensions])
121
122 Logger.info(
123 "No emoji.txt found for pack \"#{pack_name}\", assuming all #{Enum.join(extensions, ", ")} files are emoji"
124 )
125
126 make_shortcode_to_file_map(pack_dir, extensions)
127 |> Enum.map(fn {shortcode, rel_file} ->
128 filename = Path.join("/emoji/#{pack_name}", rel_file)
129
130 {shortcode, filename, [to_string(match_extra(emoji_groups, filename))]}
131 end)
132 end
133 end
134 end
135
136 def make_shortcode_to_file_map(pack_dir, exts) do
137 find_all_emoji(pack_dir, exts)
138 |> Enum.map(&Path.relative_to(&1, pack_dir))
139 |> Enum.map(fn f -> {f |> Path.basename() |> Path.rootname(), f} end)
140 |> Enum.into(%{})
141 end
142
143 def find_all_emoji(dir, exts) do
144 dir
145 |> File.ls!()
146 |> Enum.flat_map(fn f ->
147 filepath = Path.join(dir, f)
148
149 if File.dir?(filepath) do
150 find_all_emoji(filepath, exts)
151 else
152 [filepath]
153 end
154 end)
155 |> Enum.filter(fn f -> Path.extname(f) in exts end)
156 end
157
158 defp load_from_file(file, emoji_groups) do
159 if File.exists?(file) do
160 load_from_file_stream(File.stream!(file), emoji_groups)
161 else
162 []
163 end
164 end
165
166 defp load_from_file_stream(stream, emoji_groups) do
167 stream
168 |> Stream.map(&String.trim/1)
169 |> Stream.map(fn line ->
170 case String.split(line, ~r/,\s*/) do
171 [name, file] ->
172 {name, file, [to_string(match_extra(emoji_groups, file))]}
173
174 [name, file | tags] ->
175 {name, file, tags}
176
177 _ ->
178 nil
179 end
180 end)
181 |> Enum.to_list()
182 end
183
184 defp load_from_globs(globs, emoji_groups) do
185 static_path = Path.join(:code.priv_dir(:pleroma), "static")
186
187 paths =
188 Enum.map(globs, fn glob ->
189 Path.join(static_path, glob)
190 |> Path.wildcard()
191 end)
192 |> Enum.concat()
193
194 Enum.map(paths, fn path ->
195 tag = match_extra(emoji_groups, Path.join("/", Path.relative_to(path, static_path)))
196 shortcode = Path.basename(path, Path.extname(path))
197 external_path = Path.join("/", Path.relative_to(path, static_path))
198 {shortcode, external_path, [to_string(tag)]}
199 end)
200 end
201
202 @doc """
203 Finds a matching group for the given emoji filename
204 """
205 @spec match_extra(group_patterns(), String.t()) :: atom() | nil
206 def match_extra(group_patterns, filename) do
207 match_group_patterns(group_patterns, fn pattern ->
208 case pattern do
209 %Regex{} = regex -> Regex.match?(regex, filename)
210 string when is_binary(string) -> filename == string
211 end
212 end)
213 end
214
215 defp match_group_patterns(group_patterns, matcher) do
216 Enum.find_value(group_patterns, fn {group, patterns} ->
217 patterns =
218 patterns
219 |> List.wrap()
220 |> Enum.map(fn pattern ->
221 if String.contains?(pattern, "*") do
222 ~r(#{String.replace(pattern, "*", ".*")})
223 else
224 pattern
225 end
226 end)
227
228 Enum.any?(patterns, matcher) && group
229 end)
230 end
231 end