navidrome/tests/mock_library_repo.go
Deluan Quintão 758e64c999
feat(scanner): per-library PID configuration (#6252)
* feat(model): add per-library PID config columns

* refactor(metadata): pass PID config to ToMediaFile and add spec validation

* feat(scanner): rescan only libraries whose PID config changed

* feat(server): validate library PID config and rescan on change

* feat(ui): edit per-library PID config

* fix(ui): label the PID mode selects

* fix: tighten per-library PID rescan edge cases

An interrupted PID rescan no longer upgrades every library to a full scan, a save that loses the race for the scanner logs at debug, the confirm dialog only shows when the effective PID spec changes, and it now gets translation keys.

* refactor(metadata): pass the library to ToMediaFile

ToMediaFile and core.Inspect took the library ID and its PID config as
separate arguments, so a caller could mix values from two libraries. They
now take the model.Library and resolve the effective PID config from it.

* chore: tidy per-library PID comments, PropTypes and migration

Trim comments that restated the code, add PropTypes to the new UI
components, and recreate the migration with make migration-sql.

* fix(ui): show the PID spec help under its input

* feat(cmd): make inspect use the file's library PID config

inspect always used the global PID config, so it showed different IDs than
the scanner for files in a library with an override. It now finds the
file's library in the DB and uses its effective config, falling back to
the global config when there is no DB or the file is outside every
library. It never creates a DB. The library path matcher moves from
core/playlists to model so both can use it.

* refactor: simplify per-library PID code

Share the DB-file check between CLI commands, move ErrAlreadyScanning to
model so core no longer imports scanner, read the libraries once for
insights, and let ValidatePIDSpec accept an empty spec and look tags up
directly. In the scanner, use FullScanInProgress instead of a second
flag, and skip recomputing album IDs when the album spec did not change.
In the UI, share the PID inputs between Create and Edit, and use docsUrl.

* feat(ui): add section titles to Library Create and pre-fill Custom PID specs

Custom now starts from the global spec, so admins edit a working spec
instead of typing one from scratch.

* fix(inspect): map files with the library-relative path the scanner uses

Inspect gave metadata the file's directory as typed, so folder-based PIDs
never matched the DB. It now uses the path relative to the library root,
through the scanner's helper, which moves to model.

* fix(scanner): say when a PID rescan only covers target folders

* fix: reject tag aliases in album PID specs and match root libraries

Tags are stored under canonical names, so an alias in a spec always reads
as empty. In an album spec that gives every album the same ID, so album
specs now require the tag name. Track specs keep accepting aliases, since
the default one uses them. LibraryMatcher now matches paths under a
library at the filesystem root.

* refactor(model): move the tag alias lookup to tag_mappings.go

* test: run the library matcher and inspect tests on Windows

Build test paths with filepath instead of Unix literals, so they use the
OS separator like filepath.Abs output, and drop the Windows skips.

* feat(ui): add pt-BR translations for per-library PID settings
2026-10-02 05:05:32 -04:00

313 lines
7.2 KiB
Go

package tests
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"github.com/Masterminds/squirrel"
"github.com/deluan/rest"
"github.com/navidrome/navidrome/model"
)
type MockLibraryRepo struct {
model.LibraryRepository
Data map[int]model.Library
Err error
PutFn func(*model.Library) error // Allow custom Put behavior for testing
PutCols []string
}
func (m *MockLibraryRepo) SetData(data model.Libraries) {
m.Data = make(map[int]model.Library)
for _, d := range data {
m.Data[d.ID] = d
}
}
func (m *MockLibraryRepo) GetAll(_ context.Context, _ ...model.QueryOptions) (model.Libraries, error) {
if m.Err != nil {
return nil, m.Err
}
var libraries model.Libraries
for _, lib := range m.Data {
libraries = append(libraries, lib)
}
// Sort by ID for predictable order
slices.SortFunc(libraries, func(a, b model.Library) int {
return a.ID - b.ID
})
return libraries, nil
}
func (m *MockLibraryRepo) CountAll(_ context.Context, qo ...model.QueryOptions) (int64, error) {
if m.Err != nil {
return 0, m.Err
}
// If no query options, return total count
if len(qo) == 0 || qo[0].Filters == nil {
return int64(len(m.Data)), nil
}
// Handle squirrel.Eq filter for ID validation
if eq, ok := qo[0].Filters.(squirrel.Eq); ok {
if idFilter, exists := eq["id"]; exists {
if ids, isSlice := idFilter.([]int); isSlice {
count := 0
for _, id := range ids {
if _, exists := m.Data[id]; exists {
count++
}
}
return int64(count), nil
}
}
}
// Default to total count for other filters
return int64(len(m.Data)), nil
}
func (m *MockLibraryRepo) Get(_ context.Context, id int) (*model.Library, error) {
if m.Err != nil {
return nil, m.Err
}
if lib, ok := m.Data[id]; ok {
return &lib, nil
}
return nil, model.ErrNotFound
}
func (m *MockLibraryRepo) GetPath(_ context.Context, id int) (string, error) {
if m.Err != nil {
return "", m.Err
}
if lib, ok := m.Data[id]; ok {
return lib.Path, nil
}
return "", model.ErrNotFound
}
func (m *MockLibraryRepo) Put(_ context.Context, library *model.Library, colsToUpdate ...string) error {
m.PutCols = colsToUpdate
if m.PutFn != nil {
return m.PutFn(library)
}
if m.Err != nil {
return m.Err
}
if m.Data == nil {
m.Data = make(map[int]model.Library)
}
m.Data[library.ID] = *library
return nil
}
func (m *MockLibraryRepo) Delete(_ context.Context, id int) error {
if m.Err != nil {
return m.Err
}
if _, ok := m.Data[id]; !ok {
return model.ErrNotFound
}
delete(m.Data, id)
return nil
}
func (m *MockLibraryRepo) StoreMusicFolder(_ context.Context) error {
if m.Err != nil {
return m.Err
}
return nil
}
func (m *MockLibraryRepo) AddArtist(_ context.Context, id int, artistID string) error {
if m.Err != nil {
return m.Err
}
return nil
}
func (m *MockLibraryRepo) ScanBegin(_ context.Context, id int, fullScan bool) error {
if m.Err != nil {
return m.Err
}
return nil
}
func (m *MockLibraryRepo) ScanEnd(_ context.Context, id int) error {
if m.Err != nil {
return m.Err
}
return nil
}
func (m *MockLibraryRepo) SetScannedPID(_ context.Context, id int, pid model.PIDConfig) error {
if m.Err != nil {
return m.Err
}
if lib, ok := m.Data[id]; ok {
lib.ScannedPIDAlbum, lib.ScannedPIDTrack = pid.Album, pid.Track
m.Data[id] = lib
}
return nil
}
func (m *MockLibraryRepo) ScanInProgress(_ context.Context) (bool, error) {
if m.Err != nil {
return false, m.Err
}
return false, nil
}
func (m *MockLibraryRepo) RefreshStats(_ context.Context, id int) error {
return nil
}
// User-library association methods - mock implementations
func (m *MockLibraryRepo) GetUsersWithLibraryAccess(_ context.Context, libraryID int) (model.Users, error) {
if m.Err != nil {
return nil, m.Err
}
// Mock: return empty users for now
return model.Users{}, nil
}
func (m *MockLibraryRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) {
return m.CountAll(ctx)
}
func (m *MockLibraryRepo) Read(ctx context.Context, id string) (*model.Library, error) {
idInt, _ := strconv.Atoi(id)
return m.Get(ctx, idInt)
}
func (m *MockLibraryRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.Library, error) {
return m.GetAll(ctx)
}
// REST Repository methods (string-based IDs)
func (m *MockLibraryRepo) Save(_ context.Context, lib *model.Library) (string, error) {
if m.Err != nil {
return "", m.Err
}
// Validate required fields
if lib.Name == "" {
return "", &rest.ValidationError{Errors: map[string]string{"name": "library name is required"}}
}
if lib.Path == "" {
return "", &rest.ValidationError{Errors: map[string]string{"path": "library path is required"}}
}
// Generate ID if not set
if lib.ID == 0 {
lib.ID = len(m.Data) + 1
}
if m.Data == nil {
m.Data = make(map[int]model.Library)
}
m.Data[lib.ID] = *lib
return strconv.Itoa(lib.ID), nil
}
func (m *MockLibraryRepo) Update(_ context.Context, id string, entity model.Library, _ ...string) error {
lib := &entity
if m.Err != nil {
return m.Err
}
// Validate required fields
if lib.Name == "" {
return &rest.ValidationError{Errors: map[string]string{"name": "library name is required"}}
}
if lib.Path == "" {
return &rest.ValidationError{Errors: map[string]string{"path": "library path is required"}}
}
idInt, err := strconv.Atoi(id)
if err != nil {
return errors.New("invalid ID format")
}
if _, exists := m.Data[idInt]; !exists {
return rest.ErrNotFound
}
lib.ID = idInt
m.Data[idInt] = *lib
return nil
}
func (m *MockLibraryRepo) DeleteByStringID(id string) error {
if m.Err != nil {
return m.Err
}
idInt, err := strconv.Atoi(id)
if err != nil {
return errors.New("invalid ID format")
}
if _, exists := m.Data[idInt]; !exists {
return rest.ErrNotFound
}
delete(m.Data, idInt)
return nil
}
// Service-level methods for core.Library interface
func (m *MockLibraryRepo) GetUserLibraries(ctx context.Context, userID string) (model.Libraries, error) {
if m.Err != nil {
return nil, m.Err
}
if userID == "non-existent" {
return nil, model.ErrNotFound
}
// Convert map to slice for return
var libraries model.Libraries
for _, lib := range m.Data {
libraries = append(libraries, lib)
}
// Sort by ID for predictable order
slices.SortFunc(libraries, func(a, b model.Library) int {
return a.ID - b.ID
})
return libraries, nil
}
func (m *MockLibraryRepo) SetUserLibraries(ctx context.Context, userID string, libraryIDs []int) error {
if m.Err != nil {
return m.Err
}
if userID == "non-existent" {
return model.ErrNotFound
}
if userID == "admin-1" {
return fmt.Errorf("%w: cannot manually assign libraries to admin users", model.ErrValidation)
}
if len(libraryIDs) == 0 {
return fmt.Errorf("%w: at least one library must be assigned to non-admin users", model.ErrValidation)
}
// Validate all library IDs exist
for _, id := range libraryIDs {
if _, exists := m.Data[id]; !exists {
return fmt.Errorf("%w: library ID %d does not exist", model.ErrValidation, id)
}
}
return nil
}
func (m *MockLibraryRepo) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error {
if m.Err != nil {
return m.Err
}
// For testing purposes, allow access to all libraries
return nil
}
var _ model.LibraryRepository = (*MockLibraryRepo)(nil)
var _ rest.Repository[model.Library] = (*MockLibraryRepo)(nil)