sonda/internal/library/taglib.go
tgiachi b0a7a562a6 fix(discovery): purge lock, cleanup chains and rescans that cannot read
- fix: on PostgreSQL a purge could delete a discovered artist while a scan was
  adopting it. The scan then failed on the missing artist for the whole file,
  and the two could also deadlock. Purge now takes the same artist lock as the
  scanner and discovery before it removes anything. Saving a list or tags does
  too, and an artist that is gone by then is reported as not found instead of a
  foreign key error, so a user who opened an artist that was removed meanwhile
  gets a 404
- fix: a discovered artist that was only the source of a list stayed forever and
  kept the artists of its own list alive, so chains built up. Cleanup now removes
  such an artist and then follows the chain until nothing more goes
- fix: in a full rescan a file that came back but could not be read stayed
  marked missing. It is restored first, as in a normal scan, and read as well
- fix: ?full given twice is refused, so a typo cannot start a scan of another
  kind
- fix: genre cleaning lives in one place, used by the reader and the store
- docs: the files genres count the tracks the artist is credited on, and the spec
  says every files tag is a genre
- test: a purge colliding with a scan on both databases (it fails without the
  lock), a chain of discovered artists, saving for an artist that is gone, a
  file that returns unreadable during a full scan
2026-11-11 17:36:14 +01:00

195 lines
5.7 KiB
Go

package library
import (
"fmt"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode/utf8"
"go.senan.xyz/taglib"
)
// UnknownArtist is used when a file has no artist tag.
const UnknownArtist = "Unknown Artist"
// TaglibReader reads tags and audio properties with TagLib (compiled to
// WebAssembly, so there is no CGO). It is safe for concurrent use.
type TaglibReader struct{}
// Read implements TagReader.
func (TaglibReader) Read(path string) (Metadata, error) {
tags, err := taglib.ReadTags(path)
if err != nil {
return Metadata{}, fmt.Errorf("%w: %v", ErrUnreadable, err)
}
props, err := taglib.ReadProperties(path)
if err != nil {
return Metadata{}, fmt.Errorf("%w: %v", ErrUnreadable, err)
}
// TagLib does not fail on random bytes named .mp3; it just finds no audio.
if props.SampleRate == 0 || props.Length <= 0 {
return Metadata{}, fmt.Errorf("%w: no audio stream found", ErrUnreadable)
}
artists := nonEmpty(tags["ARTIST"])
albumArtist := first(tags, "ALBUMARTIST")
albumArtistID := ""
if albumArtist != "" {
// The id belongs to the album artist tag: when the tag is missing the name
// below is only a fallback, and an id would land on the wrong artist.
albumArtistID = singleID(tags["MUSICBRAINZ_ALBUMARTISTID"])
}
m := Metadata{
Tags: Tags{
Genres: CleanGenres(tags["GENRE"]),
Title: first(tags, "TITLE"),
Album: first(tags, "ALBUM"),
AlbumArtist: albumArtist,
Artists: artists,
ArtistMBIDs: pairArtistIDs(artists, tags["MUSICBRAINZ_ARTISTID"]),
AlbumArtistMBID: albumArtistID,
TrackNo: leadingInt(first(tags, "TRACKNUMBER")),
DiscNo: leadingInt(first(tags, "DISCNUMBER")),
},
Properties: Properties{
Format: strings.ToLower(props.Format),
DurationMs: props.Length.Milliseconds(),
SampleRate: int(props.SampleRate),
BitRate: int(props.BitRate),
},
}
if m.Title == "" {
base := filepath.Base(path)
m.Title = strings.TrimSuffix(base, filepath.Ext(base))
}
if len(m.Artists) == 0 {
m.Artists = []string{UnknownArtist}
m.ArtistMBIDs = nil // an id for an artist the file never named is not ours to use
}
if m.AlbumArtist == "" {
m.AlbumArtist = m.Artists[0]
}
return m, nil
}
// maxGenreLen bounds one genre; a longer one is a sentence, not a genre.
const maxGenreLen = 100
// CleanGenres turns the values of the GENRE tag into a short list of lower case
// genres without repeats. A tagger may write several genres as several values or
// as one value joined with ";". A slash is not a separator: "R&B/Soul" is one genre.
func CleanGenres(values []string) []string {
var out []string
seen := map[string]bool{}
for _, v := range values {
for _, g := range strings.Split(v, ";") {
g = strings.ToLower(strings.TrimSpace(g))
if g == "" || utf8.RuneCountInString(g) > maxGenreLen || seen[g] {
continue
}
seen[g] = true
out = append(out, g)
if len(out) == MaxGenresPerTrack {
return out
}
}
}
return out
}
var mbidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
// splitIDs reads the MusicBrainz ids out of the values of one tag. Taggers write
// several artists either as several values or as one value joined with "/" or ";".
// ok is false when any piece is not a MusicBrainz id.
func splitIDs(values []string) (ids []string, ok bool) {
for _, v := range values {
for _, piece := range strings.FieldsFunc(v, func(r rune) bool { return r == '/' || r == ';' || r == ',' }) {
piece = strings.TrimSpace(piece)
if piece == "" {
continue
}
if !mbidRe.MatchString(piece) {
return nil, false
}
ids = append(ids, strings.ToLower(piece))
}
}
return ids, true
}
// pairArtistIDs returns one id per artist, in order, or nothing. Fewer or more
// ids than artists, or an id that is not one, means the pairing would be a guess,
// and a wrong id on an artist is worse than none.
func pairArtistIDs(artists, values []string) []string {
ids, ok := splitIDs(values)
if !ok || len(ids) == 0 || len(ids) != len(artists) {
return nil
}
// One credit with one id ("X feat. Y" with the id of X) is the usual way a
// tagger writes the id of the first artist only. Without a way to tell, no id.
if len(artists) == 1 && looksLikeCredit(artists[0]) {
return nil
}
return ids
}
// creditWords are the separators of a credit that names several artists. A slash
// is not one: AC/DC is a band.
var creditWords = []string{" feat.", " feat ", " featuring ", " ft.", " ft ", " with ", " & ", " and ", " vs ", " vs. ", " x ", ",", ";"}
// looksLikeCredit says whether a name seems to credit more than one artist. It
// errs on the side of "yes": a missing id costs a lookup, a wrong one a wrong artist.
func looksLikeCredit(name string) bool {
n := " " + strings.ToLower(name) + " "
for _, w := range creditWords {
// Text must stand on both sides: a band called "X" is not a credit.
if i := strings.Index(n, w); i > 1 && i+len(w) < len(n)-1 {
return true
}
}
return false
}
// singleID returns the id when the tag holds exactly one valid id.
func singleID(values []string) string {
ids, ok := splitIDs(values)
if !ok || len(ids) != 1 {
return ""
}
return ids[0]
}
func first(tags map[string][]string, key string) string {
for _, v := range tags[key] {
if v = strings.TrimSpace(v); v != "" {
return v
}
}
return ""
}
func nonEmpty(values []string) []string {
var out []string
for _, v := range values {
if v = strings.TrimSpace(v); v != "" {
out = append(out, v)
}
}
return out
}
// leadingInt parses "3" or "3/12" and returns 0 when there is no number.
func leadingInt(s string) int {
if i := strings.IndexByte(s, '/'); i >= 0 {
s = s[:i]
}
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil || n < 0 {
return 0
}
return n
}