Can fetch an artist info from Last.fm

This commit is contained in:
Claudio Ortolina
2024-12-01 18:06:30 +00:00
parent b63b3a633a
commit 2d721774d6
7 changed files with 1975 additions and 4 deletions
+3 -1
View File
@@ -1,7 +1,9 @@
defmodule LastFm.APIBehaviour do
alias LastFm.Track
alias LastFm.{Artist, Track}
@type musicbrainz_id :: String.t()
@type user :: String.t()
@type api_key :: String.t()
@callback get_recent_tracks(user, api_key) :: {:ok, [Track.t()]} | {:error, String.t()}
@callback get_artist_info(musicbrainz_id, api_key) :: {:ok, Artist.t()} | {:error, String.t()}
end
+29 -1
View File
@@ -3,7 +3,7 @@ defmodule LastFm.APIImpl do
require Logger
alias LastFm.Track
alias LastFm.{Artist, Track}
@base_url "http://ws.audioscrobbler.com/2.0/"
@@ -44,6 +44,34 @@ defmodule LastFm.APIImpl do
end
end
@impl true
def get_artist_info(artist_mbid, api_key) do
options = [
method: "artist.getInfo",
api_key: api_key,
mbid: artist_mbid,
format: "json",
limit: 50
]
url = @base_url <> "?" <> URI.encode_query(options)
Logger.debug("Fetching data from #{sanitize_url(url, api_key)}")
case json_get(url) do
{:ok, response} ->
{:ok,
response
|> Map.get("artist")
|> Artist.from_api_response()}
other ->
msg = "Failed to fetch data from #{sanitize_url(url, api_key)}, reason: #{inspect(other)}"
Logger.error(msg)
{:error, msg}
end
end
defp json_get(url) do
req =
Finch.build(:get, url, [
+19 -2
View File
@@ -1,8 +1,25 @@
defmodule LastFm.Artist do
defstruct [:musicbrainz_id, :name]
defstruct [:musicbrainz_id, :name, :bio, :image]
@type t :: %__MODULE__{
musicbrainz_id: String.t(),
name: String.t()
name: String.t(),
bio: String.t(),
image: String.t()
}
def from_api_response(api_response) do
%__MODULE__{
musicbrainz_id: api_response["mbid"],
name: api_response["name"],
bio: api_response["bio"]["summary"],
image: get_image(api_response)
}
end
defp get_image(api_response) do
api_response["image"]
|> Enum.find(%{"#text" => nil}, fn i -> i["size"] == "medium" end)
|> Map.get("#text")
end
end
+13
View File
@@ -186,6 +186,10 @@ defmodule MusicLibrary.Records do
end
end
def get_artist(musicbrainz_id) do
last_fm().get_artist_info(musicbrainz_id, last_fm_api_key())
end
defp build_record_attrs(release_group, attrs) do
release_group
|> Record.attrs_from_release_group()
@@ -215,4 +219,13 @@ defmodule MusicLibrary.Records do
defp musicbrainz do
Application.get_env(:music_library, :musicbrainz, MusicBrainz.APIImpl)
end
defp last_fm do
Application.get_env(:music_library, :last_fm, LastFm.APIImpl)
end
defp last_fm_api_key do
Application.get_env(:music_library, LastFm)
|> Keyword.fetch!(:api_key)
end
end