mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 18:37:09 +02:00
* 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.
249 lines
7.6 KiB
Go
249 lines
7.6 KiB
Go
package nativeapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/deluan/rest"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/navidrome/navidrome/core/playlists"
|
|
"github.com/navidrome/navidrome/log"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/utils/req"
|
|
"github.com/navidrome/navidrome/utils/str"
|
|
)
|
|
|
|
// writePlaylistError maps a playlist service error to an HTTP status, or defaultStatus if unknown.
|
|
func writePlaylistError(w http.ResponseWriter, err error, defaultStatus int) {
|
|
switch {
|
|
case errors.Is(err, model.ErrNotFound):
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
case errors.Is(err, model.ErrNotAuthorized):
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
case errors.Is(err, model.ErrPlaylistNotEditable):
|
|
http.Error(w, err.Error(), http.StatusConflict)
|
|
default:
|
|
http.Error(w, err.Error(), defaultStatus)
|
|
}
|
|
}
|
|
|
|
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))
|
|
if tracks == nil {
|
|
http.Error(w, "not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
handler(tracks).ServeHTTP(w, r)
|
|
}
|
|
}
|
|
|
|
func getPlaylist(pls playlists.Playlists) http.HandlerFunc {
|
|
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) {
|
|
if strings.ToLower(r.Header.Get("accept")) == "audio/x-mpegurl" {
|
|
handleExportPlaylist(pls)(w, r)
|
|
return
|
|
}
|
|
handler(w, r)
|
|
}
|
|
}
|
|
|
|
func getPlaylistTrack(pls playlists.Playlists) http.HandlerFunc {
|
|
return playlistTracksHandler(pls, rest.Get[model.PlaylistTrack], func(*http.Request) bool { return true })
|
|
}
|
|
|
|
func createPlaylistFromM3U(pls playlists.Playlists) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
pl, err := pls.ImportM3U(ctx, r.Body)
|
|
if err != nil {
|
|
log.Error(r.Context(), "Error parsing playlist", err)
|
|
// TODO: consider returning StatusBadRequest for playlists that are malformed
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, err = w.Write([]byte(pl.ToM3U8())) //nolint:gosec
|
|
if err != nil {
|
|
log.Error(ctx, "Error sending m3u contents", err)
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func handleExportPlaylist(pls playlists.Playlists) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
plsId := chi.URLParam(r, "playlistId")
|
|
playlist, err := pls.GetWithTracks(ctx, plsId)
|
|
if errors.Is(err, model.ErrNotFound) {
|
|
log.Warn(ctx, "Playlist not found", "playlistId", plsId)
|
|
http.Error(w, "not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
log.Error(ctx, "Error retrieving the playlist", "playlistId", plsId, err)
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
log.Debug(ctx, "Exporting playlist as M3U", "playlistId", plsId, "name", playlist.Name)
|
|
w.Header().Set("Content-Type", "audio/x-mpegurl")
|
|
w.Header().Set("Content-Disposition", str.ContentDispositionAttachment(playlist.Name+".m3u"))
|
|
|
|
_, err = w.Write([]byte(playlist.ToM3U8())) //nolint:gosec
|
|
if err != nil {
|
|
log.Error(ctx, "Error sending playlist", "name", playlist.Name)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func deleteFromPlaylist(pls playlists.Playlists) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
p := req.Params(r)
|
|
playlistId, _ := p.String(":playlistId")
|
|
ids := p.Strings("id")
|
|
err := pls.RemoveTracks(r.Context(), playlistId, ids)
|
|
if len(ids) == 1 && errors.Is(err, model.ErrNotFound) {
|
|
log.Warn(r.Context(), "Track not found in playlist", "playlistId", playlistId, "id", ids[0])
|
|
http.Error(w, "not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
if err != nil {
|
|
log.Error(r.Context(), "Error deleting tracks from playlist", "playlistId", playlistId, "ids", ids, err)
|
|
writePlaylistError(w, err, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
writeDeleteManyResponse(w, r, ids)
|
|
}
|
|
}
|
|
|
|
func addToPlaylist(pls playlists.Playlists) http.HandlerFunc {
|
|
type addTracksPayload struct {
|
|
Ids []string `json:"ids"`
|
|
AlbumIds []string `json:"albumIds"`
|
|
ArtistIds []string `json:"artistIds"`
|
|
Discs []model.DiscID `json:"discs"`
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
p := req.Params(r)
|
|
playlistId, _ := p.String(":playlistId")
|
|
var payload addTracksPayload
|
|
err := json.NewDecoder(r.Body).Decode(&payload)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
count, c := 0, 0
|
|
if c, err = pls.AddTracks(ctx, playlistId, payload.Ids); err != nil {
|
|
writePlaylistError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddAlbums(ctx, playlistId, payload.AlbumIds); err != nil {
|
|
writePlaylistError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddArtists(ctx, playlistId, payload.ArtistIds); err != nil {
|
|
writePlaylistError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddDiscs(ctx, playlistId, payload.Discs); err != nil {
|
|
writePlaylistError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
|
|
// Must return an object with an ID, to satisfy ReactAdmin `create` call
|
|
_, err = fmt.Fprintf(w, `{"added":%d}`, count) //nolint:gosec
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
}
|
|
|
|
func reorderItem(pls playlists.Playlists) http.HandlerFunc {
|
|
type reorderPayload struct {
|
|
InsertBefore string `json:"insert_before"`
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
p := req.Params(r)
|
|
playlistId, _ := p.String(":playlistId")
|
|
id := p.IntOr(":id", 0)
|
|
if id == 0 {
|
|
http.Error(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var payload reorderPayload
|
|
err := json.NewDecoder(r.Body).Decode(&payload)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
newPos, err := strconv.Atoi(payload.InsertBefore)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
err = pls.ReorderTrack(ctx, playlistId, id, newPos)
|
|
if err != nil {
|
|
writePlaylistError(w, err, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
_, err = w.Write(fmt.Appendf(nil, `{"id":"%d"}`, id)) //nolint:gosec
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
}
|
|
|
|
func getSongPlaylists(svc playlists.Playlists) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
p := req.Params(r)
|
|
trackId, _ := p.String(":id")
|
|
playlists, err := svc.GetPlaylists(r.Context(), trackId)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
data, err := json.Marshal(playlists)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
_, _ = w.Write(data) //nolint:gosec
|
|
}
|
|
}
|
|
|
|
func uploadPlaylistImage(pls playlists.Playlists) http.HandlerFunc {
|
|
return handleImageUpload(func(ctx context.Context, reader io.Reader, ext string) error {
|
|
playlistId := chi.URLParamFromCtx(ctx, "id")
|
|
return pls.SetImage(ctx, playlistId, reader, ext)
|
|
})
|
|
}
|
|
|
|
func deletePlaylistImage(pls playlists.Playlists) http.HandlerFunc {
|
|
return handleImageDelete(func(ctx context.Context) error {
|
|
playlistId := chi.URLParamFromCtx(ctx, "id")
|
|
return pls.RemoveImage(ctx, playlistId)
|
|
})
|
|
}
|