596 lines
16 KiB
Go
596 lines
16 KiB
Go
// Package library scans the rip download directory, reads audio tags and maps
|
|
// Apple Music playlist tracks to the downloaded files.
|
|
package library
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/dhowden/tag"
|
|
|
|
"applesync/internal/model"
|
|
"applesync/internal/text"
|
|
)
|
|
|
|
var audioExt = map[string]bool{
|
|
".flac": true,
|
|
".mp3": true,
|
|
".m4a": true,
|
|
".mp4": true,
|
|
".ogg": true,
|
|
".opus": true,
|
|
".dsf": true,
|
|
".aiff": true,
|
|
".aif": true,
|
|
".wav": true,
|
|
".ape": true,
|
|
".wv": true,
|
|
}
|
|
|
|
type Index struct {
|
|
byISRC map[string][]*model.FileEntry
|
|
byKey map[string][]*model.FileEntry
|
|
byTitle map[string][]*model.FileEntry
|
|
|
|
seenPaths map[string]bool
|
|
fullScan bool
|
|
fileCount int
|
|
missingDir map[string]bool
|
|
libraryRoot string
|
|
downloadsRoot string
|
|
}
|
|
|
|
type dirInfo struct {
|
|
path string
|
|
norm string
|
|
}
|
|
|
|
// Build indexes the library. In "albums" mode only the directories for the
|
|
// supplied albums are tagged. "all" scans the whole tree. "auto" starts with
|
|
// album directories and falls back to a full scan when many are not found.
|
|
//
|
|
// libraryRoot is the root the music server sees (the final, imported library).
|
|
// downloadsRoot is where rip writes new albums; it may be a subdirectory of
|
|
// libraryRoot. Both are scanned, and files outside downloadsRoot are preferred
|
|
// when the same track exists in both places.
|
|
func Build(ctx context.Context, downloadsRoot, libraryRoot string, albums []*model.Album, matches map[string]*model.AlbumMatch, scanMode string, logf func(string, ...any)) (*Index, error) {
|
|
return build(ctx, downloadsRoot, libraryRoot, nil, albums, matches, scanMode, logf, true)
|
|
}
|
|
|
|
// BuildWithBeets builds an index from beets entries plus a targeted scan of
|
|
// rip's download folder. The (potentially huge) final library is not walked;
|
|
// beets is authoritative for it.
|
|
func BuildWithBeets(ctx context.Context, downloadsRoot, libraryRoot string, beetsFiles []*model.FileEntry, albums []*model.Album, matches map[string]*model.AlbumMatch, scanMode string, logf func(string, ...any)) (*Index, error) {
|
|
return build(ctx, downloadsRoot, libraryRoot, beetsFiles, albums, matches, scanMode, logf, false)
|
|
}
|
|
|
|
func build(ctx context.Context, downloadsRoot, libraryRoot string, beetsFiles []*model.FileEntry, albums []*model.Album, matches map[string]*model.AlbumMatch, scanMode string, logf func(string, ...any), scanLibrary bool) (*Index, error) {
|
|
downloadsRoot = cleanRoot(downloadsRoot)
|
|
libraryRoot = cleanRoot(libraryRoot)
|
|
if libraryRoot == "" {
|
|
libraryRoot = downloadsRoot
|
|
}
|
|
if downloadsRoot == "" {
|
|
downloadsRoot = libraryRoot
|
|
}
|
|
if libraryRoot == "" {
|
|
return nil, fmt.Errorf("downloads_dir is empty")
|
|
}
|
|
for _, root := range uniqueRoots(downloadsRoot, libraryRoot) {
|
|
info, err := os.Stat(root)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("library root %s: %w", root, err)
|
|
}
|
|
if !info.IsDir() {
|
|
return nil, fmt.Errorf("library root %s is not a directory", root)
|
|
}
|
|
}
|
|
if logf == nil {
|
|
logf = func(string, ...any) {}
|
|
}
|
|
|
|
scanMode = strings.ToLower(strings.TrimSpace(scanMode))
|
|
if scanMode == "" {
|
|
scanMode = "auto"
|
|
}
|
|
idx := &Index{
|
|
byISRC: map[string][]*model.FileEntry{},
|
|
byKey: map[string][]*model.FileEntry{},
|
|
byTitle: map[string][]*model.FileEntry{},
|
|
seenPaths: map[string]bool{},
|
|
missingDir: map[string]bool{},
|
|
libraryRoot: libraryRoot,
|
|
downloadsRoot: downloadsRoot,
|
|
}
|
|
for _, file := range beetsFiles {
|
|
if file == nil || file.Path == "" || idx.seenPaths[file.Path] {
|
|
continue
|
|
}
|
|
idx.seenPaths[file.Path] = true
|
|
idx.add(file)
|
|
}
|
|
if len(beetsFiles) > 0 {
|
|
logf("library: beets index: %d files", idx.fileCount)
|
|
}
|
|
|
|
if scanMode != "all" {
|
|
roots := scanRoots(libraryRoot, downloadsRoot)
|
|
if !scanLibrary {
|
|
roots = []string{downloadsRoot}
|
|
}
|
|
var dirs []dirInfo
|
|
for _, root := range roots {
|
|
found, err := listDirs(root, 4)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
dirs = append(dirs, found...)
|
|
}
|
|
logf("library: indexing %d candidate album folders", len(albums))
|
|
for _, album := range albums {
|
|
if err := ctx.Err(); err != nil {
|
|
return idx, err
|
|
}
|
|
candidates := findAlbumDirs(album, matches[album.AppleID], dirs)
|
|
if len(candidates) == 0 {
|
|
idx.missingDir[album.AppleID] = true
|
|
continue
|
|
}
|
|
found := false
|
|
for _, candidate := range candidates {
|
|
before := idx.fileCount
|
|
idx.scanFiles(ctx, candidate, 2, logf)
|
|
if idx.fileCount > before {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
idx.missingDir[album.AppleID] = true
|
|
}
|
|
}
|
|
logf("library: album scan: %d audio files", idx.fileCount)
|
|
}
|
|
|
|
doFull := scanMode == "all"
|
|
if scanMode == "auto" && !doFull {
|
|
// If many album directories were not found, the folder naming may be
|
|
// custom; fall back to a full tag scan once.
|
|
threshold := len(albums) / 4
|
|
if threshold < 1 {
|
|
threshold = 1
|
|
}
|
|
if len(idx.missingDir) >= threshold || idx.fileCount == 0 {
|
|
doFull = true
|
|
}
|
|
}
|
|
if doFull {
|
|
idx.fullScan = true
|
|
roots := scanRoots(libraryRoot, downloadsRoot)
|
|
if !scanLibrary && scanMode != "all" {
|
|
roots = []string{downloadsRoot}
|
|
}
|
|
for _, root := range roots {
|
|
logf("library: full scan of %s (this may take a while)", root)
|
|
idx.scanFiles(ctx, root, 0, logf)
|
|
}
|
|
logf("library: full scan: %d audio files", idx.fileCount)
|
|
}
|
|
return idx, nil
|
|
}
|
|
|
|
func cleanRoot(root string) string {
|
|
root = strings.TrimSpace(root)
|
|
if root == "" {
|
|
return ""
|
|
}
|
|
if abs, err := filepath.Abs(root); err == nil {
|
|
return filepath.Clean(abs)
|
|
}
|
|
return filepath.Clean(root)
|
|
}
|
|
|
|
func uniqueRoots(roots ...string) []string {
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(roots))
|
|
for _, root := range roots {
|
|
if root == "" || seen[root] {
|
|
continue
|
|
}
|
|
seen[root] = true
|
|
out = append(out, root)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// scanRoots returns the roots to walk. When the downloads directory lives
|
|
// inside the library root, walking the library root covers both.
|
|
func scanRoots(libraryRoot, downloadsRoot string) []string {
|
|
if downloadsRoot != "" && isUnder(downloadsRoot, libraryRoot) {
|
|
return []string{libraryRoot}
|
|
}
|
|
return uniqueRoots(libraryRoot, downloadsRoot)
|
|
}
|
|
|
|
func isUnder(path, root string) bool {
|
|
if path == "" || root == "" {
|
|
return false
|
|
}
|
|
rel, err := filepath.Rel(root, path)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
|
|
}
|
|
|
|
// FileCount returns the number of unique tagged files in the index.
|
|
func (i *Index) FileCount() int { return i.fileCount }
|
|
|
|
// FullScan reports whether a whole-tree scan was performed.
|
|
func (i *Index) FullScan() bool { return i.fullScan }
|
|
|
|
// MissingAlbumDir reports whether no folder was found for an album before any
|
|
// full-scan fallback.
|
|
func (i *Index) MissingAlbumDir(appleAlbumID string) bool { return i.missingDir[appleAlbumID] }
|
|
|
|
func listDirs(root string, maxDepth int) ([]dirInfo, error) {
|
|
var dirs []dirInfo
|
|
var walk func(string, int, string) error
|
|
walk = func(dir string, depth int, rel string) error {
|
|
if depth > maxDepth {
|
|
return nil
|
|
}
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
for _, entry := range entries {
|
|
if !entry.IsDir() {
|
|
continue
|
|
}
|
|
path := filepath.Join(dir, entry.Name())
|
|
childRel := filepath.Join(rel, entry.Name())
|
|
dirs = append(dirs, dirInfo{path: path, norm: text.Normalize(filepath.ToSlash(childRel))})
|
|
if err := walk(path, depth+1, childRel); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if err := walk(root, 1, ""); err != nil {
|
|
return nil, err
|
|
}
|
|
return dirs, nil
|
|
}
|
|
|
|
type dirCandidate struct {
|
|
path string
|
|
score int
|
|
}
|
|
|
|
func findAlbumDirs(album *model.Album, match *model.AlbumMatch, dirs []dirInfo) []string {
|
|
title := text.CleanAlbumTitle(album.Title)
|
|
artist := album.Artist
|
|
if match != nil {
|
|
if match.QobuzTitle != "" {
|
|
title = text.CleanAlbumTitle(match.QobuzTitle)
|
|
}
|
|
if match.QobuzArtist != "" {
|
|
artist = match.QobuzArtist
|
|
}
|
|
}
|
|
normTitle := text.Normalize(title)
|
|
normArtist := text.Normalize(artist)
|
|
if normTitle == "" {
|
|
return nil
|
|
}
|
|
|
|
find := func(titleNeedle string) []string {
|
|
var candidates []dirCandidate
|
|
for _, dir := range dirs {
|
|
if !strings.Contains(dir.norm, titleNeedle) {
|
|
continue
|
|
}
|
|
s := 10
|
|
if normArtist != "" && strings.Contains(dir.norm, normArtist) {
|
|
s += 5
|
|
}
|
|
combined := strings.TrimSpace(normArtist + " " + normTitle)
|
|
if combined != "" && strings.Contains(dir.norm, combined) {
|
|
s += 3
|
|
}
|
|
// Prefer the shortest folder name when scores tie.
|
|
s -= len(dir.norm) / 1000
|
|
candidates = append(candidates, dirCandidate{path: dir.path, score: s})
|
|
}
|
|
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].score > candidates[j].score })
|
|
limit := 3
|
|
if len(candidates) < limit {
|
|
limit = len(candidates)
|
|
}
|
|
out := make([]string, 0, limit)
|
|
seen := map[string]bool{}
|
|
for _, candidate := range candidates[:limit] {
|
|
if !seen[candidate.path] {
|
|
seen[candidate.path] = true
|
|
out = append(out, candidate.path)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
out := find(normTitle)
|
|
if len(out) == 0 && len([]rune(normTitle)) > 48 {
|
|
// rip truncates long path components to 120 runes; compare a prefix
|
|
// when the full title cannot be contained.
|
|
prefix := []rune(normTitle)
|
|
prefix = prefix[:48]
|
|
needle := strings.TrimSpace(string(prefix))
|
|
if idx := strings.LastIndex(needle, " "); idx > 24 {
|
|
needle = needle[:idx]
|
|
}
|
|
out = find(needle)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (i *Index) scanFiles(ctx context.Context, root string, maxDepth int, logf func(string, ...any)) {
|
|
count := 0
|
|
var walk func(string, int)
|
|
walk = func(dir string, depth int) {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return
|
|
}
|
|
for _, entry := range entries {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
path := filepath.Join(dir, entry.Name())
|
|
if entry.IsDir() {
|
|
if maxDepth == 0 || depth < maxDepth {
|
|
walk(path, depth+1)
|
|
}
|
|
continue
|
|
}
|
|
if !audioExt[strings.ToLower(filepath.Ext(path))] {
|
|
continue
|
|
}
|
|
if i.seenPaths[path] {
|
|
continue
|
|
}
|
|
i.seenPaths[path] = true
|
|
file, err := readTags(path)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
i.add(file)
|
|
count++
|
|
if count%250 == 0 {
|
|
logf("library: scanned %d files…", count)
|
|
}
|
|
}
|
|
}
|
|
walk(root, 0)
|
|
}
|
|
|
|
func (i *Index) add(file *model.FileEntry) {
|
|
i.fileCount++
|
|
if file.ISRC != "" {
|
|
key := strings.ToUpper(strings.TrimSpace(file.ISRC))
|
|
i.byISRC[key] = append(i.byISRC[key], file)
|
|
}
|
|
if file.Title != "" {
|
|
key := text.TrackKey(file.Artist, file.Title)
|
|
i.byKey[key] = append(i.byKey[key], file)
|
|
titleKey := text.Normalize(file.Title)
|
|
i.byTitle[titleKey] = append(i.byTitle[titleKey], file)
|
|
}
|
|
}
|
|
|
|
var filenameTrackRe = regexp.MustCompile(`^\s*(\d{1,3})[.\-_\s]+(.*)$`)
|
|
|
|
func readTags(path string) (*model.FileEntry, error) {
|
|
f, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer f.Close()
|
|
|
|
file := &model.FileEntry{Path: path}
|
|
md, err := tag.ReadFrom(f)
|
|
if err == nil {
|
|
file.Title = strings.TrimSpace(md.Title())
|
|
file.Artist = strings.TrimSpace(md.Artist())
|
|
file.Album = strings.TrimSpace(md.Album())
|
|
file.AlbumArtist = strings.TrimSpace(md.AlbumArtist())
|
|
file.Format = string(md.Format())
|
|
if track, _ := md.Track(); track > 0 {
|
|
file.TrackNumber = track
|
|
}
|
|
if disc, _ := md.Disc(); disc > 0 {
|
|
file.DiscNumber = disc
|
|
}
|
|
file.ISRC = rawISRC(md.Raw())
|
|
}
|
|
|
|
// Fall back to the streamrip filename format: "01. Artist - Title.flac".
|
|
base := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
|
|
if file.Title == "" || file.Artist == "" {
|
|
rest := base
|
|
if match := filenameTrackRe.FindStringSubmatch(base); len(match) == 3 {
|
|
if n, err := strconv.Atoi(match[1]); err == nil && file.TrackNumber == 0 {
|
|
file.TrackNumber = n
|
|
}
|
|
rest = match[2]
|
|
}
|
|
if file.Artist == "" || file.Title == "" {
|
|
if artist, title, ok := strings.Cut(rest, " - "); ok {
|
|
if file.Artist == "" {
|
|
file.Artist = strings.TrimSpace(artist)
|
|
}
|
|
if file.Title == "" {
|
|
file.Title = strings.TrimSpace(title)
|
|
}
|
|
} else if file.Title == "" {
|
|
file.Title = strings.TrimSpace(rest)
|
|
}
|
|
}
|
|
}
|
|
if file.Title == "" {
|
|
return nil, fmt.Errorf("no title tag in %s", path)
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
func rawISRC(raw map[string]any) string {
|
|
for key, value := range raw {
|
|
if !strings.EqualFold(key, "isrc") {
|
|
continue
|
|
}
|
|
switch v := value.(type) {
|
|
case string:
|
|
return strings.ToUpper(strings.TrimSpace(v))
|
|
case []string:
|
|
if len(v) > 0 {
|
|
return strings.ToUpper(strings.TrimSpace(v[0]))
|
|
}
|
|
case []any:
|
|
if len(v) > 0 {
|
|
if s, ok := v[0].(string); ok {
|
|
return strings.ToUpper(strings.TrimSpace(s))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// rootScore prefers files that are in the final library but not in rip's
|
|
// download folder.
|
|
func (i *Index) rootScore(path string) int {
|
|
underDownloads := isUnder(path, i.downloadsRoot)
|
|
underLibrary := isUnder(path, i.libraryRoot)
|
|
if underLibrary && !underDownloads {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// Resolve finds the downloaded file for a playlist track, preferring the album
|
|
// that was matched and downloaded.
|
|
func (i *Index) Resolve(track *model.Track, album *model.Album, match *model.AlbumMatch) (*model.FileEntry, bool) {
|
|
preferredAlbums := map[string]bool{}
|
|
addPreferred := func(value string) {
|
|
if value != "" {
|
|
preferredAlbums[text.Normalize(text.CleanAlbumTitle(value))] = true
|
|
}
|
|
}
|
|
if album != nil {
|
|
addPreferred(album.Title)
|
|
}
|
|
if match != nil {
|
|
addPreferred(match.QobuzTitle)
|
|
}
|
|
addPreferred(track.AlbumName)
|
|
|
|
artists := []string{track.ArtistName, track.AlbumArtist}
|
|
if album != nil && album.Artist != "" {
|
|
artists = append(artists, album.Artist)
|
|
}
|
|
if match != nil && match.QobuzArtist != "" {
|
|
artists = append(artists, match.QobuzArtist)
|
|
}
|
|
artistMatches := func(file *model.FileEntry) bool {
|
|
for _, fileArtist := range []string{file.Artist, file.AlbumArtist} {
|
|
if strings.TrimSpace(fileArtist) == "" {
|
|
continue
|
|
}
|
|
for _, artist := range artists {
|
|
if strings.TrimSpace(artist) == "" {
|
|
continue
|
|
}
|
|
if text.Normalize(fileArtist) == text.Normalize(artist) || text.Similarity(fileArtist, artist) >= 0.85 {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
pick := func(candidates []*model.FileEntry, requireArtist bool) (*model.FileEntry, bool) {
|
|
filtered := make([]*model.FileEntry, 0, len(candidates))
|
|
for _, candidate := range candidates {
|
|
if requireArtist && !artistMatches(candidate) {
|
|
continue
|
|
}
|
|
filtered = append(filtered, candidate)
|
|
}
|
|
if len(filtered) == 0 {
|
|
return nil, false
|
|
}
|
|
if len(filtered) == 1 {
|
|
return filtered[0], true
|
|
}
|
|
best := filtered[0]
|
|
bestScore := -1
|
|
for _, candidate := range filtered {
|
|
// Prefer the final, imported library copy over rip's staging copy.
|
|
s := i.rootScore(candidate.Path) * 4
|
|
if preferredAlbums[text.Normalize(text.CleanAlbumTitle(candidate.Album))] {
|
|
s += 2
|
|
}
|
|
if text.Normalize(candidate.Artist) == text.Normalize(track.ArtistName) {
|
|
s++
|
|
}
|
|
if s > bestScore {
|
|
bestScore = s
|
|
best = candidate
|
|
}
|
|
}
|
|
return best, true
|
|
}
|
|
|
|
if track.ISRC != "" {
|
|
if candidate, ok := pick(i.byISRC[strings.ToUpper(strings.TrimSpace(track.ISRC))], false); ok {
|
|
return candidate, true
|
|
}
|
|
}
|
|
|
|
seen := map[*model.FileEntry]bool{}
|
|
var byKey []*model.FileEntry
|
|
for _, artist := range artists {
|
|
for _, candidate := range i.byKey[text.TrackKey(artist, track.Title)] {
|
|
if !seen[candidate] {
|
|
seen[candidate] = true
|
|
byKey = append(byKey, candidate)
|
|
}
|
|
}
|
|
}
|
|
if candidate, ok := pick(byKey, false); ok {
|
|
return candidate, true
|
|
}
|
|
|
|
// Last resort: exact normalized title, restricted to the matched album and
|
|
// to a matching artist. This avoids picking up a different artist's song
|
|
// that happens to share the title (very common for singles).
|
|
var byTitle []*model.FileEntry
|
|
for _, candidate := range i.byTitle[text.Normalize(track.Title)] {
|
|
if preferredAlbums[text.Normalize(text.CleanAlbumTitle(candidate.Album))] {
|
|
byTitle = append(byTitle, candidate)
|
|
}
|
|
}
|
|
if candidate, ok := pick(byTitle, true); ok {
|
|
return candidate, true
|
|
}
|
|
return nil, false
|
|
}
|