quintodrome/server/e2e/subsonic_sonic_similarity_test.go
Deluan Quintão 94eb6c522b
feat(subsonic): implement playbackReport OpenSubsonic extension (#5442)
* feat(req): add Float64Or helper for parsing float query params

* feat(scrobbler): extend NowPlayingInfo with state/position/rate fields

* feat(scrobbler): implement ReportPlayback with state machine and auto-scrobble

* feat(responses): add state/positionMs/playbackRate to NowPlayingEntry

* feat(subsonic): add reportPlayback endpoint handler

* feat(subsonic): include state/positionMs/playbackRate in getNowPlaying response

* feat(subsonic): register playbackReport OpenSubsonic extension

* test(e2e): add reportPlayback endpoint e2e tests

* refactor(scrobbler): simplify ReportPlayback — extract helpers, remove duplication

- Add state constants and exported ValidStates map
- Extract remainingTTL() helper (was duplicated 3x)
- Merge playing/paused switch cases into single branch
- Use Get instead of GetWithParticipants for non-stopped states
- Guard NowPlayingCount broadcast with count-change detection
- Use cache entry for NowPlaying dispatch instead of extra DB query
- Remove redundant Position field from NowPlayingInfo

* refactor(scrobbler): skip DB query in playing/paused when playMap has entry

* fix(play_tracker): handle errors when adding/updating NowPlayingInfo in cache

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker): replace sort with slices.SortFunc for NowPlayingInfo

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(play_tracker): check all ReportPlayback errors in tests

Replace _ = with explicit error assertions to avoid masking
failures in intermediate calls.

Signed-off-by: Deluan <deluan@navidrome.org>

* test(e2e): use real PlayTracker and assert getNowPlaying after reportPlayback

Replace noopPlayTracker with a real PlayTracker backed by the E2E
database. E2E tests now verify the full round-trip: reportPlayback
creates/updates/removes entries visible via getNowPlaying, including
state, positionMs, and playbackRate fields.

Export NewPlayTracker constructor for use outside the scrobbler package.

* fix(play_tracker): account for playback rate in TTL and detect track switches

The remainingTTL function now divides remaining time by the playback rate,
so cache entries expire correctly at non-1x speeds (e.g., 2x playback halves
the TTL). Zero/negative rates default to 1.0. The playing/paused case now
checks if the cached MediaFile ID matches the reported mediaId, falling back
to a DB fetch when the client switches tracks without sending stopped/starting.
Adds parameterized tests for remainingTTL covering rate variations and edge cases.

* fix(subsonic): validate positionMs and playbackRate in reportPlayback

Reject negative positionMs values and invalid playbackRate values (NaN,
Inf, zero, negative) at the API boundary before they reach TTL and
position estimation math. Returns clear error messages for each case.

* feat(play_tracker): add ClientId and ClientName to ReportPlayback parameters

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker): replace NowPlaying method with ReportPlayback calls

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(play_tracker_test): remove redundant TTL behavior tests and clean up mockPluginLoader

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-04-30 23:04:05 -04:00

273 lines
8.5 KiB
Go

package e2e
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"github.com/Masterminds/squirrel"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/agents"
"github.com/navidrome/navidrome/core/lyrics"
"github.com/navidrome/navidrome/core/matcher"
"github.com/navidrome/navidrome/core/metrics"
"github.com/navidrome/navidrome/core/playback"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/core/scrobbler"
"github.com/navidrome/navidrome/core/sonic"
"github.com/navidrome/navidrome/core/stream"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/events"
"github.com/navidrome/navidrome/server/subsonic"
"github.com/navidrome/navidrome/server/subsonic/responses"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// buildSonicRouter creates a subsonic.Router with a real sonic.Sonic service
// backed by the given provider and the shared e2e DataStore.
func buildSonicRouter(provider sonic.Provider) *subsonic.Router {
loader := &mockSonicPluginLoader{provider: provider}
m := matcher.New(ds)
sonicSvc := sonic.New(ds, loader, m)
decider := stream.NewTranscodeDecider(ds, noopFFmpeg{})
return subsonic.New(
ds,
noopArtwork{},
&spyStreamer{},
noopArchiver{},
core.NewPlayers(ds),
noopProvider{},
nil, // scanner
events.NoopBroker(),
playlists.NewPlaylists(ds, core.NewImageUploadService()),
scrobbler.NewPlayTracker(ds, events.NoopBroker(), nil),
core.NewShare(ds),
playback.PlaybackServer(nil),
metrics.NewNoopInstance(),
lyrics.NewLyrics(nil),
decider,
sonicSvc,
)
}
// doSonicReq makes a request through a sonic-enabled router and returns the parsed response.
func doSonicReq(sonicRouter *subsonic.Router, endpoint string, params ...string) *responses.Subsonic {
w := httptest.NewRecorder()
r := buildReq(adminUser, endpoint, params...)
sonicRouter.ServeHTTP(w, r)
return parseJSONResponse(w)
}
// doSonicRawReq makes a request through a sonic-enabled router and returns the raw recorder.
func doSonicRawReq(sonicRouter *subsonic.Router, endpoint string, params ...string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
r := buildReq(adminUser, endpoint, params...)
sonicRouter.ServeHTTP(w, r)
return w
}
var _ = Describe("Sonic Similarity Endpoints", func() {
BeforeEach(func() {
setupTestDB()
})
Context("without sonic similarity plugin", func() {
Describe("getSonicSimilarTracks", func() {
It("returns 404 when no sonic similarity plugin is available", func() {
w := doRawReq("getSonicSimilarTracks", "id", "any-song-id")
Expect(w.Code).To(Equal(http.StatusNotFound))
})
})
Describe("findSonicPath", func() {
It("returns 404 when no sonic similarity plugin is available", func() {
w := doRawReq("findSonicPath", "startSongId", "any-song-id", "endSongId", "another-song-id")
Expect(w.Code).To(Equal(http.StatusNotFound))
})
})
})
Context("with sonic similarity plugin", func() {
var (
sonicRouter *subsonic.Router
comeTogether model.MediaFile
something model.MediaFile
)
BeforeEach(func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
Filters: squirrel.Eq{"title": "Come Together"},
})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
comeTogether = songs[0]
songs, err = ds.MediaFile(ctx).GetAll(model.QueryOptions{
Filters: squirrel.Eq{"title": "Something"},
})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
something = songs[0]
provider := &mockSonicProvider{
similarIDs: []string{something.ID, comeTogether.ID},
pathIDs: []string{comeTogether.ID, something.ID},
}
sonicRouter = buildSonicRouter(provider)
})
Describe("getSonicSimilarTracks", func() {
It("returns similar tracks with similarity scores", func() {
resp := doSonicReq(sonicRouter, "getSonicSimilarTracks", "id", comeTogether.ID)
Expect(resp.Status).To(Equal(responses.StatusOK))
matches := *resp.SonicMatches
Expect(matches).To(HaveLen(2))
Expect(matches[0].Entry.Title).To(Equal("Something"))
Expect(matches[0].Similarity).To(Equal(1.0))
Expect(matches[1].Entry.Title).To(Equal("Come Together"))
Expect(matches[1].Similarity).To(Equal(0.9))
})
It("respects the count parameter", func() {
resp := doSonicReq(sonicRouter, "getSonicSimilarTracks", "id", comeTogether.ID, "count", "1")
Expect(resp.Status).To(Equal(responses.StatusOK))
Expect(*resp.SonicMatches).To(HaveLen(1))
})
It("returns an error for a missing id parameter", func() {
resp := doSonicReq(sonicRouter, "getSonicSimilarTracks")
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
It("returns an error for a non-existent song ID", func() {
resp := doSonicReq(sonicRouter, "getSonicSimilarTracks", "id", "non-existent-id")
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
It("returns correct JSON structure", func() {
w := doSonicRawReq(sonicRouter, "getSonicSimilarTracks", "id", comeTogether.ID)
Expect(w.Code).To(Equal(http.StatusOK))
var wrapper responses.JsonWrapper
Expect(json.Unmarshal(w.Body.Bytes(), &wrapper)).To(Succeed())
matches := *wrapper.Subsonic.SonicMatches
Expect(matches).To(HaveLen(2))
Expect(matches[0].Similarity).To(BeNumerically(">", 0))
Expect(matches[0].Entry.Id).ToNot(BeEmpty())
})
})
Describe("findSonicPath", func() {
It("returns a path between two tracks with similarity scores", func() {
resp := doSonicReq(sonicRouter, "findSonicPath",
"startSongId", comeTogether.ID,
"endSongId", something.ID,
)
Expect(resp.Status).To(Equal(responses.StatusOK))
matches := *resp.SonicMatches
Expect(matches).To(HaveLen(2))
Expect(matches[0].Entry.Title).To(Equal("Come Together"))
Expect(matches[0].Similarity).To(Equal(1.0))
Expect(matches[1].Entry.Title).To(Equal("Something"))
Expect(matches[1].Similarity).To(Equal(0.95))
})
It("returns an error for a missing startSongId parameter", func() {
resp := doSonicReq(sonicRouter, "findSonicPath", "endSongId", something.ID)
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
It("returns an error for a missing endSongId parameter", func() {
resp := doSonicReq(sonicRouter, "findSonicPath", "startSongId", comeTogether.ID)
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
It("returns an error for a non-existent start song ID", func() {
resp := doSonicReq(sonicRouter, "findSonicPath",
"startSongId", "non-existent-id",
"endSongId", something.ID,
)
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
It("returns an error for a non-existent end song ID", func() {
resp := doSonicReq(sonicRouter, "findSonicPath",
"startSongId", comeTogether.ID,
"endSongId", "non-existent-id",
)
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
})
})
})
})
// mockSonicProvider returns results using IDs from the real test library,
// so that the matcher can resolve them back to actual MediaFiles.
type mockSonicProvider struct {
similarIDs []string
pathIDs []string
}
func (m *mockSonicProvider) GetSonicSimilarTracks(_ context.Context, mf *model.MediaFile, count int) ([]sonic.SimilarResult, error) {
var results []sonic.SimilarResult
for i, id := range m.similarIDs {
if i >= count {
break
}
results = append(results, sonic.SimilarResult{
Song: agents.Song{ID: id},
Similarity: 1.0 - float64(i)*0.1,
})
}
return results, nil
}
func (m *mockSonicProvider) FindSonicPath(_ context.Context, startMf, endMf *model.MediaFile, count int) ([]sonic.SimilarResult, error) {
var results []sonic.SimilarResult
for i, id := range m.pathIDs {
if i >= count {
break
}
results = append(results, sonic.SimilarResult{
Song: agents.Song{ID: id},
Similarity: 1.0 - float64(i)*0.05,
})
}
return results, nil
}
type mockSonicPluginLoader struct {
provider sonic.Provider
}
func (m *mockSonicPluginLoader) PluginNames(capability string) []string {
if capability == "SonicSimilarity" && m.provider != nil {
return []string{"mock-sonic"}
}
return nil
}
func (m *mockSonicPluginLoader) LoadSonicSimilarity(_ string) (sonic.Provider, bool) {
if m.provider != nil {
return m.provider, true
}
return nil, false
}