sonda/internal/storage/subsonic_lists_test.go
tgiachi 74f683d26e feat: favourites of songs, albums and artists, in the API and in apps
A person can mark songs, albums and artists as favourites. They are theirs
alone: never shown to a friend, never sent anywhere. Only what can be played is
listed.

- migration 0035 favorites, internal/favorites, storage.FavoritesRepo
- PUT/DELETE /me/favorites/{kind}/{id}, GET /me/favorites/{kind} and
  GET /me/favorites/ids, in the OpenAPI spec
- catalog.Filter IDs now also reads artists by id
- OpenSubsonic: star, unstar, getStarred2, the starred date on songs, albums and
  artists, and getAlbumList2 of type starred
2026-11-16 10:51:07 +01:00

195 lines
8.2 KiB
Go

package storage
import (
"context"
"reflect"
"testing"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/opensubsonic"
)
type albumWorld struct {
repo *SubsonicRepo
album map[string]int64 // album id by title
user int64
ctx context.Context
s seeded
db *bun.DB
}
func newAlbumWorld(t *testing.T, db *bun.DB) albumWorld {
t.Helper()
w := albumWorld{ctx: context.Background(), s: seedCatalog(t, db), repo: NewSubsonicRepo(db, 20*time.Second), album: map[string]int64{}, db: db}
rows, err := db.Query("SELECT id, title FROM albums")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var id int64
var title string
if err := rows.Scan(&id, &title); err != nil {
t.Fatal(err)
}
w.album[title] = id
}
rows.Close()
w.user = seedUser(t, db, "l@example.org")
w.exec("UPDATE tracks SET year = 1997 WHERE album_id = ?", w.album["OK Computer"])
w.exec("UPDATE tracks SET year = 1995 WHERE album_id = ?", w.album["Post"])
w.exec("UPDATE tracks SET year = 1959 WHERE album_id = ?", w.album["Kind of Blue"])
w.exec("UPDATE audio_files SET mtime_unix = 100 WHERE track_id IN (SELECT id FROM tracks WHERE album_id = ?)", w.album["OK Computer"])
w.exec("UPDATE audio_files SET mtime_unix = 400 WHERE track_id IN (SELECT id FROM tracks WHERE album_id = ?)", w.album["Post"])
w.exec("UPDATE audio_files SET mtime_unix = 300 WHERE track_id IN (SELECT id FROM tracks WHERE album_id = ?)", w.album["Kind of Blue"])
w.exec("UPDATE audio_files SET mtime_unix = 200 WHERE track_id IN (SELECT id FROM tracks WHERE album_id = ?)", w.album["Various Hits"])
w.exec("INSERT INTO track_genres (track_id, genre) SELECT id, 'jazz' FROM tracks WHERE album_id = ?", w.album["Kind of Blue"])
w.exec("INSERT INTO track_genres (track_id, genre) SELECT id, 'rock' FROM tracks WHERE album_id = ?", w.album["OK Computer"])
return w
}
func (w albumWorld) exec(q string, args ...any) {
if _, err := w.db.ExecContext(w.ctx, q, args...); err != nil {
panic(err)
}
}
func (w albumWorld) listen(track string, at int64, kind string, ms int64) {
w.exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
VALUES (?, ?, ?, ?, ?, ?)`, w.user, w.s.track[track], kind, at, ms, kind+track+time.Unix(at, 0).String())
}
func (w albumWorld) titles(t *testing.T, ids []int64, err error) []string {
t.Helper()
if err != nil {
t.Fatal(err)
}
byID := map[int64]string{}
for title, id := range w.album {
byID[id] = title
}
out := []string{}
for _, id := range ids {
out = append(out, byID[id])
}
return out
}
func TestAlbumListsComeInTheOrderAskedFor(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
w := newAlbumWorld(t, db)
ask := func(q opensubsonic.AlbumQuery) []string {
t.Helper()
if q.Size == 0 {
q.Size = 50
}
ids, err := w.repo.AlbumIDs(w.ctx, q)
return w.titles(t, ids, err)
}
check := func(name string, got []string, want ...string) {
t.Helper()
if len(got) == 0 && len(want) == 0 {
return
}
if !reflect.DeepEqual(got, want) {
t.Errorf("%s = %v, want %v", name, got, want)
}
}
// The album of files that are all gone is never in a list.
check("by name", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByName}), "Kind of Blue", "OK Computer", "Post", "Various Hits")
check("by artist", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByArtist}), "Post", "Kind of Blue", "OK Computer", "Various Hits")
check("newest", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListNewest}), "Post", "Kind of Blue", "Various Hits", "OK Computer")
check("by year", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByYear, FromYear: 1990, ToYear: 2000}), "Post", "OK Computer")
check("by year backwards", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByYear, FromYear: 2000, ToYear: 1990}), "OK Computer", "Post")
check("by genre", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByGenre, Genre: "Jazz"}), "Kind of Blue")
check("by an unknown genre", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByGenre, Genre: "polka"}))
check("paged", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByName, Size: 2, Offset: 1}), "OK Computer", "Post")
check("past the end", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByName, Offset: 10}))
check("in a library", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListByName, LibraryID: w.s.jazz}), "Kind of Blue", "OK Computer", "Various Hits") // a second encoding of Airbag is in it
check("starred, with none", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListStarred, UserID: w.user}))
w.exec("INSERT INTO favorites (user_id, kind, item_id, created_at) VALUES (?, 'album', ?, 10), (?, 'album', ?, 20), (?, 'album', ?, 30)",
w.user, w.album["Post"], w.user, w.album["Kind of Blue"], w.user, w.album["Hidden Album"])
check("starred", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListStarred, UserID: w.user}), "Kind of Blue", "Post") // the hidden one cannot be played
check("starred of someone else", ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListStarred, UserID: w.user + 100}))
random := ask(opensubsonic.AlbumQuery{Type: opensubsonic.ListRandom, Size: 3})
seen := map[string]bool{}
for _, r := range random {
seen[r] = true
}
if len(random) != 3 || len(seen) != 3 {
t.Errorf("random = %v", random)
}
if _, err := w.repo.AlbumIDs(w.ctx, opensubsonic.AlbumQuery{Type: "nope", Size: 5}); err == nil {
t.Error("an unknown kind of list was answered")
}
})
}
func TestFrequentAndRecentAlbumsAreOfTheListenerAndOfListensThatCount(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
w := newAlbumWorld(t, db)
other := seedUser(t, db, "o@example.org")
w.listen("So What", 1000, "complete", 1000)
w.listen("So What", 2000, "complete", 1000)
w.listen("Freddie Freeloader", 3000, "play", 30_000) // long enough to count
w.listen("Airbag", 4000, "complete", 1000)
w.listen("Karma Police", 5000, "skip", 2000) // too short: not a listen
w.exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
VALUES (?, ?, 'complete', 9000, 1000, 'x')`, other, w.s.track["Army of Me"])
freq, err := w.repo.AlbumIDs(w.ctx, opensubsonic.AlbumQuery{Type: opensubsonic.ListFrequent, Size: 10, UserID: w.user})
if got := w.titles(t, freq, err); !reflect.DeepEqual(got, []string{"Kind of Blue", "OK Computer"}) {
t.Errorf("frequent = %v", got)
}
recent, err := w.repo.AlbumIDs(w.ctx, opensubsonic.AlbumQuery{Type: opensubsonic.ListRecent, Size: 10, UserID: w.user})
if got := w.titles(t, recent, err); !reflect.DeepEqual(got, []string{"OK Computer", "Kind of Blue"}) {
t.Errorf("recent = %v", got)
}
})
}
func TestSongListsAreByGenreAndRandom(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
w := newAlbumWorld(t, db)
ids, err := w.repo.SongIDs(w.ctx, opensubsonic.SongQuery{Genre: "JAZZ", Size: 10})
if err != nil || len(ids) != 3 {
t.Fatalf("jazz songs = %v, %v", ids, err)
}
// In the order of the album: So What (1), Freddie Freeloader (2), Blue in Green (3).
if ids[0] != w.s.track["So What"] || ids[2] != w.s.track["Blue in Green"] {
t.Errorf("jazz songs in the wrong order: %v", ids)
}
page, _ := w.repo.SongIDs(w.ctx, opensubsonic.SongQuery{Genre: "jazz", Size: 1, Offset: 1})
if len(page) != 1 || page[0] != w.s.track["Freddie Freeloader"] {
t.Errorf("second jazz song = %v", page)
}
years, _ := w.repo.SongIDs(w.ctx, opensubsonic.SongQuery{Random: true, FromYear: 1990, ToYear: 2000, Size: 50})
if len(years) != 4 { // 3 of OK Computer that can be played (Ghost cannot), 1 of Post
t.Errorf("songs of the nineties = %d", len(years))
}
some, _ := w.repo.SongIDs(w.ctx, opensubsonic.SongQuery{Random: true, Size: 5})
seen := map[int64]bool{}
for _, id := range some {
seen[id] = true
}
if len(some) != 5 || len(seen) != 5 {
t.Errorf("random songs = %v", some)
}
if ghost, _ := w.repo.SongIDs(w.ctx, opensubsonic.SongQuery{Random: true, Size: 500}); contains(ghost, w.s.track["Ghost"]) || contains(ghost, w.s.track["Hidden Song"]) {
t.Error("a song with no file to play is in a list")
}
})
}
func contains(ids []int64, id int64) bool {
for _, x := range ids {
if x == id {
return true
}
}
return false
}