navidrome/model/library.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

101 lines
4 KiB
Go

package model
import (
"cmp"
"context"
"strings"
"time"
"github.com/deluan/rest"
"github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/utils/slice"
)
type Library struct {
ID int `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Path string `json:"path" db:"path"`
RemotePath string `json:"remotePath" db:"remote_path"`
LastScanAt time.Time `json:"lastScanAt" db:"last_scan_at"`
LastScanStartedAt time.Time `json:"lastScanStartedAt" db:"last_scan_started_at"`
FullScanInProgress bool `json:"fullScanInProgress" db:"full_scan_in_progress"`
UpdatedAt time.Time `json:"updatedAt" db:"updated_at"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
TotalSongs int `json:"totalSongs" db:"total_songs"`
TotalAlbums int `json:"totalAlbums" db:"total_albums"`
TotalArtists int `json:"totalArtists" db:"total_artists"`
TotalFolders int `json:"totalFolders" db:"total_folders"`
TotalFiles int `json:"totalFiles" db:"total_files"`
TotalMissingFiles int `json:"totalMissingFiles" db:"total_missing_files"`
TotalSize int64 `json:"totalSize" db:"total_size"`
TotalDuration float64 `json:"totalDuration" db:"total_duration"`
DefaultNewUsers bool `json:"defaultNewUsers" db:"default_new_users"`
PIDAlbum string `json:"pidAlbum" db:"pid_album"`
PIDTrack string `json:"pidTrack" db:"pid_track"`
ScannedPIDAlbum string `json:"-" db:"scanned_pid_album"`
ScannedPIDTrack string `json:"-" db:"scanned_pid_track"`
}
// PIDConfig holds the persistent ID specs used to compute track and album IDs.
type PIDConfig struct {
Track string
Album string
}
// EffectivePID returns the PID specs in effect for this library: its own overrides, falling back to
// the global config.
func (l Library) EffectivePID() PIDConfig {
return PIDConfig{
Track: cmp.Or(l.PIDTrack, conf.Server.PID.Track),
Album: cmp.Or(l.PIDAlbum, conf.Server.PID.Album),
}
}
// PIDChanged reports whether the effective PID specs differ from the ones used by the last finished
// scan of this library. A library that was never scanned counts as changed.
func (l Library) PIDChanged() bool {
pid := l.EffectivePID()
return !strings.EqualFold(l.ScannedPIDAlbum, pid.Album) || !strings.EqualFold(l.ScannedPIDTrack, pid.Track)
}
// NeedsPIDRescan reports whether the library has content imported with an old PID config, so it must be
// rescanned in full. A library that never finished a scan has nothing to regroup.
func (l Library) NeedsPIDRescan() bool {
return !l.LastScanAt.IsZero() && l.PIDChanged()
}
const (
DefaultLibraryID = 1
DefaultLibraryName = "Music Library"
)
type Libraries []Library
func (l Libraries) IDs() []int {
return slice.Map(l, func(lib Library) int { return lib.ID })
}
type LibraryRepository interface {
rest.Repository[Library]
Get(ctx context.Context, id int) (*Library, error)
// GetPath returns the path of the library with the given ID.
// Its implementation must be optimized to avoid unnecessary queries.
GetPath(ctx context.Context, id int) (string, error)
GetAll(ctx context.Context, options ...QueryOptions) (Libraries, error)
CountAll(ctx context.Context, options ...QueryOptions) (int64, error)
Put(ctx context.Context, l *Library, colsToUpdate ...string) error
Delete(ctx context.Context, id int) error
StoreMusicFolder(ctx context.Context) error
AddArtist(ctx context.Context, id int, artistID string) error
// User-library association methods
GetUsersWithLibraryAccess(ctx context.Context, libraryID int) (Users, error)
// TODO These methods should be moved to a core service
ScanBegin(ctx context.Context, id int, fullScan bool) error
ScanEnd(ctx context.Context, id int) error
// SetScannedPID records the PID specs used by the last finished scan of the library
SetScannedPID(ctx context.Context, id int, pid PIDConfig) error
ScanInProgress(ctx context.Context) (bool, error)
RefreshStats(ctx context.Context, id int) error
}