Merge branch 'ecto-rollback-in-test-env' into 'develop'
[akkoma] / lib / pleroma / web / activity_pub / mrf / steal_emoji_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.StealEmojiPolicy do
6 require Logger
7
8 alias Pleroma.Config
9
10 @moduledoc "Detect new emojis by their shortcode and steals them"
11 @behaviour Pleroma.Web.ActivityPub.MRF
12
13 defp accept_host?(host), do: host in Config.get([:mrf_steal_emoji, :hosts], [])
14
15 defp steal_emoji({shortcode, url}, emoji_dir_path) do
16 url = Pleroma.Web.MediaProxy.url(url)
17
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)
20
21 if byte_size(response.body) <= size_limit do
22 extension =
23 url
24 |> URI.parse()
25 |> Map.get(:path)
26 |> Path.basename()
27 |> Path.extname()
28
29 file_path = Path.join(emoji_dir_path, shortcode <> (extension || ".png"))
30
31 case File.write(file_path, response.body) do
32 :ok ->
33 shortcode
34
35 e ->
36 Logger.warn("MRF.StealEmojiPolicy: Failed to write to #{file_path}: #{inspect(e)}")
37 nil
38 end
39 else
40 Logger.debug(
41 "MRF.StealEmojiPolicy: :#{shortcode}: at #{url} (#{byte_size(response.body)} B) over size limit (#{
42 size_limit
43 } B)"
44 )
45
46 nil
47 end
48 else
49 e ->
50 Logger.warn("MRF.StealEmojiPolicy: Failed to fetch #{url}: #{inspect(e)}")
51 nil
52 end
53 end
54
55 @impl true
56 def filter(%{"object" => %{"emoji" => foreign_emojis, "actor" => actor}} = message) do
57 host = URI.parse(actor).host
58
59 if host != Pleroma.Web.Endpoint.host() and accept_host?(host) do
60 installed_emoji = Pleroma.Emoji.get_all() |> Enum.map(fn {k, _} -> k end)
61
62 emoji_dir_path =
63 Config.get(
64 [:mrf_steal_emoji, :path],
65 Path.join(Config.get([:instance, :static_dir]), "emoji/stolen")
66 )
67
68 File.mkdir_p(emoji_dir_path)
69
70 new_emojis =
71 foreign_emojis
72 |> Enum.reject(fn {shortcode, _url} -> shortcode in installed_emoji end)
73 |> Enum.filter(fn {shortcode, _url} ->
74 reject_emoji? =
75 [:mrf_steal_emoji, :rejected_shortcodes]
76 |> Config.get([])
77 |> Enum.find(false, fn regex -> String.match?(shortcode, regex) end)
78
79 !reject_emoji?
80 end)
81 |> Enum.map(&steal_emoji(&1, emoji_dir_path))
82 |> Enum.filter(& &1)
83
84 if !Enum.empty?(new_emojis) do
85 Logger.info("Stole new emojis: #{inspect(new_emojis)}")
86 Pleroma.Emoji.reload()
87 end
88 end
89
90 {:ok, message}
91 end
92
93 def filter(message), do: {:ok, message}
94
95 @impl true
96 def describe do
97 {:ok, %{}}
98 end
99 end