Move Artist and ArtistInfo under Artists context

This commit is contained in:
Claudio Ortolina
2025-05-23 20:11:57 +01:00
parent 83fb9a01b3
commit b44693b022
8 changed files with 12 additions and 9 deletions
+18
View File
@@ -0,0 +1,18 @@
defmodule MusicLibrary.Artists.Artist do
use Ecto.Schema
import Ecto.Changeset
@primary_key {:musicbrainz_id, :binary_id, autogenerate: false}
embedded_schema do
field :name, :string
field :sort_name, :string
field :disambiguation, :string
end
def changeset(artist, attrs) do
artist
|> cast(attrs, [:name, :sort_name, :disambiguation, :musicbrainz_id])
|> validate_required([:name, :sort_name, :musicbrainz_id])
end
end
+84
View File
@@ -0,0 +1,84 @@
defmodule MusicLibrary.Artists.ArtistInfo do
use Ecto.Schema
import Ecto.Changeset
alias MusicLibrary.Records.Cover
@primary_key {:id, :binary_id, autogenerate: true}
schema "artist_infos" do
field :musicbrainz_data, :map, default: %{}
field :discogs_data, :map, default: %{}
field :image_data, :binary
field :image_data_hash, :string
field :image_data_width, :integer
timestamps(type: :utc_datetime)
end
def changeset(artist_info, attrs) do
artist_info
|> cast(attrs, [
:id,
:musicbrainz_data,
:discogs_data,
:image_data,
:image_data_width
])
|> validate_required([:musicbrainz_data])
|> generate_image_hash()
end
def country(artist_info) do
%{"area" => area} =
artist_info.musicbrainz_data
country_code =
case area["iso-3166-1-codes"] || area["iso-3166-2-codes"] do
[code | _rest] -> code
nil -> artist_info.musicbrainz_data["country"]
end
%{name: area["name"] || "World", code: keep_alpha_2(country_code) || "XW"}
end
defp keep_alpha_2(nil), do: nil
defp keep_alpha_2(country_code) do
String.slice(country_code, 0..1)
end
def generate_image_hash(%__MODULE__{image_data: image_data} = artist_info) do
change(artist_info, image_data_hash: Cover.hash(image_data))
end
def generate_image_hash(changeset) do
case get_change(changeset, :image_data) do
nil ->
changeset
image_data ->
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 = extract_image(artist_info.discogs_data, "primary")
secondary_image = extract_image(artist_info.discogs_data, "secondary")
if image = primary_image || secondary_image do
{:ok, %{url: image["resource_url"], width: image["width"]}}
else
{:error, :image_not_found}
end
end
defp extract_image(discogs_data, type) do
Enum.find(discogs_data["images"] || [], fn image ->
image["type"] == type
end)
end
end