do fix?
This commit is contained in:
parent
6ae835dbb3
commit
01ce7866bb
1 changed files with 35 additions and 6 deletions
|
|
@ -1,9 +1,13 @@
|
||||||
defmodule ZoeyscomputerWeb.DiscordHandler do
|
defmodule ZoeyscomputerWeb.DiscordHandler do
|
||||||
|
alias ExAws.S3
|
||||||
import Plug.Conn
|
import Plug.Conn
|
||||||
|
import Mogrify
|
||||||
|
|
||||||
def init(opts), do: opts
|
def init(opts), do: opts
|
||||||
|
|
||||||
def call(%{path_info: ["images", _id]} = conn, _opts) do
|
def call(%{path_info: ["images", _id]} = conn, _opts) do
|
||||||
|
handle_discord(conn)
|
||||||
|
|
||||||
case get_req_header(conn, "user-agent") do
|
case get_req_header(conn, "user-agent") do
|
||||||
["Mozilla/5.0 (compatible; Discordbot/" <> _rest] -> handle_discord(conn)
|
["Mozilla/5.0 (compatible; Discordbot/" <> _rest] -> handle_discord(conn)
|
||||||
_ -> conn
|
_ -> conn
|
||||||
|
|
@ -13,12 +17,37 @@ defmodule ZoeyscomputerWeb.DiscordHandler do
|
||||||
def call(conn, _opts), do: conn
|
def call(conn, _opts), do: conn
|
||||||
|
|
||||||
defp handle_discord(%{path_info: ["images", id]} = conn) do
|
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
|
{:error, reason} ->
|
||||||
|> put_resp_header("location", url)
|
IO.inspect(reason)
|
||||||
|> put_resp_content_type("text/plain")
|
|
||||||
|> send_resp(302, "Redirecting to image")
|
conn
|
||||||
|> halt()
|
|> 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
|
||||||
end
|
end
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue