mirror of
https://github.com/navidrome/navidrome.git
synced 2026-02-24 02:48:29 -05:00
* refactor: move playlist business logic from repositories to core.Playlists service Move authorization, permission checks, and orchestration logic from playlist repositories to the core.Playlists service, following the existing pattern used by core.Share and core.Library. Changes: - Expand core.Playlists interface with read, mutation, track management, and REST adapter methods - Add playlistRepositoryWrapper for REST Save/Update/Delete with permission checks (follows Share/Library pattern) - Simplify persistence/playlist_repository.go: remove isWritable(), auth checks from Delete()/Put()/updatePlaylist() - Simplify persistence/playlist_track_repository.go: remove isTracksEditable() and permission checks from Add/Delete/Reorder - Update Subsonic API handlers to route through service - Update Native API handlers to accept core.Playlists instead of model.DataStore * test: add coverage for playlist service methods and REST wrapper Add 30 new tests covering the service methods added during the playlist refactoring: - Delete: owner, admin, denied, not found - Create: new playlist, replace tracks, admin bypass, denied, not found - AddTracks: owner, admin, denied, smart playlist, not found - RemoveTracks: owner, smart playlist denied, non-owner denied - ReorderTrack: owner, smart playlist denied - NewRepository wrapper: Save (owner assignment, ID clearing), Update (owner, admin, denied, ownership change, not found), Delete (delegation with permission checks) Expand mockedPlaylistRepo with Get, Delete, Tracks, GetWithTracks, and rest.Persistable methods. Add mockedPlaylistTrackRepo for track operation verification. * fix: add authorization check to playlist Update method Added ownership verification to the Subsonic Update endpoint in the playlist service layer. The authorization check was present in the old repository code but was not carried over during the refactoring to the service layer, allowing any authenticated user to modify playlists they don't own via the Subsonic API. Also added corresponding tests for the Update method's permission logic. * refactor: improve playlist permission checks and error handling, add e2e tests Signed-off-by: Deluan <deluan@navidrome.org> * refactor: rename core.Playlists to playlists package and update references Signed-off-by: Deluan <deluan@navidrome.org> * refactor: rename playlists_internal_test.go to parse_m3u_test.go and update tests; add new parse_nsp.go and rest_adapter.go files Signed-off-by: Deluan <deluan@navidrome.org> * fix: block track mutations on smart playlists in Create and Update Create now rejects replacing tracks on smart playlists (pre-existing gap). Update now uses checkTracksEditable instead of checkWritable when track changes are requested, restoring the protection that was removed from the repository layer during the refactoring. Metadata-only updates on smart playlists remain allowed. * test: add smart playlist protection tests to ensure readonly behavior and mutation restrictions * refactor: optimize track removal and renumbering in playlists Signed-off-by: Deluan <deluan@navidrome.org> * refactor: implement track reordering in playlists with SQL updates Signed-off-by: Deluan <deluan@navidrome.org> * refactor: wrap track deletion and reordering in transactions for consistency Signed-off-by: Deluan <deluan@navidrome.org> * refactor: remove unused getTracks method from playlistTrackRepository Signed-off-by: Deluan <deluan@navidrome.org> * refactor: optimize playlist track renumbering with CTE-based UPDATE Replace the DELETE + re-INSERT renumbering strategy with a two-step UPDATE approach using a materialized CTE and ROW_NUMBER() window function. The previous approach (SELECT all IDs, DELETE all tracks, re-INSERT in chunks of 200) required 13 SQL operations for a 2000-track playlist. The new approach uses just 2 UPDATEs: first negating all IDs to clear the positive space, then assigning sequential positions via UPDATE...FROM with a CTE. This avoids the UNIQUE constraint violations that affected the original correlated subquery while reducing per-delete request time from ~110ms to ~12ms on a 2000-track playlist. Signed-off-by: Deluan <deluan@navidrome.org> * refactor: rename New function to NewPlaylists for clarity Signed-off-by: Deluan <deluan@navidrome.org> * refactor: update mock playlist repository and tests for consistency Signed-off-by: Deluan <deluan@navidrome.org> --------- Signed-off-by: Deluan <deluan@navidrome.org>
227 lines
6.8 KiB
Go
227 lines
6.8 KiB
Go
package nativeapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"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"
|
|
)
|
|
|
|
type restHandler = func(rest.RepositoryConstructor, ...rest.Logger) http.HandlerFunc
|
|
|
|
func playlistTracksHandler(pls playlists.Playlists, handler restHandler, 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(func(ctx context.Context) rest.Repository { return tracks }).ServeHTTP(w, r)
|
|
}
|
|
}
|
|
|
|
func getPlaylist(pls playlists.Playlists) http.HandlerFunc {
|
|
handler := playlistTracksHandler(pls, rest.GetAll, 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, 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")
|
|
disposition := fmt.Sprintf("attachment; filename=\"%s.m3u\"", playlist.Name)
|
|
w.Header().Set("Content-Disposition", disposition)
|
|
|
|
_, 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)
|
|
http.Error(w, err.Error(), 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 {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddAlbums(ctx, playlistId, payload.AlbumIds); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddArtists(ctx, playlistId, payload.ArtistIds); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
count += c
|
|
if c, err = pls.AddDiscs(ctx, playlistId, payload.Discs); err != nil {
|
|
http.Error(w, err.Error(), 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 errors.Is(err, model.ErrNotAuthorized) {
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
return
|
|
}
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 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
|
|
}
|
|
}
|