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 }