Fork of Pleroma with site-specific changes and feature branches https://git.pleroma.social/pleroma/pleroma
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.9KB

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