philomena/lib/camo/image.ex

41 lines
829 B
Elixir
Raw Normal View History

2019-11-11 00:35:52 +01:00
defmodule Camo.Image do
def image_url(input) do
2021-03-22 17:53:23 +01:00
uri = URI.parse(input)
2019-11-11 00:35:52 +01:00
2021-03-22 17:53:23 +01:00
cond do
is_nil(uri.host) ->
""
2020-01-11 05:20:19 +01:00
2021-03-22 17:53:23 +01:00
is_nil(camo_key()) ->
input
2019-11-11 00:35:52 +01:00
2021-03-22 17:53:23 +01:00
uri.host in [cdn_host(), camo_host()] ->
2021-03-22 19:37:17 +01:00
URI.to_string(%{uri | scheme: "https", port: 443})
2021-03-22 17:53:23 +01:00
true ->
camo_digest = :crypto.hmac(:sha, camo_key(), input) |> Base.encode16(case: :lower)
camo_uri = %URI{
host: camo_host(),
path: "/" <> camo_digest,
query: URI.encode_query(url: input),
scheme: "https"
}
URI.to_string(camo_uri)
2019-11-11 00:35:52 +01:00
end
end
defp cdn_host do
Application.get_env(:philomena, :cdn_host)
end
defp camo_key do
Application.get_env(:philomena, :camo_key)
end
defp camo_host do
Application.get_env(:philomena, :camo_host)
end
2020-01-11 05:20:19 +01:00
end