c5aaea2d47849d8c8a6710b4730367a0717c2513
[akkoma] / lib / pleroma / web / rich_media / parsers / ttl / aws_signed_url.ex
1 defmodule Pleroma.Web.RichMedia.Parser.TTL.AwsSignedUrl do
2 @behaviour Pleroma.Web.RichMedia.Parser.TTL
3
4 @impl Pleroma.Web.RichMedia.Parser.TTL
5 def ttl(data, _url) do
6 image = Map.get(data, :image)
7
8 if is_aws_signed_url(image) do
9 image
10 |> parse_query_params()
11 |> format_query_params()
12 |> get_expiration_timestamp()
13 else
14 {:error, "Not aws signed url #{inspect(image)}"}
15 end
16 end
17
18 defp is_aws_signed_url(image) when is_binary(image) and image != "" do
19 %URI{host: host, query: query} = URI.parse(image)
20
21 String.contains?(host, "amazonaws.com") and String.contains?(query, "X-Amz-Expires")
22 end
23
24 defp is_aws_signed_url(_), do: nil
25
26 defp parse_query_params(image) do
27 %URI{query: query} = URI.parse(image)
28 query
29 end
30
31 defp format_query_params(query) do
32 query
33 |> String.split(~r/&|=/)
34 |> Enum.chunk_every(2)
35 |> Map.new(fn [k, v] -> {k, v} end)
36 end
37
38 defp get_expiration_timestamp(params) when is_map(params) do
39 {:ok, date} =
40 params
41 |> Map.get("X-Amz-Date")
42 |> Timex.parse("{ISO:Basic:Z}")
43
44 {:ok, Timex.to_unix(date) + String.to_integer(Map.get(params, "X-Amz-Expires"))}
45 end
46 end