honkoma/lib/pleroma/web/media_proxy/invalidation/script.ex

63 lines
1.5 KiB
Elixir
Raw Normal View History

2020-05-18 06:22:26 +00:00
# Pleroma: A lightweight social networking server
# Copyright © 2017-2023 Pleroma Authors <https://pleroma.social/>
2020-05-18 06:22:26 +00:00
# SPDX-License-Identifier: AGPL-3.0-only
2020-05-15 18:34:46 +00:00
defmodule Pleroma.Web.MediaProxy.Invalidation.Script do
2020-05-18 06:22:26 +00:00
@moduledoc false
2020-05-15 18:34:46 +00:00
@behaviour Pleroma.Web.MediaProxy.Invalidation
2020-05-18 06:22:26 +00:00
require Logger
2020-05-15 18:34:46 +00:00
@impl Pleroma.Web.MediaProxy.Invalidation
def purge(urls, opts \\ []) do
2020-05-16 12:16:33 +00:00
args =
urls
2021-01-21 20:41:28 +00:00
|> maybe_format_urls(Keyword.get(opts, :url_format))
2020-05-16 12:16:33 +00:00
|> List.wrap()
|> Enum.uniq()
|> Enum.join(" ")
2020-06-14 18:02:57 +00:00
opts
|> Keyword.get(:script_path)
2020-06-14 18:02:57 +00:00
|> do_purge([args])
|> handle_result(urls)
2020-05-18 06:22:26 +00:00
end
2020-06-14 18:02:57 +00:00
defp do_purge(script_path, args) when is_binary(script_path) do
path = Path.expand(script_path)
Logger.debug("Running cache purge: #{inspect(args)}, #{inspect(path)}")
2020-05-18 06:22:26 +00:00
System.cmd(path, args)
rescue
2020-06-14 18:02:57 +00:00
error -> error
end
defp do_purge(_, _), do: {:error, "not found script path"}
defp handle_result({_result, 0}, urls), do: {:ok, urls}
defp handle_result({:error, error}, urls), do: handle_result(error, urls)
defp handle_result(error, _) do
Logger.error("Error while cache purge: #{inspect(error)}")
{:error, inspect(error)}
2020-05-15 18:34:46 +00:00
end
2021-01-21 20:41:28 +00:00
def maybe_format_urls(urls, :htcacheclean) do
urls
|> Enum.map(fn url ->
uri = URI.parse(url)
query =
if !is_nil(uri.query) do
"?" <> uri.query
else
"?"
end
uri.scheme <> "://" <> uri.host <> ":#{inspect(uri.port)}" <> uri.path <> query
end)
end
2021-01-21 20:41:28 +00:00
def maybe_format_urls(urls, _), do: urls
2020-05-15 18:34:46 +00:00
end