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.Web.ActivityPub.MRF.StealEmojiPolicy do
10 @moduledoc "Detect new emojis by their shortcode and steals them"
11 @behaviour Pleroma.Web.ActivityPub.MRF.Policy
13 defp accept_host?(host), do: host in Config.get([:mrf_steal_emoji, :hosts], [])
15 defp steal_emoji({shortcode, url}, emoji_dir_path) do
16 url = Pleroma.Web.MediaProxy.url(url)
18 with {:ok, %{status: status} = response} when status in 200..299 <- Pleroma.HTTP.get(url) do
19 size_limit = Config.get([:mrf_steal_emoji, :size_limit], 50_000)
21 if byte_size(response.body) <= size_limit do
29 file_path = Path.join(emoji_dir_path, shortcode <> (extension || ".png"))
31 case File.write(file_path, response.body) do
36 Logger.warn("MRF.StealEmojiPolicy: Failed to write to #{file_path}: #{inspect(e)}")
41 "MRF.StealEmojiPolicy: :#{shortcode}: at #{url} (#{byte_size(response.body)} B) over size limit (#{size_limit} B)"
48 Logger.warn("MRF.StealEmojiPolicy: Failed to fetch #{url}: #{inspect(e)}")
54 def filter(%{"object" => %{"emoji" => foreign_emojis, "actor" => actor}} = message) do
55 host = URI.parse(actor).host
57 if host != Pleroma.Web.Endpoint.host() and accept_host?(host) do
58 installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
62 [:mrf_steal_emoji, :path],
63 Path.join(Config.get([:instance, :static_dir]), "emoji/stolen")
66 File.mkdir_p(emoji_dir_path)
70 |> Enum.reject(fn {shortcode, _url} -> shortcode in installed_emoji end)
71 |> Enum.filter(fn {shortcode, _url} ->
73 [:mrf_steal_emoji, :rejected_shortcodes]
75 |> Enum.find(false, fn regex -> String.match?(shortcode, regex) end)
79 |> Enum.map(&steal_emoji(&1, emoji_dir_path))
82 if !Enum.empty?(new_emojis) do
83 Logger.info("Stole new emojis: #{inspect(new_emojis)}")
84 Pleroma.Emoji.reload()
91 def filter(message), do: {:ok, message}
94 @spec config_description :: %{
97 description: <<_::272, _::_*256>>,
98 key: :hosts | :rejected_shortcodes | :size_limit,
99 suggestions: [any(), ...],
100 type: {:list, :string} | {:list, :string} | :integer
104 description: <<_::448>>,
105 key: :mrf_steal_emoji,
107 related_policy: <<_::352>>
109 def config_description do
111 key: :mrf_steal_emoji,
112 related_policy: "Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy",
114 description: "Steals emojis from selected instances when it sees them.",
118 type: {:list, :string},
119 description: "List of hosts to steal emojis from",
123 key: :rejected_shortcodes,
124 type: {:list, :string},
125 description: "Regex-list of shortcodes to reject",
131 description: "File size limit (in bytes), checked before an emoji is saved to the disk",
132 suggestions: ["100000"]