1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Emoji.Pack do
6 @derive {Jason.Encoder, only: [:files, :pack, :files_count]}
14 @type t() :: %__MODULE__{
15 files: %{String.t() => Path.t()},
16 files_count: non_neg_integer(),
23 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
26 alias Pleroma.Emoji.Pack
29 @spec create(String.t()) :: {:ok, t()} | {:error, File.posix()} | {:error, :empty_values}
31 with :ok <- validate_not_empty([name]),
32 dir <- Path.join(emoji_path(), name),
33 :ok <- File.mkdir(dir) do
34 save_pack(%__MODULE__{pack_file: Path.join(dir, "pack.json")})
38 defp paginate(entities, 1, page_size), do: Enum.take(entities, page_size)
40 defp paginate(entities, page, page_size) do
42 |> Enum.chunk_every(page_size)
46 @spec show(keyword()) :: {:ok, t()} | {:error, atom()}
50 with :ok <- validate_not_empty([name]),
51 {:ok, pack} <- load_pack(name) do
56 |> paginate(opts[:page], opts[:page_size])
58 pack = Map.put(pack, :files, Map.take(pack.files, shortcodes))
60 {:ok, validate_pack(pack)}
64 @spec delete(String.t()) ::
65 {:ok, [binary()]} | {:error, File.posix(), binary()} | {:error, :empty_values}
67 with :ok <- validate_not_empty([name]),
68 pack_path <- Path.join(emoji_path(), name) do
73 @spec unpack_zip_emojies(list(tuple())) :: list(map())
74 defp unpack_zip_emojies(zip_files) do
75 Enum.reduce(zip_files, [], fn
76 {_, path, s, _, _, _}, acc when elem(s, 2) == :regular ->
78 filename <- Path.basename(path),
79 shortcode <- Path.basename(filename, Path.extname(filename)),
80 false <- Emoji.exist?(shortcode)
82 [%{path: path, filename: path, shortcode: shortcode} | acc]
92 @spec add_file(t(), String.t(), Path.t(), Plug.Upload.t()) ::
94 | {:error, File.posix() | atom()}
95 def add_file(%Pack{} = pack, _, _, %Plug.Upload{content_type: "application/zip"} = file) do
96 with {:ok, zip_files} <- :zip.table(to_charlist(file.path)),
97 [_ | _] = emojies <- unpack_zip_emojies(zip_files),
98 {:ok, tmp_dir} <- Utils.tmp_dir("emoji") do
100 {:ok, _emoji_files} =
102 to_charlist(file.path),
103 [{:file_list, Enum.map(emojies, & &1[:path])}, {:cwd, tmp_dir}]
107 Enum.map_reduce(emojies, pack, fn item, emoji_pack ->
108 emoji_file = %Plug.Upload{
109 filename: item[:filename],
110 path: Path.join(tmp_dir, item[:path])
113 {:ok, updated_pack} =
117 to_string(item[:filename]),
131 {:error, _} = error ->
139 def add_file(%Pack{} = pack, shortcode, filename, %Plug.Upload{} = file) do
140 with :ok <- validate_not_empty([shortcode, filename]),
141 :ok <- validate_emoji_not_exists(shortcode),
142 {:ok, updated_pack} <- do_add_file(pack, shortcode, filename, file) do
148 defp do_add_file(pack, shortcode, filename, file) do
149 with :ok <- save_file(file, pack, filename) do
151 |> put_emoji(shortcode, filename)
156 @spec delete_file(t(), String.t()) ::
157 {:ok, t()} | {:error, File.posix() | atom()}
158 def delete_file(%Pack{} = pack, shortcode) do
159 with :ok <- validate_not_empty([shortcode]),
160 :ok <- remove_file(pack, shortcode),
161 {:ok, updated_pack} <- pack |> delete_emoji(shortcode) |> save_pack() do
167 @spec update_file(t(), String.t(), String.t(), String.t(), boolean()) ::
168 {:ok, t()} | {:error, File.posix() | atom()}
169 def update_file(%Pack{} = pack, shortcode, new_shortcode, new_filename, force) do
170 with :ok <- validate_not_empty([shortcode, new_shortcode, new_filename]),
171 {:ok, filename} <- get_filename(pack, shortcode),
172 :ok <- validate_emoji_not_exists(new_shortcode, force),
173 :ok <- rename_file(pack, filename, new_filename),
174 {:ok, updated_pack} <-
176 |> delete_emoji(shortcode)
177 |> put_emoji(new_shortcode, new_filename)
184 @spec import_from_filesystem() :: {:ok, [String.t()]} | {:error, File.posix() | atom()}
185 def import_from_filesystem do
186 emoji_path = emoji_path()
188 with {:ok, %{access: :read_write}} <- File.stat(emoji_path),
189 {:ok, results} <- File.ls(emoji_path) do
192 |> Enum.map(&Path.join(emoji_path, &1))
193 |> Enum.reject(fn path ->
194 File.dir?(path) and File.exists?(Path.join(path, "pack.json"))
196 |> Enum.map(&write_pack_contents/1)
197 |> Enum.reject(&is_nil/1)
201 {:ok, %{access: _}} -> {:error, :no_read_write}
206 @spec list_remote(keyword()) :: {:ok, map()} | {:error, atom()}
207 def list_remote(opts) do
208 uri = opts[:url] |> String.trim() |> URI.parse()
210 with :ok <- validate_shareable_packs_available(uri) do
213 "/api/v1/pleroma/emoji/packs?page=#{opts[:page]}&page_size=#{opts[:page_size]}"
219 @spec list_local(keyword()) :: {:ok, map(), non_neg_integer()}
220 def list_local(opts) do
221 with {:ok, results} <- list_packs_dir() do
224 |> Enum.map(fn name ->
225 case load_pack(name) do
230 |> Enum.reject(&is_nil/1)
234 |> paginate(opts[:page], opts[:page_size])
235 |> Map.new(fn pack -> {pack.name, validate_pack(pack)} end)
237 {:ok, packs, length(all_packs)}
241 @spec get_archive(String.t()) :: {:ok, binary()} | {:error, atom()}
242 def get_archive(name) do
243 with {:ok, pack} <- load_pack(name),
244 :ok <- validate_downloadable(pack) do
245 {:ok, fetch_archive(pack)}
249 @spec download(String.t(), String.t(), String.t()) :: {:ok, t()} | {:error, atom()}
250 def download(name, url, as) do
251 uri = url |> String.trim() |> URI.parse()
253 with :ok <- validate_shareable_packs_available(uri),
254 {:ok, remote_pack} <-
255 uri |> URI.merge("/api/v1/pleroma/emoji/pack?name=#{name}") |> http_get(),
256 {:ok, %{sha: sha, url: url} = pack_info} <- fetch_pack_info(remote_pack, uri, name),
257 {:ok, archive} <- download_archive(url, sha),
258 pack <- copy_as(remote_pack, as || name),
259 {:ok, _} = unzip(archive, pack_info, remote_pack, pack) do
260 # Fallback can't contain a pack.json file, since that would cause the fallback-src-sha256
261 # in it to depend on itself
262 if pack_info[:fallback] do
270 @spec save_metadata(map(), t()) :: {:ok, t()} | {:error, File.posix()}
271 def save_metadata(metadata, %__MODULE__{} = pack) do
273 |> Map.put(:pack, metadata)
277 @spec update_metadata(String.t(), map()) :: {:ok, t()} | {:error, File.posix()}
278 def update_metadata(name, data) do
279 with {:ok, pack} <- load_pack(name) do
280 if fallback_sha_changed?(pack, data) do
281 update_sha_and_save_metadata(pack, data)
283 save_metadata(data, pack)
288 @spec load_pack(String.t()) :: {:ok, t()} | {:error, :file.posix()}
289 def load_pack(name) do
290 pack_file = Path.join([emoji_path(), name, "pack.json"])
292 with {:ok, _} <- File.stat(pack_file),
293 {:ok, pack_data} <- File.read(pack_file) do
298 pack_file: pack_file,
299 path: Path.dirname(pack_file),
309 {:ok, Map.put(pack, :files_count, files_count)}
313 @spec emoji_path() :: Path.t()
315 [:instance, :static_dir]
316 |> Pleroma.Config.get!()
317 |> Path.join("emoji")
320 defp validate_emoji_not_exists(shortcode, force \\ false)
321 defp validate_emoji_not_exists(_shortcode, true), do: :ok
323 defp validate_emoji_not_exists(shortcode, _) do
324 if Emoji.exist?(shortcode) do
325 {:error, :already_exists}
331 defp write_pack_contents(path) do
333 files: files_from_path(path),
335 pack_file: Path.join(path, "pack.json")
338 case save_pack(pack) do
339 {:ok, _pack} -> Path.basename(path)
344 defp files_from_path(path) do
345 txt_path = Path.join(path, "emoji.txt")
347 if File.exists?(txt_path) do
348 # There's an emoji.txt file, it's likely from a pack installed by the pack manager.
349 # Make a pack.json file from the contents of that emoji.txt file
351 # FIXME: Copy-pasted from Pleroma.Emoji/load_from_file_stream/2
353 # Create a map of shortcodes to filenames from emoji.txt
356 |> String.split("\n")
357 |> Enum.map(&String.trim/1)
358 |> Enum.map(fn line ->
359 case String.split(line, ~r/,\s*/) do
360 # This matches both strings with and without tags
361 # and we don't care about tags here
363 file_dir_name = Path.dirname(file)
365 if String.ends_with?(path, file_dir_name) do
366 {name, Path.basename(file)}
375 |> Enum.reject(&is_nil/1)
378 # If there's no emoji.txt, assume all files
379 # that are of certain extensions from the config are emojis and import them all
380 pack_extensions = Pleroma.Config.get!([:emoji, :pack_extensions])
381 Emoji.Loader.make_shortcode_to_file_map(path, pack_extensions)
385 defp validate_pack(pack) do
387 if downloadable?(pack) do
388 archive = fetch_archive(pack)
389 archive_sha = :crypto.hash(:sha256, archive) |> Base.encode16()
392 |> Map.put("can-download", true)
393 |> Map.put("download-sha256", archive_sha)
395 Map.put(pack.pack, "can-download", false)
398 Map.put(pack, :pack, info)
401 defp downloadable?(pack) do
402 # If the pack is set as shared, check if it can be downloaded
403 # That means that when asked, the pack can be packed and sent to the remote
404 # Otherwise, they'd have to download it from external-src
405 pack.pack["share-files"] &&
406 Enum.all?(pack.files, fn {_, file} ->
413 defp create_archive_and_cache(pack, hash) do
414 files = ['pack.json' | Enum.map(pack.files, fn {_, file} -> to_charlist(file) end)]
417 :zip.zip('#{pack.name}.zip', files, [:memory, cwd: to_charlist(pack.path)])
419 ttl_per_file = Pleroma.Config.get!([:emoji, :shared_pack_cache_seconds_per_file])
420 overall_ttl = :timer.seconds(ttl_per_file * Enum.count(files))
425 # if pack.json MD5 changes, the cache is not valid anymore
426 %{hash: hash, pack_data: result},
427 # Add a minute to cache time for every file in the pack
434 defp save_pack(pack) do
435 with {:ok, json} <- Jason.encode(pack, pretty: true),
436 :ok <- File.write(pack.pack_file, json) do
441 defp from_json(json, attrs) do
442 map = Jason.decode!(json)
451 struct(__MODULE__, pack_attrs)
454 defp validate_shareable_packs_available(uri) do
455 with {:ok, %{"links" => links}} <- uri |> URI.merge("/.well-known/nodeinfo") |> http_get(),
456 # Get the actual nodeinfo address and fetch it
457 {:ok, %{"metadata" => %{"features" => features}}} <-
458 links |> List.last() |> Map.get("href") |> http_get() do
459 if Enum.member?(features, "shareable_emoji_packs") do
462 {:error, :not_shareable}
467 defp validate_not_empty(list) do
468 if Enum.all?(list, fn i -> is_binary(i) and i != "" end) do
471 {:error, :empty_values}
475 defp save_file(%Plug.Upload{path: upload_path}, pack, filename) do
476 file_path = Path.join(pack.path, filename)
477 create_subdirs(file_path)
479 with {:ok, _} <- File.copy(upload_path, file_path) do
484 defp put_emoji(pack, shortcode, filename) do
485 files = Map.put(pack.files, shortcode, filename)
486 %{pack | files: files, files_count: length(Map.keys(files))}
489 defp delete_emoji(pack, shortcode) do
490 files = Map.delete(pack.files, shortcode)
491 %{pack | files: files}
494 defp rename_file(pack, filename, new_filename) do
495 old_path = Path.join(pack.path, filename)
496 new_path = Path.join(pack.path, new_filename)
497 create_subdirs(new_path)
499 with :ok <- File.rename(old_path, new_path) do
500 remove_dir_if_empty(old_path, filename)
504 defp create_subdirs(file_path) do
505 with true <- String.contains?(file_path, "/"),
506 path <- Path.dirname(file_path),
507 false <- File.exists?(path) do
512 defp remove_file(pack, shortcode) do
513 with {:ok, filename} <- get_filename(pack, shortcode),
514 emoji <- Path.join(pack.path, filename),
515 :ok <- File.rm(emoji) do
516 remove_dir_if_empty(emoji, filename)
520 defp remove_dir_if_empty(emoji, filename) do
521 dir = Path.dirname(emoji)
523 if String.contains?(filename, "/") and File.ls!(dir) == [] do
530 defp get_filename(pack, shortcode) do
531 with %{^shortcode => filename} when is_binary(filename) <- pack.files,
532 file_path <- Path.join(pack.path, filename),
533 {:ok, _} <- File.stat(file_path) do
536 {:error, _} = error ->
540 {:error, :doesnt_exist}
544 defp http_get(%URI{} = url), do: url |> to_string() |> http_get()
546 defp http_get(url) do
547 with {:ok, %{body: body}} <- Pleroma.HTTP.get(url, [], []) do
552 defp list_packs_dir do
553 emoji_path = emoji_path()
554 # Create the directory first if it does not exist. This is probably the first request made
555 # with the API so it should be sufficient
556 with {:create_dir, :ok} <- {:create_dir, File.mkdir_p(emoji_path)},
557 {:ls, {:ok, results}} <- {:ls, File.ls(emoji_path)} do
558 {:ok, Enum.sort(results)}
560 {:create_dir, {:error, e}} -> {:error, :create_dir, e}
561 {:ls, {:error, e}} -> {:error, :ls, e}
565 defp validate_downloadable(pack) do
566 if downloadable?(pack), do: :ok, else: {:error, :cant_download}
569 defp copy_as(remote_pack, local_name) do
570 path = Path.join(emoji_path(), local_name)
575 files: remote_pack["files"],
576 pack_file: Path.join(path, "pack.json")
580 defp unzip(archive, pack_info, remote_pack, local_pack) do
581 with :ok <- File.mkdir_p!(local_pack.path) do
582 files = Enum.map(remote_pack["files"], fn {_, path} -> to_charlist(path) end)
583 # Fallback cannot contain a pack.json file
584 files = if pack_info[:fallback], do: files, else: ['pack.json' | files]
586 :zip.unzip(archive, cwd: to_charlist(local_pack.path), file_list: files)
590 defp fetch_pack_info(remote_pack, uri, name) do
591 case remote_pack["pack"] do
592 %{"share-files" => true, "can-download" => true, "download-sha256" => sha} ->
596 url: URI.merge(uri, "/api/v1/pleroma/emoji/packs/archive?name=#{name}") |> to_string()
599 %{"fallback-src" => src, "fallback-src-sha256" => sha} when is_binary(src) ->
608 {:error, "The pack was not set as shared and there is no fallback src to download from"}
612 defp download_archive(url, sha) do
613 with {:ok, %{body: archive}} <- Pleroma.HTTP.get(url) do
614 if Base.decode16!(sha) == :crypto.hash(:sha256, archive) do
617 {:error, :invalid_checksum}
622 defp fetch_archive(pack) do
623 hash = :crypto.hash(:md5, File.read!(pack.pack_file))
625 case @cachex.get!(:emoji_packs_cache, pack.name) do
626 %{hash: ^hash, pack_data: archive} -> archive
627 _ -> create_archive_and_cache(pack, hash)
631 defp fallback_sha_changed?(pack, data) do
632 is_binary(data[:"fallback-src"]) and data[:"fallback-src"] != pack.pack["fallback-src"]
635 defp update_sha_and_save_metadata(pack, data) do
636 with {:ok, %{body: zip}} <- Pleroma.HTTP.get(data[:"fallback-src"]),
637 :ok <- validate_has_all_files(pack, zip) do
638 fallback_sha = :sha256 |> :crypto.hash(zip) |> Base.encode16()
641 |> Map.put("fallback-src-sha256", fallback_sha)
642 |> save_metadata(pack)
646 defp validate_has_all_files(pack, zip) do
647 with {:ok, f_list} <- :zip.unzip(zip, [:memory]) do
648 # Check if all files from the pack.json are in the archive
650 |> Enum.all?(fn {_, from_manifest} ->
651 List.keyfind(f_list, to_charlist(from_manifest), 0)
653 |> if(do: :ok, else: {:error, :incomplete})