51 lines
1.3 KiB
Elixir
51 lines
1.3 KiB
Elixir
defmodule ZoeyscomputerWeb.DiscordHandler do
|
|
alias ExAws.S3
|
|
import Plug.Conn
|
|
import Mogrify
|
|
|
|
def init(opts), do: opts
|
|
|
|
def call(%{path_info: ["images", _id]} = conn, _opts) do
|
|
case get_req_header(conn, "user-agent") do
|
|
["Mozilla/5.0 (compatible; Discordbot/" <> _rest] -> handle_discord(conn)
|
|
_ -> conn
|
|
end
|
|
end
|
|
|
|
def call(conn, _opts), do: conn
|
|
|
|
defp handle_discord(%{path_info: ["images", id]} = conn) do
|
|
case download_from_s3("imgs", id) do
|
|
{:ok, image_binary, content_type} ->
|
|
conn
|
|
|> put_resp_content_type(content_type)
|
|
|> send_resp(200, image_binary)
|
|
|> halt()
|
|
|
|
{:error, reason} ->
|
|
IO.inspect(reason)
|
|
|
|
conn
|
|
|> put_resp_content_type("text/plain")
|
|
|> send_resp(500, "Failed to retrieve image")
|
|
|> halt()
|
|
end
|
|
end
|
|
|
|
defp download_from_s3(bucket, key) do
|
|
case S3.get_object(bucket, "uploads/#{key}.png") |> ExAws.request() do
|
|
{:ok, %{body: image_binary}} ->
|
|
local_path = "/tmp/#{key}.png"
|
|
File.write!(local_path, image_binary)
|
|
|
|
image = open(local_path) |> format("webp") |> save()
|
|
|
|
{:ok, file_binary} = File.read(image.path)
|
|
|
|
{:ok, file_binary, "image/webp"}
|
|
|
|
error ->
|
|
error
|
|
end
|
|
end
|
|
end
|