fix(subsonic): one listen is one play, and a daily mix played in a Subsonic app is credited to it
release / web (push) Successful in 1m23s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m16s
release / android (push) Successful in 4m50s
release / Build signed APK (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped

A Subsonic app reports "now playing" when a song starts and "played" when
it ends. The played report used to close the now-playing row as a play of
its own and write a second one, so every listen counted twice, and as a
skip when the app sent the song's start time. The report now completes the
app's own row for that song. A late report for an earlier song no longer
cuts short the song playing now.

Subsonic's scrobble doesn't say where a song was played from, so Minstrel
remembers, per user and app, the daily mix the app last opened (for six
hours). A play of a song in that mix is credited to it: the mix's metrics
count it and its rotation moves on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 21:48:17 -05:00
co-authored by Claude Opus 5.5
parent 7f7e946bad
commit 333523b30e
8 changed files with 477 additions and 88 deletions
+6
View File
@@ -25,6 +25,9 @@ type pickHandlers struct {
picker *recommendation.Picker
playlists *playlists.Service
logger *slog.Logger
// recall notes the daily mix an app opens, so its plays are credited
// to that mix (see mixRecall).
recall *mixRecall
}
// ---- getPlaylists / getPlaylist ----
@@ -163,6 +166,9 @@ func (h *pickHandlers) getPlaylist(w http.ResponseWriter, r *http.Request) {
WriteFail(w, r, ErrGeneric, "Playlist unavailable")
return
}
if detail.Kind == "system" && detail.SystemVariant != nil {
h.recall.remember(user.ID, r.URL.Query().Get("c"), *detail.SystemVariant)
}
head := playlistRef(&detail.PlaylistRow)
head.SongCount = len(songs)
head.Duration = 0
+103
View File
@@ -0,0 +1,103 @@
package subsonic
import (
"context"
"errors"
"sync"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// mixRecallFor is how long after an app opens a daily mix its plays are
// still credited to that mix: long enough for a mix of a few hours played
// straight through, short enough that tomorrow's listening isn't credited
// to yesterday's mix.
const mixRecallFor = 6 * time.Hour
// mixRecall remembers, for each user and app, the daily mix that app last
// opened with getPlaylist. A Subsonic scrobble says which song was played
// but not where it was played from, so this is how a play of For You in a
// Subsonic app is credited to For You: its metrics count it and its
// rotation moves on.
//
// It lives in memory. After a restart, plays go uncredited until the app
// opens a mix again, which only loses the credit, never the play.
type mixRecall struct {
mu sync.Mutex
last map[recallKey]recalledMix
now func() time.Time
}
type recallKey struct {
user pgtype.UUID
client string
}
type recalledMix struct {
variant string
at time.Time
}
func newMixRecall() *mixRecall {
return &mixRecall{last: map[recallKey]recalledMix{}, now: time.Now}
}
// remember notes that the user's app (the Subsonic c parameter) opened a
// daily mix of the given variant. Entries past mixRecallFor are dropped
// on the way, so the map holds at most one entry per user and app.
func (m *mixRecall) remember(user pgtype.UUID, client, variant string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
now := m.now()
for k, v := range m.last {
if now.Sub(v.at) > mixRecallFor {
delete(m.last, k)
}
}
m.last[recallKey{user, client}] = recalledMix{variant: variant, at: now}
}
// variant is the daily mix the user's app opened within mixRecallFor, or
// "" when it opened none. A nil mixRecall remembers nothing.
func (m *mixRecall) variant(user pgtype.UUID, client string) string {
if m == nil {
return ""
}
m.mu.Lock()
defer m.mu.Unlock()
v, ok := m.last[recallKey{user, client}]
if !ok || m.now().Sub(v.at) > mixRecallFor {
return ""
}
return v.variant
}
// sourceFor is the play source to record for a Subsonic play of trackID:
// the daily mix the app last opened, when the track is in that mix's
// current snapshot, and otherwise "". A song played from an album after
// opening a mix is not in the mix, so it isn't credited to it.
func (m *mixRecall) sourceFor(ctx context.Context, q *dbq.Queries, user pgtype.UUID, client string, trackID pgtype.UUID) (string, error) {
variant := m.variant(user, client)
if variant == "" {
return "", nil
}
_, err := q.GetSystemPickKindForTrack(ctx, dbq.GetSystemPickKindForTrackParams{
UserID: user,
SystemVariant: &variant,
TrackID: trackID,
})
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
}
if err != nil {
return "", err
}
return variant, nil
}
+101
View File
@@ -0,0 +1,101 @@
package subsonic
import (
"context"
"io"
"log/slog"
"testing"
"time"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/playevents"
"git.fabledsword.com/bvandeusen/minstrel/internal/playlists"
)
// An app that has opened a daily mix is credited with it only for a while,
// so a mix opened yesterday doesn't claim today's listening.
func TestMixRecall_ForgetsAfterAWhile(t *testing.T) {
clock := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
m := newMixRecall()
m.now = func() time.Time { return clock }
user := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
m.remember(user, "play:Sub", "for_you")
if got := m.variant(user, "play:Sub"); got != "for_you" {
t.Fatalf("just opened: %q, want for_you", got)
}
if got := m.variant(user, "Amperfy"); got != "" {
t.Errorf("another app: %q, want nothing", got)
}
clock = clock.Add(mixRecallFor + time.Minute)
if got := m.variant(user, "play:Sub"); got != "" {
t.Errorf("after %v: %q, want nothing", mixRecallFor, got)
}
var none *mixRecall
none.remember(user, "play:Sub", "for_you")
if got := none.variant(user, "play:Sub"); got != "" {
t.Errorf("nil recall: %q, want nothing", got)
}
}
// A Subsonic app that opens For You and then reports songs played has those
// plays credited to For You, as the web and Android apps do, so the mix's
// metrics count them and its rotation moves on. A song that isn't in the
// mix, or a report from a different app, is not credited.
func TestScrobble_CreditsTheDailyMixTheAppOpened(t *testing.T) {
f := seedPicks(t)
ctx := context.Background()
svc := playlists.NewService(f.pool, nil, "")
mix, err := svc.Create(ctx, f.user.ID, "For you", "", false)
if err != nil {
t.Fatalf("create mix: %v", err)
}
if err := svc.AppendTracks(ctx, f.user.ID, mix.ID, []pgtype.UUID{f.tracks["Gale"].ID, f.tracks["Harbour"].ID}); err != nil {
t.Fatalf("fill mix: %v", err)
}
f.exec(t, `UPDATE playlists SET kind = 'system', system_variant = 'for_you' WHERE id = $1`, mix.ID)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
recall := newMixRecall()
picks := f.handlers()
picks.recall = recall
media := newMediaHandlers(f.pool, playevents.NewWriter(f.pool, logger, 30*time.Minute, 0.5, 30000), logger)
media.recall = recall
if code := call(t, picks.getPlaylist, f.user, "c=play:Sub&id="+uuidToID(mix.ID), nil); code != 0 {
t.Fatalf("getPlaylist: error %d", code)
}
scrobble := func(song, client string) {
t.Helper()
if code := call(t, media.handleScrobble, f.user, "submission=true&c="+client+"&id="+uuidToID(f.tracks[song].ID), nil); code != 0 {
t.Fatalf("scrobble %s: error %d", song, code)
}
}
scrobble("Gale", "play:Sub")
scrobble("Dusk", "play:Sub")
scrobble("Harbour", "Amperfy")
for song, want := range map[string]string{"Gale": "for_you", "Dusk": "", "Harbour": ""} {
var source *string
if err := f.pool.QueryRow(ctx, `SELECT source FROM play_events WHERE user_id = $1 AND track_id = $2`,
f.user.ID, f.tracks[song].ID).Scan(&source); err != nil {
t.Fatalf("play of %s: %v", song, err)
}
got := ""
if source != nil {
got = *source
}
if got != want {
t.Errorf("%s credited to %q, want %q", song, got, want)
}
}
var rotation []pgtype.UUID
if err := f.pool.QueryRow(ctx, `SELECT played_track_ids FROM system_playlist_rotation_state
WHERE user_id = $1 AND playlist_kind = 'for_you'`, f.user.ID).Scan(&rotation); err != nil {
t.Fatalf("for_you rotation: %v", err)
}
if len(rotation) != 1 || rotation[0] != f.tracks["Gale"].ID {
t.Errorf("for_you rotation = %v, want Gale only", rotation)
}
}
+17 -6
View File
@@ -28,6 +28,9 @@ type mediaHandlers struct {
pool *pgxpool.Pool
events *playevents.Writer
logger *slog.Logger
// recall credits a scrobble to the daily mix the app last opened
// (see mixRecall); nil credits nothing.
recall *mixRecall
}
func newMediaHandlers(pool *pgxpool.Pool, events *playevents.Writer, logger *slog.Logger) *mediaHandlers {
@@ -175,10 +178,12 @@ func imageContentType(path string) string {
// handleScrobble translates Subsonic scrobble calls into native play_events.
//
// submission=false (now-playing): writes a play_started, leaves ended_at NULL.
// submission=true (completed): writes a synthetic completed play (start+end
// in one transaction). play_events WHERE ended_at IS NULL is the source of
// truth for "currently playing"; the prior in-memory nowPlayingMap is gone.
// submission=false (now playing) opens a play, leaving ended_at NULL.
// submission=true (played) completes that play when it is the same song,
// and otherwise writes a completed one; either way a listen is one row.
// play_events WHERE ended_at IS NULL is the source of truth for "currently
// playing". A song in the daily mix the app last opened is credited to
// that mix.
func (m *mediaHandlers) handleScrobble(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
idStr := params.Get("id")
@@ -207,17 +212,23 @@ func (m *mediaHandlers) handleScrobble(w http.ResponseWriter, r *http.Request) {
}
}
clientID := params.Get("c")
source, err := m.recall.sourceFor(r.Context(), dbq.New(m.pool), user.ID, clientID, trackID)
if err != nil {
// Crediting a mix is a refinement; the play itself still counts.
m.logger.Warn("subsonic: scrobble mix lookup failed", "err", err)
source = ""
}
// Subsonic default is submission=true (completed play).
submission := strings.ToLower(params.Get("submission"))
switch submission {
case "true", "":
if err := m.events.RecordSyntheticCompletedPlay(r.Context(), user.ID, trackID, clientID, at); err != nil {
if err := m.events.RecordSyntheticCompletedPlay(r.Context(), user.ID, trackID, clientID, source, at); err != nil {
WriteFail(w, r, ErrGeneric, "Could not record play")
return
}
case "false":
if _, err := m.events.RecordPlayStarted(r.Context(), user.ID, trackID, clientID, at); err != nil {
if _, err := m.events.RecordPlayStartedWithSource(r.Context(), user.ID, trackID, clientID, source, "", at); err != nil {
WriteFail(w, r, ErrGeneric, "Could not record now-playing")
return
}
+3 -1
View File
@@ -36,10 +36,12 @@ import (
// method answering that scanning is not available.
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, events *playevents.Writer, hops func() int, picker *recommendation.Picker, lists *playlists.Service, startScan StartScan) {
b := &browseHandlers{pool: pool}
recall := newMixRecall()
m := newMediaHandlers(pool, events, logger)
m.recall = recall
u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername, list: dbq.New(pool).ListUsers}
sc := &scanHandlers{pool: pool, start: startScan}
p := &pickHandlers{pool: pool, picker: picker, playlists: lists, logger: logger}
p := &pickHandlers{pool: pool, picker: picker, playlists: lists, logger: logger, recall: recall}
r.Route("/rest", func(rest chi.Router) {
// The one method the OpenSubsonic spec has answer without credentials.
register(rest, "/getOpenSubsonicExtensions", handleGetOpenSubsonicExtensions)