From 15bc1816cfcee52668ba807019c681c79e2f35eb Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Sun, 22 Sep 2024 21:01:38 +0100 Subject: [PATCH] Add function to search the MusicBrainz API --- lib/music_library/records/importer.ex | 23 ++---------- lib/music_library/records/music_brainz.ex | 44 +++++++++++++++++++++++ 2 files changed, 46 insertions(+), 21 deletions(-) create mode 100644 lib/music_library/records/music_brainz.ex diff --git a/lib/music_library/records/importer.ex b/lib/music_library/records/importer.ex index 34a1dc10..ee519344 100644 --- a/lib/music_library/records/importer.ex +++ b/lib/music_library/records/importer.ex @@ -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, [ diff --git a/lib/music_library/records/music_brainz.ex b/lib/music_library/records/music_brainz.ex new file mode 100644 index 00000000..0bd85da4 --- /dev/null +++ b/lib/music_library/records/music_brainz.ex @@ -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