Refactor cover controller to reuse common pieces

This commit is contained in:
Claudio Ortolina
2024-12-31 15:54:49 +00:00
parent 97533416f7
commit f58c82e1fd
@@ -7,28 +7,16 @@ defmodule MusicLibraryWeb.CoverController do
def show(conn, %{"record_id" => record_id, "size" => size}) do
case Records.get_cover(record_id) do
nil ->
conn
|> put_status(:not_found)
|> text("Not found")
not_found(conn)
%{cover_data: cover_data} ->
# TODO: find a way to cache computation, or pre-compute thumb and store it
{:ok, thumb_data} = Cover.resize(cover_data, String.to_integer(size))
hash = :crypto.hash(:sha256, thumb_data) |> Base.encode16()
case get_req_header(conn, "if-none-match") do
[^hash] ->
conn
# 24 hours
|> put_resp_header("cache-control", "public, max-age=86400")
|> send_resp(304, "")
_ ->
conn
|> put_resp_content_type("image/jpeg", "utf-8")
# 24 hours
|> put_resp_header("cache-control", "public, max-age=86400")
|> put_resp_header("etag", hash)
|> send_resp(200, thumb_data)
[^hash] -> extend_cache(conn)
_ -> respond_with_cache(conn, thumb_data, hash)
end
end
end
@@ -36,26 +24,35 @@ defmodule MusicLibraryWeb.CoverController do
def show(conn, %{"record_id" => record_id}) do
case Records.get_cover(record_id) do
nil ->
conn
|> put_status(:not_found)
|> text("Not found")
not_found(conn)
%{cover_data: cover_data, cover_hash: etag} ->
case get_req_header(conn, "if-none-match") do
[^etag] ->
conn
# 24 hours
|> put_resp_header("cache-control", "public, max-age=86400")
|> send_resp(304, "")
_ ->
conn
|> put_resp_content_type("image/jpeg", "utf-8")
# 24 hours
|> put_resp_header("cache-control", "public, max-age=86400")
|> put_resp_header("etag", etag)
|> send_resp(200, cover_data)
[^etag] -> extend_cache(conn)
_ -> respond_with_cache(conn, cover_data, etag)
end
end
end
defp not_found(conn) do
conn
|> put_status(:not_found)
|> text("Not found")
end
# 24 hours
defp extend_cache(conn) do
conn
|> put_resp_header("cache-control", "public, max-age=86400")
|> send_resp(304, "")
end
# 24 hours
defp respond_with_cache(conn, cover_data, etag) do
conn
|> put_resp_content_type("image/jpeg", "utf-8")
|> put_resp_header("cache-control", "public, max-age=86400")
|> put_resp_header("etag", etag)
|> send_resp(200, cover_data)
end
end