Support arbitrary resizing in cover controller

This commit is contained in:
Claudio Ortolina
2024-12-31 11:57:56 +00:00
parent 6a51251d55
commit 97533416f7
5 changed files with 49 additions and 2 deletions
+2 -2
View File
@@ -1,8 +1,8 @@
defmodule MusicLibrary.Records.Cover do
@size 600
def resize(cover_data) do
{:ok, thumb} = Vix.Vips.Operation.thumbnail_buffer(cover_data, @size)
def resize(cover_data, size \\ @size) do
{:ok, thumb} = Vix.Vips.Operation.thumbnail_buffer(cover_data, size)
Vix.Vips.Image.write_to_buffer(thumb, ".jpg")
end
@@ -2,6 +2,36 @@ defmodule MusicLibraryWeb.CoverController do
use MusicLibraryWeb, :controller
alias MusicLibrary.Records
alias MusicLibrary.Records.Cover
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")
%{cover_data: cover_data} ->
{: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)
end
end
end
def show(conn, %{"record_id" => record_id}) do
case Records.get_cover(record_id) do