diff --git a/model/datastore.go b/model/datastore.go index 6ded8c575..e2f03784e 100644 --- a/model/datastore.go +++ b/model/datastore.go @@ -13,6 +13,9 @@ type QueryOptions struct { Offset int Filters squirrel.Sqlizer Seed string // for random sorting + // SortOrders is one "asc"/"desc" per Sort key, kept on every column its mapping expands into. + // Empty means Order applies to every key; a key past the end reuses the first entry. + SortOrders []string } type DataStore interface { diff --git a/persistence/artwork_hydration.go b/persistence/artwork_hydration.go index 76646ec74..3f1817acf 100644 --- a/persistence/artwork_hydration.go +++ b/persistence/artwork_hydration.go @@ -41,7 +41,10 @@ func streamByIDs[S ~[]T, T any](ids []string, fetch func(chunk []string) (S, err func chunkOptions(options []model.QueryOptions, idField string) func([]string) model.QueryOptions { var base model.QueryOptions if len(options) > 0 { - base = model.QueryOptions{Sort: options[0].Sort, Order: options[0].Order, Filters: options[0].Filters} + base = model.QueryOptions{ + Sort: options[0].Sort, Order: options[0].Order, SortOrders: options[0].SortOrders, + Filters: options[0].Filters, + } } return func(chunk []string) model.QueryOptions { opts := base diff --git a/persistence/sql_base_repository.go b/persistence/sql_base_repository.go index 03cc6a01b..32c839535 100644 --- a/persistence/sql_base_repository.go +++ b/persistence/sql_base_repository.go @@ -155,7 +155,14 @@ func (r sqlRepository) applyOptions(sq SelectBuilder, options ...model.QueryOpti sq = sq.Offset(uint64(options[0].Offset)) } if options[0].Sort != "" { - sq = sq.OrderBy(r.buildSortOrder(options[0].Sort, options[0].Order)) + sort, order := options[0].Sort, options[0].Order + // Per-key directions are absolute, so buildSortOrder gets an ascending baseline. + // resetSeededRandom has already rewritten "random" to SEEDEDRAND by here. + if len(options[0].SortOrders) > 0 && sort != "random" && !strings.HasPrefix(sort, "SEEDEDRAND(") { + sort = r.sortWithKeyOrders(sort, options[0].SortOrders) + order = "" + } + sq = sq.OrderBy(r.buildSortOrder(sort, order)) } } return sq @@ -196,6 +203,39 @@ func (r sqlRepository) lookupSortMapping(sort string) (mapping, snakeCased strin return mapping, snakeCased, ok } +// sortWithKeyOrders maps each logical sort key, then marks descending keys so buildSortOrder +// keeps that direction on every column the mapping expands into. +func (r sqlRepository) sortWithKeyOrders(sort string, orders []string) string { + keys := strings.FieldsFunc(sort, splitFunc(',')) + out := make([]string, 0, len(keys)) + for i, key := range keys { + key = strings.TrimSpace(key) + if key == "" { + continue + } + mapped := r.sortMapping(key) + if !descendingOrder(i, orders) { + out = append(out, mapped) + continue + } + for _, col := range strings.FieldsFunc(mapped, splitFunc(',')) { + out = append(out, strings.TrimSpace(col)+" desc") + } + } + return strings.Join(out, ", ") +} + +func descendingOrder(i int, orders []string) bool { + if len(orders) == 0 { + return false + } + raw := orders[0] + if i < len(orders) { + raw = orders[i] + } + return raw == "desc" +} + func (r sqlRepository) buildSortOrder(sort, order string) string { sort = r.sortMapping(sort) order = strings.ToLower(strings.TrimSpace(order)) diff --git a/persistence/sql_base_repository_test.go b/persistence/sql_base_repository_test.go index 4b42e7f1d..ab364e794 100644 --- a/persistence/sql_base_repository_test.go +++ b/persistence/sql_base_repository_test.go @@ -62,6 +62,18 @@ var _ = Describe("sqlRepository", func() { sql, _, _ := sq.ToSql() Expect(sql).To(Equal("SELECT * FROM test ORDER BY title desc LIMIT 1 OFFSET 2")) }) + + It("applies a per-key SortOrder after mappings expand", func() { + r.sortMappings["max_year"] = "coalesce(nullif(original_date,''), cast(max_year as text)), release_date" + sq = r.applyOptions(sq, model.QueryOptions{ + Sort: "duration, name, max_year, play_count", + Order: "desc", + SortOrders: []string{"desc", "asc", "desc"}, + }) + sql, _, _ := sq.ToSql() + Expect(sql).To(Equal("SELECT * FROM test ORDER BY duration desc, title asc, " + + "coalesce(nullif(original_date,''), cast(max_year as text)) desc, release_date desc, play_count desc")) + }) }) Describe("toSQL", func() { diff --git a/server/filter/filters.go b/server/filter/filters.go index 9014bb799..e015db073 100644 --- a/server/filter/filters.go +++ b/server/filter/filters.go @@ -46,7 +46,7 @@ func AlbumsByArtist() Options { return addDefaultFilters(Options{Sort: "artist"}) } -func AlbumsByArtistID(artistId string) Options { +func AlbumsByArtistID(artistId any) Options { roles := []model.Role{model.RoleAlbumArtist} if conf.Server.Subsonic.ArtistParticipations { roles = append(roles, model.RoleArtist) @@ -57,10 +57,9 @@ func AlbumsByArtistID(artistId string) Options { }) } -// AlbumsByContributingArtistID matches albums where the artist performs on a track but is not the -// album artist — Jellyfin's "Featured On". The disjoint complement of AlbumsByArtistID, so an -// artist's own discography never leaks into it. -func AlbumsByContributingArtistID(artistId string) Options { +// AlbumsByContributingArtistID matches albums where the artist (an id or a slice of ids) performs on +// a track but is not the album artist: Jellyfin's "Featured On", the complement of AlbumsByArtistID. +func AlbumsByContributingArtistID(artistId any) Options { return addDefaultFilters(Options{ Sort: "max_year", Filters: And{ @@ -101,7 +100,7 @@ func SongsByAlbum(albumId string) Options { // SongsByArtistID matches media files where the artist participates as album or track artist, in // album order. -func SongsByArtistID(artistId string) Options { +func SongsByArtistID(artistId any) Options { return addDefaultFilters(Options{ Sort: "album", Filters: persistence.ParticipantIDFilter("media_file", artistId, model.RoleArtist, model.RoleAlbumArtist), diff --git a/server/jellyfin/items.go b/server/jellyfin/items.go index 28de4c31e..ff6de027b 100644 --- a/server/jellyfin/items.go +++ b/server/jellyfin/items.go @@ -31,6 +31,12 @@ func searchTerm(p *req.Values) string { return strings.TrimSpace(p.StringOr("searchterm", "")) } +// joinedStrings joins repeated values of a query param with commas. Clients send lists either +// comma-separated (Finamp) or as repeated keys (@jellyfin/sdk), and the parsers split on commas. +func joinedStrings(p *req.Values, key string) string { + return strings.Join(p.Strings(key), ",") +} + // itemFilters is the parsed Filters=... list together with the standalone isFavorite/isPlayed params // clients may send instead. A nil field means the client asked for no filtering on that dimension. type itemFilters struct { @@ -42,7 +48,7 @@ type itemFilters struct { // Jellyfin. Tokens with no Navidrome equivalent (Likes, IsFolder, IsResumable) are dropped. func parseItemFilters(p *req.Values) itemFilters { f := itemFilters{favorite: p.BoolPtr("isfavorite"), played: p.BoolPtr("isplayed")} - for token := range strings.SplitSeq(p.StringOr("filters", ""), ",") { + for token := range strings.SplitSeq(joinedStrings(p, "filters"), ",") { switch strings.TrimSpace(token) { case "IsFavorite", "IsFavoriteOrLikes": f.favorite = new(true) @@ -294,9 +300,9 @@ type itemsQuery struct { entityParent string isLibraryParent bool scopeIDs []int - // artistId selects that artist's own discography; contributingOnly means albums they merely - // appear on (Jellyfin's "Featured On"), which must exclude that discography. - artistId string + // artistIds selects those artists' own discography (any of them). contributingOnly means albums + // they merely appear on (Jellyfin's "Featured On"), which must exclude that discography. + artistIds []string contributingOnly bool genreIds []string albumIds []string @@ -309,8 +315,8 @@ func listParams(p *req.Values) itemsQuery { return itemsQuery{ fields: dto.ParseFields(p.Strings("fields")...), search: searchTerm(p), - sortBy: p.StringOr("sortby", ""), - sortOrder: p.StringOr("sortorder", ""), + sortBy: joinedStrings(p, "sortby"), + sortOrder: joinedStrings(p, "sortorder"), offset: p.IntOr("startindex", 0), limit: p.IntOr("limit", 0), filters: parseItemFilters(p), @@ -349,7 +355,7 @@ func (api *Router) parseItemsQuery(ctx context.Context, r *http.Request) (itemsQ } q := listParams(p) q.ids = ids - q.rawTypes = knownItemKinds(p.StringOr("includeitemtypes", "")) + q.rawTypes = knownItemKinds(joinedStrings(p, "includeitemtypes")) q.parentId = parentId q.genreIds = genreIds q.albumIds = albumIds @@ -357,14 +363,15 @@ func (api *Router) parseItemsQuery(ctx context.Context, r *http.Request) (itemsQ q.studioIds = studioIds // An artist's page filters by artist, not ParentId: Finamp sends ParentId= for scoping // plus AlbumArtistIds/ArtistIds/contributingArtistIds for the artist. - albumArtistScope := firstNonEmpty(p.StringOr("albumartistids", ""), p.StringOr("artistids", "")) - contributingScope := p.StringOr("contributingartistids", "") - artistId, ok := firstDecodedID(firstNonEmpty(albumArtistScope, contributingScope)) + albumArtistScope := joinedStrings(p, "albumartistids") + artistScope := joinedStrings(p, "artistids") + contributingScope := joinedStrings(p, "contributingartistids") + artistIds, ok := decodedIDList(firstNonEmpty(albumArtistScope, artistScope, contributingScope)) if !ok { return itemsQuery{}, model.ErrNotFound } - q.artistId = artistId - q.contributingOnly = albumArtistScope == "" && contributingScope != "" + q.artistIds = artistIds + q.contributingOnly = albumArtistScope == "" && artistScope == "" && contributingScope != "" q.types = parseTypes(q.rawTypes) q.scopeIDs, q.isLibraryParent = resolveLibraryScope(ctx, q.parentId) @@ -560,14 +567,25 @@ func firstNonEmpty(vals ...string) string { return "" } -// firstDecodedID decodes the first id from a (possibly comma-separated) Jellyfin id list, reporting -// whether it decoded successfully (see decodeFilterParam). -func firstDecodedID(s string) (string, bool) { - if s == "" { - return "", true +// decodedIDList decodes every id in a comma-joined Jellyfin id list. ok is false when any entry is +// malformed, so a later bad id can't be dropped and widen the query (see decodeFilterParam). +func decodedIDList(s string) ([]string, bool) { + if strings.TrimSpace(s) == "" { + return nil, true } - first, _, _ := strings.Cut(s, ",") - return decodeFilterParam(strings.TrimSpace(first)) + var ids []string + for part := range strings.SplitSeq(s, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + id, ok := decodeFilterParam(part) + if !ok { + return nil, false + } + ids = append(ids, id) + } + return ids, true } // decodedQueryIDs reads an id-list param in both client spellings (see queryIDs). ok is false if @@ -707,10 +725,12 @@ func (api *Router) listAlbums(ctx context.Context, opts model.QueryOptions, q it // For albums, ParentId (browse an artist) and AlbumArtistIds/ArtistIds both mean "this artist's // albums"; contributingArtistIds means "albums they only appear on" (Featured On). switch { - case q.contributingOnly && q.artistId != "": - filters = append(filters, filter.AlbumsByContributingArtistID(q.artistId).Filters) - case firstNonEmpty(q.artistId, q.entityParent) != "": - filters = append(filters, filter.AlbumsByArtistID(firstNonEmpty(q.artistId, q.entityParent)).Filters) + case q.contributingOnly && len(q.artistIds) > 0: + filters = append(filters, filter.AlbumsByContributingArtistID(q.artistIds).Filters) + case len(q.artistIds) > 0: + filters = append(filters, filter.AlbumsByArtistID(q.artistIds).Filters) + case q.entityParent != "": + filters = append(filters, filter.AlbumsByArtistID(q.entityParent).Filters) default: filters = append(filters, notMissing) } @@ -753,8 +773,8 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite filters := squirrel.And{} // For songs, ArtistIds/AlbumArtistIds selects an artist's tracks; ParentId selects an album's. switch { - case q.artistId != "": - filters = append(filters, filter.SongsByArtistID(q.artistId).Filters) + case len(q.artistIds) > 0: + filters = append(filters, filter.SongsByArtistID(q.artistIds).Filters) case q.entityParent != "": filters = append(filters, filter.SongsByAlbum(q.entityParent).Filters) default: @@ -791,7 +811,7 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite } // When browsing an album's tracks, default to disc+track order (like Subsonic's GetAlbum); an // explicit client SortBy still wins, since applySort already set opts.Sort. - if q.artistId == "" && q.entityParent != "" && opts.Sort == "" { + if len(q.artistIds) == 0 && q.entityParent != "" && opts.Sort == "" { opts.Sort = filter.SongsByAlbum(q.entityParent).Sort } // A full-library request (Finamp's sync, with MediaSources) is tens of thousands of fat rows. @@ -1011,17 +1031,24 @@ func result(items []dto.BaseItemDto, total, start int) dto.QueryResult { return dto.QueryResult{Items: items, TotalRecordCount: total, StartIndex: start} } -// applySort keeps every recognized SortBy key, so secondary keys break ties as Jellyfin intends. -// Unrecognized keys are skipped, not passed through raw where they could make an invalid ORDER BY. +// applySort keeps every recognized SortBy key, paired with SortOrder by index as Jellyfin's GetOrderBy +// does. Unrecognized keys are skipped, not passed through raw where they could make an invalid ORDER BY. func applySort(opts *model.QueryOptions, itemType, sortBy, order string) { - var cols []string - for key := range strings.SplitSeq(sortBy, ",") { + dirs := listParts(order) + var cols, colOrders []string + for i, key := range strings.Split(sortBy, ",") { + // An absent SortBy splits to one empty part; that is "no sort", not a key to count. + if sortBy == "" { + break + } + dir := sortDirection(i, dirs) col, ok := sortColumn(itemType, strings.TrimSpace(key)) // The repo matches random by exact string equality, so it can only ever sort alone. if !ok || slices.Contains(cols, col) || (col == "random" && len(cols) > 0) { continue } cols = append(cols, col) + colOrders = append(colOrders, dir) if col == "random" { break } @@ -1029,16 +1056,62 @@ func applySort(opts *model.QueryOptions, itemType, sortBy, order string) { switch { case len(cols) > 0: opts.Sort = strings.Join(cols, ", ") - case sortBy != "": + case strings.TrimSpace(sortBy) != "": log.Debug("Jellyfin API: no usable SortBy key, falling back to the default order", "itemType", itemType, "sortBy", sortBy) } - // Jellyfin allows a per-key SortOrder list, which one Order can't express; honor the first value - // for every key, as Jellyfin does for keys past the end of the list. - first, _, _ := strings.Cut(order, ",") - if strings.EqualFold(first, "Descending") { - opts.Order = "desc" + if !mixedDirections(colOrders) { + // With no kept key, a lone SortOrder still sets Order. + dir := sortDirection(0, dirs) + if len(colOrders) > 0 { + dir = colOrders[0] + } + if dir == "desc" { + opts.Order = "desc" + } + return } + opts.SortOrders = colOrders +} + +// listParts splits a comma-joined query value. An absent value is nil, not a single empty part. +func listParts(s string) []string { + if strings.TrimSpace(s) == "" { + return nil + } + parts := strings.Split(s, ",") + for i, part := range parts { + parts[i] = strings.TrimSpace(part) + } + return parts +} + +// sortDirection is "desc" only for Jellyfin's Descending. Keys past the end of dirs reuse the first +// entry, which is what Jellyfin does for a SortOrder list shorter than SortBy. +func sortDirection(i int, dirs []string) string { + if len(dirs) == 0 { + return "asc" + } + raw := dirs[0] + if i < len(dirs) { + raw = dirs[i] + } + if strings.EqualFold(raw, "Descending") { + return "desc" + } + return "asc" +} + +func mixedDirections(orders []string) bool { + if len(orders) < 2 { + return false + } + for _, order := range orders[1:] { + if order != orders[0] { + return true + } + } + return false } // sortColumnsByType maps lowercased-SortBy -> repo-sort-key per item type (repos map logical fields diff --git a/server/jellyfin/items_test.go b/server/jellyfin/items_test.go index bdf0be253..fe1f95a05 100644 --- a/server/jellyfin/items_test.go +++ b/server/jellyfin/items_test.go @@ -14,6 +14,7 @@ import ( "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/utils/req" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -288,6 +289,37 @@ var _ = Describe("Items", func() { Expect(res.TotalRecordCount).To(Equal(2)) }) + // @jellyfin/sdk (Jellify) sends array params as repeated keys. + It("merges results from every repeated IncludeItemTypes key", func() { + ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) + ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?SearchTerm=Salt&IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio&IncludeItemTypes=MusicAlbum", 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.Items).To(HaveLen(3)) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + Expect(res.TotalRecordCount).To(Equal(3)) + }) + + It("mixes a repeated IncludeItemTypes key with a comma-separated one", func() { + ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) + ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio,MusicAlbum", 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()) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + }) + It("merges favorite songs, albums, and playlists", func() { mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) @@ -313,6 +345,19 @@ var _ = Describe("Items", func() { Expect(playlistSQL).To(ContainSubstring("starred")) }) + It("applies every repeated Filters key", 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&Filters=IsFavorite&Filters=IsPlayed", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + sql, _, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(sql).To(ContainSubstring("starred")) + Expect(sql).To(ContainSubstring("play_count")) + }) + It("applies StartIndex/Limit to the merged multi-type result set", func() { ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) @@ -708,9 +753,8 @@ var _ = Describe("Items", func() { Entry("nothing recognized leaves the repo default", "MusicAlbum", "SeriesSortName", ""), ) - // Jellyfin allows a per-key SortOrder list; we cannot express that through one Order, so - // we honor the first value for all keys, matching Jellyfin's fallback for extra keys. - DescribeTable("reads the first SortOrder value for the whole sort", + // Jellyfin reuses the first SortOrder for keys past the end of the list. + DescribeTable("applies one SortOrder to every sort key", func(sortOrder, want string) { albumRepo := ds.Album().(*tests.MockAlbumRepo) albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) @@ -719,13 +763,50 @@ var _ = Describe("Items", func() { "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder="+sortOrder, nil).WithContext(ctxUser()) invoke(api.getItems, w, r) Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) Expect(albumRepo.Options.Order).To(Equal(want)) + Expect(albumRepo.Options.SortOrders).To(BeEmpty()) }, Entry("ascending", "Ascending", ""), Entry("descending", "Descending", "desc"), - Entry("descending leading a list", "Descending,Ascending", "desc"), - Entry("ascending leading a list", "Ascending,Descending", ""), ) + + It("pairs each SortOrder with its SortBy key", 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&SortBy=Runtime,SortName,PlayCount&SortOrder=Descending,Ascending", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name, play_count")) + Expect(albumRepo.Options.Order).To(BeEmpty()) + Expect(albumRepo.Options.SortOrders).To(Equal([]string{"desc", "asc", "desc"})) + }) + + It("keeps every key of a repeated SortBy", 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&SortBy=Runtime&SortBy=SortName", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) + }) + + It("pairs a repeated SortOrder key with its SortBy key", 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&SortBy=Runtime,SortName&SortOrder=Ascending&SortOrder=Descending", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(albumRepo.Options.Sort).To(Equal("duration, name")) + Expect(albumRepo.Options.Order).To(BeEmpty()) + Expect(albumRepo.Options.SortOrders).To(Equal([]string{"asc", "desc"})) + }) }) Describe("library scoping", func() { @@ -849,6 +930,56 @@ var _ = Describe("Items", func() { Expect(w.Code).To(Equal(http.StatusNotFound)) }) + It("404s when a later repeated ArtistIds value is malformed", func() { + ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds=not-a-valid-id", nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusNotFound)) + }) + + It("filters songs by every repeated ArtistIds key", func() { + mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) + mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", + "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds="+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + _, args, err := mfRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + }) + + It("filters albums by every artist in a comma-separated AlbumArtistIds", 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&AlbumArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + _, args, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + }) + + It("excludes an album artist from a multi-id contributingArtistIds Featured On filter", 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&contributingArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) + invoke(api.getItems, w, r) + Expect(w.Code).To(Equal(http.StatusOK)) + sql, args, err := albumRepo.Options.Filters.ToSql() + Expect(err).NotTo(HaveOccurred()) + Expect(sql).To(ContainSubstring("NOT IN")) + Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + Expect(strings.Count(sql, "album_artists")).To(Equal(2)) + }) + It("still applies the artist filter (rather than dropping it) for a well-formed but unknown AlbumArtistIds", func() { albumRepo := ds.Album().(*tests.MockAlbumRepo) albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) @@ -1154,6 +1285,17 @@ var _ = Describe("Items", func() { Expect(knownItemKinds("music, audio,MUSICVIDEO")).To(Equal("audio,MUSICVIDEO")) }) + It("keeps entries from every value of a repeated param", func() { + repeated := func(rawURL string) string { + r := httptest.NewRequest("GET", rawURL, nil) + return knownItemKinds(joinedStrings(req.Params(r), "includeitemtypes")) + } + Expect(repeated("/Items?includeitemtypes=MusicArtist&includeitemtypes=Audio&includeitemtypes=MusicAlbum")). + To(Equal("MusicArtist,Audio,MusicAlbum")) + Expect(repeated("/Items?includeitemtypes=Nonsense&includeitemtypes=music")).To(BeEmpty()) + Expect(repeated("/Items")).To(BeEmpty()) + }) + It("defaults to albums only when IncludeItemTypes is absent", func() { Expect(parseTypes("")).To(Equal([]string{"MusicAlbum"})) Expect(parseTypes("Nonsense")).To(BeEmpty()) diff --git a/server/jellyfin/stream.go b/server/jellyfin/stream.go index 515a6fcb8..6ca2e11b2 100644 --- a/server/jellyfin/stream.go +++ b/server/jellyfin/stream.go @@ -107,7 +107,7 @@ func (api *Router) streamUniversal(w http.ResponseWriter, r *http.Request) { func universalClientInfo(p *req.Values) *stream.ClientInfo { ci := &stream.ClientInfo{Name: "jellyfin-universal", MaxAudioBitrate: bitRateParam(p)} - for entry := range strings.SplitSeq(p.StringOr("container", ""), ",") { + for entry := range strings.SplitSeq(joinedStrings(p, "container"), ",") { container, codec, _ := strings.Cut(strings.TrimSpace(entry), "|") if container == "" { continue diff --git a/server/jellyfin/stream_test.go b/server/jellyfin/stream_test.go index 7a1112f37..08357d14d 100644 --- a/server/jellyfin/stream_test.go +++ b/server/jellyfin/stream_test.go @@ -299,6 +299,14 @@ var _ = Describe("Stream", func() { Expect(decider.client.MaxTranscodingAudioBitrate).To(Equal(128)) }) + It("accepts repeated Container query parameters", func() { + universal("Container=mp3&Container=m4a|aac&TranscodingContainer=m4a&AudioCodec=aac") + Expect(decider.client.DirectPlayProfiles).To(Equal([]stream.DirectPlayProfile{ + {Containers: []string{"mp3"}, Protocols: []string{stream.ProtocolHTTP}}, + {Containers: []string{"m4a"}, AudioCodecs: []string{"aac"}, Protocols: []string{stream.ProtocolHTTP}}, + })) + }) + It("uses AudioCodec as the target when no TranscodingContainer is given", func() { universal("Container=mp3&AudioCodec=aac") Expect(decider.client.TranscodingProfiles).To(Equal([]stream.Profile{