fix(jellyfin): clamp negative StartIndex to zero - #6341 (#6366)

This commit is contained in:
Santhi Prakash 2026-11-11 02:42:19 +05:30 committed by GitHub
parent 27d041486c
commit 64cf86fae9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 109 additions and 19 deletions

View File

@ -57,7 +57,8 @@ func (api *Router) listArtistsByRole(w http.ResponseWriter, r *http.Request, rol
func (api *Router) getGenres(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
p := req.Params(r)
opts := model.QueryOptions{Offset: p.IntOr("startindex", 0), Max: p.IntOr("limit", 0)}
offset, limit := pageParams(p)
opts := model.QueryOptions{Offset: offset, Max: limit}
res, err := api.listGenres(ctx, opts)
if err != nil {
api.internalError(w, r, err)
@ -83,8 +84,8 @@ func (api *Router) getStudios(w http.ResponseWriter, r *http.Request) {
return
}
items := slice.Map(labels, dto.StudioToBaseItem)
offset, max := p.IntOr("startindex", 0), p.IntOr("limit", 0)
api.ok(w, r, result(paginate(items, offset, max), len(items), offset))
offset, limit := pageParams(p)
api.ok(w, r, result(paginate(items, offset, limit), len(items), offset))
}
// getQueryFiltersLegacy handles GET /Items/Filters. Genres and Years are scoped to ParentId's

View File

@ -206,6 +206,16 @@ var _ = Describe("Browsing", func() {
invoke(api.getGenres, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
})
It("treats a negative StartIndex as 0 instead of panicking", func() {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Genres?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
invoke(api.getGenres, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.StartIndex).To(Equal(0))
})
})
Describe("getStudios", func() {
@ -238,6 +248,16 @@ var _ = Describe("Browsing", func() {
invoke(api.getStudios, w, r)
Expect(w.Code).To(Equal(http.StatusNotFound))
})
It("treats a negative StartIndex as 0 instead of panicking", func() {
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Studios?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
invoke(api.getStudios, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.StartIndex).To(Equal(0))
})
})
Describe("getQueryFiltersLegacy", func() {

View File

@ -312,13 +312,14 @@ type itemsQuery struct {
// listParams reads the itemsQuery fields that come straight from query params.
func listParams(p *req.Values) itemsQuery {
offset, limit := pageParams(p)
return itemsQuery{
fields: dto.ParseFields(p.Strings("fields")...),
search: searchTerm(p),
sortBy: joinedStrings(p, "sortby"),
sortOrder: joinedStrings(p, "sortorder"),
offset: p.IntOr("startindex", 0),
limit: p.IntOr("limit", 0),
offset: offset,
limit: limit,
filters: parseItemFilters(p),
}
}
@ -504,7 +505,8 @@ func (api *Router) mergeTypesPaged(ctx context.Context, q itemsQuery, offset int
// Each per-type query needs at most offset+limit rows (worst case: one type fills the whole window).
window := offset + q.limit
if q.search != "" {
window = min(window, maxSearchLimit)
// Capping offset before the sum keeps a huge StartIndex from wrapping the window negative.
window = min(min(offset, maxSearchLimit)+q.limit, maxSearchLimit)
}
lists := make([][]dto.BaseItemDto, len(q.types))
totals := make([]int, len(q.types))
@ -650,9 +652,16 @@ func parseTypes(types string) []string {
return slice.Unique(recognized)
}
// pageParams reads StartIndex/Limit; Jellyfin treats a negative StartIndex as 0.
func pageParams(p *req.Values) (offset, limit int) {
return max(p.IntOr("startindex", 0), 0), p.IntOr("limit", 0)
}
// paginate applies StartIndex/Limit to an in-memory item list, for the multi-type merge path only
// (single-type queries push Offset/Max down to SQL instead).
func paginate(items []dto.BaseItemDto, offset, limit int) []dto.BaseItemDto {
// A negative offset would panic the slice below; Jellyfin treats it as 0.
offset = max(offset, 0)
if offset >= len(items) {
return []dto.BaseItemDto{}
}

View File

@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"slices"
@ -386,6 +387,39 @@ var _ = Describe("Items", func() {
Expect(albumRepo.Options.Max).To(Equal(3))
})
It("treats a negative StartIndex as 0 on the multi-type merge instead of panicking", func() {
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}})
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=-1&Limit=2", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.StartIndex).To(Equal(0))
Expect(res.Items).To(HaveLen(2))
Expect(res.TotalRecordCount).To(Equal(4))
// The clamped offset must feed the per-type window too: 0+Limit, not -1+Limit.
Expect(mfRepo.Options.Max).To(Equal(2))
Expect(albumRepo.Options.Max).To(Equal(2))
})
It("clamps a negative StartIndex to 0 on the single-type path", func() {
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&StartIndex=-1&Limit=10", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
Expect(albumRepo.Options.Offset).To(Equal(0))
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.StartIndex).To(Equal(0))
Expect(res.Items).To(HaveLen(1))
})
DescribeTable("translates the Filters list and its standalone equivalents",
func(query string, wantSQL, notWantSQL []string) {
albumRepo := ds.Album().(*tests.MockAlbumRepo)
@ -532,18 +566,22 @@ var _ = Describe("Items", func() {
Expect(res.TotalRecordCount).To(BeNumerically(">", 10))
})
It("bounds the multi-type search window however large StartIndex is", func() {
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=500000&Limit=1", nil).
WithContext(ctxUser())
invoke(api.getItems, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
// Without the bound this asks each type for ~500001 rows.
Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1))
})
DescribeTable("bounds the multi-type search window however large StartIndex is",
func(startIndex int) {
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", startIndex), nil).
WithContext(ctxUser())
invoke(api.getItems, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1))
},
Entry("large", 500000),
// StartIndex+Limit would wrap negative and slice out of range in a worker goroutine.
Entry("near the int limit", math.MaxInt),
)
It("stops a multi-type search at the ceiling rather than serving another type's rows", func() {
// Bounding the per-type window is what keeps StartIndex from driving it without limit, and

View File

@ -216,7 +216,8 @@ func (api *Router) getPlaylistItems(w http.ResponseWriter, r *http.Request) {
}
p := req.Params(r)
fields := dto.ParseFields(p.Strings("fields")...)
res, err := api.playlistTrackPage(ctx, repo, fields, p.IntOr("startindex", 0), p.IntOr("limit", 0))
offset, limit := pageParams(p)
res, err := api.playlistTrackPage(ctx, repo, fields, offset, limit)
if err != nil {
api.internalError(w, r, err)
return

View File

@ -270,6 +270,27 @@ var _ = Describe("Playlists", func() {
Expect(fp.tracksRepo.Options.Max).To(Equal(1))
})
It("clamps a negative StartIndex to 0", func() {
fp.getPls = &model.Playlist{
ID: testID("pl1"),
Tracks: model.PlaylistTracks{
{ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}},
{ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}},
},
}
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Playlists/"+testID("pl1")+"/Items?StartIndex=-1&Limit=1", nil).
WithContext(context.Background())
r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1")))
invoke(api.getPlaylistItems, w, r)
Expect(w.Code).To(Equal(http.StatusOK))
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.StartIndex).To(Equal(0))
Expect(res.Items).To(HaveLen(1))
Expect(fp.tracksRepo.Options.Offset).To(Equal(0))
})
It("returns 404 for a non-owned or absent playlist", func() {
fp.getErr = model.ErrNotFound
w := httptest.NewRecorder()