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