1 defmodule Pleroma.Emoji.Pack do
2 @derive {Jason.Encoder, only: [:files, :pack, :files_count]}
10 @type t() :: %__MODULE__{
11 files: %{String.t() => Path.t()},
12 files_count: non_neg_integer(),
21 @spec create(String.t()) :: {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
23 with :ok <- validate_not_empty([name]),
24 dir <- Path.join(emoji_path(), name),
25 :ok <- File.mkdir(dir) do
26 %__MODULE__{pack_file: Path.join(dir, "pack.json")}
31 defp paginate(entities, 1, page_size), do: Enum.take(entities, page_size)
33 defp paginate(entities, page, page_size) do
35 |> Enum.chunk_every(page_size)
39 @spec show(keyword()) :: {:ok, t()} | {:error, atom()}
43 with :ok <- validate_not_empty([name]),
44 {:ok, pack} <- load_pack(name) do
49 |> paginate(opts[:page], opts[:page_size])
51 pack = Map.put(pack, :files, Map.take(pack.files, shortcodes))
53 {:ok, validate_pack(pack)}
57 @spec delete(String.t()) ::
58 {:ok, [binary()]} | {:error, File.posix(), binary()} | {:error, :empty_values}
60 with :ok <- validate_not_empty([name]) do
67 @spec add_file(String.t(), String.t(), Path.t(), Plug.Upload.t() | String.t()) ::
68 {:ok, t()} | {:error, File.posix() | atom()}
69 def add_file(name, shortcode, filename, file) do
70 with :ok <- validate_not_empty([name, shortcode, filename]),
71 :ok <- validate_emoji_not_exists(shortcode),
72 {:ok, pack} <- load_pack(name),
73 :ok <- save_file(file, pack, filename),
74 {:ok, updated_pack} <- pack |> put_emoji(shortcode, filename) |> save_pack() do
80 @spec delete_file(String.t(), String.t()) ::
81 {:ok, t()} | {:error, File.posix() | atom()}
82 def delete_file(name, shortcode) do
83 with :ok <- validate_not_empty([name, shortcode]),
84 {:ok, pack} <- load_pack(name),
85 :ok <- remove_file(pack, shortcode),
86 {:ok, updated_pack} <- pack |> delete_emoji(shortcode) |> save_pack() do
92 @spec update_file(String.t(), String.t(), String.t(), String.t(), boolean()) ::
93 {:ok, t()} | {:error, File.posix() | atom()}
94 def update_file(name, shortcode, new_shortcode, new_filename, force) do
95 with :ok <- validate_not_empty([name, shortcode, new_shortcode, new_filename]),
96 {:ok, pack} <- load_pack(name),
97 {:ok, filename} <- get_filename(pack, shortcode),
98 :ok <- validate_emoji_not_exists(new_shortcode, force),
99 :ok <- rename_file(pack, filename, new_filename),
100 {:ok, updated_pack} <-
102 |> delete_emoji(shortcode)
103 |> put_emoji(new_shortcode, new_filename)
110 @spec import_from_filesystem() :: {:ok, [String.t()]} | {:error, File.posix() | atom()}
111 def import_from_filesystem do
112 emoji_path = emoji_path()
114 with {:ok, %{access: :read_write}} <- File.stat(emoji_path),
115 {:ok, results} <- File.ls(emoji_path) do
118 |> Enum.map(&Path.join(emoji_path, &1))
119 |> Enum.reject(fn path ->
120 File.dir?(path) and File.exists?(Path.join(path, "pack.json"))
122 |> Enum.map(&write_pack_contents/1)
123 |> Enum.reject(&is_nil/1)
127 {:ok, %{access: _}} -> {:error, :no_read_write}
132 @spec list_remote(String.t()) :: {:ok, map()} | {:error, atom()}
133 def list_remote(url) do
134 uri = url |> String.trim() |> URI.parse()
136 with :ok <- validate_shareable_packs_available(uri) do
138 |> URI.merge("/api/pleroma/emoji/packs")
143 @spec list_local(keyword()) :: {:ok, map(), non_neg_integer()}
144 def list_local(opts) do
145 with {:ok, results} <- list_packs_dir() do
148 |> Enum.map(fn name ->
149 case load_pack(name) do
154 |> Enum.reject(&is_nil/1)
158 |> paginate(opts[:page], opts[:page_size])
159 |> Map.new(fn pack -> {pack.name, validate_pack(pack)} end)
161 {:ok, packs, length(all_packs)}
165 @spec get_archive(String.t()) :: {:ok, binary()} | {:error, atom()}
166 def get_archive(name) do
167 with {:ok, pack} <- load_pack(name),
168 :ok <- validate_downloadable(pack) do
169 {:ok, fetch_archive(pack)}
173 @spec download(String.t(), String.t(), String.t()) :: {:ok, t()} | {:error, atom()}
174 def download(name, url, as) do
175 uri = url |> String.trim() |> URI.parse()
177 with :ok <- validate_shareable_packs_available(uri),
178 {:ok, remote_pack} <- uri |> URI.merge("/api/pleroma/emoji/packs/#{name}") |> http_get(),
179 {:ok, %{sha: sha, url: url} = pack_info} <- fetch_pack_info(remote_pack, uri, name),
180 {:ok, archive} <- download_archive(url, sha),
181 pack <- copy_as(remote_pack, as || name),
182 {:ok, _} = unzip(archive, pack_info, remote_pack, pack) do
183 # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
184 # in it to depend on itself
185 if pack_info[:fallback] do
193 @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
194 def save_metadata(metadata, %__MODULE__{} = pack) do
196 |> Map.put(:pack, metadata)
200 @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
201 def update_metadata(name, data) do
202 with {:ok, pack} <- load_pack(name) do
203 if fallback_sha_changed?(pack, data) do
204 update_sha_and_save_metadata(pack, data)
206 save_metadata(data, pack)
211 @spec load_pack(String.t()) :: {:ok, t()} | {:error, :not_found}
212 def load_pack(name) do
213 pack_file = Path.join([emoji_path(), name, "pack.json"])
215 if File.exists?(pack_file) do
220 |> Map.put(:pack_file, pack_file)
221 |> Map.put(:path, Path.dirname(pack_file))
222 |> Map.put(:name, name)
229 {:ok, Map.put(pack, :files_count, files_count)}
235 @spec emoji_path() :: Path.t()
237 [:instance, :static_dir]
238 |> Pleroma.Config.get!()
239 |> Path.join("emoji")
242 defp validate_emoji_not_exists(shortcode, force \\ false)
243 defp validate_emoji_not_exists(_shortcode, true), do: :ok
245 defp validate_emoji_not_exists(shortcode, _) do
246 case Emoji.get(shortcode) do
248 _ -> {:error, :already_exists}
252 defp write_pack_contents(path) do
254 files: files_from_path(path),
256 pack_file: Path.join(path, "pack.json")
259 case save_pack(pack) do
260 {:ok, _pack} -> Path.basename(path)
265 defp files_from_path(path) do
266 txt_path = Path.join(path, "emoji.txt")
268 if File.exists?(txt_path) do
269 # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
270 # Make a pack.json file from the contents of that emoji.txt file
272 # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
274 # Create a map of shortcodes to filenames from emoji.txt
277 |> String.split("\n")
278 |> Enum.map(&String.trim/1)
279 |> Enum.map(fn line ->
280 case String.split(line, ~r/,\s*/) do
281 # This matches both strings with and without tags
282 # and we don't care about tags here
284 file_dir_name = Path.dirname(file)
286 if String.ends_with?(path, file_dir_name) do
287 {name, Path.basename(file)}
296 |> Enum.reject(&is_nil/1)
299 # If there's no emoji.txt, assume all files
300 # that are of certain extensions from the config are emojis and import them all
301 pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
302 Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
306 defp validate_pack(pack) do
308 if downloadable?(pack) do
309 archive = fetch_archive(pack)
310 archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
313 |> Map.put("can-download", true)
314 |> Map.put("download-sha256", archive_sha)
316 Map.put(pack.pack, "can-download", false)
319 Map.put(pack, :pack, info)
322 defp downloadable?(pack) do
323 # If the pack is set as shared, check if it can be downloaded
324 # That means that when asked, the pack can be packed and sent to the remote
325 # Otherwise, they'd have to download it from external-src
326 pack.pack["share-files"] &&
327 Enum.all?(pack.files, fn {_, file} ->
334 defp create_archive_and_cache(pack, hash) do
335 files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
338 :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
340 ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
341 overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
346 # if pack.json MD5 changes, the cache is not valid anymore
347 %{hash: hash, pack_data: result},
348 # Add a minute to cache time for every file in the pack
355 defp save_pack(pack) do
356 with {:ok, json} <- Jason.encode(pack, pretty: true),
357 :ok <- File.write(pack.pack_file, json) do
362 defp from_json(json) do
363 map = Jason.decode!(json)
365 struct(__MODULE__, %{files: map["files"], pack: map["pack"]})
368 defp validate_shareable_packs_available(uri) do
369 with {:ok, %{"links" => links}} <- uri |> URI.merge("/.well-known/nodeinfo") |> http_get(),
370 # Get the actual nodeinfo address and fetch it
371 {:ok, %{"metadata" => %{"features" => features}}} <-
372 links |> List.last() |> Map.get("href") |> http_get() do
373 if Enum.member?(features, "shareable_emoji_packs") do
376 {:error, :not_shareable}
381 defp validate_not_empty(list) do
382 if Enum.all?(list, fn i -> is_binary(i) and i != "" end) do
385 {:error, :empty_values}
389 defp save_file(file, pack, filename) do
390 file_path = Path.join(pack.path, filename)
391 create_subdirs(file_path)
394 %Plug.Upload{path: upload_path} ->
395 # Copy the uploaded file from the temporary directory
396 with {:ok, _} <- File.copy(upload_path, file_path), do: :ok
398 url when is_binary(url) ->
399 # Download and write the file
400 file_contents = Tesla.get!(url).body
401 File.write(file_path, file_contents)
405 defp put_emoji(pack, shortcode, filename) do
406 files = Map.put(pack.files, shortcode, filename)
407 %{pack | files: files}
410 defp delete_emoji(pack, shortcode) do
411 files = Map.delete(pack.files, shortcode)
412 %{pack | files: files}
415 defp rename_file(pack, filename, new_filename) do
416 old_path = Path.join(pack.path, filename)
417 new_path = Path.join(pack.path, new_filename)
418 create_subdirs(new_path)
420 with :ok <- File.rename(old_path, new_path) do
421 remove_dir_if_empty(old_path, filename)
425 defp create_subdirs(file_path) do
426 if String.contains?(file_path, "/") do
433 defp remove_file(pack, shortcode) do
434 with {:ok, filename} <- get_filename(pack, shortcode),
435 emoji <- Path.join(pack.path, filename),
436 :ok <- File.rm(emoji) do
437 remove_dir_if_empty(emoji, filename)
441 defp remove_dir_if_empty(emoji, filename) do
442 dir = Path.dirname(emoji)
444 if String.contains?(filename, "/") and File.ls!(dir) == [] do
451 defp get_filename(pack, shortcode) do
452 with %{^shortcode => filename} when is_binary(filename) <- pack.files,
453 true <- pack.path |> Path.join(filename) |> File.exists?() do
456 _ -> {:error, :doesnt_exist}
460 defp http_get(%URI{} = url), do: url |> to_string() |> http_get()
462 defp http_get(url) do
463 with {:ok, %{body: body}} <- url |> Pleroma.HTTP.get() do
468 defp list_packs_dir do
469 emoji_path = emoji_path()
470 # Create the directory first if it does not exist. This is probably the first request made
471 # with the API so it should be sufficient
472 with {:create_dir, :ok} <- {:create_dir, File.mkdir_p(emoji_path)},
473 {:ls, {:ok, results}} <- {:ls, File.ls(emoji_path)} do
474 {:ok, Enum.sort(results)}
476 {:create_dir, {:error, e}} -> {:error, :create_dir, e}
477 {:ls, {:error, e}} -> {:error, :ls, e}
481 defp validate_downloadable(pack) do
482 if downloadable?(pack), do: :ok, else: {:error, :cant_download}
485 defp copy_as(remote_pack, local_name) do
486 path = Path.join(emoji_path(), local_name)
491 files: remote_pack["files"],
492 pack_file: Path.join(path, "pack.json")
496 defp unzip(archive, pack_info, remote_pack, local_pack) do
497 with :ok <- File.mkdir_p!(local_pack.path) do
498 files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
499 # Fallback cannot contain a pack.json file
500 files = if pack_info[:fallback], do: files, else: ['pack.json' | files]
502 :zip.unzip(archive, cwd: to_charlist(local_pack.path), file_list: files)
506 defp fetch_pack_info(remote_pack, uri, name) do
507 case remote_pack["pack"] do
508 %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
512 url: URI.merge(uri, "/api/pleroma/emoji/packs/#{name}/archive") |> to_string()
515 %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
524 {:error, "The pack was not set as shared and there is no fallback src to download from"}
528 defp download_archive(url, sha) do
529 with {:ok, %{body: archive}} <- Tesla.get(url) do
530 if Base.decode16!(sha) == :crypto.hash(:sha256, archive) do
533 {:error, :invalid_checksum}
538 defp fetch_archive(pack) do
539 hash = :crypto.hash(:md5, File.read!(pack.pack_file))
541 case Cachex.get!(:emoji_packs_cache, pack.name) do
542 %{hash: ^hash, pack_data: archive} -> archive
543 _ -> create_archive_and_cache(pack, hash)
547 defp fallback_sha_changed?(pack, data) do
548 is_binary(data[:"fallback-src"]) and data[:"fallback-src"] != pack.pack["fallback-src"]
551 defp update_sha_and_save_metadata(pack, data) do
552 with {:ok, %{body: zip}} <- Tesla.get(data[:"fallback-src"]),
553 :ok <- validate_has_all_files(pack, zip) do
554 fallback_sha = :sha256 |> :crypto.hash(zip) |> Base.encode16()
557 |> Map.put("fallback-src-sha256", fallback_sha)
558 |> save_metadata(pack)
562 defp validate_has_all_files(pack, zip) do
563 with {:ok, f_list} <- :zip.unzip(zip, [:memory]) do
564 # Check if all files from the pack.json are in the archive
566 |> Enum.all?(fn {_, from_manifest} ->
567 List.keyfind(f_list, to_charlist(from_manifest), 0)
569 |> if(do: :ok, else: {:error, :incomplete})