package storage import ( "context" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/affinity" "git.kmalloc.org/squid/sonda/internal/library" "git.kmalloc.org/squid/sonda/internal/listening" "git.kmalloc.org/squid/sonda/internal/spotifyimport" ) // affinitySongBy is affinitySong for a test that does not need the track. func affinitySongBy(t *testing.T, db *bun.DB, lib int64, rel, title, artist string) { t.Helper() affinitySong(t, db, lib, rel, title, artist) } // affinitySong puts a song with one artist in the library and gives the id of its track. func affinitySong(t *testing.T, db *bun.DB, lib int64, rel, title, artist string) int64 { t.Helper() f := library.ParsedFile{ FileInfo: library.FileInfo{RelPath: rel, Size: 100, MTimeUnix: 1}, Metadata: library.Metadata{ Tags: library.Tags{Title: title, Album: "Album of " + artist, AlbumArtist: artist, Artists: []string{artist}}, Properties: library.Properties{Format: "flac", DurationMs: 200_000, SampleRate: 44100, BitRate: 900}, }, } if _, err := NewLibraryRepo(db).SaveFile(context.Background(), lib, f, 0); err != nil { t.Fatal(err) } var id int64 if err := db.QueryRow("SELECT id FROM tracks WHERE title = ?", title).Scan(&id); err != nil { t.Fatal(err) } return id } func TestTheAffinityRepoReadsThePlaysThatCountAndKeepsTheModel(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() u, err := NewUserRepo(db).CreateUser(ctx, "alice", "h", false) if err != nil { t.Fatal(err) } other, err := NewUserRepo(db).CreateUser(ctx, "bob", "h", false) if err != nil { t.Fatal(err) } lib, err := NewLibraryRepo(db).CreateLibrary(ctx, "music", "/music") if err != nil { t.Fatal(err) } pixies := affinitySong(t, db, lib.ID, "a.flac", "Debaser", "Pixies") blur := affinitySong(t, db, lib.ID, "b.flac", "Song 2", "Blur") minListen := 20 * time.Second listens := NewListeningRepo(db) ev := func(user, track int64, typ listening.EventType, ms int64, at int64, key string) listening.Event { return listening.Event{UserID: user, TrackID: track, Type: typ, DurationPlayedMs: ms, OccurredAt: time.Unix(at, 0), IdempotencyKey: key} } for _, e := range []listening.Event{ ev(u.ID, pixies, listening.Complete, 1000, 1000, "p1"), // counts: complete ev(u.ID, pixies, listening.Play, 30_000, 2000, "p2"), // counts: long enough ev(u.ID, pixies, listening.Play, 5_000, 3000, "p3"), // too short ev(u.ID, blur, listening.Skip, 1_000, 4000, "p4"), // a skip ev(other.ID, blur, listening.Complete, 1000, 5000, "p5"), } { if _, err := listens.Record(ctx, e); err != nil { t.Fatal(err) } } outside := NewOutsidePlayRepo(db) if _, err := outside.RecordOutside(ctx, u.ID, []spotifyimport.OutsidePlay{ {Key: "o1", Artist: "Giorgio Canali", PlayedAt: time.Unix(6000, 0)}, {Key: "p1", Artist: "Pixies", PlayedAt: time.Unix(1000, 0)}, // the same play as the event p1 }); err != nil { t.Fatal(err) } repo := NewAffinityRepo(db) plays, err := repo.Plays(ctx, u.ID, minListen) if err != nil { t.Fatal(err) } got := map[string]int{} for _, p := range plays { got[p.Name]++ if p.Key != SearchKey(p.Name) { t.Errorf("key %q of %q, want its search key", p.Key, p.Name) } } if len(plays) != 3 || got["Pixies"] != 2 || got["Giorgio Canali"] != 1 { t.Errorf("plays = %v (%d), want Pixies twice and Canali once: the short one, the skip, the other person's and the duplicate are out", got, len(plays)) } if n, err := repo.PlayCount(ctx, u.ID, minListen); err != nil || n != len(plays) { t.Errorf("PlayCount = %d, %v, want %d", n, err, len(plays)) } if _, ok, err := repo.Build(ctx, u.ID); err != nil || ok { t.Errorf("Build before any = %v, %v, want none", ok, err) } at := time.Unix(9000, 0) model := affinity.Model{ Plays: 3, Sessions: 2, Artists: []affinity.Artist{ {Key: "pixies", Name: "Pixies", Plays: 2, Sessions: 2, Last: time.Unix(2000, 0), Weight: 1.5}, {Key: "blur", Name: "Blur", Plays: 1, Sessions: 1, Last: time.Unix(1000, 0), Weight: 0.5}, {Key: "giorgio canali", Name: "Giorgio Canali", Plays: 1, Sessions: 1, Last: time.Unix(6000, 0), Weight: 3}, }, Links: []affinity.Link{{A: "blur", B: "pixies", Score: 0.5}, {A: "giorgio canali", B: "pixies", Score: 0.25}}, } if err := repo.Save(ctx, u.ID, at, model); err != nil { t.Fatal(err) } b, ok, err := repo.Build(ctx, u.ID) if err != nil || !ok || b.Plays != 3 || b.Sessions != 2 || b.Artists != 3 || b.Links != 2 || b.BuiltAt.Unix() != 9000 { t.Errorf("Build = %+v, %v, %v", b, ok, err) } seeds, err := repo.Seeds(ctx, u.ID, 2) if err != nil || len(seeds) != 2 || seeds[0].Key != "giorgio canali" || seeds[1].Key != "pixies" || seeds[1].Last.Unix() != 2000 { t.Errorf("Seeds = %+v, %v, want the two heaviest, heaviest first", seeds, err) } arts, err := repo.Artists(ctx, u.ID, []string{"blur", "nobody"}) if err != nil || len(arts) != 1 || arts["blur"].Name != "Blur" { t.Errorf("Artists = %+v, %v", arts, err) } links, err := repo.Neighbours(ctx, u.ID, []string{"blur"}) if err != nil || len(links) != 1 || links[0].A != "blur" || links[0].B != "pixies" || links[0].Score != 0.5 { t.Errorf("Neighbours(blur) = %+v, %v", links, err) } if links, _ := repo.Neighbours(ctx, u.ID, []string{"pixies"}); len(links) != 2 { t.Errorf("Neighbours(pixies) = %+v, want both links, from either end", links) } if links, _ := repo.Neighbours(ctx, other.ID, []string{"pixies"}); len(links) != 0 { t.Errorf("another person's links = %+v, want none", links) } if links, err := repo.Neighbours(ctx, u.ID, nil); err != nil || links != nil { t.Errorf("Neighbours of nobody = %v, %v", links, err) } // Building again replaces it, and drops the kept play that has an event now. if err := repo.Save(ctx, u.ID, at.Add(time.Hour), affinity.Model{Plays: 1}); err != nil { t.Fatal(err) } if b, _, _ := repo.Build(ctx, u.ID); b.Artists != 0 || b.Links != 0 || b.Plays != 1 { t.Errorf("Build after a smaller model = %+v", b) } if seeds, _ := repo.Seeds(ctx, u.ID, 10); len(seeds) != 0 { t.Errorf("Seeds = %+v, want none after it was replaced", seeds) } if got := count(t, db, "SELECT COUNT(*) FROM outside_plays WHERE user_id = ?", u.ID); got != 1 { t.Errorf("%d kept plays left, want 1 (the one that is a listening event was dropped)", got) } }) } func TestLibraryArtistsSayWhichHaveMusicAndWishlistFindsOrMakesThem(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() u, err := NewUserRepo(db).CreateUser(ctx, "alice", "h", false) if err != nil { t.Fatal(err) } lib, err := NewLibraryRepo(db).CreateLibrary(ctx, "music", "/music") if err != nil { t.Fatal(err) } affinitySong(t, db, lib.ID, "a.flac", "Debaser", "Pixies") if _, err := db.ExecContext(ctx, "INSERT INTO artists (name, name_key, search_key, discovered) VALUES ('Björk', 'björk', ?, ?)", SearchKey("Björk"), true); err != nil { t.Fatal(err) } repo := NewAffinityRepo(db) got, err := repo.LibraryArtists(ctx, []string{SearchKey("Pixies"), SearchKey("Björk"), "nobody"}) if err != nil { t.Fatal(err) } if len(got) != 2 || !got[SearchKey("Pixies")].Playable || got[SearchKey("Pixies")].Name != "Pixies" || got[SearchKey("Björk")].Playable || got[SearchKey("Björk")].ID == 0 { t.Errorf("LibraryArtists = %+v, want Pixies with music, Björk without, nobody not there", got) } // The artist that has the name is the one on the wishlist (also written without the accent) and none is made. id, err := repo.Wishlist(ctx, u.ID, "Bjork", time.Unix(100, 0)) if err != nil || id != got[SearchKey("Björk")].ID { t.Errorf("Wishlist(Bjork) = %d, %v, want the artist that exists (%d)", id, err, got[SearchKey("Björk")].ID) } // A new name makes an artist that nothing names but the mark, with no MusicBrainz id. id2, err := repo.Wishlist(ctx, u.ID, " Giorgio Canali ", time.Unix(200, 0)) if err != nil || id2 == 0 { t.Fatalf("Wishlist(new) = %d, %v", id2, err) } var name string var mbidNull, discovered bool if err := db.QueryRow("SELECT name, mbid IS NULL, discovered FROM artists WHERE id = ?", id2).Scan(&name, &mbidNull, &discovered); err != nil || name != "Giorgio Canali" || !mbidNull || !discovered { t.Errorf("made artist = %q, no mbid %v, discovered %v, %v", name, mbidNull, discovered, err) } again, err := repo.Wishlist(ctx, u.ID, "Giorgio Canali", time.Unix(300, 0)) if err != nil || again != id2 { t.Errorf("wishing again = %d, %v, want the same artist %d", again, err, id2) } var at int64 if err := db.QueryRow("SELECT created_at FROM artist_feedback WHERE user_id = ? AND artist_id = ?", u.ID, id2).Scan(&at); err != nil || at != 200 { t.Errorf("mark date = %d, %v, want the first date 200", at, err) } if got := count(t, db, "SELECT COUNT(*) FROM artists WHERE search_key = ?", SearchKey("Giorgio Canali")); got != 1 { t.Errorf("%d artists named Canali, want 1", got) } if _, err := repo.Wishlist(ctx, 999999, "Whoever", time.Unix(1, 0)); err == nil { t.Error("a wish of a person that does not exist was accepted") } }) }