Move BackfillScrobbledTracks worker under MusicLibrary namespace

This commit is contained in:
Claudio Ortolina
2026-03-28 08:05:02 +00:00
parent 4e2e0605ed
commit 47f8eddff1
4 changed files with 29 additions and 24 deletions
+17 -1
View File
@@ -13,12 +13,14 @@ defmodule MusicLibrary.ListeningStats do
alias MusicLibrary.{
Artists,
BackgroundRepo,
Collection,
ListeningStats.Refresh,
Records.ArtistRecord,
Records.Record,
Repo,
Wishlist
Wishlist,
Worker
}
@pagination Application.compile_env!(:music_library, :pagination)
@@ -79,6 +81,20 @@ defmodule MusicLibrary.ListeningStats do
Refresh.refresh()
end
@spec lowest_scrobbled_at_uts() :: integer() | nil
def lowest_scrobbled_at_uts do
Repo.aggregate(Track, :min, :scrobbled_at_uts)
end
@spec backfill_scrobbled_tracks() :: {:ok, Oban.Job.t()} | {:error, Ecto.Changeset.t()}
def backfill_scrobbled_tracks do
to_uts = lowest_scrobbled_at_uts()
%{"to_uts" => to_uts}
|> Worker.BackfillScrobbledTracks.new()
|> BackgroundRepo.insert()
end
@spec artist_play_count(String.t()) :: non_neg_integer()
def artist_play_count(artist_musicbrainz_id) do
from(t in Track,
@@ -0,0 +1,33 @@
defmodule MusicLibrary.Worker.BackfillScrobbledTracks do
@moduledoc """
Oban worker that backfills scrobbled tracks from Last.fm in batches.
Self-chaining: after importing a full batch, enqueues itself with the
next `to_uts` timestamp to continue backfilling.
"""
use Oban.Worker, queue: :heavy_writes, max_attempts: 3
alias MusicLibrary.{BackgroundRepo, ListeningStats}
@backfill_delay 1
@batch_size 200
@impl Oban.Worker
def perform(%{args: %{"to_uts" => to_uts}}) do
case LastFm.Import.batch(to_uts: to_uts, limit: @batch_size) do
{:ok, @batch_size} ->
next_to_uts = ListeningStats.lowest_scrobbled_at_uts()
%{"to_uts" => next_to_uts}
|> new(schedule_in: @backfill_delay)
|> BackgroundRepo.insert()
{:ok, _other_count} ->
:ok
error ->
error
end
end
end