Improve track refresh logic

This commit is contained in:
Claudio Ortolina
2025-06-02 21:00:44 +01:00
parent 3e9c719ce8
commit 46681deca9
4 changed files with 21 additions and 10 deletions
+1 -1
View File
@@ -2,7 +2,7 @@ defmodule LastFm do
alias LastFm.{API, Feed, Refresh, Scrobble, Track, Worker}
alias MusicLibrary.{BackgroundRepo, Repo}
def get_scrobbled_tracks, do: Feed.all_tracks(100)
def get_scrobbled_tracks(limit \\ 100), do: Feed.all_tracks(limit)
def subscribe_to_feed, do: Feed.subscribe()
+2 -1
View File
@@ -28,12 +28,13 @@ defmodule LastFm.Feed do
|> Enum.map(fn t -> Map.take(t, @insertable_fields) end)
|> Enum.map(&Map.to_list/1)
{count, nil} =
MusicLibrary.Repo.insert_all(LastFm.Track, track_params,
on_conflict: :nothing,
conflict_target: [:scrobbled_at_uts, :title]
)
Phoenix.PubSub.broadcast(LastFm.PubSub, "feed:update", %{tracks: tracks})
Phoenix.PubSub.broadcast(LastFm.PubSub, "feed:update", %{track_count: count})
end
@spec all_tracks(non_neg_integer()) :: [LastFm.Track.t()]
@@ -143,7 +143,13 @@ defmodule MusicLibraryWeb.StatsLive.Index do
|> assign(scrobble_activity_mode: String.to_existing_atom(mode))}
end
def handle_info(%{tracks: recent_tracks}, socket) do
def handle_info(%{track_count: 0}, socket) do
{:noreply, socket}
end
def handle_info(%{track_count: _count}, socket) do
recent_tracks = LastFm.get_scrobbled_tracks()
{:noreply,
socket
|> assign_scrobble_activity(recent_tracks)}
+7 -3
View File
@@ -37,11 +37,15 @@ defmodule LastFm.FeedTest do
}
describe "update and broadcast" do
test "it stores the track and broadcasts the update" do
test "it stores the track and broadcasts the updated track count" do
:ok = Feed.subscribe()
:ok = Feed.update([@track_two, @track_one])
assert_receive %{tracks: [@track_two, @track_one]}
:ok = Feed.update([@track_two, @track_one])
assert_receive %{track_count: 2}
# Tracks have already been inserted, count of new tracks is 0
:ok = Feed.update([@track_two, @track_one])
assert_receive %{track_count: 0}
end
test "it returns tracks in descending order of scrobble" do