2019-06-27 03:06:58 +00:00
|
|
|
# Pleroma: A lightweight social networking server
|
2020-03-02 05:08:45 +00:00
|
|
|
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
|
2019-06-27 03:06:58 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
defmodule Pleroma.Web.ActivityPub.MRF.MediaProxyWarmingPolicy do
|
|
|
|
@moduledoc "Preloads any attachments in the MediaProxy cache by prefetching them"
|
|
|
|
@behaviour Pleroma.Web.ActivityPub.MRF
|
|
|
|
|
|
|
|
alias Pleroma.HTTP
|
|
|
|
alias Pleroma.Web.MediaProxy
|
2019-08-13 17:20:26 +00:00
|
|
|
alias Pleroma.Workers.BackgroundWorker
|
2019-06-27 03:06:58 +00:00
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
2020-09-05 17:19:09 +00:00
|
|
|
@adapter_options [
|
2020-09-10 08:54:10 +00:00
|
|
|
pool: :media,
|
|
|
|
recv_timeout: 10_000
|
2019-06-27 03:06:58 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
def perform(:prefetch, url) do
|
2020-09-05 17:19:09 +00:00
|
|
|
# Fetching only proxiable resources
|
|
|
|
if MediaProxy.enabled?() and MediaProxy.url_proxiable?(url) do
|
|
|
|
# If preview proxy is enabled, it'll also hit media proxy (so we're caching both requests)
|
|
|
|
prefetch_url = MediaProxy.preview_url(url)
|
2019-06-27 03:06:58 +00:00
|
|
|
|
2020-09-05 17:19:09 +00:00
|
|
|
Logger.debug("Prefetching #{inspect(url)} as #{inspect(prefetch_url)}")
|
2020-02-11 07:12:57 +00:00
|
|
|
|
2020-09-10 08:54:10 +00:00
|
|
|
HTTP.get(prefetch_url, [], @adapter_options)
|
2020-09-05 17:19:09 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-06-27 03:06:58 +00:00
|
|
|
def perform(:preload, %{"object" => %{"attachment" => attachments}} = _message) do
|
|
|
|
Enum.each(attachments, fn
|
|
|
|
%{"url" => url} when is_list(url) ->
|
|
|
|
url
|
|
|
|
|> Enum.each(fn
|
|
|
|
%{"href" => href} ->
|
2019-08-31 18:58:42 +00:00
|
|
|
BackgroundWorker.enqueue("media_proxy_prefetch", %{"url" => href})
|
2019-06-27 03:06:58 +00:00
|
|
|
|
|
|
|
x ->
|
|
|
|
Logger.debug("Unhandled attachment URL object #{inspect(x)}")
|
|
|
|
end)
|
|
|
|
|
|
|
|
x ->
|
|
|
|
Logger.debug("Unhandled attachment #{inspect(x)}")
|
|
|
|
end)
|
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def filter(
|
|
|
|
%{"type" => "Create", "object" => %{"attachment" => attachments} = _object} = message
|
|
|
|
)
|
|
|
|
when is_list(attachments) and length(attachments) > 0 do
|
2019-08-31 18:58:42 +00:00
|
|
|
BackgroundWorker.enqueue("media_proxy_preload", %{"message" => message})
|
2019-06-27 03:06:58 +00:00
|
|
|
|
|
|
|
{:ok, message}
|
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def filter(message), do: {:ok, message}
|
2019-08-13 21:52:54 +00:00
|
|
|
|
|
|
|
@impl true
|
2019-08-13 22:36:24 +00:00
|
|
|
def describe, do: {:ok, %{}}
|
2019-06-27 03:06:58 +00:00
|
|
|
end
|