From f58c82e1fd8820e4f81a628a24b83866edeecd47 Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Tue, 31 Dec 2024 15:54:49 +0000 Subject: [PATCH] Refactor cover controller to reuse common pieces --- .../controllers/cover_controller.ex | 61 +++++++++---------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/lib/music_library_web/controllers/cover_controller.ex b/lib/music_library_web/controllers/cover_controller.ex index df8c4eef..9d99811b 100644 --- a/lib/music_library_web/controllers/cover_controller.ex +++ b/lib/music_library_web/controllers/cover_controller.ex @@ -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