logo

pleroma

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

media_proxy_warming_policy.ex (1831B)


  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. @impl true
  11. def history_awareness, do: :auto
  12. defp prefetch(url) do
  13. # Fetching only proxiable resources
  14. if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
  15. # If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
  16. prefetch_url = MediaProxy.preview_url(url)
  17. Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
  18. fetch(prefetch_url)
  19. end
  20. end
  21. defp fetch(url) do
  22. http_client_opts = Pleroma.Config.get([:media_proxy, :proxy_opts, :http], pool: :media)
  23. HTTP.get(url, [], http_client_opts)
  24. end
  25. defp preload(%{"object" => %{"attachment" => attachments}} = _activity) do
  26. Enum.each(attachments, fn
  27. %{"url" => url} when is_list(url) ->
  28. url
  29. |> Enum.each(fn
  30. %{"href" => href} ->
  31. prefetch(href)
  32. x ->
  33. Logger.debug("Unhandled attachment URL object #{inspect(x)}")
  34. end)
  35. x ->
  36. Logger.debug("Unhandled attachment #{inspect(x)}")
  37. end)
  38. end
  39. @impl true
  40. def filter(%{"type" => type, "object" => %{"attachment" => attachments} = _object} = activity)
  41. when type in ["Create", "Update"] and is_list(attachments) and length(attachments) > 0 do
  42. preload(activity)
  43. {:ok, activity}
  44. end
  45. @impl true
  46. def filter(activity), do: {:ok, activity}
  47. @impl true
  48. def describe, do: {:ok, %{}}
  49. end