Skip to content

Commit 6049ef8

Browse files
committed
refactor: update OGImageController delay upload and return image content directly
1 parent 5c7cfb2 commit 6049ef8

File tree

1 file changed

+32
-16
lines changed

1 file changed

+32
-16
lines changed

lib/algora_web/controllers/og_image_controller.ex

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,33 @@ defmodule AlgoraWeb.OGImageController do
1313
object_path = Path.join(["og"] ++ path ++ ["og.png"])
1414
url = Path.join(Algora.S3.bucket_url(), object_path)
1515

16-
case :head |> Finch.build(url) |> Finch.request(Algora.Finch) do
17-
{:ok, %Finch.Response{status: status, headers: headers}} when status in 200..299 ->
16+
case :get |> Finch.build(url) |> Finch.request(Algora.Finch) do
17+
{:ok, %Finch.Response{status: status, body: body, headers: headers}} when status in 200..299 ->
1818
if should_regenerate?(headers) do
1919
case take_and_upload_screenshot(path) do
20-
{:ok, s3_url} -> redirect(conn, external: s3_url)
21-
{:error, reason} -> handle_error(conn, path, reason)
20+
{:ok, body} ->
21+
conn
22+
|> put_resp_content_type("image/png")
23+
|> send_resp(200, body)
24+
25+
{:error, reason} ->
26+
handle_error(conn, path, reason)
2227
end
2328
else
24-
redirect(conn, external: url)
29+
conn
30+
|> put_resp_content_type("image/png")
31+
|> send_resp(200, body)
2532
end
2633

2734
_error ->
2835
case take_and_upload_screenshot(path) do
29-
{:ok, s3_url} -> redirect(conn, external: s3_url)
30-
{:error, reason} -> handle_error(conn, path, reason)
36+
{:ok, body} ->
37+
conn
38+
|> put_resp_content_type("image/png")
39+
|> send_resp(200, body)
40+
41+
{:error, reason} ->
42+
handle_error(conn, path, reason)
3143
end
3244
end
3345
end
@@ -70,15 +82,19 @@ defmodule AlgoraWeb.OGImageController do
7082
{:ok, _path} ->
7183
object_path = Path.join(["og"] ++ path ++ ["og.png"])
7284

73-
with {:ok, file_contents} <- File.read(filepath),
74-
{:ok, _} <-
75-
Algora.S3.upload(file_contents, object_path,
76-
content_type: "image/png",
77-
cache_control: "public, max-age=#{@max_age}"
78-
) do
79-
File.rm(filepath)
80-
{:ok, Path.join(Algora.S3.bucket_url(), object_path)}
81-
else
85+
case File.read(filepath) do
86+
{:ok, body} ->
87+
Task.start(fn ->
88+
Algora.S3.upload(body, object_path,
89+
content_type: "image/png",
90+
cache_control: "public, max-age=#{@max_age}"
91+
)
92+
93+
File.rm(filepath)
94+
end)
95+
96+
{:ok, body}
97+
8298
error ->
8399
File.rm(filepath)
84100
error

0 commit comments

Comments
 (0)