diff --git a/lib/music_library/records.ex b/lib/music_library/records.ex index 9f8ab5e2..1c347a13 100644 --- a/lib/music_library/records.ex +++ b/lib/music_library/records.ex @@ -242,6 +242,21 @@ defmodule MusicLibrary.Records do end def get_last_listened_track(record) do + q = + from t in scrobbles_for_record_query(record), + order_by: [desc: t.scrobbled_at_uts], + limit: 1 + + Repo.one(q) + end + + def play_count(record) do + record + |> scrobbles_for_record_query() + |> Repo.aggregate(:count) + end + + defp scrobbles_for_record_query(record) do record_id = record.id q = @@ -253,16 +268,11 @@ defmodule MusicLibrary.Records do 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 - - Repo.one(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 end def refresh_cover(record) do diff --git a/lib/music_library_web/live/collection_live/show.ex b/lib/music_library_web/live/collection_live/show.ex index c607cae3..8bf8a6ba 100644 --- a/lib/music_library_web/live/collection_live/show.ex +++ b/lib/music_library_web/live/collection_live/show.ex @@ -35,6 +35,7 @@ defmodule MusicLibraryWeb.CollectionLive.Show do def handle_params(%{"id" => id}, _, socket) do record = Records.get_record!(id) last_listened_track = Records.get_last_listened_track(record) + play_count = Records.play_count(record) || 0 socket = if record.selected_release_id do @@ -48,6 +49,7 @@ defmodule MusicLibraryWeb.CollectionLive.Show do |> assign(:page_title, page_title(socket.assigns.live_action, record)) |> assign(:record, record) |> assign(:last_listened_track, last_listened_track) + |> assign(:play_count, play_count) |> assign_similar_records()} end diff --git a/lib/music_library_web/live/collection_live/show.html.heex b/lib/music_library_web/live/collection_live/show.html.heex index 3cb057a6..873bcaa5 100644 --- a/lib/music_library_web/live/collection_live/show.html.heex +++ b/lib/music_library_web/live/collection_live/show.html.heex @@ -321,8 +321,15 @@ {gettext("Last listened at")}