Merge upstream/master into feat-podcast-ux-improvements/5420

Resolve conflicts with the stateless-repositories refactor (#6149):
- port podcast repositories, model interfaces, mocks, service and handlers to per-call ctx
- podcast channel repo now implements generic rest.Repository/Persistable
- register podcast repos in SQLStore and MockDataStore
- merge OpenSubsonic extensions (apiKeyAuthentication + podcast extensions)
- renumber podcast migrations after upstream's latest (20260930...)
This commit is contained in:
Jiho Andrew Lee 2026-09-30 15:23:00 +09:00
commit 19385dc28b
508 changed files with 13229 additions and 8764 deletions

98
server/apiv1/api.go Normal file
View file

@ -0,0 +1,98 @@
package apiv1
import (
"errors"
"net/http"
"runtime/debug"
"slices"
"strings"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
)
type Router struct {
http.Handler
ds model.DataStore
}
func New(ds model.DataStore) *Router {
rt := &Router{ds: ds}
rt.Handler = rt.routes()
return rt
}
func (rt *Router) routes() http.Handler {
r := chi.NewRouter()
r.Use(problemRecoverer, headAsGet(r))
r.NotFound(func(w http.ResponseWriter, req *http.Request) {
writeProblemStatus(w, req, http.StatusNotFound, ProblemCodeNotFound, "no such endpoint")
})
r.MethodNotAllowed(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Allow", strings.Join(allowedMethods(r, req), ", "))
writeProblemStatus(w, req, http.StatusMethodNotAllowed, ProblemCodeMethodNotAllowed, "")
})
r.Get("/openapi.json", specHandler(withBasePath(api.SpecJSON(), `"url": `, true), "application/json"))
r.Get("/openapi.yaml", specHandler(withBasePath(api.SpecYAML(), "url: ", false), "application/yaml"))
strict := NewStrictHandlerWithOptions(rt, nil, StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, req *http.Request, err error) {
writeProblemStatus(w, req, http.StatusBadRequest, "validation", err.Error())
},
ResponseErrorHandlerFunc: writeProblem,
})
HandlerWithOptions(strict, ChiServerOptions{BaseRouter: r, ErrorHandlerFunc: bindingErrorHandler})
return r
}
func problemRecoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
rec := recover()
if rec == nil {
return
}
if err, ok := rec.(error); ok && errors.Is(err, http.ErrAbortHandler) {
panic(rec)
}
log.Error(r.Context(), "API v1: panic in handler", "panic", rec, "stack", string(debug.Stack()))
writeProblemStatus(w, r, http.StatusInternalServerError, ProblemCodeInternal, "")
}()
next.ServeHTTP(w, r)
})
}
var routableMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete}
// Looks routes up on mux itself: chi's RouteContext().Routes points at the parent router when mounted.
func allowedMethods(mux chi.Routes, req *http.Request) []string {
path := routePath(req)
var allowed []string
for _, m := range routableMethods {
if mux.Match(chi.NewRouteContext(), m, path) || (m == http.MethodHead && slices.Contains(allowed, http.MethodGet)) {
allowed = append(allowed, m)
}
}
return allowed
}
func headAsGet(mux chi.Routes) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodHead && !mux.Match(chi.NewRouteContext(), http.MethodHead, routePath(req)) {
chi.RouteContext(req.Context()).RouteMethod = http.MethodGet
}
next.ServeHTTP(w, req)
})
}
}
func routePath(req *http.Request) string {
if rctx := chi.RouteContext(req.Context()); rctx != nil && rctx.RoutePath != "" {
return rctx.RoutePath
}
return req.URL.Path
}

390
server/apiv1/api_gen.go Normal file
View file

@ -0,0 +1,390 @@
// Package apiv1 provides primitives to interact with the openapi HTTP API.
//
// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.8.0 DO NOT EDIT.
package apiv1
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
// Defines values for ProblemCode.
const (
ProblemCodeForbidden ProblemCode = "forbidden"
ProblemCodeInternal ProblemCode = "internal"
ProblemCodeMethodNotAllowed ProblemCode = "method_not_allowed"
ProblemCodeNotFound ProblemCode = "not_found"
ProblemCodeUnauthorized ProblemCode = "unauthorized"
ProblemCodeUnavailable ProblemCode = "unavailable"
ProblemCodeValidation ProblemCode = "validation"
)
// Valid indicates whether the value is a known member of the ProblemCode enum.
func (e ProblemCode) Valid() bool {
switch e {
case ProblemCodeForbidden:
return true
case ProblemCodeInternal:
return true
case ProblemCodeMethodNotAllowed:
return true
case ProblemCodeNotFound:
return true
case ProblemCodeUnauthorized:
return true
case ProblemCodeUnavailable:
return true
case ProblemCodeValidation:
return true
default:
return false
}
}
// Defines values for ServerInfoLoginMethods.
const (
ServerInfoLoginMethodsPassword ServerInfoLoginMethods = "password"
)
// Valid indicates whether the value is a known member of the ServerInfoLoginMethods enum.
func (e ServerInfoLoginMethods) Valid() bool {
switch e {
case ServerInfoLoginMethodsPassword:
return true
default:
return false
}
}
// Problem RFC 9457 problem details, returned for every 4xx and 5xx response.
type Problem struct {
// Code Machine-readable error code, and the value clients switch on. New codes may be added.
Code ProblemCode `json:"code"`
// Detail Human-readable explanation specific to this occurrence. Omitted for internal errors.
Detail *string `json:"detail,omitempty"`
// Errors Per-field failures. Present only when `code` is `validation`.
Errors *[]ValidationError `json:"errors,omitempty"`
// Status HTTP status code of this response.
Status int `json:"status"`
// Title Short human-readable summary, the same for all occurrences of this problem type.
Title string `json:"title"`
// Type URI reference identifying the problem type. Omitted while the problem carries no semantics
// beyond its HTTP status code, which RFC 9457 defines as `about:blank`. Problems with their
// own semantics get their own URI; switch on `code` instead.
Type *string `json:"type,omitempty"`
}
// ProblemCode Machine-readable error code, and the value clients switch on. New codes may be added.
type ProblemCode string
// ServerInfo Public server description. Everything an add-server screen needs before login.
type ServerInfo struct {
// LoginMethods Login methods this server accepts. New methods may be added; clients ignore values they do not recognise.
LoginMethods []ServerInfoLoginMethods `json:"loginMethods"`
// Name Human-readable server product name.
Name string `json:"name"`
// ServerVersion Version of the running server build.
ServerVersion string `json:"serverVersion"`
// SetupRequired True until the first admin user has been created.
SetupRequired bool `json:"setupRequired"`
// SpecVersion Version of the OpenAPI document this server implements.
SpecVersion string `json:"specVersion"`
}
// ServerInfoLoginMethods defines model for ServerInfo.LoginMethods.
type ServerInfoLoginMethods string
// ValidationError One field-level validation failure.
type ValidationError struct {
// Field Name of the offending query parameter, path parameter, or body field (dotted for nested).
Field string `json:"field"`
// Message Why the value was rejected.
Message string `json:"message"`
}
// InternalError RFC 9457 problem details, returned for every 4xx and 5xx response.
type InternalError = Problem
// ServerInterface represents all server handlers.
type ServerInterface interface {
// GetServerInfo Describe the server
// (GET /server)
GetServerInfo(w http.ResponseWriter, r *http.Request)
}
// Unimplemented server implementation that returns http.StatusNotImplemented for each endpoint.
type Unimplemented struct{}
// GetServerInfo Describe the server
// (GET /server)
func (_ Unimplemented) GetServerInfo(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
}
// ServerInterfaceWrapper converts contexts to parameters.
type ServerInterfaceWrapper struct {
Handler ServerInterface
HandlerMiddlewares []MiddlewareFunc
ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
type MiddlewareFunc func(http.Handler) http.Handler
// GetServerInfo operation middleware
func (siw *ServerInterfaceWrapper) GetServerInfo(w http.ResponseWriter, r *http.Request) {
handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
siw.Handler.GetServerInfo(w, r)
}))
for _, middleware := range siw.HandlerMiddlewares {
handler = middleware(handler)
}
handler.ServeHTTP(w, r)
}
type UnescapedCookieParamError struct {
ParamName string
Err error
}
func (e *UnescapedCookieParamError) Error() string {
return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName)
}
func (e *UnescapedCookieParamError) Unwrap() error {
return e.Err
}
type UnmarshalingParamError struct {
ParamName string
Err error
}
func (e *UnmarshalingParamError) Error() string {
return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error())
}
func (e *UnmarshalingParamError) Unwrap() error {
return e.Err
}
type RequiredParamError struct {
ParamName string
}
func (e *RequiredParamError) Error() string {
return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName)
}
type RequiredHeaderError struct {
ParamName string
Err error
}
func (e *RequiredHeaderError) Error() string {
return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName)
}
func (e *RequiredHeaderError) Unwrap() error {
return e.Err
}
type InvalidParamFormatError struct {
ParamName string
Err error
}
func (e *InvalidParamFormatError) Error() string {
return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error())
}
func (e *InvalidParamFormatError) Unwrap() error {
return e.Err
}
type TooManyValuesForParamError struct {
ParamName string
Count int
}
func (e *TooManyValuesForParamError) Error() string {
return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count)
}
// Handler creates http.Handler with routing matching OpenAPI spec.
func Handler(si ServerInterface) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{})
}
type ChiServerOptions struct {
BaseURL string
BaseRouter chi.Router
Middlewares []MiddlewareFunc
ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux.
func HandlerFromMux(si ServerInterface, r chi.Router) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{
BaseRouter: r,
})
}
func HandlerFromMuxWithBaseURL(si ServerInterface, r chi.Router, baseURL string) http.Handler {
return HandlerWithOptions(si, ChiServerOptions{
BaseURL: baseURL,
BaseRouter: r,
})
}
// HandlerWithOptions creates http.Handler with additional options
func HandlerWithOptions(si ServerInterface, options ChiServerOptions) http.Handler {
r := options.BaseRouter
if r == nil {
r = chi.NewRouter()
}
if options.ErrorHandlerFunc == nil {
options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
wrapper := ServerInterfaceWrapper{
Handler: si,
HandlerMiddlewares: options.Middlewares,
ErrorHandlerFunc: options.ErrorHandlerFunc,
}
r.Group(func(r chi.Router) {
r.Get(options.BaseURL+"/server", wrapper.GetServerInfo)
})
return r
}
type InternalErrorApplicationProblemPlusJSONResponse Problem
type GetServerInfoRequestObject struct {
}
type GetServerInfoResponseObject interface {
VisitGetServerInfoResponse(w http.ResponseWriter) error
}
type GetServerInfo200JSONResponse ServerInfo
func (response GetServerInfo200JSONResponse) VisitGetServerInfoResponse(w http.ResponseWriter) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(response); err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, err := buf.WriteTo(w)
return err
}
type GetServerInfo500ApplicationProblemPlusJSONResponse struct {
InternalErrorApplicationProblemPlusJSONResponse
}
func (response GetServerInfo500ApplicationProblemPlusJSONResponse) VisitGetServerInfoResponse(w http.ResponseWriter) error {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(response); err != nil {
return err
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(500)
_, err := buf.WriteTo(w)
return err
}
// StrictServerInterface represents all server handlers.
type StrictServerInterface interface {
// GetServerInfo Describe the server
// (GET /server)
GetServerInfo(ctx context.Context, request GetServerInfoRequestObject) (GetServerInfoResponseObject, error)
}
type StrictHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error)
type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc
type StrictHTTPServerOptions struct {
RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error)
}
func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface {
return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
},
ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
},
}}
}
func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface {
if options.RequestErrorHandlerFunc == nil {
options.RequestErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
}
if options.ResponseErrorHandlerFunc == nil {
options.ResponseErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
return &strictHandler{ssi: ssi, middlewares: middlewares, options: options}
}
type strictHandler struct {
ssi StrictServerInterface
middlewares []StrictMiddlewareFunc
options StrictHTTPServerOptions
}
// GetServerInfo operation middleware
func (sh *strictHandler) GetServerInfo(w http.ResponseWriter, r *http.Request) {
var request GetServerInfoRequestObject
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) {
return sh.ssi.GetServerInfo(ctx, request.(GetServerInfoRequestObject))
}
for _, middleware := range sh.middlewares {
handler = middleware(handler, "GetServerInfo")
}
response, err := handler(r.Context(), w, r, request)
if err != nil {
sh.options.ResponseErrorHandlerFunc(w, r, err)
} else if validResponse, ok := response.(GetServerInfoResponseObject); ok {
if err := validResponse.VisitGetServerInfoResponse(w); err != nil {
sh.options.ResponseErrorHandlerFunc(w, r, err)
}
} else if response != nil {
sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response))
}
}

75
server/apiv1/api_test.go Normal file
View file

@ -0,0 +1,75 @@
package apiv1
import (
"net/http"
"net/http/httptest"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Router", func() {
var router *Router
BeforeEach(func() {
router = New(&tests.MockDataStore{})
})
It("returns a 404 problem for unknown paths", func() {
w := serve(router, httptest.NewRequest(http.MethodGet, "/api/v1/nope", nil))
Expect(w.Code).To(Equal(http.StatusNotFound))
Expect(w.Header().Get("Content-Type")).To(Equal(problemContentType))
Expect(decodeProblem(w).Code).To(Equal(ProblemCodeNotFound))
})
It("returns a 405 problem listing the allowed methods for a wrong method on a known path", func() {
w := serve(router, httptest.NewRequest(http.MethodPost, "/api/v1/server", nil))
Expect(w.Code).To(Equal(http.StatusMethodNotAllowed))
Expect(w.Header().Get("Allow")).To(Equal("GET, HEAD"))
Expect(decodeProblem(w).Code).To(Equal(ProblemCodeMethodNotAllowed))
})
DescribeTable("answers HEAD wherever GET is routed",
func(path, contentType string) {
w := serve(router, httptest.NewRequest(http.MethodHead, path, nil))
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Type")).To(Equal(contentType))
},
Entry("server info", "/api/v1/server", "application/json"),
Entry("JSON spec", "/api/v1/openapi.json", "application/json"),
Entry("YAML spec", "/api/v1/openapi.yaml", "application/yaml"),
)
It("revalidates HEAD requests with If-None-Match", func() {
etag := serve(router, httptest.NewRequest(http.MethodHead, "/api/v1/openapi.json", nil)).Header().Get("ETag")
req := httptest.NewRequest(http.MethodHead, "/api/v1/openapi.json", nil)
req.Header.Set("If-None-Match", etag)
Expect(serve(router, req).Code).To(Equal(http.StatusNotModified))
})
It("returns a 404 problem for HEAD on unknown paths", func() {
w := serve(router, httptest.NewRequest(http.MethodHead, "/api/v1/nope", nil))
Expect(w.Code).To(Equal(http.StatusNotFound))
Expect(w.Header().Get("Allow")).To(BeEmpty())
})
panicking := func(v any) http.Handler {
return problemRecoverer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic(v) }))
}
It("turns a handler panic into a 500 problem", func() {
w := httptest.NewRecorder()
panicking("kaboom").ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/boom", nil))
Expect(w.Code).To(Equal(http.StatusInternalServerError))
p := decodeProblem(w)
Expect(p.Code).To(Equal(ProblemCodeInternal))
Expect(p.Detail).To(BeNil())
})
It("re-panics http.ErrAbortHandler so the server can drop the connection", func() {
Expect(func() {
panicking(http.ErrAbortHandler).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/abort", nil))
}).To(PanicWith(http.ErrAbortHandler))
})
})

View file

@ -0,0 +1,66 @@
package apiv1
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/getkin/kin-openapi/routers"
"github.com/getkin/kin-openapi/routers/gorillamux"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestAPIv1(t *testing.T) {
tests.Init(t, false)
log.SetLevel(log.LevelFatal)
RegisterFailHandler(Fail)
RunSpecs(t, "API v1 Suite")
}
var specRouter routers.Router
var _ = BeforeSuite(func() {
doc, err := openapi3.NewLoader().LoadFromData(api.SpecJSON())
Expect(err).ToNot(HaveOccurred())
specRouter, err = gorillamux.NewRouter(doc)
Expect(err).ToNot(HaveOccurred())
})
// serve routes req through h mounted at /api/v1 and asserts the response conforms to the spec.
func serve(h http.Handler, req *http.Request) *httptest.ResponseRecorder {
root := chi.NewRouter()
root.Mount("/api/v1", h)
w := httptest.NewRecorder()
root.ServeHTTP(w, req)
validateAgainstSpec(req, w)
return w
}
func validateAgainstSpec(req *http.Request, w *httptest.ResponseRecorder) {
route, pathParams, err := specRouter.FindRoute(req)
if errors.Is(err, routers.ErrPathNotFound) || errors.Is(err, routers.ErrMethodNotAllowed) {
return
}
ExpectWithOffset(2, err).ToNot(HaveOccurred())
input := &openapi3filter.ResponseValidationInput{
RequestValidationInput: &openapi3filter.RequestValidationInput{
Request: req, PathParams: pathParams, Route: route,
},
Status: w.Code,
Header: w.Header(),
Body: io.NopCloser(bytes.NewReader(w.Body.Bytes())),
Options: &openapi3filter.Options{IncludeResponseStatus: true},
}
ExpectWithOffset(2, openapi3filter.ValidateResponse(req.Context(), input)).To(Succeed(),
"response for %s %s does not conform to the spec", req.Method, req.URL.Path)
}

View file

@ -0,0 +1,12 @@
package: apiv1
output: server/apiv1/api_gen.go
generate:
chi-server: true
strict-server: true
models: true
output-options:
exclude-operation-ids:
- getOpenAPISpecJSON
- getOpenAPISpecYAML
compatibility:
always-prefix-enum-values: true

72
server/apiv1/problem.go Normal file
View file

@ -0,0 +1,72 @@
package apiv1
import (
"encoding/json"
"errors"
"net/http"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
)
const problemContentType = "application/problem+json"
func writeProblem(w http.ResponseWriter, r *http.Request, err error) {
status, code := classifyError(err)
detail := err.Error()
if status == http.StatusInternalServerError {
log.Error(r.Context(), "API v1: unexpected error", "path", r.URL.Path, err)
detail = ""
}
writeProblemStatus(w, r, status, code, detail)
}
func classifyError(err error) (int, ProblemCode) {
switch {
case errors.Is(err, model.ErrNotFound):
return http.StatusNotFound, ProblemCodeNotFound
case errors.Is(err, model.ErrNotAuthorized):
return http.StatusForbidden, ProblemCodeForbidden
case errors.Is(err, model.ErrInvalidAuth), errors.Is(err, model.ErrExpired):
return http.StatusUnauthorized, ProblemCodeUnauthorized
case errors.Is(err, model.ErrValidation):
return http.StatusBadRequest, ProblemCodeValidation
case errors.Is(err, model.ErrNotAvailable):
return http.StatusServiceUnavailable, ProblemCodeUnavailable
}
return http.StatusInternalServerError, ProblemCodeInternal
}
func writeProblemStatus(w http.ResponseWriter, r *http.Request, status int, code ProblemCode, detail string, fieldErrors ...ValidationError) {
p := Problem{Title: http.StatusText(status), Status: status, Code: code}
if detail != "" {
p.Detail = &detail
}
if len(fieldErrors) > 0 {
p.Errors = &fieldErrors
}
w.Header().Set("Content-Type", problemContentType)
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(p); err != nil {
log.Warn(r.Context(), "API v1: could not write problem response", err)
}
}
func bindingErrorHandler(w http.ResponseWriter, r *http.Request, err error) {
var fieldErrors []ValidationError
var required *RequiredParamError
var invalid *InvalidParamFormatError
var tooMany *TooManyValuesForParamError
var unmarshal *UnmarshalingParamError
switch {
case errors.As(err, &required):
fieldErrors = append(fieldErrors, ValidationError{Field: required.ParamName, Message: "is required"})
case errors.As(err, &invalid):
fieldErrors = append(fieldErrors, ValidationError{Field: invalid.ParamName, Message: invalid.Err.Error()})
case errors.As(err, &tooMany):
fieldErrors = append(fieldErrors, ValidationError{Field: tooMany.ParamName, Message: "expected a single value"})
case errors.As(err, &unmarshal):
fieldErrors = append(fieldErrors, ValidationError{Field: unmarshal.ParamName, Message: unmarshal.Err.Error()})
}
writeProblemStatus(w, r, http.StatusBadRequest, ProblemCodeValidation, err.Error(), fieldErrors...)
}

View file

@ -0,0 +1,114 @@
package apiv1
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"github.com/navidrome/navidrome/model"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func decodeProblem(w *httptest.ResponseRecorder) Problem {
var p Problem
ExpectWithOffset(1, json.Unmarshal(w.Body.Bytes(), &p)).To(Succeed())
return p
}
var _ = Describe("problem", func() {
var w *httptest.ResponseRecorder
var r *http.Request
BeforeEach(func() {
w = httptest.NewRecorder()
r = httptest.NewRequest(http.MethodGet, "/api/v1/server", nil)
})
Describe("writeProblem", func() {
DescribeTable("maps domain errors to status and code",
func(err error, status int, code ProblemCode) {
writeProblem(w, r, err)
Expect(w.Code).To(Equal(status))
Expect(w.Header().Get("Content-Type")).To(Equal(problemContentType))
p := decodeProblem(w)
Expect(p.Status).To(Equal(status))
Expect(p.Code).To(Equal(code))
Expect(p.Title).To(Equal(http.StatusText(status)))
Expect(p.Type).To(BeNil())
Expect(w.Body.String()).ToNot(ContainSubstring(`"type"`))
},
Entry("not found", model.ErrNotFound, http.StatusNotFound, ProblemCodeNotFound),
Entry("not authorized", model.ErrNotAuthorized, http.StatusForbidden, ProblemCodeForbidden),
Entry("invalid auth", model.ErrInvalidAuth, http.StatusUnauthorized, ProblemCodeUnauthorized),
Entry("expired", model.ErrExpired, http.StatusUnauthorized, ProblemCodeUnauthorized),
Entry("validation", model.ErrValidation, http.StatusBadRequest, ProblemCodeValidation),
Entry("not available", model.ErrNotAvailable, http.StatusServiceUnavailable, ProblemCodeUnavailable),
Entry("unknown", errors.New("boom"), http.StatusInternalServerError, ProblemCodeInternal),
)
DescribeTable("keeps the wrapping context as detail for client errors",
func(err error) {
writeProblem(w, r, err)
p := decodeProblem(w)
Expect(p.Status).To(Equal(http.StatusNotFound))
Expect(p.Detail).ToNot(BeNil())
Expect(*p.Detail).To(ContainSubstring("album 123"))
},
Entry("fmt.Errorf %w", fmt.Errorf("album 123: %w", model.ErrNotFound)),
Entry("errors.Join", errors.Join(errors.New("album 123"), model.ErrNotFound)),
)
It("hides details for internal errors", func() {
writeProblem(w, r, errors.New("db password is hunter2"))
p := decodeProblem(w)
Expect(p.Detail).To(BeNil())
})
})
Describe("writeProblemStatus", func() {
It("writes field errors only when provided", func() {
writeProblemStatus(w, r, http.StatusBadRequest, ProblemCodeValidation, "bad input",
ValidationError{Field: "limit", Message: "must be <= 2000"})
p := decodeProblem(w)
Expect(p.Errors).ToNot(BeNil())
Expect(*p.Errors).To(HaveLen(1))
Expect((*p.Errors)[0].Field).To(Equal("limit"))
})
It("omits detail when empty", func() {
writeProblemStatus(w, r, http.StatusMethodNotAllowed, ProblemCodeMethodNotAllowed, "")
Expect(w.Body.String()).ToNot(ContainSubstring(`"detail"`))
Expect(w.Body.String()).ToNot(ContainSubstring(`"errors"`))
})
})
Describe("bindingErrorHandler", func() {
DescribeTable("maps parameter binding errors to a validation problem with the field",
func(err error, field, message string) {
bindingErrorHandler(w, r, err)
Expect(w.Code).To(Equal(http.StatusBadRequest))
p := decodeProblem(w)
Expect(p.Code).To(Equal(ProblemCodeValidation))
Expect(p.Errors).ToNot(BeNil())
Expect(*p.Errors).To(HaveLen(1))
Expect((*p.Errors)[0].Field).To(Equal(field))
Expect((*p.Errors)[0].Message).To(ContainSubstring(message))
},
Entry("required", &RequiredParamError{ParamName: "limit"}, "limit", "is required"),
Entry("invalid format", &InvalidParamFormatError{ParamName: "offset", Err: errors.New("not a number")}, "offset", "not a number"),
Entry("too many values", &TooManyValuesForParamError{ParamName: "sort", Count: 2}, "sort", "single value"),
Entry("unmarshaling", &UnmarshalingParamError{ParamName: "ids", Err: errors.New("bad json")}, "ids", "bad json"),
)
It("still returns a validation problem for unknown binding errors", func() {
bindingErrorHandler(w, r, errors.New("weird"))
p := decodeProblem(w)
Expect(p.Status).To(Equal(http.StatusBadRequest))
Expect(p.Code).To(Equal(ProblemCodeValidation))
Expect(p.Errors).To(BeNil())
})
})
})

View file

@ -0,0 +1,23 @@
package apiv1
import (
"context"
"fmt"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/consts"
)
func (rt *Router) GetServerInfo(ctx context.Context, _ GetServerInfoRequestObject) (GetServerInfoResponseObject, error) {
count, err := rt.ds.User().CountAll(ctx)
if err != nil {
return nil, fmt.Errorf("counting users: %w", err)
}
return GetServerInfo200JSONResponse{
Name: "Navidrome",
ServerVersion: consts.Version,
SpecVersion: api.SpecVersion(),
SetupRequired: count == 0,
LoginMethods: []ServerInfoLoginMethods{ServerInfoLoginMethodsPassword},
}, nil
}

View file

@ -0,0 +1,61 @@
package apiv1
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("GET /server", func() {
var ctx context.Context
var ds *tests.MockDataStore
var users *tests.MockedUserRepo
BeforeEach(func() {
ctx = GinkgoT().Context()
users = tests.CreateMockUserRepo()
ds = &tests.MockDataStore{MockedUser: users}
})
get := func() (*httptest.ResponseRecorder, ServerInfo) {
w := serve(New(ds), httptest.NewRequest(http.MethodGet, "/api/v1/server", nil))
var info ServerInfo
if w.Code == http.StatusOK {
ExpectWithOffset(1, json.Unmarshal(w.Body.Bytes(), &info)).To(Succeed())
}
return w, info
}
It("describes the server with setupRequired when there are no users", func() {
w, info := get()
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Type")).To(HavePrefix("application/json"))
Expect(info.Name).To(Equal("Navidrome"))
Expect(info.ServerVersion).To(Equal(consts.Version))
Expect(info.SpecVersion).To(Equal(api.SpecVersion()))
Expect(info.SetupRequired).To(BeTrue())
Expect(info.LoginMethods).To(ConsistOf(ServerInfoLoginMethodsPassword))
})
It("reports setupRequired=false once a user exists", func() {
Expect(users.Put(ctx, &model.User{ID: "u1", UserName: "admin", IsAdmin: true})).To(Succeed())
_, info := get()
Expect(info.SetupRequired).To(BeFalse())
})
It("returns a 500 problem when the user count fails", func() {
users.Error = errors.New("db down")
w, _ := get()
Expect(w.Code).To(Equal(http.StatusInternalServerError))
Expect(decodeProblem(w).Code).To(Equal(ProblemCodeInternal))
})
})

51
server/apiv1/spec.go Normal file
View file

@ -0,0 +1,51 @@
package apiv1
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"path"
"strconv"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/utils/req"
"github.com/zeebo/xxh3"
)
func specHandler(body []byte, contentType string) http.HandlerFunc {
etag := fmt.Sprintf("%016x", xxh3.Hash(body))
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("ETag", `"`+etag+`"`)
w.Header().Set("Cache-Control", "no-cache")
if req.IfNoneMatch(r, etag) {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}
}
// withBasePath adds BasePath to the advertised server URL, since only the running server knows it.
func withBasePath(body []byte, key string, quotedInBundle bool) []byte {
serverURL := path.Join(conf.Server.BasePath, consts.URLPathAPIv1)
if serverURL == consts.URLPathAPIv1 {
return body
}
oldURL := consts.URLPathAPIv1
if quotedInBundle {
oldURL = strconv.Quote(oldURL)
}
old := []byte(key + oldURL)
if bytes.Count(body, old) != 1 {
log.Error("API v1: server URL not found in the bundled spec, serving it without the base path", "key", key)
return body
}
// A JSON string is also a valid YAML double-quoted scalar, so one encoding escapes both formats.
newURL, _ := json.Marshal(serverURL)
return bytes.Replace(body, old, append([]byte(key), newURL...), 1)
}

136
server/apiv1/spec_test.go Normal file
View file

@ -0,0 +1,136 @@
package apiv1
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"github.com/navidrome/navidrome/api"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"gopkg.in/yaml.v3"
)
var _ = Describe("OpenAPI document routes", func() {
var router *Router
BeforeEach(func() {
router = New(&tests.MockDataStore{})
})
get := func(path string, headers map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
return serve(router, req)
}
DescribeTable("serves the embedded bundle",
func(path, contentType string, body []byte) {
w := get(path, nil)
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Type")).To(Equal(contentType))
Expect(w.Header().Get("ETag")).ToNot(BeEmpty())
Expect(w.Header().Get("Cache-Control")).To(Equal("no-cache"))
Expect(w.Body.Bytes()).To(Equal(body))
},
Entry("JSON", "/api/v1/openapi.json", "application/json", api.SpecJSON()),
Entry("YAML", "/api/v1/openapi.yaml", "application/yaml", api.SpecYAML()),
)
DescribeTable("revalidates with If-None-Match",
func(ifNoneMatch func(etag string) string, expected int) {
etag := get("/api/v1/openapi.json", nil).Header().Get("ETag")
w := get("/api/v1/openapi.json", map[string]string{"If-None-Match": ifNoneMatch(etag)})
Expect(w.Code).To(Equal(expected))
if expected == http.StatusNotModified {
Expect(w.Body.Len()).To(BeZero())
Expect(w.Header().Get("ETag")).To(Equal(etag))
} else {
Expect(w.Body.Bytes()).To(Equal(api.SpecJSON()))
}
},
Entry("exact ETag", func(etag string) string { return etag }, http.StatusNotModified),
Entry("ETag in a list", func(etag string) string { return `"other", ` + etag }, http.StatusNotModified),
Entry("weak ETag", func(etag string) string { return "W/" + etag }, http.StatusNotModified),
Entry("wildcard", func(string) string { return "*" }, http.StatusNotModified),
Entry("stale ETag", func(string) string { return `"stale"` }, http.StatusOK),
)
It("ignores Range and returns the full document", func() {
w := get("/api/v1/openapi.json", map[string]string{"Range": "bytes=0-9"})
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Accept-Ranges")).To(BeEmpty())
Expect(w.Body.Bytes()).To(Equal(api.SpecJSON()))
})
It("uses different ETags for JSON and YAML", func() {
j := get("/api/v1/openapi.json", nil)
y := get("/api/v1/openapi.yaml", nil)
Expect(j.Header().Get("ETag")).ToNot(Equal(y.Header().Get("ETag")))
})
Describe("with a base path", func() {
decode := func(format string, body []byte) map[string]any {
var doc map[string]any
if format == "json" {
ExpectWithOffset(1, json.Unmarshal(body, &doc)).To(Succeed())
} else {
ExpectWithOffset(1, yaml.Unmarshal(body, &doc)).To(Succeed())
}
return doc
}
serverURL := func(doc map[string]any) any {
return doc["servers"].([]any)[0].(map[string]any)["url"]
}
var plainETag string
BeforeEach(func() {
plainETag = get("/api/v1/openapi.json", nil).Header().Get("ETag")
DeferCleanup(configtest.SetupConfig())
conf.Server.BasePath = "/music"
router = New(&tests.MockDataStore{})
})
DescribeTable("advertises the server under the base path and changes nothing else",
func(path, format string, bundle []byte) {
w := get(path, nil)
Expect(w.Code).To(Equal(http.StatusOK))
served, original := decode(format, w.Body.Bytes()), decode(format, bundle)
Expect(serverURL(served)).To(Equal("/music/api/v1"))
delete(served, "servers")
delete(original, "servers")
Expect(served).To(Equal(original))
},
Entry("JSON", "/api/v1/openapi.json", "json", api.SpecJSON()),
Entry("YAML", "/api/v1/openapi.yaml", "yaml", api.SpecYAML()),
)
It("uses its own ETag, and still revalidates", func() {
etag := get("/api/v1/openapi.json", nil).Header().Get("ETag")
Expect(etag).ToNot(Equal(plainETag))
Expect(get("/api/v1/openapi.json", map[string]string{"If-None-Match": etag}).Code).To(Equal(http.StatusNotModified))
})
It("escapes base paths that need quoting", func() {
conf.Server.BasePath = "/my music: \"live\""
router = New(&tests.MockDataStore{})
Expect(serverURL(decode("json", get("/api/v1/openapi.json", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1"))
Expect(serverURL(decode("yaml", get("/api/v1/openapi.yaml", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1"))
})
})
DescribeTable("the bundle advertises the API path exactly once, which the base-path rewrite relies on",
func(bundle []byte) {
Expect(bytes.Count(bundle, []byte(consts.URLPathAPIv1))).To(Equal(1))
},
Entry("JSON", api.SpecJSON()),
Entry("YAML", api.SpecYAML()),
)
})

View file

@ -49,7 +49,7 @@ func login(ds model.DataStore) func(w http.ResponseWriter, r *http.Request) {
}
func doLogin(ds model.DataStore, username string, password string, w http.ResponseWriter, r *http.Request) {
user, err := validateLogin(ds.User(r.Context()), username, password)
user, err := validateLogin(r.Context(), ds.User(), username, password)
if err != nil {
_ = rest.RespondWithError(w, http.StatusInternalServerError, "Unknown error authentication user. Please try again")
return
@ -127,7 +127,7 @@ func createAdmin(ds model.DataStore) func(w http.ResponseWriter, r *http.Request
_ = rest.RespondWithError(w, http.StatusUnprocessableEntity, err.Error())
return
}
c, err := ds.User(r.Context()).CountAll()
c, err := ds.User().CountAll(r.Context())
if err != nil {
_ = rest.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
@ -157,16 +157,16 @@ func createAdminUser(ctx context.Context, ds model.DataStore, username, password
IsAdmin: true,
LastLoginAt: new(time.Now()),
}
err := ds.User(ctx).Put(&initialUser)
err := ds.User().Put(ctx, &initialUser)
if err != nil {
log.Error(ctx, "Could not create initial user", "user", initialUser, err)
log.Error(ctx, "Could not create initial user", "user", initialUser.UserName, err)
return fmt.Errorf("creating initial user: %w", err)
}
return nil
}
func validateLogin(userRepo model.UserRepository, userName, password string) (*model.User, error) {
u, err := userRepo.FindByUsernameWithPassword(userName)
func validateLogin(ctx context.Context, userRepo model.UserRepository, userName, password string) (*model.User, error) {
u, err := userRepo.FindByUsernameWithPassword(ctx, userName)
if errors.Is(err, model.ErrNotFound) {
return nil, nil
}
@ -176,9 +176,9 @@ func validateLogin(userRepo model.UserRepository, userName, password string) (*m
if u.Password != password {
return nil, nil
}
err = userRepo.UpdateLastLoginAt(u.ID)
err = userRepo.UpdateLastLoginAt(ctx, u.ID)
if err != nil {
log.Error("Could not update LastLoginAt", "user", userName)
log.Error(ctx, "Could not update LastLoginAt", "user", userName)
}
return u, nil
}
@ -244,7 +244,7 @@ func UsernameFromConfig(*http.Request) string {
}
func contextWithUser(ctx context.Context, ds model.DataStore, username string) (context.Context, error) {
user, err := ds.User(ctx).FindByUsername(username)
user, err := ds.User().FindByUsername(ctx, username)
if err == nil {
ctx = log.NewContext(ctx, "username", username)
ctx = request.WithUsername(ctx, user.UserName)
@ -309,7 +309,7 @@ func tokenAllowed(ctx context.Context) bool {
// epoch the handler bumped reaches the token the client stores.
type refreshingWriter struct {
http.ResponseWriter
ctx context.Context
ctx context.Context //nolint:containedctx // ResponseWriter wrapper defers work to Write, which has no ctx
token jwt.Token
once sync.Once
}
@ -377,12 +377,13 @@ func handleLoginFromHeaders(ds model.DataStore, r *http.Request) map[string]any
}
}
userRepo := ds.User(r.Context())
user, err := userRepo.FindByUsernameWithPassword(username)
ctx := r.Context()
userRepo := ds.User()
user, err := userRepo.FindByUsernameWithPassword(ctx, username)
if user == nil || err != nil {
log.Info(r, "User passed in header not found", "user", username)
// Check if this is the first user being created
count, _ := userRepo.CountAll()
count, _ := userRepo.CountAll(ctx)
isFirstUser := count == 0
newUser := model.User{
@ -393,19 +394,19 @@ func handleLoginFromHeaders(ds model.DataStore, r *http.Request) map[string]any
NewPassword: consts.PasswordAutogenPrefix + id.NewRandom(),
IsAdmin: isFirstUser, // Make the first user an admin
}
err := userRepo.Put(&newUser)
err := userRepo.Put(ctx, &newUser)
if err != nil {
log.Error(r, "Could not create new user", "user", username, err)
return nil
}
user, err = userRepo.FindByUsernameWithPassword(username)
user, err = userRepo.FindByUsernameWithPassword(ctx, username)
if user == nil || err != nil {
log.Error(r, "Created user but failed to fetch it", "user", username)
return nil
}
}
err = userRepo.UpdateLastLoginAt(user.ID)
err = userRepo.UpdateLastLoginAt(ctx, user.ID)
if err != nil {
log.Error(r, "Could not update LastLoginAt", "user", username, err)
return nil

View file

@ -28,6 +28,12 @@ import (
)
var _ = Describe("Auth", func() {
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
})
Describe("User login", func() {
var ds model.DataStore
var req *http.Request
@ -48,8 +54,8 @@ var _ = Describe("Auth", func() {
})
It("creates an admin user with the specified password", func() {
usr := ds.User(context.Background())
u, err := usr.FindByUsername("johndoe")
usr := ds.User()
u, err := usr.FindByUsername(ctx, "johndoe")
Expect(err).To(BeNil())
Expect(u.Password).ToNot(BeEmpty())
Expect(u.IsAdmin).To(BeTrue())
@ -76,6 +82,18 @@ var _ = Describe("Auth", func() {
})
})
Describe("createAdmin when the user cannot be stored", func() {
It("responds 500 rather than falling through to login", func() {
failing := dsWithFailingPut(errors.New("db is down"))
req = httptest.NewRequest("POST", "/createAdmin", strings.NewReader(`{"username":"johndoe", "password":"secret"}`))
resp = httptest.NewRecorder()
createAdmin(failing)(resp, req)
Expect(resp.Code).To(Equal(http.StatusInternalServerError))
})
})
Describe("Login from HTTP headers", func() {
const (
trustedIpv4 = "192.168.0.42"
@ -87,8 +105,8 @@ var _ = Describe("Auth", func() {
fs := os.DirFS("tests/fixtures")
BeforeEach(func() {
usr := ds.User(context.Background())
_ = usr.Put(&model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})
usr := ds.User()
_ = usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})
req = httptest.NewRequest("GET", "/index.html", nil)
req.Header.Add("Remote-User", "janedoe")
resp = httptest.NewRecorder()
@ -220,8 +238,8 @@ var _ = Describe("Auth", func() {
})
It("logs in successfully if user exists", func() {
usr := ds.User(context.Background())
_ = usr.Put(&model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})
usr := ds.User()
_ = usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})
login(ds)(resp, req)
Expect(resp.Code).To(Equal(http.StatusOK))
@ -385,14 +403,14 @@ var _ = Describe("Auth", func() {
Expect(result["isAdmin"]).To(BeTrue())
// Verify user was created as admin
u, err := ds.User(context.Background()).FindByUsername("firstuser")
u, err := ds.User().FindByUsername(ctx, "firstuser")
Expect(err).To(BeNil())
Expect(u.IsAdmin).To(BeTrue())
})
It("does not make subsequent users admins", func() {
// Create the first user
_ = ds.User(context.Background()).Put(&model.User{
_ = ds.User().Put(ctx, &model.User{
ID: "existing-user-id",
UserName: "existinguser",
Name: "Existing User",
@ -407,7 +425,7 @@ var _ = Describe("Auth", func() {
Expect(result["isAdmin"]).To(BeFalse())
// Verify user was created as non-admin
u, err := ds.User(context.Background()).FindByUsername("seconduser")
u, err := ds.User().FindByUsername(ctx, "seconduser")
Expect(err).To(BeNil())
Expect(u.IsAdmin).To(BeFalse())
})
@ -422,9 +440,9 @@ var _ = Describe("Auth", func() {
conf.Server.SessionTimeout = time.Hour
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.TODO()).(*tests.MockedUserRepo)
ur := ds.User().(*tests.MockedUserRepo)
usr = &model.User{ID: "u1", UserName: "johndoe", NewPassword: "pw", TokenEpoch: 2}
Expect(ur.Put(usr)).To(Succeed())
Expect(ur.Put(ctx, usr)).To(Succeed())
})
serve := func(token string) *httptest.ResponseRecorder {

View file

@ -34,7 +34,7 @@ type (
id uint64
event string
data string
senderCtx context.Context
senderCtx context.Context //nolint:containedctx // queued message carries the sender ctx
}
messageChan chan message
clientsChan chan client

View file

@ -4,9 +4,9 @@ package imghttp
import (
"net/http"
"strings"
"github.com/navidrome/navidrome/core/artwork"
"github.com/navidrome/navidrome/utils/req"
)
// WriteImageHeaders applies the artwork caching contract and reports whether a 304 was written
@ -40,28 +40,9 @@ func WriteImageHeaders(w http.ResponseWriter, r *http.Request, img *artwork.Imag
h.Set("Cache-Control", "public, no-cache")
}
if etag != "" && ifNoneMatch(r.Header.Get("If-None-Match"), etag) {
if etag != "" && req.IfNoneMatch(r, etag) {
w.WriteHeader(http.StatusNotModified)
return true
}
return false
}
// ifNoneMatch reports whether If-None-Match asserts hash, using RFC 9110 weak comparison.
func ifNoneMatch(header, hash string) bool {
header = strings.TrimSpace(header)
if header == "" {
return false
}
if header == "*" {
return true
}
for tag := range strings.SplitSeq(header, ",") {
tag = strings.TrimSpace(tag)
tag = strings.TrimPrefix(tag, "W/")
if strings.Trim(tag, `"`) == hash {
return true
}
}
return false
}

View file

@ -16,34 +16,37 @@ import (
func initialSetup(ds model.DataStore) {
ctx := context.TODO()
_ = ds.WithTx(func(tx model.DataStore) error {
if err := tx.Library(ctx).StoreMusicFolder(); err != nil {
err := ds.WithTx(func(tx model.DataStore) error {
if err := tx.Library().StoreMusicFolder(ctx); err != nil {
return err
}
properties := tx.Property(ctx)
_, err := properties.Get(consts.InitialSetupFlagKey)
properties := tx.Property()
_, err := properties.Get(ctx, consts.InitialSetupFlagKey)
if err == nil {
return nil
}
log.Info("Running initial setup")
if conf.Server.DevAutoCreateAdminPassword != "" {
if err = createInitialAdminUser(tx, conf.Server.DevAutoCreateAdminPassword); err != nil {
if err = createInitialAdminUser(ctx, tx, conf.Server.DevAutoCreateAdminPassword); err != nil {
return err
}
}
err = properties.Put(consts.InitialSetupFlagKey, time.Now().String())
err = properties.Put(ctx, consts.InitialSetupFlagKey, time.Now().String())
return err
}, "initial setup")
if err != nil {
log.Fatal("Error running initial setup", err)
}
}
// If the Dev Admin user is not present, create it
func createInitialAdminUser(ds model.DataStore, initialPassword string) error {
users := ds.User(context.TODO())
c, err := users.CountAll(model.QueryOptions{Filters: squirrel.Eq{"user_name": consts.DevInitialUserName}})
func createInitialAdminUser(ctx context.Context, ds model.DataStore, initialPassword string) error {
users := ds.User()
c, err := users.CountAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"user_name": consts.DevInitialUserName}})
if err != nil {
panic(fmt.Sprintf("Could not access User table: %s", err))
return fmt.Errorf("could not access User table: %w", err)
}
if c == 0 {
newID := id.NewRandom()
@ -57,12 +60,11 @@ func createInitialAdminUser(ds model.DataStore, initialPassword string) error {
NewPassword: initialPassword,
IsAdmin: true,
}
err := users.Put(&initialUser)
if err != nil {
log.Error("Could not create initial admin user", "user", initialUser, err)
if err := users.Put(ctx, &initialUser); err != nil {
return fmt.Errorf("could not create initial admin user: %w", err)
}
}
return err
return nil
}
func checkFFmpegInstallation() {
@ -70,10 +72,6 @@ func checkFFmpegInstallation() {
_, err := f.CmdPath()
if err != nil {
log.Warn("Unable to find ffmpeg. Transcoding will fail if used", err)
if conf.Server.Scanner.Extractor == "ffmpeg" {
log.Warn("ffmpeg cannot be used for metadata extraction. Falling back to taglib")
conf.Server.Scanner.Extractor = "taglib"
}
return
}
if !f.IsProbeAvailable() {

View file

@ -2,6 +2,7 @@ package server
import (
"context"
"errors"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
@ -9,28 +10,52 @@ import (
. "github.com/onsi/gomega"
)
type failingPutUserRepo struct {
model.UserRepository
err error
}
func (r *failingPutUserRepo) Put(context.Context, *model.User) error { return r.err }
func dsWithFailingPut(err error) model.DataStore {
return &tests.MockDataStore{MockedUser: &failingPutUserRepo{UserRepository: tests.CreateMockUserRepo(), err: err}}
}
var _ = Describe("initial_setup", func() {
var ds model.DataStore
var ctx context.Context
BeforeEach(func() {
ds = &tests.MockDataStore{}
ctx = GinkgoT().Context()
})
Describe("createInitialAdminUser", func() {
It("creates a new admin user with specified password if User table is empty", func() {
Expect(createInitialAdminUser(ds, "pass123")).To(BeNil())
ur := ds.User(context.TODO())
admin, err := ur.FindByUsername("admin")
Expect(createInitialAdminUser(ctx, ds, "pass123")).To(BeNil())
ur := ds.User()
admin, err := ur.FindByUsername(ctx, "admin")
Expect(err).To(BeNil())
Expect(admin.Password).To(Equal("pass123"))
})
It("does not create a new admin user if User table is not empty", func() {
Expect(createInitialAdminUser(ds, "first")).To(BeNil())
ur := ds.User(context.TODO())
Expect(ur.CountAll()).To(Equal(int64(1)))
Expect(createInitialAdminUser(ds, "second")).To(BeNil())
Expect(ur.CountAll()).To(Equal(int64(1)))
Expect(createInitialAdminUser(ctx, ds, "first")).To(BeNil())
ur := ds.User()
Expect(ur.CountAll(ctx)).To(Equal(int64(1)))
Expect(createInitialAdminUser(ctx, ds, "second")).To(BeNil())
Expect(ur.CountAll(ctx)).To(Equal(int64(1)))
})
It("returns the error when the user cannot be stored", func() {
boom := errors.New("db is down")
Expect(createInitialAdminUser(ctx, dsWithFailingPut(boom), "pass123")).To(MatchError(boom))
})
It("returns the error when the user table cannot be read", func() {
boom := errors.New("db is down")
ds = &tests.MockDataStore{MockedUser: &tests.MockedUserRepo{Error: boom}}
Expect(createInitialAdminUser(ctx, ds, "pass123")).To(MatchError(boom))
})
})
})

View file

@ -40,6 +40,7 @@ ND_JELLYFIN_SERVERNAME="My Music Server"
ND_JELLYFIN_EXPOSEDPUBLICUSERS="alice,bob"
ND_JELLYFIN_AUTODISCOVERY=true
ND_JELLYFIN_QUICKCONNECT=false
ND_JELLYFIN_MAXCONCURRENTSTREAMS=4
```
Once enabled, the API is mounted at:
@ -140,8 +141,10 @@ Jellyfin has no native concept of multiple music libraries the way Navidrome doe
Navidrome library the current user can access is exposed as its own top-level Jellyfin
"CollectionFolder" view (`GET /UserViews`), instead of merging every library into a single view.
Browsing (`/Items`), artists, and the "Latest" list are all scoped to the libraries the
authenticated user has access to; a library (or item within it) the user cannot access returns
`404`, never `403`, so ids can't be used as an existence oracle.
authenticated user has access to. Fetching an item the user cannot access returns `404`, never
`403`, so ids can't be used as an existence oracle. An inaccessible library id sent as `ParentId`
is not a `404`: it is simply not treated as a library, so none of that library's content is
returned.
### Browsing filters
@ -152,7 +155,7 @@ tracks — Finamp's artist screen sends these *alongside* `ParentId=<libraryId>`
album's tracks — Feishin fetches them this way instead of `ParentId`); `GenreIds` (a
genre's albums or tracks — Finamp's genre screen sends it the same way; `/Artists/AlbumArtists`
and `MusicArtist` queries accept it too, matching artists credited on an album of that genre);
`SearchTerm`;
`Years`; `StudioIds` (record labels, as listed by `GET Studios`); `SearchTerm`;
`Filters` (`IsFavorite`, `IsFavoriteOrLikes`, `IsPlayed`, `IsUnplayed`) and the standalone
`isFavorite`/`isPlayed` booleans it can also be expressed as — `Filters` wins when both are sent, as
in Jellyfin; `Likes`, `Dislikes`, `IsFolder`, `IsNotFolder` and `IsResumable` have no Navidrome
@ -169,9 +172,9 @@ returns direct children only (no tracks — no track is a library's direct child
| Quick Connect | `GET QuickConnect/Enabled`, `POST QuickConnect/Initiate`, `GET QuickConnect/Connect`, `POST QuickConnect/Authorize` (authenticated), `POST Users/AuthenticateWithQuickConnect` |
| Auth | `POST Users/AuthenticateByName`, `GET Users/Public` |
| Users | `GET UserViews`, `GET Users/{userId}/Views`, `GET Users/Me`, `GET Users/{userId}` |
| Browsing | `GET Items`, `GET Users/{userId}/Items`, `GET Items/{itemId}`, `GET Users/{userId}/Items/{itemId}`, `GET Users/{userId}/Items/Latest`, `DELETE Items/{itemId}` (playlists only) |
| Artists / genres | `GET Artists`, `GET Artists/AlbumArtists`, `GET Genres`, `GET MusicGenres` |
| Similar / mixes | `GET Artists/{itemId}/Similar`, `GET Items/{itemId}/Similar`, `GET {Items,Songs,Albums,Artists,Playlists}/{itemId}/InstantMix`, `GET Artists/InstantMix?id=`, `GET MusicGenres/InstantMix?id=` |
| Browsing | `GET Items`, `GET Users/{userId}/Items`, `GET Items/{itemId}`, `GET Users/{userId}/Items/{itemId}`, `GET Items/Latest`, `GET Users/{userId}/Items/Latest`, `DELETE Items/{itemId}` (playlists only) |
| Artists / genres / labels | `GET Artists`, `GET Artists/AlbumArtists`, `GET Genres`, `GET MusicGenres`, `GET Studios`, `GET Items/Filters` |
| Similar / mixes | `GET Artists/{itemId}/Similar`, `GET Items/{itemId}/Similar`, `GET Albums/{itemId}/Similar`, `GET {Items,Songs,Albums,Artists,Playlists}/{itemId}/InstantMix`, `GET Artists/InstantMix?id=`, `GET MusicGenres/InstantMix?id=` |
| Images | `GET Items/{itemId}/Images/{type}[/{index}]` (public), `POST`/`DELETE Items/{itemId}/Images/{type}` (playlist cover, authenticated) |
| Favorites / ratings for songs, albums, artists, and playlists | `POST`/`DELETE UserFavoriteItems/{itemId}`, `POST`/`DELETE Users/{userId}/FavoriteItems/{itemId}`, `POST`/`DELETE Users/{userId}/Items/{itemId}/Rating`, `GET UserItems/{itemId}/UserData`, `GET Users/{userId}/Items/{itemId}/UserData` |
| Streaming | `GET Audio/{itemId}/stream[.{container}]`, `GET Audio/{itemId}/universal`, `GET Audio/{itemId}/main.m3u8`, `GET Items/{itemId}/File`, `GET Items/{itemId}/Download`, `GET`/`POST Items/{itemId}/PlaybackInfo` (`HEAD` too on stream, universal, File, Download and images; a transcode HEAD answers without starting it) |
@ -267,6 +270,22 @@ The stream endpoints reuse the same transcode-decision pipeline as the Subsonic
Subsonic. `File`/`Download` stay raw. For HLS clients, force `aac` or `mp3`; other formats are
advertised and served but packed-audio players won't decode them.
## Lyrics
`GET Audio/{id}/Lyrics` serves the main lyric track as a `LyricDto` (`Start` in 100ns ticks,
word-level `Cues` when present), resolved through the full `core/lyrics` pipeline (embedded, `.lrc`
sidecars, plugins per `LyricsPriority`). No lyrics returns `404`, never an empty `200`.
Results, misses included, are cached for 5 minutes: Jellify fetches lyrics for every played track and
Feishin on every song change, so lyric-less tracks are the hot path. Concurrent misses on the same
track share one pipeline run. That run is detached from the request, so a cancelled request doesn't
fail it for other waiters, and its context has a one-minute deadline.
Finamp opens its lyrics view only when the track has a `Lyric` `MediaStream` (`HasLyrics` is just a
list badge). Browse lists set both from embedded lyrics only. `PlaybackInfo` runs the full pipeline
per track, so sidecar and plugin lyrics show up there. Feishin also requires server version ≥ 10.9
(we advertise 12.1.0).
## AudioMuse-AI compatible endpoints
Compatibility shim for Jellyfin front-ends that integrate [AudioMuse-AI](https://github.com/NeptuneHub/audiomuse-ai-plugin)
@ -356,8 +375,9 @@ curl -s -X DELETE "${AUTH[@]}" "$BASE/Items/$PLAYLIST_ID"
Handler-level unit tests live alongside each file (`*_test.go`). A full end-to-end suite in
[`e2e/`](e2e) exercises every endpoint through the real router against a real SQLite database and
real repositories (only artwork/streaming/ffmpeg are stubbed), with per-`Describe` snapshot
isolation — mirroring the Subsonic `server/subsonic/e2e` suite. Run it with:
real repositories (only artwork, streaming, ffmpeg, external metadata agents and sonic similarity
are stubbed), with per-`Describe` snapshot isolation — mirroring the Subsonic `server/subsonic/e2e`
suite. Run it with:
```bash
make test PKG=./server/jellyfin/...
@ -365,42 +385,37 @@ make test PKG=./server/jellyfin/...
## Known limitations
- **Genres are global.** `GET Genres`/`MusicGenres` is not scoped to the current user's
libraries (genre tags aren't per-library entities in Navidrome's model).
- **Artist item-access relies on list-time scoping.** Unlike albums and songs (which each
belong to exactly one library and are checked against `user.HasLibraryAccess` on every
fetch), an artist can have content across multiple libraries via `library_artist`, so there's
no single library id to gate a direct `GET Items/{artistId}` or favorite/rating call against.
Access control for artists is enforced by scoping the `Artists`/`Items?IncludeItemTypes=MusicArtist`
*list* to the user's libraries, plus the persistence layer's own defense-in-depth; a client
that already has an artist id from elsewhere is not re-checked against library membership.
- **Blurhashes are synthetic, not computed from the artwork (follow-up).** `ImageBlurHashes` is
populated by `dto/blurhash.go`, which derives a well-formed **1-component (solid color)**
blurhash by hashing the item id — it never looks at the actual image. Real Jellyfin computes a
multi-component blurhash from the cover's pixels (downscaled to 128×128) once at scan time and
stores it per image, so its placeholder approximates the art. Ours satisfies the protocol
(Finamp gets a valid value to use as a de-dup key and a placeholder, no missing-blurhash
warning) but renders as a flat color while art loads. A proper implementation would compute the
real blurhash in the `core/artwork` pipeline (where the image is already decoded), cache it
keyed like the artwork, and have the mappers read it — keeping the synthetic value as a fallback
for art that hasn't been rendered yet.
- **The WebSocket only keep-alives; it pushes no events (follow-up).** `GET socket` sends a
`ForceKeepAlive` and answers `KeepAlive` pings so real-time clients (Finamp) settle into a
working session instead of 404-loop-reconnecting, but it never pushes anything. A follow-up
would broadcast real session/playstate and library-change events over it (via `server/events`),
mirroring Jellyfin's session messages.
- **Lyrics.** `GET Audio/{id}/Lyrics` serves the main lyric track as a `LyricDto` (`Start` in
100ns ticks, word-level `Cues` when present), resolved through the full `core/lyrics` pipeline
(embedded, `.lrc` sidecars, plugins per `LyricsPriority`) behind a 5-minute TTL cache that also
caches misses — Jellify fetches for every played track, Feishin per song change, so lyric-less
tracks are the hot path. No lyrics → 404 (never an empty 200), which all three clients degrade
gracefully. Finamp gates its lyrics view on a `Lyric` `MediaStream` (not `HasLyrics`, which is
just a list badge): browse lists advertise it from embedded lyrics only (the `"[]"` sentinel
check — the column is never `""` post-scan), while `PlaybackInfo` runs the full pipeline per
track so sidecar/plugin lyrics also light up. Feishin additionally requires server version
≥ 10.9 (`jellyfinVersion` advertises 12.1.0).
Concurrent misses on the same track share one pipeline invocation (`SimpleCache.GetWithLoader`
is singleflighted), and the load runs detached from the request context with a one-minute bound,
so a cancelled request or hung plugin can't fail or pin the load for other waiters.
Follow-up: tracks whose only lyrics are sidecar/plugin-sourced show no `HasLyrics` badge in
lists (request-time sources can't be known at list time without per-row I/O).
- **Genre lists ignore `ParentId`.** `GET Genres`/`MusicGenres` and
`Items?IncludeItemTypes=MusicGenre` list the genres of every library the user can access, never
only the `ParentId` library. `Items?IncludeItemTypes=MusicGenre` also ignores `SearchTerm`.
`GET Items/Filters` is the exception: its genres follow `ParentId`.
- **Search skips some filters.** With `SearchTerm`, `Filters=IsFavorite`, `IsPlayed`, `IsUnplayed`
and `isFavorite`/`isPlayed` are skipped, so the response holds every search match. The full-text
search's first phase has no annotation join to filter on. Artist searches also skip the role (album
artist vs. artist) and `GenreIds`. Playlist lists ignore `SearchTerm`.
- **Search pages are capped at 2,000 items.** A larger `Limit` is lowered to 2,000. Jellyfin has no
cap.
- **One-character searches return nothing.** The shared search layer ignores terms shorter than two
characters, so album, artist and song searches for `a` come back empty. Real Jellyfin has no
minimum.
- **Playlist entry ids are positions, not song ids.** `PlaylistItemId` encodes the entry's position
in the playlist, so ids change when entries are inserted or removed; re-read the list after an
edit. Real Jellyfin uses the song id. Clients that echo `PlaylistItemId` back (Finamp) work;
clients that send the song id as `EntryIds` or to `Move` (Jellify) get `404`.
- **Rating uses the `rating` param.** `POST Users/{userId}/Items/{itemId}/Rating` reads a `rating`
(0-10) and stores it as 0-5 stars. Jellyfin's `likes` boolean is not read, so a client that sends
only `likes` clears the rating.
- **Missing endpoints.** `UserPlayedItems` (mark played/unplayed), `Search/Hints` and the non-legacy
`UserItems/{itemId}/Rating` are not implemented. Play counts only change through playback
reporting.
- **Some `Fields` are never emitted.** `ProviderIds`, `People`, `Etag` and `DateLastMediaAdded` are
accepted but never returned.
- **Blurhashes can be missing.** `ImageBlurHashes` carries the real blurhash that the artwork
pipeline computes and stores. Until that happens for an item, the field is omitted: a fake value
would pin the wrong placeholder in clients that key their image cache on it.
- **The WebSocket only keeps alive; it pushes no events.** `GET socket` sends `ForceKeepAlive` and
answers `KeepAlive` pings, so real-time clients (Finamp) keep a working session instead of
reconnecting in a loop. It never pushes session, playstate or library-change events.
- **List lyric badges only see embedded lyrics.** Tracks with only sidecar or plugin lyrics show no
`HasLyrics` badge in lists, because those sources can't be known at list time without per-row I/O.
`PlaybackInfo` and `Audio/{id}/Lyrics` still find them (see "Lyrics").

View file

@ -28,16 +28,16 @@ func (api *Router) resolveAnnotated(w http.ResponseWriter, r *http.Request, id s
switch e := entity.(type) {
case *model.Album:
if u.HasLibraryAccess(e.LibraryID) {
return api.ds.Album(ctx), "album"
return api.ds.Album(), "album"
}
case *model.Artist:
return api.ds.Artist(ctx), "artist"
return api.ds.Artist(), "artist"
case *model.MediaFile:
if u.HasLibraryAccess(e.LibraryID) {
return api.ds.MediaFile(ctx), "song"
return api.ds.MediaFile(), "song"
}
case *model.Playlist:
return api.ds.Playlist(ctx), "playlist"
return api.ds.Playlist(), "playlist"
}
// Unknown ids, inaccessible-library items and non-annotatable entities (radios) all read as absent.
http.Error(w, "Not Found", http.StatusNotFound)
@ -74,7 +74,7 @@ func (api *Router) setFavorite(w http.ResponseWriter, r *http.Request, starred b
if repo == nil {
return
}
if err := repo.SetStar(starred, id); err != nil {
if err := repo.SetStar(r.Context(), starred, id); err != nil {
api.internalError(w, r, err)
return
}
@ -97,7 +97,7 @@ func (api *Router) setItemRating(w http.ResponseWriter, r *http.Request, rating
if repo == nil {
return
}
if err := repo.SetRating(rating, id); err != nil {
if err := repo.SetRating(r.Context(), rating, id); err != nil {
api.internalError(w, r, err)
return
}

View file

@ -32,7 +32,7 @@ var _ = Describe("Annotations", func() {
Describe("markFavorite / unmarkFavorite", func() {
It("stars a song and returns IsFavorite=true", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser())
@ -46,7 +46,7 @@ var _ = Describe("Annotations", func() {
})
It("stars an album and returns IsFavorite=true", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser())
@ -60,7 +60,7 @@ var _ = Describe("Annotations", func() {
})
It("stars an artist without checking library access (artists span multiple libraries)", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
// alice only has access to library 1, but artists aren't gated per-library.
@ -75,7 +75,7 @@ var _ = Describe("Annotations", func() {
})
It("stars a visible playlist", func() {
playlistRepo := ds.Playlist(context.Background()).(*tests.MockPlaylistRepo)
playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo)
playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "Mix", OwnerID: testID("u1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("p1")), nil).WithContext(ctxUser())
@ -86,7 +86,7 @@ var _ = Describe("Annotations", func() {
})
It("unstars a song and returns IsFavorite=false", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Annotations: model.Annotations{Starred: true}}})
w := httptest.NewRecorder()
r := httptest.NewRequest("DELETE", "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser())
@ -100,7 +100,7 @@ var _ = Describe("Annotations", func() {
})
It("returns 404 and does not star an album in a library the user can't access", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) // only has access to library 1
@ -111,7 +111,7 @@ var _ = Describe("Annotations", func() {
})
It("returns 404 and does not star a song in a library the user can't access", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser()) // only has access to library 1
@ -130,7 +130,7 @@ var _ = Describe("Annotations", func() {
})
It("returns 500 (not 404) when a repository lookup fails for a reason other than not-found", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetError(true)
ds.Album().(*tests.MockAlbumRepo).SetError(true)
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/x1", nil).WithContext(ctxUser())
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("x1")))
@ -139,7 +139,7 @@ var _ = Describe("Annotations", func() {
})
It("emits a refreshResource event when starring a song", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser())
@ -150,7 +150,7 @@ var _ = Describe("Annotations", func() {
})
It("emits a refreshResource event when starring an album", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser())
@ -161,7 +161,7 @@ var _ = Describe("Annotations", func() {
})
It("does not emit an event when the item is not accessible", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser())
@ -174,7 +174,7 @@ var _ = Describe("Annotations", func() {
Describe("setRating / removeRating", func() {
It("maps a Jellyfin 0-10 rating to Navidrome's 0-5 scale", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=8", nil).WithContext(ctxUser())
@ -189,7 +189,7 @@ var _ = Describe("Annotations", func() {
})
It("rates an album", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/"+dto.EncodeID(testID("a1"))+"/Rating?Rating=10", nil).WithContext(ctxUser())
@ -200,7 +200,7 @@ var _ = Describe("Annotations", func() {
})
It("rates a visible playlist", func() {
playlistRepo := ds.Playlist(context.Background()).(*tests.MockPlaylistRepo)
playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo)
playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "Mix", OwnerID: testID("u1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/"+dto.EncodeID(testID("p1"))+"/Rating?Rating=8", nil).WithContext(ctxUser())
@ -211,7 +211,7 @@ var _ = Describe("Annotations", func() {
})
It("removes a rating", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Annotations: model.Annotations{Rating: 4}}})
w := httptest.NewRecorder()
r := httptest.NewRequest("DELETE", "/Users/u1/Items/s1/Rating", nil).WithContext(ctxUser())
@ -225,7 +225,7 @@ var _ = Describe("Annotations", func() {
})
It("returns 404 and does not rate an album in a library the user can't access", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/"+dto.EncodeID(testID("a1"))+"/Rating?Rating=10", nil).WithContext(ctxUser()) // only has access to library 1
@ -236,7 +236,7 @@ var _ = Describe("Annotations", func() {
})
It("rounds an odd rating to the nearest star instead of truncating", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=9", nil).WithContext(ctxUser())
@ -247,7 +247,7 @@ var _ = Describe("Annotations", func() {
})
It("stores the minimum star for Rating=1 instead of clearing the rating", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Annotations: model.Annotations{Rating: 4}}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=1", nil).WithContext(ctxUser())
@ -258,7 +258,7 @@ var _ = Describe("Annotations", func() {
})
It("accepts a fractional rating (UserItemDataDto.Rating is a double)", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=7.5", nil).WithContext(ctxUser())
@ -269,7 +269,7 @@ var _ = Describe("Annotations", func() {
})
It("clamps a Rating above 10 to Navidrome's max (5)", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=100", nil).WithContext(ctxUser())
@ -280,7 +280,7 @@ var _ = Describe("Annotations", func() {
})
It("clamps a negative Rating to Navidrome's min (0)", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=-5", nil).WithContext(ctxUser())
@ -291,7 +291,7 @@ var _ = Describe("Annotations", func() {
})
It("emits a refreshResource event when rating a song", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/u1/Items/s1/Rating?Rating=8", nil).WithContext(ctxUser())

View file

@ -1,6 +1,7 @@
package jellyfin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
@ -18,6 +19,12 @@ import (
)
var _ = Describe("Router", func() {
var ctx context.Context
BeforeEach(func() {
ctx = GinkgoT().Context()
})
It("serves the public handshake through the mounted handler", func() {
ds := &tests.MockDataStore{}
api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
@ -49,8 +56,8 @@ var _ = Describe("Router", func() {
It("registers a player on a general authenticated request, not just playback reports", func() {
ds := &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(GinkgoT().Context()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
token, err := auth.CreateToken(&model.User{ID: testID("u1"), UserName: "alice"})
Expect(err).ToNot(HaveOccurred())
@ -95,7 +102,7 @@ var _ = Describe("Router", func() {
ds := &tests.MockDataStore{}
auth.Init(ds)
usr := model.User{ID: testID("alice"), UserName: "alice"}
Expect(ds.User(GinkgoT().Context()).Put(&usr)).To(Succeed())
Expect(ds.User().Put(ctx, &usr)).To(Succeed())
token, err := auth.CreateAPIToken(&usr, auth.AudienceJellyfin)
Expect(err).ToNot(HaveOccurred())
api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, quickconnect.New())

View file

@ -24,7 +24,7 @@ func (api *Router) authenticateByName(w http.ResponseWriter, r *http.Request) {
}
// Navidrome stores recoverable passwords; this mirrors Subsonic's validateCredentials plaintext path.
usr, err := api.ds.User(ctx).FindByUsernameWithPassword(body.Username)
usr, err := api.ds.User().FindByUsernameWithPassword(ctx, body.Username)
if body.Pw == "" || err != nil || usr == nil || usr.Password != body.Pw {
log.Warn(ctx, "Jellyfin API: invalid login", "username", body.Username, "remoteAddr", r.RemoteAddr)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
@ -37,7 +37,7 @@ func (api *Router) signIn(w http.ResponseWriter, r *http.Request, usr *model.Use
ctx := r.Context()
// Best-effort, like the web UI's validateLogin: without it, Jellyfin-only users show a
// never/stale "Last Login" in the admin UI.
if err := api.ds.User(ctx).UpdateLastLoginAt(usr.ID); err != nil {
if err := api.ds.User().UpdateLastLoginAt(ctx, usr.ID); err != nil {
log.Error(ctx, "Jellyfin API: could not update last login date", "username", usr.UserName, err)
}

View file

@ -17,13 +17,15 @@ import (
)
var _ = Describe("AuthenticateByName", func() {
var ctx context.Context
var api *Router
var ds *tests.MockDataStore
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
api = &Router{ds: ds}
})
@ -105,15 +107,15 @@ var _ = Describe("AuthenticateByName", func() {
api.authenticateByName(w, r)
Expect(w.Code).To(Equal(http.StatusOK))
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
usr, err := ur.FindByUsername("alice")
ur := ds.User().(*tests.MockedUserRepo)
usr, err := ur.FindByUsername(ctx, "alice")
Expect(err).ToNot(HaveOccurred())
Expect(usr.LastLoginAt).ToNot(BeNil())
})
It("reflects an administrator in the User.Policy", func() {
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("admin1"), UserName: "root", NewPassword: "secret", IsAdmin: true})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("admin1"), UserName: "root", NewPassword: "secret", IsAdmin: true})).To(Succeed())
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",
@ -136,8 +138,8 @@ var _ = Describe("AuthenticateByName", func() {
})
It("rejects an empty password even for a user with an empty stored password with 401", func() {
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("e"), UserName: "empty", NewPassword: ""})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("e"), UserName: "empty", NewPassword: ""})).To(Succeed())
w := httptest.NewRecorder()
r := httptest.NewRequest("POST", "/Users/AuthenticateByName",

View file

@ -77,7 +77,7 @@ func (api *Router) getStudios(w http.ResponseWriter, r *http.Request) {
return
}
opts := model.QueryOptions{Sort: "tag_value", Filters: libraryScopeFilter(scope)}
labels, err := api.ds.Tag(ctx).GetAll(model.TagRecordLabel, opts)
labels, err := api.ds.Tag().GetAll(ctx, model.TagRecordLabel, opts)
if err != nil {
api.internalError(w, r, err)
return
@ -97,12 +97,12 @@ func (api *Router) getQueryFiltersLegacy(w http.ResponseWriter, r *http.Request)
return
}
genreOpts := model.QueryOptions{Sort: "name", Filters: libraryScopeFilter(scope)}
genres, err := api.ds.Genre(ctx).GetAll(genreOpts)
genres, err := api.ds.Genre().GetAll(ctx, genreOpts)
if err != nil {
api.internalError(w, r, err)
return
}
years, err := api.ds.Album(ctx).GetYears(scope...)
years, err := api.ds.Album().GetYears(ctx, scope...)
if err != nil {
api.internalError(w, r, err)
return

View file

@ -33,7 +33,7 @@ var _ = Describe("Browsing", func() {
Describe("getArtists", func() {
It("lists artists via /Artists", func() {
ds.Artist(context.Background()).(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}})
ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
invoke(api.getArtists, w, r)
@ -45,7 +45,7 @@ var _ = Describe("Browsing", func() {
})
It("handles /Artists/AlbumArtists the same way", func() {
ds.Artist(context.Background()).(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}})
ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists/AlbumArtists", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
invoke(api.getArtists, w, r)
@ -56,7 +56,7 @@ var _ = Describe("Browsing", func() {
})
It("scopes results to the user's accessible libraries", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -70,7 +70,7 @@ var _ = Describe("Browsing", func() {
})
It("scopes to a single library when ParentId is an accessible library id", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -85,7 +85,7 @@ var _ = Describe("Browsing", func() {
})
It("does not let ParentId=<inaccessible library id> narrow the scope", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}} // no access to library 99
@ -100,7 +100,7 @@ var _ = Describe("Browsing", func() {
})
It("forwards SearchTerm to the repo's Search method", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists?SearchTerm=art", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
@ -112,7 +112,7 @@ var _ = Describe("Browsing", func() {
})
It("bounds a search the client left unbounded, and clamps an oversized one", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
@ -129,7 +129,7 @@ var _ = Describe("Browsing", func() {
})
It("forwards StartIndex/Limit as Offset/Max", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists?StartIndex=5&Limit=10", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
@ -140,7 +140,7 @@ var _ = Describe("Browsing", func() {
})
It("does not restrict results for an admin user", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists", nil).WithContext(ctxAdmin())
@ -158,7 +158,7 @@ var _ = Describe("Browsing", func() {
DescribeTable("restricts to favorites",
func(url string, handler func(*Router) http.HandlerFunc) {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", url, nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
@ -180,7 +180,7 @@ var _ = Describe("Browsing", func() {
)
It("404s a malformed ParentId instead of listing every library's artists", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Artists?ParentId=not-a-valid-id", nil).WithContext(ctxUser(model.Libraries{{ID: 1}}))
@ -210,7 +210,7 @@ var _ = Describe("Browsing", func() {
Describe("getStudios", func() {
It("scopes results to the user's accessible libraries", func() {
tagRepo := ds.Tag(context.Background()).(*tests.MockTagRepo)
tagRepo := ds.Tag().(*tests.MockTagRepo)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Studios", nil).WithContext(ctxUser(model.Libraries{{ID: 1}, {ID: 2}}))
invoke(api.getStudios, w, r)
@ -224,7 +224,7 @@ var _ = Describe("Browsing", func() {
// An empty scope (admin, or a non-admin with no explicit library grants) must be treated
// as unrestricted, matching accessibleLibraryIDs' documented contract, not as "match nothing".
It("does not restrict results for an admin user", func() {
tagRepo := ds.Tag(context.Background()).(*tests.MockTagRepo)
tagRepo := ds.Tag().(*tests.MockTagRepo)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Studios", nil).WithContext(ctxAdmin())
invoke(api.getStudios, w, r)
@ -242,7 +242,7 @@ var _ = Describe("Browsing", func() {
Describe("getQueryFiltersLegacy", func() {
It("scopes genres to the user's accessible libraries", func() {
genreRepo := ds.Genre(context.Background()).(*tests.MockedGenreRepo)
genreRepo := ds.Genre().(*tests.MockedGenreRepo)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/Filters", nil).WithContext(ctxUser(model.Libraries{{ID: 1}, {ID: 2}}))
invoke(api.getQueryFiltersLegacy, w, r)
@ -254,7 +254,7 @@ var _ = Describe("Browsing", func() {
})
It("does not restrict genres for an admin user", func() {
genreRepo := ds.Genre(context.Background()).(*tests.MockedGenreRepo)
genreRepo := ds.Genre().(*tests.MockedGenreRepo)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/Filters", nil).WithContext(ctxAdmin())
invoke(api.getQueryFiltersLegacy, w, r)

View file

@ -87,10 +87,10 @@ var _ = Describe("Authentication", func() {
Expect(pw.Code).To(Equal(http.StatusOK))
// A real password change through the repository, which is what revokes in production.
admin, err := ds.User(ctx).Get(testID("admin-1"))
admin, err := ds.User().Get(ctx, testID("admin-1"))
Expect(err).ToNot(HaveOccurred())
admin.NewPassword = "rotated"
Expect(ds.User(ctx).Put(admin)).To(Succeed())
Expect(ds.User().Put(ctx, admin)).To(Succeed())
r = httptest.NewRequest("GET", "/Users/Me", nil)
r.Header.Set("X-Emby-Token", res.AccessToken)

View file

@ -222,8 +222,14 @@ func createPlaylistAs(user model.User, name string, encodedIds ...string) string
}
body, err := json.Marshal(map[string]any{"Name": name, "Ids": encodedIds})
Expect(err).ToNot(HaveOccurred())
return createPlaylistBodyAs(user, string(body))
}
// createPlaylistBodyAs posts a raw create body, for tests that need fields the helpers above don't
// build, and returns the new playlist's decoded id.
func createPlaylistBodyAs(user model.User, body string) string {
var res map[string]string
parseInto(postAs(user, "/Playlists", string(body)), &res)
parseInto(postAs(user, "/Playlists", body), &res)
Expect(res["Id"]).ToNot(BeEmpty())
id, ok := dto.DecodeID(res["Id"])
Expect(ok).To(BeTrue())
@ -238,7 +244,7 @@ func enc(id string) string { return dto.EncodeID(id) }
// guessing repository filter column names.
func albumID(name string) string {
albums, err := ds.Album(ctx).GetAll()
albums, err := ds.Album().GetAll(ctx)
Expect(err).ToNot(HaveOccurred())
for _, a := range albums {
if a.Name == name {
@ -250,7 +256,7 @@ func albumID(name string) string {
}
func songID(title string) string {
mfs, err := ds.MediaFile(ctx).GetAll()
mfs, err := ds.MediaFile().GetAll(ctx)
Expect(err).ToNot(HaveOccurred())
for _, mf := range mfs {
if mf.Title == title {
@ -262,7 +268,7 @@ func songID(title string) string {
}
func artistID(name string) string {
artists, err := ds.Artist(ctx).GetAll()
artists, err := ds.Artist().GetAll(ctx)
Expect(err).ToNot(HaveOccurred())
for _, a := range artists {
if a.Name == name {
@ -274,7 +280,7 @@ func artistID(name string) string {
}
func genreID(name string) string {
genres, err := ds.Genre(ctx).GetAll()
genres, err := ds.Genre().GetAll(ctx)
Expect(err).ToNot(HaveOccurred())
for _, g := range genres {
if g.Name == name {
@ -393,7 +399,7 @@ func (f *fakeSonicProvider) FindSonicPath(context.Context, *model.MediaFile, *mo
// songAgent looks a seeded track up by title (titles are unique in the seed) and builds an
// agents.Song carrying its title+artist, so the matcher resolves it back to that MediaFile.
func songAgent(title string) agents.Song {
mfs, err := ds.MediaFile(ctx).GetAll()
mfs, err := ds.MediaFile().GetAll(ctx)
Expect(err).ToNot(HaveOccurred())
for _, mf := range mfs {
if mf.Title == title {

View file

@ -19,8 +19,8 @@ var _ = Describe("Multi-user access control", func() {
It("hides all content from a user with no library access", func() {
noAccess := model.User{ID: testID("noaccess-1"), UserName: "noaccess", Name: "No Access", NewPassword: "password"}
Expect(ds.User(ctx).Put(&noAccess)).To(Succeed())
loaded, err := ds.User(ctx).FindByUsername("noaccess")
Expect(ds.User().Put(ctx, &noAccess)).To(Succeed())
loaded, err := ds.User().FindByUsername(ctx, "noaccess")
Expect(err).ToNot(HaveOccurred())
q := queryResult(getAs(*loaded, "/Items?IncludeItemTypes=MusicAlbum&Recursive=true"))

View file

@ -21,12 +21,19 @@ var _ = Describe("Playlists", func() {
}
order := func(plID string) []string { return names(playlistItems(plID).Items) }
createWith := func(body string) string { return createPlaylistBodyAs(adminUser, body) }
openAccess := func(plID string) bool {
var info dto.PlaylistInfo
parseInto(get("/Playlists/"+enc(plID)), &info)
return info.OpenAccess
}
Describe("create", func() {
It("creates an empty playlist", func() {
plID := createPlaylist("Empty", nil)
var info dto.PlaylistInfo
parseInto(get("/Playlists/"+enc(plID)), &info)
Expect(info.OpenAccess).To(BeFalse())
Expect(info.OpenAccess).To(BeFalse(), "a playlist created without IsPublic stays private")
Expect(info.Shares).To(BeEmpty())
Expect(info.ItemIds).To(BeEmpty())
})
@ -48,16 +55,24 @@ var _ = Describe("Playlists", func() {
Expect(playlistItems(plID).TotalRecordCount).To(Equal(3)) // Abbey Road (2) + Help! (1)
})
It("creates a public playlist when the client sends IsPublic true", func() {
Expect(openAccess(createWith(`{"Name":"Public","Ids":[],"IsPublic":true}`))).To(BeTrue())
})
It("creates a private playlist when the client sends IsPublic false", func() {
Expect(openAccess(createWith(`{"Name":"Private","Ids":[],"IsPublic":false}`))).To(BeFalse())
})
// dto.DecodeIDs is all-or-nothing: a malformed entry must 404 the whole request, not get
// dropped while the well-formed entries are still used to create a playlist.
It("404s when one of the Ids is malformed, without creating a playlist", func() {
before, err := ds.Playlist(ctx).CountAll()
before, err := ds.Playlist().CountAll(ctx)
Expect(err).ToNot(HaveOccurred())
body := `{"Name":"ShouldNotExist","Ids":["` + enc(songID("So What")) + `","not-a-valid-id"]}`
Expect(post("/Playlists", body).Code).To(Equal(http.StatusNotFound))
after, err := ds.Playlist(ctx).CountAll()
after, err := ds.Playlist().CountAll(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(after).To(Equal(before))
})
@ -303,14 +318,14 @@ var _ = Describe("Playlists", func() {
Expect(upload(adminUser, "/Items/"+enc(plID)+"/Images/Primary", "image/jpeg", jpeg).Code).
To(Equal(http.StatusNoContent))
pls, err := ds.Playlist(ctx).Get(plID)
pls, err := ds.Playlist().Get(ctx, plID)
Expect(err).ToNot(HaveOccurred())
Expect(pls.UploadedImage).ToNot(BeEmpty())
_, statErr := os.Stat(pls.UploadedImagePath())
Expect(statErr).ToNot(HaveOccurred(), "cover file should exist on disk")
Expect(del("/Items/" + enc(plID) + "/Images/Primary").Code).To(Equal(http.StatusNoContent))
pls, _ = ds.Playlist(ctx).Get(plID)
pls, _ = ds.Playlist().Get(ctx, plID)
Expect(pls.UploadedImage).To(BeEmpty())
})
@ -323,7 +338,7 @@ var _ = Describe("Playlists", func() {
// from their tag-keyed cache until the next scan.
It("clears the resolved image tag after a cover upload", func() {
plID := createPlaylist("Cover Tag", nil)
Expect(ds.Artwork(ctx).PutItemArtwork(&model.ItemArtwork{
Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{
ItemKind: model.KindPlaylistArtwork.Prefix(), ItemID: plID, Hash: "1111111111111111",
})).To(Succeed())
@ -355,10 +370,7 @@ var _ = Describe("Playlists", func() {
It("makes a playlist public", func() {
plID := createPlaylist("Make Public", nil)
Expect(post("/Playlists/"+enc(plID), `{"Name":"Make Public","IsPublic":true}`).Code).To(Equal(http.StatusNoContent))
var info dto.PlaylistInfo
parseInto(get("/Playlists/"+enc(plID)), &info)
Expect(info.OpenAccess).To(BeTrue())
Expect(openAccess(plID)).To(BeTrue())
// Now visible to other users.
Expect(queryResult(getAs(regularUser, "/Items?IncludeItemTypes=Playlist&Recursive=true")).TotalRecordCount).To(Equal(1))
})
@ -366,7 +378,7 @@ var _ = Describe("Playlists", func() {
It("renames a playlist", func() {
plID := createPlaylist("Old Name", nil)
Expect(post("/Playlists/"+enc(plID), `{"Name":"New Name"}`).Code).To(Equal(http.StatusNoContent))
pls, _ := ds.Playlist(ctx).Get(plID)
pls, _ := ds.Playlist().Get(ctx, plID)
Expect(pls.Name).To(Equal("New Name"))
})
@ -398,7 +410,7 @@ var _ = Describe("Playlists", func() {
q := playlistItems(plID)
Expect(q.TotalRecordCount).To(Equal(1))
Expect(q.Items[0].Name).To(Equal("So What"))
pls, _ := ds.Playlist(ctx).Get(plID)
pls, _ := ds.Playlist().Get(ctx, plID)
Expect(pls.Name).To(Equal("Combo Renamed"))
Expect(pls.Public).To(BeTrue())
})
@ -412,13 +424,13 @@ var _ = Describe("Playlists", func() {
// An id that decodes to "" would tell Create to make a new playlist instead of updating one —
// itemIDParam must 404 before that decode ever runs, not silently create one.
It("404s for a malformed playlist id, without creating a playlist", func() {
before, err := ds.Playlist(ctx).CountAll()
before, err := ds.Playlist().CountAll(ctx)
Expect(err).ToNot(HaveOccurred())
w := post("/Playlists/00000000000000000000000000000000", `{"Ids":["`+enc(songID("So What"))+`"]}`)
Expect(w.Code).To(Equal(http.StatusNotFound))
after, err := ds.Playlist(ctx).CountAll()
after, err := ds.Playlist().CountAll(ctx)
Expect(err).ToNot(HaveOccurred())
Expect(after).To(Equal(before))
})

View file

@ -27,12 +27,12 @@ var _ = Describe("Sessions", func() {
It("counts a play stopped past the threshold", func() {
id := songID("So What")
mf, err := ds.MediaFile(ctx).Get(id)
mf, err := ds.MediaFile().Get(ctx, id)
Expect(err).ToNot(HaveOccurred())
// Report a stop at the end of the track — comfortably past 50% / the 4-minute cap.
Expect(post("/Sessions/Playing/Stopped", reportBody(id, ticks(int64(mf.Duration*1000)))).Code).To(Equal(http.StatusNoContent))
mf, err = ds.MediaFile(ctx).Get(id)
mf, err = ds.MediaFile().Get(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(mf.PlayCount).To(BeNumerically(">=", 1))
})
@ -48,7 +48,7 @@ var _ = Describe("Sessions", func() {
id := songID("Help!")
Expect(post("/Sessions/Playing/Stopped", reportBody(id, ticks(1000))).Code).To(Equal(http.StatusNoContent))
mf, err := ds.MediaFile(ctx).Get(id)
mf, err := ds.MediaFile().Get(ctx, id)
Expect(err).ToNot(HaveOccurred())
Expect(mf.PlayCount).To(Equal(int64(0)))
})

View file

@ -68,9 +68,9 @@ var _ = Describe("Similar", func() {
// Seed an album in a second library the regular user has no access to, and point a
// provider similar-song at it.
otherLib := model.Library{ID: 2, Name: "Other Library", Path: "fake:///other"}
Expect(ds.Library(ctx).Put(&otherLib)).To(Succeed())
Expect(ds.Library().Put(ctx, &otherLib)).To(Succeed())
otherAlbum := model.Album{ID: testID("other-album"), Name: "Other Album", LibraryID: 2}
Expect(ds.Album(ctx).Put(&otherAlbum)).To(Succeed())
Expect(ds.Album().Put(ctx, &otherAlbum)).To(Succeed())
providerFake.similarSongs = model.MediaFiles{
{ID: testID("x1"), AlbumID: albumID("IV")}, // library 1 -> visible

View file

@ -82,16 +82,16 @@ func hashFromTag(r *http.Request) string {
// resolveArtworkID maps a Jellyfin item id to a Navidrome ArtworkID, probing
// album -> artist -> media file -> playlist.
func (api *Router) resolveArtworkID(ctx context.Context, itemId string) string {
if al, err := api.ds.Album(ctx).Get(itemId); err == nil {
if al, err := api.ds.Album().Get(ctx, itemId); err == nil {
return al.CoverArtID().String()
}
if ar, err := api.ds.Artist(ctx).Get(itemId); err == nil {
if ar, err := api.ds.Artist().Get(ctx, itemId); err == nil {
return ar.CoverArtID().String()
}
if mf, err := api.ds.MediaFile(ctx).Get(itemId); err == nil {
if mf, err := api.ds.MediaFile().Get(ctx, itemId); err == nil {
return mf.CoverArtID().String()
}
if pl, err := api.ds.Playlist(ctx).Get(itemId); err == nil {
if pl, err := api.ds.Playlist().Get(ctx, itemId); err == nil {
return pl.CoverArtID().String()
}
return (model.ArtworkID{}).String()

View file

@ -68,7 +68,7 @@ var _ = Describe("Images", func() {
DescribeTable("derives the requested size from the Jellyfin size params",
func(query string, wantSize int) {
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
fa := &fakeArtwork{}
api := &Router{ds: ds, artwork: fa}
@ -97,7 +97,7 @@ var _ = Describe("Images", func() {
It("streams album artwork", func() {
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
fa := &fakeArtwork{}
api := &Router{ds: ds, artwork: fa}
@ -138,7 +138,7 @@ var _ = Describe("Images", func() {
It("sniffs the Content-Type instead of hardcoding it", func() {
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
png := append([]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, make([]byte, 512)...)
fa := &fakeArtwork{data: png}
@ -153,7 +153,7 @@ var _ = Describe("Images", func() {
It("resolves a playlist's cover regardless of visibility, even for an anonymous caller", func() {
ds := &tests.MockDataStore{}
ds.Playlist(context.Background()).(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("pl1"), Name: "Mix", OwnerID: testID("someone")}})
ds.Playlist().(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("pl1"), Name: "Mix", OwnerID: testID("someone")}})
fa := &fakeArtwork{}
api := &Router{ds: ds, artwork: fa}
@ -169,7 +169,7 @@ var _ = Describe("Images", func() {
// silently falls back to the placeholder.
It("resolves artwork under an elevated admin context", func() {
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
fa := &fakeArtwork{}
api := &Router{ds: ds, artwork: fa}
@ -185,7 +185,7 @@ var _ = Describe("Images", func() {
It("serves immutable when the tag param asserts the current hash", func() {
const hash = "0123456789abcdef"
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
fa := &fakeArtwork{hash: hash}
api := &Router{ds: ds, artwork: fa}
@ -203,7 +203,7 @@ var _ = Describe("Images", func() {
It("revalidates via no-cache when no tag is provided", func() {
const hash = "0123456789abcdef"
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
fa := &fakeArtwork{hash: hash}
api := &Router{ds: ds, artwork: fa}

View file

@ -382,7 +382,7 @@ func (api *Router) parseItemsQuery(ctx context.Context, r *http.Request) (itemsQ
if q.parentId == dto.PlaylistsFolderID {
// Browsing into the synthetic playlists folder lists the user's playlists.
q.types = []string{"Playlist"}
} else if _, err := api.ds.Album(ctx).Get(q.parentId); err == nil {
} else if _, err := api.ds.Album().Get(ctx, q.parentId); err == nil {
q.types = []string{"Audio"}
}
}
@ -412,7 +412,7 @@ func (api *Router) queryItems(ctx context.Context, r *http.Request) (itemsResult
return materialized(result([]dto.BaseItemDto{playlistsFolder()}, 1, 0)), nil
}
if repo, ok := api.playlistTracksRepo(ctx, q); ok {
return api.playlistTrackPage(repo, q.fields, q.offset, q.limit)
return api.playlistTrackPage(ctx, repo, q.fields, q.offset, q.limit)
}
if q.search != "" {
q.limit = clampLimit(q.limit, defaultSearchLimit, maxSearchLimit)
@ -702,7 +702,7 @@ func searchPage[S ~[]E, E any](opts model.QueryOptions, search func(model.QueryO
func (api *Router) listAlbums(ctx context.Context, opts model.QueryOptions, q itemsQuery) (itemsResult, error) {
toItem := func(al model.Album) dto.BaseItemDto { return dto.AlbumToBaseItem(al, q.fields) }
repo := api.ds.Album(ctx)
repo := api.ds.Album()
filters := squirrel.And{}
// For albums, ParentId (browse an artist) and AlbumArtistIds/ArtistIds both mean "this artist's
// albums"; contributingArtistIds means "albums they only appear on" (Featured On).
@ -733,23 +733,23 @@ func (api *Router) listAlbums(ctx context.Context, opts model.QueryOptions, q it
if q.search != "" {
albums, total, err := searchPage(opts, func(o model.QueryOptions) (model.Albums, error) {
return repo.Search(q.search, o)
return repo.Search(ctx, q.search, o)
})
if err != nil {
return itemsResult{}, err
}
return materialized(result(slice.Map(albums, toItem), total, opts.Offset)), nil
}
total, _ := repo.CountAll(model.QueryOptions{Filters: opts.Filters})
total, _ := repo.CountAll(ctx, model.QueryOptions{Filters: opts.Filters})
open := streamCursor(func() (func(func(model.Album, error) bool), error) {
return repo.GetCursor(opts)
return repo.GetCursor(ctx, opts)
}, toItem)
return streamed(open, int(total), opts.Offset), nil
}
func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q itemsQuery) (itemsResult, error) {
toItem := func(mf model.MediaFile) dto.BaseItemDto { return dto.SongToBaseItem(mf, q.fields) }
repo := api.ds.MediaFile(ctx)
repo := api.ds.MediaFile()
filters := squirrel.And{}
// For songs, ArtistIds/AlbumArtistIds selects an artist's tracks; ParentId selects an album's.
switch {
@ -782,7 +782,7 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite
if q.search != "" {
mfs, total, err := searchPage(opts, func(o model.QueryOptions) (model.MediaFiles, error) {
return repo.Search(q.search, o)
return repo.Search(ctx, q.search, o)
})
if err != nil {
return itemsResult{}, err
@ -795,9 +795,9 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite
opts.Sort = filter.SongsByAlbum(q.entityParent).Sort
}
// A full-library request (Finamp's sync, with MediaSources) is tens of thousands of fat rows.
total, _ := repo.CountAll(model.QueryOptions{Filters: opts.Filters})
total, _ := repo.CountAll(ctx, model.QueryOptions{Filters: opts.Filters})
open := streamCursor(func() (func(func(model.MediaFile, error) bool), error) {
return repo.GetCursorWithArtwork(opts)
return repo.GetCursorWithArtwork(ctx, opts)
}, toItem)
return streamed(open, int(total), opts.Offset), nil
}
@ -806,7 +806,7 @@ func (api *Router) listSongs(ctx context.Context, opts model.QueryOptions, q ite
// RoleArtist for performing artists (/Artists). Without the role filter both lists would be identical.
// genreIds isn't applied to search — a name lookup, like role (see below).
func (api *Router) listArtists(ctx context.Context, opts model.QueryOptions, q itemsQuery, role model.Role) (itemsResult, error) {
repo := api.ds.Artist(ctx)
repo := api.ds.Artist()
toItem := func(ar model.Artist) dto.BaseItemDto { return dto.ArtistToBaseItem(ar, q.fields) }
// Artist Search does its own library scoping: it consumes a sole Eq{"library_id": ...} filter as a
@ -818,7 +818,7 @@ func (api *Router) listArtists(ctx context.Context, opts model.QueryOptions, q i
opts.Filters = squirrel.Eq{"library_id": q.scopeIDs}
}
artists, total, err := searchPage(opts, func(o model.QueryOptions) (model.Artists, error) {
return repo.Search(q.search, o)
return repo.Search(ctx, q.search, o)
})
if err != nil {
return itemsResult{}, err
@ -834,9 +834,9 @@ func (api *Router) listArtists(ctx context.Context, opts model.QueryOptions, q i
opts.Filters = filters
opts = filter.ArtistsByRole(opts, role)
opts = filter.ApplyArtistLibraryFilter(opts, q.scopeIDs)
total, _ := repo.CountAll(model.QueryOptions{Filters: opts.Filters})
total, _ := repo.CountAll(ctx, model.QueryOptions{Filters: opts.Filters})
open := streamCursor(func() (func(func(model.Artist, error) bool), error) {
return repo.GetCursor(opts)
return repo.GetCursor(ctx, opts)
}, toItem)
return streamed(open, int(total), opts.Offset), nil
}
@ -845,7 +845,7 @@ func (api *Router) listArtists(ctx context.Context, opts model.QueryOptions, q i
// the one listXxx that stays materialized: GenreRepository has no CountAll, so the total is the
// length of the full list and paging is in-memory — nothing for a cursor to page over.
func (api *Router) listGenres(ctx context.Context, opts model.QueryOptions) (itemsResult, error) {
genres, err := api.ds.Genre(ctx).GetAll(model.QueryOptions{Sort: opts.Sort, Order: opts.Order})
genres, err := api.ds.Genre().GetAll(ctx, model.QueryOptions{Sort: opts.Sort, Order: opts.Order})
if err != nil {
return itemsResult{}, err
}
@ -859,13 +859,13 @@ func (api *Router) listPlaylists(ctx context.Context, opts model.QueryOptions, q
if preds := q.filters.predicates(); len(preds) > 0 {
opts.Filters = squirrel.And(preds)
}
repo := api.ds.Playlist(ctx)
total, err := repo.CountAll(model.QueryOptions{Filters: opts.Filters})
repo := api.ds.Playlist()
total, err := repo.CountAll(ctx, model.QueryOptions{Filters: opts.Filters})
if err != nil {
return itemsResult{}, err
}
open := streamCursor(func() (func(func(model.Playlist, error) bool), error) {
return repo.GetCursor(opts)
return repo.GetCursor(ctx, opts)
}, func(p model.Playlist) dto.BaseItemDto { return dto.PlaylistToBaseItem(p, q.fields) })
return streamed(open, int(total), opts.Offset), nil
}
@ -882,22 +882,21 @@ func (api *Router) resolveItemByID(ctx context.Context, id string, fields dto.Fi
// Finamp resolves a /UserViews entry (Id=library id) by fetching it as a plain item; without this
// the home screen and library tabs 404.
if libID, err := strconv.Atoi(id); err == nil && u.HasLibraryAccess(libID) {
if lib, err := api.ds.Library(ctx).Get(libID); err == nil {
if lib, err := api.ds.Library().Get(ctx, libID); err == nil {
return dto.LibraryToBaseItem(*lib), true
}
}
if al, err := api.ds.Album(ctx).Get(id); err == nil {
if al, err := api.ds.Album().Get(ctx, id); err == nil {
if !u.HasLibraryAccess(al.LibraryID) {
return dto.BaseItemDto{}, false
}
return dto.AlbumToBaseItem(*al, fields), true
}
if ar, err := api.ds.Artist(ctx).Get(id); err == nil {
// TODO: an artist spans multiple libraries (library_artist), so there's no single
// LibraryID to gate here; artist access relies on list-time scoping and persistence.
if ar, err := api.ds.Artist().Get(ctx, id); err == nil {
// Artist.Get already scopes to the user's libraries via library_artist.
return dto.ArtistToBaseItem(*ar, fields), true
}
if mf, err := api.ds.MediaFile(ctx).Get(id); err == nil {
if mf, err := api.ds.MediaFile().Get(ctx, id); err == nil {
if !u.HasLibraryAccess(mf.LibraryID) {
return dto.BaseItemDto{}, false
}
@ -907,7 +906,7 @@ func (api *Router) resolveItemByID(ctx context.Context, id string, fields dto.Fi
if pl, err := api.playlists.Get(ctx, id); err == nil {
return dto.PlaylistToBaseItem(*pl, fields), true
}
if g, err := api.ds.Genre(ctx).Get(id); err == nil {
if g, err := api.ds.Genre().Get(ctx, id); err == nil {
return dto.GenreToBaseItem(*g), true
}
return dto.BaseItemDto{}, false
@ -918,7 +917,7 @@ func (api *Router) songsByIDs(ctx context.Context, ids []string) map[string]mode
songs := make(map[string]model.MediaFile, len(ids))
// Chunked to stay under SQLITE_MAX_VARIABLE_NUMBER, like playqueue's loadTracks.
for chunk := range slice.CollectChunks(slices.Values(ids), 500) {
mfs, err := api.ds.MediaFile(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"media_file.id": chunk}})
mfs, err := api.ds.MediaFile().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"media_file.id": chunk}})
if err != nil {
log.Error(ctx, "Jellyfin API: error fetching songs by id", err)
continue
@ -998,9 +997,9 @@ func (api *Router) getLatest(w http.ResponseWriter, r *http.Request) {
opts.Filters = squirrel.And{opts.Filters, filter.AlbumsByArtistID(parentID).Filters}
}
opts = filter.ApplyLibraryFilter(opts, scopeIDs)
repo := api.ds.Album(ctx)
repo := api.ds.Album()
open := streamCursor(func() (func(func(model.Album, error) bool), error) {
return repo.GetCursor(opts)
return repo.GetCursor(ctx, opts)
}, func(al model.Album) dto.BaseItemDto { return dto.AlbumToBaseItem(al, fields) })
api.writeItemsArray(w, r, streamed(open, 0, 0))
}

View file

@ -49,7 +49,7 @@ var _ = Describe("Items", func() {
Describe("getItems", func() {
It("lists albums when IncludeItemTypes=MusicAlbum", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&Recursive=true", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -62,8 +62,8 @@ var _ = Describe("Items", func() {
})
It("lists an album's songs when ParentId is an album and type is Audio", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -75,8 +75,8 @@ var _ = Describe("Items", func() {
})
It("ignores IncludeItemTypes names that aren't Jellyfin item kinds", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=music", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -126,8 +126,8 @@ var _ = Describe("Items", func() {
It("falls through to the type dispatch when ParentId is not a playlist", func() {
fp.getErr = model.ErrNotFound
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", nil).
WithContext(ctxUser())
@ -140,7 +140,7 @@ var _ = Describe("Items", func() {
})
It("returns 500 when the song cursor fails to open, instead of a truncated 200", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetError(true)
ds.MediaFile().(*tests.MockMediaFileRepo).SetError(true)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio&Recursive=true", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -151,8 +151,8 @@ var _ = Describe("Items", func() {
// looking for tracks outside any album; answering with every track streams the whole library.
Describe("Recursive=false", func() {
BeforeEach(func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}})
})
It("returns no songs for a library parent, as tracks are never its direct children", func() {
@ -223,21 +223,21 @@ var _ = Describe("Items", func() {
})
It("lists an artist's albums when ParentId is an artist and type is MusicAlbum", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", AlbumArtistID: testID("ar1")}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", AlbumArtistID: testID("ar1")}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ParentId="+dto.EncodeID(testID("ar1"))+"&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
var res dto.QueryResult
Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed())
Expect(res.Items).To(HaveLen(1))
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
sql, _, err := albumRepo.Options.Filters.ToSql()
Expect(err).NotTo(HaveOccurred())
Expect(sql).To(ContainSubstring("album_artists"))
})
It("lists artists when IncludeItemTypes=MusicArtist", func() {
ds.Artist(context.Background()).(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicArtist", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -258,7 +258,7 @@ var _ = Describe("Items", func() {
})
It("lists playlists when IncludeItemTypes=Playlist", func() {
ds.Playlist(context.Background()).(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("p1"), Name: "My Mix", SongCount: 5}})
ds.Playlist().(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("p1"), Name: "My Mix", SongCount: 5}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Playlist", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -272,8 +272,8 @@ var _ = Describe("Items", func() {
})
It("merges results from every requested type in IncludeItemTypes", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -287,11 +287,11 @@ var _ = Describe("Items", func() {
})
It("merges favorite songs, albums, and playlists", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
playlistRepo := ds.Playlist(context.Background()).(*tests.MockPlaylistRepo)
playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo)
playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "My Mix", Annotations: model.Annotations{Starred: true}}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum,Playlist&Filters=IsFavorite", nil).WithContext(ctxUser())
@ -312,8 +312,8 @@ var _ = Describe("Items", func() {
})
It("applies StartIndex/Limit to the merged multi-type result set", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}})
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
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"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=1&Limit=2", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -326,9 +326,9 @@ var _ = Describe("Items", func() {
})
It("caps each per-type query at StartIndex+Limit instead of fetching everything", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}})
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
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())
@ -341,7 +341,7 @@ var _ = Describe("Items", func() {
DescribeTable("translates the Filters list and its standalone equivalents",
func(query string, wantSQL, notWantSQL []string) {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&"+query, nil).WithContext(ctxUser())
@ -381,8 +381,8 @@ var _ = Describe("Items", func() {
// annotation predicate there is "no such column: starred" -> 500.
DescribeTable("does not push annotation filters into a search",
func(itemType, filters string) {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
ds.Album().(*tests.MockAlbumRepo).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="+itemType+"&SearchTerm=one&Filters="+filters, nil).WithContext(ctxUser())
@ -390,9 +390,9 @@ var _ = Describe("Items", func() {
Expect(w.Code).To(Equal(http.StatusOK))
var opts model.QueryOptions
if itemType == "MusicAlbum" {
opts = ds.Album(context.Background()).(*tests.MockAlbumRepo).Options
opts = ds.Album().(*tests.MockAlbumRepo).Options
} else {
opts = ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).Options
opts = ds.MediaFile().(*tests.MockMediaFileRepo).Options
}
if opts.Filters == nil {
return
@ -410,7 +410,7 @@ var _ = Describe("Items", func() {
)
It("forwards SearchTerm to the repo's Search method", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", nil).WithContext(ctxUser())
@ -422,7 +422,7 @@ var _ = Describe("Items", func() {
})
It("caps a search the client left unbounded", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", nil).WithContext(ctxUser())
@ -432,7 +432,7 @@ var _ = Describe("Items", func() {
})
It("honors an explicit search Limit up to the ceiling", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=500", nil).
@ -443,7 +443,7 @@ var _ = Describe("Items", func() {
})
It("clamps a search Limit that would materialize the library", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=999999", nil).
@ -454,7 +454,7 @@ var _ = Describe("Items", func() {
})
It("treats an all-whitespace SearchTerm as no search, streaming the unfiltered list", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
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=MusicAlbum&SearchTerm=%20%20", nil).
@ -472,8 +472,8 @@ var _ = Describe("Items", func() {
for i := range songs {
songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"}
}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&Limit=10", nil).
WithContext(ctxUser())
@ -486,9 +486,9 @@ var _ = Describe("Items", func() {
})
It("bounds the multi-type search window however large StartIndex is", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
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())
@ -505,8 +505,8 @@ var _ = Describe("Items", func() {
for i := range songs {
songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"}
}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET",
fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", maxSearchLimit),
@ -526,8 +526,8 @@ var _ = Describe("Items", func() {
}
// The mock repo returns rows sorted by ID; reorder to match so index-based assertions hold.
slices.SortFunc(songs, func(a, b model.MediaFile) int { return strings.Compare(a.ID, b.ID) })
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET",
fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=10", maxSearchLimit-1),
@ -546,8 +546,8 @@ var _ = Describe("Items", func() {
for i := range songs {
songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"}
}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song", nil).
WithContext(ctxUser())
@ -565,8 +565,8 @@ var _ = Describe("Items", func() {
}
// The mock repo returns rows sorted by ID; reorder to match so index-based assertions hold.
slices.SortFunc(songs, func(a, b model.MediaFile) int { return strings.Compare(a.ID, b.ID) })
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET",
fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d", defaultSearchLimit+50),
@ -581,7 +581,7 @@ var _ = Describe("Items", func() {
})
It("reports a search total beyond the fetched page instead of the page length", func() {
ds.Artist(context.Background()).(*tests.MockArtistRepo).SetData(model.Artists{
ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{
{ID: testID("r1"), Name: "Alpha"}, {ID: testID("r2"), Name: "Beta"}, {ID: testID("r3"), Name: "Gamma"},
})
w := httptest.NewRecorder()
@ -595,7 +595,7 @@ var _ = Describe("Items", func() {
})
It("forwards StartIndex/Limit as Offset/Max", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
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=5&Limit=10", nil).WithContext(ctxUser())
@ -609,7 +609,7 @@ var _ = Describe("Items", func() {
// Finamp's download/sync fetches a track's BaseItemDto via /Items?ids=<id>; without
// this, queryItems ignored Ids and returned the default type-dispatched list instead.
It("returns exactly the requested item when Ids has a single id", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?Ids="+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -623,8 +623,8 @@ var _ = Describe("Items", func() {
})
It("returns items of different types for a lowercase ids param with multiple ids", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -640,7 +640,7 @@ var _ = Describe("Items", func() {
})
It("resolves song ids with one batched IN query, not a Get per id", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}, {ID: testID("s2"), Title: "Song2", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?ids="+dto.EncodeID(testID("s1"))+","+dto.EncodeID(testID("s2")), nil).WithContext(ctxUser())
@ -656,8 +656,8 @@ var _ = Describe("Items", func() {
})
It("omits an id in a library the user can't access, without erroring the whole batch", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}}) // alice only has access to library 1
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}}) // alice only has access to library 1
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?Ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -673,9 +673,9 @@ var _ = Describe("Items", func() {
Describe("sorting", func() {
DescribeTable("translates SortBy into the repo's sort keys",
func(itemType, sortBy, want string) {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes="+itemType+"&SortBy="+sortBy, nil).WithContext(ctxUser())
@ -710,7 +710,7 @@ var _ = Describe("Items", func() {
// 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",
func(sortOrder, want string) {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET",
@ -728,7 +728,7 @@ var _ = Describe("Items", func() {
Describe("library scoping", func() {
It("scopes a MusicAlbum listing (no ParentId) to the user's accessible libraries", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -742,7 +742,7 @@ var _ = Describe("Items", func() {
})
It("scopes a Audio listing (no ParentId) to the user's accessible libraries", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -756,7 +756,7 @@ var _ = Describe("Items", func() {
})
It("scopes a MusicArtist listing to the user's accessible libraries", func() {
artistRepo := ds.Artist(context.Background()).(*tests.MockArtistRepo)
artistRepo := ds.Artist().(*tests.MockArtistRepo)
artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -770,7 +770,7 @@ var _ = Describe("Items", func() {
})
It("treats a numeric ParentId matching an accessible library as a library scope, not an artist id", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}
@ -785,7 +785,7 @@ var _ = Describe("Items", func() {
})
It("does not let ParentId=<inaccessible library id> scope results to that library", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}} // no access to library 99
@ -803,7 +803,7 @@ var _ = Describe("Items", func() {
})
It("does not restrict a default MusicAlbum listing for an admin user", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}, {ID: testID("a2"), Name: "Two", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum", nil).WithContext(ctxAdmin())
@ -824,7 +824,7 @@ var _ = Describe("Items", func() {
// still reach the entity filter, not the unfiltered default.
Describe("stale and malformed id filtering", func() {
It("404s a malformed ParentId instead of listing every song", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio&ParentId=not-a-valid-id", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -832,7 +832,7 @@ var _ = Describe("Items", func() {
})
It("404s a malformed AlbumArtistIds instead of listing every album", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds=not-a-valid-id", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -840,7 +840,7 @@ var _ = Describe("Items", func() {
})
It("404s a malformed ArtistIds instead of listing every song", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio&ArtistIds=not-a-valid-id", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -848,7 +848,7 @@ var _ = Describe("Items", func() {
})
It("still applies the artist filter (rather than dropping it) for a well-formed but unknown AlbumArtistIds", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
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("no-such-artist")), nil).WithContext(ctxUser())
@ -860,7 +860,7 @@ var _ = Describe("Items", func() {
})
It("still applies the album filter (rather than dropping it) for a well-formed but unknown ParentId", func() {
mfRepo := ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo)
mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio&ParentId="+dto.EncodeID(testID("no-such-album")), nil).WithContext(ctxUser())
@ -875,8 +875,8 @@ var _ = Describe("Items", func() {
Describe("mixed IncludeItemTypes merge", func() {
BeforeEach(func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "S1"}, {ID: testID("s2"), Title: "S2"}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "S1"}, {ID: testID("s2"), Title: "S2"}})
})
It("returns a mix of both types, not all of one", func() {
@ -927,7 +927,7 @@ var _ = Describe("Items", func() {
})
It("propagates a per-type query error", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetError(true)
ds.MediaFile().(*tests.MockMediaFileRepo).SetError(true)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", nil).WithContext(ctxUser())
invoke(api.getItems, w, r)
@ -938,7 +938,7 @@ var _ = Describe("Items", func() {
Describe("getItem", func() {
It("returns an album by id", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser())
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1")))
@ -959,7 +959,7 @@ var _ = Describe("Items", func() {
})
It("returns 404 for an album in a library the user can't access", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) // only has access to library 1
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1")))
@ -968,7 +968,7 @@ var _ = Describe("Items", func() {
})
It("returns 404 for a song in a library the user can't access", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser()) // only has access to library 1
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1")))
@ -977,7 +977,7 @@ var _ = Describe("Items", func() {
})
It("returns an album to an admin even when it's outside their (empty) Libraries", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxAdmin()) // admin, Libraries: nil
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1")))
@ -993,7 +993,7 @@ var _ = Describe("Items", func() {
It("resolves a library-view id (from /UserViews) as a CollectionFolder item", func() {
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1, Name: "Music Library"}}
ds.Library(context.Background()).(*tests.MockLibraryRepo).SetData(libs)
ds.Library().(*tests.MockLibraryRepo).SetData(libs)
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeLibraryID(1), nil).WithContext(ctxUserWithLibraries(libs))
r = withChiURLParam(r, "itemId", dto.EncodeLibraryID(1))
invoke(api.getItem, w, r)
@ -1043,7 +1043,7 @@ var _ = Describe("Items", func() {
// Finamp's genre "See all" fetches the genre by id; a 404 white-screens it (see resolveItemByID).
It("resolves a genre id as a MusicGenre item", func() {
Expect(ds.Genre(context.Background()).(*tests.MockedGenreRepo).Put(&model.Genre{ID: testID("g1"), Name: "Rock"})).To(Succeed())
Expect(ds.Genre().(*tests.MockedGenreRepo).Put(&model.Genre{ID: testID("g1"), Name: "Rock"})).To(Succeed())
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeID(testID("g1")), nil).WithContext(ctxUser())
r = withChiURLParam(r, "itemId", dto.EncodeID(testID("g1")))
@ -1057,7 +1057,7 @@ var _ = Describe("Items", func() {
})
It("resolves a library-view id for an admin even though their Libraries slice is empty", func() {
ds.Library(context.Background()).(*tests.MockLibraryRepo).SetData(model.Libraries{{ID: 1, Name: "Music Library"}})
ds.Library().(*tests.MockLibraryRepo).SetData(model.Libraries{{ID: 1, Name: "Music Library"}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Items/"+dto.EncodeLibraryID(1), nil).WithContext(ctxAdmin())
r = withChiURLParam(r, "itemId", dto.EncodeLibraryID(1))
@ -1073,7 +1073,7 @@ var _ = Describe("Items", func() {
Describe("getLatest", func() {
It("returns a bare array of the newest albums", func() {
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/Users/u1/Items/Latest", nil).WithContext(ctxUser())
invoke(api.getLatest, w, r)
@ -1085,7 +1085,7 @@ var _ = Describe("Items", func() {
})
It("scopes to the user's accessible libraries", func() {
albumRepo := ds.Album(context.Background()).(*tests.MockAlbumRepo)
albumRepo := ds.Album().(*tests.MockAlbumRepo)
albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}})
w := httptest.NewRecorder()
libs := model.Libraries{{ID: 1}, {ID: 2}}

View file

@ -52,7 +52,7 @@ var _ = Describe("getLyrics", func() {
BeforeEach(func() {
ds = &tests.MockDataStore{}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", LibraryID: 1},
{ID: testID("s2"), Title: "Silent Song", LibraryID: 1},
})

View file

@ -162,7 +162,7 @@ func (api *Router) userFromToken(r *http.Request) (model.User, bool) {
if err != nil || claims.Subject == "" {
return model.User{}, false
}
usr, err := api.ds.User(r.Context()).FindByUsername(claims.Subject)
usr, err := api.ds.User().FindByUsername(r.Context(), claims.Subject)
if err != nil {
log.Warn(r.Context(), "Jellyfin API: token subject not found", "user", claims.Subject, err)
return model.User{}, false

View file

@ -18,13 +18,15 @@ import (
)
var _ = Describe("authenticate middleware", func() {
var ctx context.Context
var api *Router
var ds *tests.MockDataStore
BeforeEach(func() {
ctx = GinkgoT().Context()
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
api = &Router{ds: ds}
})
@ -100,9 +102,9 @@ var _ = Describe("authenticate middleware", func() {
var usr *model.User
BeforeEach(func() {
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
ur := ds.User().(*tests.MockedUserRepo)
usr = &model.User{ID: testID("u2"), UserName: "bob", NewPassword: "secret", TokenEpoch: 3}
Expect(ur.Put(usr)).To(Succeed())
Expect(ur.Put(ctx, usr)).To(Succeed())
})
serve := func(token string) *httptest.ResponseRecorder {

View file

@ -48,6 +48,7 @@ type createPlaylistRequest struct {
Name string `json:"Name"`
Ids []string `json:"Ids"`
MediaType string `json:"MediaType"`
IsPublic *bool `json:"IsPublic"`
}
// createPlaylist always creates a new playlist (playlistId "" tells core/playlists.Create not to
@ -69,6 +70,13 @@ func (api *Router) createPlaylist(w http.ResponseWriter, r *http.Request) {
api.internalError(w, r, err)
return
}
// Create takes no visibility, so a requested one costs a second write.
if body.IsPublic != nil {
if err := api.playlists.Update(r.Context(), id, nil, nil, body.IsPublic, nil, nil); err != nil {
api.playlistError(w, r, err)
return
}
}
api.ok(w, r, map[string]string{"Id": dto.EncodeID(id)})
}
@ -138,14 +146,14 @@ func (api *Router) clearPlaylist(ctx context.Context, id string) error {
// playlistTrackPage streams one page of a playlist's tracks. Streams because a playlist can be the
// whole library (a smart playlist matching everything) and clients may omit Limit. Excludes missing
// tracks, and counts the same set, like GetWithTracks.
func (api *Router) playlistTrackPage(repo model.PlaylistTrackRepository, fields dto.Fields, offset, limit int) (itemsResult, error) {
total, err := repo.CountAll(model.QueryOptions{Filters: notMissing})
func (api *Router) playlistTrackPage(ctx context.Context, repo model.PlaylistTrackRepository, fields dto.Fields, offset, limit int) (itemsResult, error) {
total, err := repo.CountAll(ctx, model.QueryOptions{Filters: notMissing})
if err != nil {
return itemsResult{}, err
}
opts := model.QueryOptions{Sort: "id", Offset: offset, Max: limit, Filters: notMissing}
open := streamCursor(func() (func(func(model.PlaylistTrack, error) bool), error) {
return repo.GetCursor(opts)
return repo.GetCursor(ctx, opts)
}, func(t model.PlaylistTrack) dto.BaseItemDto { return trackToBaseItem(t, fields) })
return streamed(open, int(total), offset), nil
}
@ -180,7 +188,7 @@ func (api *Router) getPlaylist(w http.ResponseWriter, r *http.Request) {
return
}
// PlaylistInfo carries every track id, so this can't be paged — but it needs no track data.
trackIDs, err := repo.GetMediaFileIDs(model.QueryOptions{Sort: "id", Filters: notMissing})
trackIDs, err := repo.GetMediaFileIDs(ctx, model.QueryOptions{Sort: "id", Filters: notMissing})
if err != nil {
api.internalError(w, r, err)
return
@ -208,7 +216,7 @@ func (api *Router) getPlaylistItems(w http.ResponseWriter, r *http.Request) {
}
p := req.Params(r)
fields := dto.ParseFields(p.Strings("fields")...)
res, err := api.playlistTrackPage(repo, fields, p.IntOr("startindex", 0), p.IntOr("limit", 0))
res, err := api.playlistTrackPage(ctx, repo, fields, p.IntOr("startindex", 0), p.IntOr("limit", 0))
if err != nil {
api.internalError(w, r, err)
return
@ -241,9 +249,9 @@ func (api *Router) expandContainerIDs(ctx context.Context, ids []string) []strin
for _, id := range ids {
if _, ok := songs[id]; ok {
out = append(out, id) // already a song
} else if _, err := api.ds.Album(ctx).Get(id); err == nil {
} else if _, err := api.ds.Album().Get(ctx, id); err == nil {
out = append(out, api.songIDs(ctx, filter.SongsByAlbum(id))...)
} else if _, err := api.ds.Artist(ctx).Get(id); err == nil {
} else if _, err := api.ds.Artist().Get(ctx, id); err == nil {
out = append(out, api.songIDs(ctx, filter.SongsByArtistID(id))...)
} else if pl, err := api.playlists.GetWithTracks(ctx, id); err == nil {
out = append(out, slice.Map(pl.Tracks, func(t model.PlaylistTrack) string { return t.MediaFileID })...)
@ -255,7 +263,7 @@ func (api *Router) expandContainerIDs(ctx context.Context, ids []string) []strin
}
func (api *Router) songIDs(ctx context.Context, opts model.QueryOptions) []string {
mfs, err := api.ds.MediaFile(ctx).GetAll(opts)
mfs, err := api.ds.MediaFile().GetAll(ctx, opts)
if err != nil {
log.Error(ctx, "Jellyfin: error expanding container to tracks", err)
return nil

View file

@ -55,6 +55,16 @@ type fakePlaylists struct {
deletePlaylistID string
deleteErr error
updatePlaylistID string
updatePublic *bool
updateErr error
}
func (f *fakePlaylists) Update(_ context.Context, playlistID string, _ *string, _ *string, public *bool, _ []string, _ []int) error {
f.updatePlaylistID = playlistID
f.updatePublic = public
return f.updateErr
}
func (f *fakePlaylists) Delete(_ context.Context, id string) error {
@ -184,6 +194,31 @@ var _ = Describe("Playlists", func() {
invoke(api.createPlaylist, w, r)
Expect(w.Code).To(Equal(http.StatusInternalServerError))
})
createReq := func(body string) *http.Request {
return httptest.NewRequest("POST", "/Playlists", strings.NewReader(body)).
WithContext(GinkgoT().Context())
}
DescribeTable("visibility",
func(body string, wantPublic *bool, wantUpdatedID string) {
w := httptest.NewRecorder()
invoke(api.createPlaylist, w, createReq(body))
Expect(w.Code).To(Equal(http.StatusOK))
Expect(fp.updatePublic).To(Equal(wantPublic))
Expect(fp.updatePlaylistID).To(Equal(wantUpdatedID))
},
Entry("applies IsPublic true", `{"Name":"Mix","IsPublic":true}`, new(true), testID("pl-new")),
Entry("applies an explicit IsPublic false", `{"Name":"Mix","IsPublic":false}`, new(false), testID("pl-new")),
Entry("leaves visibility alone when IsPublic is omitted", `{"Name":"Mix"}`, nil, ""),
)
It("returns 500 when the visibility update fails", func() {
fp.updateErr = errors.New("boom")
w := httptest.NewRecorder()
invoke(api.createPlaylist, w, createReq(`{"Name":"Mix","IsPublic":true}`))
Expect(w.Code).To(Equal(http.StatusInternalServerError))
})
})
Describe("getPlaylistItems", func() {
@ -264,27 +299,27 @@ var _ = Describe("Playlists", func() {
}
It("passes a bare song id through unchanged", func() {
ds.MediaFile(ctx).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}})
createWith(testID("s1"))
Expect(fp.createdIds).To(Equal([]string{testID("s1")}))
})
It("expands an album id into its songs, filtered by album", func() {
ds.Album(ctx).(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("al1")}})
ds.MediaFile(ctx).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("al1")}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), AlbumID: testID("al1")}, {ID: testID("s2"), AlbumID: testID("al1")},
})
createWith(testID("al1"))
Expect(fp.createdIds).To(Equal([]string{testID("s1"), testID("s2")}))
Expect(ds.MediaFile(ctx).(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByAlbum(testID("al1")).Filters))
Expect(ds.MediaFile().(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByAlbum(testID("al1")).Filters))
})
It("expands an artist id into its songs", func() {
ds.Artist(ctx).(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1")}})
ds.MediaFile(ctx).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}, {ID: testID("s2")}})
ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1")}})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}, {ID: testID("s2")}})
createWith(testID("ar1"))
Expect(fp.createdIds).To(Equal([]string{testID("s1"), testID("s2")}))
Expect(ds.MediaFile(ctx).(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByArtistID(testID("ar1")).Filters))
Expect(ds.MediaFile().(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByArtistID(testID("ar1")).Filters))
})
It("expands a playlist id into its tracks' media file ids", func() {

View file

@ -77,7 +77,7 @@ func (api *Router) quickConnectAuthorize(w http.ResponseWriter, r *http.Request)
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
usr, err := api.ds.User(ctx).Get(userID)
usr, err := api.ds.User().Get(ctx, userID)
if errors.Is(err, model.ErrNotFound) {
http.Error(w, "Unknown user", http.StatusNotFound)
return
@ -118,7 +118,7 @@ func (api *Router) authenticateWithQuickConnect(w http.ResponseWriter, r *http.R
http.Error(w, "Unknown secret", http.StatusNotFound)
return
}
usr, err := api.ds.User(ctx).Get(userID)
usr, err := api.ds.User().Get(ctx, userID)
if errors.Is(err, model.ErrNotFound) {
log.Warn(ctx, "Jellyfin API: Quick Connect user not found", "userID", userID)
http.Error(w, "Unauthorized", http.StatusUnauthorized)

View file

@ -1,7 +1,6 @@
package jellyfin
import (
"context"
"encoding/json"
"errors"
"net/http"
@ -42,9 +41,9 @@ var _ = Describe("QuickConnect", func() {
conf.Server.Jellyfin.QuickConnect = true
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
ur := ds.User().(*tests.MockedUserRepo)
for _, u := range []model.User{alice, bob, admin} {
Expect(ur.Put(&u)).To(Succeed())
Expect(ur.Put(GinkgoT().Context(), &u)).To(Succeed())
}
qc = quickconnect.New()
api = &Router{ds: ds, quickConnect: qc}
@ -294,7 +293,7 @@ var _ = Describe("QuickConnect", func() {
It("returns 500 when the user lookup fails", func() {
req := initiate()
_, _ = qc.Authorize(req.Code, alice.ID)
ds.User(context.Background()).(*tests.MockedUserRepo).Error = errors.New("db down")
ds.User().(*tests.MockedUserRepo).Error = errors.New("db down")
Expect(redeemSecret(req.Secret).Code).To(Equal(http.StatusInternalServerError))
})
})

View file

@ -216,7 +216,7 @@ func (api *Router) similarAlbums(ctx context.Context, id string, limit int) dto.
continue
}
seen[s.AlbumID] = true
if al, err := api.ds.Album(ctx).Get(s.AlbumID); err == nil && u.HasLibraryAccess(al.LibraryID) {
if al, err := api.ds.Album().Get(ctx, s.AlbumID); err == nil && u.HasLibraryAccess(al.LibraryID) {
items = append(items, dto.AlbumToBaseItem(*al, nil))
if len(items) >= limit {
break

View file

@ -122,7 +122,7 @@ var _ = Describe("getInstantMix", func() {
DeferCleanup(func() { similarWait = old })
ds := &tests.MockDataStore{}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Seed Song", LibraryID: 1},
})
release := make(chan struct{})
@ -150,7 +150,7 @@ var _ = Describe("getInstantMix", func() {
songs = append(songs, model.MediaFile{ID: testID(fmt.Sprintf("t%d", i)), Title: fmt.Sprintf("Track %d", i), LibraryID: 1})
}
ds := &tests.MockDataStore{}
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(songs)
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs)
api := &Router{ds: ds, provider: &fakeSimilarProvider{songs: songs[1:]}}
w := httptest.NewRecorder()
@ -191,7 +191,7 @@ var _ = Describe("getSimilarAlbums", func() {
// With no external agent the provider falls back to the album's own tracks, which map
// straight back to the requested album.
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: testID("al-1"), Name: "Seed Album", LibraryID: 1},
})
api := &Router{ds: ds, provider: &fakeSimilarProvider{
@ -212,7 +212,7 @@ var _ = Describe("getSimilarAlbums", func() {
It("returns albums derived from the provider's similar songs", func() {
ds := &tests.MockDataStore{}
ds.Album(context.Background()).(*tests.MockAlbumRepo).SetData(model.Albums{
ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{
{ID: testID("al-2"), Name: "Other", LibraryID: 1},
})
api := &Router{ds: ds, provider: &fakeSimilarProvider{

View file

@ -1,7 +1,6 @@
package jellyfin
import (
"context"
"net/http"
"net/http/httptest"
"strings"
@ -87,8 +86,8 @@ var _ = Describe("handleSocket", func() {
BeforeEach(func() {
ds = &tests.MockDataStore{}
auth.Init(ds)
ur := ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
ur := ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(GinkgoT().Context(), &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed())
t, err := auth.CreateToken(&model.User{ID: testID("u1"), UserName: "alice"})
Expect(err).ToNot(HaveOccurred())

View file

@ -29,7 +29,7 @@ func (api *Router) mediaFileForRequest(w http.ResponseWriter, r *http.Request) (
if !ok {
return nil, false
}
mf, err := api.ds.MediaFile(ctx).Get(id)
mf, err := api.ds.MediaFile().Get(ctx, id)
if err != nil {
http.Error(w, "Not Found", http.StatusNotFound)
return nil, false

View file

@ -42,7 +42,7 @@ var _ = Describe("Stream", func() {
Describe("getPlaybackInfo", func() {
It("returns a media source for an accessible track", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1},
})
w := httptest.NewRecorder()
@ -61,7 +61,7 @@ var _ = Describe("Stream", func() {
})
It("returns 404 for a track in a library the user can't access", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2},
})
w := httptest.NewRecorder()
@ -102,7 +102,7 @@ var _ = Describe("Stream", func() {
}
It("advertises a Lyric stream for plugin/sidecar-sourced lyrics not embedded in the file", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{
@ -113,7 +113,7 @@ var _ = Describe("Stream", func() {
})
It("advertises no Lyric stream when the pipeline finds nothing", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
@ -121,7 +121,7 @@ var _ = Describe("Stream", func() {
})
It("advertises no Lyric stream when the lyrics endpoint would 404 (main lyric has no lines)", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{
@ -132,7 +132,7 @@ var _ = Describe("Stream", func() {
})
It("doesn't duplicate the Lyric stream when lyrics are already embedded", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1, Lyrics: `[{"lang":"xxx","line":[]}]`},
})
api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{
@ -145,7 +145,7 @@ var _ = Describe("Stream", func() {
It("still returns 200 with a valid MediaSource and no Lyric stream when the lyrics pipeline errors", func() {
// Own ID: an erroring loader isn't cached, but a shared ID could still pick up
// another test's cached (non-error) result and mask this assertion.
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s-err"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1},
})
api.lyrics = &fakeLyricsService{err: errors.New("boom")}
@ -166,7 +166,7 @@ var _ = Describe("Stream", func() {
Describe("streamAudio", func() {
It("invokes the transcode decider and streamer for an accessible track", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
streamer.content = "audio-bytes"
@ -182,7 +182,7 @@ var _ = Describe("Stream", func() {
})
It("returns 404 for a track in a library the user can't access, without invoking the streamer or decider", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2},
})
w := httptest.NewRecorder()
@ -207,7 +207,7 @@ var _ = Describe("Stream", func() {
})
It("converts the bps audioBitRate param to kbps", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1},
})
w := httptest.NewRecorder()
@ -219,7 +219,7 @@ var _ = Describe("Stream", func() {
})
It("uses the audioCodec param as target format when no container is given", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1},
})
w := httptest.NewRecorder()
@ -231,7 +231,7 @@ var _ = Describe("Stream", func() {
})
It("returns 500 and logs when the streamer fails", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
streamer.err = errors.New("boom")
@ -246,7 +246,7 @@ var _ = Describe("Stream", func() {
Describe("HEAD requests", func() {
head := func(query string) *httptest.ResponseRecorder {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1},
})
streamer.content = "audio-bytes"
@ -276,7 +276,7 @@ var _ = Describe("Stream", func() {
Describe("streamUniversal", func() {
universal := func(query string) {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Suffix: "mp3", LibraryID: 1},
})
w := httptest.NewRecorder()
@ -315,7 +315,7 @@ var _ = Describe("Stream", func() {
Describe("streamHls", func() {
BeforeEach(func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "dsf", Duration: 100.5, LibraryID: 1},
})
})
@ -370,21 +370,21 @@ var _ = Describe("Stream", func() {
})
It("returns 404 for a track in a library the user can't access", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "dsf", LibraryID: 2},
})
Expect(hls("", ctxUser()).Code).To(Equal(http.StatusNotFound))
})
It("returns 404 when the id doesn't match any media file", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{})
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{})
Expect(hls("", ctxUser()).Code).To(Equal(http.StatusNotFound))
})
})
Describe("streamFile", func() {
It("invokes the decider with a raw/direct-play request and the streamer for an accessible track", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1},
})
streamer.content = "audio-bytes"
@ -401,7 +401,7 @@ var _ = Describe("Stream", func() {
})
It("returns 404 for a track in a library the user can't access, without invoking the streamer or decider", func() {
ds.MediaFile(context.Background()).(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{
{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2},
})
w := httptest.NewRecorder()

View file

@ -51,11 +51,11 @@ func resolveServerID(ctx context.Context, ds model.DataStore, cached *string) st
*cached = newServerID()
return *cached
}
id, err := ds.Property(ctx).Get(consts.JellyfinServerIDKey)
id, err := ds.Property().Get(ctx, consts.JellyfinServerIDKey)
switch {
case errors.Is(err, model.ErrNotFound):
id = newServerID()
if err := ds.Property(ctx).Put(consts.JellyfinServerIDKey, id); err != nil {
if err := ds.Property().Put(ctx, consts.JellyfinServerIDKey, id); err != nil {
log.Error(ctx, "Jellyfin API: could not persist server id", err)
return id
}

View file

@ -182,10 +182,10 @@ var _ = Describe("System", func() {
})
It("does not overwrite or pin over a stored id when the property read fails transiently", func() {
Expect(ds.Property(ctx).Put(consts.JellyfinServerIDKey, "6ba7b8109dad11d180b400c04fd430c8")).To(Succeed())
Expect(ds.Property().Put(ctx, consts.JellyfinServerIDKey, "6ba7b8109dad11d180b400c04fd430c8")).To(Succeed())
r := &Router{ds: ds}
props := ds.Property(ctx).(*tests.MockedPropertyRepo)
props := ds.Property().(*tests.MockedPropertyRepo)
props.Error = errors.New("database is locked")
degraded := r.serverID(ctx)
Expect(degraded).ToNot(BeEmpty())
@ -194,7 +194,7 @@ var _ = Describe("System", func() {
// Once the DB recovers, the stored id is intact and served again.
Expect(r.serverID(ctx)).To(Equal("6ba7b8109dad11d180b400c04fd430c8"))
stored, err := ds.Property(ctx).Get(consts.JellyfinServerIDKey)
stored, err := ds.Property().Get(ctx, consts.JellyfinServerIDKey)
Expect(err).ToNot(HaveOccurred())
Expect(stored).To(Equal("6ba7b8109dad11d180b400c04fd430c8"))
})
@ -205,7 +205,7 @@ var _ = Describe("System", func() {
})
It("strips dashes from an already-persisted id", func() {
Expect(ds.Property(ctx).Put(
Expect(ds.Property().Put(ctx,
consts.JellyfinServerIDKey, "1b4e28ba-2fa1-11d2-883f-0016d3cca427")).To(Succeed())
r := &Router{ds: ds}
Expect(r.serverID(ctx)).To(Equal("1b4e28ba2fa111d2883f0016d3cca427"))

View file

@ -17,7 +17,7 @@ func (api *Router) getUserViews(w http.ResponseWriter, r *http.Request) {
u, _ := request.UserFrom(ctx)
// u.Libraries comes from a projection without counts or stats, and clients hide a library that
// looks empty, so the rows are re-read in full here.
libs, err := api.ds.Library(ctx).GetAll()
libs, err := api.ds.Library().GetAll(ctx)
if err != nil {
api.internalError(w, r, err)
return
@ -55,7 +55,7 @@ func (api *Router) getPublicUsers(w http.ResponseWriter, r *http.Request) {
continue
}
seen[key] = true
usr, err := api.ds.User(ctx).FindByUsername(name)
usr, err := api.ds.User().FindByUsername(ctx, name)
if err != nil {
log.Warn(ctx, "Jellyfin API: configured public user not found", "username", name, err)
continue

View file

@ -18,10 +18,11 @@ import (
)
var _ = Describe("Users", func() {
var ctx context.Context
var api *Router
// The repo holds the full rows; the user carries the id/name-only copy its projection returns.
authedWithLibraries := func(r *http.Request, libs model.Libraries) *http.Request {
api.ds.Library(context.Background()).(*tests.MockLibraryRepo).SetData(libs)
api.ds.Library().(*tests.MockLibraryRepo).SetData(libs)
stripped := make(model.Libraries, len(libs))
for i, lib := range libs {
stripped[i] = model.Library{ID: lib.ID, Name: lib.Name}
@ -29,7 +30,10 @@ var _ = Describe("Users", func() {
ctx := request.WithUser(context.Background(), model.User{ID: testID("u1"), UserName: "alice", Libraries: stripped})
return r.WithContext(ctx)
}
BeforeEach(func() { api = &Router{ds: &tests.MockDataStore{}} })
BeforeEach(func() {
ctx = GinkgoT().Context()
api = &Router{ds: &tests.MockDataStore{}}
})
Describe("getUserViews", func() {
It("returns one view per accessible library", func() {
@ -117,9 +121,9 @@ var _ = Describe("Users", func() {
BeforeEach(func() {
DeferCleanup(configtest.SetupConfig())
ur = api.ds.User(context.Background()).(*tests.MockedUserRepo)
Expect(ur.Put(&model.User{ID: testID("u1"), UserName: "alice"})).To(Succeed())
Expect(ur.Put(&model.User{ID: testID("u2"), UserName: "bob"})).To(Succeed())
ur = api.ds.User().(*tests.MockedUserRepo)
Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice"})).To(Succeed())
Expect(ur.Put(ctx, &model.User{ID: testID("u2"), UserName: "bob"})).To(Succeed())
})
It("returns an empty list when the config is unset", func() {

View file

@ -380,7 +380,7 @@ func UpdateLastAccessMiddleware(ds model.DataStore) func(next http.Handler) http
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
err := ds.User(ctx).UpdateLastAccessAt(usr.ID)
err := ds.User().UpdateLastAccessAt(ctx, usr.ID)
if err != nil {
log.Warn(ctx, "Could not update user's lastAccessAt", "username", usr.UserName,
"elapsed", time.Since(start), err)

View file

@ -381,7 +381,7 @@ var _ = Describe("middlewares", func() {
id = uuid.NewString()
ds = &tests.MockDataStore{}
lastAccessTime = time.Now()
Expect(ds.User(ctx).Put(&model.User{ID: id, UserName: "johndoe", LastAccessAt: &lastAccessTime})).
Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: "johndoe", LastAccessAt: &lastAccessTime})).
To(Succeed())
middleware = UpdateLastAccessMiddleware(ds)
@ -407,14 +407,14 @@ var _ = Describe("middlewares", func() {
callMiddleware(req)
user, _ := ds.MockedUser.FindByUsername("johndoe")
user, _ := ds.MockedUser.FindByUsername(ctx, "johndoe")
Expect(*user.LastAccessAt).To(BeTemporally(">", lastAccessTime, time.Second))
})
It("skip fast successive requests", func() {
// First request
callMiddleware(req)
user, _ := ds.MockedUser.FindByUsername("johndoe")
user, _ := ds.MockedUser.FindByUsername(ctx, "johndoe")
lastAccessTime = *user.LastAccessAt // Store the last access time
// Second request
@ -422,7 +422,7 @@ var _ = Describe("middlewares", func() {
callMiddleware(req)
// The second request should not have changed the last access time
user, _ = ds.MockedUser.FindByUsername("johndoe")
user, _ = ds.MockedUser.FindByUsername(ctx, "johndoe")
Expect(user.LastAccessAt).To(Equal(&lastAccessTime))
})
})
@ -431,7 +431,7 @@ var _ = Describe("middlewares", func() {
req = req.WithContext(context.Background())
callMiddleware(req)
usr, _ := ds.MockedUser.FindByUsername("johndoe")
usr, _ := ds.MockedUser.FindByUsername(ctx, "johndoe")
Expect(usr.LastAccessAt).To(Equal(&lastAccessTime))
})
})

View file

@ -15,14 +15,12 @@ import (
)
func (api *Router) addArtistRoute(r chi.Router) {
constructor := func(ctx context.Context) rest.Repository {
return api.ds.Resource(ctx, model.Artist{})
}
repo := api.ds.Artist()
r.Route("/artist", func(r chi.Router) {
r.Get("/", rest.GetAll(constructor))
r.Get("/", rest.GetAll(repo))
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Get("/", rest.Get(repo))
r.Post("/image", api.uploadArtistImage())
r.Delete("/image", api.deleteArtistImage())
})
@ -32,7 +30,7 @@ func (api *Router) addArtistRoute(r chi.Router) {
func (api *Router) uploadArtistImage() http.HandlerFunc {
return handleImageUpload(func(ctx context.Context, reader io.Reader, ext string) error {
artistID := chi.URLParamFromCtx(ctx, "id")
ar, err := api.ds.Artist(ctx).Get(artistID)
ar, err := api.ds.Artist().Get(ctx, artistID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return model.ErrNotFound
@ -46,7 +44,7 @@ func (api *Router) uploadArtistImage() http.HandlerFunc {
}
ar.UploadedImage = filename
ar.UpdatedAt = new(time.Now())
if err := api.ds.Artist(ctx).Put(ar, "uploaded_image", "updated_at"); err != nil {
if err := api.ds.Artist().Put(ctx, ar, "uploaded_image", "updated_at"); err != nil {
return err
}
api.imgUpload.EnqueueArtwork(ctx, consts.EntityArtist, ar.ID)
@ -57,7 +55,7 @@ func (api *Router) uploadArtistImage() http.HandlerFunc {
func (api *Router) deleteArtistImage() http.HandlerFunc {
return handleImageDelete(func(ctx context.Context) error {
artistID := chi.URLParamFromCtx(ctx, "id")
ar, err := api.ds.Artist(ctx).Get(artistID)
ar, err := api.ds.Artist().Get(ctx, artistID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return model.ErrNotFound
@ -69,7 +67,7 @@ func (api *Router) deleteArtistImage() http.HandlerFunc {
}
ar.UploadedImage = ""
ar.UpdatedAt = new(time.Now())
if err := api.ds.Artist(ctx).Put(ar, "uploaded_image", "updated_at"); err != nil {
if err := api.ds.Artist().Put(ctx, ar, "uploaded_image", "updated_at"); err != nil {
return err
}
api.imgUpload.EnqueueArtwork(ctx, consts.EntityArtist, ar.ID)

View file

@ -11,6 +11,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
@ -19,17 +20,19 @@ import (
)
var _ = Describe("Config API", func() {
var ctx context.Context
var ds model.DataStore
var router http.Handler
var adminUser, regularUser model.User
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
conf.Server.DevUIShowConfig = true // Enable config endpoint for tests
ds = &tests.MockDataStore{}
auth.Init(ds)
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
// Create test users
@ -49,8 +52,8 @@ var _ = Describe("Config API", func() {
}
// Store in mock datastore
Expect(ds.User(context.TODO()).Put(&adminUser)).To(Succeed())
Expect(ds.User(context.TODO()).Put(&regularUser)).To(Succeed())
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
Expect(ds.User().Put(ctx, &regularUser)).To(Succeed())
})
Describe("GET /api/config", func() {

View file

@ -0,0 +1,49 @@
package nativeapi
import (
"encoding/json"
"net/http"
"net/http/httptest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("writeDeleteManyResponse", func() {
var w *httptest.ResponseRecorder
write := func(ids ...string) map[string]any {
w = httptest.NewRecorder()
writeDeleteManyResponse(w, httptest.NewRequest("DELETE", "/missing", nil), ids)
var body map[string]any
Expect(json.Unmarshal(w.Body.Bytes(), &body)).To(Succeed(), "response body must be valid JSON: %s", w.Body.String())
return body
}
It("returns a single id as an object", func() {
Expect(write("abc123")).To(HaveKeyWithValue("id", "abc123"))
})
It("returns multiple ids as a list", func() {
Expect(write("a", "b")).To(HaveKeyWithValue("ids", ConsistOf("a", "b")))
})
It("stays valid JSON when the id contains a backslash", func() {
Expect(write(`a\`)).To(HaveKeyWithValue("id", `a\`))
})
It("stays valid JSON when the id contains a quote", func() {
Expect(write(`a"b`)).To(HaveKeyWithValue("id", `a"b`))
})
It("does not HTML-escape the id into entities", func() {
Expect(write("a&b")).To(HaveKeyWithValue("id", "a&b"))
})
It("responds 200 with a JSON content type", func() {
write("abc123")
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Type")).To(Equal("application/json"))
})
})

View file

@ -13,7 +13,7 @@ import (
)
func doInspect(ctx context.Context, ds model.DataStore, id string) (*core.InspectOutput, error) {
file, err := ds.MediaFile(ctx).Get(id)
file, err := ds.MediaFile().Get(ctx, id)
if err != nil {
return nil, err
}

View file

@ -13,6 +13,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
@ -21,17 +22,19 @@ import (
)
var _ = Describe("Library API", func() {
var ctx context.Context
var ds model.DataStore
var router http.Handler
var adminUser, regularUser model.User
var library1, library2 model.Library
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
ds = &tests.MockDataStore{}
auth.Init(ds)
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
// Create test users
@ -63,10 +66,10 @@ var _ = Describe("Library API", func() {
}
// Store in mock datastore
Expect(ds.User(context.TODO()).Put(&adminUser)).To(Succeed())
Expect(ds.User(context.TODO()).Put(&regularUser)).To(Succeed())
Expect(ds.Library(context.TODO()).Put(&library1)).To(Succeed())
Expect(ds.Library(context.TODO()).Put(&library2)).To(Succeed())
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
Expect(ds.User().Put(ctx, &regularUser)).To(Succeed())
Expect(ds.Library().Put(ctx, &library1)).To(Succeed())
Expect(ds.Library().Put(ctx, &library2)).To(Succeed())
})
Describe("Library CRUD Operations", func() {
@ -293,7 +296,7 @@ var _ = Describe("Library API", func() {
Describe("GET /api/user/{id}/library", func() {
It("returns user's libraries", func() {
// Set up user libraries
err := ds.User(context.TODO()).SetUserLibraries(regularUser.ID, []int{1, 2})
err := ds.User().SetUserLibraries(ctx, regularUser.ID, []int{1, 2})
Expect(err).ToNot(HaveOccurred())
req := createAuthenticatedRequest("GET", fmt.Sprintf("/user/%s/library", regularUser.ID), nil, adminToken)

View file

@ -11,6 +11,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/external"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
@ -38,6 +39,7 @@ func (f *fakeProvider) calls() []string {
}
var _ = Describe("Metadata API", func() {
var ctx context.Context
var ds *tests.MockDataStore
var artRepo *tests.MockArtworkRepo
var queueRepo *tests.MockArtworkQueueRepo
@ -47,6 +49,7 @@ var _ = Describe("Metadata API", func() {
var adminToken, userToken string
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
artRepo = tests.CreateMockArtworkRepo()
@ -54,9 +57,9 @@ var _ = Describe("Metadata API", func() {
albumRepo = tests.CreateMockAlbumRepo()
artistRepo := tests.CreateMockArtistRepo()
playlistRepo := tests.CreateMockPlaylistRepo()
Expect(albumRepo.Put(&model.Album{ID: "al-1", Name: "Kid A"})).To(Succeed())
Expect(artistRepo.Put(&model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
Expect(playlistRepo.Put(&model.Playlist{ID: "pl-1", Name: "My Playlist"})).To(Succeed())
Expect(albumRepo.Put(ctx, &model.Album{ID: "al-1", Name: "Kid A"})).To(Succeed())
Expect(artistRepo.Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed())
Expect(playlistRepo.Put(ctx, &model.Playlist{ID: "pl-1", Name: "My Playlist"})).To(Succeed())
ds = &tests.MockDataStore{
MockedArtwork: artRepo,
MockedArtworkQueue: queueRepo,
@ -66,13 +69,13 @@ var _ = Describe("Metadata API", func() {
}
auth.Init(ds)
provider = &fakeProvider{}
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, provider, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, provider, nil)
router = server.JWTVerifier(nativeRouter)
adminUser := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true, NewPassword: "adminpass"}
regularUser := model.User{ID: "user-1", UserName: "regular", IsAdmin: false, NewPassword: "userpass"}
Expect(ds.User(context.TODO()).Put(&adminUser)).To(Succeed())
Expect(ds.User(context.TODO()).Put(&regularUser)).To(Succeed())
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
Expect(ds.User().Put(ctx, &regularUser)).To(Succeed())
var err error
adminToken, err = auth.CreateToken(&adminUser)
@ -83,7 +86,7 @@ var _ = Describe("Metadata API", func() {
Describe("POST /api/metadata/{kind}/{id}/refresh", func() {
It("clears state and enqueues a Bump for admins", func() {
Expect(artRepo.PutItemArtwork(&model.ItemArtwork{
Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{
ItemKind: "al", ItemID: "al-1", Hash: "oldhash", Source: "external",
})).To(Succeed())
@ -93,10 +96,10 @@ var _ = Describe("Metadata API", func() {
Expect(w.Code).To(Equal(http.StatusNoContent))
_, err := artRepo.GetItemArtwork(model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
_, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary)
Expect(err).To(MatchError(model.ErrNotFound))
queued, err := queueRepo.DequeueBatch(1000)
queued, err := queueRepo.DequeueBatch(ctx, 1000)
Expect(err).ToNot(HaveOccurred())
Expect(queued).To(ContainElement(SatisfyAll(
HaveField("ItemKind", "al"),

View file

@ -14,24 +14,21 @@ import (
)
type missingRepository struct {
model.ResourceRepository
rest.Repository[model.MediaFile]
mfRepo model.MediaFileRepository
}
func newMissingRepository(ds model.DataStore) rest.RepositoryConstructor {
return func(ctx context.Context) rest.Repository {
return &missingRepository{mfRepo: ds.MediaFile(ctx), ResourceRepository: ds.Resource(ctx, model.MediaFile{})}
}
func newMissingRepository(ds model.DataStore) rest.Repository[model.MediaFile] {
mf := ds.MediaFile()
return &missingRepository{Repository: mf, mfRepo: mf}
}
func (r *missingRepository) Count(options ...rest.QueryOptions) (int64, error) {
opt := r.parseOptions(options)
return r.ResourceRepository.Count(opt)
func (r *missingRepository) Count(ctx context.Context, options ...rest.QueryOptions) (int64, error) {
return r.Repository.Count(ctx, r.parseOptions(options))
}
func (r *missingRepository) ReadAll(options ...rest.QueryOptions) (any, error) {
opt := r.parseOptions(options)
return r.ResourceRepository.ReadAll(opt)
func (r *missingRepository) ReadAll(ctx context.Context, options ...rest.QueryOptions) ([]model.MediaFile, error) {
return r.Repository.ReadAll(ctx, r.parseOptions(options))
}
func (r *missingRepository) parseOptions(options []rest.QueryOptions) rest.QueryOptions {
@ -44,8 +41,8 @@ func (r *missingRepository) parseOptions(options []rest.QueryOptions) rest.Query
return opt
}
func (r *missingRepository) Read(id string) (any, error) {
mf, err := r.mfRepo.Get(id)
func (r *missingRepository) Read(ctx context.Context, id string) (*model.MediaFile, error) {
mf, err := r.mfRepo.Get(ctx, id)
if err != nil {
return nil, err
}
@ -55,10 +52,6 @@ func (r *missingRepository) Read(id string) (any, error) {
return mf, nil
}
func (r *missingRepository) EntityName() string {
return "missing_files"
}
func deleteMissingFiles(maintenance core.Maintenance) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
@ -86,5 +79,3 @@ func deleteMissingFiles(maintenance core.Maintenance) http.HandlerFunc {
writeDeleteManyResponse(w, r, ids)
}
}
var _ model.ResourceRepository = &missingRepository{}

View file

@ -9,6 +9,7 @@ import (
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
@ -35,12 +36,12 @@ var _ = Describe("Missing Files Endpoint", func() {
auth.Init(ds)
user := model.User{ID: "user-1", UserName: "user", NewPassword: "pass"}
Expect(userRepo.Put(&user)).To(Succeed())
Expect(userRepo.Put(GinkgoT().Context(), &user)).To(Succeed())
var err error
token, err = auth.CreateToken(&user)
Expect(err).ToNot(HaveOccurred())
router = server.JWTVerifier(New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil))
router = server.JWTVerifier(New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil))
})
DescribeTable("GET /missing/{id}",

View file

@ -2,8 +2,6 @@ package nativeapi
import (
"context"
"encoding/json"
"html"
"net/http"
"strconv"
"time"
@ -62,26 +60,26 @@ func (api *Router) routes() http.Handler {
r := chi.NewRouter()
// Public
api.RX(r, "/translation", newTranslationRepository, false)
rx(r, "/translation", newTranslationRepository(), false)
// Protected
r.Group(func(r chi.Router) {
r.Use(server.Authenticator(api.ds))
r.Use(server.JWTRefresher)
r.Use(server.UpdateLastAccessMiddleware(api.ds))
api.RX(r, "/user", api.users.NewRepository, true)
api.R(r, "/song", model.MediaFile{}, false)
api.R(r, "/album", model.Album{}, false)
rx(r, "/user", api.users.Repository(), true)
rx(r, "/song", api.ds.MediaFile(), false)
rx(r, "/album", api.ds.Album(), false)
api.addArtistRoute(r)
api.R(r, "/genre", model.Genre{}, false)
api.R(r, "/player", model.Player{}, true)
api.R(r, "/transcoding", model.Transcoding{}, conf.Server.EnableTranscodingConfig)
rx(r, "/genre", api.ds.Genre(), false)
rx(r, "/player", api.ds.Player(), true)
rx(r, "/transcoding", api.ds.Transcoding(), conf.Server.EnableTranscodingConfig)
api.addRadioRoute(r)
api.addPodcastRoute(r)
api.R(r, "/tag", model.Tag{}, false)
api.R(r, "/scrobble", model.Scrobble{}, false)
rx(r, "/tag", api.ds.Tag(), false)
rx(r, "/scrobble", api.ds.Scrobble(), false)
if conf.Server.EnableSharing {
api.RX(r, "/share", api.share.NewRepository, true)
rx(r, "/share", api.share.Repository(), true)
}
api.addPlaylistRoute(r)
@ -99,47 +97,38 @@ func (api *Router) routes() http.Handler {
api.addUserLibraryRoute(r)
api.addPluginRoute(r)
api.addMetadataRoute(r)
api.RX(r, "/library", api.libs.NewRepository, true)
rx(r, "/library", api.libs.Repository(), true)
})
})
return r
}
func (api *Router) R(r chi.Router, pathPrefix string, model any, persistable bool) {
constructor := func(ctx context.Context) rest.Repository {
return api.ds.Resource(ctx, model)
}
api.RX(r, pathPrefix, constructor, persistable)
}
func (api *Router) RX(r chi.Router, pathPrefix string, constructor rest.RepositoryConstructor, persistable bool) {
func rx[T any](r chi.Router, pathPrefix string, repo rest.Repository[T], persistable bool) {
r.Route(pathPrefix, func(r chi.Router) {
r.Get("/", rest.GetAll(constructor))
r.Get("/", rest.GetAll(repo))
if persistable {
r.Post("/", rest.Post(constructor))
r.Post("/", rest.Post(repo))
}
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Get("/", rest.Get(repo))
if persistable {
r.Put("/", rest.Put(constructor))
r.Delete("/", rest.Delete(constructor))
r.Put("/", rest.Put(repo))
r.Delete("/", rest.Delete(repo))
}
})
})
}
func (api *Router) addPlaylistRoute(r chi.Router) {
constructor := func(ctx context.Context) rest.Repository {
return api.playlists.NewRepository(ctx)
}
repo := api.playlists.Repository()
r.Route("/playlist", func(r chi.Router) {
r.Get("/", rest.GetAll(constructor))
r.Get("/", rest.GetAll(repo))
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") == "application/json" {
rest.Post(constructor)(w, r)
rest.Post(repo)(w, r)
return
}
createPlaylistFromM3U(api.playlists)(w, r)
@ -147,9 +136,9 @@ func (api *Router) addPlaylistRoute(r chi.Router) {
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Put("/", rest.Put(constructor))
r.Delete("/", rest.Delete(constructor))
r.Get("/", rest.Get(repo))
r.Put("/", rest.Put(repo))
r.Delete("/", rest.Delete(repo))
r.Post("/image", uploadPlaylistImage(api.playlists))
r.Delete("/image", deletePlaylistImage(api.playlists))
})
@ -201,28 +190,24 @@ func (api *Router) addQueueRoute(r chi.Router) {
func (api *Router) addMissingFilesRoute(r chi.Router) {
r.Route("/missing", func(r chi.Router) {
api.RX(r, "/", newMissingRepository(api.ds), false)
rx(r, "/", newMissingRepository(api.ds), false)
r.Delete("/", deleteMissingFiles(api.maintenance))
})
}
func writeDeleteManyResponse(w http.ResponseWriter, r *http.Request, ids []string) {
var resp []byte
var err error
var payload any
if len(ids) == 1 {
resp = []byte(`{"id":"` + html.EscapeString(ids[0]) + `"}`)
payload = struct {
ID string `json:"id"`
}{ID: ids[0]}
} else {
resp, err = json.Marshal(&struct {
payload = struct {
Ids []string `json:"ids"`
}{Ids: ids})
if err != nil {
log.Error(r.Context(), "Error marshaling response", "ids", ids, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}{Ids: ids}
}
_, err = w.Write(resp) //nolint:gosec
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
if err := rest.RespondWithJSON(w, http.StatusOK, payload); err != nil {
log.Error(r.Context(), "Error writing response", "ids", ids, err)
}
}

View file

@ -2,6 +2,7 @@ package nativeapi
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@ -12,6 +13,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
"github.com/navidrome/navidrome/tests"
@ -21,6 +23,7 @@ import (
var _ = Describe("Song Endpoints", func() {
var (
ctx context.Context
router http.Handler
ds *tests.MockDataStore
mfRepo *tests.MockMediaFileRepo
@ -31,6 +34,7 @@ var _ = Describe("Song Endpoints", func() {
)
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
conf.Server.SessionTimeout = time.Minute
@ -56,7 +60,7 @@ var _ = Describe("Song Endpoints", func() {
IsAdmin: false,
NewPassword: "testpass",
}
err := userRepo.Put(&testUser)
err := userRepo.Put(ctx, &testUser)
Expect(err).ToNot(HaveOccurred())
// Create test songs
@ -95,7 +99,7 @@ var _ = Describe("Song Endpoints", func() {
mfRepo.SetData(testSongs)
// Create the native API router and wrap it with the JWTVerifier middleware
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
w = httptest.NewRecorder()
})
@ -369,7 +373,7 @@ var _ = Describe("Song Endpoints", func() {
IsAdmin: true,
NewPassword: "adminpass",
}
err := userRepo.Put(&adminUser)
err := userRepo.Put(ctx, &adminUser)
Expect(err).ToNot(HaveOccurred())
// Create JWT token for admin user
@ -392,7 +396,7 @@ var _ = Describe("Song Endpoints", func() {
IsAdmin: false,
NewPassword: "userpass",
}
err := userRepo.Put(&regularUser)
err := userRepo.Put(ctx, &regularUser)
Expect(err).ToNot(HaveOccurred())
// Create JWT token for regular user

View file

@ -16,10 +16,9 @@ import (
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/req"
"github.com/navidrome/navidrome/utils/str"
)
type restHandler = func(rest.RepositoryConstructor, ...rest.Logger) http.HandlerFunc
// writePlaylistError maps a playlist service error to an HTTP status, or defaultStatus if unknown.
func writePlaylistError(w http.ResponseWriter, err error, defaultStatus int) {
switch {
@ -34,7 +33,7 @@ func writePlaylistError(w http.ResponseWriter, err error, defaultStatus int) {
}
}
func playlistTracksHandler(pls playlists.Playlists, handler restHandler, refreshSmartPlaylist func(*http.Request) bool) http.HandlerFunc {
func playlistTracksHandler(pls playlists.Playlists, handler func(rest.Repository[model.PlaylistTrack]) http.HandlerFunc, refreshSmartPlaylist func(*http.Request) bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
plsId := chi.URLParam(r, "playlistId")
tracks := pls.TracksRepository(r.Context(), plsId, refreshSmartPlaylist(r))
@ -42,12 +41,12 @@ func playlistTracksHandler(pls playlists.Playlists, handler restHandler, refresh
http.Error(w, "not found", http.StatusNotFound)
return
}
handler(func(ctx context.Context) rest.Repository { return tracks }).ServeHTTP(w, r)
handler(tracks).ServeHTTP(w, r)
}
}
func getPlaylist(pls playlists.Playlists) http.HandlerFunc {
handler := playlistTracksHandler(pls, rest.GetAll, func(r *http.Request) bool {
handler := playlistTracksHandler(pls, rest.GetAll[model.PlaylistTrack], func(r *http.Request) bool {
return req.Params(r).Int64Or("_start", 0) == 0
})
return func(w http.ResponseWriter, r *http.Request) {
@ -60,7 +59,7 @@ func getPlaylist(pls playlists.Playlists) http.HandlerFunc {
}
func getPlaylistTrack(pls playlists.Playlists) http.HandlerFunc {
return playlistTracksHandler(pls, rest.Get, func(*http.Request) bool { return true })
return playlistTracksHandler(pls, rest.Get[model.PlaylistTrack], func(*http.Request) bool { return true })
}
func createPlaylistFromM3U(pls playlists.Playlists) http.HandlerFunc {
@ -101,8 +100,7 @@ func handleExportPlaylist(pls playlists.Playlists) http.HandlerFunc {
log.Debug(ctx, "Exporting playlist as M3U", "playlistId", plsId, "name", playlist.Name)
w.Header().Set("Content-Type", "audio/x-mpegurl")
disposition := fmt.Sprintf("attachment; filename=\"%s.m3u\"", playlist.Name)
w.Header().Set("Content-Disposition", disposition)
w.Header().Set("Content-Disposition", str.ContentDispositionAttachment(playlist.Name+".m3u"))
_, err = w.Write([]byte(playlist.ToM3U8())) //nolint:gosec
if err != nil {

View file

@ -9,6 +9,7 @@ import (
"time"
"github.com/deluan/rest"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
@ -96,7 +97,7 @@ var _ = Describe("Playlist Tracks Endpoint", func() {
IsAdmin: false,
NewPassword: "testpass",
}
err := userRepo.Put(&testUser)
err := userRepo.Put(GinkgoT().Context(), &testUser)
Expect(err).ToNot(HaveOccurred())
nativeRouter := New(ds, nil, plsSvc, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)
@ -183,6 +184,37 @@ var _ = Describe("Playlist Tracks Endpoint", func() {
})
})
var _ = Describe("handleExportPlaylist", func() {
export := func(name string) *httptest.ResponseRecorder {
r := chi.NewRouter()
r.Get("/playlist/{playlistId}", handleExportPlaylist(&mockPlaylistsService{
playlist: &model.Playlist{ID: "pls-1", Name: name},
}))
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/playlist/pls-1", nil))
return w
}
It("names the download after the playlist", func() {
w := export("Road Trip")
Expect(w.Code).To(Equal(http.StatusOK))
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="Road Trip.m3u"`))
})
It("does not let the playlist name inject a second filename parameter", func() {
w := export(`party"; filename="evil.html`)
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="party_; filename=_evil.html.m3u"`))
})
It("keeps non-ASCII names in filename*", func() {
w := export("Кино")
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="download.m3u"; filename*=utf-8''%D0%9A%D0%B8%D0%BD%D0%BE.m3u`))
})
})
var _ = Describe("writePlaylistError", func() {
DescribeTable("maps a service error to an HTTP status",
func(err error, expected int) {
@ -203,23 +235,15 @@ type mockPlaylistTrackRepo struct {
tracks model.PlaylistTracks
}
func (m *mockPlaylistTrackRepo) Count(...rest.QueryOptions) (int64, error) {
func (m *mockPlaylistTrackRepo) Count(context.Context, ...rest.QueryOptions) (int64, error) {
return int64(len(m.tracks)), nil
}
func (m *mockPlaylistTrackRepo) ReadAll(...rest.QueryOptions) (any, error) {
func (m *mockPlaylistTrackRepo) ReadAll(context.Context, ...rest.QueryOptions) ([]model.PlaylistTrack, error) {
return m.tracks, nil
}
func (m *mockPlaylistTrackRepo) EntityName() string {
return "playlist_track"
}
func (m *mockPlaylistTrackRepo) NewInstance() any {
return &model.PlaylistTrack{}
}
func (m *mockPlaylistTrackRepo) Read(id string) (any, error) {
func (m *mockPlaylistTrackRepo) Read(_ context.Context, id string) (*model.PlaylistTrack, error) {
for _, t := range m.tracks {
if t.ID == id {
return &t, nil
@ -230,7 +254,9 @@ func (m *mockPlaylistTrackRepo) Read(id string) (any, error) {
type mockPlaylistsService struct {
playlists.Playlists
tracksRepo rest.Repository
repo rest.Repository[model.Playlist]
tracksRepo rest.Repository[model.PlaylistTrack]
playlist *model.Playlist
removeImageFn func(ctx context.Context, id string) error
setImageFn func(ctx context.Context, id string, reader io.Reader, ext string) error
}
@ -249,6 +275,17 @@ func (m *mockPlaylistsService) SetImage(ctx context.Context, id string, reader i
return model.ErrNotFound
}
func (m *mockPlaylistsService) TracksRepository(_ context.Context, _ string, _ bool) rest.Repository {
func (m *mockPlaylistsService) Repository() rest.Repository[model.Playlist] {
return m.repo
}
func (m *mockPlaylistsService) GetWithTracks(_ context.Context, _ string) (*model.Playlist, error) {
if m.playlist == nil {
return nil, model.ErrNotFound
}
return m.playlist, nil
}
func (m *mockPlaylistsService) TracksRepository(_ context.Context, _ string, _ bool) rest.Repository[model.PlaylistTrack] {
return m.tracksRepo
}

View file

@ -15,17 +15,15 @@ import (
)
func (api *Router) addPluginRoute(r chi.Router) {
constructor := func(ctx context.Context) rest.Repository {
return api.ds.Plugin(ctx)
}
repo := api.ds.Plugin()
r.Route("/plugin", func(r chi.Router) {
r.Use(pluginsEnabledMiddleware)
r.Get("/", rest.GetAll(constructor))
r.Get("/", rest.GetAll(repo))
r.Post("/rescan", api.rescanPlugins)
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Get("/", rest.Get(repo))
r.Put("/", api.updatePlugin)
})
})
@ -68,10 +66,10 @@ type PluginUpdateRequest struct {
func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
ctx := r.Context()
repo := api.ds.Plugin(ctx)
repo := api.ds.Plugin()
// Get existing plugin to verify it exists
if _, err := repo.Get(id); err != nil {
if _, err := repo.Get(ctx, id); err != nil {
if errors.Is(err, rest.ErrPermissionDenied) {
http.Error(w, "Access denied: admin privileges required", http.StatusForbidden)
return
@ -123,7 +121,7 @@ func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) {
if enableErr := api.pluginManager.EnablePlugin(ctx, id); enableErr != nil {
log.Error(ctx, "Error enabling plugin", "id", id, enableErr)
// Refresh plugin from DB to get the error
plugin, err := repo.Get(id)
plugin, err := repo.Get(ctx, id)
if err != nil {
log.Error(ctx, "Error getting updated plugin after enable failure", "id", id, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
@ -153,7 +151,7 @@ func (api *Router) updatePlugin(w http.ResponseWriter, r *http.Request) {
}
// Refresh and return updated plugin
plugin, err := repo.Get(id)
plugin, err := repo.Get(ctx, id)
if err != nil {
log.Error(ctx, "Error getting updated plugin", "id", id, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
@ -204,7 +202,7 @@ func validateAndUpdateConfig(ctx context.Context, pm PluginManager, id, configJS
// Returns an error if validation or update fails (error response already written).
func validateAndUpdateUsers(ctx context.Context, pm PluginManager, repo model.PluginRepository, id string, req PluginUpdateRequest, w http.ResponseWriter) error {
// Get current values if not provided in request
plugin, err := repo.Get(id)
plugin, err := repo.Get(ctx, id)
if err != nil {
log.Error(ctx, "Error getting plugin for users update", "id", id, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
@ -237,7 +235,7 @@ func validateAndUpdateUsers(ctx context.Context, pm PluginManager, repo model.Pl
// Returns an error if validation or update fails (error response already written).
func validateAndUpdateLibraries(ctx context.Context, pm PluginManager, repo model.PluginRepository, id string, req PluginUpdateRequest, w http.ResponseWriter) error {
// Get current values if not provided in request
plugin, err := repo.Get(id)
plugin, err := repo.Get(ctx, id)
if err != nil {
log.Error(ctx, "Error getting plugin for libraries update", "id", id, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)

View file

@ -12,6 +12,7 @@ import (
"github.com/navidrome/navidrome/conf/configtest"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server"
@ -21,6 +22,7 @@ import (
)
var _ = Describe("Plugin API", func() {
var ctx context.Context
var ds *tests.MockDataStore
var mockManager *tests.MockPluginManager
var router http.Handler
@ -28,13 +30,14 @@ var _ = Describe("Plugin API", func() {
var testPlugin1, testPlugin2 model.Plugin
BeforeEach(func() {
ctx = GinkgoT().Context()
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableSharing = false
conf.Server.Plugins.Enabled = true
ds = &tests.MockDataStore{}
mockManager = &tests.MockPluginManager{}
auth.Init(ds)
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
// Create test users
@ -71,8 +74,8 @@ var _ = Describe("Plugin API", func() {
}
// Store users in mock datastore
Expect(ds.User(GinkgoT().Context()).Put(&adminUser)).To(Succeed())
Expect(ds.User(GinkgoT().Context()).Put(&regularUser)).To(Succeed())
Expect(ds.User().Put(ctx, &adminUser)).To(Succeed())
Expect(ds.User().Put(ctx, &regularUser)).To(Succeed())
})
Context("when plugins are disabled", func() {
@ -104,10 +107,9 @@ var _ = Describe("Plugin API", func() {
Expect(err).ToNot(HaveOccurred())
// Store test plugins as admin
ctx := GinkgoT().Context()
adminCtx := request.WithUser(ctx, adminUser)
Expect(ds.Plugin(adminCtx).Put(&testPlugin1)).To(Succeed())
Expect(ds.Plugin(adminCtx).Put(&testPlugin2)).To(Succeed())
Expect(ds.Plugin().Put(adminCtx, &testPlugin1)).To(Succeed())
Expect(ds.Plugin().Put(adminCtx, &testPlugin2)).To(Succeed())
})
Describe("GET /api/plugin", func() {
@ -160,9 +162,9 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when EnablePlugin is called
mockManager.EnablePluginFn = func(ctx context.Context, id string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Enabled = true
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"enabled":true}`)
@ -186,9 +188,9 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginConfig is called
mockManager.UpdatePluginConfigFn = func(ctx context.Context, id, configJSON string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Config = configJSON
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"config":"{\"key\":\"value\"}"}`)
@ -226,9 +228,9 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginConfig is called
mockManager.UpdatePluginConfigFn = func(ctx context.Context, id, configJSON string) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Config = configJSON
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"config":""}`)
@ -251,10 +253,10 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":"[\"user1\",\"user2\"]"}`)
@ -279,10 +281,10 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"allUsers":true}`)
@ -307,10 +309,10 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":"[\"user1\"]","allUsers":false}`)
@ -348,10 +350,10 @@ var _ = Describe("Plugin API", func() {
// Configure mock to update the repo when UpdatePluginUsers is called
mockManager.UpdatePluginUsersFn = func(ctx context.Context, id, usersJSON string, allUsers bool) error {
adminCtx := request.WithUser(ctx, adminUser)
p, _ := ds.Plugin(adminCtx).Get(id)
p, _ := ds.Plugin().Get(adminCtx, id)
p.Users = usersJSON
p.AllUsers = allUsers
return ds.Plugin(adminCtx).Put(p)
return ds.Plugin().Put(adminCtx, p)
}
body := bytes.NewBufferString(`{"users":""}`)

View file

@ -1,28 +1,24 @@
package nativeapi
import (
"context"
"encoding/json"
"net/http"
"github.com/deluan/rest"
"github.com/go-chi/chi/v5"
"github.com/navidrome/navidrome/core/podcasts"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server"
)
func (api *Router) addPodcastRoute(r chi.Router) {
constructor := func(ctx context.Context) rest.Repository {
return api.ds.Resource(ctx, model.PodcastChannel{})
}
repo := api.ds.PodcastChannel()
r.Route("/podcast", func(r chi.Router) {
r.Get("/", rest.GetAll(constructor))
r.Get("/", rest.GetAll(repo))
r.With(adminOnlyMiddleware).Get("/preview", api.podcastPreview)
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Delete("/", rest.Delete(constructor))
r.Get("/", rest.Get(repo))
r.Delete("/", rest.Delete(repo))
})
})
}
@ -38,7 +34,7 @@ func (api *Router) podcastPreview(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
exists, _ := api.ds.PodcastChannel(r.Context()).ExistsByURL(feedURL)
exists, _ := api.ds.PodcastChannel().ExistsByURL(r.Context(), feedURL)
feed.AlreadyExists = exists
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(feed)

View file

@ -32,7 +32,7 @@ func validateCurrentIndex(w http.ResponseWriter, current int, itemsLength int) b
// retrieveExistingQueue retrieves an existing play queue for a user with proper error handling.
// Returns the queue (nil if not found) and false if an error occurred and response was sent.
func retrieveExistingQueue(ctx context.Context, w http.ResponseWriter, ds model.DataStore, userID string) (*model.PlayQueue, bool) {
existing, err := ds.PlayQueue(ctx).Retrieve(userID)
existing, err := ds.PlayQueue().Retrieve(ctx, userID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Error retrieving queue", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -70,8 +70,8 @@ func getQueue(ds model.DataStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, _ := request.UserFrom(ctx)
repo := ds.PlayQueue(ctx)
pq, err := repo.RetrieveWithMediaFiles(user.ID)
repo := ds.PlayQueue()
pq, err := repo.RetrieveWithMediaFiles(ctx, user.ID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Error retrieving queue", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -112,7 +112,7 @@ func saveQueue(ds model.DataStore) http.HandlerFunc {
ChangedBy: client,
Items: items,
}
if err := ds.PlayQueue(ctx).Store(pq); err != nil {
if err := ds.PlayQueue().Store(ctx, pq); err != nil {
log.Error(ctx, "Error saving queue", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -191,7 +191,7 @@ func updateQueue(ds model.DataStore) http.HandlerFunc {
}
// Perform partial update of the specified columns only
if err := ds.PlayQueue(ctx).Store(pq, cols...); err != nil {
if err := ds.PlayQueue().Store(ctx, pq, cols...); err != nil {
log.Error(ctx, "Error updating queue", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -204,7 +204,7 @@ func clearQueue(ds model.DataStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, _ := request.UserFrom(ctx)
if err := ds.PlayQueue(ctx).Clear(user.ID); err != nil {
if err := ds.PlayQueue().Clear(ctx, user.ID); err != nil {
log.Error(ctx, "Error clearing queue", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return

View file

@ -25,7 +25,7 @@ var _ = Describe("Queue Endpoints", func() {
repo = &tests.MockPlayQueueRepo{}
user = model.User{ID: "u1", UserName: "user"}
userRepo = tests.CreateMockUserRepo()
_ = userRepo.Put(&user)
_ = userRepo.Put(GinkgoT().Context(), &user)
ds = &tests.MockDataStore{MockedPlayQueue: repo, MockedUser: userRepo, MockedProperty: &tests.MockedPropertyRepo{}}
})

View file

@ -14,17 +14,15 @@ import (
)
func (api *Router) addRadioRoute(r chi.Router) {
constructor := func(ctx context.Context) rest.Repository {
return api.ds.Resource(ctx, model.Radio{})
}
repo := api.ds.Radio()
r.Route("/radio", func(r chi.Router) {
r.Get("/", rest.GetAll(constructor))
r.Post("/", rest.Post(constructor))
r.Get("/", rest.GetAll(repo))
r.Post("/", rest.Post(repo))
r.Route("/{id}", func(r chi.Router) {
r.Use(server.URLParamsMiddleware)
r.Get("/", rest.Get(constructor))
r.Put("/", rest.Put(constructor))
r.Delete("/", rest.Delete(constructor))
r.Get("/", rest.Get(repo))
r.Put("/", rest.Put(repo))
r.Delete("/", rest.Delete(repo))
r.Post("/image", api.uploadRadioImage())
r.Delete("/image", api.deleteRadioImage())
})
@ -34,7 +32,7 @@ func (api *Router) addRadioRoute(r chi.Router) {
func (api *Router) uploadRadioImage() http.HandlerFunc {
return handleImageUpload(func(ctx context.Context, reader io.Reader, ext string) error {
radioID := chi.URLParamFromCtx(ctx, "id")
radio, err := api.ds.Radio(ctx).Get(radioID)
radio, err := api.ds.Radio().Get(ctx, radioID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return model.ErrNotFound
@ -47,7 +45,7 @@ func (api *Router) uploadRadioImage() http.HandlerFunc {
return err
}
radio.UploadedImage = filename
if err := api.ds.Radio(ctx).Put(radio, "UploadedImage"); err != nil {
if err := api.ds.Radio().Put(ctx, radio, "UploadedImage"); err != nil {
return err
}
api.imgUpload.EnqueueArtwork(ctx, consts.EntityRadio, radio.ID)
@ -58,7 +56,7 @@ func (api *Router) uploadRadioImage() http.HandlerFunc {
func (api *Router) deleteRadioImage() http.HandlerFunc {
return handleImageDelete(func(ctx context.Context) error {
radioID := chi.URLParamFromCtx(ctx, "id")
radio, err := api.ds.Radio(ctx).Get(radioID)
radio, err := api.ds.Radio().Get(ctx, radioID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return model.ErrNotFound
@ -69,7 +67,7 @@ func (api *Router) deleteRadioImage() http.HandlerFunc {
return err
}
radio.UploadedImage = ""
if err := api.ds.Radio(ctx).Put(radio, "UploadedImage"); err != nil {
if err := api.ds.Radio().Put(ctx, radio, "UploadedImage"); err != nil {
return err
}
api.imgUpload.EnqueueArtwork(ctx, consts.EntityRadio, radio.ID)

View file

@ -23,28 +23,28 @@ type translation struct {
TermCount int `json:"termCount"`
}
func newTranslationRepository(context.Context) rest.Repository {
func newTranslationRepository() rest.Repository[translation] {
return &translationRepository{}
}
type translationRepository struct{}
func (r *translationRepository) Read(id string) (any, error) {
func (r *translationRepository) Read(_ context.Context, id string) (*translation, error) {
translations, _ := loadTranslations()
if t, ok := translations[id]; ok {
return t, nil
return &t, nil
}
return nil, rest.ErrNotFound
}
// Count simple implementation, does not support any `options`
func (r *translationRepository) Count(...rest.QueryOptions) (int64, error) {
func (r *translationRepository) Count(context.Context, ...rest.QueryOptions) (int64, error) {
_, count := loadTranslations()
return count, nil
}
// ReadAll simple implementation, only returns IDs. Does not support any `options`
func (r *translationRepository) ReadAll(...rest.QueryOptions) (any, error) {
func (r *translationRepository) ReadAll(context.Context, ...rest.QueryOptions) ([]translation, error) {
translations, _ := loadTranslations()
var result []translation
for _, t := range translations {
@ -54,14 +54,6 @@ func (r *translationRepository) ReadAll(...rest.QueryOptions) (any, error) {
return result, nil
}
func (r *translationRepository) EntityName() string {
return "translation"
}
func (r *translationRepository) NewInstance() any {
return &translation{}
}
var loadTranslations = sync.OnceValues(func() (map[string]translation, int64) {
translations := make(map[string]translation)
fsys := resources.FS()
@ -140,4 +132,4 @@ func countTranslatedTerms(obj map[string]any) int {
return count
}
var _ rest.Repository = (*translationRepository)(nil)
var _ rest.Repository[translation] = (*translationRepository)(nil)

View file

@ -14,6 +14,7 @@ import (
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/core/playlists"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/persistence"
@ -29,10 +30,12 @@ func (noopPluginUnloader) UnloadDisabledPlugins(context.Context) {}
// Pins that the token-epoch handoff survives a real request through the real middleware chain.
var _ = Describe("PUT /user/{id}: token refresh on self password change", func() {
var ctx context.Context
var ds model.DataStore
var router http.Handler
BeforeEach(func() {
ctx = GinkgoT().Context()
// db.Db() is a process-wide singleton that this DeferCleanup closes for the whole binary; keep this the only real-DB spec in this package.
DeferCleanup(configtest.SetupConfig())
conf.Server.EnableUserEditing = true
@ -45,13 +48,13 @@ var _ = Describe("PUT /user/{id}: token refresh on self password change", func()
auth.Init(ds)
userService := core.NewUser(ds, noopPluginUnloader{})
nativeRouter := New(ds, nil, nil, nil, tests.NewMockLibraryService(), userService, nil, nil, nil, nil, nil)
nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), userService, nil, nil, nil, nil, nil)
router = server.JWTVerifier(nativeRouter)
})
It("carries the bumped epoch in the refreshed token, not the epoch the token was minted with", func() {
usr := model.User{UserName: "selfchanger", Name: "Self Changer", NewPassword: "old-password"}
Expect(ds.User(GinkgoT().Context()).Put(&usr)).To(Succeed())
Expect(ds.User().Put(ctx, &usr)).To(Succeed())
token, err := auth.CreateToken(&usr)
Expect(err).ToNot(HaveOccurred())
@ -72,7 +75,7 @@ var _ = Describe("PUT /user/{id}: token refresh on self password change", func()
claims, err := auth.Validate(refreshed)
Expect(err).ToNot(HaveOccurred())
reloaded, err := ds.User(GinkgoT().Context()).Get(usr.ID)
reloaded, err := ds.User().Get(ctx, usr.ID)
Expect(err).ToNot(HaveOccurred())
Expect(reloaded.TokenEpoch).To(Equal(1))
Expect(claims.Epoch).To(Equal(reloaded.TokenEpoch))

View file

@ -2,9 +2,7 @@ package public
import (
"cmp"
"fmt"
"net/http"
"strings"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/utils/req"
@ -31,9 +29,8 @@ func (pub *Router) handleDownloads(w http.ResponseWriter, r *http.Request) {
return
}
name := str.SanitizeFilename(cmp.Or(s.Description, s.ID))
name = strings.ReplaceAll(name, ",", "_")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name+".zip"))
name := cmp.Or(s.Description, s.ID)
w.Header().Set("Content-Disposition", str.ContentDispositionAttachment(name+".zip"))
w.Header().Set("Content-Type", "application/zip")
err = pub.archiver.ZipShare(ctx, s, w)

View file

@ -4,6 +4,7 @@ import (
"context"
"errors"
"io"
"mime"
"net/http"
"net/http/httptest"
"time"
@ -95,6 +96,26 @@ var _ = Describe("handleDownloads", func() {
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="AC_DC_ Live_ 1979.zip"`))
})
It("sanitizes the UTF-8 filename* as well", func() {
shareIs(&model.Share{ID: "abc123", Description: "Sigur Rós/Live", Downloadable: true})
w := makeRequest("abc123")
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="Sigur Ros_Live.zip"; filename*=utf-8''Sigur%20R%C3%B3s_Live.zip`))
})
It("does not let the share description inject a second filename parameter", func() {
shareIs(&model.Share{ID: "abc123", Description: `mix"; filename="evil.html`, Downloadable: true})
w := makeRequest("abc123")
disposition := w.Header().Get("Content-Disposition")
Expect(disposition).ToNot(ContainSubstring(`filename="evil.html`))
_, params, err := mime.ParseMediaType(disposition)
Expect(err).ToNot(HaveOccurred())
Expect(params["filename"]).To(Equal(`mix_; filename=_evil.html.zip`))
})
It("returns 403 without invoking the archiver when the share is not downloadable", func() {
shareIs(&model.Share{ID: "abc123", Description: "No Download", Downloadable: false})

View file

@ -58,8 +58,8 @@ func (pub *Router) handleM3U(w http.ResponseWriter, r *http.Request) {
}
s = pub.mapShareToM3U(r, *s)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "audio/x-mpegurl")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(s.ToM3U8())) //nolint:gosec
}

View file

@ -0,0 +1,55 @@
package public
import (
"net/http"
"net/http/httptest"
"github.com/go-chi/jwtauth/v5"
"github.com/navidrome/navidrome/core"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/tests"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("handleM3U", func() {
var ds *tests.MockDataStore
var shareRepo *tests.MockShareRepo
var pub *Router
BeforeEach(func() {
auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil)
ds = &tests.MockDataStore{}
shareRepo = &tests.MockShareRepo{}
ds.MockedShare = shareRepo
pub = &Router{ds: ds, share: core.NewShare(ds)}
})
makeRequest := func(id string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/public/"+id+"/m3u?%3Aid="+id, nil)
w := httptest.NewRecorder()
pub.handleM3U(w, r)
return w
}
It("sets the M3U content type", func() {
share := &model.Share{ID: "abc123", Tracks: model.MediaFiles{{ID: "t1", Title: "Track 1"}}}
shareRepo.ID = share.ID
shareRepo.Entity = share
w := makeRequest("abc123")
Expect(w.Code).To(Equal(http.StatusOK))
// Result() has the headers sent at WriteHeader time, unlike w.Header()
Expect(w.Result().Header.Get("Content-Type")).To(Equal("audio/x-mpegurl"))
Expect(w.Body.String()).To(HavePrefix("#EXTM3U"))
})
It("returns 404 when the share does not exist", func() {
shareRepo.ID = "other"
shareRepo.Entity = &model.Share{ID: "other"}
Expect(makeRequest("missing").Code).To(Equal(http.StatusNotFound))
})
})

View file

@ -26,7 +26,7 @@ func (pub *Router) handleStream(w http.ResponseWriter, r *http.Request) {
return
}
share, err := pub.ds.Share(ctx).Get(info.shareID)
share, err := pub.ds.Share().Get(ctx, info.shareID)
if err != nil {
checkShareError(ctx, w, err, info.shareID)
return
@ -35,14 +35,14 @@ func (pub *Router) handleStream(w http.ResponseWriter, r *http.Request) {
checkShareError(ctx, w, model.ErrExpired, info.shareID)
return
}
shareOwner, err := pub.ds.User(ctx).Get(share.UserID)
shareOwner, err := pub.ds.User().Get(ctx, share.UserID)
if err != nil {
log.Error(ctx, "Error retrieving share owner for shared stream", "share", info.shareID, "owner", share.UserID, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
mf, err := pub.ds.MediaFile(ctx).Get(info.id)
mf, err := pub.ds.MediaFile().Get(ctx, info.id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
http.Error(w, "not found", http.StatusNotFound)

View file

@ -107,12 +107,14 @@ var _ = Describe("encodeMediafileShare", func() {
})
var _ = Describe("handleStream", func() {
var ctx context.Context
var ds *tests.MockDataStore
var shareRepo *tests.MockShareRepo
var streamer *mockStreamer
var pub *Router
BeforeEach(func() {
ctx = GinkgoT().Context()
auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil)
ds = &tests.MockDataStore{}
shareRepo = &tests.MockShareRepo{}
@ -132,7 +134,7 @@ var _ = Describe("handleStream", func() {
shareRepo.ID = "share123"
shareRepo.Entity = &model.Share{ID: "share123", UserID: owner.ID, Tracks: model.MediaFiles{mf}}
userRepo := tests.CreateMockUserRepo()
Expect(userRepo.Put(&owner)).To(Succeed())
Expect(userRepo.Put(ctx, &owner)).To(Succeed())
ds.MockedUser = userRepo
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{mf})
@ -171,7 +173,7 @@ var _ = Describe("handleStream", func() {
It("returns 404 when the track is not a member of the share", func() {
owner := model.User{ID: "owner1", UserName: "owner1", IsAdmin: true}
userRepo := tests.CreateMockUserRepo()
Expect(userRepo.Put(&owner)).To(Succeed())
Expect(userRepo.Put(ctx, &owner)).To(Succeed())
ds.MockedUser = userRepo
mfRepo := tests.CreateMockMediaFileRepo()
mfRepo.SetData(model.MediaFiles{{ID: "mf-shared"}, {ID: "mf-other"}})

View file

@ -32,7 +32,7 @@ func IndexWithShare(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.H
// Injects the config in the `index.html` template
func serveIndex(ds model.DataStore, fs fs.FS, shareInfo *model.Share) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := ds.User(r.Context()).CountAll()
c, err := ds.User().CountAll(r.Context())
firstTime := c == 0 && err == nil
t, err := getIndexTemplate(r, fs)

View file

@ -1,6 +1,7 @@
package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
@ -341,7 +342,7 @@ type mockedUserRepo struct {
empty bool
}
func (u *mockedUserRepo) CountAll(...model.QueryOptions) (int64, error) {
func (u *mockedUserRepo) CountAll(context.Context, ...model.QueryOptions) (int64, error) {
if u.empty {
return 0, nil
}

View file

@ -71,14 +71,14 @@ func (api *Router) getAlbumList(r *http.Request) (model.Albums, int64, error) {
opts.Offset = p.IntOr("offset", 0)
opts.Max = min(p.IntOr("size", 10), 500)
albums, err := api.ds.Album(r.Context()).GetAll(opts)
albums, err := api.ds.Album().GetAll(r.Context(), opts)
if err != nil {
log.Error(r, "Error retrieving albums", err)
return nil, 0, newError(responses.ErrorGeneric, "internal error")
}
count, err := api.ds.Album(r.Context()).CountAll(opts)
count, err := api.ds.Album().CountAll(r.Context(), opts)
if err != nil {
log.Error(r, "Error counting albums", err)
return nil, 0, newError(responses.ErrorGeneric, "internal error")
@ -137,7 +137,7 @@ func (api *Router) getStarredItems(r *http.Request) (model.Artists, model.Albums
func() error {
artistOpts := filter.ApplyArtistLibraryFilter(filter.ArtistsByStarred(), musicFolderIds)
var err error
artists, err = api.ds.Artist(ctx).GetAll(artistOpts)
artists, err = api.ds.Artist().GetAll(ctx, artistOpts)
if err != nil {
log.Error(r, "Error retrieving starred artists", err)
}
@ -147,7 +147,7 @@ func (api *Router) getStarredItems(r *http.Request) (model.Artists, model.Albums
func() error {
albumOpts := filter.ApplyLibraryFilter(filter.ByStarred(), musicFolderIds)
var err error
albums, err = api.ds.Album(ctx).GetAll(albumOpts)
albums, err = api.ds.Album().GetAll(ctx, albumOpts)
if err != nil {
log.Error(r, "Error retrieving starred albums", err)
}
@ -157,7 +157,7 @@ func (api *Router) getStarredItems(r *http.Request) (model.Artists, model.Albums
func() error {
mediaFileOpts := filter.ApplyLibraryFilter(filter.ByStarred(), musicFolderIds)
var err error
mediaFiles, err = api.ds.MediaFile(ctx).GetAll(mediaFileOpts)
mediaFiles, err = api.ds.MediaFile().GetAll(ctx, mediaFileOpts)
if err != nil {
log.Error(r, "Error retrieving starred mediaFiles", err)
}
@ -244,7 +244,7 @@ func (api *Router) GetRandomSongs(r *http.Request) (*responses.Subsonic, error)
opts = filter.ApplyLibraryFilter(opts, musicFolderIds)
opts.Max = size
songs, err := api.ds.MediaFile(r.Context()).GetRandom(opts)
songs, err := api.ds.MediaFile().GetRandom(r.Context(), opts)
if err != nil {
log.Error(r, "Error retrieving random songs", err)
return nil, err
@ -286,5 +286,5 @@ func (api *Router) GetSongsByGenre(r *http.Request) (*responses.Subsonic, error)
func (api *Router) getSongs(ctx context.Context, offset, size int, opts filter.Options) (model.MediaFiles, error) {
opts.Offset = offset
opts.Max = size
return api.ds.MediaFile(ctx).GetAll(opts)
return api.ds.MediaFile().GetAll(ctx, opts)
}

View file

@ -6,7 +6,6 @@ import (
"net/http/httptest"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server/subsonic/responses"
@ -21,12 +20,11 @@ var _ = Describe("Album Lists", func() {
var ds model.DataStore
var mockRepo *tests.MockAlbumRepo
var w *httptest.ResponseRecorder
ctx := log.NewContext(context.TODO())
BeforeEach(func() {
ds = &tests.MockDataStore{}
auth.Init(ds)
mockRepo = ds.Album(ctx).(*tests.MockAlbumRepo)
mockRepo = ds.Album().(*tests.MockAlbumRepo)
router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
w = httptest.NewRecorder()
})
@ -236,7 +234,7 @@ var _ = Describe("Album Lists", func() {
var mockMediaFileRepo *tests.MockMediaFileRepo
BeforeEach(func() {
mockMediaFileRepo = ds.MediaFile(ctx).(*tests.MockMediaFileRepo)
mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo)
})
It("should return random songs", func() {
@ -328,7 +326,7 @@ var _ = Describe("Album Lists", func() {
var mockMediaFileRepo *tests.MockMediaFileRepo
BeforeEach(func() {
mockMediaFileRepo = ds.MediaFile(ctx).(*tests.MockMediaFileRepo)
mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo)
})
It("should return songs by genre", func() {
@ -422,9 +420,9 @@ var _ = Describe("Album Lists", func() {
var mockMediaFileRepo *tests.MockMediaFileRepo
BeforeEach(func() {
mockArtistRepo = ds.Artist(ctx).(*tests.MockArtistRepo)
mockAlbumRepo = ds.Album(ctx).(*tests.MockAlbumRepo)
mockMediaFileRepo = ds.MediaFile(ctx).(*tests.MockMediaFileRepo)
mockArtistRepo = ds.Artist().(*tests.MockArtistRepo)
mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo)
mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo)
})
It("should return starred items", func() {
@ -484,9 +482,9 @@ var _ = Describe("Album Lists", func() {
var mockMediaFileRepo *tests.MockMediaFileRepo
BeforeEach(func() {
mockArtistRepo = ds.Artist(ctx).(*tests.MockArtistRepo)
mockAlbumRepo = ds.Album(ctx).(*tests.MockAlbumRepo)
mockMediaFileRepo = ds.MediaFile(ctx).(*tests.MockMediaFileRepo)
mockArtistRepo = ds.Artist().(*tests.MockArtistRepo)
mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo)
mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo)
})
It("should return starred items in ID3 format", func() {

View file

@ -111,6 +111,7 @@ func (api *Router) routes() http.Handler {
r.Use(getPlayer(api.players))
h(r, "ping", api.Ping)
h(r, "getLicense", api.GetLicense)
h(r, "tokenInfo", api.TokenInfo)
})
r.Group(func(r chi.Router) {
r.Use(getPlayer(api.players))

View file

@ -15,8 +15,8 @@ import (
func (api *Router) GetBookmarks(r *http.Request) (*responses.Subsonic, error) {
user, _ := request.UserFrom(r.Context())
repo := api.ds.MediaFile(r.Context())
bookmarks, err := repo.GetBookmarks()
repo := api.ds.MediaFile()
bookmarks, err := repo.GetBookmarks(r.Context())
if err != nil {
return nil, err
}
@ -46,8 +46,8 @@ func (api *Router) CreateBookmark(r *http.Request) (*responses.Subsonic, error)
comment, _ := p.String("comment")
position := p.Int64Or("position", 0)
repo := api.ds.MediaFile(r.Context())
ok, err := repo.Exists(id)
repo := api.ds.MediaFile()
ok, err := repo.Exists(r.Context(), id)
if err != nil {
return nil, err
}
@ -55,7 +55,7 @@ func (api *Router) CreateBookmark(r *http.Request) (*responses.Subsonic, error)
return nil, newError(responses.ErrorDataNotFound, "Song not found")
}
err = repo.AddBookmark(id, comment, position)
err = repo.AddBookmark(r.Context(), id, comment, position)
if err != nil {
return nil, err
}
@ -69,8 +69,8 @@ func (api *Router) DeleteBookmark(r *http.Request) (*responses.Subsonic, error)
return nil, err
}
repo := api.ds.MediaFile(r.Context())
err = repo.DeleteBookmark(id)
repo := api.ds.MediaFile()
err = repo.DeleteBookmark(r.Context(), id)
if err != nil {
return nil, err
}
@ -80,8 +80,8 @@ func (api *Router) DeleteBookmark(r *http.Request) (*responses.Subsonic, error)
func (api *Router) GetPlayQueue(r *http.Request) (*responses.Subsonic, error) {
user, _ := request.UserFrom(r.Context())
repo := api.ds.PlayQueue(r.Context())
pq, err := repo.RetrieveWithMediaFiles(user.ID)
repo := api.ds.PlayQueue()
pq, err := repo.RetrieveWithMediaFiles(r.Context(), user.ID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, err
}
@ -140,8 +140,8 @@ func (api *Router) SavePlayQueue(r *http.Request) (*responses.Subsonic, error) {
UpdatedAt: time.Time{},
}
repo := api.ds.PlayQueue(r.Context())
err := repo.Store(pq)
repo := api.ds.PlayQueue()
err := repo.Store(r.Context(), pq)
if err != nil {
return nil, err
}
@ -151,8 +151,8 @@ func (api *Router) SavePlayQueue(r *http.Request) (*responses.Subsonic, error) {
func (api *Router) GetPlayQueueByIndex(r *http.Request) (*responses.Subsonic, error) {
user, _ := request.UserFrom(r.Context())
repo := api.ds.PlayQueue(r.Context())
pq, err := repo.RetrieveWithMediaFiles(user.ID)
repo := api.ds.PlayQueue()
pq, err := repo.RetrieveWithMediaFiles(r.Context(), user.ID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, err
}
@ -215,8 +215,8 @@ func (api *Router) SavePlayQueueByIndex(r *http.Request) (*responses.Subsonic, e
UpdatedAt: time.Time{},
}
repo := api.ds.PlayQueue(r.Context())
err = repo.Store(pq)
repo := api.ds.PlayQueue()
err = repo.Store(r.Context(), pq)
if err != nil {
return nil, err
}

View file

@ -19,9 +19,9 @@ var _ = Describe("Bookmarks", func() {
BeforeEach(func() {
ds = &tests.MockDataStore{}
router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
ctx = request.WithUser(context.Background(), model.User{ID: "u1", UserName: "u1"})
mfRepo = ds.MediaFile(ctx).(*tests.MockMediaFileRepo)
mfRepo = ds.MediaFile().(*tests.MockMediaFileRepo)
mfRepo.SetData(model.MediaFiles{{ID: "visible"}})
})

View file

@ -33,7 +33,7 @@ func (api *Router) GetMusicFolders(r *http.Request) (*responses.Subsonic, error)
func (api *Router) getArtist(r *http.Request, libIds []int, ifModifiedSince time.Time) (model.ArtistIndexes, int64, error) {
ctx := r.Context()
lastScanStr, err := api.ds.Property(ctx).DefaultGet(consts.LastScanStartTimeKey, "")
lastScanStr, err := api.ds.Property().DefaultGet(ctx, consts.LastScanStartTimeKey, "")
if err != nil {
log.Error(ctx, "Error retrieving last scan start time", err)
return nil, 0, err
@ -45,7 +45,7 @@ func (api *Router) getArtist(r *http.Request, libIds []int, ifModifiedSince time
var indexes model.ArtistIndexes
if lastScan.After(ifModifiedSince) {
indexes, err = api.ds.Artist(ctx).GetIndex(false, libIds, model.RoleAlbumArtist)
indexes, err = api.ds.Artist().GetIndex(ctx, false, libIds, model.RoleAlbumArtist)
if err != nil {
log.Error(ctx, "Error retrieving Indexes", err)
return nil, 0, err
@ -167,7 +167,7 @@ func (api *Router) GetArtist(r *http.Request) (*responses.Subsonic, error) {
id, _ := p.String("id")
ctx := r.Context()
artist, err := api.ds.Artist(ctx).Get(id)
artist, err := api.ds.Artist().Get(ctx, id)
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Requested ArtistID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Artist not found")
@ -191,7 +191,7 @@ func (api *Router) GetAlbum(r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
album, err := api.ds.Album(ctx).Get(id)
album, err := api.ds.Album().Get(ctx, id)
if errors.Is(err, model.ErrNotFound) {
log.Error(ctx, "Requested AlbumID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Album not found")
@ -201,7 +201,7 @@ func (api *Router) GetAlbum(r *http.Request) (*responses.Subsonic, error) {
return nil, err
}
mfs, err := api.ds.MediaFile(ctx).GetAll(filter.SongsByAlbum(id))
mfs, err := api.ds.MediaFile().GetAll(ctx, filter.SongsByAlbum(id))
if err != nil {
log.Error(ctx, "Error retrieving tracks from album", "id", id, "name", album.Name, err)
return nil, err
@ -247,7 +247,7 @@ func (api *Router) GetSong(r *http.Request) (*responses.Subsonic, error) {
id, _ := p.String("id")
ctx := r.Context()
mf, err := api.ds.MediaFile(ctx).Get(id)
mf, err := api.ds.MediaFile().Get(ctx, id)
if errors.Is(err, model.ErrNotFound) {
log.Error(r, "Requested MediaFileID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Song not found")
@ -264,7 +264,7 @@ func (api *Router) GetSong(r *http.Request) (*responses.Subsonic, error) {
func (api *Router) GetGenres(r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
genres, err := api.ds.Genre(ctx).GetAll(model.QueryOptions{Sort: "song_count, album_count, name desc", Order: "desc"})
genres, err := api.ds.Genre().GetAll(ctx, model.QueryOptions{Sort: "song_count, album_count, name desc", Order: "desc"})
if err != nil {
log.Error(r, err)
return nil, err
@ -421,7 +421,7 @@ func (api *Router) buildArtistDirectory(ctx context.Context, artist *model.Artis
dir.Starred = artist.StarredAt
}
albums, err := api.ds.Album(ctx).GetAll(filter.AlbumsByArtistID(artist.ID))
albums, err := api.ds.Album().GetAll(ctx, filter.AlbumsByArtistID(artist.ID))
if err != nil {
return nil, err
}
@ -435,7 +435,7 @@ func (api *Router) buildArtist(r *http.Request, artist *model.Artist) (*response
a := &responses.ArtistWithAlbumsID3{}
a.ArtistID3 = toArtistID3(r, *artist)
albums, err := api.ds.Album(ctx).GetAll(filter.AlbumsByArtistID(artist.ID))
albums, err := api.ds.Album().GetAll(ctx, filter.AlbumsByArtistID(artist.ID))
if err != nil {
return nil, err
}
@ -463,7 +463,7 @@ func (api *Router) buildAlbumDirectory(ctx context.Context, album *model.Album)
dir.Starred = album.StarredAt
}
mfs, err := api.ds.MediaFile(ctx).GetAll(filter.SongsByAlbum(album.ID))
mfs, err := api.ds.MediaFile().GetAll(ctx, filter.SongsByAlbum(album.ID))
if err != nil {
return nil, err
}

View file

@ -83,14 +83,14 @@ var _ = Describe("Browsing", func() {
ctx = contextWithUser(ctx, "user-id", 2, 3)
// Setup minimal mock library data for working tests
mockLibRepo := ds.Library(ctx).(*tests.MockLibraryRepo)
mockLibRepo := ds.Library().(*tests.MockLibraryRepo)
mockLibRepo.SetData(model.Libraries{
{ID: 2, Name: "Test Library 2", Path: "/music/library2"},
{ID: 3, Name: "Test Library 3", Path: "/music/library3"},
})
// Setup mock artist data
mockArtistRepo := ds.Artist(ctx).(*tests.MockArtistRepo)
mockArtistRepo := ds.Artist().(*tests.MockArtistRepo)
mockArtistRepo.SetData(model.Artists{
{ID: "1", Name: "Test Artist 1"},
{ID: "2", Name: "Test Artist 2"},
@ -132,14 +132,14 @@ var _ = Describe("Browsing", func() {
ctx = contextWithUser(ctx, "user-id", 1, 2)
// Setup minimal mock library data for working tests
mockLibRepo := ds.Library(ctx).(*tests.MockLibraryRepo)
mockLibRepo := ds.Library().(*tests.MockLibraryRepo)
mockLibRepo.SetData(model.Libraries{
{ID: 1, Name: "Test Library 1", Path: "/music/library1"},
{ID: 2, Name: "Test Library 2", Path: "/music/library2"},
})
// Setup mock artist data
mockArtistRepo := ds.Artist(ctx).(*tests.MockArtistRepo)
mockArtistRepo := ds.Artist().(*tests.MockArtistRepo)
mockArtistRepo.SetData(model.Artists{
{ID: "1", Name: "Test Artist 1"},
{ID: "2", Name: "Test Artist 2"},

View file

@ -224,10 +224,10 @@ func createUser(id, username, name string, isAdmin bool) model.User {
IsAdmin: isAdmin,
NewPassword: "password",
}
Expect(ds.User(ctx).Put(&user)).To(Succeed())
Expect(ds.User(ctx).SetUserLibraries(user.ID, []int{lib.ID})).To(Succeed())
Expect(ds.User().Put(ctx, &user)).To(Succeed())
Expect(ds.User().SetUserLibraries(ctx, user.ID, []int{lib.ID})).To(Succeed())
loadedUser, err := ds.User(ctx).FindByUsername(user.UserName)
loadedUser, err := ds.User().FindByUsername(ctx, user.UserName)
Expect(err).ToNot(HaveOccurred())
user.Libraries = loadedUser.Libraries
return user

View file

@ -142,7 +142,7 @@ var _ = Describe("Album List Endpoints", func() {
setupTestDB()
// Star an album so the starred filter returns results
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -166,7 +166,7 @@ var _ = Describe("Album List Endpoints", func() {
setupTestDB()
// Rate an album so the highest filter returns results
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Kind of Blue"},
})
Expect(err).ToNot(HaveOccurred())

View file

@ -0,0 +1,54 @@
package e2e
import (
"net/http/httptest"
"net/url"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server/subsonic/responses"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("API key authentication", func() {
var key string
BeforeEach(func() {
setupTestDB()
userCtx := request.WithUser(ctx, regularUser)
player := &model.Player{ID: "apikey-player", Name: "Phone", UserId: regularUser.ID, Client: "test-client"}
Expect(ds.Player().Put(userCtx, player)).To(Succeed())
key = "nds_0123456789abcdefghijkl"
Expect(ds.Player().SetAPIKey(userCtx, player.ID, key)).To(Succeed())
})
doKeyReq := func(endpoint, apiKey string) *responses.Subsonic {
q := url.Values{"apiKey": {apiKey}, "v": {"1.16.1"}, "c": {"test-client"}, "f": {"json"}}
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest("GET", "/"+endpoint+"?"+q.Encode(), nil))
return parseJSONResponse(w)
}
It("authenticates ping with only the key", func() {
resp := doKeyReq("ping", key)
Expect(resp.Status).To(Equal(responses.StatusOK))
})
It("reports the key owner in tokenInfo", func() {
resp := doKeyReq("tokenInfo", key)
Expect(resp.Status).To(Equal(responses.StatusOK))
Expect(resp.TokenInfo).ToNot(BeNil())
Expect(resp.TokenInfo.Username).To(Equal(regularUser.UserName))
})
It("rejects an unknown key with error 44", func() {
resp := doKeyReq("ping", "nds_unknown")
Expect(resp.Status).To(Equal(responses.StatusFailed))
Expect(resp.Error).ToNot(BeNil())
Expect(resp.Error.Code).To(Equal(int32(44)))
})
})

View file

@ -108,8 +108,8 @@ var _ = Describe("Artwork Serving", Ordered, func() {
// harness's MaxOpenConns=1, so wipe the golden content and import this library fresh.
wipeScannedContent()
artLib := model.Library{Name: "Artwork Library", Path: musicDir}
Expect(ds.Library(ctx).Put(&artLib)).To(Succeed())
Expect(ds.User(ctx).SetUserLibraries(adminUser.ID, []int{artLib.ID})).To(Succeed())
Expect(ds.Library().Put(ctx, &artLib)).To(Succeed())
Expect(ds.User().SetUserLibraries(ctx, adminUser.ID, []int{artLib.ID})).To(Succeed())
s := scanner.New(ctx, ds, events.NoopBroker(),
playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance())
@ -148,20 +148,20 @@ var _ = Describe("Artwork Serving", Ordered, func() {
It("drains the queue: folder art is acquired, the artless album settles absent", func() {
// Enqueues the way the serving paths do, so the drain is driven by a plain queue row.
for _, id := range []string{artfulID, artlessID} {
Expect(ds.ArtworkQueue(ctx).EnqueuePreservingBackoff(model.ArtworkQueueItem{
Expect(ds.ArtworkQueue().EnqueuePreservingBackoff(ctx, model.ArtworkQueueItem{
ItemKind: model.KindAlbumArtwork.Prefix(), ItemID: id,
ImageType: model.ImageTypePrimary, Priority: model.ArtworkPriorityBump,
})).To(Succeed())
}
runWorkerUntil(ctx, worker, func() bool {
found, err := ds.Artwork(ctx).GetItemArtwork(model.KindAlbumArtwork, artfulID, model.ImageTypePrimary)
found, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, artfulID, model.ImageTypePrimary)
if err != nil || found.Hash == "" {
return false
}
absent, err := ds.Artwork(ctx).GetItemArtwork(model.KindAlbumArtwork, artlessID, model.ImageTypePrimary)
absent, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, artlessID, model.ImageTypePrimary)
return err == nil && absent.Hash == ""
})
ia, err := ds.Artwork(ctx).GetItemArtwork(model.KindAlbumArtwork, artfulID, model.ImageTypePrimary)
ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, artfulID, model.ImageTypePrimary)
Expect(err).ToNot(HaveOccurred())
Expect(ia.Source).To(Equal("folder"))
artfulHash = ia.Hash
@ -277,7 +277,7 @@ func wipeScannedContent() {
func albumIDByName(name string) string {
GinkgoHelper()
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{Filters: squirrel.Eq{"album.name": name}})
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"album.name": name}})
Expect(err).ToNot(HaveOccurred())
Expect(albums).To(HaveLen(1), "expected exactly one album named %q", name)
return albums[0].ID

View file

@ -19,7 +19,7 @@ var _ = Describe("Bookmark and PlayQueue Endpoints", Ordered, func() {
BeforeAll(func() {
// Get a media file ID from the database to use for bookmarks
mfs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1})
mfs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1})
Expect(err).ToNot(HaveOccurred())
Expect(mfs).ToNot(BeEmpty())
trackID = mfs[0].ID
@ -69,7 +69,7 @@ var _ = Describe("Bookmark and PlayQueue Endpoints", Ordered, func() {
BeforeAll(func() {
// Get multiple media file IDs from the database
mfs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 3, Sort: "title"})
mfs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 3, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(len(mfs)).To(BeNumerically(">=", 2))
for _, mf := range mfs {

View file

@ -14,7 +14,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
getBeatlesId := func() string {
artists, err := ds.Artist(ctx).GetAll(model.QueryOptions{
artists, err := ds.Artist().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"name": "The Beatles"},
})
Expect(err).ToNot(HaveOccurred())
@ -105,7 +105,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
It("returns an album directory with its tracks as children", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -159,7 +159,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
It("returns artist with a single album", func() {
artists, err := ds.Artist(ctx).GetAll(model.QueryOptions{
artists, err := ds.Artist().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"name": "Led Zeppelin"},
})
Expect(err).ToNot(HaveOccurred())
@ -177,7 +177,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getAlbum", func() {
It("returns album with its tracks", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -193,7 +193,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
It("includes correct track metadata", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -210,7 +210,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
It("returns album with correct artist and year", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Kind of Blue"},
})
Expect(err).ToNot(HaveOccurred())
@ -236,7 +236,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getSong", func() {
It("returns a song by its ID", func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "Come Together"},
})
Expect(err).ToNot(HaveOccurred())
@ -260,7 +260,7 @@ var _ = Describe("Browsing Endpoints", func() {
})
It("returns correct metadata for a jazz track", func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "So What"},
})
Expect(err).ToNot(HaveOccurred())
@ -343,7 +343,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getAlbumInfo", func() {
It("returns album info for a valid album", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -359,7 +359,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getAlbumInfo2", func() {
It("returns album info for a valid album", func() {
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -434,7 +434,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getSimilarSongs", func() {
It("returns a response for a valid song ID", func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "Come Together"},
})
Expect(err).ToNot(HaveOccurred())
@ -451,7 +451,7 @@ var _ = Describe("Browsing Endpoints", func() {
Describe("getSimilarSongs2", func() {
It("returns a response for a valid song ID", func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "Come Together"},
})
Expect(err).ToNot(HaveOccurred())

View file

@ -17,19 +17,19 @@ var _ = Describe("Media Annotation Endpoints", Ordered, func() {
BeforeAll(func() {
// Look up a song from the scanned data
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
songID = songs[0].ID
// Look up an album
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "name"})
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "name"})
Expect(err).ToNot(HaveOccurred())
Expect(albums).ToNot(BeEmpty())
albumID = albums[0].ID
// Look up an artist
artists, err := ds.Artist(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "name"})
artists, err := ds.Artist().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "name"})
Expect(err).ToNot(HaveOccurred())
Expect(artists).ToNot(BeEmpty())
artistID = artists[0].ID
@ -97,12 +97,12 @@ var _ = Describe("Media Annotation Endpoints", Ordered, func() {
var songID, albumID string
BeforeAll(func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
songID = songs[0].ID
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "name"})
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "name"})
Expect(err).ToNot(HaveOccurred())
Expect(albums).ToNot(BeEmpty())
albumID = albums[0].ID
@ -141,7 +141,7 @@ var _ = Describe("Media Annotation Endpoints", Ordered, func() {
Describe("Scrobble", func() {
It("submits a scrobble for a song", func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
@ -163,7 +163,7 @@ var _ = Describe("Media Annotation Endpoints", Ordered, func() {
var songID string
BeforeAll(func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
songID = songs[0].ID

View file

@ -21,7 +21,7 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() {
BeforeAll(func() {
// All test tracks are mp3 at 320kbps
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
trackID = songs[0].ID
@ -106,14 +106,15 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() {
})
Describe("Download", func() {
var trackID string
var trackID, trackTitle string
BeforeAll(func() {
// All test tracks are mp3 at 320kbps
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Max: 1, Sort: "title"})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Max: 1, Sort: "title"})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
trackID = songs[0].ID
trackTitle = songs[0].Title
})
It("returns error when id parameter is missing", func() {
@ -143,6 +144,7 @@ var _ = Describe("Media Retrieval Endpoints", Ordered, func() {
Expect(w.Code).To(Equal(http.StatusOK))
Expect(streamerSpy.LastRequest.Format).To(Equal("opus"))
Expect(streamerSpy.LastRequest.BitRate).To(Equal(128))
Expect(w.Header().Get("Content-Disposition")).To(Equal(`attachment; filename="` + trackTitle + `.opus"`))
})
It("returns error when downloads are disabled", func() {

View file

@ -44,10 +44,10 @@ var _ = Describe("Multi-Library Support", Ordered, func() {
// Create the second library in the DB (Put auto-assigns admin users)
lib2 = model.Library{ID: 2, Name: "Classical Library", Path: "fake2:///classical"}
Expect(ds.Library(ctx).Put(&lib2)).To(Succeed())
Expect(ds.Library().Put(ctx, &lib2)).To(Succeed())
// Reload admin user to get both libraries in the Libraries field
loadedAdmin, err := ds.User(ctx).FindByUsername(adminUser.UserName)
loadedAdmin, err := ds.User().FindByUsername(ctx, adminUser.UserName)
Expect(err).ToNot(HaveOccurred())
adminWithLibs = *loadedAdmin
@ -65,10 +65,10 @@ var _ = Describe("Multi-Library Support", Ordered, func() {
IsAdmin: false,
NewPassword: "password",
}
Expect(ds.User(ctx).Put(&userLib1Only)).To(Succeed())
Expect(ds.User(ctx).SetUserLibraries(userLib1Only.ID, []int{lib.ID})).To(Succeed())
Expect(ds.User().Put(ctx, &userLib1Only)).To(Succeed())
Expect(ds.User().SetUserLibraries(ctx, userLib1Only.ID, []int{lib.ID})).To(Succeed())
loadedUser, err := ds.User(ctx).FindByUsername(userLib1Only.UserName)
loadedUser, err := ds.User().FindByUsername(ctx, userLib1Only.UserName)
Expect(err).ToNot(HaveOccurred())
userLib1Only.Libraries = loadedUser.Libraries
})
@ -181,7 +181,7 @@ var _ = Describe("Multi-Library Support", Ordered, func() {
BeforeAll(func() {
// Look up one song from each library
lib1Songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
lib1Songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"media_file.library_id": lib.ID},
Max: 1, Sort: "title",
})
@ -189,7 +189,7 @@ var _ = Describe("Multi-Library Support", Ordered, func() {
Expect(lib1Songs).ToNot(BeEmpty())
lib1SongID = lib1Songs[0].ID
lib2Songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
lib2Songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"media_file.library_id": lib2.ID},
Max: 1, Sort: "title",
})
@ -248,7 +248,7 @@ var _ = Describe("Multi-Library Support", Ordered, func() {
var lib2AlbumID string
BeforeAll(func() {
lib2Albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
lib2Albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.library_id": lib2.ID},
})
Expect(err).ToNot(HaveOccurred())

View file

@ -19,7 +19,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
setupTestDB()
// Look up song IDs from scanned data for playlist operations
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Sort: "title", Max: 6})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Sort: "title", Max: 6})
Expect(err).ToNot(HaveOccurred())
Expect(len(songs)).To(BeNumerically(">=", 5))
for _, s := range songs {
@ -244,7 +244,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
BeforeAll(func() {
setupTestDB()
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Sort: "title", Max: 6})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Sort: "title", Max: 6})
Expect(err).ToNot(HaveOccurred())
Expect(len(songs)).To(BeNumerically(">=", 3))
for _, s := range songs {
@ -438,7 +438,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
setupTestDB()
// Look up a song ID for mutation tests
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Sort: "title", Max: 1})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Sort: "title", Max: 1})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
songID = songs[0].ID
@ -450,7 +450,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
Public: false,
Rules: &criteria.Criteria{Expression: criteria.Contains{"title": ""}},
}
Expect(ds.Playlist(ctx).Put(smartPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, smartPls)).To(Succeed())
smartPlaylistID = smartPls.ID
})
@ -525,7 +525,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
BeforeAll(func() {
setupTestDB()
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{Sort: "title", Max: 1})
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{Sort: "title", Max: 1})
Expect(err).ToNot(HaveOccurred())
Expect(songs).ToNot(BeEmpty())
songID = songs[0].ID
@ -543,7 +543,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"loved": true}}},
}
Expect(ds.Playlist(ctx).Put(boolPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, boolPls)).To(Succeed())
boolPlaylistID = boolPls.ID
// Create smart playlist with string "true"
@ -552,7 +552,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"loved": "true"}}},
}
Expect(ds.Playlist(ctx).Put(stringPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, stringPls)).To(Succeed())
stringPlaylistID = stringPls.ID
// Create smart playlist with string "true" in nested any group (exact issue #4826 scenario)
@ -565,7 +565,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
},
}},
}
Expect(ds.Playlist(ctx).Put(nestedPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, nestedPls)).To(Succeed())
nestedPlaylistID = nestedPls.ID
})
@ -607,7 +607,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsPresent{"genre": "true"}}},
}
Expect(ds.Playlist(ctx).Put(pls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, pls)).To(Succeed())
resp := doReq("getPlaylist", "id", pls.ID)
Expect(resp.Status).To(Equal(responses.StatusOK))
@ -620,7 +620,7 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsMissing{"genre": "true"}}},
}
Expect(ds.Playlist(ctx).Put(pls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, pls)).To(Succeed())
resp := doReq("getPlaylist", "id", pls.ID)
Expect(resp.Status).To(Equal(responses.StatusOK))
@ -633,14 +633,14 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsMissing{"genre": true}}},
}
Expect(ds.Playlist(ctx).Put(boolPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, boolPls)).To(Succeed())
stringPls := &model.Playlist{
Name: "Genre Missing String2",
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsMissing{"genre": "true"}}},
}
Expect(ds.Playlist(ctx).Put(stringPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, stringPls)).To(Succeed())
boolResp := doReq("getPlaylist", "id", boolPls.ID)
stringResp := doReq("getPlaylist", "id", stringPls.ID)
@ -654,19 +654,19 @@ var _ = Describe("Playlist Endpoints", Ordered, func() {
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.Contains{"title": ""}},
}
Expect(ds.Playlist(ctx).Put(allPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, allPls)).To(Succeed())
missingPls := &model.Playlist{
Name: "Missing " + fieldName,
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsMissing{fieldName: true}}},
}
Expect(ds.Playlist(ctx).Put(missingPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, missingPls)).To(Succeed())
presentPls := &model.Playlist{
Name: "Present " + fieldName,
OwnerID: adminUser.ID,
Rules: &criteria.Criteria{Expression: criteria.All{criteria.IsPresent{fieldName: true}}},
}
Expect(ds.Playlist(ctx).Put(presentPls)).To(Succeed())
Expect(ds.Playlist().Put(ctx, presentPls)).To(Succeed())
allResp := doReq("getPlaylist", "id", allPls.ID)
missingResp := doReq("getPlaylist", "id", missingPls.ID)

View file

@ -18,14 +18,14 @@ var _ = Describe("Sharing Endpoints", Ordered, func() {
conf.Server.EnableSharing = true
setupTestDB()
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
Expect(albums).ToNot(BeEmpty())
albumID = albums[0].ID
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "Come Together"},
})
Expect(err).ToNot(HaveOccurred())
@ -139,7 +139,7 @@ var _ = Describe("Sharing Cross-User Isolation", Ordered, func() {
userA = createUser("share-user-a", "share-user-a", "Share User A", false)
userB = createUser("share-user-b", "share-user-b", "Share User B", false)
albums, err := ds.Album(ctx).GetAll(model.QueryOptions{
albums, err := ds.Album().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"album.name": "Abbey Road"},
})
Expect(err).ToNot(HaveOccurred())
@ -221,7 +221,7 @@ var _ = Describe("Sharing Downloadable Default", func() {
resp := doReq("createShare", append([]string{"id", albumID}, params...)...)
Expect(resp.Status).To(Equal(responses.StatusOK))
Expect(resp.Shares.Share).To(HaveLen(1))
share, err := ds.Share(ctx).Get(resp.Shares.Share[0].ID)
share, err := ds.Share().Get(ctx, resp.Shares.Share[0].ID)
Expect(err).ToNot(HaveOccurred())
return share
}
@ -248,7 +248,7 @@ var _ = Describe("Sharing Downloadable Default", func() {
resp := doReq("updateShare", "id", share.ID, "description", "Updated")
Expect(resp.Status).To(Equal(responses.StatusOK))
updated, err := ds.Share(ctx).Get(share.ID)
updated, err := ds.Share().Get(ctx, share.ID)
Expect(err).ToNot(HaveOccurred())
Expect(updated.Description).To(Equal("Updated"))
Expect(updated.Downloadable).To(BeTrue())
@ -261,7 +261,7 @@ var _ = Describe("Sharing Downloadable Default", func() {
resp := doReq("updateShare", "id", share.ID, "downloadable", "false")
Expect(resp.Status).To(Equal(responses.StatusOK))
updated, err := ds.Share(ctx).Get(share.ID)
updated, err := ds.Share().Get(ctx, share.ID)
Expect(err).ToNot(HaveOccurred())
Expect(updated.Downloadable).To(BeFalse())
Expect(updated.Description).To(Equal("Keep me"))
@ -273,7 +273,7 @@ var _ = Describe("Sharing Downloadable Default", func() {
resp := doReq("updateShare", "id", share.ID, "description", "")
Expect(resp.Status).To(Equal(responses.StatusOK))
updated, err := ds.Share(ctx).Get(share.ID)
updated, err := ds.Share().Get(ctx, share.ID)
Expect(err).ToNot(HaveOccurred())
Expect(updated.Description).To(BeEmpty())
})

View file

@ -103,14 +103,14 @@ var _ = Describe("Sonic Similarity Endpoints", func() {
)
BeforeEach(func() {
songs, err := ds.MediaFile(ctx).GetAll(model.QueryOptions{
songs, err := ds.MediaFile().GetAll(ctx, 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{
songs, err = ds.MediaFile().GetAll(ctx, model.QueryOptions{
Filters: squirrel.Eq{"title": "Something"},
})
Expect(err).ToNot(HaveOccurred())

Some files were not shown because too many files have changed in this diff Show more