release / go (push) Successful in 1m56s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m0s
release / android (push) Successful in 4m20s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
- library.ProbeDurationMs and IsAudioFile, and db.MigrationsFS, had no callers. - The delta sync logged and hydrated like and playlist changes on every like, playlist edit and duplicate merge, including a GetPlaylistsByIDs query per sync. Android applies only artists, albums and tracks, and the web doesn't sync; likes and playlists reach both through their own endpoints and live events. The like and playlist-entry deletes also went to every caller unscoped, user ids included. They are no longer written or served, and migration 0112 clears the rows already logged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
683 lines
24 KiB
Go
683 lines
24 KiB
Go
// Package playlists implements the user-facing playlist CRUD service.
|
|
//
|
|
// Visibility model:
|
|
// - Playlists are private by default. Only the owner sees private rows
|
|
// in List, Get, and is allowed to mutate them via Update / Delete.
|
|
// - is_public = true makes a playlist readable by any authenticated
|
|
// user; mutations are still owner-only.
|
|
//
|
|
// Track-list mutations (AppendTracks / RemoveTrack / Reorder) bump
|
|
// the denormalized rollups (track_count, duration_sec) on the playlist
|
|
// row and trigger cover-art regeneration via GenerateCollage. The
|
|
// collage generator itself lives alongside in collage.go.
|
|
package playlists
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/eventbus"
|
|
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
|
)
|
|
|
|
// Typed errors. The API layer maps each to its wire status code; tests
|
|
// use errors.Is to assert the right path was taken.
|
|
//
|
|
// ErrNotFound aliases apierror.ErrNotFound so handlers can errors.Is
|
|
// against the shared sentinel; existing playlists.ErrNotFound callsites
|
|
// still resolve to the same pointer.
|
|
var (
|
|
ErrNotFound = apierror.ErrNotFound
|
|
ErrForbidden = errors.New("playlists: forbidden")
|
|
ErrInvalidInput = errors.New("playlists: invalid input")
|
|
ErrTrackNotFound = errors.New("playlists: track not found")
|
|
ErrSystemPlaylistReadonly = errors.New("playlists: system playlist is read-only")
|
|
ErrListChanged = errors.New("playlists: the list changed")
|
|
)
|
|
|
|
// Service wires the sqlc queries + on-disk cover-art directory together.
|
|
// dataDir is the root for cached cover-art collages (cover_path on the
|
|
// playlist row is stored relative to this directory so the install can
|
|
// be relocated without rewriting rows).
|
|
type Service struct {
|
|
pool *pgxpool.Pool
|
|
logger *slog.Logger
|
|
dataDir string
|
|
bus *eventbus.Bus
|
|
}
|
|
|
|
// NewService constructs a Service. A nil logger gets slog.Default().
|
|
func NewService(pool *pgxpool.Pool, logger *slog.Logger, dataDir string) *Service {
|
|
if logger == nil {
|
|
logger = slog.Default()
|
|
}
|
|
return &Service{pool: pool, logger: logger, dataDir: dataDir}
|
|
}
|
|
|
|
// PublishTo makes every change to a playlist, from any client, tell the
|
|
// owner's signed-in clients through bus, so each can refresh what it shows.
|
|
func (s *Service) PublishTo(bus *eventbus.Bus) {
|
|
s.bus = bus
|
|
}
|
|
|
|
// PlaylistRow is the wire shape returned by Create / Update / List /
|
|
// the embedded portion of Get. owner_username is denormalized in via
|
|
// the JOIN on users so callers don't have to resolve it themselves.
|
|
type PlaylistRow struct {
|
|
ID pgtype.UUID
|
|
UserID pgtype.UUID
|
|
OwnerUsername string
|
|
Name string
|
|
Description string
|
|
IsPublic bool
|
|
Kind string // 'user' | 'system'
|
|
SystemVariant *string // 'for_you' | 'songs_like_artist' | nil
|
|
SeedArtistID pgtype.UUID // Valid=true only for 'songs_like_artist'
|
|
CoverPath *string
|
|
// CoverAlbumIDs are up to six distinct albums with cover art, in the
|
|
// order they first appear in the playlist. Filled by List and Get;
|
|
// empty for a playlist with no covers, and on the rows Create and
|
|
// Update return.
|
|
CoverAlbumIDs []pgtype.UUID
|
|
// ShelfRank is a system mix's place on its Home shelf, 1 first; 0 for
|
|
// playlists the clients order themselves. Only genre mixes are ranked.
|
|
ShelfRank int32
|
|
TrackCount int32
|
|
DurationSec int32
|
|
CreatedAt pgtype.Timestamptz
|
|
UpdatedAt pgtype.Timestamptz
|
|
}
|
|
|
|
// PlaylistDetail extends PlaylistRow with the ordered track list.
|
|
// Returned by Get only; the List endpoint stays cheap and returns
|
|
// header-only PlaylistRows.
|
|
type PlaylistDetail struct {
|
|
PlaylistRow
|
|
Tracks []PlaylistTrack
|
|
}
|
|
|
|
// PlaylistTrack is one row of a playlist's ordered track list.
|
|
//
|
|
// Title / ArtistName / AlbumTitle / DurationSec are the snapshot the
|
|
// playlist row was created with — they remain authoritative even after
|
|
// the upstream tracks/albums/artists rows change or disappear.
|
|
//
|
|
// TrackID is nil when the upstream tracks row has been deleted from
|
|
// the library (ON DELETE SET NULL). AlbumID / ArtistID come from the
|
|
// LEFT JOIN through the live track and follow the same nil-on-removed
|
|
// semantics — once the track row is gone, neither the album nor the
|
|
// artist can be resolved either, so they collapse to nil together.
|
|
type PlaylistTrack struct {
|
|
Position int32
|
|
TrackID *pgtype.UUID
|
|
AlbumID *pgtype.UUID
|
|
ArtistID *pgtype.UUID
|
|
Title string
|
|
ArtistName string
|
|
AlbumTitle string
|
|
DurationSec int32
|
|
AddedAt pgtype.Timestamptz
|
|
// Unavailable reports that the track still exists in the library but
|
|
// its file is currently missing from disk (tracks.missing_since is
|
|
// set). The entry keeps its place in the playlist — the user
|
|
// put it there — but nothing should try to play it.
|
|
Unavailable bool
|
|
}
|
|
|
|
// Create makes a new playlist owned by userID.
|
|
func (s *Service) Create(ctx context.Context, userID pgtype.UUID, name, description string, isPublic bool) (*PlaylistRow, error) {
|
|
return s.CreateWithID(ctx, userID, pgtype.UUID{}, name, description, isPublic)
|
|
}
|
|
|
|
// CreateWithID makes a new playlist owned by userID under id, the id a
|
|
// client chose for it, or a new id when id is not valid. A client that
|
|
// made the list while offline sends the same id on every retry, so when
|
|
// userID already owns a list with that id, that list is returned
|
|
// unchanged. An id another user's list holds is ErrInvalidInput.
|
|
func (s *Service) CreateWithID(ctx context.Context, userID, id pgtype.UUID, name, description string, isPublic bool) (*PlaylistRow, error) {
|
|
if name == "" {
|
|
return nil, fmt.Errorf("%w: name required", ErrInvalidInput)
|
|
}
|
|
q := dbq.New(s.pool)
|
|
row, err := q.CreatePlaylist(ctx, dbq.CreatePlaylistParams{
|
|
ID: id,
|
|
UserID: userID,
|
|
Name: name,
|
|
Description: description,
|
|
IsPublic: isPublic,
|
|
})
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
existing, gerr := q.GetPlaylist(ctx, id)
|
|
if gerr != nil {
|
|
return nil, fmt.Errorf("get existing playlist: %w", gerr)
|
|
}
|
|
if !pgtypeUUIDEqual(existing.UserID, userID) || existing.Kind != "user" {
|
|
return nil, fmt.Errorf("%w: playlist id already in use", ErrInvalidInput)
|
|
}
|
|
return playlistFromGetRow(existing), nil
|
|
case err != nil:
|
|
return nil, fmt.Errorf("create playlist: %w", err)
|
|
}
|
|
s.publish("playlist.created", userID, row.ID)
|
|
// CreatePlaylist returns the playlist's own columns; the owner's
|
|
// username comes from GetPlaylist's join.
|
|
full, err := q.GetPlaylist(ctx, row.ID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get-after-create: %w", err)
|
|
}
|
|
return playlistFromGetRow(full), nil
|
|
}
|
|
|
|
// Get returns the playlist identified by playlistID along with its
|
|
// ordered track list. Visibility: owner can always see; non-owners
|
|
// only see public playlists. Returns ErrNotFound for missing rows
|
|
// and ErrForbidden when a non-owner asks for a private one.
|
|
func (s *Service) Get(ctx context.Context, callerID, playlistID pgtype.UUID) (*PlaylistDetail, error) {
|
|
q := dbq.New(s.pool)
|
|
row, err := q.GetPlaylist(ctx, playlistID)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, fmt.Errorf("get playlist: %w", err)
|
|
}
|
|
if !row.IsPublic && !pgtypeUUIDEqual(row.UserID, callerID) {
|
|
return nil, ErrForbidden
|
|
}
|
|
|
|
trackRows, err := q.ListPlaylistTracks(ctx, playlistID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list tracks: %w", err)
|
|
}
|
|
tracks := make([]PlaylistTrack, 0, len(trackRows))
|
|
for _, t := range trackRows {
|
|
pt := PlaylistTrack{
|
|
Position: t.Position,
|
|
Title: t.Title,
|
|
ArtistName: t.ArtistName,
|
|
AlbumTitle: t.AlbumTitle,
|
|
DurationSec: t.DurationSec,
|
|
AddedAt: t.AddedAt,
|
|
Unavailable: t.MissingSince.Valid,
|
|
}
|
|
// pt.track_id (snapshot FK, ON DELETE SET NULL) and the joined
|
|
// live_track_id should agree on validity in normal operation —
|
|
// prefer the snapshot's track_id because it survives even when
|
|
// the live row's other join columns happen to be NULL for
|
|
// unrelated reasons.
|
|
if t.TrackID.Valid {
|
|
id := t.TrackID
|
|
pt.TrackID = &id
|
|
}
|
|
if t.AlbumID.Valid {
|
|
id := t.AlbumID
|
|
pt.AlbumID = &id
|
|
}
|
|
if t.ArtistID.Valid {
|
|
id := t.ArtistID
|
|
pt.ArtistID = &id
|
|
}
|
|
tracks = append(tracks, pt)
|
|
}
|
|
|
|
detail := &PlaylistDetail{
|
|
PlaylistRow: *playlistFromGetRow(row),
|
|
Tracks: tracks,
|
|
}
|
|
covers, err := coverAlbums(ctx, q, []pgtype.UUID{playlistID})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
detail.CoverAlbumIDs = covers[playlistID]
|
|
return detail, nil
|
|
}
|
|
|
|
// List returns all playlists visible to callerID: every playlist owned
|
|
// by the caller (any visibility) plus every other user's public
|
|
// playlists, ordered newest-first by updated_at.
|
|
func (s *Service) List(ctx context.Context, callerID pgtype.UUID) ([]PlaylistRow, error) {
|
|
q := dbq.New(s.pool)
|
|
rows, err := q.ListPlaylistsForUser(ctx, callerID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list playlists: %w", err)
|
|
}
|
|
out := make([]PlaylistRow, 0, len(rows))
|
|
ids := make([]pgtype.UUID, 0, len(rows))
|
|
for _, r := range rows {
|
|
out = append(out, *playlistFromListRow(r))
|
|
ids = append(ids, r.ID)
|
|
}
|
|
covers, err := coverAlbums(ctx, q, ids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range out {
|
|
out[i].CoverAlbumIDs = covers[out[i].ID]
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// coverAlbums looks up the cover albums of several playlists in one query,
|
|
// keyed by playlist id. A playlist with no covered albums is absent.
|
|
func coverAlbums(ctx context.Context, q *dbq.Queries, ids []pgtype.UUID) (map[pgtype.UUID][]pgtype.UUID, error) {
|
|
out := make(map[pgtype.UUID][]pgtype.UUID, len(ids))
|
|
if len(ids) == 0 {
|
|
return out, nil
|
|
}
|
|
rows, err := q.ListPlaylistCoverAlbums(ctx, ids)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list cover albums: %w", err)
|
|
}
|
|
for _, r := range rows {
|
|
out[r.PlaylistID] = r.AlbumIds
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// UpdateInput captures optional fields. Each pointer being nil means
|
|
// "don't touch" — non-nil triggers a write of that column. The sqlc
|
|
// UpdatePlaylist query uses CASE-WHEN flags so we can keep PATCH
|
|
// semantics with one query rather than N variants.
|
|
type UpdateInput struct {
|
|
Name *string
|
|
Description *string
|
|
IsPublic *bool
|
|
}
|
|
|
|
// Update applies a partial update to playlistID. Only the owner may
|
|
// mutate — non-owners (including admins, currently) get ErrForbidden.
|
|
// Empty Name (when explicitly set) is rejected with ErrInvalidInput
|
|
// rather than silently no-op'd, since the user clearly intended to
|
|
// change something.
|
|
func (s *Service) Update(ctx context.Context, callerID, playlistID pgtype.UUID, in UpdateInput) (*PlaylistRow, error) {
|
|
q := dbq.New(s.pool)
|
|
if _, err := editable(ctx, q, callerID, playlistID); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
params := dbq.UpdatePlaylistParams{
|
|
ID: playlistID,
|
|
UpdateName: in.Name != nil,
|
|
UpdateDescription: in.Description != nil,
|
|
UpdateIsPublic: in.IsPublic != nil,
|
|
}
|
|
if in.Name != nil {
|
|
if *in.Name == "" {
|
|
return nil, fmt.Errorf("%w: name cannot be empty", ErrInvalidInput)
|
|
}
|
|
params.Name = *in.Name
|
|
}
|
|
if in.Description != nil {
|
|
params.Description = *in.Description
|
|
}
|
|
if in.IsPublic != nil {
|
|
params.IsPublic = *in.IsPublic
|
|
}
|
|
|
|
updated, err := q.UpdatePlaylist(ctx, params)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("update playlist: %w", err)
|
|
}
|
|
s.publish("playlist.updated", callerID, playlistID)
|
|
full, err := q.GetPlaylist(ctx, updated.ID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get-after-update: %w", err)
|
|
}
|
|
return playlistFromGetRow(full), nil
|
|
}
|
|
|
|
// Delete removes playlistID. Owner-only, like Update. After the row is
|
|
// gone, a best-effort attempt is made to remove the cached cover-art
|
|
// collage from disk; failures other than ENOENT are logged but do not
|
|
// fail the call (the row is already gone, returning an error would
|
|
// confuse callers about whether the delete took effect).
|
|
func (s *Service) Delete(ctx context.Context, callerID, playlistID pgtype.UUID) error {
|
|
q := dbq.New(s.pool)
|
|
if _, err := editable(ctx, q, callerID, playlistID); err != nil {
|
|
return err
|
|
}
|
|
|
|
deleted, err := q.DeletePlaylist(ctx, playlistID)
|
|
if err != nil {
|
|
return fmt.Errorf("delete playlist: %w", err)
|
|
}
|
|
s.publish("playlist.deleted", callerID, playlistID)
|
|
if deleted.CoverPath != nil && *deleted.CoverPath != "" {
|
|
full := filepath.Join(s.dataDir, *deleted.CoverPath)
|
|
if rerr := os.Remove(full); rerr != nil && !errors.Is(rerr, os.ErrNotExist) {
|
|
s.logger.Warn("playlist delete: cover file remove failed",
|
|
"path", full, "playlist_id", playlistID, "err", rerr)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// editable loads playlistID for a change by callerID. It answers
|
|
// ErrNotFound when the playlist doesn't exist, ErrForbidden when the caller
|
|
// doesn't own it, and ErrSystemPlaylistReadonly for a system mix, which only
|
|
// Minstrel rebuilds.
|
|
func editable(ctx context.Context, q *dbq.Queries, callerID, playlistID pgtype.UUID) (dbq.GetPlaylistRow, error) {
|
|
p, err := q.GetPlaylist(ctx, playlistID)
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return p, ErrNotFound
|
|
}
|
|
return p, fmt.Errorf("get playlist: %w", err)
|
|
}
|
|
if !pgtypeUUIDEqual(p.UserID, callerID) {
|
|
return p, ErrForbidden
|
|
}
|
|
if p.Kind == "system" {
|
|
return p, ErrSystemPlaylistReadonly
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
// AppendTracks adds the given track ids at the end of the playlist,
|
|
// preserving order. Snapshot fields (title, artist, album, duration_sec)
|
|
// are populated from the tracks/albums/artists join at insert time.
|
|
// Triggers cover regeneration after.
|
|
func (s *Service) AppendTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
|
|
if len(trackIDs) == 0 {
|
|
return fmt.Errorf("%w: at least one track id required", ErrInvalidInput)
|
|
}
|
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
|
return appendTracks(ctx, tx, playlistID, trackIDs)
|
|
})
|
|
}
|
|
|
|
// ReplaceTracks makes trackIDs the playlist's whole track list, in order;
|
|
// an empty list empties it. The old list goes only if every new track
|
|
// exists.
|
|
func (s *Service) ReplaceTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
|
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
|
if _, err := tx.Exec(ctx, `DELETE FROM playlist_tracks WHERE playlist_id = $1`, playlistID); err != nil {
|
|
return fmt.Errorf("clear tracks: %w", err)
|
|
}
|
|
return appendTracks(ctx, tx, playlistID, trackIDs)
|
|
})
|
|
}
|
|
|
|
// RemoveTrack deletes the row at `position` and renumbers subsequent
|
|
// rows to close the gap. With a valid expect, the row must hold that
|
|
// track, or nothing is removed and the answer is ErrListChanged: a client
|
|
// replaying a removal it made offline must not take out whichever song has
|
|
// since moved into that place.
|
|
func (s *Service) RemoveTrack(ctx context.Context, callerID, playlistID pgtype.UUID, position int32, expect pgtype.UUID) error {
|
|
return s.removePositions(ctx, callerID, playlistID, []int32{position}, expect)
|
|
}
|
|
|
|
// RemovePositions deletes the rows at the given positions, all counted
|
|
// in the list as it stands before the call, and closes the gaps. A
|
|
// position repeated is removed once; one with no row is ErrNotFound and
|
|
// removes nothing.
|
|
func (s *Service) RemovePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32) error {
|
|
return s.removePositions(ctx, callerID, playlistID, positions, pgtype.UUID{})
|
|
}
|
|
|
|
// removePositions removes the rows at positions; a valid expect is the
|
|
// track the single row must hold (see RemoveTrack).
|
|
func (s *Service) removePositions(ctx context.Context, callerID, playlistID pgtype.UUID, positions []int32, expect pgtype.UUID) error {
|
|
if len(positions) == 0 {
|
|
return fmt.Errorf("%w: at least one position required", ErrInvalidInput)
|
|
}
|
|
// Highest first, so closing one gap never moves a row still to go.
|
|
order := slices.Clone(positions)
|
|
slices.Sort(order)
|
|
order = slices.Compact(order)
|
|
slices.Reverse(order)
|
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
|
tq := dbq.New(tx)
|
|
for _, position := range order {
|
|
// Read first: a missing position is ErrNotFound, and expect
|
|
// is checked against the row's track.
|
|
var deletedTrackID pgtype.UUID
|
|
if err := tx.QueryRow(ctx,
|
|
`SELECT track_id FROM playlist_tracks WHERE playlist_id = $1 AND position = $2`,
|
|
playlistID, position,
|
|
).Scan(&deletedTrackID); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrNotFound
|
|
}
|
|
return fmt.Errorf("lookup track at position: %w", err)
|
|
}
|
|
if expect.Valid && deletedTrackID != expect {
|
|
return ErrListChanged
|
|
}
|
|
if err := tq.DeletePlaylistTrack(ctx, dbq.DeletePlaylistTrackParams{
|
|
PlaylistID: playlistID,
|
|
Position: position,
|
|
}); err != nil {
|
|
return fmt.Errorf("delete track row: %w", err)
|
|
}
|
|
if err := tq.RenumberPlaylistTracksAfter(ctx, dbq.RenumberPlaylistTracksAfterParams{
|
|
PlaylistID: playlistID,
|
|
Position: position,
|
|
}); err != nil {
|
|
return fmt.Errorf("renumber: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// changeTracks runs change in one transaction on a playlist callerID may
|
|
// edit, then updates the playlist's song count and length and redraws its
|
|
// cover. A cover that fails to draw is logged, not returned: the change
|
|
// has already committed.
|
|
func (s *Service) changeTracks(ctx context.Context, callerID, playlistID pgtype.UUID, change func(pgx.Tx) error) error {
|
|
if _, err := editable(ctx, dbq.New(s.pool), callerID, playlistID); err != nil {
|
|
return err
|
|
}
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("begin tx: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
if err := change(tx); err != nil {
|
|
return err
|
|
}
|
|
if err := dbq.New(tx).UpdatePlaylistRollups(ctx, playlistID); err != nil {
|
|
return fmt.Errorf("update rollups: %w", err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("commit: %w", err)
|
|
}
|
|
s.publish("playlist.tracks_changed", callerID, playlistID)
|
|
if _, cerr := GenerateCollage(ctx, s.pool, playlistID, s.dataDir); cerr != nil {
|
|
s.logger.Warn("collage regeneration failed", "playlist_id", playlistID, "err", cerr)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// appendTracks adds trackIDs at the end of the playlist inside tx. A track
|
|
// id that matches no track is ErrTrackNotFound.
|
|
func appendTracks(ctx context.Context, tx pgx.Tx, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
|
|
tq := dbq.New(tx)
|
|
for _, tid := range trackIDs {
|
|
// The insert selects from tracks, so a missing track inserts
|
|
// nothing and the :one query answers pgx.ErrNoRows.
|
|
if _, err := tq.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
|
|
PlaylistID: playlistID,
|
|
TrackID: tid,
|
|
}); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrTrackNotFound
|
|
}
|
|
return fmt.Errorf("append track: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Reorder atomically rewrites all positions to the supplied permutation.
|
|
// orderedPositions is the new positional order: if the playlist has 4
|
|
// tracks at positions [0, 1, 2, 3] and the caller wants the order
|
|
// (old[3], old[0], old[1], old[2]), they send [3, 0, 1, 2].
|
|
func (s *Service) Reorder(ctx context.Context, callerID, playlistID pgtype.UUID, orderedPositions []int32) error {
|
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
|
entries, err := dbq.New(tx).ListPlaylistEntriesForUpdate(ctx, playlistID)
|
|
if err != nil {
|
|
return fmt.Errorf("list entries: %w", err)
|
|
}
|
|
n := int32(len(entries))
|
|
if int32(len(orderedPositions)) != n {
|
|
return fmt.Errorf("%w: expected %d positions, got %d", ErrInvalidInput, n, len(orderedPositions))
|
|
}
|
|
seen := make(map[int32]struct{}, n)
|
|
for _, p := range orderedPositions {
|
|
if p < 0 || p >= n {
|
|
return fmt.Errorf("%w: position %d out of range", ErrInvalidInput, p)
|
|
}
|
|
if _, dup := seen[p]; dup {
|
|
return fmt.Errorf("%w: position %d duplicated", ErrInvalidInput, p)
|
|
}
|
|
seen[p] = struct{}{}
|
|
}
|
|
return writeOrder(ctx, tx, playlistID, orderedPositions)
|
|
})
|
|
}
|
|
|
|
// ReorderTracks puts the playlist's songs in the order trackIDs gives.
|
|
// Entries it doesn't name (a song that has left the library, or one added
|
|
// since the caller last looked) keep their places, and the named ones are
|
|
// arranged among the places left; a track id the playlist doesn't hold is
|
|
// skipped. Sending the same order twice changes nothing the second time,
|
|
// which is what lets a client replay a reorder it made offline.
|
|
func (s *Service) ReorderTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error {
|
|
return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error {
|
|
entries, err := dbq.New(tx).ListPlaylistEntriesForUpdate(ctx, playlistID)
|
|
if err != nil {
|
|
return fmt.Errorf("list entries: %w", err)
|
|
}
|
|
current := make([]pgtype.UUID, len(entries))
|
|
for i, e := range entries {
|
|
current[i] = e.TrackID
|
|
}
|
|
return writeOrder(ctx, tx, playlistID, orderByTracks(current, trackIDs))
|
|
})
|
|
}
|
|
|
|
// orderByTracks returns the permutation Reorder takes (new position i
|
|
// holds old position perm[i]) that puts the entries holding want's tracks
|
|
// in want's order, within the positions those entries hold now. A track
|
|
// listed twice matches its entries in turn.
|
|
func orderByTracks(current, want []pgtype.UUID) []int32 {
|
|
at := make(map[[16]byte][]int32, len(current))
|
|
for i, id := range current {
|
|
if id.Valid {
|
|
at[id.Bytes] = append(at[id.Bytes], int32(i))
|
|
}
|
|
}
|
|
picked := make([]int32, 0, len(want))
|
|
for _, id := range want {
|
|
if q := at[id.Bytes]; id.Valid && len(q) > 0 {
|
|
picked = append(picked, q[0])
|
|
at[id.Bytes] = q[1:]
|
|
}
|
|
}
|
|
slots := slices.Clone(picked)
|
|
slices.Sort(slots)
|
|
perm := make([]int32, len(current))
|
|
for i := range perm {
|
|
perm[i] = int32(i)
|
|
}
|
|
for k, slot := range slots {
|
|
perm[slot] = picked[k]
|
|
}
|
|
return perm
|
|
}
|
|
|
|
// writeOrder moves the row at position perm[i] to position i. Every row
|
|
// first moves out of the range of valid positions, so no two rows ever
|
|
// hold one position mid-rewrite.
|
|
func writeOrder(ctx context.Context, tx pgx.Tx, playlistID pgtype.UUID, perm []int32) error {
|
|
if _, err := tx.Exec(ctx,
|
|
`UPDATE playlist_tracks SET position = position + 10000 WHERE playlist_id = $1`,
|
|
playlistID); err != nil {
|
|
return fmt.Errorf("offset positions: %w", err)
|
|
}
|
|
for newPos, oldPos := range perm {
|
|
if _, err := tx.Exec(ctx,
|
|
`UPDATE playlist_tracks SET position = $1 WHERE playlist_id = $2 AND position = $3`,
|
|
int32(newPos), playlistID, oldPos+10000); err != nil {
|
|
return fmt.Errorf("write new position: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// publish tells the owner's signed-in clients that a playlist changed.
|
|
func (s *Service) publish(kind string, ownerID, playlistID pgtype.UUID) {
|
|
if s.bus == nil {
|
|
return
|
|
}
|
|
s.bus.Publish(eventbus.Event{
|
|
Kind: kind,
|
|
UserID: syncpkg.FormatUUID(ownerID),
|
|
Data: map[string]any{"playlist_id": syncpkg.FormatUUID(playlistID)},
|
|
})
|
|
}
|
|
|
|
func playlistFromGetRow(r dbq.GetPlaylistRow) *PlaylistRow {
|
|
return &PlaylistRow{
|
|
ID: r.ID,
|
|
UserID: r.UserID,
|
|
OwnerUsername: r.OwnerUsername,
|
|
Name: r.Name,
|
|
Description: r.Description,
|
|
IsPublic: r.IsPublic,
|
|
Kind: r.Kind,
|
|
SystemVariant: r.SystemVariant,
|
|
SeedArtistID: r.SeedArtistID,
|
|
CoverPath: r.CoverPath,
|
|
ShelfRank: r.ShelfRank,
|
|
TrackCount: r.TrackCount,
|
|
DurationSec: r.DurationSec,
|
|
CreatedAt: r.CreatedAt,
|
|
UpdatedAt: r.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
func playlistFromListRow(r dbq.ListPlaylistsForUserRow) *PlaylistRow {
|
|
return &PlaylistRow{
|
|
ID: r.ID,
|
|
UserID: r.UserID,
|
|
OwnerUsername: r.OwnerUsername,
|
|
Name: r.Name,
|
|
Description: r.Description,
|
|
IsPublic: r.IsPublic,
|
|
Kind: r.Kind,
|
|
SystemVariant: r.SystemVariant,
|
|
SeedArtistID: r.SeedArtistID,
|
|
CoverPath: r.CoverPath,
|
|
ShelfRank: r.ShelfRank,
|
|
TrackCount: r.TrackCount,
|
|
DurationSec: r.DurationSec,
|
|
CreatedAt: r.CreatedAt,
|
|
UpdatedAt: r.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
// pgtypeUUIDEqual treats two zero/invalid UUIDs as not-equal. The
|
|
// service uses this for owner-vs-caller checks where an invalid UUID
|
|
// can never legitimately match anything.
|
|
func pgtypeUUIDEqual(a, b pgtype.UUID) bool {
|
|
if !a.Valid || !b.Valid {
|
|
return false
|
|
}
|
|
return a.Bytes == b.Bytes
|
|
}
|