Extract LastFm.Track and related structs

This commit is contained in:
Claudio Ortolina
2024-11-04 09:25:43 +00:00
parent 1abcc5e6ad
commit 7e4e57f6ac
6 changed files with 1135 additions and 61 deletions
+3 -61
View File
@@ -1,6 +1,8 @@
defmodule LastFm.API do
require Logger
alias LastFm.Track
@base_url "http://ws.audioscrobbler.com/2.0/"
def get_recent_tracks(user, api_key) do
@@ -21,7 +23,7 @@ defmodule LastFm.API do
{:ok,
response
|> get_in(["recenttracks", "track"])
|> parse_tracks()}
|> Track.from_api_response()}
other ->
msg = "Failed to fetch data from #{sanitize_url(url, api_key)}, reason: #{inspect(other)}"
@@ -45,66 +47,6 @@ defmodule LastFm.API do
end
end
defmodule Artist do
defstruct [:musicbrainz_id, :name]
end
defmodule Album do
defstruct [:musicbrainz_id, :title]
end
defmodule Track do
@moduledoc """
Data is not always guaranteed:
- musicbrainz_id can be an empty string
"""
defstruct [
:musicbrainz_id,
:title,
:artist,
:album,
:cover_url,
:scrobbled_at_uts,
:scrobbled_at_label
]
end
defp parse_tracks(raw_tracks) do
Enum.map(raw_tracks, fn t ->
album = %Album{
musicbrainz_id: t["album"]["mbid"],
title: t["album"]["#text"]
}
artist = %Artist{
musicbrainz_id: t["artist"]["mbid"],
name: t["artist"]["#text"]
}
%Track{
musicbrainz_id: t["mbid"],
title: t["name"],
artist: artist,
album: album,
cover_url: parse_cover_url(t),
scrobbled_at_uts: parse_scrobble_at_uts(t),
scrobbled_at_label: t["date"]["#text"]
}
end)
end
defp parse_cover_url(track) do
track["image"]
|> Enum.find(%{"#text" => nil}, fn i -> i["size"] == "small" end)
|> Map.get("#text")
end
defp parse_scrobble_at_uts(track) do
track["date"]["uts"]
|> String.to_integer()
end
defp sanitize_url(url, api_key) do
String.replace(url, api_key, "<redacted_api_key>")
end