Files
minstrel/internal/subsonic/playlistwrite.go
T
bvandeusenandClaude Opus 5.5 e1f270362d
release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
chore(release): everything that ships points at GitHub and GHCR (#7897)
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every
  import and the Dockerfile's version ldflags.
- buildinfo.ProjectURL, the contact outside services see in Minstrel's
  User-Agent: https://github.com/Fabled-Sword/minstrel.
- README's compose example pulls ghcr.io/fabled-sword/minstrel:latest.
- docs/security.md sends problem reports to the GitHub issues.
- The demo-library stack builds Minstrel from the checkout, since :dev
  is not published to GHCR.
- hygiene.go's same-site example uses example.com names.

The workbench CI (.gitea/, ci/, export-ignored) still builds and
publishes :dev to the private registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:28:16 -05:00

284 lines
8.0 KiB
Go

package subsonic
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/jackc/pgx/v5/pgtype"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/playlists"
)
// ---- createPlaylist / updatePlaylist / deletePlaylist ----
//
// A listener changes only their own playlists. Someone else's private
// playlist reads as absent, as it does in getPlaylist; someone else's public
// one, and a daily mix, which Minstrel rebuilds itself, answer "not
// authorized".
// createPlaylist makes a playlist from name and the songs in songId, or, with
// playlistId, replaces that playlist's songs (and its name, when name is
// given). It answers with the playlist, as getPlaylist does.
func (h *pickHandlers) createPlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
params := r.URL.Query()
songs, ok := songIDs(w, r, params["songId"])
if !ok {
return
}
name := params.Get("name")
ctx := r.Context()
var id pgtype.UUID
if raw := params.Get("playlistId"); raw != "" {
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
id = detail.ID
if err := h.playlists.ReplaceTracks(ctx, user.ID, id, songs); err != nil {
h.failPlaylistChange(w, r, err)
return
}
if name != "" {
if _, err := h.playlists.Update(ctx, user.ID, id, playlists.UpdateInput{Name: &name}); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
} else {
if name == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: name or playlistId")
return
}
created, err := h.playlists.Create(ctx, user.ID, name, "", false)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
id = created.ID
if len(songs) > 0 {
if err := h.playlists.AppendTracks(ctx, user.ID, id, songs); err != nil {
// A list that failed to fill isn't the one asked for.
if derr := h.playlists.Delete(ctx, user.ID, id); derr != nil {
h.logger.Warn("subsonic: remove unfilled playlist", "err", derr)
}
h.failPlaylistChange(w, r, err)
return
}
}
}
detail, err := h.playlists.Get(ctx, user.ID, id)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
h.writePlaylist(w, r, detail)
}
// updatePlaylist renames a playlist (name), sets its comment and whether it is
// public, removes the songs at songIndexToRemove and adds those in
// songIdToAdd at the end. Each index counts the songs as getPlaylist lists
// them before this call, so the song removed is the one the app showed.
func (h *pickHandlers) updatePlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
params := r.URL.Query()
raw := params.Get("playlistId")
if raw == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: playlistId")
return
}
add, ok := songIDs(w, r, params["songIdToAdd"])
if !ok {
return
}
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
ctx := r.Context()
// Every song to add and every index is checked before anything
// changes: the name, comment, removals and additions are separate
// writes, so a bad one found partway would answer an error over a
// playlist already half changed.
missing, err := firstMissingSong(ctx, dbq.New(h.pool), add)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
if missing >= 0 {
WriteFail(w, r, ErrDataNotFound, "Song not found: "+params["songIdToAdd"][missing])
return
}
var remove []int32
if indexes := params["songIndexToRemove"]; len(indexes) > 0 {
_, positions, err := shownEntries(ctx, dbq.New(h.pool), detail)
if err != nil {
h.failPlaylistChange(w, r, err)
return
}
for _, s := range indexes {
i, err := strconv.Atoi(s)
if err != nil || i < 0 || i >= len(positions) {
WriteFail(w, r, ErrDataNotFound, "No song at index "+s)
return
}
remove = append(remove, positions[i])
}
}
var in playlists.UpdateInput
if params.Has("name") {
v := params.Get("name")
in.Name = &v
}
if params.Has("comment") {
v := params.Get("comment")
in.Description = &v
}
if params.Has("public") {
v, err := strconv.ParseBool(params.Get("public"))
if err != nil {
WriteFail(w, r, ErrGeneric, "public must be true or false")
return
}
in.IsPublic = &v
}
if in.Name != nil || in.Description != nil || in.IsPublic != nil {
if _, err := h.playlists.Update(ctx, user.ID, detail.ID, in); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
if len(remove) > 0 {
if err := h.playlists.RemovePositions(ctx, user.ID, detail.ID, remove); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
if len(add) > 0 {
if err := h.playlists.AppendTracks(ctx, user.ID, detail.ID, add); err != nil {
h.failPlaylistChange(w, r, err)
return
}
}
Write(w, r, NewEnvelope("ok"))
}
// deletePlaylist deletes the playlist id.
func (h *pickHandlers) deletePlaylist(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
return
}
raw := r.URL.Query().Get("id")
if raw == "" {
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
return
}
detail, ok := h.ownPlaylist(w, r, user, raw)
if !ok {
return
}
if err := h.playlists.Delete(r.Context(), user.ID, detail.ID); err != nil {
h.failPlaylistChange(w, r, err)
return
}
Write(w, r, NewEnvelope("ok"))
}
// ownPlaylist loads the playlist raw names for a change by user, or answers
// with why it can't be changed and returns false.
func (h *pickHandlers) ownPlaylist(w http.ResponseWriter, r *http.Request, user dbq.User, raw string) (*playlists.PlaylistDetail, bool) {
id, ok := parseUUID(raw)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Playlist not found")
return nil, false
}
detail, err := h.playlists.Get(r.Context(), user.ID, id)
switch {
case errors.Is(err, playlists.ErrForbidden):
// Get refuses only someone else's private list, which reads as
// absent.
h.failPlaylistChange(w, r, playlists.ErrNotFound)
return nil, false
case err != nil:
h.failPlaylistChange(w, r, err)
return nil, false
case detail.UserID != user.ID:
h.failPlaylistChange(w, r, playlists.ErrForbidden)
return nil, false
case detail.Kind == "system":
h.failPlaylistChange(w, r, playlists.ErrSystemPlaylistReadonly)
return nil, false
}
return detail, true
}
// failPlaylistChange answers a playlist change the service refused.
func (h *pickHandlers) failPlaylistChange(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, playlists.ErrNotFound):
WriteFail(w, r, ErrDataNotFound, "Playlist not found")
case errors.Is(err, playlists.ErrTrackNotFound):
WriteFail(w, r, ErrDataNotFound, "Song not found")
case errors.Is(err, playlists.ErrForbidden):
WriteFail(w, r, ErrNotAuthorized, "Only the playlist's owner can change it")
case errors.Is(err, playlists.ErrSystemPlaylistReadonly):
WriteFail(w, r, ErrNotAuthorized, "Minstrel's mixes can't be changed")
case errors.Is(err, playlists.ErrInvalidInput):
WriteFail(w, r, ErrGeneric, "A playlist needs a name")
default:
h.logger.Error("subsonic: change playlist", "err", err)
WriteFail(w, r, ErrGeneric, "Playlist unavailable")
}
}
// songIDs parses repeated song id parameters, or answers that one names no
// song and returns false.
func songIDs(w http.ResponseWriter, r *http.Request, raw []string) ([]pgtype.UUID, bool) {
ids := make([]pgtype.UUID, 0, len(raw))
for _, s := range raw {
id, ok := parseUUID(s)
if !ok {
WriteFail(w, r, ErrDataNotFound, "Song not found: "+s)
return nil, false
}
ids = append(ids, id)
}
return ids, true
}
// firstMissingSong returns the index of the first of ids that names no
// track, or -1 when every one exists.
func firstMissingSong(ctx context.Context, q *dbq.Queries, ids []pgtype.UUID) (int, error) {
if len(ids) == 0 {
return -1, nil
}
found, err := q.GetTracksByIDs(ctx, ids)
if err != nil {
return -1, fmt.Errorf("look up songs: %w", err)
}
have := make(map[pgtype.UUID]struct{}, len(found))
for _, t := range found {
have[t.ID] = struct{}{}
}
for i, id := range ids {
if _, ok := have[id]; !ok {
return i, nil
}
}
return -1, nil
}