package playlists_test import ( "context" "errors" "os" "path/filepath" "testing" "github.com/jackc/pgx/v5/pgtype" "github.com/Fabled-Sword/minstrel/internal/dbtest" "github.com/Fabled-Sword/minstrel/internal/playlists" ) // A playlist is its owner's to change. Anyone may see a public one, only the // owner a private one, and an unknown id is not found rather than forbidden. // The REST API and the Subsonic endpoints both rely on these answers. func TestService_WhoMaySeeAndChangeAPlaylist(t *testing.T) { ctx := context.Background() pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") bob := seedUser(t, pool, "bob") track := seedTrack(t, pool, "T", "A") svc := playlists.NewService(pool, nil, t.TempDir()) create := func(owner pgtype.UUID, name string, public bool) *playlists.PlaylistRow { t.Helper() row, err := svc.Create(ctx, owner, name, "", public) if err != nil { t.Fatalf("Create %q: %v", name, err) } return row } private := create(alice.ID, "Alice private", false) public := create(alice.ID, "Alice public", true) create(bob.ID, "Bob private", false) create(bob.ID, "Bob public", true) if private.OwnerUsername != "test-alice" || private.TrackCount != 0 || private.DurationSec != 0 { t.Errorf("created row = %+v, want owner test-alice and empty rollups", private) } rename := "Renamed" for _, tc := range []struct { name string do func() error want error }{ {"the owner sees her private playlist", func() error { _, err := svc.Get(ctx, alice.ID, private.ID); return err }, nil}, {"another user can't see it", func() error { _, err := svc.Get(ctx, bob.ID, private.ID); return err }, playlists.ErrForbidden}, {"another user sees a public one", func() error { _, err := svc.Get(ctx, bob.ID, public.ID); return err }, nil}, {"an unknown id is not found", func() error { _, err := svc.Get(ctx, alice.ID, randomUUID()); return err }, playlists.ErrNotFound}, {"another user can't rename it", func() error { _, err := svc.Update(ctx, bob.ID, public.ID, playlists.UpdateInput{Name: &rename}) return err }, playlists.ErrForbidden}, {"renaming an unknown id", func() error { _, err := svc.Update(ctx, alice.ID, randomUUID(), playlists.UpdateInput{Name: &rename}) return err }, playlists.ErrNotFound}, {"another user can't add to a public one", func() error { return svc.AppendTracks(ctx, bob.ID, public.ID, []pgtype.UUID{track.ID}) }, playlists.ErrForbidden}, {"another user can't delete it", func() error { return svc.Delete(ctx, bob.ID, public.ID) }, playlists.ErrForbidden}, {"deleting an unknown id", func() error { return svc.Delete(ctx, alice.ID, randomUUID()) }, playlists.ErrNotFound}, } { if err := tc.do(); !errors.Is(err, tc.want) { t.Errorf("%s: err = %v, want %v", tc.name, err, tc.want) } } rows, err := svc.List(ctx, alice.ID) if err != nil { t.Fatalf("List: %v", err) } names := map[string]bool{} for _, r := range rows { names[r.Name] = true } if len(rows) != 3 || !names["Alice private"] || !names["Alice public"] || !names["Bob public"] { t.Errorf("alice's list = %v, want her two and bob's public one", names) } if updated, err := svc.Update(ctx, alice.ID, private.ID, playlists.UpdateInput{Name: &rename}); err != nil || updated.Name != "Renamed" { t.Errorf("owner rename = %+v, %v; want Renamed", updated, err) } if err := svc.Delete(ctx, alice.ID, private.ID); err != nil { t.Fatalf("owner Delete: %v", err) } // A second delete reports NotFound rather than silently succeeding. if err := svc.Delete(ctx, alice.ID, private.ID); !errors.Is(err, playlists.ErrNotFound) { t.Errorf("repeat Delete err = %v, want ErrNotFound", err) } } // Bad input is refused as ErrInvalidInput, which the API answers with 400: // an empty name on create or rename, and a reorder that isn't a permutation // of the playlist's positions. A track that doesn't exist is its own error. func TestService_RefusesBadInput(t *testing.T) { ctx := context.Background() pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") t1 := seedTrack(t, pool, "T1", "A") t2 := seedTrack(t, pool, "T2", "A") svc := playlists.NewService(pool, nil, t.TempDir()) if _, err := svc.Create(ctx, alice.ID, "", "", false); !errors.Is(err, playlists.ErrInvalidInput) { t.Errorf("Create with no name: err = %v, want ErrInvalidInput", err) } pl, err := svc.Create(ctx, alice.ID, "Two", "", false) if err != nil { t.Fatal(err) } empty := "" if _, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{Name: &empty}); !errors.Is(err, playlists.ErrInvalidInput) { t.Errorf("rename to nothing: err = %v, want ErrInvalidInput", err) } if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{randomUUID()}); !errors.Is(err, playlists.ErrTrackNotFound) { t.Errorf("append an unknown track: err = %v, want ErrTrackNotFound", err) } if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID}); err != nil { t.Fatal(err) } for _, order := range [][]int32{{0, 1, 2}, {0, 0}, {1}} { if err := svc.Reorder(ctx, alice.ID, pl.ID, order); !errors.Is(err, playlists.ErrInvalidInput) { t.Errorf("Reorder %v of two tracks: err = %v, want ErrInvalidInput", order, err) } } } // An update changes only the fields it carries. func TestService_UpdateLeavesFieldsItDoesNotCarry(t *testing.T) { ctx := context.Background() pool := dbtest.Pool(t) alice := seedUser(t, pool, "alice") svc := playlists.NewService(pool, nil, t.TempDir()) pl, err := svc.Create(ctx, alice.ID, "Original", "Long description", false) if err != nil { t.Fatalf("seed Create: %v", err) } pub := true updated, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{IsPublic: &pub}) if err != nil { t.Fatalf("Update: %v", err) } if updated.Name != "Original" || updated.Description != "Long description" || !updated.IsPublic { t.Errorf("after toggling public: %+v; want name and description unchanged", updated) } } // A playlist's entries keep a snapshot of each track's title and artist, so an // entry survives its track being deleted, shown by name with no track id. // Removing an entry renumbers the rest, and a reorder applies a permutation. func TestService_TrackListEdits(t *testing.T) { ctx := context.Background() pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") a := seedTrack(t, pool, "Prismatic", "Fields of Ontario") b := seedTrack(t, pool, "B", "Artist") c := seedTrack(t, pool, "C", "Artist") d := seedTrack(t, pool, "D", "Artist") svc := playlists.NewService(pool, nil, t.TempDir()) pl, err := svc.Create(ctx, user.ID, "Test", "", false) if err != nil { t.Fatal(err) } titles := func() []string { t.Helper() got, err := svc.Get(ctx, user.ID, pl.ID) if err != nil { t.Fatal(err) } out := make([]string, len(got.Tracks)) for i, pt := range got.Tracks { if int(pt.Position) != i { t.Errorf("entry %d has position %d", i, pt.Position) } out[i] = pt.Title } return out } expect := func(step string, want ...string) { t.Helper() if got := titles(); !equal(got, want) { t.Errorf("after %s: %q, want %q", step, got, want) } } if err := svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID, c.ID, d.ID}); err != nil { t.Fatalf("AppendTracks: %v", err) } got, _ := svc.Get(ctx, user.ID, pl.ID) if got.TrackCount != 4 || got.Tracks[0].ArtistName != "Fields of Ontario" { t.Errorf("after append: count %d, first artist %q; want 4 and the snapshot artist", got.TrackCount, got.Tracks[0].ArtistName) } if err := svc.RemoveTrack(ctx, user.ID, pl.ID, 1, pgtype.UUID{}); err != nil { t.Fatalf("RemoveTrack: %v", err) } expect("removing position 1", "Prismatic", "C", "D") if err := svc.Reorder(ctx, user.ID, pl.ID, []int32{2, 1, 0}); err != nil { t.Fatalf("Reorder: %v", err) } expect("reversing", "D", "C", "Prismatic") if _, err := pool.Exec(ctx, `DELETE FROM tracks WHERE id = $1`, a.ID); err != nil { t.Fatalf("delete track: %v", err) } got, _ = svc.Get(ctx, user.ID, pl.ID) if len(got.Tracks) != 3 || got.Tracks[2].Title != "Prismatic" || got.Tracks[2].TrackID != nil { t.Errorf("after the track's deletion: %+v; want the entry kept by name, with no track id", got.Tracks) } } // Deleting a playlist removes its cached cover from disk, and a cover file // already gone is no obstacle. func TestService_DeleteRemovesTheCoverFile(t *testing.T) { ctx := context.Background() pool := dbtest.Pool(t) user := seedUser(t, pool, "alice") dir := t.TempDir() svc := playlists.NewService(pool, nil, dir) if err := os.MkdirAll(filepath.Join(dir, "playlist_covers"), 0o755); err != nil { t.Fatal(err) } withCover := func(name string, onDisk bool) (*playlists.PlaylistRow, string) { t.Helper() pl, err := svc.Create(ctx, user.ID, name, "", false) if err != nil { t.Fatal(err) } rel := filepath.Join("playlist_covers", uuidString(pl.ID)+".jpg") if onDisk { if err := os.WriteFile(filepath.Join(dir, rel), []byte("jpeg-bytes"), 0o644); err != nil { t.Fatal(err) } } if _, err := pool.Exec(ctx, `UPDATE playlists SET cover_path = $1 WHERE id = $2`, rel, pl.ID); err != nil { t.Fatal(err) } return pl, filepath.Join(dir, rel) } pl, full := withCover("With a cover", true) if err := svc.Delete(ctx, user.ID, pl.ID); err != nil { t.Fatalf("Delete: %v", err) } if _, err := os.Stat(full); !errors.Is(err, os.ErrNotExist) { t.Errorf("cover file still on disk after delete: %v", err) } gone, _ := withCover("Cover already gone", false) if err := svc.Delete(ctx, user.ID, gone.ID); err != nil { t.Errorf("Delete with its cover file already gone: %v", err) } } func equal(a, b []string) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true }