navidrome/server/subsonic/browsing.go
Deluan Quintão b293b96256
refactor(persistence): stateless repositories with per-call context (#6149)
* refactor(persistence): adopt generic deluan/rest repository API

Pin deluan/rest to the refactor branch. REST-facing repository methods
take a context and return typed values. Drop DataStore.Resource and
ResourceRepository; the native API names typed repositories directly
through a per-request adapter that later commits remove.

* refactor(persistence): base repository helpers take a context

* refactor(persistence): LibraryRepository takes a context per call

* refactor(persistence): PropertyRepository takes a context per call

* refactor(persistence): UserPropsRepository takes a context per call

* refactor(persistence): TranscodingRepository takes a context per call

* refactor(persistence): ShareRepository takes a context per call

* refactor(persistence): PlayerRepository takes a context per call

* refactor(persistence): RadioRepository takes a context per call

* refactor(persistence): PlayQueueRepository takes a context per call

* refactor(persistence): Tag and Genre repositories take a context per call

* refactor(persistence): PluginRepository takes a context per call

* refactor(persistence): Scrobble repositories take a context per call

* refactor(persistence): FolderRepository takes a context per call

* refactor(persistence): Artwork repositories take a context per call

* refactor(persistence): UserRepository takes a context per call

* refactor(persistence): ArtistRepository takes a context per call

ReadAll no longer rewrites the shared sort mappings for the role filter;
it works on a per-call copy.

* test(persistence): assert artist role sort sanitization in ReadAll

* refactor(persistence): AlbumRepository takes a context per call

* test(persistence): pass the test context to album repository helpers

* refactor(persistence): MediaFileRepository takes a context per call

* refactor(persistence): Playlist repositories take a context per call

* refactor(persistence): build all repositories once per store

* refactor(core): REST repository wrappers are built once

* refactor(persistence): repositories are stateless

Remove the context field from the base repository and the per-request
REST adapter. Enable the containedctx linter so no repository can hold a
request context again.

* chore(lint): skip containedctx in test files

* refactor: share simplifications from the stateless repositories sweep

Add deleteOwnedAll on sqlRepository and use it in player/share Delete
to remove the duplicated bulk-delete loop; have Share.Repository()
return model.ShareRepository so subsonic sharing.go drops its repeated
type assertions.

* chore(core): assert REST wrappers implement Persistable

* chore: reformat imports

* perf(persistence): build repositories on first use

Each transaction store used to construct all 21 repositories up front,
paying for filter and sort mapping setup the block never touched. Fields
are now sync.OnceValue thunks, so a store only builds what it uses.

* fix(persistence): clean plugin references per deleted user

A bulk user delete that fails on a later id had already removed the
earlier rows but skipped their plugin cleanup. Cleanup now runs right
after each successful delete.

* fix(core): unload disabled plugins even when a user delete fails

A bulk delete can fail on a later id after earlier users were removed
and their plugins auto-disabled. The wrapper returned before unloading,
leaving those plugins running until the next successful delete or a
restart.

* chore(deps): pin deluan/rest to v1.0.1

Replaces the pseudo-version of the refactor branch with the tagged
release. REST error messages now name the bare type (Artist, not
model.Artist).

* test: use the spec context instead of context.Background()

Replace the context.Background()/context.TODO() calls this branch added
to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so
repository calls are bound to the running spec's lifetime.

* test: declare the spec context once per Describe

Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
2026-09-25 18:06:10 -04:00

480 lines
13 KiB
Go

package subsonic
import (
"context"
"errors"
"net/http"
"time"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/core/publicurl"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/server/filter"
"github.com/navidrome/navidrome/server/subsonic/responses"
"github.com/navidrome/navidrome/utils/req"
"github.com/navidrome/navidrome/utils/slice"
)
func (api *Router) GetMusicFolders(r *http.Request) (*responses.Subsonic, error) {
libraries := getUserAccessibleLibraries(r.Context())
folders := make([]responses.MusicFolder, len(libraries))
for i, f := range libraries {
folders[i].Id = int32(f.ID)
folders[i].Name = f.Name
}
response := newResponse()
response.MusicFolders = &responses.MusicFolders{Folders: folders}
return response, nil
}
func (api *Router) getArtist(r *http.Request, libIds []int, ifModifiedSince time.Time) (model.ArtistIndexes, int64, error) {
ctx := r.Context()
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
}
lastScan := time.Now()
if lastScanStr != "" {
lastScan, err = time.Parse(time.RFC3339, lastScanStr)
}
var indexes model.ArtistIndexes
if lastScan.After(ifModifiedSince) {
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
}
if len(indexes) == 0 {
log.Debug(ctx, "No artists found in library", "libId", libIds)
return nil, 0, newError(responses.ErrorDataNotFound, "Library not found or empty")
}
}
return indexes, lastScan.UnixMilli(), err
}
func (api *Router) getArtistIndex(r *http.Request, libIds []int, ifModifiedSince time.Time) (*responses.Indexes, error) {
indexes, modified, err := api.getArtist(r, libIds, ifModifiedSince)
if err != nil {
return nil, err
}
res := &responses.Indexes{
IgnoredArticles: conf.Server.IgnoredArticles,
LastModified: modified,
}
res.Index = make([]responses.Index, len(indexes))
for i, idx := range indexes {
res.Index[i].Name = idx.ID
res.Index[i].Artists = slice.MapWithArg(idx.Artists, r, toArtist)
}
return res, nil
}
func (api *Router) getArtistIndexID3(r *http.Request, libIds []int, ifModifiedSince time.Time) (*responses.Artists, error) {
indexes, modified, err := api.getArtist(r, libIds, ifModifiedSince)
if err != nil {
return nil, err
}
res := &responses.Artists{
IgnoredArticles: conf.Server.IgnoredArticles,
LastModified: modified,
}
res.Index = make([]responses.IndexID3, len(indexes))
for i, idx := range indexes {
res.Index[i].Name = idx.ID
res.Index[i].Artists = slice.MapWithArg(idx.Artists, r, toArtistID3)
}
return res, nil
}
func (api *Router) GetIndexes(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
musicFolderIds, _ := selectedMusicFolderIds(r, false)
ifModifiedSince := p.TimeOr("ifModifiedSince", time.Time{})
res, err := api.getArtistIndex(r, musicFolderIds, ifModifiedSince)
if err != nil {
return nil, err
}
response := newResponse()
response.Indexes = res
return response, nil
}
func (api *Router) GetArtists(r *http.Request) (*responses.Subsonic, error) {
musicFolderIds, _ := selectedMusicFolderIds(r, false)
res, err := api.getArtistIndexID3(r, musicFolderIds, time.Time{})
if err != nil {
return nil, err
}
response := newResponse()
response.Artist = res
return response, nil
}
func (api *Router) GetMusicDirectory(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, _ := p.String("id")
ctx := r.Context()
entity, err := model.GetEntityByID(ctx, api.ds, id)
if errors.Is(err, model.ErrNotFound) {
log.Error(r, "Requested ID not found ", "id", id)
return nil, newError(responses.ErrorDataNotFound, "Directory not found")
}
if err != nil {
log.Error(err)
return nil, err
}
var dir *responses.Directory
switch v := entity.(type) {
case *model.Artist:
dir, err = api.buildArtistDirectory(ctx, v)
case *model.Album:
dir, err = api.buildAlbumDirectory(ctx, v)
default:
log.Error(r, "Requested ID of invalid type", "id", id, "entity", v)
return nil, newError(responses.ErrorDataNotFound, "Directory not found")
}
if err != nil {
log.Error(err)
return nil, err
}
response := newResponse()
response.Directory = dir
return response, nil
}
func (api *Router) GetArtist(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, _ := p.String("id")
ctx := r.Context()
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")
}
if err != nil {
log.Error(ctx, "Error retrieving artist", "id", id, err)
return nil, err
}
response := newResponse()
response.ArtistWithAlbumsID3, err = api.buildArtist(r, artist)
if err != nil {
log.Error(ctx, "Error retrieving albums by artist", "id", artist.ID, "name", artist.Name, err)
}
return response, err
}
func (api *Router) GetAlbum(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, _ := p.String("id")
ctx := r.Context()
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")
}
if err != nil {
log.Error(ctx, "Error retrieving album", "id", id, err)
return nil, err
}
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
}
response := newResponse()
response.AlbumWithSongsID3 = api.buildAlbum(ctx, album, mfs)
return response, nil
}
func (api *Router) GetAlbumInfo(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, err := p.String("id")
ctx := r.Context()
if err != nil {
return nil, err
}
album, err := api.provider.UpdateAlbumInfo(ctx, id)
if err != nil {
return nil, err
}
response := newResponse()
response.AlbumInfo = &responses.AlbumInfo{}
response.AlbumInfo.Notes = album.Description
if !album.ImageAbsent {
response.AlbumInfo.SmallImageUrl = publicurl.ImageURL(r.Context(), album.CoverArtID(), 300)
response.AlbumInfo.MediumImageUrl = publicurl.ImageURL(r.Context(), album.CoverArtID(), 600)
response.AlbumInfo.LargeImageUrl = publicurl.ImageURL(r.Context(), album.CoverArtID(), 1200)
}
response.AlbumInfo.LastFmUrl = album.ExternalUrl
response.AlbumInfo.MusicBrainzID = album.MbzAlbumID
return response, nil
}
func (api *Router) GetSong(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, _ := p.String("id")
ctx := r.Context()
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")
}
if err != nil {
log.Error(r, "Error retrieving MediaFile", "id", id, err)
return nil, err
}
response := newResponse()
response.Song = new(childFromMediaFile(ctx, *mf))
return response, nil
}
func (api *Router) GetGenres(r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
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
}
for i, g := range genres {
if g.Name == "" {
genres[i].Name = "<Empty>"
}
}
response := newResponse()
response.Genres = toGenres(genres)
return response, nil
}
func (api *Router) getArtistInfo(r *http.Request) (*responses.ArtistInfoBase, *model.Artists, error) {
ctx := r.Context()
p := req.Params(r)
id, err := p.String("id")
if err != nil {
return nil, nil, err
}
count := p.IntOr("count", 20)
includeNotPresent := p.BoolOr("includeNotPresent", false)
artist, err := api.provider.UpdateArtistInfo(ctx, id, count, includeNotPresent)
if err != nil {
return nil, nil, err
}
base := responses.ArtistInfoBase{}
base.Biography = artist.Biography
if !artist.ImageAbsent {
base.SmallImageUrl = publicurl.ImageURL(r.Context(), artist.CoverArtID(), 300)
base.MediumImageUrl = publicurl.ImageURL(r.Context(), artist.CoverArtID(), 600)
base.LargeImageUrl = publicurl.ImageURL(r.Context(), artist.CoverArtID(), 1200)
}
base.LastFmUrl = artist.ExternalUrl
base.MusicBrainzID = artist.MbzArtistID
return &base, &artist.SimilarArtists, nil
}
func (api *Router) GetArtistInfo(r *http.Request) (*responses.Subsonic, error) {
base, similarArtists, err := api.getArtistInfo(r)
if err != nil {
return nil, err
}
response := newResponse()
response.ArtistInfo = &responses.ArtistInfo{}
response.ArtistInfo.ArtistInfoBase = *base
for _, s := range *similarArtists {
similar := toArtist(r, s)
if s.ID == "" {
similar.Id = "-1"
}
response.ArtistInfo.SimilarArtist = append(response.ArtistInfo.SimilarArtist, similar)
}
return response, nil
}
func (api *Router) GetArtistInfo2(r *http.Request) (*responses.Subsonic, error) {
base, similarArtists, err := api.getArtistInfo(r)
if err != nil {
return nil, err
}
response := newResponse()
response.ArtistInfo2 = &responses.ArtistInfo2{}
response.ArtistInfo2.ArtistInfoBase = *base
for _, s := range *similarArtists {
similar := toArtistID3(r, s)
if s.ID == "" {
similar.Id = "-1"
}
response.ArtistInfo2.SimilarArtist = append(response.ArtistInfo2.SimilarArtist, similar)
}
return response, nil
}
func (api *Router) GetSimilarSongs(r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
p := req.Params(r)
id, err := p.String("id")
if err != nil {
return nil, err
}
count := p.IntOr("count", 50)
songs, err := api.provider.SimilarSongs(ctx, id, count)
if err != nil {
return nil, err
}
response := newResponse()
response.SimilarSongs = &responses.SimilarSongs{
Song: slice.MapWithArg(songs, ctx, childFromMediaFile),
}
return response, nil
}
func (api *Router) GetSimilarSongs2(r *http.Request) (*responses.Subsonic, error) {
res, err := api.GetSimilarSongs(r)
if err != nil {
return nil, err
}
response := newResponse()
response.SimilarSongs2 = &responses.SimilarSongs2{
Song: res.SimilarSongs.Song,
}
return response, nil
}
func (api *Router) GetTopSongs(r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
p := req.Params(r)
id, idErr := p.String("id")
artist, err := p.String("artist")
if err != nil && idErr != nil {
return nil, err
}
count := p.IntOr("count", 50)
songs, err := api.provider.TopSongs(ctx, artist, id, count)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, err
}
response := newResponse()
response.TopSongs = &responses.TopSongs{
Song: slice.MapWithArg(songs, ctx, childFromMediaFile),
}
return response, nil
}
func (api *Router) buildArtistDirectory(ctx context.Context, artist *model.Artist) (*responses.Directory, error) {
dir := &responses.Directory{}
dir.Id = artist.ID
dir.Name = artist.Name
dir.PlayCount = artist.PlayCount
if artist.PlayCount > 0 {
dir.Played = artist.PlayDate
}
dir.AlbumCount = getArtistAlbumCount(artist)
dir.UserRating = int32(artist.Rating)
if conf.Server.Subsonic.EnableAverageRating {
dir.AverageRating = artist.AverageRating
}
if artist.Starred {
dir.Starred = artist.StarredAt
}
albums, err := api.ds.Album().GetAll(ctx, filter.AlbumsByArtistID(artist.ID))
if err != nil {
return nil, err
}
dir.Child = slice.MapWithArg(albums, ctx, childFromAlbum)
return dir, nil
}
func (api *Router) buildArtist(r *http.Request, artist *model.Artist) (*responses.ArtistWithAlbumsID3, error) {
ctx := r.Context()
a := &responses.ArtistWithAlbumsID3{}
a.ArtistID3 = toArtistID3(r, *artist)
albums, err := api.ds.Album().GetAll(ctx, filter.AlbumsByArtistID(artist.ID))
if err != nil {
return nil, err
}
a.Album = slice.MapWithArg(albums, ctx, buildAlbumID3)
return a, nil
}
func (api *Router) buildAlbumDirectory(ctx context.Context, album *model.Album) (*responses.Directory, error) {
dir := &responses.Directory{}
dir.Id = album.ID
dir.Name = album.FullName()
dir.Parent = album.AlbumArtistID
dir.PlayCount = album.PlayCount
if album.PlayCount > 0 {
dir.Played = album.PlayDate
}
dir.UserRating = int32(album.Rating)
if conf.Server.Subsonic.EnableAverageRating {
dir.AverageRating = album.AverageRating
}
dir.SongCount = int32(album.SongCount)
dir.CoverArt = coverArtOrEmpty(album.CoverArtID(), album.ImageAbsent)
if album.Starred {
dir.Starred = album.StarredAt
}
mfs, err := api.ds.MediaFile().GetAll(ctx, filter.SongsByAlbum(album.ID))
if err != nil {
return nil, err
}
dir.Child = slice.MapWithArg(mfs, ctx, childFromMediaFile)
return dir, nil
}
func (api *Router) buildAlbum(ctx context.Context, album *model.Album, mfs model.MediaFiles) *responses.AlbumWithSongsID3 {
dir := &responses.AlbumWithSongsID3{}
dir.AlbumID3 = buildAlbumID3(ctx, *album)
dir.Song = slice.MapWithArg(mfs, ctx, childFromMediaFile)
return dir
}