diff --git a/lib/zoeyscomputer_web/plugs/discord_handler.ex b/lib/zoeyscomputer_web/plugs/discord_handler.ex index 85deb05..c34cc22 100644 --- a/lib/zoeyscomputer_web/plugs/discord_handler.ex +++ b/lib/zoeyscomputer_web/plugs/discord_handler.ex @@ -1,9 +1,13 @@ 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 + handle_discord(conn) + case get_req_header(conn, "user-agent") do ["Mozilla/5.0 (compatible; Discordbot/" <> _rest] -> handle_discord(conn) _ -> conn @@ -13,12 +17,37 @@ defmodule ZoeyscomputerWeb.DiscordHandler do def call(conn, _opts), do: conn defp handle_discord(%{path_info: ["images", id]} = conn) do - url = "https://s3.zoeys.computer/imgs/uploads/#{id}.png" + 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() - conn - |> put_resp_header("location", url) - |> put_resp_content_type("text/plain") - |> send_resp(302, "Redirecting to image") - |> 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