Merge remote-tracking branch 'upstream/develop' into aliases
[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 @adapter_options [
16 pool: :media,
17 recv_timeout: 10_000
18 ]
19
20 def perform(:prefetch, url) do
21 # Fetching only proxiable resources
22 if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
23 # If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
24 prefetch_url = MediaProxy.preview_url(url)
25
26 Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
27
28 HTTP.get(prefetch_url, [], @adapter_options)
29 end
30 end
31
32 def perform(:preload, %{"object" => %{"attachment" => attachments}} = _message) do
33 Enum.each(attachments, fn
34 %{"url" => url} when is_list(url) ->
35 url
36 |> Enum.each(fn
37 %{"href" => href} ->
38 BackgroundWorker.enqueue("media_proxy_prefetch", %{"url" => href})
39
40 x ->
41 Logger.debug("Unhandled attachment URL object #{inspect(x)}")
42 end)
43
44 x ->
45 Logger.debug("Unhandled attachment #{inspect(x)}")
46 end)
47 end
48
49 @impl true
50 def filter(
51 %{"type" => "Create", "object" => %{"attachment" => attachments} = _object} = message
52 )
53 when is_list(attachments) and length(attachments) > 0 do
54 BackgroundWorker.enqueue("media_proxy_preload", %{"message" => message})
55
56 {:ok, message}
57 end
58
59 @impl true
60 def filter(message), do: {:ok, message}
61
62 @impl true
63 def describe, do: {:ok, %{}}
64 end