Use finch everywhere (#33)
[akkoma] / lib / pleroma / web / activity_pub / mrf / media_proxy_warming_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.MediaProxyWarmingPolicy do
6 @moduledoc "Preloads any attachments in the MediaProxy cache by prefetching them"
7 @behaviour Pleroma.Web.ActivityPub.MRF.Policy
8
9 alias Pleroma.HTTP
10 alias Pleroma.Web.MediaProxy
11
12 require Logger
13
14 @adapter_options [
15 recv_timeout: 10_000
16 ]
17
18 defp prefetch(url) do
19 # Fetching only proxiable resources
20 if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
21 # If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
22 prefetch_url = MediaProxy.preview_url(url)
23
24 Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
25
26 if Pleroma.Config.get(:env) == :test do
27 fetch(prefetch_url)
28 else
29 ConcurrentLimiter.limit(__MODULE__, fn ->
30 Task.start(fn -> fetch(prefetch_url) end)
31 end)
32 end
33 end
34 end
35
36 defp fetch(url), do: HTTP.get(url, [], @adapter_options)
37
38 defp preload(%{"object" => %{"attachment" => attachments}} = _message) do
39 Enum.each(attachments, fn
40 %{"url" => url} when is_list(url) ->
41 url
42 |> Enum.each(fn
43 %{"href" => href} ->
44 prefetch(href)
45
46 x ->
47 Logger.debug("Unhandled attachment URL object #{inspect(x)}")
48 end)
49
50 x ->
51 Logger.debug("Unhandled attachment #{inspect(x)}")
52 end)
53 end
54
55 @impl true
56 def filter(
57 %{"type" => "Create", "object" => %{"attachment" => attachments} = _object} = message
58 )
59 when is_list(attachments) and length(attachments) > 0 do
60 preload(message)
61
62 {:ok, message}
63 end
64
65 @impl true
66 def filter(message), do: {:ok, message}
67
68 @impl true
69 def describe, do: {:ok, %{}}
70 end