Files
AppleSync/cmd/applesync/main.go
T
2026-11-26 15:11:41 +01:00

698 lines
20 KiB
Go

package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"sync/atomic"
"syscall"
"time"
"applesync/internal/apple"
"applesync/internal/beets"
"applesync/internal/config"
"applesync/internal/library"
"applesync/internal/m3u"
"applesync/internal/matcher"
"applesync/internal/model"
"applesync/internal/qobuz"
"applesync/internal/report"
"applesync/internal/rip"
"applesync/internal/state"
"applesync/internal/text"
)
const version = "0.1.0"
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, os.Args[1:]); err != nil {
if errors.Is(err, context.Canceled) {
fmt.Fprintln(os.Stderr, "\ninterrupted")
os.Exit(130)
}
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string) error {
if len(args) == 0 {
args = []string{"sync"}
}
switch args[0] {
case "sync":
return runSync(ctx, args[1:])
case "version", "--version", "-V":
fmt.Printf("applesync %s\n", version)
return nil
case "help", "-h", "--help":
printUsage(os.Stdout)
return nil
default:
if strings.HasPrefix(args[0], "-") {
return runSync(ctx, args)
}
return fmt.Errorf("unknown command %q (try applesync help)", args[0])
}
}
func printUsage(w io.Writer) {
fmt.Fprintln(w, `Usage:
applesync sync [options] Sync configured playlists
applesync version Show version
applesync help Show this help
Sync options:
--config <path> Config file (default: ./applesync.toml)
--playlist <name|url> Only sync matching playlists (repeatable)
--mode replace|append Override the configured m3u mode
--dry-run Fetch and match only; no rip, no m3u
--skip-download Do not invoke rip; rebuild m3u from files
--force Ask rip to redownload albums (--force)
--limit-albums <n> Download at most n albums (testing aid)
--refresh-matches Ignore cached album matches for this run
--report <path> Write a JSON report
-v, --verbose Verbose progress`)
}
type multiFlag []string
func (m *multiFlag) String() string { return strings.Join(*m, ",") }
func (m *multiFlag) Set(value string) error {
*m = append(*m, value)
return nil
}
type playlistRun struct {
cfg config.PlaylistConfig
playlist *model.Playlist
matches map[string]*model.AlbumMatch
m3uPath string
mode string
report report.PlaylistReport
err error
}
func runSync(ctx context.Context, args []string) error {
fs := flag.NewFlagSet("sync", flag.ContinueOnError)
fs.SetOutput(os.Stderr)
configPath := fs.String("config", "", "config file")
modeOverride := fs.String("mode", "", "m3u mode override")
dryRun := fs.Bool("dry-run", false, "fetch and match only")
skipDownload := fs.Bool("skip-download", false, "do not run rip")
force := fs.Bool("force", false, "redownload albums")
limitAlbums := fs.Int("limit-albums", 0, "download at most n albums")
refreshMatches := fs.Bool("refresh-matches", false, "ignore cached matches")
reportPath := fs.String("report", "", "JSON report path")
verbose := fs.Bool("v", false, "verbose")
fs.BoolVar(verbose, "verbose", false, "verbose")
var filters multiFlag
fs.Var(&filters, "playlist", "only matching playlists (repeatable)")
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
if fs.NArg() > 0 {
return fmt.Errorf("unexpected arguments: %s", strings.Join(fs.Args(), " "))
}
path, err := config.FindPath(*configPath)
if err != nil {
return err
}
cfg, err := config.Load(path)
if err != nil {
return err
}
if *dryRun {
cfg.Global.DryRun = true
}
if *reportPath != "" {
cfg.Global.Report = state.ExpandPath(*reportPath)
}
if *modeOverride != "" {
mode := strings.ToLower(strings.TrimSpace(*modeOverride))
if mode != "replace" && mode != "append" {
return fmt.Errorf("--mode must be replace or append")
}
for i := range cfg.Playlists {
cfg.Playlists[i].Mode = mode
}
}
debugf := func(format string, args ...any) {
if *verbose {
fmt.Printf("[debug] "+format+"\n", args...)
}
}
logf := func(format string, args ...any) {
fmt.Printf(format+"\n", args...)
}
lock, err := state.AcquireLock(cfg.Global.StateDir)
if err != nil {
return err
}
defer lock.Release()
cache, err := state.LoadMatchCache(filepath.Join(cfg.Global.StateDir, "qobuz_matches.json"))
if err != nil {
return fmt.Errorf("match cache: %w", err)
}
runner := &rip.Runner{
Binary: cfg.Rip.Binary,
ConfigPath: cfg.Rip.ConfigPath,
Quality: cfg.Rip.Quality,
Codec: cfg.Rip.Codec,
Folder: cfg.Global.DownloadsDir,
ExtraArgs: cfg.Rip.ExtraArgs,
NoProgress: cfg.Rip.NoProgress,
StateDir: cfg.Global.StateDir,
Logf: debugf,
}
appID, err := resolveAppID(ctx, cfg, runner, debugf)
if err != nil {
return err
}
qobuzClient := qobuz.New(appID)
qobuzClient.SetLogf(debugf)
appleClient := apple.NewClient(cfg.Apple.Language)
appleClient.SetLogf(debugf)
matcherClient := matcher.New(qobuzClient, cache, cfg.Global.Concurrency)
matcherClient.SetRefresh(*refreshMatches)
var matchCalls atomic.Int64
matcherClient.SetLogf(func(format string, args ...any) {
n := matchCalls.Add(1)
if *verbose || n%25 == 0 {
fmt.Printf(format+"\n", args...)
}
})
enabled := make([]config.PlaylistConfig, 0, len(cfg.Playlists))
for _, playlist := range cfg.Playlists {
if !playlist.IsEnabled() {
continue
}
if !matchesFilter(playlist, filters) {
continue
}
enabled = append(enabled, playlist)
}
if len(enabled) == 0 {
return fmt.Errorf("no playlists matched the filters")
}
m3uUsed := map[string]string{}
runs := make([]*playlistRun, 0, len(enabled))
for _, playlistCfg := range enabled {
run := &playlistRun{cfg: playlistCfg, mode: playlistCfg.Mode}
runs = append(runs, run)
run.report.Mode = run.mode
run.report.URL = playlistCfg.URL
ref, err := apple.ParsePlaylistURL(playlistCfg.URL)
if err != nil {
run.err = err
continue
}
playlist, err := appleClient.FetchPlaylist(ctx, ref)
if err != nil {
run.err = fmt.Errorf("fetch playlist: %w", err)
continue
}
if err := appleClient.EnrichAlbums(ctx, playlist); err != nil {
run.err = fmt.Errorf("enrich albums: %w", err)
continue
}
run.playlist = playlist
displayName := firstNonEmpty(playlistCfg.Name, playlist.Name)
run.report.Name = displayName
run.report.TracksTotal = len(playlist.Tracks)
run.report.AlbumsTotal = len(playlist.Albums)
m3uPath, err := playlistM3UPath(cfg, playlistCfg, displayName)
if err != nil {
run.err = err
continue
}
if previous, used := m3uUsed[m3uPath]; used {
run.err = fmt.Errorf("m3u %s is also used by %s", m3uPath, previous)
continue
}
m3uUsed[m3uPath] = displayName
run.m3uPath = m3uPath
run.report.M3UPath = m3uPath
matches, err := matcherClient.MatchAll(ctx, playlist.Albums)
if err != nil {
return err
}
run.matches = matches
run.report.AlbumsMatched = len(matches)
run.report.AlbumsUnmatched = len(playlist.Albums) - len(matches)
logf("%s: %d tracks, %d albums, %d matched, %d unmatched", displayName, len(playlist.Tracks), len(playlist.Albums), len(matches), len(playlist.Albums)-len(matches))
for _, album := range playlist.Albums {
if matches[album.AppleID] != nil {
continue
}
reason := "no Qobuz match"
if entry, ok := cache.Get(album.AppleID); ok && entry.Error != "" {
reason = entry.Error
}
run.report.UnmatchedAlbums = append(run.report.UnmatchedAlbums, report.AlbumIssue{
Artist: album.Artist,
Title: album.Title,
UPC: album.UPC,
Reason: reason,
})
}
}
if err := cache.Save(); err != nil {
debugf("cache save: %v", err)
}
var runErr error
for _, run := range runs {
if run.err != nil {
run.report.Error = run.err.Error()
runErr = errors.Join(runErr, fmt.Errorf("%s: %w", firstNonEmpty(run.report.Name, run.cfg.URL), run.err))
}
}
// Aggregate albums and query beets before deciding what to rip. This lets
// us skip albums that are already in the library instead of downloading
// them again.
allAlbums := uniqueAlbums(runs)
allMatches := map[string]*model.AlbumMatch{}
for _, run := range runs {
for id, match := range run.matches {
if match != nil {
allMatches[id] = match
}
}
}
beetsFiles := queryBeets(ctx, cfg, allAlbums, allMatches, debugf, logf)
var preIdx *library.Index
if len(beetsFiles) > 0 {
idx, err := buildLibraryIndex(ctx, cfg, allAlbums, allMatches, beetsFiles, debugf)
if err != nil {
logf("pre-check: %v; ripping all matched albums", err)
} else {
preIdx = idx
logf("pre-check: %d library files indexed", idx.FileCount())
}
}
selectIdx := preIdx
if *force {
// --force means redownload even when the album is already present.
selectIdx = nil
}
qobuzIDs, presentAlbums := albumsToDownload(runs, selectIdx)
if *limitAlbums > 0 && len(qobuzIDs) > *limitAlbums {
logf("rip: limiting this run to %d of %d albums", *limitAlbums, len(qobuzIDs))
qobuzIDs = qobuzIDs[:*limitAlbums]
}
if preIdx != nil {
logf("pre-check: %d album(s) already satisfied; %d album(s) need rip", presentAlbums, len(qobuzIDs))
} else {
logf("pre-check: beets unavailable; %d matched album(s) will be sent to rip", len(qobuzIDs))
}
if cfg.Global.DryRun {
printDryRun(logf, runs, *verbose, presentAlbums, len(qobuzIDs), preIdx != nil)
if err := writeReport(cfg.Global.Report, runs, nil, len(qobuzIDs), presentAlbums); err != nil {
return err
}
return runErr
}
var ripErr error
if !*skipDownload {
if len(qobuzIDs) == 0 {
logf("rip: nothing to download")
} else {
logf("rip: downloading %d album(s)", len(qobuzIDs))
if err := runner.DownloadAlbums(ctx, qobuzIDs, *force); err != nil {
ripErr = err
logf("rip: error: %v", err)
}
}
}
var idx *library.Index
switch {
case *skipDownload && preIdx != nil:
idx = preIdx
case len(qobuzIDs) == 0 && preIdx != nil:
idx = preIdx
default:
idx, err = buildLibraryIndex(ctx, cfg, allAlbums, allMatches, beetsFiles, debugf)
if err != nil {
return errors.Join(runErr, err)
}
}
logf("library: %d audio files indexed%s", idx.FileCount(), fullScanLabel(idx.FullScan()))
for _, run := range runs {
if run.playlist == nil {
continue
}
if err := writePlaylistM3U(cfg, run, idx); err != nil {
run.report.Error = err.Error()
runErr = errors.Join(runErr, fmt.Errorf("%s: %w", firstNonEmpty(run.report.Name, run.cfg.URL), err))
logf("%s: error: %v", firstNonEmpty(run.report.Name, run.cfg.URL), err)
continue
}
logf("%s: m3u %s: %d/%d tracks written (%s)", run.report.Name, run.m3uPath, run.report.TracksWritten, run.report.TracksTotal, run.mode)
if run.report.TracksMissing > 0 {
printMissing(logf, run, 5)
}
}
if cfg.Global.Report != "" {
if err := writeReport(cfg.Global.Report, runs, ripErr, len(qobuzIDs), presentAlbums); err != nil {
runErr = errors.Join(runErr, err)
} else {
logf("report: %s", cfg.Global.Report)
}
}
if ripErr != nil {
if cfg.Global.Missing == "fail" {
runErr = errors.Join(runErr, fmt.Errorf("rip: %w", ripErr))
} else {
logf("rip: completed with errors; missing tracks are listed above")
}
}
return runErr
}
func resolveAppID(ctx context.Context, cfg *config.Config, runner *rip.Runner, debugf func(string, ...any)) (string, error) {
if value := strings.TrimSpace(cfg.Qobuz.AppID); value != "" {
return value, nil
}
if value, err := runner.QobuzAppID(ctx); err == nil && strings.TrimSpace(value) != "" {
debugf("qobuz: using app id from rip config")
return value, nil
}
value, err := qobuz.ResolveAppID(ctx, "")
if err != nil {
return "", err
}
debugf("qobuz: scraped public app id")
return value, nil
}
func matchesFilter(playlist config.PlaylistConfig, filters []string) bool {
if len(filters) == 0 {
return true
}
haystack := strings.ToLower(playlist.URL + " " + playlist.Name)
for _, filter := range filters {
if filter != "" && strings.Contains(haystack, strings.ToLower(filter)) {
return true
}
}
return false
}
func playlistM3UPath(cfg *config.Config, playlist config.PlaylistConfig, name string) (string, error) {
file := strings.TrimSpace(playlist.M3U)
if file == "" {
file = text.Slug(name) + ".m3u"
}
if filepath.IsAbs(file) {
return file, nil
}
if strings.TrimSpace(cfg.Global.M3UDir) == "" {
return "", fmt.Errorf("global.m3u_dir is empty")
}
return filepath.Join(cfg.Global.M3UDir, file), nil
}
func writePlaylistM3U(cfg *config.Config, run *playlistRun, idx *library.Index) error {
albumByID := map[string]*model.Album{}
for _, album := range run.playlist.Albums {
albumByID[album.AppleID] = album
}
entries := make([]m3u.Entry, 0, len(run.playlist.Tracks))
missing := make([]report.TrackIssue, 0)
for _, track := range run.playlist.Tracks {
album := albumByID[track.AlbumID]
match := run.matches[track.AlbumID]
file, ok := idx.Resolve(track, album, match)
if !ok {
missing = append(missing, report.TrackIssue{
Artist: track.ArtistName,
Title: track.Title,
Album: track.AlbumName,
ISRC: track.ISRC,
Reason: "file not found",
})
continue
}
entries = append(entries, m3u.Entry{File: file, Track: track})
}
run.report.TracksMissing = len(missing)
run.report.MissingTracks = missing
if len(entries) == 0 {
return fmt.Errorf("no playlist tracks resolved to downloaded files; m3u not written")
}
if cfg.Global.Missing == "fail" && len(missing) > 0 {
return fmt.Errorf("%d of %d tracks are missing; m3u not written (missing=fail)", len(missing), len(run.playlist.Tracks))
}
if err := os.MkdirAll(filepath.Dir(run.m3uPath), 0o755); err != nil {
return err
}
written, err := m3u.Write(run.m3uPath, entries, run.mode, cfg.Global.M3UPaths, cfg.Global.ExtendedM3U)
if err != nil {
return err
}
run.report.TracksWritten = written
return nil
}
func writeReport(path string, runs []*playlistRun, ripErr error, toDownload, present int) error {
if path == "" {
return nil
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
rep := &report.Report{
GeneratedAt: time.Now(),
AlbumsToDownload: toDownload,
AlbumsPresent: present,
}
if ripErr != nil {
rep.RipError = ripErr.Error()
}
for _, run := range runs {
rep.Playlists = append(rep.Playlists, run.report)
}
return report.Write(path, rep)
}
func queryBeets(ctx context.Context, cfg *config.Config, albums []*model.Album, matches map[string]*model.AlbumMatch, debugf, logf func(string, ...any)) []*model.FileEntry {
if !cfg.Beets.Enabled {
return nil
}
br := beets.New(cfg.Beets.Binary)
br.Logf = debugf
if !br.Available() {
logf("beets: %s not found; using filesystem scan", cfg.Beets.Binary)
return nil
}
isrcs, titles := beetsQueries(albums, matches)
files, err := br.Files(ctx, isrcs, titles)
switch {
case err != nil:
logf("beets: %v; using filesystem scan", err)
return nil
case len(files) == 0:
logf("beets: no matching files; using filesystem scan")
return nil
default:
logf("beets: %d library files indexed", len(files))
return files
}
}
func buildLibraryIndex(ctx context.Context, cfg *config.Config, albums []*model.Album, matches map[string]*model.AlbumMatch, beetsFiles []*model.FileEntry, logf func(string, ...any)) (*library.Index, error) {
if len(beetsFiles) > 0 {
return library.BuildWithBeets(ctx, cfg.Global.DownloadsDir, cfg.Global.LibraryDir, beetsFiles, albums, matches, cfg.Global.LibraryScan, logf)
}
return library.Build(ctx, cfg.Global.DownloadsDir, cfg.Global.LibraryDir, albums, matches, cfg.Global.LibraryScan, logf)
}
// albumsToDownload returns the Qobuz albums that still need ripping. If idx is
// non-nil, albums whose playlist tracks all resolve in the library are skipped.
func albumsToDownload(runs []*playlistRun, idx *library.Index) ([]string, int) {
var ids []string
seen := map[string]bool{}
seenPresent := map[string]bool{}
present := 0
for _, run := range runs {
if run.playlist == nil {
continue
}
for _, album := range run.playlist.Albums {
match := run.matches[album.AppleID]
if match == nil || match.QobuzAlbumID == "" {
continue
}
if idx != nil && albumSatisfied(idx, run, album) {
if !seenPresent[match.QobuzAlbumID] {
seenPresent[match.QobuzAlbumID] = true
present++
}
continue
}
if seen[match.QobuzAlbumID] {
continue
}
seen[match.QobuzAlbumID] = true
ids = append(ids, match.QobuzAlbumID)
}
}
return ids, present
}
func albumSatisfied(idx *library.Index, run *playlistRun, album *model.Album) bool {
if len(album.Tracks) == 0 {
return false
}
for _, track := range album.Tracks {
if _, ok := idx.Resolve(track, album, run.matches[album.AppleID]); !ok {
return false
}
}
return true
}
func printDryRun(logf func(string, ...any), runs []*playlistRun, verbose bool, present, toDownload int, preChecked bool) {
logf("")
logf("Dry run — no downloads or m3u writes")
for _, run := range runs {
if run.playlist == nil {
continue
}
byMethod := map[string]int{}
for _, match := range run.matches {
if match != nil {
byMethod[match.Method]++
}
}
logf("%s: %d tracks, %d albums (%d upc, %d isrc, %d fuzzy), %d unmatched", run.report.Name, run.report.TracksTotal, run.report.AlbumsTotal, byMethod["upc"], byMethod["isrc"], byMethod["fuzzy"], run.report.AlbumsUnmatched)
if verbose {
for _, album := range run.playlist.Albums {
match := run.matches[album.AppleID]
if match == nil {
logf(" [ ] %s — %s", album.Artist, album.Title)
continue
}
logf(" [x] %s — %s -> %s (%s)", album.Artist, album.Title, match.QobuzAlbumID, match.Method)
}
continue
}
if len(run.report.UnmatchedAlbums) > 0 {
limit := 10
for i, issue := range run.report.UnmatchedAlbums {
if i >= limit {
logf(" … and %d more unmatched albums", len(run.report.UnmatchedAlbums)-limit)
break
}
logf(" unmatched: %s — %s (%s)", issue.Artist, issue.Title, issue.Reason)
}
}
}
if preChecked {
logf("pre-check: %d album(s) already present, %d album(s) would be downloaded", present, toDownload)
} else {
logf("pre-check: unavailable (beets not used); %d matched album(s) would be sent to rip", toDownload)
}
}
func printMissing(logf func(string, ...any), run *playlistRun, limit int) {
n := 0
for _, missing := range run.report.MissingTracks {
if n >= limit {
logf(" … and %d more missing", len(run.report.MissingTracks)-limit)
break
}
logf(" missing: %s — %s", missing.Artist, missing.Title)
n++
}
}
func beetsQueries(albums []*model.Album, matches map[string]*model.AlbumMatch) ([]string, []string) {
var isrcs []string
var titles []string
for _, album := range albums {
for _, track := range album.Tracks {
if track.ISRC != "" {
isrcs = append(isrcs, track.ISRC)
}
}
if album.Title != "" {
titles = append(titles, text.SearchTitle(album.Title))
}
if match := matches[album.AppleID]; match != nil && match.QobuzTitle != "" {
titles = append(titles, match.QobuzTitle)
}
}
return isrcs, titles
}
func uniqueAlbums(runs []*playlistRun) []*model.Album {
seen := map[string]bool{}
var out []*model.Album
for _, run := range runs {
if run.playlist == nil {
continue
}
for _, album := range run.playlist.Albums {
if album.AppleID == "" || seen[album.AppleID] {
continue
}
seen[album.AppleID] = true
out = append(out, album)
}
}
return out
}
func fullScanLabel(full bool) string {
if full {
return " (full scan)"
}
return ""
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}