First
[anni] / lib / pleroma / web / media_proxy / invalidation / script.ex
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
5 defmodule Pleroma.Web.MediaProxy.Invalidation.Script do
6   @moduledoc false
7
8   @behaviour Pleroma.Web.MediaProxy.Invalidation
9
10   require Logger
11
12   @impl Pleroma.Web.MediaProxy.Invalidation
13   def purge(urls, opts \\ []) do
14     args =
15       urls
16       |> maybe_format_urls(Keyword.get(opts, :url_format))
17       |> List.wrap()
18       |> Enum.uniq()
19       |> Enum.join(" ")
20
21     opts
22     |> Keyword.get(:script_path)
23     |> do_purge([args])
24     |> handle_result(urls)
25   end
26
27   defp do_purge(script_path, args) when is_binary(script_path) do
28     path = Path.expand(script_path)
29     Logger.debug("Running cache purge: #{inspect(args)}, #{inspect(path)}")
30     System.cmd(path, args)
31   rescue
32     error -> error
33   end
34
35   defp do_purge(_, _), do: {:error, "not found script path"}
36
37   defp handle_result({_result, 0}, urls), do: {:ok, urls}
38   defp handle_result({:error, error}, urls), do: handle_result(error, urls)
39
40   defp handle_result(error, _) do
41     Logger.error("Error while cache purge: #{inspect(error)}")
42     {:error, inspect(error)}
43   end
44
45   def maybe_format_urls(urls, :htcacheclean) do
46     urls
47     |> Enum.map(fn url ->
48       uri = URI.parse(url)
49
50       query =
51         if !is_nil(uri.query) do
52           "?" <> uri.query
53         else
54           "?"
55         end
56
57       uri.scheme <> "://" <> uri.host <> ":#{inspect(uri.port)}" <> uri.path <> query
58     end)
59   end
60
61   def maybe_format_urls(urls, _), do: urls
62 end