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