package httpapi import ( "fmt" "net/http" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/storage" ) const suggestionsPath = "/api/v1/me/suggestions" // listeningHistory plays this out for the only user: three old sittings of Radiohead, Pixies and (outside the library) // Giorgio Canali, and two recent ones of Radiohead and Placebo. Pixies and Placebo have a song in the library. func listeningHistory(t *testing.T, db *bun.DB) { t.Helper() seedSong(t, db, "a.flac", "Airbag", "OK Computer", "Radiohead") seedSong(t, db, "b.flac", "Debaser", "Doolittle", "Pixies") seedSong(t, db, "c.flac", "Nancy Boy", "Placebo", "Placebo") var user int64 if err := db.QueryRow("SELECT id FROM users LIMIT 1").Scan(&user); err != nil { t.Fatal(err) } track := func(title string) int64 { var id int64 if err := db.QueryRow("SELECT id FROM tracks WHERE title = ?", title).Scan(&id); err != nil { t.Fatal(err) } return id } n := 0 event := func(title string, at time.Time) { n++ if _, err := db.Exec("INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key) VALUES (?, ?, 'complete', ?, 200000, ?)", user, track(title), at.Unix(), fmt.Sprintf("k%d", n)); err != nil { t.Fatal(err) } } away := func(artist string, at time.Time) { n++ if _, err := db.Exec("INSERT INTO outside_plays (user_id, idempotency_key, artist, artist_key, played_at) VALUES (?, ?, ?, ?, ?)", user, fmt.Sprintf("o%d", n), artist, storage.SearchKey(artist), at.Unix()); err != nil { t.Fatal(err) } } now := time.Now() for _, days := range []int{200, 199, 198} { at := now.AddDate(0, 0, -days) event("Airbag", at) event("Debaser", at.Add(time.Minute)) away("Giorgio Canali", at.Add(2*time.Minute)) } for _, days := range []int{10, 9} { at := now.AddDate(0, 0, -days) event("Airbag", at) event("Nancy Boy", at.Add(time.Minute)) } } func allowListening(t *testing.T, h http.Handler, tok string) { t.Helper() if r := do(t, h, "PATCH", "/api/v1/me/settings", tok, map[string]any{"discover_from_listening": true}); r.Code != http.StatusOK { t.Fatalf("settings: %d %v", r.Code, r.Body) } } func artistNames(body map[string]any, list string) []string { out := []string{} items, _ := body[list].([]any) for _, it := range items { out = append(out, it.(map[string]any)["name"].(string)) } return out } func TestSuggestionsComeFromHowThePersonListensAndNeedTheirPermission(t *testing.T) { h, db := newTestEnv(t, func(*Deps) {}) tok := registerAndLogin(t, h) listeningHistory(t, db) if r := do(t, h, "GET", suggestionsPath, tok, nil); r.Code != http.StatusBadRequest || errCode(r) != "listening_not_allowed" { t.Fatalf("without permission: %d %v, want 400 listening_not_allowed", r.Code, r.Body) } allowListening(t, h, tok) r := do(t, h, "GET", suggestionsPath, tok, nil) if r.Code != http.StatusOK { t.Fatalf("suggestions: %d %v", r.Code, r.Body) } sameKeys(t, "suggestions", r.Body, "library", "missing", "built") if got := artistNames(r.Body, "library"); len(got) != 1 || got[0] != "Pixies" { t.Errorf("library = %v, want Pixies (Placebo and Radiohead were played lately)", got) } if got := artistNames(r.Body, "missing"); len(got) != 1 || got[0] != "Giorgio Canali" { t.Errorf("missing = %v, want Giorgio Canali", got) } pixies := r.Body["library"].([]any)[0].(map[string]any) sameKeys(t, "suggestion", pixies, "name", "artist_id", "score", "plays", "last_played_at", "wishlisted", "because") if pixies["artist_id"] == nil || pixies["score"] != 1.0 || pixies["plays"] != 3.0 || pixies["wishlisted"] != false { t.Errorf("Pixies = %v", pixies) } canali := r.Body["missing"].([]any)[0].(map[string]any) if canali["artist_id"] != nil || canali["plays"] != 3.0 { t.Errorf("Canali = %v, want no artist yet and 3 plays", canali) } built, _ := r.Body["built"].(map[string]any) sameKeys(t, "built", built, "at", "plays", "sessions", "artists", "links") if built["sessions"] != 5.0 || built["artists"] != 4.0 { t.Errorf("built = %v, want 5 sittings and 4 artists", built) } if r := do(t, h, "GET", suggestionsPath+"?limit=-1", tok, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("a negative limit: %d %v", r.Code, r.Body) } if r := do(t, h, "GET", suggestionsPath, "", nil); r.Code != http.StatusUnauthorized { t.Errorf("without a token: %d, want 401", r.Code) } } func TestAMissingArtistGoesOnTheWishlistByName(t *testing.T) { h, db := newTestEnv(t, func(*Deps) {}) tok := registerAndLogin(t, h) listeningHistory(t, db) allowListening(t, h, tok) wish := suggestionsPath + "/wishlist" if r := do(t, h, "POST", wish, tok, map[string]any{"name": "Nobody I played"}); r.Code != http.StatusNotFound || errCode(r) != "artist_not_played" { t.Errorf("an artist not played: %d %v, want 404 artist_not_played", r.Code, r.Body) } if r := do(t, h, "POST", wish, tok, map[string]any{"name": "Giorgio Canali"}); r.Code != http.StatusOK || r.Body["artist_id"] == nil { t.Fatalf("wish: %d %v", r.Code, r.Body) } if r := do(t, h, "POST", wish, tok, map[string]any{"name": "Giorgio Canali"}); r.Code != http.StatusOK { t.Errorf("wishing twice: %d %v, want 200", r.Code, r.Body) } list := do(t, h, "GET", "/api/v1/wishlist", tok, nil) items, _ := list.Body["items"].([]any) if len(items) != 1 || items[0].(map[string]any)["artist"].(map[string]any)["name"] != "Giorgio Canali" { t.Errorf("wishlist = %v, want the artist", list.Body) } if got := do(t, h, "GET", suggestionsPath, tok, nil); !got.Body["missing"].([]any)[0].(map[string]any)["wishlisted"].(bool) { t.Errorf("the suggestion does not say it is on the wishlist: %v", got.Body["missing"]) } var named int if err := db.QueryRow("SELECT COUNT(*) FROM artists WHERE name = 'Giorgio Canali' AND mbid IS NULL AND discovered = ?", true).Scan(&named); err != nil || named != 1 { t.Errorf("%d artists made for it (%v), want one without a MusicBrainz id", named, err) } if r := do(t, h, "POST", wish, tok, map[string]any{"nope": 1}); r.Code != http.StatusBadRequest { t.Errorf("a body that is not valid: %d, want 400", r.Code) } if r := do(t, h, "POST", wish, "", map[string]any{"name": "x"}); r.Code != http.StatusUnauthorized { t.Errorf("without a token: %d, want 401", r.Code) } } func TestAnotherPersonSeesNothingOfMyListening(t *testing.T) { h, db := newTestEnv(t, func(*Deps) {}) tok := registerAndLogin(t, h) listeningHistory(t, db) _, other := addUser(t, h, tok, "other", false) allowListening(t, h, other) r := do(t, h, "GET", suggestionsPath, other, nil) if r.Code != http.StatusOK || len(artistNames(r.Body, "library")) != 0 || len(artistNames(r.Body, "missing")) != 0 { t.Errorf("another person: %d %v, want empty lists", r.Code, r.Body) } if r := do(t, h, "POST", suggestionsPath+"/wishlist", other, map[string]any{"name": "Giorgio Canali"}); r.Code != http.StatusNotFound { t.Errorf("wishing an artist only someone else played: %d, want 404", r.Code) } }