package httpapi import ( "context" "fmt" "net/http" "net/url" "slices" "strings" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/library" "git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/storage" ) // mixAPI is a server with 40 rock songs by 8 artists and 36 hard rock songs by 6, and a user. type mixAPI struct { h http.Handler db *bun.DB alice string } func newMixAPI(t *testing.T) *mixAPI { return newMixAPIWith(t, func(*Deps, *bun.DB) {}) } // newMixAPIWith is newMixAPI with a change to the services before the server is made. func newMixAPIWith(t *testing.T, mutate func(*Deps, *bun.DB)) *mixAPI { t.Helper() h, db := newTestEnvDB(t, mutate) alice := registerAndLogin(t, h) ctx := context.Background() lib := storage.NewLibraryRepo(db) l, err := lib.CreateLibrary(ctx, "m", "/lib/m") if err != nil { t.Fatal(err) } add := func(prefix string, n, artists int, genres ...string) { for i := 0; i < n; i++ { artist := fmt.Sprintf("%s artist %d", prefix, i%artists) title := fmt.Sprintf("%s song %d", prefix, i) f := library.ParsedFile{ FileInfo: library.FileInfo{RelPath: prefix + "/" + title + ".flac", Size: 100, MTimeUnix: 1}, Metadata: library.Metadata{ Tags: library.Tags{Title: title, Album: prefix + " album", AlbumArtist: artist, Artists: []string{artist}, TrackNo: i + 1, DiscNo: 1, Genres: genres}, Properties: library.Properties{Format: "flac", DurationMs: 60000, SampleRate: 44100}, }, } if _, err := lib.SaveFile(ctx, l.ID, f, 0); err != nil { t.Fatal(err) } } } add("rock", 40, 8, "rock") add("hard", 36, 6, "hard rock") return &mixAPI{h: h, db: db, alice: alice} } func (m *mixAPI) get(t *testing.T, id, query string) resp { t.Helper() return do(t, m.h, "GET", "/api/v1/mixes/"+url.PathEscape(id)+query, m.alice, nil) } func trackIDs(t *testing.T, r resp) []float64 { t.Helper() var out []float64 for _, x := range r.Body["tracks"].([]any) { out = append(out, x.(map[string]any)["id"].(float64)) } return out } func TestMixRoutesNeedASignedInUser(t *testing.T) { m := newMixAPI(t) for _, rt := range []struct{ method, path string }{ {"GET", "/api/v1/mixes"}, {"GET", "/api/v1/mixes/genre:rock"}, {"POST", "/api/v1/mixes/genre:rock/playlist"}, } { if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized { t.Errorf("%s %s without a token: %d", rt.method, rt.path, r.Code) } } } func TestTheListOfMixesHasTheGenresOfTheLibrary(t *testing.T) { m := newMixAPI(t) r := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil) if r.Code != http.StatusOK { t.Fatalf("list: %d %v", r.Code, r.Body) } byID := map[string]map[string]any{} for _, x := range r.Body["items"].([]any) { mix := x.(map[string]any) byID[mix["id"].(string)] = mix } rock := byID["genre:rock"] if rock == nil || rock["kind"] != "genre" || rock["title"] != "Rock Mix" || rock["genre"] != "rock" || len(rock["artists"].([]any)) != 3 { t.Fatalf("rock = %v in %v", rock, byID) } if byID["genre:hard rock"] == nil { t.Errorf("hard rock is missing: %v", byID) } unheard := byID["unheard"] if unheard == nil || unheard["kind"] != "unheard" || unheard["genre"] != nil { t.Errorf("unheard = %v", unheard) } if byID["favourites"] != nil || byID["rediscover"] != nil { t.Errorf("mixes that need history are there with none: %v", byID) } } func TestAMixHasItsSongsAndStaysTheSameUntilAnotherVariantIsAsked(t *testing.T) { m := newMixAPI(t) r := m.get(t, "genre:rock", "") if r.Code != http.StatusOK || r.Body["id"] != "genre:rock" || r.Body["variant"] != float64(0) || r.Body["title"] != "Rock Mix" { t.Fatalf("mix: %d %v", r.Code, r.Body) } first := r.Body["tracks"].([]any)[0].(map[string]any) if first["title"] == nil || first["album"] == nil || len(first["artists"].([]any)) != 1 { t.Errorf("a song of the mix = %v", first) } ids := trackIDs(t, r) if len(ids) != 40 { t.Fatalf("%d songs, want the 40 there are (fewer than 50)", len(ids)) } if again := trackIDs(t, m.get(t, "genre:rock", "")); !slices.Equal(ids, again) { t.Error("the same mix twice is not the same") } v1 := m.get(t, "genre:rock", "?variant=1") if v1.Body["variant"] != float64(1) || slices.Equal(ids, trackIDs(t, v1)) { t.Errorf("variant 1 = %v", v1.Body["variant"]) } // Spaces in the id come percent-encoded. if r := m.get(t, "genre:hard rock", ""); r.Code != http.StatusOK || len(trackIDs(t, r)) != 36 { t.Errorf("hard rock: %d", r.Code) } } func TestSongsSkippedLatelyAreLeftOutOfAMix(t *testing.T) { m := newMixAPI(t) var ids []int64 rows, err := m.db.Query("SELECT id FROM tracks WHERE title LIKE 'rock song%' ORDER BY id LIMIT 10") if err != nil { t.Fatal(err) } for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { t.Fatal(err) } ids = append(ids, id) } rows.Close() var userID int64 if err := m.db.QueryRow("SELECT id FROM users").Scan(&userID); err != nil { t.Fatal(err) } rec := listening.NewService(storage.NewListeningRepo(m.db), 20*time.Second) record := func(id int64, typ listening.EventType, played int64, key string) { t.Helper() if _, err := rec.Record(context.Background(), listening.Event{UserID: userID, TrackID: id, Type: typ, DurationPlayedMs: played, OccurredAt: time.Now().Add(-time.Hour), IdempotencyKey: key}); err != nil { t.Fatal(err) } } for i, id := range ids { record(id, listening.Skip, 3000, fmt.Sprintf("skip%d", i)) } // The artists also have songs they listened to to the end, so none of them is an avoided artist: // what is left out is the skipped songs and nothing else. for a := 0; a < 8; a++ { for _, n := range []int{16, 24, 32} { var id int64 if err := m.db.QueryRow("SELECT id FROM tracks WHERE title = ?", fmt.Sprintf("rock song %d", a+n)).Scan(&id); err != nil { t.Fatal(err) } record(id, listening.Complete, 59000, fmt.Sprintf("done%d-%d", a, n)) } } got := trackIDs(t, m.get(t, "genre:rock", "")) if len(got) != 30 { t.Fatalf("%d songs, want 30: ten were skipped", len(got)) } for _, id := range got { if slices.Contains(ids, int64(id)) { t.Fatalf("song %v was skipped an hour ago", id) } } } func TestAnUnknownMixOrABadVariantIsRefused(t *testing.T) { m := newMixAPI(t) for _, id := range []string{"nope", "genre:polka", "genre:other", "favourites", "rediscover"} { if r := m.get(t, id, ""); r.Code != http.StatusNotFound || errCode(r) != "mix_not_found" { t.Errorf("%s: %d %v, want 404 mix_not_found", id, r.Code, r.Body) } } for _, q := range []string{"?variant=abc", "?variant=-1", "?variant=99999999999"} { if r := m.get(t, "genre:rock", q); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("%s: %d %v, want 400 invalid_input", q, r.Code, r.Body) } } } func TestAMixIsSavedAsAPlaylistWithTheSongsThatWereShown(t *testing.T) { m := newMixAPI(t) shown := trackIDs(t, m.get(t, "genre:rock", "?variant=2")) r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"variant": 2}) if r.Code != http.StatusCreated || r.Body["name"] != "Rock Mix" || r.Body["track_count"] != float64(len(shown)) { t.Fatalf("save: %d %v", r.Code, r.Body) } pl := int64(r.Body["id"].(float64)) items := do(t, m.h, "GET", "/api/v1/playlists/"+id(pl)+"/tracks?limit=200", m.alice, nil) var got []float64 for _, it := range items.Body["items"].([]any) { got = append(got, it.(map[string]any)["track"].(map[string]any)["id"].(float64)) } if !slices.Equal(got, shown) { t.Errorf("the playlist has %v, the mix showed %v", got, shown) } named := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"name": " For the car "}) if named.Code != http.StatusCreated || named.Body["name"] != "For the car" { t.Errorf("named: %d %v", named.Code, named.Body) } if r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"name": strings.Repeat("a", 201)}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("a name that is too long: %d %v", r.Code, r.Body) } if r := do(t, m.h, "POST", "/api/v1/mixes/nope/playlist", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "mix_not_found" { t.Errorf("unknown mix: %d %v", r.Code, r.Body) } if r := do(t, m.h, "POST", "/api/v1/mixes/genre:rock/playlist", m.alice, map[string]any{"variant": -3}); r.Code != http.StatusBadRequest { t.Errorf("a negative variant: %d", r.Code) } // A refused save leaves no playlist behind: the two that worked are all there is. list := do(t, m.h, "GET", "/api/v1/playlists", m.alice, nil) if list.Body["total"] != float64(2) { t.Errorf("playlists = %v, want 2", list.Body["total"]) } } func TestMixesSayWhichAlbumsStandForThem(t *testing.T) { m := newMixAPI(t) r := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil) for _, x := range r.Body["items"].([]any) { if ids, ok := x.(map[string]any)["album_ids"].([]any); !ok || len(ids) != 0 { t.Fatalf("with no cover a mix has an empty list: %v", x) } } // Five of the eight rock albums (one for each artist) get a cover; a mix shows four. rows, err := m.db.Query("SELECT DISTINCT t.album_id FROM tracks t WHERE t.title LIKE 'rock song%' ORDER BY t.album_id") if err != nil { t.Fatal(err) } var albums []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { t.Fatal(err) } albums = append(albums, id) } rows.Close() if len(albums) != 8 { t.Fatalf("albums = %v", albums) } for _, id := range albums[:5] { if _, err := m.db.Exec("DELETE FROM images WHERE kind = 'album' AND owner_id = ?", id); err != nil { t.Fatal(err) } if _, err := m.db.Exec("INSERT INTO images (kind, owner_id, status, checked_at) VALUES ('album', ?, 'ok', 1)", id); err != nil { t.Fatal(err) } } want := []any{float64(albums[0]), float64(albums[1]), float64(albums[2]), float64(albums[3])} list := do(t, m.h, "GET", "/api/v1/mixes", m.alice, nil) var got []any for _, x := range list.Body["items"].([]any) { if x.(map[string]any)["id"] == "genre:rock" { got = x.(map[string]any)["album_ids"].([]any) } } if !slices.Equal(got, want) { t.Errorf("rock albums = %v, want %v", got, want) } one := m.get(t, "genre:rock", "") if ids := one.Body["album_ids"].([]any); !slices.Equal(ids, want) { t.Errorf("album_ids of the mix = %v", one.Body["album_ids"]) } }