1 defmodule Pleroma.Emoji.Pack do
2 @derive {Jason.Encoder, only: [:files, :pack]}
9 @type t() :: %__MODULE__{
10 files: %{String.t() => Path.t()},
19 @spec emoji_path() :: Path.t()
21 static = Pleroma.Config.get!([:instance, :static_dir])
22 Path.join(static, "emoji")
25 @spec create(String.t()) :: :ok | {:error, File.posix()} | {:error, :empty_values}
26 def create(name) when byte_size(name) > 0 do
27 dir = Path.join(emoji_path(), name)
29 with :ok <- File.mkdir(dir) do
31 pack_file: Path.join(dir, "pack.json")
37 def create(_), do: {:error, :empty_values}
39 @spec show(String.t()) :: {:ok, t()} | {:loaded, nil} | {:error, :empty_values}
40 def show(name) when byte_size(name) > 0 do
41 with {_, %__MODULE__{} = pack} <- {:loaded, load_pack(name)},
42 {_, pack} <- validate_pack(pack) do
47 def show(_), do: {:error, :empty_values}
49 @spec delete(String.t()) ::
50 {:ok, [binary()]} | {:error, File.posix(), binary()} | {:error, :empty_values}
51 def delete(name) when byte_size(name) > 0 do
57 def delete(_), do: {:error, :empty_values}
59 @spec add_file(String.t(), String.t(), Path.t(), Plug.Upload.t() | String.t()) ::
60 {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
61 def add_file(name, shortcode, filename, file)
62 when byte_size(name) > 0 and byte_size(shortcode) > 0 and byte_size(filename) > 0 do
63 with {_, nil} <- {:exists, Emoji.get(shortcode)},
64 {_, %__MODULE__{} = pack} <- {:loaded, load_pack(name)} do
65 file_path = Path.join(pack.path, filename)
67 create_subdirs(file_path)
70 %Plug.Upload{path: upload_path} ->
71 # Copy the uploaded file from the temporary directory
72 File.copy!(upload_path, file_path)
74 url when is_binary(url) ->
75 # Download and write the file
76 file_contents = Tesla.get!(url).body
77 File.write!(file_path, file_contents)
80 files = Map.put(pack.files, shortcode, filename)
82 updated_pack = %{pack | files: files}
84 case save_pack(updated_pack) do
95 def add_file(_, _, _, _), do: {:error, :empty_values}
97 defp create_subdirs(file_path) do
98 if String.contains?(file_path, "/") do
105 @spec delete_file(String.t(), String.t()) ::
106 {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
107 def delete_file(name, shortcode) when byte_size(name) > 0 and byte_size(shortcode) > 0 do
108 with {_, %__MODULE__{} = pack} <- {:loaded, load_pack(name)},
109 {_, {filename, files}} when not is_nil(filename) <-
110 {:exists, Map.pop(pack.files, shortcode)},
111 emoji <- Path.join(pack.path, filename),
112 {_, true} <- {:exists, File.exists?(emoji)} do
113 emoji_dir = Path.dirname(emoji)
117 if String.contains?(filename, "/") and File.ls!(emoji_dir) == [] do
118 File.rmdir!(emoji_dir)
121 updated_pack = %{pack | files: files}
123 case save_pack(updated_pack) do
134 def delete_file(_, _), do: {:error, :empty_values}
136 @spec update_file(String.t(), String.t(), String.t(), String.t(), boolean()) ::
137 {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
138 def update_file(name, shortcode, new_shortcode, new_filename, force)
139 when byte_size(name) > 0 and byte_size(shortcode) > 0 and byte_size(new_shortcode) > 0 and
140 byte_size(new_filename) > 0 do
141 with {_, %__MODULE__{} = pack} <- {:loaded, load_pack(name)},
142 {_, {filename, files}} when not is_nil(filename) <-
143 {:exists, Map.pop(pack.files, shortcode)},
144 {_, true} <- {:not_used, force or is_nil(Emoji.get(new_shortcode))} do
145 old_path = Path.join(pack.path, filename)
146 old_dir = Path.dirname(old_path)
147 new_path = Path.join(pack.path, new_filename)
149 create_subdirs(new_path)
151 :ok = File.rename(old_path, new_path)
153 if String.contains?(filename, "/") and File.ls!(old_dir) == [] do
157 files = Map.put(files, new_shortcode, new_filename)
159 updated_pack = %{pack | files: files}
161 case save_pack(updated_pack) do
172 def update_file(_, _, _, _, _), do: {:error, :empty_values}
174 @spec import_from_filesystem() :: {:ok, [String.t()]} | {:error, atom()}
175 def import_from_filesystem do
176 emoji_path = emoji_path()
178 with {:ok, %{access: :read_write}} <- File.stat(emoji_path),
179 {:ok, results} <- File.ls(emoji_path) do
182 |> Enum.map(&Path.join(emoji_path, &1))
183 |> Enum.reject(fn path ->
184 File.dir?(path) and File.exists?(Path.join(path, "pack.json"))
186 |> Enum.map(&write_pack_contents/1)
191 {:ok, %{access: _}} -> {:error, :no_read_write}
196 defp write_pack_contents(path) do
198 files: files_from_path(path),
200 pack_file: Path.join(path, "pack.json")
203 case save_pack(pack) do
204 :ok -> Path.basename(path)
209 defp files_from_path(path) do
210 txt_path = Path.join(path, "emoji.txt")
212 if File.exists?(txt_path) do
213 # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
214 # Make a pack.json file from the contents of that emoji.txt file
216 # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
218 # Create a map of shortcodes to filenames from emoji.txt
220 |> String.split("\n")
221 |> Enum.map(&String.trim/1)
222 |> Enum.map(fn line ->
223 case String.split(line, ~r/,\s*/) do
224 # This matches both strings with and without tags
225 # and we don't care about tags here
227 file_dir_name = Path.dirname(file)
230 if String.ends_with?(path, file_dir_name) do
245 # If there's no emoji.txt, assume all files
246 # that are of certain extensions from the config are emojis and import them all
247 pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
248 Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
252 @spec list_remote(String.t()) :: {:ok, map()}
253 def list_remote(url) do
259 with {_, true} <- {:shareable, shareable_packs_available?(uri)} do
262 |> URI.merge("/api/pleroma/emoji/packs")
272 @spec list_local() :: {:ok, map()}
274 emoji_path = emoji_path()
276 # Create the directory first if it does not exist. This is probably the first request made
277 # with the API so it should be sufficient
278 with {:create_dir, :ok} <- {:create_dir, File.mkdir_p(emoji_path)},
279 {:ls, {:ok, results}} <- {:ls, File.ls(emoji_path)} do
282 |> Enum.map(&load_pack/1)
284 |> Enum.map(&validate_pack/1)
291 defp validate_pack(pack) do
292 if downloadable?(pack) do
293 archive = fetch_archive(pack)
294 archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
298 |> Map.put("can-download", true)
299 |> Map.put("download-sha256", archive_sha)
301 {pack.name, Map.put(pack, :pack, info)}
303 info = Map.put(pack.pack, "can-download", false)
304 {pack.name, Map.put(pack, :pack, info)}
308 defp downloadable?(pack) do
309 # If the pack is set as shared, check if it can be downloaded
310 # That means that when asked, the pack can be packed and sent to the remote
311 # Otherwise, they'd have to download it from external-src
312 pack.pack["share-files"] &&
313 Enum.all?(pack.files, fn {_, file} ->
314 File.exists?(Path.join(pack.path, file))
318 @spec get_archive(String.t()) :: {:ok, binary()}
319 def get_archive(name) do
320 with {_, %__MODULE__{} = pack} <- {:exists?, load_pack(name)},
321 {_, true} <- {:can_download?, downloadable?(pack)} do
322 {:ok, fetch_archive(pack)}
326 defp fetch_archive(pack) do
327 hash = :crypto.hash(:md5, File.read!(pack.pack_file))
329 case Cachex.get!(:emoji_packs_cache, pack.name) do
330 %{hash: ^hash, pack_data: archive} ->
334 create_archive_and_cache(pack, hash)
338 defp create_archive_and_cache(pack, hash) do
339 files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
342 :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
344 ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
345 overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
350 # if pack.json MD5 changes, the cache is not valid anymore
351 %{hash: hash, pack_data: result},
352 # Add a minute to cache time for every file in the pack
359 @spec download(String.t(), String.t(), String.t()) :: :ok
360 def download(name, url, as) do
366 with {_, true} <- {:shareable, shareable_packs_available?(uri)} do
369 |> URI.merge("/api/pleroma/emoji/packs/#{name}")
376 case remote_pack["pack"] do
377 %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
381 url: URI.merge(uri, "/api/pleroma/emoji/packs/#{name}/archive") |> to_string()
384 %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
394 "The pack was not set as shared and there is no fallback src to download from"}
397 with {:ok, %{sha: sha, url: url} = pinfo} <- result,
398 %{body: archive} <- Tesla.get!(url),
399 {_, true} <- {:checksum, Base.decode16!(sha) == :crypto.hash(:sha256, archive)} do
400 local_name = as || name
402 path = Path.join(emoji_path(), local_name)
407 files: remote_pack["files"],
408 pack_file: Path.join(path, "pack.json")
411 File.mkdir_p!(pack.path)
413 files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
414 # Fallback cannot contain a pack.json file
415 files = if pinfo[:fallback], do: files, else: ['pack.json' | files]
417 {:ok, _} = :zip.unzip(archive, cwd: to_charlist(pack.path), file_list: files)
419 # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
420 # in it to depend on itself
421 if pinfo[:fallback] do
430 defp save_pack(pack), do: File.write(pack.pack_file, Jason.encode!(pack, pretty: true))
432 @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
433 def save_metadata(metadata, %__MODULE__{} = pack) do
434 pack = Map.put(pack, :pack, metadata)
436 with :ok <- save_pack(pack) do
441 @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
442 def update_metadata(name, data) do
443 pack = load_pack(name)
446 not is_nil(data["fallback-src"]) and data["fallback-src"] != pack.pack["fallback-src"]
448 with {_, true} <- {:update?, fb_sha_changed?},
449 {:ok, %{body: zip}} <- Tesla.get(data["fallback-src"]),
450 {:ok, f_list} <- :zip.unzip(zip, [:memory]),
451 {_, true} <- {:has_all_files?, has_all_files?(pack.files, f_list)} do
452 fallback_sha = :crypto.hash(:sha256, zip) |> Base.encode16()
455 |> Map.put("fallback-src-sha256", fallback_sha)
456 |> save_metadata(pack)
458 {:update?, _} -> save_metadata(data, pack)
463 # Check if all files from the pack.json are in the archive
464 defp has_all_files?(files, f_list) do
465 Enum.all?(files, fn {_, from_manifest} ->
466 List.keyfind(f_list, to_charlist(from_manifest), 0)
470 @spec load_pack(String.t()) :: t() | nil
471 def load_pack(name) do
472 pack_file = Path.join([emoji_path(), name, "pack.json"])
474 if File.exists?(pack_file) do
478 |> Map.put(:pack_file, pack_file)
479 |> Map.put(:path, Path.dirname(pack_file))
480 |> Map.put(:name, name)
484 defp from_json(json) do
485 map = Jason.decode!(json)
487 struct(__MODULE__, %{files: map["files"], pack: map["pack"]})
490 defp shareable_packs_available?(uri) do
492 |> URI.merge("/.well-known/nodeinfo")
500 # Get the actual nodeinfo address and fetch it
504 |> get_in(["metadata", "features"])
505 |> Enum.member?("shareable_emoji_packs")