1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
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
10 alias Pleroma.Web.MediaProxy
11 alias Pleroma.Workers.BackgroundWorker
19 def perform(:prefetch, url) do
20 # Fetching only proxiable resources
21 if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
22 # If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
23 prefetch_url = MediaProxy.preview_url(url)
25 Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
27 HTTP.get(prefetch_url, [], adapter: adapter_options())
31 defp adapter_options do
32 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
33 Keyword.put(@adapter_options, :recv_timeout, 10_000)
39 def perform(:preload, %{"object" => %{"attachment" => attachments}} = _message) do
40 Enum.each(attachments, fn
41 %{"url" => url} when is_list(url) ->
45 BackgroundWorker.enqueue("media_proxy_prefetch", %{"url" => href})
48 Logger.debug("Unhandled attachment URL object #{inspect(x)}")
52 Logger.debug("Unhandled attachment #{inspect(x)}")
58 %{"type" => "Create", "object" => %{"attachment" => attachments} = _object} = message
60 when is_list(attachments) and length(attachments) > 0 do
61 BackgroundWorker.enqueue("media_proxy_preload", %{"message" => message})
67 def filter(message), do: {:ok, message}
70 def describe, do: {:ok, %{}}