akkoma/lib/pleroma/web/activity_pub/mrf/media_proxy_warming_policy.ex

67 lines
1.7 KiB
Elixir
Raw Normal View History

2019-06-27 03:06:58 +00:00
# Pleroma: A lightweight social networking server
# 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
alias Pleroma.Workers.BackgroundWorker
2019-06-27 03:06:58 +00:00
require Logger
2020-02-11 07:12:57 +00:00
@options [
pool: :media
2019-06-27 03:06:58 +00:00
]
def perform(:prefetch, url) do
Logger.debug("Prefetching #{inspect(url)}")
2019-06-27 03:06:58 +00:00
2020-02-11 07:12:57 +00:00
opts =
if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Hackney do
Keyword.put(@options, :recv_timeout, 10_000)
else
@options
end
2019-06-27 03:06:58 +00:00
url
|> MediaProxy.preview_url()
2020-02-11 07:12:57 +00:00
|> HTTP.get([], adapter: opts)
2019-06-27 03:06:58 +00:00
end
def perform(:preload, %{"object" => %{"attachment" => attachments}} = _message) do
Enum.each(attachments, fn
%{"url" => url} when is_list(url) ->
url
|> Enum.each(fn
%{"href" => href} ->
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
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}
@impl true
2019-08-13 22:36:24 +00:00
def describe, do: {:ok, %{}}
2019-06-27 03:06:58 +00:00
end