Add function to search the MusicBrainz API

This commit is contained in:
Claudio Ortolina
2024-09-22 21:01:38 +01:00
parent 776dcef172
commit 15bc1816cf
2 changed files with 46 additions and 21 deletions
+2 -21
View File
@@ -38,12 +38,10 @@ defmodule MusicLibrary.Records.Importer do
import Ecto.Query, warn: false
alias MusicLibrary.Records.Record, as: Rec
alias MusicLibrary.Records.MusicBrainz
def import_artists(record) do
url =
"https://musicbrainz.org/ws/2/release-group/#{record.musicbrainz_id}?fmt=json&inc=artist-credits"
with {:ok, data} <- json_get(url) do
with {:ok, data} <- MusicBrainz.get_release_group(record.musicbrainz_id) do
artists_attrs =
data
|> get_in(["artist-credit", Access.all(), "artist"])
@@ -124,23 +122,6 @@ defmodule MusicLibrary.Records.Importer do
end)
end
defp json_get(url) do
req =
Finch.build(:get, url, [
{"User-Agent", "MusicLibrary/0.1.0 ( cloud8421@gmail.com )"}
])
case Finch.request(req, MusicLibrary.Finch) do
{:ok, response} when response.status == 200 ->
{:ok, Jason.decode!(response.body)}
other ->
msg = "Failed to fetch data from #{url}, reason: #{inspect(other)}"
Logger.error(msg)
{:error, msg}
end
end
defp blob_get(url) do
req =
Finch.build(:get, url, [
+44
View File
@@ -0,0 +1,44 @@
defmodule MusicLibrary.Records.MusicBrainz do
require Logger
def get_release_group(id) do
url =
"https://musicbrainz.org/ws/2/release-group/#{id}?fmt=json&inc=artist-credits"
json_get(url)
end
def search_release_group(query, opts \\ []) do
limit = Keyword.get(opts, :limit, 20)
offset = Keyword.get(opts, :offset, 0)
qs = [
query: query,
limit: limit,
offset: offset,
fmt: "json"
]
url =
"https://musicbrainz.org/ws/2/release-group?#{URI.encode_query(qs)}"
json_get(url)
end
defp json_get(url) do
req =
Finch.build(:get, url, [
{"User-Agent", "MusicLibrary/0.1.0 ( cloud8421@gmail.com )"}
])
case Finch.request(req, MusicLibrary.Finch) do
{:ok, response} when response.status == 200 ->
{:ok, Jason.decode!(response.body)}
other ->
msg = "Failed to fetch data from #{url}, reason: #{inspect(other)}"
Logger.error(msg)
{:error, msg}
end
end
end