Files
minstrel/internal/subsonic/playlistwrite.go
T

251 lines
7.3 KiB
Go

package subsonic
import (
"errors"
"net/http"
"strconv"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
"git.fabledsword.com/bvandeusen/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 := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
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 := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
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 index is checked before anything changes.
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 := UserFromContext(r.Context())
if !ok {
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
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
}