Merge branch 'fix/1658-invite-send' into 'develop'
[akkoma] / lib / pleroma / web / activity_pub / mrf / media_proxy_warming_policy.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy do
6 @moduledoc "Preloads any attachments in the MediaProxy cache by prefetching them"
7 @behaviour Pleroma.Web.ActivityPub.MRF
8
9 alias Pleroma.HTTP
10 alias Pleroma.Web.MediaProxy
11 alias Pleroma.Workers.BackgroundWorker
12
13 require Logger
14
15 @options [
16 pool: :media
17 ]
18
19 def perform(:prefetch, url) do
20 Logger.debug("Prefetching #{inspect(url)}")
21
22 opts =
23 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
24 Keyword.put(@options, :recv_timeout, 10_000)
25 else
26 @options
27 end
28
29 url
30 |> MediaProxy.url()
31 |> HTTP.get([], adapter: opts)
32 end
33
34 def perform(:preload, %{"object" => %{"attachment" => attachments}} = _message) do
35 Enum.each(attachments, fn
36 %{"url" => url} when is_list(url) ->
37 url
38 |> Enum.each(fn
39 %{"href" => href} ->
40 BackgroundWorker.enqueue("media_proxy_prefetch", %{"url" => href})
41
42 x ->
43 Logger.debug("Unhandled attachment URL object #{inspect(x)}")
44 end)
45
46 x ->
47 Logger.debug("Unhandled attachment #{inspect(x)}")
48 end)
49 end
50
51 @impl true
52 def filter(
53 %{"type" => "Create", "object" => %{"attachment" => attachments} = _object} = message
54 )
55 when is_list(attachments) and length(attachments) > 0 do
56 BackgroundWorker.enqueue("media_proxy_preload", %{"message" => message})
57
58 {:ok, message}
59 end
60
61 @impl true
62 def filter(message), do: {:ok, message}
63
64 @impl true
65 def describe, do: {:ok, %{}}
66 end