From 8d5ce6a3dfbe23a68c023dc30e24ebc8176751a9 Mon Sep 17 00:00:00 2001 From: Moon Man Date: Sun, 22 Mar 2020 16:41:29 +0000 Subject: [PATCH] Add actual policy file --- steal_emoji_policy.ex | 79 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 steal_emoji_policy.ex diff --git a/steal_emoji_policy.ex b/steal_emoji_policy.ex new file mode 100644 index 0000000..39bb132 --- /dev/null +++ b/steal_emoji_policy.ex @@ -0,0 +1,79 @@ +defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy do + require Logger + @moduledoc "Detect new emoji and steal them" + @behaviour Pleroma.Web.ActivityPub.MRF + + defp has_emojo(installed_emoji, str) do + result = for emojo <- installed_emoji, elem(emojo, 0) == str, do: true + length(result) == 1 + end + + @impl true + def filter(%{"object" => %{"emoji" => foreign_emoji}} = object) do + num_foreign_emoji = Kernel.map_size(foreign_emoji) + + if num_foreign_emoji > 0 do + Logger.debug("#{num_foreign_emoji} EMOJI TO PROCESS") + installed_emoji = Pleroma.Emoji.get_all() + + new_files = + for {emojo_shortcode, emojo_url} <- foreign_emoji, + !has_emojo(installed_emoji, emojo_shortcode) do + Logger.debug("HANDLING EMOJO") + cond do + String.contains?(emojo_shortcode, "/") -> + Logger.error("BAD EMOJO SHORTCODE: #{emojo_shortcode}") + + !String.starts_with(emojo_url, "https://") -> + Logger.error("BAD EMOJO URL: #{emojo_url}") + + true -> + Logger.debug("GOOD EMOJO") + remote_emojo = HTTPoison.get!(emojo_url) + + if remote_emojo.status_code == 200 do + with {:ok, current_dir} <- File.cwd() do + new_file = + current_dir <> + "/priv/static/emoji/stolen/" <> emojo_shortcode <> Path.extname(emojo_url) + + try do + {:ok, file} = File.open(new_file, [:write]) + IO.binwrite(file, remote_emojo.body) + File.close(file) + Logger.debug("SAVED EMOJO") + rescue + RuntimeError -> + _ = "Error" + Logger.error("FAILED TO SAVE EMOJO: #{new_file}") + end + + new_file + end + else + Logger.error("FAILED TO DOWNLOAD EMOJO: #{emojo_url}") + end + end + end + + Logger.debug("EMOJI FILES: #{inspect(new_files)}") + + if length(new_files) > 0 do + Logger.debug("RELOADING EMOJI") + Pleroma.Emoji.reload() + else + Logger.debug("NO EMOJI TO LOAD") + end + end + + {:ok, object} + end + + @impl true + def filter(object) do + {:ok, object} + end + + @impl true + def describe, do: {:ok, %{}} +end \ No newline at end of file