logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

media_proxy_warming_policy.ex (1978B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 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. @impl true
  15. def history_awareness, do: :auto
  16. defp prefetch(url) do
  17. # Fetching only proxiable resources
  18. if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
  19. # If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
  20. prefetch_url = MediaProxy.preview_url(url)
  21. Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
  22. if Pleroma.Config.get(:env) == :test do
  23. fetch(prefetch_url)
  24. else
  25. ConcurrentLimiter.limit(__MODULE__, fn ->
  26. Task.start(fn -> fetch(prefetch_url) end)
  27. end)
  28. end
  29. end
  30. end
  31. defp fetch(url), do: HTTP.get(url, [], @adapter_options)
  32. defp 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. prefetch(href)
  39. x ->
  40. Logger.debug("Unhandled attachment URL object #{inspect(x)}")
  41. end)
  42. x ->
  43. Logger.debug("Unhandled attachment #{inspect(x)}")
  44. end)
  45. end
  46. @impl true
  47. def filter(%{"type" => type, "object" => %{"attachment" => attachments} = _object} = message)
  48. when type in ["Create", "Update"] and 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