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
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:
@@ -0,0 +1,140 @@
|
||||
package playevents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// userPlays is every play_events row of the fixture user, oldest first.
|
||||
func userPlays(t *testing.T, f fixture) []dbq.PlayEvent {
|
||||
t.Helper()
|
||||
rows, err := f.pool.Query(context.Background(),
|
||||
`SELECT id FROM play_events WHERE user_id = $1 ORDER BY started_at`, f.user)
|
||||
if err != nil {
|
||||
t.Fatalf("list plays: %v", err)
|
||||
}
|
||||
var ids []pgtype.UUID
|
||||
for rows.Next() {
|
||||
var id pgtype.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
t.Fatalf("scan: %v", err)
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
rows.Close()
|
||||
out := make([]dbq.PlayEvent, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
ev, err := f.q.GetPlayEventByID(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("get play: %v", err)
|
||||
}
|
||||
out = append(out, ev)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A Subsonic app reports "now playing" when a song starts and "played" when
|
||||
// it ends. The pair is one listen, a full one, whether the report's time is
|
||||
// the song's start (as several apps send it) or its end (or left out, so the
|
||||
// server's clock, which is the end).
|
||||
func TestSyntheticCompletedPlay_CompletesTheNowPlayingRow(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reportAt time.Duration // after the song started
|
||||
}{
|
||||
{"report carries the start time", 0},
|
||||
{"report carries the end time", 200 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
ctx := context.Background()
|
||||
start := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Millisecond)
|
||||
if _, err := f.w.RecordPlayStarted(ctx, f.user, f.track, "dsub", start); err != nil {
|
||||
t.Fatalf("now playing: %v", err)
|
||||
}
|
||||
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "", start.Add(tc.reportAt)); err != nil {
|
||||
t.Fatalf("played: %v", err)
|
||||
}
|
||||
plays := userPlays(t, f)
|
||||
if len(plays) != 1 {
|
||||
t.Fatalf("got %d play rows for one listen, want 1", len(plays))
|
||||
}
|
||||
p := plays[0]
|
||||
if p.WasSkipped {
|
||||
t.Error("a song played to the end is recorded as a skip")
|
||||
}
|
||||
if p.CompletionRatio == nil || *p.CompletionRatio != 1 {
|
||||
t.Errorf("completion ratio = %v, want 1", p.CompletionRatio)
|
||||
}
|
||||
if !p.StartedAt.Time.Equal(start) {
|
||||
t.Errorf("started_at = %v, want the now-playing time %v", p.StartedAt.Time, start)
|
||||
}
|
||||
if want := start.Add(200 * time.Second); !p.EndedAt.Valid || !p.EndedAt.Time.Equal(want) {
|
||||
t.Errorf("ended_at = %v, want %v", p.EndedAt.Time, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An app that reports a song as played after the next one has started must
|
||||
// not cut the next one short: it stays open, still playing.
|
||||
func TestSyntheticCompletedPlay_LeavesALaterSongPlaying(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
ctx := context.Background()
|
||||
track, err := f.q.GetTrackByID(ctx, f.track)
|
||||
if err != nil {
|
||||
t.Fatalf("track: %v", err)
|
||||
}
|
||||
next, err := f.q.UpsertTrack(ctx, dbq.UpsertTrackParams{
|
||||
Title: "Next", AlbumID: track.AlbumID, ArtistID: track.ArtistID,
|
||||
FilePath: "/tmp/track-fixture-next.flac", DurationMs: 180_000,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("next track: %v", err)
|
||||
}
|
||||
songStart := time.Now().UTC().Add(-10 * time.Minute)
|
||||
nextStart := songStart.Add(200 * time.Second)
|
||||
if _, err := f.w.RecordPlayStarted(ctx, f.user, next.ID, "dsub", nextStart); err != nil {
|
||||
t.Fatalf("now playing next: %v", err)
|
||||
}
|
||||
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "", songStart); err != nil {
|
||||
t.Fatalf("played: %v", err)
|
||||
}
|
||||
open, err := f.q.GetOpenPlayEventForUser(ctx, f.user)
|
||||
if err != nil {
|
||||
t.Fatalf("the next song is no longer playing: %v", err)
|
||||
}
|
||||
if open.TrackID != next.ID {
|
||||
t.Errorf("open play is %v, want the next song", open.TrackID)
|
||||
}
|
||||
if n := len(userPlays(t, f)); n != 2 {
|
||||
t.Errorf("got %d play rows, want 2 (the reported song and the one playing)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A play reported as coming from a daily mix is credited to it: the row
|
||||
// carries the mix as its source and the mix's rotation counts the song.
|
||||
func TestSyntheticCompletedPlay_CreditsTheMix(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
seedSystemSnapshot(t, f, "for_you", "fresh")
|
||||
ctx := context.Background()
|
||||
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "for_you", time.Now().UTC()); err != nil {
|
||||
t.Fatalf("played: %v", err)
|
||||
}
|
||||
plays := userPlays(t, f)
|
||||
if len(plays) != 1 || plays[0].Source == nil || *plays[0].Source != "for_you" {
|
||||
t.Fatalf("plays = %+v, want one play from for_you", plays)
|
||||
}
|
||||
if plays[0].PickKind == nil || *plays[0].PickKind != "fresh" {
|
||||
t.Errorf("pick_kind = %v, want fresh", plays[0].PickKind)
|
||||
}
|
||||
st, err := f.q.GetRotationState(ctx, dbq.GetRotationStateParams{UserID: f.user, PlaylistKind: "for_you"})
|
||||
if err != nil || len(st.PlayedTrackIds) != 1 {
|
||||
t.Errorf("for_you rotation = %v (%v), want the song counted", st.PlayedTrackIds, err)
|
||||
}
|
||||
}
|
||||
+106
-80
@@ -57,8 +57,8 @@ type StartedResult struct {
|
||||
|
||||
// RecordPlayStarted: in one transaction, auto-close any prior open row for
|
||||
// the user, FindOrCreate the play_session, insert the new play_event,
|
||||
// return its id and session id. Source-agnostic — kept for the Subsonic
|
||||
// shim (frozen API), which never originates from a system playlist.
|
||||
// return its id and session id. The play has no source; a caller that knows
|
||||
// which surface the play came from uses RecordPlayStartedWithSource.
|
||||
func (w *Writer) RecordPlayStarted(
|
||||
ctx context.Context,
|
||||
userID, trackID pgtype.UUID,
|
||||
@@ -144,60 +144,63 @@ func (w *Writer) RecordPlayStartedWithSource(
|
||||
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
|
||||
return err
|
||||
}
|
||||
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var clientIDPtr *string
|
||||
if clientID != "" {
|
||||
clientIDPtr = &clientID
|
||||
}
|
||||
var sourcePtr *string
|
||||
if source != "" {
|
||||
sourcePtr = &source
|
||||
}
|
||||
var pickKind *string
|
||||
if systemPlaylistSources[source] {
|
||||
pickKind, err = lookupSystemPickKind(ctx, q, userID, trackID, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
|
||||
UserID: userID,
|
||||
TrackID: trackID,
|
||||
SessionID: sessionID,
|
||||
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
|
||||
ClientID: clientIDPtr,
|
||||
Source: sourcePtr,
|
||||
PickKind: pickKind,
|
||||
DeviceClass: strPtrOrNil(deviceClass),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out.PlayEventID = ev.ID
|
||||
out.SessionID = sessionID
|
||||
|
||||
// Capture session vector for the just-inserted row.
|
||||
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if systemPlaylistSources[source] {
|
||||
if err := q.AppendRotationPlayed(ctx, dbq.AppendRotationPlayedParams{
|
||||
UserID: userID,
|
||||
PlaylistKind: source,
|
||||
TrackID: trackID,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
var err error
|
||||
out, err = w.openPlay(ctx, q, userID, trackID, clientID, source, deviceClass, at)
|
||||
return err
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
// openPlay inserts a started play_event inside the caller's transaction. It
|
||||
// finds or creates the listening session, stamps a system-playlist play's
|
||||
// pick_kind, captures the session vector, and adds the track to that
|
||||
// playlist's rotation so its shuffle prefers what is still unplayed.
|
||||
func (w *Writer) openPlay(
|
||||
ctx context.Context,
|
||||
q *dbq.Queries,
|
||||
userID, trackID pgtype.UUID,
|
||||
clientID, source, deviceClass string,
|
||||
at time.Time,
|
||||
) (StartedResult, error) {
|
||||
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
|
||||
if err != nil {
|
||||
return StartedResult{}, err
|
||||
}
|
||||
var pickKind *string
|
||||
if systemPlaylistSources[source] {
|
||||
pickKind, err = lookupSystemPickKind(ctx, q, userID, trackID, source)
|
||||
if err != nil {
|
||||
return StartedResult{}, err
|
||||
}
|
||||
}
|
||||
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
|
||||
UserID: userID,
|
||||
TrackID: trackID,
|
||||
SessionID: sessionID,
|
||||
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
|
||||
ClientID: strPtrOrNil(clientID),
|
||||
Source: strPtrOrNil(source),
|
||||
PickKind: pickKind,
|
||||
DeviceClass: strPtrOrNil(deviceClass),
|
||||
})
|
||||
if err != nil {
|
||||
return StartedResult{}, err
|
||||
}
|
||||
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
|
||||
return StartedResult{}, err
|
||||
}
|
||||
if systemPlaylistSources[source] {
|
||||
if err := q.AppendRotationPlayed(ctx, dbq.AppendRotationPlayedParams{
|
||||
UserID: userID,
|
||||
PlaylistKind: source,
|
||||
TrackID: trackID,
|
||||
}); err != nil {
|
||||
return StartedResult{}, err
|
||||
}
|
||||
}
|
||||
return StartedResult{PlayEventID: ev.ID, SessionID: sessionID}, nil
|
||||
}
|
||||
|
||||
// RecordPlayEnded closes a play_event with duration + computed completion
|
||||
// ratio. Applies the skip rule (AND of completion < threshold AND
|
||||
// duration_played < threshold) — both conditions must hold for the row to
|
||||
@@ -308,13 +311,39 @@ func (w *Writer) RecordPlaySkipped(
|
||||
})
|
||||
}
|
||||
|
||||
// RecordSyntheticCompletedPlay writes a start+end pair for a Subsonic
|
||||
// scrobble?submission=true call. ended_at = at + track.duration_ms,
|
||||
// duration_played_ms = track.duration_ms, was_skipped = false.
|
||||
// sameListenWindow is how far apart a Subsonic app's "now playing" and its
|
||||
// "played" report for the same song may be and still be one listen. The
|
||||
// report's time is the song's start in some apps and its end (or omitted,
|
||||
// so the server's clock) in others, and a song can sit paused, so the
|
||||
// window is wide. A second listen of the same song always opens its own
|
||||
// row first, since the app reports "now playing" again, so a wide window
|
||||
// can't merge two listens.
|
||||
const sameListenWindow = 6 * time.Hour
|
||||
|
||||
// within reports whether a and b are no more than d apart, in either order.
|
||||
func within(a, b time.Time, d time.Duration) bool {
|
||||
gap := a.Sub(b)
|
||||
return gap <= d && gap >= -d
|
||||
}
|
||||
|
||||
// RecordSyntheticCompletedPlay records a Subsonic scrobble?submission=true
|
||||
// call: one completed listen, duration_played_ms = track.duration_ms,
|
||||
// was_skipped = false.
|
||||
//
|
||||
// Subsonic apps report "now playing" (submission=false, which opened a row
|
||||
// through RecordPlayStarted) when a song starts and "played" when it ends.
|
||||
// When the user's open row is that same song, that row is the listen and is
|
||||
// completed in place. Otherwise a completed row is written from at. An open
|
||||
// row for a different song is closed first only when it started before at:
|
||||
// one that started after it is the song playing now, which an app reporting
|
||||
// this one late must not cut short.
|
||||
//
|
||||
// source names the system playlist the listen came from, or is "" when
|
||||
// unknown; it only applies when a new row is written.
|
||||
func (w *Writer) RecordSyntheticCompletedPlay(
|
||||
ctx context.Context,
|
||||
userID, trackID pgtype.UUID,
|
||||
clientID string,
|
||||
clientID, source string,
|
||||
at time.Time,
|
||||
) error {
|
||||
var playEventID pgtype.UUID
|
||||
@@ -324,36 +353,33 @@ func (w *Writer) RecordSyntheticCompletedPlay(
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
|
||||
open, err := q.GetOpenPlayEventForUser(ctx, userID)
|
||||
hasOpen := err == nil
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var clientIDPtr *string
|
||||
if clientID != "" {
|
||||
clientIDPtr = &clientID
|
||||
}
|
||||
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
|
||||
UserID: userID,
|
||||
TrackID: trackID,
|
||||
SessionID: sessionID,
|
||||
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
|
||||
ClientID: clientIDPtr,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
playEventID = ev.ID
|
||||
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
|
||||
return err
|
||||
startedAt := at
|
||||
switch {
|
||||
case hasOpen && open.TrackID == trackID && within(open.StartedAt.Time, at, sameListenWindow):
|
||||
playEventID = open.ID
|
||||
startedAt = open.StartedAt.Time
|
||||
default:
|
||||
if hasOpen && !open.StartedAt.Time.After(at) {
|
||||
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
started, err := w.openPlay(ctx, q, userID, trackID, clientID, source, "", at)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
playEventID = started.PlayEventID
|
||||
}
|
||||
ratio := 1.0
|
||||
dur := track.DurationMs
|
||||
_, err = q.UpdatePlayEventEnded(ctx, dbq.UpdatePlayEventEndedParams{
|
||||
ID: ev.ID,
|
||||
EndedAt: pgtype.Timestamptz{Time: at.Add(time.Duration(track.DurationMs) * time.Millisecond), Valid: true},
|
||||
ID: playEventID,
|
||||
EndedAt: pgtype.Timestamptz{Time: startedAt.Add(time.Duration(track.DurationMs) * time.Millisecond), Valid: true},
|
||||
DurationPlayedMs: &dur,
|
||||
CompletionRatio: &ratio,
|
||||
WasSkipped: false,
|
||||
|
||||
@@ -286,7 +286,7 @@ func TestRecordPlaySkipped_AlwaysSkipFlagAndSkipEventRow(t *testing.T) {
|
||||
func TestRecordSyntheticCompletedPlay_WritesBothRows(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
now := time.Now().UTC()
|
||||
if err := f.w.RecordSyntheticCompletedPlay(context.Background(), f.user, f.track, "feishin", now); err != nil {
|
||||
if err := f.w.RecordSyntheticCompletedPlay(context.Background(), f.user, f.track, "feishin", "", now); err != nil {
|
||||
t.Fatalf("synthetic: %v", err)
|
||||
}
|
||||
rows, _ := f.pool.Query(context.Background(),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user