From bcc0bfd0c54784fe6a7ccd88fc083bd09dca41af Mon Sep 17 00:00:00 2001 From: Ekaterina Vaartis Date: Thu, 15 Aug 2019 19:55:58 +0300 Subject: [PATCH] Add an endpoint for emoji pack metadata updating --- .../web/emoji_api/emoji_api_controller.ex | 49 ++++++++++++++++++- lib/pleroma/web/router.ex | 1 + 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/lib/pleroma/web/emoji_api/emoji_api_controller.ex b/lib/pleroma/web/emoji_api/emoji_api_controller.ex index 3b9eab8b8..4096ccbed 100644 --- a/lib/pleroma/web/emoji_api/emoji_api_controller.ex +++ b/lib/pleroma/web/emoji_api/emoji_api_controller.ex @@ -196,7 +196,7 @@ def download_from(conn, %{"instance_address" => address, "pack_name" => name} = if pinfo[:fallback] do pack_file_path = Path.join(pack_dir, "pack.json") - File.write!(pack_file_path, Jason.encode!(full_pack)) + File.write!(pack_file_path, Jason.encode!(full_pack, pretty: true)) end conn |> text("ok") @@ -222,4 +222,51 @@ def delete(conn, %{"name" => name}) do conn |> put_status(:internal_server_error) |> text("Couldn't delete the pack #{name}") end end + + def update_metadata(conn, %{"name" => name, "new_data" => new_data}) do + pack_dir = Path.join(@emoji_dir_path, name) + pack_file_p = Path.join(pack_dir, "pack.json") + + full_pack = Jason.decode!(File.read!(pack_file_p)) + + new_data = + if not is_nil(new_data["fallback-src"]) and is_nil(new_data["fallback-src-sha256"]) do + pack_arch = Tesla.get!(new_data["fallback-src"]).body + + {:ok, flist} = :zip.unzip(pack_arch, [:memory]) + + # Check if all files from the pack.json are in the archive + has_all_files = + Enum.all?(full_pack["files"], fn {_, from_manifest} -> + Enum.find(flist, fn {from_archive, _} -> + to_string(from_archive) == from_manifest + end) + end) + + unless has_all_files do + {:error, + conn + |> put_status(:bad_request) + |> text("The fallback archive does not have all files specified in pack.json")} + else + fallback_sha = :crypto.hash(:sha256, pack_arch) |> Base.encode16() + + {:ok, new_data |> Map.put("fallback-src-sha256", fallback_sha)} + end + else + {:ok, new_data} + end + + case new_data do + {:ok, new_data} -> + full_pack = Map.put(full_pack, "pack", new_data) + File.write!(pack_file_p, Jason.encode!(full_pack, pretty: true)) + + # Send new data back with fallback sha filled + conn |> json(new_data) + + {:error, e} -> + e + end + end end diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 4df0ca3c3..471d09c43 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -218,6 +218,7 @@ defmodule Pleroma.Web.Router do # Modifying packs pipe_through([:admin_api, :oauth_write]) + post("/update_metadata/:name", EmojiAPIController, :update_metadata) delete("/delete/:name", EmojiAPIController, :delete) post("/download_from", EmojiAPIController, :download_from) end