From cacdfbaee056e89dc3f0996c6b4f5f55d0021aa4 Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Sun, 27 Apr 2025 21:17:31 +0100 Subject: [PATCH] Add Discogs function to fetch artist image --- lib/discogs.ex | 6 ++++++ lib/discogs/api.ex | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/discogs.ex b/lib/discogs.ex index df538ed8..4dc1c874 100644 --- a/lib/discogs.ex +++ b/lib/discogs.ex @@ -7,5 +7,11 @@ defmodule Discogs do API.get_artist(id, discogs_config) end + def get_artist_image(url) do + discogs_config = discogs_config() + + API.get_artist_image(url, discogs_config) + end + defp discogs_config, do: Discogs.Config.resolve(:music_library) end diff --git a/lib/discogs/api.ex b/lib/discogs/api.ex index 979d0d85..e60100a0 100644 --- a/lib/discogs/api.ex +++ b/lib/discogs/api.ex @@ -12,6 +12,17 @@ defmodule Discogs.API do |> get_request() end + def get_artist_image(url, config) do + case Req.new(url: url, max_retries: 1, user_agent: config.user_agent) + |> Req.Request.merge_options(config.req_options) + |> Req.Request.append_request_steps(log_attempt: &log_attempt/1) + |> Req.Request.append_response_steps(log_error: &log_error/1) + |> get_request() do + {:ok, data} -> {:ok, data} + {:error, _reason} -> {:error, :cover_not_available} + end + end + defp new_request(config) do Req.new( base_url: "https://api.discogs.com", @@ -42,4 +53,15 @@ defmodule Discogs.API do Logger.debug("Fetching data from #{url}") request end + + defp log_error({request, response}) do + if response.status in 400..499 or response.status in 500..599 do + Logger.error(fn -> + url = URI.to_string(request.url) + "Failed to fetch data from #{url}, reason: #{inspect(response.body)}" + end) + end + + {request, response} + end end