From 669b144c55dfb1c58d650c3fe481b21957ff64db Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Tue, 3 Jun 2025 18:05:23 +0100 Subject: [PATCH] Find last listened track based on title and artist as well --- lib/music_library/records.ex | 9 ++++++++- lib/music_library/records/record.ex | 7 +++++++ lib/music_library_web/live/collection_live/show.ex | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/music_library/records.ex b/lib/music_library/records.ex index ca764bd4..432e07c0 100644 --- a/lib/music_library/records.ex +++ b/lib/music_library/records.ex @@ -211,17 +211,24 @@ defmodule MusicLibrary.Records do end end - def get_last_listened_track(record_id) do + def get_last_listened_track(record) do + record_id = record.id + q = from r in fragment("records, json_each(records.release_ids)"), where: fragment("records.id = ?", ^record_id), select: r.value release_ids = Repo.all(q) + main_artist_name = Record.main_artist(record).name + record_title = record.title q = from t in LastFm.Track, where: fragment("? ->> '$.musicbrainz_id'", t.album) in ^release_ids, + or_where: + fragment("? ->> '$.title'", t.album) == ^record_title and + fragment("? ->> '$.name'", t.artist) == ^main_artist_name, order_by: [desc: t.scrobbled_at_uts], limit: 1 diff --git a/lib/music_library/records/record.ex b/lib/music_library/records/record.ex index 00790bda..7db224e5 100644 --- a/lib/music_library/records/record.ex +++ b/lib/music_library/records/record.ex @@ -37,6 +37,13 @@ defmodule MusicLibrary.Records.Record do Enum.map_join(record.artists, ", ", fn artist -> artist.name end) end + def main_artist(record) do + case record.artists do + [] -> nil + [main_artist | _] -> main_artist + end + end + def artist_ids(record) do Enum.map(record.artists, fn artist -> artist.musicbrainz_id end) end diff --git a/lib/music_library_web/live/collection_live/show.ex b/lib/music_library_web/live/collection_live/show.ex index 6dc2738d..32b3d3b7 100644 --- a/lib/music_library_web/live/collection_live/show.ex +++ b/lib/music_library_web/live/collection_live/show.ex @@ -29,7 +29,7 @@ defmodule MusicLibraryWeb.CollectionLive.Show do @impl true def handle_params(%{"id" => id}, _, socket) do record = Records.get_record!(id) - last_listened_track = Records.get_last_listened_track(id) + last_listened_track = Records.get_last_listened_track(record) socket = if record.selected_release_id do