Add endpoint to display an artist image

This commit is contained in:
Claudio Ortolina
2025-04-27 21:18:08 +01:00
parent cacdfbaee0
commit 3d3e758a7a
4 changed files with 90 additions and 0 deletions
+31
View File
@@ -73,6 +73,24 @@ defmodule MusicLibrary.Artists do
end
end
def get_artist_info!(artist_id) do
Repo.get!(ArtistInfo, artist_id)
end
def fetch_image(artist_id) do
artist_info = get_artist_info!(artist_id)
with {:ok, image} <- ArtistInfo.extract_image(artist_info),
{:ok, image_data} <- Discogs.get_artist_image(image.url) do
artist_info
|> ArtistInfo.changeset(%{
image_data: image_data,
image_data_width: image.width
})
|> Repo.update()
end
end
def fetch_artist_info_async(artist_id) do
meta = %{}
params = %{"id" => artist_id}
@@ -82,6 +100,19 @@ defmodule MusicLibrary.Artists do
|> BackgroundRepo.insert()
end
def get_image(artist_id) do
q =
from ai in ArtistInfo,
where: ai.id == ^artist_id,
select: %{
image_data: ai.image_data,
image_data_width: ai.image_data_width,
image_data_hash: ai.image_data_hash
}
Repo.one(q)
end
defp get_collected_artist_ids do
q =
from ar in ArtistRecord,
+17
View File
@@ -41,4 +41,21 @@ defmodule MusicLibrary.Records.ArtistInfo do
put_change(changeset, :image_data_hash, Cover.hash(image_data))
end
end
def extract_image(artist_info) when is_nil(artist_info.discogs_data) do
{:error, :no_discogs_data}
end
def extract_image(artist_info) do
primary_image =
Enum.find(artist_info.discogs_data["images"], fn image ->
image["type"] == "primary"
end)
if primary_image do
{:ok, %{url: primary_image["resource_url"], width: primary_image["width"]}}
else
{:error, :image_not_found}
end
end
end
@@ -0,0 +1,41 @@
defmodule MusicLibraryWeb.ArtistController do
use MusicLibraryWeb, :controller
alias MusicLibrary.Artists
# 1 year in seconds
@cache_duration 60 * 60 * 24 * 365
def image(conn, %{"musicbrainz_id" => artist_id}) do
case Artists.get_image(artist_id) do
nil ->
not_found(conn)
%{image_data: image_data, image_data_hash: etag} ->
case get_req_header(conn, "if-none-match") do
[^etag] -> extend_cache(conn)
_ -> respond_with_cache(conn, image_data, etag)
end
end
end
defp not_found(conn) do
conn
|> put_status(:not_found)
|> text("Not found")
end
defp extend_cache(conn) do
conn
|> put_resp_header("cache-control", "public, max-age=#{@cache_duration}")
|> send_resp(304, "")
end
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=#{@cache_duration}")
|> put_resp_header("etag", etag)
|> send_resp(200, cover_data)
end
end
+1
View File
@@ -35,6 +35,7 @@ defmodule MusicLibraryWeb.Router do
get "/backup", ArchiveController, :backup
get "/covers/:record_id", CoverController, :show
get "/artists/:musicbrainz_id/image", ArtistController, :image
live "/", StatsLive.Index, :index