logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

loader.ex (6816B)


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