183 lines
4.4 KiB
Go
183 lines
4.4 KiB
Go
// Package beets queries the beets CLI for canonical library paths and ISRCs.
|
|
// Beets is optional: it makes lookups fast on large libraries and resolves
|
|
// files that have already been imported out of rip's staging folder.
|
|
package beets
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"applesync/internal/model"
|
|
)
|
|
|
|
const format = "$path\t$title\t$artist\t$album\t$albumartist\t$isrc"
|
|
|
|
const chunkSize = 250
|
|
|
|
type Runner struct {
|
|
Binary string
|
|
Timeout time.Duration
|
|
Logf func(string, ...any)
|
|
}
|
|
|
|
func New(binary string) *Runner {
|
|
if strings.TrimSpace(binary) == "" {
|
|
binary = "beet"
|
|
}
|
|
return &Runner{Binary: binary, Timeout: 3 * time.Minute}
|
|
}
|
|
|
|
func (r *Runner) log(format string, args ...any) {
|
|
if r.Logf != nil {
|
|
r.Logf(format, args...)
|
|
}
|
|
}
|
|
|
|
func (r *Runner) Available() bool {
|
|
binary := strings.TrimSpace(r.Binary)
|
|
if binary == "" {
|
|
return false
|
|
}
|
|
if strings.Contains(binary, "/") {
|
|
info, err := os.Stat(binary)
|
|
return err == nil && !info.IsDir()
|
|
}
|
|
_, err := exec.LookPath(binary)
|
|
return err == nil
|
|
}
|
|
|
|
// Files returns library entries for the given ISRCs and album titles. The two
|
|
// queries are merged by path; album titles catch items whose beets ISRC is
|
|
// empty, while the ISRC query catches albums whose title differs.
|
|
func (r *Runner) Files(ctx context.Context, isrcs, albumTitles []string) ([]*model.FileEntry, error) {
|
|
timeout := r.Timeout
|
|
if timeout <= 0 {
|
|
timeout = 3 * time.Minute
|
|
}
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
defer cancel()
|
|
|
|
byPath := map[string]*model.FileEntry{}
|
|
isrcs = uniqueValues(isrcs)
|
|
titles := uniqueValues(albumTitles)
|
|
|
|
if len(isrcs) > 0 {
|
|
found, err := r.query(ctx, "isrc", isrcs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r.log("beets: isrc query: %d files", len(found))
|
|
for _, file := range found {
|
|
byPath[file.Path] = file
|
|
}
|
|
}
|
|
if len(titles) > 0 {
|
|
found, err := r.query(ctx, "album", titles)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r.log("beets: album query: %d files", len(found))
|
|
for _, file := range found {
|
|
byPath[file.Path] = file
|
|
}
|
|
}
|
|
|
|
out := make([]*model.FileEntry, 0, len(byPath))
|
|
for _, file := range byPath {
|
|
out = append(out, file)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (r *Runner) query(ctx context.Context, field string, values []string) ([]*model.FileEntry, error) {
|
|
var out []*model.FileEntry
|
|
for start := 0; start < len(values); start += chunkSize {
|
|
end := start + chunkSize
|
|
if end > len(values) {
|
|
end = len(values)
|
|
}
|
|
pattern := "^(" + joinEscaped(values[start:end], "|") + ")$"
|
|
query := field + "::" + pattern
|
|
args := []string{"ls", "-p", "-f", format, query}
|
|
cmd := exec.CommandContext(ctx, r.Binary, args...)
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
if err := cmd.Run(); err != nil {
|
|
return nil, fmt.Errorf("beet %s query failed: %w: %s", field, err, truncate(stderr.String(), 500))
|
|
}
|
|
entries, err := parse(stdout.String())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, entries...)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func parse(output string) ([]*model.FileEntry, error) {
|
|
var out []*model.FileEntry
|
|
for _, line := range strings.Split(output, "\n") {
|
|
line = strings.TrimSuffix(line, "\r")
|
|
if strings.TrimSpace(line) == "" {
|
|
continue
|
|
}
|
|
fields := strings.Split(line, "\t")
|
|
if len(fields) < 6 {
|
|
continue
|
|
}
|
|
path := strings.TrimSpace(fields[0])
|
|
if path == "" {
|
|
continue
|
|
}
|
|
out = append(out, &model.FileEntry{
|
|
Path: path,
|
|
Title: strings.TrimSpace(fields[1]),
|
|
Artist: strings.TrimSpace(fields[2]),
|
|
Album: strings.TrimSpace(fields[3]),
|
|
AlbumArtist: strings.TrimSpace(fields[4]),
|
|
ISRC: strings.ToUpper(strings.TrimSpace(fields[5])),
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func joinEscaped(values []string, sep string) string {
|
|
parts := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
continue
|
|
}
|
|
parts = append(parts, regexp.QuoteMeta(value))
|
|
}
|
|
return strings.Join(parts, sep)
|
|
}
|
|
|
|
func uniqueValues(values []string) []string {
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" || seen[value] {
|
|
continue
|
|
}
|
|
seen[value] = true
|
|
out = append(out, value)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func truncate(value string, limit int) string {
|
|
if len(value) <= limit {
|
|
return value
|
|
}
|
|
return value[:limit] + "…"
|
|
}
|