From a27b38f19266446813c6af910aa55633d15a5e86 Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Sat, 31 May 2025 16:16:24 +0100 Subject: [PATCH] Add logic to import a batch of Last.fm tracks --- lib/last_fm.ex | 5 +++++ lib/last_fm/api.ex | 4 +++- lib/last_fm/import.ex | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 lib/last_fm/import.ex diff --git a/lib/last_fm.ex b/lib/last_fm.ex index 0533bd59..907f74ae 100644 --- a/lib/last_fm.ex +++ b/lib/last_fm.ex @@ -7,6 +7,11 @@ defmodule LastFm do def refresh_scrobbled_tracks, do: Refresh.refresh() + def get_tracks(to_uts) do + last_fm_config = last_fm_config() + API.get_recent_tracks(to_uts, last_fm_config) + end + def get_artist_info(musicbrainz_id, name) do last_fm_config = last_fm_config() diff --git a/lib/last_fm/api.ex b/lib/last_fm/api.ex index 5da5a798..c92aee1a 100644 --- a/lib/last_fm/api.ex +++ b/lib/last_fm/api.ex @@ -51,12 +51,14 @@ defmodule LastFm.API do |> post_request() end - def get_recent_tracks(config) do + def get_recent_tracks(to_uts \\ nil, config) do params = config |> base_params() |> Keyword.merge(method: "user.getrecenttracks", limit: 50) + params = if to_uts, do: Keyword.put(params, :to, to_uts), else: params + config |> new_request() |> Req.merge(url: "/", params: params) diff --git a/lib/last_fm/import.ex b/lib/last_fm/import.ex new file mode 100644 index 00000000..a5b7ede1 --- /dev/null +++ b/lib/last_fm/import.ex @@ -0,0 +1,23 @@ +defmodule LastFm.Import do + @insertable_fields [ + :musicbrainz_id, + :title, + :artist, + :album, + :cover_url, + :scrobbled_at_uts, + :scrobbled_at_label, + :last_fm_data + ] + + def batch(uts_to) do + with {:ok, tracks} <- LastFm.get_tracks(uts_to) do + track_params = + tracks + |> Enum.map(fn t -> Map.take(t, @insertable_fields) end) + |> Enum.map(&Map.to_list/1) + + MusicLibrary.Repo.insert_all(LastFm.Track, track_params) + end + end +end