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