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

141 lines
4.2 KiB
Go

package metadata
import (
"cmp"
"errors"
"fmt"
"path/filepath"
"strings"
"github.com/navidrome/navidrome/consts"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/id"
"github.com/navidrome/navidrome/utils"
"github.com/navidrome/navidrome/utils/str"
)
type hashFunc = func(...string) string
// computePID calculates the persistent ID for a given spec. The spec is a
// pipe-separated list of fields, where each field is a comma-separated list of
// attributes. Attributes can be either tags or processed values like folder,
// albumid, albumartistid, etc. For each field, it gets all its attribute values
// and concatenates them, then hashes the result. If a field is empty, it is
// skipped and the function looks for the next field. albumSpec is the album PID
// spec used to resolve the `albumid` attribute.
//
// Taking hash as a parameter (instead of closing over it in a factory) keeps
// mf on the stack: closing over mf would force the whole ~1KB MediaFile to the
// heap on every call.
func computePID(mf model.MediaFile, md Metadata, spec, albumSpec string, prependLibId bool, hash hashFunc) string {
switch spec {
case "track_legacy":
return legacyTrackID(mf, prependLibId)
case "album_legacy":
return legacyAlbumID(mf, md, prependLibId)
}
pid := ""
fields := strings.SplitSeq(spec, "|")
for field := range fields {
attributes := strings.Split(field, ",")
values := make([]string, len(attributes))
hasValue := false
for i, attr := range attributes {
v := getPIDAttr(mf, md, attr, prependLibId, spec, albumSpec, hash)
if v != "" {
hasValue = true
}
values[i] = v
}
if hasValue {
pid += strings.Join(values, "\\")
break
}
}
if prependLibId {
pid = fmt.Sprintf("%d\\%s", mf.LibraryID, pid)
}
return hash(pid)
}
func getPIDAttr(mf model.MediaFile, md Metadata, attr string, prependLibId bool, spec, albumSpec string, hash hashFunc) string {
attr = strings.TrimSpace(strings.ToLower(attr))
switch attr {
case "albumid":
if spec == albumSpec {
log.Error("Recursive PID definition detected, ignoring `albumid`", "spec", spec)
return ""
}
return computePID(mf, md, albumSpec, albumSpec, prependLibId, hash)
case "folder":
return filepath.Dir(mf.Path)
case "albumartistid":
return hash(str.Clear(strings.ToLower(mf.AlbumArtist)))
case "title":
return mf.Title
case "album":
return str.Clear(strings.ToLower(md.String(model.TagAlbum)))
}
return md.String(model.TagName(attr))
}
// ValidatePIDSpec checks a PID override before it is stored; empty means "use the global config".
// Aliases resolve to empty at scan time: accepted only in track specs, because the default one uses them.
func ValidatePIDSpec(spec string, isAlbum bool) error {
switch {
case spec == "", isAlbum && spec == "album_legacy", !isAlbum && spec == "track_legacy":
return nil
}
for field := range strings.SplitSeq(spec, "|") {
for attr := range strings.SplitSeq(field, ",") {
attr = strings.TrimSpace(strings.ToLower(attr))
switch attr {
case "":
return fmt.Errorf("empty attribute in %q", spec)
case "albumid":
if isAlbum {
return errors.New("albumid cannot be used in an album PID")
}
case "folder", "albumartistid":
default:
name, ok := model.CanonicalTagName(attr)
if !ok {
return fmt.Errorf("unknown attribute %q", attr)
}
if isAlbum && string(name) != attr {
return fmt.Errorf("use the tag name %q instead of its alias %q", name, attr)
}
}
}
}
return nil
}
func (md Metadata) trackPID(mf model.MediaFile, pid model.PIDConfig) string {
return computePID(mf, md, pid.Track, pid.Album, true, id.NewHash)
}
func (md Metadata) albumID(mf model.MediaFile, pidConf string) string {
return computePID(mf, md, pidConf, pidConf, true, id.NewHash)
}
// BFR Must be configurable?
func (md Metadata) artistID(name string) string {
mf := model.MediaFile{AlbumArtist: name}
return computePID(mf, md, "albumartistid", "", false, id.NewHash)
}
func (md Metadata) mapTrackTitle() string {
if title := md.String(model.TagTitle); title != "" {
return title
}
return utils.BaseName(md.FilePath())
}
func (md Metadata) mapAlbumName() string {
return cmp.Or(
md.String(model.TagAlbum),
consts.UnknownAlbum,
)
}