package storage import ( "context" "database/sql" "errors" "os" "path/filepath" "testing" "time" "github.com/uptrace/bun" "git.kmalloc.org/squid/sonda/internal/catalog" "git.kmalloc.org/squid/sonda/internal/library" "git.kmalloc.org/squid/sonda/internal/streaming" ) func parsed(rel, title, album string, artists ...string) library.ParsedFile { albumArtist := "" if len(artists) > 0 { albumArtist = artists[0] } return library.ParsedFile{ FileInfo: library.FileInfo{RelPath: rel, Size: 100, MTimeUnix: 1_700_000_000}, Metadata: library.Metadata{ Tags: library.Tags{ Title: title, Album: album, AlbumArtist: albumArtist, Artists: artists, TrackNo: 2, DiscNo: 1, }, Properties: library.Properties{Format: "flac", DurationMs: 180000, SampleRate: 44100, BitRate: 900}, }, } } // mkLib creates a library row and returns its id. func mkLib(t *testing.T, repo *LibraryRepo, name string) int64 { t.Helper() lib, err := repo.CreateLibrary(context.Background(), name, "/lib/"+name) if err != nil { t.Fatal(err) } return lib.ID } func count(t *testing.T, db *bun.DB, query string, args ...any) int { t.Helper() var n int if err := db.QueryRow(query, args...).Scan(&n); err != nil { t.Fatal(err) } return n } func TestLibraryRepoSaveNewFile(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "music") added, err := repo.SaveFile(ctx, lib, parsed("a/1.flac", "Song", "Album", "Radiohead"), 0) if err != nil || !added { t.Fatalf("added=%v err=%v", added, err) } // Same artist (different case) and same album are reused, not duplicated. if _, err := repo.SaveFile(ctx, lib, parsed("a/2.flac", "Other", "album", "RADIOHEAD"), 0); err != nil { t.Fatal(err) } if n := count(t, db, "SELECT COUNT(*) FROM artists"); n != 1 { t.Errorf("artists = %d, want 1", n) } if n := count(t, db, "SELECT COUNT(*) FROM albums"); n != 1 { t.Errorf("albums = %d, want 1", n) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 2 { t.Errorf("tracks = %d, want 2", n) } if n := count(t, db, "SELECT COUNT(*) FROM audio_files WHERE library_id = ?", lib); n != 2 { t.Errorf("audio_files = %d, want 2", n) } if n := count(t, db, "SELECT COUNT(*) FROM track_artists"); n != 2 { t.Errorf("track_artists = %d, want 2", n) } if n := count(t, db, "SELECT COUNT(*) FROM artists WHERE mbid IS NOT NULL"); n != 0 { t.Errorf("a MusicBrainz id was invented for %d artists", n) } var title string var dur, trackNo int64 err = db.QueryRow("SELECT title, duration_ms, track_no FROM tracks WHERE title = 'Song'").Scan(&title, &dur, &trackNo) if err != nil || dur != 180000 || trackNo != 2 { t.Errorf("track row: %q %d %d err=%v", title, dur, trackNo, err) } }) } // SQLite's lower() only folds ASCII, so matching is done in Go on a stored key. func TestLibraryRepoMatchesUnicodeNamesCaseInsensitively(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") if _, err := repo.SaveFile(ctx, lib, parsed("1.flac", "Hyperballad", "Post", "Björk"), 0); err != nil { t.Fatal(err) } if _, err := repo.SaveFile(ctx, lib, parsed("2.flac", "Army of Me", "POST", "BJÖRK"), 0); err != nil { t.Fatal(err) } if _, err := repo.SaveFile(ctx, lib, parsed("3.flac", "Isobel", "Ünïcode Album", "Åsa"), 0); err != nil { t.Fatal(err) } if _, err := repo.SaveFile(ctx, lib, parsed("4.flac", "Other", "ÜNÏCODE ALBUM", "ÅSA"), 0); err != nil { t.Fatal(err) } if n := count(t, db, "SELECT COUNT(*) FROM artists"); n != 2 { t.Errorf("artists = %d, want 2 (Björk and Åsa, whatever the case)", n) } if n := count(t, db, "SELECT COUNT(*) FROM albums"); n != 2 { t.Errorf("albums = %d, want 2", n) } }) } // Rows written before migration 0003 got an ASCII-only key from SQL lower(). // RefreshMatchKeys recomputes them so matching works for those rows too. func TestLibraryRepoRefreshMatchKeysFixesOldRows(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") // Simulate what the migration backfill leaves behind on SQLite. if _, err := db.Exec("INSERT INTO artists (name, name_key) VALUES ('BJÖRK', 'bjÖrk')"); err != nil { t.Fatal(err) } if _, err := db.Exec("INSERT INTO albums (title, title_key, artist_id) SELECT 'POST', 'post', id FROM artists"); err != nil { t.Fatal(err) } if err := repo.RefreshMatchKeys(ctx); err != nil { t.Fatal(err) } if err := repo.RefreshMatchKeys(ctx); err != nil { // idempotent t.Fatal(err) } if _, err := repo.SaveFile(ctx, lib, parsed("1.flac", "Hyperballad", "post", "Björk"), 0); err != nil { t.Fatal(err) } if n := count(t, db, "SELECT COUNT(*) FROM artists"); n != 1 { t.Errorf("artists = %d, want 1: the old row was not matched", n) } if n := count(t, db, "SELECT COUNT(*) FROM albums"); n != 1 { t.Errorf("albums = %d, want 1", n) } }) } func TestLibraryRepoTrackWithoutAlbum(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") if _, err := repo.SaveFile(context.Background(), lib, parsed("x.flac", "Loose", "", "Someone"), 0); err != nil { t.Fatal(err) } if n := count(t, db, "SELECT COUNT(*) FROM albums"); n != 0 { t.Errorf("albums = %d, want 0", n) } if n := count(t, db, "SELECT COUNT(*) FROM tracks WHERE album_id IS NULL"); n != 1 { t.Errorf("tracks without album = %d, want 1", n) } }) } func TestLibraryRepoUpdateKeepsIdentityAndReplacesCredits(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") if _, err := repo.SaveFile(ctx, lib, parsed("s.flac", "Old", "Album", "Artist A"), 0); err != nil { t.Fatal(err) } existing, err := repo.ExistingFiles(ctx, lib) if err != nil || len(existing) != 1 { t.Fatalf("existing = %v err=%v", existing, err) } id := existing[0].ID upd := parsed("s.flac", "New", "Album", "Artist B") upd.Size, upd.MTimeUnix = 200, 1_800_000_000 added, err := repo.SaveFile(ctx, lib, upd, id) if err != nil || added { t.Fatalf("update: added=%v err=%v", added, err) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 1 { t.Errorf("tracks = %d, want 1 (no duplicate on update)", n) } if n := count(t, db, "SELECT COUNT(*) FROM audio_files"); n != 1 { t.Errorf("audio_files = %d, want 1", n) } if n := count(t, db, "SELECT COUNT(*) FROM tracks WHERE title = 'New'"); n != 1 { t.Error("title was not updated") } if n := count(t, db, `SELECT COUNT(*) FROM track_artists ta JOIN artists a ON a.id = ta.artist_id WHERE a.name = 'Artist B'`); n != 1 { t.Error("credits were not replaced") } if n := count(t, db, `SELECT COUNT(*) FROM track_artists ta JOIN artists a ON a.id = ta.artist_id WHERE a.name = 'Artist A'`); n != 0 { t.Error("old credit still present") } after, _ := repo.ExistingFiles(ctx, lib) if after[0].ID != id || after[0].Size != 200 || after[0].MTimeUnix != 1_800_000_000 { t.Errorf("after update = %+v", after[0]) } }) } func TestLibraryRepoSameRelPathUnderTwoLibraries(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) a, b := mkLib(t, repo, "a"), mkLib(t, repo, "b") for _, lib := range []int64{a, b} { if _, err := repo.SaveFile(ctx, lib, parsed("same.flac", "S", "", "X"), 0); err != nil { t.Fatalf("library %d: %v", lib, err) } } for _, lib := range []int64{a, b} { if ex, _ := repo.ExistingFiles(ctx, lib); len(ex) != 1 { t.Errorf("library %d has %d files, want 1", lib, len(ex)) } } }) } func TestLibraryRepoMissingRestoreRename(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") if _, err := repo.SaveFile(ctx, lib, parsed("a.flac", "A", "", "X"), 0); err != nil { t.Fatal(err) } ex, _ := repo.ExistingFiles(ctx, lib) id := ex[0].ID if err := repo.MarkMissing(ctx, []int64{id}, time.Unix(1_900_000_000, 0)); err != nil { t.Fatal(err) } ex, _ = repo.ExistingFiles(ctx, lib) if len(ex) != 1 || !ex[0].Missing { t.Fatalf("after MarkMissing: %+v (row must be kept, flagged)", ex) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 1 { t.Errorf("tracks = %d: marking a file missing must keep the track", n) } if err := repo.Restore(ctx, []int64{id}); err != nil { t.Fatal(err) } if ex, _ = repo.ExistingFiles(ctx, lib); ex[0].Missing { t.Error("Restore did not clear the missing flag") } _ = repo.MarkMissing(ctx, []int64{id}, time.Now()) if err := repo.RenameFile(ctx, id, "sub/b.flac"); err != nil { t.Fatal(err) } ex, _ = repo.ExistingFiles(ctx, lib) if ex[0].ID != id || ex[0].RelPath != "sub/b.flac" || ex[0].Missing { t.Errorf("after rename: %+v", ex[0]) } }) } func TestLibraryRepoPlayableFile(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) if _, err := repo.PlayableFile(ctx, 999); !errors.Is(err, streaming.ErrNotFound) { t.Fatalf("unknown track: err = %v, want ErrNotFound", err) } lib := mkLib(t, repo, "music") // path /lib/music if _, err := repo.SaveFile(ctx, lib, parsed("a/1.flac", "Song", "", "X"), 0); err != nil { t.Fatal(err) } var trackID, fileID int64 if err := db.QueryRow("SELECT track_id, id FROM audio_files").Scan(&trackID, &fileID); err != nil { t.Fatal(err) } f, err := repo.PlayableFile(ctx, trackID) if err != nil || f.Root != "/lib/music" || f.RelPath != "a/1.flac" { t.Fatalf("PlayableFile = %+v err=%v", f, err) } // A second encoding of the same track. if _, err := db.Exec(`INSERT INTO audio_files (track_id, library_id, rel_path, format, size_bytes, mtime_unix) VALUES (?, ?, 'a/1.mp3', 'mp3', 1, 1)`, trackID, lib); err != nil { t.Fatal(err) } // The first file goes missing: the other one is served. if err := repo.MarkMissing(ctx, []int64{fileID}, time.Now()); err != nil { t.Fatal(err) } f, err = repo.PlayableFile(ctx, trackID) if err != nil || f.RelPath != "a/1.mp3" { t.Fatalf("with one file missing: %+v err=%v", f, err) } // Every file missing: nothing to play, but the track still exists. if _, err := db.Exec("UPDATE audio_files SET missing_at = 1"); err != nil { t.Fatal(err) } if _, err := repo.PlayableFile(ctx, trackID); !errors.Is(err, streaming.ErrNotFound) { t.Fatalf("all files missing: err = %v, want ErrNotFound", err) } }) } // stubReader lets the end-to-end test run without real audio. type stubReader struct{} func (stubReader) Read(path string) (library.Metadata, error) { return library.Metadata{ Tags: library.Tags{Title: filepath.Base(path), Artists: []string{"Band"}, Album: "LP", AlbumArtist: "Band"}, Properties: library.Properties{Format: "mp3", DurationMs: 1000, SampleRate: 44100}, }, nil } func TestScannerEndToEndOnBothBackends(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { root := t.TempDir() for _, n := range []string{"one.mp3", "two.mp3"} { if err := os.WriteFile(filepath.Join(root, n), []byte(n), 0o644); err != nil { t.Fatal(err) } } repo := NewLibraryRepo(db) lib, err := repo.CreateLibrary(context.Background(), "e2e", root) if err != nil { t.Fatal(err) } s := library.NewScanner(repo, stubReader{}, library.NewHub(), 4) scan := func() library.Summary { sum, err := s.Scan(context.Background(), []library.Library{lib}) if err != nil { t.Fatal(err) } return sum } if sum := scan(); sum.Added != 2 { t.Fatalf("first scan: %+v", sum) } if sum := scan(); sum.Unchanged != 2 || sum.Added != 0 { t.Fatalf("rescan: %+v", sum) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 2 { t.Errorf("tracks = %d after rescan, want 2 (no duplicates)", n) } if err := os.Remove(filepath.Join(root, "one.mp3")); err != nil { t.Fatal(err) } if sum := scan(); sum.Missing != 1 { t.Fatalf("after delete: %+v", sum) } if n := count(t, db, "SELECT COUNT(*) FROM audio_files WHERE missing_at IS NOT NULL"); n != 1 { t.Errorf("missing files = %d, want 1", n) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 2 { t.Errorf("tracks = %d: history must survive a missing file", n) } }) } func TestLibraryRepoCRUD(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) if libs, err := repo.ListLibraries(ctx); err != nil || len(libs) != 0 { t.Fatalf("empty list: %v err=%v", libs, err) } a, err := repo.CreateLibrary(ctx, "Jazz", "/music/jazz") if err != nil || a.ID == 0 || a.Name != "Jazz" || a.Path != "/music/jazz" || a.CreatedAt.IsZero() { t.Fatalf("create: %+v err=%v", a, err) } b, _ := repo.CreateLibrary(ctx, "Rock", "/music/rock") libs, err := repo.ListLibraries(ctx) if err != nil || len(libs) != 2 || libs[0].ID != a.ID || libs[1].ID != b.ID { t.Fatalf("list: %+v err=%v", libs, err) } got, err := repo.GetLibrary(ctx, a.ID) if err != nil || got.Name != "Jazz" { t.Fatalf("get: %+v err=%v", got, err) } upd, err := repo.UpdateLibrary(ctx, a.ID, "Jazz Collection", "/mnt/jazz") if err != nil || upd.Name != "Jazz Collection" || upd.Path != "/mnt/jazz" || upd.ID != a.ID { t.Fatalf("update: %+v err=%v", upd, err) } }) } func TestLibraryRepoRejectsDuplicatesAndUnknownIDs(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) a, _ := repo.CreateLibrary(ctx, "Jazz", "/music/jazz") b, _ := repo.CreateLibrary(ctx, "Rock", "/music/rock") if _, err := repo.CreateLibrary(ctx, "jazz", "/other"); !errors.Is(err, library.ErrLibraryExists) { t.Errorf("same name in another case: %v", err) } if _, err := repo.CreateLibrary(ctx, "Other", "/music/jazz"); !errors.Is(err, library.ErrLibraryExists) { t.Errorf("same path: %v", err) } if _, err := repo.UpdateLibrary(ctx, b.ID, "JAZZ", "/music/rock"); !errors.Is(err, library.ErrLibraryExists) { t.Errorf("update onto another name: %v", err) } if _, err := repo.UpdateLibrary(ctx, b.ID, "Rock", "/music/jazz"); !errors.Is(err, library.ErrLibraryExists) { t.Errorf("update onto another path: %v", err) } if _, err := repo.UpdateLibrary(ctx, a.ID, "Jazz", "/music/jazz"); err != nil { t.Errorf("update to its own values: %v", err) } if _, err := repo.GetLibrary(ctx, 999); !errors.Is(err, library.ErrLibraryNotFound) { t.Errorf("get: %v", err) } if _, err := repo.UpdateLibrary(ctx, 999, "x", "/x"); !errors.Is(err, library.ErrLibraryNotFound) { t.Errorf("update: %v", err) } if err := repo.DeleteLibrary(ctx, 999); !errors.Is(err, library.ErrLibraryNotFound) { t.Errorf("delete: %v", err) } }) } // Moving a library's folder is a one-row change: its files keep their identity. func TestLibraryRepoPathChangeKeepsFiles(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "m") if _, err := repo.SaveFile(ctx, lib, parsed("a.flac", "A", "", "X"), 0); err != nil { t.Fatal(err) } before, _ := repo.ExistingFiles(ctx, lib) if _, err := repo.UpdateLibrary(ctx, lib, "m", "/moved/here"); err != nil { t.Fatal(err) } after, _ := repo.ExistingFiles(ctx, lib) if len(after) != 1 || after[0].ID != before[0].ID { t.Fatalf("files after the move: %+v, want the same one", after) } var trackID int64 _ = db.QueryRow("SELECT track_id FROM audio_files").Scan(&trackID) f, err := repo.PlayableFile(ctx, trackID) if err != nil || f.Root != "/moved/here" { t.Errorf("playable file after the move: %+v err=%v", f, err) } }) } // Deleting a library drops its index entries; tracks (and with them the // listening history) stay. func TestLibraryRepoDeleteRemovesFilesButKeepsTracks(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) keep, drop := mkLib(t, repo, "keep"), mkLib(t, repo, "drop") for _, lib := range []int64{keep, drop} { if _, err := repo.SaveFile(ctx, lib, parsed("x.flac", "T", "", "X"), 0); err != nil { t.Fatal(err) } } if err := repo.DeleteLibrary(ctx, drop); err != nil { t.Fatal(err) } if n := count(t, db, "SELECT COUNT(*) FROM audio_files WHERE library_id = ?", drop); n != 0 { t.Errorf("files of the deleted library = %d, want 0", n) } if n := count(t, db, "SELECT COUNT(*) FROM audio_files WHERE library_id = ?", keep); n != 1 { t.Errorf("files of the other library = %d, want 1", n) } if n := count(t, db, "SELECT COUNT(*) FROM tracks"); n != 2 { t.Errorf("tracks = %d, want 2: history must survive", n) } }) } // ---- the release group id of an album ---- func albumMBID(t *testing.T, db *bun.DB, title string) string { t.Helper() var m sql.NullString if err := db.QueryRow("SELECT mbid FROM albums WHERE title = ?", title).Scan(&m); err != nil { t.Fatal(err) } return m.String } func withAlbumID(f library.ParsedFile, id string) library.ParsedFile { f.AlbumMBID = id return f } func TestAnAlbumTakesTheReleaseGroupIDFromItsFiles(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() lib := NewLibraryRepo(db) l, _ := lib.CreateLibrary(ctx, "m", "/lib/m") const a, b = "11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222" save := func(f library.ParsedFile) { t.Helper() if _, err := lib.SaveFile(ctx, l.ID, f, 0); err != nil { t.Fatal(err) } } // The first file of an album has the id, the second (without it) leaves it alone. save(withAlbumID(pf("a/1.flac", "One", "First", "Band", 1, 1, "flac", "Band"), a)) save(pf("a/2.flac", "Two", "First", "Band", 2, 1, "flac", "Band")) if got := albumMBID(t, db, "First"); got != a { t.Errorf("First = %q, want %q", got, a) } // An album that had none takes it when a file brings one (a full rescan after tagging). save(pf("b/1.flac", "Three", "Second", "Band", 1, 1, "flac", "Band")) if got := albumMBID(t, db, "Second"); got != "" { t.Fatalf("Second = %q before it has an id", got) } save(withAlbumID(pf("b/2.flac", "Four", "Second", "Band", 2, 1, "flac", "Band"), b)) if got := albumMBID(t, db, "Second"); got != b { t.Errorf("Second = %q, want %q", got, b) } // An id already used by another album is not given twice (it is unique), and not an error. save(withAlbumID(pf("c/1.flac", "Five", "Third", "Band", 1, 1, "flac", "Band"), a)) if got := albumMBID(t, db, "Third"); got != "" { t.Errorf("Third = %q, want none: the id belongs to First", got) } // An album that has an id keeps it when a file says another. save(withAlbumID(pf("a/3.flac", "Six", "First", "Band", 3, 1, "flac", "Band"), b)) if got := albumMBID(t, db, "First"); got != a { t.Errorf("First = %q, want it to keep %q", got, a) } }) } func TestAnAlbumWithoutAnIDCannotTakeOneThatAnotherAlbumHasAndNothingBreaks(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() lib := NewLibraryRepo(db) l, _ := lib.CreateLibrary(ctx, "m", "/lib/m") const id = "11111111-1111-4111-8111-111111111111" save := func(f library.ParsedFile) { t.Helper() if _, err := lib.SaveFile(ctx, l.ID, f, 0); err != nil { t.Fatalf("SaveFile: %v", err) } } save(withAlbumID(pf("a/1.flac", "One", "Owner", "Band", 1, 1, "flac", "Band"), id)) save(pf("b/1.flac", "Two", "Waiting", "Band", 1, 1, "flac", "Band")) // An album that already exists, has no id, and now meets one that is taken: the // UPDATE must not violate the unique constraint, and must leave it without. save(withAlbumID(pf("b/2.flac", "Three", "Waiting", "Band", 2, 1, "flac", "Band"), id)) if got := albumMBID(t, db, "Waiting"); got != "" { t.Errorf("Waiting = %q, want none", got) } if got := albumMBID(t, db, "Owner"); got != id { t.Errorf("Owner = %q, want it to keep %q", got, id) } }) } // Retagging a title leaves the old album with no track. Albums are never deleted, so its id // must be given up, or the retagged album could never have it. func TestTheIDOfAnAlbumWithNoTracksLeftPassesToTheRetaggedOne(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() lib := NewLibraryRepo(db) l, _ := lib.CreateLibrary(ctx, "m", "/lib/m") const id = "11111111-1111-4111-8111-111111111111" if _, err := lib.SaveFile(ctx, l.ID, withAlbumID(pf("a/1.flac", "One", "Typo Albm", "Band", 1, 1, "flac", "Band"), id), 0); err != nil { t.Fatal(err) } var fileID int64 if err := db.QueryRow("SELECT id FROM audio_files WHERE rel_path = 'a/1.flac'").Scan(&fileID); err != nil { t.Fatal(err) } // The title is fixed: the same file now says another album, and carries the same id. if _, err := lib.SaveFile(ctx, l.ID, withAlbumID(pf("a/1.flac", "One", "Fixed Album", "Band", 1, 1, "flac", "Band"), id), fileID); err != nil { t.Fatalf("SaveFile: %v", err) } if got := albumMBID(t, db, "Fixed Album"); got != id { t.Errorf("Fixed Album = %q, want %q", got, id) } if got := albumMBID(t, db, "Typo Albm"); got != "" { t.Errorf("Typo Albm = %q: an album with no tracks must not hold the id", got) } // An album that still has tracks keeps its id. if _, err := lib.SaveFile(ctx, l.ID, withAlbumID(pf("c/1.flac", "Two", "Keeps", "Band", 1, 1, "flac", "Band"), "22222222-2222-4222-8222-222222222222"), 0); err != nil { t.Fatal(err) } var other int64 if err := db.QueryRow("SELECT id FROM audio_files WHERE rel_path = 'c/1.flac'").Scan(&other); err != nil { t.Fatal(err) } if _, err := lib.SaveFile(ctx, l.ID, pf("c/2.flac", "Three", "Keeps", "Band", 2, 1, "flac", "Band"), 0); err != nil { t.Fatal(err) } if got := albumMBID(t, db, "Keeps"); got != "22222222-2222-4222-8222-222222222222" { t.Errorf("Keeps = %q", got) } }) } func TestLibraryRepoKeepsTheYearOfATrackAndUpdatesItOnARescan(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "music") f := parsed("a/1.flac", "Song", "Album", "Radiohead") f.Year = 1997 if _, err := repo.SaveFile(ctx, lib, f, 0); err != nil { t.Fatal(err) } year := func() sql.NullInt64 { var y sql.NullInt64 if err := db.QueryRow("SELECT year FROM tracks WHERE title = 'Song'").Scan(&y); err != nil { t.Fatal(err) } return y } if y := year(); !y.Valid || y.Int64 != 1997 { t.Fatalf("year = %v, want 1997", y) } var fileID int64 if err := db.QueryRow("SELECT id FROM audio_files").Scan(&fileID); err != nil { t.Fatal(err) } f.Year = 1998 if _, err := repo.SaveFile(ctx, lib, f, fileID); err != nil { t.Fatal(err) } if y := year(); y.Int64 != 1998 { t.Errorf("after a rescan year = %v, want 1998", y) } f.Year = 0 if _, err := repo.SaveFile(ctx, lib, f, fileID); err != nil { t.Fatal(err) } if y := year(); y.Valid { t.Errorf("a file with no year leaves the track with none, got %v", y) } }) } func gainOf(v float64) *float64 { return &v } func TestLibraryRepoKeepsTheReplayGainOfAFileAndUpdatesItOnARescan(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "music") f := parsed("a/1.flac", "Song", "Album", "Radiohead") f.ReplayGain = library.ReplayGain{TrackGain: gainOf(-6.5), AlbumGain: gainOf(-7), TrackPeak: gainOf(0.98), AlbumPeak: gainOf(1)} if _, err := repo.SaveFile(ctx, lib, f, 0); err != nil { t.Fatal(err) } read := func() (tg, ag, tp, ap sql.NullFloat64) { if err := db.QueryRow("SELECT rg_track_gain, rg_album_gain, rg_track_peak, rg_album_peak FROM audio_files").Scan(&tg, &ag, &tp, &ap); err != nil { t.Fatal(err) } return } tg, ag, tp, ap := read() if tg.Float64 != -6.5 || ag.Float64 != -7 || tp.Float64 != 0.98 || ap.Float64 != 1 { t.Fatalf("stored %v %v %v %v", tg, ag, tp, ap) } var fileID int64 if err := db.QueryRow("SELECT id FROM audio_files").Scan(&fileID); err != nil { t.Fatal(err) } f.ReplayGain = library.ReplayGain{TrackGain: gainOf(-3)} if _, err := repo.SaveFile(ctx, lib, f, fileID); err != nil { t.Fatal(err) } tg, ag, tp, ap = read() if tg.Float64 != -3 || ag.Valid || tp.Valid || ap.Valid { t.Errorf("after a rescan %v %v %v %v, want only the track gain, -3", tg, ag, tp, ap) } }) } func TestTracksCarryTheReplayGainOfTheirFirstPlayableFile(t *testing.T) { forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { ctx := context.Background() repo := NewLibraryRepo(db) lib := mkLib(t, repo, "music") tagged := parsed("a/1.flac", "Tagged", "Album", "Radiohead") tagged.ReplayGain = library.ReplayGain{TrackGain: gainOf(-6.5), TrackPeak: gainOf(0.98)} if _, err := repo.SaveFile(ctx, lib, tagged, 0); err != nil { t.Fatal(err) } if _, err := repo.SaveFile(ctx, lib, parsed("a/2.flac", "Plain", "Album", "Radiohead"), 0); err != nil { t.Fatal(err) } page, err := NewCatalogRepo(db).ListTracks(ctx, catalog.Filter{Limit: 10}) if err != nil { t.Fatal(err) } got := map[string]*catalog.ReplayGain{} for _, tr := range page.Items { got[tr.Title] = tr.ReplayGain } g := got["Tagged"] if g == nil || g.TrackGain == nil || *g.TrackGain != -6.5 || g.TrackPeak == nil || *g.TrackPeak != 0.98 || g.AlbumGain != nil || g.AlbumPeak != nil { t.Errorf("the tagged song has %+v", g) } if got["Plain"] != nil { t.Errorf("a song with no ReplayGain tags has %+v, want none", got["Plain"]) } }) }